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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
azavea/python-omgeo | omgeo/services/base.py | GeocodeService._get_xml_doc | def _get_xml_doc(self, endpoint, query, is_post=False):
"""
Return False if connection could not be made.
Otherwise, return a minidom Document.
"""
response = self._get_response(endpoint, query, is_post=is_post)
return minidom.parse(response.text) | python | def _get_xml_doc(self, endpoint, query, is_post=False):
"""
Return False if connection could not be made.
Otherwise, return a minidom Document.
"""
response = self._get_response(endpoint, query, is_post=is_post)
return minidom.parse(response.text) | [
"def",
"_get_xml_doc",
"(",
"self",
",",
"endpoint",
",",
"query",
",",
"is_post",
"=",
"False",
")",
":",
"response",
"=",
"self",
".",
"_get_response",
"(",
"endpoint",
",",
"query",
",",
"is_post",
"=",
"is_post",
")",
"return",
"minidom",
".",
"parse... | Return False if connection could not be made.
Otherwise, return a minidom Document. | [
"Return",
"False",
"if",
"connection",
"could",
"not",
"be",
"made",
".",
"Otherwise",
"return",
"a",
"minidom",
"Document",
"."
] | 40f4e006f087dbc795a5d954ffa2c0eab433f8c9 | https://github.com/azavea/python-omgeo/blob/40f4e006f087dbc795a5d954ffa2c0eab433f8c9/omgeo/services/base.py#L168-L174 | train | 43,700 |
azavea/python-omgeo | omgeo/services/google.py | Google._make_candidate_from_result | def _make_candidate_from_result(self, result):
""" Make a Candidate from a Google geocoder results dictionary. """
candidate = Candidate()
candidate.match_addr = result['formatted_address']
candidate.x = result['geometry']['location']['lng']
candidate.y = result['geometry']['location']['lat']
candidate.locator = self.LOCATOR_MAPPING.get(result['geometry']['location_type'], '')
candidate.entity_types = result['types']
candidate.partial_match = result.get('partial_match', False)
component_lookups = {
'city': {'type': 'locality', 'key': 'long_name'},
'subregion': {'type': 'administrative_area_level_2', 'key': 'long_name'},
'region': {'type': 'administrative_area_level_1', 'key': 'short_name'},
'postal': {'type': 'postal_code', 'key': 'long_name'},
'country': {'type': 'country', 'key': 'short_name'},
}
for (field, lookup) in component_lookups.items():
setattr(candidate, 'match_' + field, self._get_component_from_result(result, lookup))
candidate.geoservice = self.__class__.__name__
return candidate | python | def _make_candidate_from_result(self, result):
""" Make a Candidate from a Google geocoder results dictionary. """
candidate = Candidate()
candidate.match_addr = result['formatted_address']
candidate.x = result['geometry']['location']['lng']
candidate.y = result['geometry']['location']['lat']
candidate.locator = self.LOCATOR_MAPPING.get(result['geometry']['location_type'], '')
candidate.entity_types = result['types']
candidate.partial_match = result.get('partial_match', False)
component_lookups = {
'city': {'type': 'locality', 'key': 'long_name'},
'subregion': {'type': 'administrative_area_level_2', 'key': 'long_name'},
'region': {'type': 'administrative_area_level_1', 'key': 'short_name'},
'postal': {'type': 'postal_code', 'key': 'long_name'},
'country': {'type': 'country', 'key': 'short_name'},
}
for (field, lookup) in component_lookups.items():
setattr(candidate, 'match_' + field, self._get_component_from_result(result, lookup))
candidate.geoservice = self.__class__.__name__
return candidate | [
"def",
"_make_candidate_from_result",
"(",
"self",
",",
"result",
")",
":",
"candidate",
"=",
"Candidate",
"(",
")",
"candidate",
".",
"match_addr",
"=",
"result",
"[",
"'formatted_address'",
"]",
"candidate",
".",
"x",
"=",
"result",
"[",
"'geometry'",
"]",
... | Make a Candidate from a Google geocoder results dictionary. | [
"Make",
"a",
"Candidate",
"from",
"a",
"Google",
"geocoder",
"results",
"dictionary",
"."
] | 40f4e006f087dbc795a5d954ffa2c0eab433f8c9 | https://github.com/azavea/python-omgeo/blob/40f4e006f087dbc795a5d954ffa2c0eab433f8c9/omgeo/services/google.py#L54-L74 | train | 43,701 |
azavea/python-omgeo | omgeo/services/google.py | Google._get_component_from_result | def _get_component_from_result(self, result, lookup):
"""
Helper function to get a particular address component from a Google result.
Since the address components in results are an array of objects containing a types array,
we have to search for a particular component rather than being able to look it up directly.
Returns the first match, so this should be used for unique component types (e.g.
'locality'), not for categories (e.g. 'political') that can describe multiple components.
:arg dict result: A results dict with an 'address_components' key, as returned by the
Google geocoder.
:arg dict lookup: The type (e.g. 'street_number') and key ('short_name' or 'long_name') of
the desired address component value.
:returns: address component or empty string
"""
for component in result['address_components']:
if lookup['type'] in component['types']:
return component.get(lookup['key'], '')
return '' | python | def _get_component_from_result(self, result, lookup):
"""
Helper function to get a particular address component from a Google result.
Since the address components in results are an array of objects containing a types array,
we have to search for a particular component rather than being able to look it up directly.
Returns the first match, so this should be used for unique component types (e.g.
'locality'), not for categories (e.g. 'political') that can describe multiple components.
:arg dict result: A results dict with an 'address_components' key, as returned by the
Google geocoder.
:arg dict lookup: The type (e.g. 'street_number') and key ('short_name' or 'long_name') of
the desired address component value.
:returns: address component or empty string
"""
for component in result['address_components']:
if lookup['type'] in component['types']:
return component.get(lookup['key'], '')
return '' | [
"def",
"_get_component_from_result",
"(",
"self",
",",
"result",
",",
"lookup",
")",
":",
"for",
"component",
"in",
"result",
"[",
"'address_components'",
"]",
":",
"if",
"lookup",
"[",
"'type'",
"]",
"in",
"component",
"[",
"'types'",
"]",
":",
"return",
... | Helper function to get a particular address component from a Google result.
Since the address components in results are an array of objects containing a types array,
we have to search for a particular component rather than being able to look it up directly.
Returns the first match, so this should be used for unique component types (e.g.
'locality'), not for categories (e.g. 'political') that can describe multiple components.
:arg dict result: A results dict with an 'address_components' key, as returned by the
Google geocoder.
:arg dict lookup: The type (e.g. 'street_number') and key ('short_name' or 'long_name') of
the desired address component value.
:returns: address component or empty string | [
"Helper",
"function",
"to",
"get",
"a",
"particular",
"address",
"component",
"from",
"a",
"Google",
"result",
"."
] | 40f4e006f087dbc795a5d954ffa2c0eab433f8c9 | https://github.com/azavea/python-omgeo/blob/40f4e006f087dbc795a5d954ffa2c0eab433f8c9/omgeo/services/google.py#L76-L95 | train | 43,702 |
raonyguimaraes/pynnotator | pynnotator/install.py | Installer.install_requirements | def install_requirements(self):
"""Install Ubuntu Requirements"""
print('Installing Requirements')
print(platform.dist())
if platform.dist()[0] in ['Ubuntu', 'LinuxMint']:
command = 'sudo apt-get install -y gcc git python3-dev zlib1g-dev make zip libssl-dev libbz2-dev liblzma-dev libcurl4-openssl-dev build-essential libxml2-dev apache2 zlib1g-dev bcftools build-essential cpanminus curl git libbz2-dev libcurl4-openssl-dev liblocal-lib-perl liblzma-dev libmysqlclient-dev libpng-dev libpq-dev libssl-dev manpages mysql-client openssl perl perl-base pkg-config python3-dev python3-pip python3-setuptools sed tabix unzip vcftools vim wget zlib1g-dev apache2 build-essential cpanminus curl git libmysqlclient-dev libpng-dev libssl-dev locales manpages mysql-client openssl perl perl-base unzip vim wget libgd-dev' # lamp-server^
sts = call(command, shell=True)
try:
subprocess.call(['java', '-version'])
except:
command = """sudo apt install -y software-properties-common
sudo add-apt-repository -y ppa:webupd8team/java
sudo apt-get update
echo "oracle-java8-installer shared/accepted-oracle-license-v1-1 select true" | sudo debconf-set-selections
sudo apt-get -y install oracle-java8-installer"""
sts = call(command, shell=True)
elif platform.dist()[0] in ['debian']:
command = 'sudo apt-get update'
sts = call(command, shell=True)
command = 'sudo apt-get install -y libmodule-install-perl apache2 bcftools build-essential cpanminus curl git libbz2-dev libcurl4-openssl-dev liblocal-lib-perl liblzma-dev default-libmysqlclient-dev libpng-dev libpq-dev libssl-dev manpages mysql-client openssl perl perl-base pkg-config python3-dev python3-pip python3-setuptools sed tabix unzip vcftools vim wget zlib1g-dev apache2 build-essential cpanminus curl git libpng-dev libssl-dev locales manpages mysql-client openssl perl perl-base unzip vim wget libgd-dev libxml-libxml-perl libgd-dev' # lamp-server^
sts = call(command, shell=True)
command = 'sudo apt-get install -y default-jre default-jdk'
sts = call(command, shell=True)
elif platform.dist()[0] in ['redhat', 'centos']:
command = 'sudo yum install libcurl-devel sed vcftools bcftools tabix zlib-devel postgresql96-libs perl-local-lib perl-App-cpanminus curl unzip wget'
sts = call(command, shell=True)
command = """sudo yum groupinstall 'Development Tools'"""
sts = call(command, shell=True)
command = """sudo yum install gcc gcc-c++ make openssl-devel"""
sts = call(command, shell=True)
try:
subprocess.call(['java', '-version'])
except:
command = "sudo yum install -y java-1.8.0-openjdk"
sts = call(command, shell=True)
# Perl Requirements
command = "sudo cpanm DBI DBD::mysql File::Copy::Recursive Archive::Extract Archive::Zip LWP::Simple Bio::Root::Version LWP::Protocol::https Bio::DB::Fasta CGI Test::utf8 Test::File inc::Module::Install XML::DOM::XPath XML::LibXML"
sts = call(command, shell=True)
command = "sudo cpanm --local-lib=~/perl5 local::lib && eval $(perl -I ~/perl5/lib/perl5/ -Mlocal::lib)"
sts = call(command, shell=True) | python | def install_requirements(self):
"""Install Ubuntu Requirements"""
print('Installing Requirements')
print(platform.dist())
if platform.dist()[0] in ['Ubuntu', 'LinuxMint']:
command = 'sudo apt-get install -y gcc git python3-dev zlib1g-dev make zip libssl-dev libbz2-dev liblzma-dev libcurl4-openssl-dev build-essential libxml2-dev apache2 zlib1g-dev bcftools build-essential cpanminus curl git libbz2-dev libcurl4-openssl-dev liblocal-lib-perl liblzma-dev libmysqlclient-dev libpng-dev libpq-dev libssl-dev manpages mysql-client openssl perl perl-base pkg-config python3-dev python3-pip python3-setuptools sed tabix unzip vcftools vim wget zlib1g-dev apache2 build-essential cpanminus curl git libmysqlclient-dev libpng-dev libssl-dev locales manpages mysql-client openssl perl perl-base unzip vim wget libgd-dev' # lamp-server^
sts = call(command, shell=True)
try:
subprocess.call(['java', '-version'])
except:
command = """sudo apt install -y software-properties-common
sudo add-apt-repository -y ppa:webupd8team/java
sudo apt-get update
echo "oracle-java8-installer shared/accepted-oracle-license-v1-1 select true" | sudo debconf-set-selections
sudo apt-get -y install oracle-java8-installer"""
sts = call(command, shell=True)
elif platform.dist()[0] in ['debian']:
command = 'sudo apt-get update'
sts = call(command, shell=True)
command = 'sudo apt-get install -y libmodule-install-perl apache2 bcftools build-essential cpanminus curl git libbz2-dev libcurl4-openssl-dev liblocal-lib-perl liblzma-dev default-libmysqlclient-dev libpng-dev libpq-dev libssl-dev manpages mysql-client openssl perl perl-base pkg-config python3-dev python3-pip python3-setuptools sed tabix unzip vcftools vim wget zlib1g-dev apache2 build-essential cpanminus curl git libpng-dev libssl-dev locales manpages mysql-client openssl perl perl-base unzip vim wget libgd-dev libxml-libxml-perl libgd-dev' # lamp-server^
sts = call(command, shell=True)
command = 'sudo apt-get install -y default-jre default-jdk'
sts = call(command, shell=True)
elif platform.dist()[0] in ['redhat', 'centos']:
command = 'sudo yum install libcurl-devel sed vcftools bcftools tabix zlib-devel postgresql96-libs perl-local-lib perl-App-cpanminus curl unzip wget'
sts = call(command, shell=True)
command = """sudo yum groupinstall 'Development Tools'"""
sts = call(command, shell=True)
command = """sudo yum install gcc gcc-c++ make openssl-devel"""
sts = call(command, shell=True)
try:
subprocess.call(['java', '-version'])
except:
command = "sudo yum install -y java-1.8.0-openjdk"
sts = call(command, shell=True)
# Perl Requirements
command = "sudo cpanm DBI DBD::mysql File::Copy::Recursive Archive::Extract Archive::Zip LWP::Simple Bio::Root::Version LWP::Protocol::https Bio::DB::Fasta CGI Test::utf8 Test::File inc::Module::Install XML::DOM::XPath XML::LibXML"
sts = call(command, shell=True)
command = "sudo cpanm --local-lib=~/perl5 local::lib && eval $(perl -I ~/perl5/lib/perl5/ -Mlocal::lib)"
sts = call(command, shell=True) | [
"def",
"install_requirements",
"(",
"self",
")",
":",
"print",
"(",
"'Installing Requirements'",
")",
"print",
"(",
"platform",
".",
"dist",
"(",
")",
")",
"if",
"platform",
".",
"dist",
"(",
")",
"[",
"0",
"]",
"in",
"[",
"'Ubuntu'",
",",
"'LinuxMint'",... | Install Ubuntu Requirements | [
"Install",
"Ubuntu",
"Requirements"
] | 84ba8c3cdefde4c1894b853ba8370d3b4ff1d62a | https://github.com/raonyguimaraes/pynnotator/blob/84ba8c3cdefde4c1894b853ba8370d3b4ff1d62a/pynnotator/install.py#L33-L79 | train | 43,703 |
morpframework/morpfw | morpfw/interfaces.py | IStorageBase.search | def search(self, query: Optional[dict] = None, offset: Optional[int] = None,
limit: Optional[int] = None,
order_by: Union[None, list, tuple] = None) -> Sequence['IModel']:
"""return search result based on specified rulez query"""
raise NotImplementedError | python | def search(self, query: Optional[dict] = None, offset: Optional[int] = None,
limit: Optional[int] = None,
order_by: Union[None, list, tuple] = None) -> Sequence['IModel']:
"""return search result based on specified rulez query"""
raise NotImplementedError | [
"def",
"search",
"(",
"self",
",",
"query",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"offset",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"limit",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"order_by",
":",
"Union",
... | return search result based on specified rulez query | [
"return",
"search",
"result",
"based",
"on",
"specified",
"rulez",
"query"
] | 803fbf29714e6f29456482f1cfbdbd4922b020b0 | https://github.com/morpframework/morpfw/blob/803fbf29714e6f29456482f1cfbdbd4922b020b0/morpfw/interfaces.py#L137-L141 | train | 43,704 |
morpframework/morpfw | morpfw/interfaces.py | IStorage.aggregate | def aggregate(self, query: Optional[dict] = None,
group: Optional[dict] = None,
order_by: Union[None, list, tuple] = None) -> list:
"""return aggregation result based on specified rulez query and group"""
raise NotImplementedError | python | def aggregate(self, query: Optional[dict] = None,
group: Optional[dict] = None,
order_by: Union[None, list, tuple] = None) -> list:
"""return aggregation result based on specified rulez query and group"""
raise NotImplementedError | [
"def",
"aggregate",
"(",
"self",
",",
"query",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"group",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"order_by",
":",
"Union",
"[",
"None",
",",
"list",
",",
"tuple",
"]",
"=",
"None",
... | return aggregation result based on specified rulez query and group | [
"return",
"aggregation",
"result",
"based",
"on",
"specified",
"rulez",
"query",
"and",
"group"
] | 803fbf29714e6f29456482f1cfbdbd4922b020b0 | https://github.com/morpframework/morpfw/blob/803fbf29714e6f29456482f1cfbdbd4922b020b0/morpfw/interfaces.py#L168-L172 | train | 43,705 |
morpframework/morpfw | morpfw/interfaces.py | IModel.put_blob | def put_blob(self, field: str, fileobj: BinaryIO,
filename: str,
mimetype: Optional[str] = None,
size: Optional[int] = None,
encoding: Optional[str] = None) -> IBlob:
"""Receive and store blob object"""
raise NotImplementedError | python | def put_blob(self, field: str, fileobj: BinaryIO,
filename: str,
mimetype: Optional[str] = None,
size: Optional[int] = None,
encoding: Optional[str] = None) -> IBlob:
"""Receive and store blob object"""
raise NotImplementedError | [
"def",
"put_blob",
"(",
"self",
",",
"field",
":",
"str",
",",
"fileobj",
":",
"BinaryIO",
",",
"filename",
":",
"str",
",",
"mimetype",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"size",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",... | Receive and store blob object | [
"Receive",
"and",
"store",
"blob",
"object"
] | 803fbf29714e6f29456482f1cfbdbd4922b020b0 | https://github.com/morpframework/morpfw/blob/803fbf29714e6f29456482f1cfbdbd4922b020b0/morpfw/interfaces.py#L289-L295 | train | 43,706 |
morpframework/morpfw | morpfw/interfaces.py | ICollection.search | def search(self, query: Optional[dict] = None,
offset: int = 0,
limit: Optional[int] = None,
order_by: Optional[tuple] = None,
secure: bool = False) -> List[IModel]:
"""Search for models
Filtering is done through ``rulez`` based JSON/dict query, which
defines boolean statements in JSON/dict structure.
: param query: Rulez based query
: param offset: Result offset
: param limit: Maximum number of result
: param order_by: Tuple of ``(field, order)`` where ``order`` is
``'asc'`` or ``'desc'``
: param secure: When set to True, this will filter out any object which
current logged in user is not allowed to see
: todo: ``order_by`` need to allow multiple field ordering
"""
raise NotImplementedError | python | def search(self, query: Optional[dict] = None,
offset: int = 0,
limit: Optional[int] = None,
order_by: Optional[tuple] = None,
secure: bool = False) -> List[IModel]:
"""Search for models
Filtering is done through ``rulez`` based JSON/dict query, which
defines boolean statements in JSON/dict structure.
: param query: Rulez based query
: param offset: Result offset
: param limit: Maximum number of result
: param order_by: Tuple of ``(field, order)`` where ``order`` is
``'asc'`` or ``'desc'``
: param secure: When set to True, this will filter out any object which
current logged in user is not allowed to see
: todo: ``order_by`` need to allow multiple field ordering
"""
raise NotImplementedError | [
"def",
"search",
"(",
"self",
",",
"query",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"offset",
":",
"int",
"=",
"0",
",",
"limit",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"order_by",
":",
"Optional",
"[",
"tuple",
"]",
"="... | Search for models
Filtering is done through ``rulez`` based JSON/dict query, which
defines boolean statements in JSON/dict structure.
: param query: Rulez based query
: param offset: Result offset
: param limit: Maximum number of result
: param order_by: Tuple of ``(field, order)`` where ``order`` is
``'asc'`` or ``'desc'``
: param secure: When set to True, this will filter out any object which
current logged in user is not allowed to see
: todo: ``order_by`` need to allow multiple field ordering | [
"Search",
"for",
"models"
] | 803fbf29714e6f29456482f1cfbdbd4922b020b0 | https://github.com/morpframework/morpfw/blob/803fbf29714e6f29456482f1cfbdbd4922b020b0/morpfw/interfaces.py#L339-L359 | train | 43,707 |
morpframework/morpfw | morpfw/interfaces.py | ICollection.aggregate | def aggregate(self, query: Optional[dict] = None,
group: Optional[dict] = None,
order_by: Optional[tuple] = None) -> List[IModel]:
"""Get aggregated results
: param query: Rulez based query
: param group: Grouping structure
: param order_by: Tuple of ``(field, order)`` where ``order`` is
``'asc'`` or ``'desc'``
: todo: Grouping structure need to be documented
"""
raise NotImplementedError | python | def aggregate(self, query: Optional[dict] = None,
group: Optional[dict] = None,
order_by: Optional[tuple] = None) -> List[IModel]:
"""Get aggregated results
: param query: Rulez based query
: param group: Grouping structure
: param order_by: Tuple of ``(field, order)`` where ``order`` is
``'asc'`` or ``'desc'``
: todo: Grouping structure need to be documented
"""
raise NotImplementedError | [
"def",
"aggregate",
"(",
"self",
",",
"query",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"group",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"order_by",
":",
"Optional",
"[",
"tuple",
"]",
"=",
"None",
")",
"->",
"List",
"[",
... | Get aggregated results
: param query: Rulez based query
: param group: Grouping structure
: param order_by: Tuple of ``(field, order)`` where ``order`` is
``'asc'`` or ``'desc'``
: todo: Grouping structure need to be documented | [
"Get",
"aggregated",
"results"
] | 803fbf29714e6f29456482f1cfbdbd4922b020b0 | https://github.com/morpframework/morpfw/blob/803fbf29714e6f29456482f1cfbdbd4922b020b0/morpfw/interfaces.py#L362-L375 | train | 43,708 |
azavea/python-omgeo | omgeo/places.py | Viewbox.to_bing_str | def to_bing_str(self):
"""
Convert Viewbox object to a string that can be used by Bing
as a query parameter.
"""
vb = self.convert_srs(4326)
return '%s,%s,%s,%s' % (vb.bottom, vb.left, vb.top, vb.right) | python | def to_bing_str(self):
"""
Convert Viewbox object to a string that can be used by Bing
as a query parameter.
"""
vb = self.convert_srs(4326)
return '%s,%s,%s,%s' % (vb.bottom, vb.left, vb.top, vb.right) | [
"def",
"to_bing_str",
"(",
"self",
")",
":",
"vb",
"=",
"self",
".",
"convert_srs",
"(",
"4326",
")",
"return",
"'%s,%s,%s,%s'",
"%",
"(",
"vb",
".",
"bottom",
",",
"vb",
".",
"left",
",",
"vb",
".",
"top",
",",
"vb",
".",
"right",
")"
] | Convert Viewbox object to a string that can be used by Bing
as a query parameter. | [
"Convert",
"Viewbox",
"object",
"to",
"a",
"string",
"that",
"can",
"be",
"used",
"by",
"Bing",
"as",
"a",
"query",
"parameter",
"."
] | 40f4e006f087dbc795a5d954ffa2c0eab433f8c9 | https://github.com/azavea/python-omgeo/blob/40f4e006f087dbc795a5d954ffa2c0eab433f8c9/omgeo/places.py#L29-L35 | train | 43,709 |
azavea/python-omgeo | omgeo/places.py | Viewbox.to_pelias_dict | def to_pelias_dict(self):
"""
Convert Viewbox object to a string that can be used by Pelias
as a query parameter.
"""
vb = self.convert_srs(4326)
return {
'boundary.rect.min_lat': vb.bottom,
'boundary.rect.min_lon': vb.left,
'boundary.rect.max_lat': vb.top,
'boundary.rect.max_lon': vb.right
} | python | def to_pelias_dict(self):
"""
Convert Viewbox object to a string that can be used by Pelias
as a query parameter.
"""
vb = self.convert_srs(4326)
return {
'boundary.rect.min_lat': vb.bottom,
'boundary.rect.min_lon': vb.left,
'boundary.rect.max_lat': vb.top,
'boundary.rect.max_lon': vb.right
} | [
"def",
"to_pelias_dict",
"(",
"self",
")",
":",
"vb",
"=",
"self",
".",
"convert_srs",
"(",
"4326",
")",
"return",
"{",
"'boundary.rect.min_lat'",
":",
"vb",
".",
"bottom",
",",
"'boundary.rect.min_lon'",
":",
"vb",
".",
"left",
",",
"'boundary.rect.max_lat'",... | Convert Viewbox object to a string that can be used by Pelias
as a query parameter. | [
"Convert",
"Viewbox",
"object",
"to",
"a",
"string",
"that",
"can",
"be",
"used",
"by",
"Pelias",
"as",
"a",
"query",
"parameter",
"."
] | 40f4e006f087dbc795a5d954ffa2c0eab433f8c9 | https://github.com/azavea/python-omgeo/blob/40f4e006f087dbc795a5d954ffa2c0eab433f8c9/omgeo/places.py#L37-L48 | train | 43,710 |
azavea/python-omgeo | omgeo/places.py | Viewbox.to_esri_wgs_json | def to_esri_wgs_json(self):
"""
Convert Viewbox object to a JSON string that can be used
by the ESRI World Geocoding Service as a parameter.
"""
try:
return ('{ "xmin" : %s, '
'"ymin" : %s, '
'"xmax" : %s, '
'"ymax" : %s, '
'"spatialReference" : {"wkid" : %d} }'
% (self.left,
self.bottom,
self.right,
self.top,
self.wkid))
except ValueError:
raise Exception('One or more values could not be cast to a number. '
'Four bounding points must be real numbers. '
'WKID must be an integer.') | python | def to_esri_wgs_json(self):
"""
Convert Viewbox object to a JSON string that can be used
by the ESRI World Geocoding Service as a parameter.
"""
try:
return ('{ "xmin" : %s, '
'"ymin" : %s, '
'"xmax" : %s, '
'"ymax" : %s, '
'"spatialReference" : {"wkid" : %d} }'
% (self.left,
self.bottom,
self.right,
self.top,
self.wkid))
except ValueError:
raise Exception('One or more values could not be cast to a number. '
'Four bounding points must be real numbers. '
'WKID must be an integer.') | [
"def",
"to_esri_wgs_json",
"(",
"self",
")",
":",
"try",
":",
"return",
"(",
"'{ \"xmin\" : %s, '",
"'\"ymin\" : %s, '",
"'\"xmax\" : %s, '",
"'\"ymax\" : %s, '",
"'\"spatialReference\" : {\"wkid\" : %d} }'",
"%",
"(",
"self",
".",
"left",
",",
"self",
".",
"bottom",
... | Convert Viewbox object to a JSON string that can be used
by the ESRI World Geocoding Service as a parameter. | [
"Convert",
"Viewbox",
"object",
"to",
"a",
"JSON",
"string",
"that",
"can",
"be",
"used",
"by",
"the",
"ESRI",
"World",
"Geocoding",
"Service",
"as",
"a",
"parameter",
"."
] | 40f4e006f087dbc795a5d954ffa2c0eab433f8c9 | https://github.com/azavea/python-omgeo/blob/40f4e006f087dbc795a5d954ffa2c0eab433f8c9/omgeo/places.py#L64-L83 | train | 43,711 |
morpframework/morpfw | morpfw/authn/pas/user/view.py | register | def register(context, request, load):
"""Validate the username and password and create the user."""
data = request.json
res = validate(data, dataclass_to_jsl(
RegistrationSchema).get_schema())
if res:
@request.after
def set_error(response):
response.status = 422
return {
'status': 'error',
'field_errors': [{'message': res[x]} for x in res.keys()]
}
if data['password'] != data['password_validate']:
@request.after
def adjust_response(response):
response.status = 422
return {'status': 'error',
'message': 'Password confirmation does not match'}
if 'state' not in data.keys() or not data['state']:
data['state'] = request.app.settings.application.new_user_state
del data['password_validate']
obj = context.create(data)
return {'status': 'success'} | python | def register(context, request, load):
"""Validate the username and password and create the user."""
data = request.json
res = validate(data, dataclass_to_jsl(
RegistrationSchema).get_schema())
if res:
@request.after
def set_error(response):
response.status = 422
return {
'status': 'error',
'field_errors': [{'message': res[x]} for x in res.keys()]
}
if data['password'] != data['password_validate']:
@request.after
def adjust_response(response):
response.status = 422
return {'status': 'error',
'message': 'Password confirmation does not match'}
if 'state' not in data.keys() or not data['state']:
data['state'] = request.app.settings.application.new_user_state
del data['password_validate']
obj = context.create(data)
return {'status': 'success'} | [
"def",
"register",
"(",
"context",
",",
"request",
",",
"load",
")",
":",
"data",
"=",
"request",
".",
"json",
"res",
"=",
"validate",
"(",
"data",
",",
"dataclass_to_jsl",
"(",
"RegistrationSchema",
")",
".",
"get_schema",
"(",
")",
")",
"if",
"res",
... | Validate the username and password and create the user. | [
"Validate",
"the",
"username",
"and",
"password",
"and",
"create",
"the",
"user",
"."
] | 803fbf29714e6f29456482f1cfbdbd4922b020b0 | https://github.com/morpframework/morpfw/blob/803fbf29714e6f29456482f1cfbdbd4922b020b0/morpfw/authn/pas/user/view.py#L22-L48 | train | 43,712 |
morpframework/morpfw | morpfw/authn/pas/user/view.py | process_login | def process_login(context, request):
"""Authenticate username and password and log in user"""
username = request.json['username']
password = request.json['password']
# Do the password validation.
user = context.authenticate(username, password)
if not user:
@request.after
def adjust_status(response):
response.status = 401
return {
'status': 'error',
'error': {
'code': 401,
'message': 'Invalid Username / Password'
}
}
@request.after
def remember(response):
"""Remember the identity of the user logged in."""
# We pass the extra info to the identity object.
response.headers.add('Access-Control-Expose-Headers', 'Authorization')
identity = user.identity
request.app.remember_identity(response, request, identity)
return {
'status': 'success'
} | python | def process_login(context, request):
"""Authenticate username and password and log in user"""
username = request.json['username']
password = request.json['password']
# Do the password validation.
user = context.authenticate(username, password)
if not user:
@request.after
def adjust_status(response):
response.status = 401
return {
'status': 'error',
'error': {
'code': 401,
'message': 'Invalid Username / Password'
}
}
@request.after
def remember(response):
"""Remember the identity of the user logged in."""
# We pass the extra info to the identity object.
response.headers.add('Access-Control-Expose-Headers', 'Authorization')
identity = user.identity
request.app.remember_identity(response, request, identity)
return {
'status': 'success'
} | [
"def",
"process_login",
"(",
"context",
",",
"request",
")",
":",
"username",
"=",
"request",
".",
"json",
"[",
"'username'",
"]",
"password",
"=",
"request",
".",
"json",
"[",
"'password'",
"]",
"# Do the password validation.",
"user",
"=",
"context",
".",
... | Authenticate username and password and log in user | [
"Authenticate",
"username",
"and",
"password",
"and",
"log",
"in",
"user"
] | 803fbf29714e6f29456482f1cfbdbd4922b020b0 | https://github.com/morpframework/morpfw/blob/803fbf29714e6f29456482f1cfbdbd4922b020b0/morpfw/authn/pas/user/view.py#L60-L89 | train | 43,713 |
morpframework/morpfw | morpfw/authn/pas/group/view.py | list_members | def list_members(context, request):
"""Return the list of users in the group."""
members = context.members()
return {
'users': [{
'username': m.identifier,
'userid': m.userid,
'roles': context.get_member_roles(m.userid),
'links': [rellink(m, request)]
} for m in members]
} | python | def list_members(context, request):
"""Return the list of users in the group."""
members = context.members()
return {
'users': [{
'username': m.identifier,
'userid': m.userid,
'roles': context.get_member_roles(m.userid),
'links': [rellink(m, request)]
} for m in members]
} | [
"def",
"list_members",
"(",
"context",
",",
"request",
")",
":",
"members",
"=",
"context",
".",
"members",
"(",
")",
"return",
"{",
"'users'",
":",
"[",
"{",
"'username'",
":",
"m",
".",
"identifier",
",",
"'userid'",
":",
"m",
".",
"userid",
",",
"... | Return the list of users in the group. | [
"Return",
"the",
"list",
"of",
"users",
"in",
"the",
"group",
"."
] | 803fbf29714e6f29456482f1cfbdbd4922b020b0 | https://github.com/morpframework/morpfw/blob/803fbf29714e6f29456482f1cfbdbd4922b020b0/morpfw/authn/pas/group/view.py#L16-L26 | train | 43,714 |
morpframework/morpfw | morpfw/authn/pas/group/view.py | grant_member | def grant_member(context, request):
"""Grant member roles in the group."""
mapping = request.json['mapping']
for entry in mapping:
user = entry['user']
roles = entry['roles']
username = user.get('username', None)
userid = user.get('userid', None)
if userid:
u = context.get_user_by_userid(userid)
elif username:
u = context.get_user_by_username(username)
else:
u = None
if u is None:
raise UnprocessableError(
'User %s does not exists' % (userid or username))
for rolename in roles:
context.grant_member_role(u.userid, rolename)
return {'status': 'success'} | python | def grant_member(context, request):
"""Grant member roles in the group."""
mapping = request.json['mapping']
for entry in mapping:
user = entry['user']
roles = entry['roles']
username = user.get('username', None)
userid = user.get('userid', None)
if userid:
u = context.get_user_by_userid(userid)
elif username:
u = context.get_user_by_username(username)
else:
u = None
if u is None:
raise UnprocessableError(
'User %s does not exists' % (userid or username))
for rolename in roles:
context.grant_member_role(u.userid, rolename)
return {'status': 'success'} | [
"def",
"grant_member",
"(",
"context",
",",
"request",
")",
":",
"mapping",
"=",
"request",
".",
"json",
"[",
"'mapping'",
"]",
"for",
"entry",
"in",
"mapping",
":",
"user",
"=",
"entry",
"[",
"'user'",
"]",
"roles",
"=",
"entry",
"[",
"'roles'",
"]",
... | Grant member roles in the group. | [
"Grant",
"member",
"roles",
"in",
"the",
"group",
"."
] | 803fbf29714e6f29456482f1cfbdbd4922b020b0 | https://github.com/morpframework/morpfw/blob/803fbf29714e6f29456482f1cfbdbd4922b020b0/morpfw/authn/pas/group/view.py#L31-L50 | train | 43,715 |
morpframework/morpfw | morpfw/authn/pas/group/view.py | revoke_member | def revoke_member(context, request):
"""Revoke member roles in the group."""
mapping = request.json['mapping']
for entry in mapping:
user = entry['user']
roles = entry['roles']
username = user.get('username', None)
userid = user.get('userid', None)
if userid:
u = context.get_user_by_userid(userid)
elif username:
u = context.get_user_by_username(username)
else:
u = None
if u is None:
raise UnprocessableError(
'User %s does not exists' % (userid or username))
for rolename in roles:
context.revoke_member_role(u.userid, rolename)
return {'status': 'success'} | python | def revoke_member(context, request):
"""Revoke member roles in the group."""
mapping = request.json['mapping']
for entry in mapping:
user = entry['user']
roles = entry['roles']
username = user.get('username', None)
userid = user.get('userid', None)
if userid:
u = context.get_user_by_userid(userid)
elif username:
u = context.get_user_by_username(username)
else:
u = None
if u is None:
raise UnprocessableError(
'User %s does not exists' % (userid or username))
for rolename in roles:
context.revoke_member_role(u.userid, rolename)
return {'status': 'success'} | [
"def",
"revoke_member",
"(",
"context",
",",
"request",
")",
":",
"mapping",
"=",
"request",
".",
"json",
"[",
"'mapping'",
"]",
"for",
"entry",
"in",
"mapping",
":",
"user",
"=",
"entry",
"[",
"'user'",
"]",
"roles",
"=",
"entry",
"[",
"'roles'",
"]",... | Revoke member roles in the group. | [
"Revoke",
"member",
"roles",
"in",
"the",
"group",
"."
] | 803fbf29714e6f29456482f1cfbdbd4922b020b0 | https://github.com/morpframework/morpfw/blob/803fbf29714e6f29456482f1cfbdbd4922b020b0/morpfw/authn/pas/group/view.py#L55-L75 | train | 43,716 |
bbayles/vod_metadata | vod_metadata/media_info.py | call_MediaInfo | def call_MediaInfo(file_name, mediainfo_path=None):
"""Returns a dictionary of dictionaries with the output of
MediaInfo -f file_name"""
if mediainfo_path is None:
mediainfo_path = find_MediaInfo()
result = subprocess.check_output(
[mediainfo_path, "-f", file_name], universal_newlines=True
)
D = collections.defaultdict(dict)
for line in result.splitlines():
line = line.split(':', 1)
# Skip separators
if line[0] == '':
continue
# Start a new section
elif len(line) == 1:
section = line[0].strip()
# Record section key, value pairs
else:
k = line[0].strip()
v = line[1].strip()
if k not in D[section]:
D[section][k] = v
return D | python | def call_MediaInfo(file_name, mediainfo_path=None):
"""Returns a dictionary of dictionaries with the output of
MediaInfo -f file_name"""
if mediainfo_path is None:
mediainfo_path = find_MediaInfo()
result = subprocess.check_output(
[mediainfo_path, "-f", file_name], universal_newlines=True
)
D = collections.defaultdict(dict)
for line in result.splitlines():
line = line.split(':', 1)
# Skip separators
if line[0] == '':
continue
# Start a new section
elif len(line) == 1:
section = line[0].strip()
# Record section key, value pairs
else:
k = line[0].strip()
v = line[1].strip()
if k not in D[section]:
D[section][k] = v
return D | [
"def",
"call_MediaInfo",
"(",
"file_name",
",",
"mediainfo_path",
"=",
"None",
")",
":",
"if",
"mediainfo_path",
"is",
"None",
":",
"mediainfo_path",
"=",
"find_MediaInfo",
"(",
")",
"result",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"mediainfo_path",
... | Returns a dictionary of dictionaries with the output of
MediaInfo -f file_name | [
"Returns",
"a",
"dictionary",
"of",
"dictionaries",
"with",
"the",
"output",
"of",
"MediaInfo",
"-",
"f",
"file_name"
] | d91c5766864e0c4f274b0e887c57a026d25a5ac5 | https://github.com/bbayles/vod_metadata/blob/d91c5766864e0c4f274b0e887c57a026d25a5ac5/vod_metadata/media_info.py#L25-L50 | train | 43,717 |
bbayles/vod_metadata | vod_metadata/media_info.py | check_video | def check_video(file_name, mediainfo_path=None):
"""
Scans the given file with MediaInfo and returns the video and audio codec
information if all the required parameters were found.
"""
D = call_MediaInfo(file_name, mediainfo_path)
err_msg = "Could not determine all video paramters"
if ("General" not in D) or ("Video" not in D):
raise MediaInfoError(err_msg)
general_keys = ("Count of audio streams", "File size", "Overall bit rate")
if any(k not in D["General"] for k in general_keys):
raise MediaInfoError(err_msg)
video_keys = (
"Format profile",
"Commercial name",
"Frame rate",
"Height",
"Scan type",
)
if any(k not in D["Video"] for k in video_keys):
raise MediaInfoError(err_msg)
return D | python | def check_video(file_name, mediainfo_path=None):
"""
Scans the given file with MediaInfo and returns the video and audio codec
information if all the required parameters were found.
"""
D = call_MediaInfo(file_name, mediainfo_path)
err_msg = "Could not determine all video paramters"
if ("General" not in D) or ("Video" not in D):
raise MediaInfoError(err_msg)
general_keys = ("Count of audio streams", "File size", "Overall bit rate")
if any(k not in D["General"] for k in general_keys):
raise MediaInfoError(err_msg)
video_keys = (
"Format profile",
"Commercial name",
"Frame rate",
"Height",
"Scan type",
)
if any(k not in D["Video"] for k in video_keys):
raise MediaInfoError(err_msg)
return D | [
"def",
"check_video",
"(",
"file_name",
",",
"mediainfo_path",
"=",
"None",
")",
":",
"D",
"=",
"call_MediaInfo",
"(",
"file_name",
",",
"mediainfo_path",
")",
"err_msg",
"=",
"\"Could not determine all video paramters\"",
"if",
"(",
"\"General\"",
"not",
"in",
"D... | Scans the given file with MediaInfo and returns the video and audio codec
information if all the required parameters were found. | [
"Scans",
"the",
"given",
"file",
"with",
"MediaInfo",
"and",
"returns",
"the",
"video",
"and",
"audio",
"codec",
"information",
"if",
"all",
"the",
"required",
"parameters",
"were",
"found",
"."
] | d91c5766864e0c4f274b0e887c57a026d25a5ac5 | https://github.com/bbayles/vod_metadata/blob/d91c5766864e0c4f274b0e887c57a026d25a5ac5/vod_metadata/media_info.py#L53-L78 | train | 43,718 |
bbayles/vod_metadata | vod_metadata/media_info.py | check_picture | def check_picture(file_name, mediainfo_path=None):
"""
Scans the given file with MediaInfo and returns the picture
information if all the required parameters were found.
"""
D = call_MediaInfo(file_name, mediainfo_path)
# Check that the file analyzed was a valid movie
if (
("Image" not in D) or
("Width" not in D["Image"]) or
("Height" not in D["Image"])
):
raise MediaInfoError("Could not determine all picture paramters")
return D | python | def check_picture(file_name, mediainfo_path=None):
"""
Scans the given file with MediaInfo and returns the picture
information if all the required parameters were found.
"""
D = call_MediaInfo(file_name, mediainfo_path)
# Check that the file analyzed was a valid movie
if (
("Image" not in D) or
("Width" not in D["Image"]) or
("Height" not in D["Image"])
):
raise MediaInfoError("Could not determine all picture paramters")
return D | [
"def",
"check_picture",
"(",
"file_name",
",",
"mediainfo_path",
"=",
"None",
")",
":",
"D",
"=",
"call_MediaInfo",
"(",
"file_name",
",",
"mediainfo_path",
")",
"# Check that the file analyzed was a valid movie",
"if",
"(",
"(",
"\"Image\"",
"not",
"in",
"D",
")"... | Scans the given file with MediaInfo and returns the picture
information if all the required parameters were found. | [
"Scans",
"the",
"given",
"file",
"with",
"MediaInfo",
"and",
"returns",
"the",
"picture",
"information",
"if",
"all",
"the",
"required",
"parameters",
"were",
"found",
"."
] | d91c5766864e0c4f274b0e887c57a026d25a5ac5 | https://github.com/bbayles/vod_metadata/blob/d91c5766864e0c4f274b0e887c57a026d25a5ac5/vod_metadata/media_info.py#L81-L95 | train | 43,719 |
Cornices/cornice.ext.sphinx | cornice_sphinx/__init__.py | ServiceDirective._get_attributes | def _get_attributes(schema, location):
"""Return the schema's children, filtered by location."""
schema = DottedNameResolver(__name__).maybe_resolve(schema)
def _filter(attr):
if not hasattr(attr, "location"):
valid_location = 'body' in location
else:
valid_location = attr.location in to_list(location)
return valid_location
return list(filter(_filter, schema().children)) | python | def _get_attributes(schema, location):
"""Return the schema's children, filtered by location."""
schema = DottedNameResolver(__name__).maybe_resolve(schema)
def _filter(attr):
if not hasattr(attr, "location"):
valid_location = 'body' in location
else:
valid_location = attr.location in to_list(location)
return valid_location
return list(filter(_filter, schema().children)) | [
"def",
"_get_attributes",
"(",
"schema",
",",
"location",
")",
":",
"schema",
"=",
"DottedNameResolver",
"(",
"__name__",
")",
".",
"maybe_resolve",
"(",
"schema",
")",
"def",
"_filter",
"(",
"attr",
")",
":",
"if",
"not",
"hasattr",
"(",
"attr",
",",
"\... | Return the schema's children, filtered by location. | [
"Return",
"the",
"schema",
"s",
"children",
"filtered",
"by",
"location",
"."
] | f73fdcc94d78fb5c94262adb9adc187c96378a53 | https://github.com/Cornices/cornice.ext.sphinx/blob/f73fdcc94d78fb5c94262adb9adc187c96378a53/cornice_sphinx/__init__.py#L117-L128 | train | 43,720 |
dims/etcd3-gateway | etcd3gw/lock.py | Lock.is_acquired | def is_acquired(self):
"""Check if the lock is acquired"""
values = self.client.get(self.key)
return six.b(self._uuid) in values | python | def is_acquired(self):
"""Check if the lock is acquired"""
values = self.client.get(self.key)
return six.b(self._uuid) in values | [
"def",
"is_acquired",
"(",
"self",
")",
":",
"values",
"=",
"self",
".",
"client",
".",
"get",
"(",
"self",
".",
"key",
")",
"return",
"six",
".",
"b",
"(",
"self",
".",
"_uuid",
")",
"in",
"values"
] | Check if the lock is acquired | [
"Check",
"if",
"the",
"lock",
"is",
"acquired"
] | ad566c29cbde135aee20cfd32e0a4815ca3b5ee6 | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/lock.py#L103-L106 | train | 43,721 |
dims/etcd3-gateway | etcd3gw/client.py | Etcd3Client.get_url | def get_url(self, path):
"""Construct a full url to the v3alpha API given a specific path
:param path:
:return: url
"""
host = ('[' + self.host + ']' if (self.host.find(':') != -1)
else self.host)
base_url = self.protocol + '://' + host + ':' + str(self.port)
return base_url + '/v3alpha/' + path.lstrip("/") | python | def get_url(self, path):
"""Construct a full url to the v3alpha API given a specific path
:param path:
:return: url
"""
host = ('[' + self.host + ']' if (self.host.find(':') != -1)
else self.host)
base_url = self.protocol + '://' + host + ':' + str(self.port)
return base_url + '/v3alpha/' + path.lstrip("/") | [
"def",
"get_url",
"(",
"self",
",",
"path",
")",
":",
"host",
"=",
"(",
"'['",
"+",
"self",
".",
"host",
"+",
"']'",
"if",
"(",
"self",
".",
"host",
".",
"find",
"(",
"':'",
")",
"!=",
"-",
"1",
")",
"else",
"self",
".",
"host",
")",
"base_ur... | Construct a full url to the v3alpha API given a specific path
:param path:
:return: url | [
"Construct",
"a",
"full",
"url",
"to",
"the",
"v3alpha",
"API",
"given",
"a",
"specific",
"path"
] | ad566c29cbde135aee20cfd32e0a4815ca3b5ee6 | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/client.py#L63-L72 | train | 43,722 |
dims/etcd3-gateway | etcd3gw/client.py | Etcd3Client.post | def post(self, *args, **kwargs):
"""helper method for HTTP POST
:param args:
:param kwargs:
:return: json response
"""
try:
resp = self.session.post(*args, **kwargs)
if resp.status_code in _EXCEPTIONS_BY_CODE:
raise _EXCEPTIONS_BY_CODE[resp.status_code](resp.reason)
if resp.status_code != requests.codes['ok']:
raise exceptions.Etcd3Exception(resp.reason)
except requests.exceptions.Timeout as ex:
raise exceptions.ConnectionTimeoutError(six.text_type(ex))
except requests.exceptions.ConnectionError as ex:
raise exceptions.ConnectionFailedError(six.text_type(ex))
return resp.json() | python | def post(self, *args, **kwargs):
"""helper method for HTTP POST
:param args:
:param kwargs:
:return: json response
"""
try:
resp = self.session.post(*args, **kwargs)
if resp.status_code in _EXCEPTIONS_BY_CODE:
raise _EXCEPTIONS_BY_CODE[resp.status_code](resp.reason)
if resp.status_code != requests.codes['ok']:
raise exceptions.Etcd3Exception(resp.reason)
except requests.exceptions.Timeout as ex:
raise exceptions.ConnectionTimeoutError(six.text_type(ex))
except requests.exceptions.ConnectionError as ex:
raise exceptions.ConnectionFailedError(six.text_type(ex))
return resp.json() | [
"def",
"post",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"resp",
"=",
"self",
".",
"session",
".",
"post",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"resp",
".",
"status_code",
"in",
"_EXCEPTIONS_BY... | helper method for HTTP POST
:param args:
:param kwargs:
:return: json response | [
"helper",
"method",
"for",
"HTTP",
"POST"
] | ad566c29cbde135aee20cfd32e0a4815ca3b5ee6 | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/client.py#L74-L91 | train | 43,723 |
dims/etcd3-gateway | etcd3gw/client.py | Etcd3Client.lease | def lease(self, ttl=DEFAULT_TIMEOUT):
"""Create a Lease object given a timeout
:param ttl: timeout
:return: Lease object
"""
result = self.post(self.get_url("/lease/grant"),
json={"TTL": ttl, "ID": 0})
return Lease(int(result['ID']), client=self) | python | def lease(self, ttl=DEFAULT_TIMEOUT):
"""Create a Lease object given a timeout
:param ttl: timeout
:return: Lease object
"""
result = self.post(self.get_url("/lease/grant"),
json={"TTL": ttl, "ID": 0})
return Lease(int(result['ID']), client=self) | [
"def",
"lease",
"(",
"self",
",",
"ttl",
"=",
"DEFAULT_TIMEOUT",
")",
":",
"result",
"=",
"self",
".",
"post",
"(",
"self",
".",
"get_url",
"(",
"\"/lease/grant\"",
")",
",",
"json",
"=",
"{",
"\"TTL\"",
":",
"ttl",
",",
"\"ID\"",
":",
"0",
"}",
")... | Create a Lease object given a timeout
:param ttl: timeout
:return: Lease object | [
"Create",
"a",
"Lease",
"object",
"given",
"a",
"timeout"
] | ad566c29cbde135aee20cfd32e0a4815ca3b5ee6 | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/client.py#L110-L118 | train | 43,724 |
dims/etcd3-gateway | etcd3gw/client.py | Etcd3Client.lock | def lock(self, id=str(uuid.uuid4()), ttl=DEFAULT_TIMEOUT):
"""Create a Lock object given an ID and timeout
:param id: ID for the lock, creates a new uuid if not provided
:param ttl: timeout
:return: Lock object
"""
return Lock(id, ttl=ttl, client=self) | python | def lock(self, id=str(uuid.uuid4()), ttl=DEFAULT_TIMEOUT):
"""Create a Lock object given an ID and timeout
:param id: ID for the lock, creates a new uuid if not provided
:param ttl: timeout
:return: Lock object
"""
return Lock(id, ttl=ttl, client=self) | [
"def",
"lock",
"(",
"self",
",",
"id",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
",",
"ttl",
"=",
"DEFAULT_TIMEOUT",
")",
":",
"return",
"Lock",
"(",
"id",
",",
"ttl",
"=",
"ttl",
",",
"client",
"=",
"self",
")"
] | Create a Lock object given an ID and timeout
:param id: ID for the lock, creates a new uuid if not provided
:param ttl: timeout
:return: Lock object | [
"Create",
"a",
"Lock",
"object",
"given",
"an",
"ID",
"and",
"timeout"
] | ad566c29cbde135aee20cfd32e0a4815ca3b5ee6 | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/client.py#L120-L127 | train | 43,725 |
dims/etcd3-gateway | etcd3gw/client.py | Etcd3Client.create | def create(self, key, value):
"""Atomically create the given key only if the key doesn't exist.
This verifies that the create_revision of a key equales to 0, then
creates the key with the value.
This operation takes place in a transaction.
:param key: key in etcd to create
:param value: value of the key
:type value: bytes or string
:returns: status of transaction, ``True`` if the create was
successful, ``False`` otherwise
:rtype: bool
"""
base64_key = _encode(key)
base64_value = _encode(value)
txn = {
'compare': [{
'key': base64_key,
'result': 'EQUAL',
'target': 'CREATE',
'create_revision': 0
}],
'success': [{
'request_put': {
'key': base64_key,
'value': base64_value,
}
}],
'failure': []
}
result = self.transaction(txn)
if 'succeeded' in result:
return result['succeeded']
return False | python | def create(self, key, value):
"""Atomically create the given key only if the key doesn't exist.
This verifies that the create_revision of a key equales to 0, then
creates the key with the value.
This operation takes place in a transaction.
:param key: key in etcd to create
:param value: value of the key
:type value: bytes or string
:returns: status of transaction, ``True`` if the create was
successful, ``False`` otherwise
:rtype: bool
"""
base64_key = _encode(key)
base64_value = _encode(value)
txn = {
'compare': [{
'key': base64_key,
'result': 'EQUAL',
'target': 'CREATE',
'create_revision': 0
}],
'success': [{
'request_put': {
'key': base64_key,
'value': base64_value,
}
}],
'failure': []
}
result = self.transaction(txn)
if 'succeeded' in result:
return result['succeeded']
return False | [
"def",
"create",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"base64_key",
"=",
"_encode",
"(",
"key",
")",
"base64_value",
"=",
"_encode",
"(",
"value",
")",
"txn",
"=",
"{",
"'compare'",
":",
"[",
"{",
"'key'",
":",
"base64_key",
",",
"'result... | Atomically create the given key only if the key doesn't exist.
This verifies that the create_revision of a key equales to 0, then
creates the key with the value.
This operation takes place in a transaction.
:param key: key in etcd to create
:param value: value of the key
:type value: bytes or string
:returns: status of transaction, ``True`` if the create was
successful, ``False`` otherwise
:rtype: bool | [
"Atomically",
"create",
"the",
"given",
"key",
"only",
"if",
"the",
"key",
"doesn",
"t",
"exist",
"."
] | ad566c29cbde135aee20cfd32e0a4815ca3b5ee6 | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/client.py#L129-L163 | train | 43,726 |
dims/etcd3-gateway | etcd3gw/client.py | Etcd3Client.put | def put(self, key, value, lease=None):
"""Put puts the given key into the key-value store.
A put request increments the revision of the key-value store
and generates one event in the event history.
:param key:
:param value:
:param lease:
:return: boolean
"""
payload = {
"key": _encode(key),
"value": _encode(value)
}
if lease:
payload['lease'] = lease.id
self.post(self.get_url("/kv/put"), json=payload)
return True | python | def put(self, key, value, lease=None):
"""Put puts the given key into the key-value store.
A put request increments the revision of the key-value store
and generates one event in the event history.
:param key:
:param value:
:param lease:
:return: boolean
"""
payload = {
"key": _encode(key),
"value": _encode(value)
}
if lease:
payload['lease'] = lease.id
self.post(self.get_url("/kv/put"), json=payload)
return True | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
",",
"lease",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"\"key\"",
":",
"_encode",
"(",
"key",
")",
",",
"\"value\"",
":",
"_encode",
"(",
"value",
")",
"}",
"if",
"lease",
":",
"payload",
"[... | Put puts the given key into the key-value store.
A put request increments the revision of the key-value store
and generates one event in the event history.
:param key:
:param value:
:param lease:
:return: boolean | [
"Put",
"puts",
"the",
"given",
"key",
"into",
"the",
"key",
"-",
"value",
"store",
"."
] | ad566c29cbde135aee20cfd32e0a4815ca3b5ee6 | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/client.py#L165-L183 | train | 43,727 |
dims/etcd3-gateway | etcd3gw/client.py | Etcd3Client.delete | def delete(self, key, **kwargs):
"""DeleteRange deletes the given range from the key-value store.
A delete request increments the revision of the key-value store and
generates a delete event in the event history for every deleted key.
:param key:
:param kwargs:
:return:
"""
payload = {
"key": _encode(key),
}
payload.update(kwargs)
result = self.post(self.get_url("/kv/deleterange"),
json=payload)
if 'deleted' in result:
return True
return False | python | def delete(self, key, **kwargs):
"""DeleteRange deletes the given range from the key-value store.
A delete request increments the revision of the key-value store and
generates a delete event in the event history for every deleted key.
:param key:
:param kwargs:
:return:
"""
payload = {
"key": _encode(key),
}
payload.update(kwargs)
result = self.post(self.get_url("/kv/deleterange"),
json=payload)
if 'deleted' in result:
return True
return False | [
"def",
"delete",
"(",
"self",
",",
"key",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"{",
"\"key\"",
":",
"_encode",
"(",
"key",
")",
",",
"}",
"payload",
".",
"update",
"(",
"kwargs",
")",
"result",
"=",
"self",
".",
"post",
"(",
"self",... | DeleteRange deletes the given range from the key-value store.
A delete request increments the revision of the key-value store and
generates a delete event in the event history for every deleted key.
:param key:
:param kwargs:
:return: | [
"DeleteRange",
"deletes",
"the",
"given",
"range",
"from",
"the",
"key",
"-",
"value",
"store",
"."
] | ad566c29cbde135aee20cfd32e0a4815ca3b5ee6 | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/client.py#L298-L317 | train | 43,728 |
dims/etcd3-gateway | etcd3gw/client.py | Etcd3Client.transaction | def transaction(self, txn):
"""Txn processes multiple requests in a single transaction.
A txn request increments the revision of the key-value store and
generates events with the same revision for every completed request.
It is not allowed to modify the same key several times within one txn.
:param txn:
:return:
"""
return self.post(self.get_url("/kv/txn"),
data=json.dumps(txn)) | python | def transaction(self, txn):
"""Txn processes multiple requests in a single transaction.
A txn request increments the revision of the key-value store and
generates events with the same revision for every completed request.
It is not allowed to modify the same key several times within one txn.
:param txn:
:return:
"""
return self.post(self.get_url("/kv/txn"),
data=json.dumps(txn)) | [
"def",
"transaction",
"(",
"self",
",",
"txn",
")",
":",
"return",
"self",
".",
"post",
"(",
"self",
".",
"get_url",
"(",
"\"/kv/txn\"",
")",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"txn",
")",
")"
] | Txn processes multiple requests in a single transaction.
A txn request increments the revision of the key-value store and
generates events with the same revision for every completed request.
It is not allowed to modify the same key several times within one txn.
:param txn:
:return: | [
"Txn",
"processes",
"multiple",
"requests",
"in",
"a",
"single",
"transaction",
"."
] | ad566c29cbde135aee20cfd32e0a4815ca3b5ee6 | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/client.py#L324-L335 | train | 43,729 |
dims/etcd3-gateway | etcd3gw/client.py | Etcd3Client.watch_prefix | def watch_prefix(self, key_prefix, **kwargs):
"""The same as ``watch``, but watches a range of keys with a prefix."""
kwargs['range_end'] = \
_increment_last_byte(key_prefix)
return self.watch(key_prefix, **kwargs) | python | def watch_prefix(self, key_prefix, **kwargs):
"""The same as ``watch``, but watches a range of keys with a prefix."""
kwargs['range_end'] = \
_increment_last_byte(key_prefix)
return self.watch(key_prefix, **kwargs) | [
"def",
"watch_prefix",
"(",
"self",
",",
"key_prefix",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'range_end'",
"]",
"=",
"_increment_last_byte",
"(",
"key_prefix",
")",
"return",
"self",
".",
"watch",
"(",
"key_prefix",
",",
"*",
"*",
"kwargs",
... | The same as ``watch``, but watches a range of keys with a prefix. | [
"The",
"same",
"as",
"watch",
"but",
"watches",
"a",
"range",
"of",
"keys",
"with",
"a",
"prefix",
"."
] | ad566c29cbde135aee20cfd32e0a4815ca3b5ee6 | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/client.py#L369-L373 | train | 43,730 |
dims/etcd3-gateway | etcd3gw/client.py | Etcd3Client.watch_prefix_once | def watch_prefix_once(self, key_prefix, timeout=None, **kwargs):
"""Watches a range of keys with a prefix, similar to watch_once"""
kwargs['range_end'] = \
_increment_last_byte(key_prefix)
return self.watch_once(key_prefix, timeout=timeout, **kwargs) | python | def watch_prefix_once(self, key_prefix, timeout=None, **kwargs):
"""Watches a range of keys with a prefix, similar to watch_once"""
kwargs['range_end'] = \
_increment_last_byte(key_prefix)
return self.watch_once(key_prefix, timeout=timeout, **kwargs) | [
"def",
"watch_prefix_once",
"(",
"self",
",",
"key_prefix",
",",
"timeout",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'range_end'",
"]",
"=",
"_increment_last_byte",
"(",
"key_prefix",
")",
"return",
"self",
".",
"watch_once",
"(",
"k... | Watches a range of keys with a prefix, similar to watch_once | [
"Watches",
"a",
"range",
"of",
"keys",
"with",
"a",
"prefix",
"similar",
"to",
"watch_once"
] | ad566c29cbde135aee20cfd32e0a4815ca3b5ee6 | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/client.py#L395-L399 | train | 43,731 |
achimnol/aiotools | src/aiotools/timer.py | create_timer | def create_timer(cb: Callable[[float], None], interval: float,
delay_policy: TimerDelayPolicy = TimerDelayPolicy.DEFAULT,
loop: Optional[asyncio.BaseEventLoop] = None) -> asyncio.Task:
'''
Schedule a timer with the given callable and the interval in seconds.
The interval value is also passed to the callable.
If the callable takes longer than the timer interval, all accumulated
callable's tasks will be cancelled when the timer is cancelled.
Args:
cb: TODO - fill argument descriptions
Returns:
You can stop the timer by cancelling the returned task.
'''
if not loop:
loop = asyncio.get_event_loop()
async def _timer():
fired_tasks = []
try:
while True:
if delay_policy == TimerDelayPolicy.CANCEL:
for t in fired_tasks:
if not t.done():
t.cancel()
await t
fired_tasks.clear()
else:
fired_tasks[:] = [t for t in fired_tasks if not t.done()]
t = loop.create_task(cb(interval=interval))
fired_tasks.append(t)
await asyncio.sleep(interval)
except asyncio.CancelledError:
for t in fired_tasks:
t.cancel()
await asyncio.gather(*fired_tasks)
return loop.create_task(_timer()) | python | def create_timer(cb: Callable[[float], None], interval: float,
delay_policy: TimerDelayPolicy = TimerDelayPolicy.DEFAULT,
loop: Optional[asyncio.BaseEventLoop] = None) -> asyncio.Task:
'''
Schedule a timer with the given callable and the interval in seconds.
The interval value is also passed to the callable.
If the callable takes longer than the timer interval, all accumulated
callable's tasks will be cancelled when the timer is cancelled.
Args:
cb: TODO - fill argument descriptions
Returns:
You can stop the timer by cancelling the returned task.
'''
if not loop:
loop = asyncio.get_event_loop()
async def _timer():
fired_tasks = []
try:
while True:
if delay_policy == TimerDelayPolicy.CANCEL:
for t in fired_tasks:
if not t.done():
t.cancel()
await t
fired_tasks.clear()
else:
fired_tasks[:] = [t for t in fired_tasks if not t.done()]
t = loop.create_task(cb(interval=interval))
fired_tasks.append(t)
await asyncio.sleep(interval)
except asyncio.CancelledError:
for t in fired_tasks:
t.cancel()
await asyncio.gather(*fired_tasks)
return loop.create_task(_timer()) | [
"def",
"create_timer",
"(",
"cb",
":",
"Callable",
"[",
"[",
"float",
"]",
",",
"None",
"]",
",",
"interval",
":",
"float",
",",
"delay_policy",
":",
"TimerDelayPolicy",
"=",
"TimerDelayPolicy",
".",
"DEFAULT",
",",
"loop",
":",
"Optional",
"[",
"asyncio",... | Schedule a timer with the given callable and the interval in seconds.
The interval value is also passed to the callable.
If the callable takes longer than the timer interval, all accumulated
callable's tasks will be cancelled when the timer is cancelled.
Args:
cb: TODO - fill argument descriptions
Returns:
You can stop the timer by cancelling the returned task. | [
"Schedule",
"a",
"timer",
"with",
"the",
"given",
"callable",
"and",
"the",
"interval",
"in",
"seconds",
".",
"The",
"interval",
"value",
"is",
"also",
"passed",
"to",
"the",
"callable",
".",
"If",
"the",
"callable",
"takes",
"longer",
"than",
"the",
"time... | 9efc66a01fbd287f70ee3a937203d466aac4a765 | https://github.com/achimnol/aiotools/blob/9efc66a01fbd287f70ee3a937203d466aac4a765/src/aiotools/timer.py#L21-L59 | train | 43,732 |
dims/etcd3-gateway | etcd3gw/lease.py | Lease.revoke | def revoke(self):
"""LeaseRevoke revokes a lease.
All keys attached to the lease will expire and be deleted.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
:return:
"""
self.client.post(self.client.get_url("/kv/lease/revoke"),
json={"ID": self.id})
return True | python | def revoke(self):
"""LeaseRevoke revokes a lease.
All keys attached to the lease will expire and be deleted.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
:return:
"""
self.client.post(self.client.get_url("/kv/lease/revoke"),
json={"ID": self.id})
return True | [
"def",
"revoke",
"(",
"self",
")",
":",
"self",
".",
"client",
".",
"post",
"(",
"self",
".",
"client",
".",
"get_url",
"(",
"\"/kv/lease/revoke\"",
")",
",",
"json",
"=",
"{",
"\"ID\"",
":",
"self",
".",
"id",
"}",
")",
"return",
"True"
] | LeaseRevoke revokes a lease.
All keys attached to the lease will expire and be deleted.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
:return: | [
"LeaseRevoke",
"revokes",
"a",
"lease",
"."
] | ad566c29cbde135aee20cfd32e0a4815ca3b5ee6 | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/lease.py#L26-L38 | train | 43,733 |
dims/etcd3-gateway | etcd3gw/lease.py | Lease.ttl | def ttl(self):
"""LeaseTimeToLive retrieves lease information.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
:return:
"""
result = self.client.post(self.client.get_url("/kv/lease/timetolive"),
json={"ID": self.id})
return int(result['TTL']) | python | def ttl(self):
"""LeaseTimeToLive retrieves lease information.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
:return:
"""
result = self.client.post(self.client.get_url("/kv/lease/timetolive"),
json={"ID": self.id})
return int(result['TTL']) | [
"def",
"ttl",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"client",
".",
"post",
"(",
"self",
".",
"client",
".",
"get_url",
"(",
"\"/kv/lease/timetolive\"",
")",
",",
"json",
"=",
"{",
"\"ID\"",
":",
"self",
".",
"id",
"}",
")",
"return",
"... | LeaseTimeToLive retrieves lease information.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
:return: | [
"LeaseTimeToLive",
"retrieves",
"lease",
"information",
"."
] | ad566c29cbde135aee20cfd32e0a4815ca3b5ee6 | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/lease.py#L40-L51 | train | 43,734 |
dims/etcd3-gateway | etcd3gw/lease.py | Lease.keys | def keys(self):
"""Get the keys associated with this lease.
:return:
"""
result = self.client.post(self.client.get_url("/kv/lease/timetolive"),
json={"ID": self.id,
"keys": True})
keys = result['keys'] if 'keys' in result else []
return [_decode(key) for key in keys] | python | def keys(self):
"""Get the keys associated with this lease.
:return:
"""
result = self.client.post(self.client.get_url("/kv/lease/timetolive"),
json={"ID": self.id,
"keys": True})
keys = result['keys'] if 'keys' in result else []
return [_decode(key) for key in keys] | [
"def",
"keys",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"client",
".",
"post",
"(",
"self",
".",
"client",
".",
"get_url",
"(",
"\"/kv/lease/timetolive\"",
")",
",",
"json",
"=",
"{",
"\"ID\"",
":",
"self",
".",
"id",
",",
"\"keys\"",
":",
... | Get the keys associated with this lease.
:return: | [
"Get",
"the",
"keys",
"associated",
"with",
"this",
"lease",
"."
] | ad566c29cbde135aee20cfd32e0a4815ca3b5ee6 | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/lease.py#L66-L75 | train | 43,735 |
embedly/embedly-python | embedly/client.py | Embedly.get_services | def get_services(self):
"""
get_services makes call to services end point of api.embed.ly to fetch
the list of supported providers and their regexes
"""
if self.services:
return self.services
url = 'http://api.embed.ly/1/services/python'
http = httplib2.Http(timeout=self.timeout)
headers = {'User-Agent': self.user_agent,
'Connection': 'close'}
resp, content = http.request(url, headers=headers)
if resp['status'] == '200':
resp_data = json.loads(content.decode('utf-8'))
self.services = resp_data
# build the regex that we can use later
_regex = []
for each in self.services:
_regex.append('|'.join(each.get('regex', [])))
self._regex = re.compile('|'.join(_regex))
return self.services | python | def get_services(self):
"""
get_services makes call to services end point of api.embed.ly to fetch
the list of supported providers and their regexes
"""
if self.services:
return self.services
url = 'http://api.embed.ly/1/services/python'
http = httplib2.Http(timeout=self.timeout)
headers = {'User-Agent': self.user_agent,
'Connection': 'close'}
resp, content = http.request(url, headers=headers)
if resp['status'] == '200':
resp_data = json.loads(content.decode('utf-8'))
self.services = resp_data
# build the regex that we can use later
_regex = []
for each in self.services:
_regex.append('|'.join(each.get('regex', [])))
self._regex = re.compile('|'.join(_regex))
return self.services | [
"def",
"get_services",
"(",
"self",
")",
":",
"if",
"self",
".",
"services",
":",
"return",
"self",
".",
"services",
"url",
"=",
"'http://api.embed.ly/1/services/python'",
"http",
"=",
"httplib2",
".",
"Http",
"(",
"timeout",
"=",
"self",
".",
"timeout",
")"... | get_services makes call to services end point of api.embed.ly to fetch
the list of supported providers and their regexes | [
"get_services",
"makes",
"call",
"to",
"services",
"end",
"point",
"of",
"api",
".",
"embed",
".",
"ly",
"to",
"fetch",
"the",
"list",
"of",
"supported",
"providers",
"and",
"their",
"regexes"
] | 314d74989411c1dd690cd004377f9108d0d1feb1 | https://github.com/embedly/embedly-python/blob/314d74989411c1dd690cd004377f9108d0d1feb1/embedly/client.py#L46-L73 | train | 43,736 |
embedly/embedly-python | embedly/client.py | Embedly._get | def _get(self, version, method, url_or_urls, **kwargs):
"""
_get makes the actual call to api.embed.ly
"""
if not url_or_urls:
raise ValueError('%s requires a url or a list of urls given: %s' %
(method.title(), url_or_urls))
# a flag we can use instead of calling isinstance() all the time
multi = isinstance(url_or_urls, list)
# throw an error early for too many URLs
if multi and len(url_or_urls) > 20:
raise ValueError('Embedly accepts only 20 urls at a time. Url '
'Count:%s' % len(url_or_urls))
query = ''
key = kwargs.get('key', self.key)
# make sure that a key was set on the client or passed in
if not key:
raise ValueError('Requires a key. None given: %s' % key)
kwargs['key'] = key
query += urlencode(kwargs)
if multi:
query += '&urls=%s&' % ','.join([quote(url) for url in url_or_urls])
else:
query += '&url=%s' % quote(url_or_urls)
url = 'http://api.embed.ly/%s/%s?%s' % (version, method, query)
http = httplib2.Http(timeout=self.timeout)
headers = {'User-Agent': self.user_agent,
'Connection': 'close'}
resp, content = http.request(url, headers=headers)
if resp['status'] == '200':
data = json.loads(content.decode('utf-8'))
if kwargs.get('raw', False):
data['raw'] = content
else:
data = {'type': 'error',
'error': True,
'error_code': int(resp['status'])}
if multi:
return map(lambda url, data: Url(data, method, url),
url_or_urls, data)
return Url(data, method, url_or_urls) | python | def _get(self, version, method, url_or_urls, **kwargs):
"""
_get makes the actual call to api.embed.ly
"""
if not url_or_urls:
raise ValueError('%s requires a url or a list of urls given: %s' %
(method.title(), url_or_urls))
# a flag we can use instead of calling isinstance() all the time
multi = isinstance(url_or_urls, list)
# throw an error early for too many URLs
if multi and len(url_or_urls) > 20:
raise ValueError('Embedly accepts only 20 urls at a time. Url '
'Count:%s' % len(url_or_urls))
query = ''
key = kwargs.get('key', self.key)
# make sure that a key was set on the client or passed in
if not key:
raise ValueError('Requires a key. None given: %s' % key)
kwargs['key'] = key
query += urlencode(kwargs)
if multi:
query += '&urls=%s&' % ','.join([quote(url) for url in url_or_urls])
else:
query += '&url=%s' % quote(url_or_urls)
url = 'http://api.embed.ly/%s/%s?%s' % (version, method, query)
http = httplib2.Http(timeout=self.timeout)
headers = {'User-Agent': self.user_agent,
'Connection': 'close'}
resp, content = http.request(url, headers=headers)
if resp['status'] == '200':
data = json.loads(content.decode('utf-8'))
if kwargs.get('raw', False):
data['raw'] = content
else:
data = {'type': 'error',
'error': True,
'error_code': int(resp['status'])}
if multi:
return map(lambda url, data: Url(data, method, url),
url_or_urls, data)
return Url(data, method, url_or_urls) | [
"def",
"_get",
"(",
"self",
",",
"version",
",",
"method",
",",
"url_or_urls",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"url_or_urls",
":",
"raise",
"ValueError",
"(",
"'%s requires a url or a list of urls given: %s'",
"%",
"(",
"method",
".",
"title",
... | _get makes the actual call to api.embed.ly | [
"_get",
"makes",
"the",
"actual",
"call",
"to",
"api",
".",
"embed",
".",
"ly"
] | 314d74989411c1dd690cd004377f9108d0d1feb1 | https://github.com/embedly/embedly-python/blob/314d74989411c1dd690cd004377f9108d0d1feb1/embedly/client.py#L92-L148 | train | 43,737 |
dims/etcd3-gateway | etcd3gw/utils.py | _encode | def _encode(data):
"""Encode the given data using base-64
:param data:
:return: base-64 encoded string
"""
if not isinstance(data, bytes_types):
data = six.b(str(data))
return base64.b64encode(data).decode("utf-8") | python | def _encode(data):
"""Encode the given data using base-64
:param data:
:return: base-64 encoded string
"""
if not isinstance(data, bytes_types):
data = six.b(str(data))
return base64.b64encode(data).decode("utf-8") | [
"def",
"_encode",
"(",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"bytes_types",
")",
":",
"data",
"=",
"six",
".",
"b",
"(",
"str",
"(",
"data",
")",
")",
"return",
"base64",
".",
"b64encode",
"(",
"data",
")",
".",
"decode",
... | Encode the given data using base-64
:param data:
:return: base-64 encoded string | [
"Encode",
"the",
"given",
"data",
"using",
"base",
"-",
"64"
] | ad566c29cbde135aee20cfd32e0a4815ca3b5ee6 | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/utils.py#L22-L30 | train | 43,738 |
dims/etcd3-gateway | etcd3gw/utils.py | _decode | def _decode(data):
"""Decode the base-64 encoded string
:param data:
:return: decoded data
"""
if not isinstance(data, bytes_types):
data = six.b(str(data))
return base64.b64decode(data.decode("utf-8")) | python | def _decode(data):
"""Decode the base-64 encoded string
:param data:
:return: decoded data
"""
if not isinstance(data, bytes_types):
data = six.b(str(data))
return base64.b64decode(data.decode("utf-8")) | [
"def",
"_decode",
"(",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"bytes_types",
")",
":",
"data",
"=",
"six",
".",
"b",
"(",
"str",
"(",
"data",
")",
")",
"return",
"base64",
".",
"b64decode",
"(",
"data",
".",
"decode",
"(",
... | Decode the base-64 encoded string
:param data:
:return: decoded data | [
"Decode",
"the",
"base",
"-",
"64",
"encoded",
"string"
] | ad566c29cbde135aee20cfd32e0a4815ca3b5ee6 | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/utils.py#L33-L41 | train | 43,739 |
dims/etcd3-gateway | etcd3gw/utils.py | _increment_last_byte | def _increment_last_byte(data):
"""Get the last byte in the array and increment it
:param bytes_string:
:return:
"""
if not isinstance(data, bytes_types):
if isinstance(data, six.string_types):
data = data.encode('utf-8')
else:
data = six.b(str(data))
s = bytearray(data)
s[-1] = s[-1] + 1
return bytes(s) | python | def _increment_last_byte(data):
"""Get the last byte in the array and increment it
:param bytes_string:
:return:
"""
if not isinstance(data, bytes_types):
if isinstance(data, six.string_types):
data = data.encode('utf-8')
else:
data = six.b(str(data))
s = bytearray(data)
s[-1] = s[-1] + 1
return bytes(s) | [
"def",
"_increment_last_byte",
"(",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"bytes_types",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"string_types",
")",
":",
"data",
"=",
"data",
".",
"encode",
"(",
"'utf-8'",
... | Get the last byte in the array and increment it
:param bytes_string:
:return: | [
"Get",
"the",
"last",
"byte",
"in",
"the",
"array",
"and",
"increment",
"it"
] | ad566c29cbde135aee20cfd32e0a4815ca3b5ee6 | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/utils.py#L44-L57 | train | 43,740 |
rackerlabs/fastfood | fastfood/book.py | CookBook.metadata | def metadata(self):
"""Return dict representation of this cookbook's metadata.rb ."""
self.metadata_path = os.path.join(self.path, 'metadata.rb')
if not os.path.isfile(self.metadata_path):
raise ValueError("Cookbook needs metadata.rb, %s"
% self.metadata_path)
if not self._metadata:
self._metadata = MetadataRb(open(self.metadata_path, 'r+'))
return self._metadata | python | def metadata(self):
"""Return dict representation of this cookbook's metadata.rb ."""
self.metadata_path = os.path.join(self.path, 'metadata.rb')
if not os.path.isfile(self.metadata_path):
raise ValueError("Cookbook needs metadata.rb, %s"
% self.metadata_path)
if not self._metadata:
self._metadata = MetadataRb(open(self.metadata_path, 'r+'))
return self._metadata | [
"def",
"metadata",
"(",
"self",
")",
":",
"self",
".",
"metadata_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"'metadata.rb'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"metadata_path",
")",
... | Return dict representation of this cookbook's metadata.rb . | [
"Return",
"dict",
"representation",
"of",
"this",
"cookbook",
"s",
"metadata",
".",
"rb",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/book.py#L49-L59 | train | 43,741 |
rackerlabs/fastfood | fastfood/book.py | CookBook.berksfile | def berksfile(self):
"""Return this cookbook's Berksfile instance."""
self.berks_path = os.path.join(self.path, 'Berksfile')
if not self._berksfile:
if not os.path.isfile(self.berks_path):
raise ValueError("No Berksfile found at %s"
% self.berks_path)
self._berksfile = Berksfile(open(self.berks_path, 'r+'))
return self._berksfile | python | def berksfile(self):
"""Return this cookbook's Berksfile instance."""
self.berks_path = os.path.join(self.path, 'Berksfile')
if not self._berksfile:
if not os.path.isfile(self.berks_path):
raise ValueError("No Berksfile found at %s"
% self.berks_path)
self._berksfile = Berksfile(open(self.berks_path, 'r+'))
return self._berksfile | [
"def",
"berksfile",
"(",
"self",
")",
":",
"self",
".",
"berks_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"'Berksfile'",
")",
"if",
"not",
"self",
".",
"_berksfile",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile"... | Return this cookbook's Berksfile instance. | [
"Return",
"this",
"cookbook",
"s",
"Berksfile",
"instance",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/book.py#L62-L70 | train | 43,742 |
rackerlabs/fastfood | fastfood/book.py | MetadataRb.from_dict | def from_dict(cls, dictionary):
"""Create a MetadataRb instance from a dict."""
cookbooks = set()
# put these in order
groups = [cookbooks]
for key, val in dictionary.items():
if key == 'depends':
cookbooks.update({cls.depends_statement(cbn, meta)
for cbn, meta in val.items()})
body = ''
for group in groups:
if group:
body += '\n'
body += '\n'.join(group)
return cls.from_string(body) | python | def from_dict(cls, dictionary):
"""Create a MetadataRb instance from a dict."""
cookbooks = set()
# put these in order
groups = [cookbooks]
for key, val in dictionary.items():
if key == 'depends':
cookbooks.update({cls.depends_statement(cbn, meta)
for cbn, meta in val.items()})
body = ''
for group in groups:
if group:
body += '\n'
body += '\n'.join(group)
return cls.from_string(body) | [
"def",
"from_dict",
"(",
"cls",
",",
"dictionary",
")",
":",
"cookbooks",
"=",
"set",
"(",
")",
"# put these in order",
"groups",
"=",
"[",
"cookbooks",
"]",
"for",
"key",
",",
"val",
"in",
"dictionary",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
... | Create a MetadataRb instance from a dict. | [
"Create",
"a",
"MetadataRb",
"instance",
"from",
"a",
"dict",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/book.py#L78-L94 | train | 43,743 |
rackerlabs/fastfood | fastfood/book.py | MetadataRb.depends_statement | def depends_statement(cookbook_name, metadata=None):
"""Return a valid Ruby 'depends' statement for the metadata.rb file."""
line = "depends '%s'" % cookbook_name
if metadata:
if not isinstance(metadata, dict):
raise TypeError("Stencil dependency options for %s "
"should be a dict of options, not %s."
% (cookbook_name, metadata))
if metadata:
line = "%s '%s'" % (line, "', '".join(metadata))
return line | python | def depends_statement(cookbook_name, metadata=None):
"""Return a valid Ruby 'depends' statement for the metadata.rb file."""
line = "depends '%s'" % cookbook_name
if metadata:
if not isinstance(metadata, dict):
raise TypeError("Stencil dependency options for %s "
"should be a dict of options, not %s."
% (cookbook_name, metadata))
if metadata:
line = "%s '%s'" % (line, "', '".join(metadata))
return line | [
"def",
"depends_statement",
"(",
"cookbook_name",
",",
"metadata",
"=",
"None",
")",
":",
"line",
"=",
"\"depends '%s'\"",
"%",
"cookbook_name",
"if",
"metadata",
":",
"if",
"not",
"isinstance",
"(",
"metadata",
",",
"dict",
")",
":",
"raise",
"TypeError",
"... | Return a valid Ruby 'depends' statement for the metadata.rb file. | [
"Return",
"a",
"valid",
"Ruby",
"depends",
"statement",
"for",
"the",
"metadata",
".",
"rb",
"file",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/book.py#L97-L107 | train | 43,744 |
rackerlabs/fastfood | fastfood/book.py | MetadataRb.parse | def parse(self):
"""Parse the metadata.rb into a dict."""
data = utils.ruby_lines(self.readlines())
data = [tuple(j.strip() for j in line.split(None, 1))
for line in data]
depends = {}
for line in data:
if not len(line) == 2:
continue
key, value = line
if key == 'depends':
value = value.split(',')
lib = utils.ruby_strip(value[0])
detail = [utils.ruby_strip(j) for j in value[1:]]
depends[lib] = detail
datamap = {key: utils.ruby_strip(val) for key, val in data}
if depends:
datamap['depends'] = depends
self.seek(0)
return datamap | python | def parse(self):
"""Parse the metadata.rb into a dict."""
data = utils.ruby_lines(self.readlines())
data = [tuple(j.strip() for j in line.split(None, 1))
for line in data]
depends = {}
for line in data:
if not len(line) == 2:
continue
key, value = line
if key == 'depends':
value = value.split(',')
lib = utils.ruby_strip(value[0])
detail = [utils.ruby_strip(j) for j in value[1:]]
depends[lib] = detail
datamap = {key: utils.ruby_strip(val) for key, val in data}
if depends:
datamap['depends'] = depends
self.seek(0)
return datamap | [
"def",
"parse",
"(",
"self",
")",
":",
"data",
"=",
"utils",
".",
"ruby_lines",
"(",
"self",
".",
"readlines",
"(",
")",
")",
"data",
"=",
"[",
"tuple",
"(",
"j",
".",
"strip",
"(",
")",
"for",
"j",
"in",
"line",
".",
"split",
"(",
"None",
",",... | Parse the metadata.rb into a dict. | [
"Parse",
"the",
"metadata",
".",
"rb",
"into",
"a",
"dict",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/book.py#L113-L132 | train | 43,745 |
rackerlabs/fastfood | fastfood/book.py | MetadataRb.merge | def merge(self, other):
"""Add requirements from 'other' metadata.rb into this one."""
if not isinstance(other, MetadataRb):
raise TypeError("MetadataRb to merge should be a 'MetadataRb' "
"instance, not %s.", type(other))
current = self.to_dict()
new = other.to_dict()
# compare and gather cookbook dependencies
meta_writelines = ['%s\n' % self.depends_statement(cbn, meta)
for cbn, meta in new.get('depends', {}).items()
if cbn not in current.get('depends', {})]
self.write_statements(meta_writelines)
return self.to_dict() | python | def merge(self, other):
"""Add requirements from 'other' metadata.rb into this one."""
if not isinstance(other, MetadataRb):
raise TypeError("MetadataRb to merge should be a 'MetadataRb' "
"instance, not %s.", type(other))
current = self.to_dict()
new = other.to_dict()
# compare and gather cookbook dependencies
meta_writelines = ['%s\n' % self.depends_statement(cbn, meta)
for cbn, meta in new.get('depends', {}).items()
if cbn not in current.get('depends', {})]
self.write_statements(meta_writelines)
return self.to_dict() | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"MetadataRb",
")",
":",
"raise",
"TypeError",
"(",
"\"MetadataRb to merge should be a 'MetadataRb' \"",
"\"instance, not %s.\"",
",",
"type",
"(",
"other",
")",
")... | Add requirements from 'other' metadata.rb into this one. | [
"Add",
"requirements",
"from",
"other",
"metadata",
".",
"rb",
"into",
"this",
"one",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/book.py#L134-L148 | train | 43,746 |
rackerlabs/fastfood | fastfood/book.py | Berksfile.parse | def parse(self):
"""Parse this Berksfile into a dict."""
self.flush()
self.seek(0)
data = utils.ruby_lines(self.readlines())
data = [tuple(j.strip() for j in line.split(None, 1))
for line in data]
datamap = {}
for line in data:
if len(line) == 1:
datamap[line[0]] = True
elif len(line) == 2:
key, value = line
if key == 'cookbook':
datamap.setdefault('cookbook', {})
value = [utils.ruby_strip(v) for v in value.split(',')]
lib, detail = value[0], value[1:]
datamap['cookbook'].setdefault(lib, {})
# if there is additional dependency data but its
# not the ruby hash, its the version constraint
if detail and not any("".join(detail).startswith(o)
for o in self.berks_options):
constraint, detail = detail[0], detail[1:]
datamap['cookbook'][lib]['constraint'] = constraint
if detail:
for deet in detail:
opt, val = [
utils.ruby_strip(i)
for i in deet.split(':', 1)
]
if not any(opt == o for o in self.berks_options):
raise ValueError(
"Cookbook detail '%s' does not specify "
"one of '%s'" % (opt, self.berks_options))
else:
datamap['cookbook'][lib][opt.strip(':')] = (
utils.ruby_strip(val))
elif key == 'source':
datamap.setdefault(key, [])
datamap[key].append(utils.ruby_strip(value))
elif key:
datamap[key] = utils.ruby_strip(value)
self.seek(0)
return datamap | python | def parse(self):
"""Parse this Berksfile into a dict."""
self.flush()
self.seek(0)
data = utils.ruby_lines(self.readlines())
data = [tuple(j.strip() for j in line.split(None, 1))
for line in data]
datamap = {}
for line in data:
if len(line) == 1:
datamap[line[0]] = True
elif len(line) == 2:
key, value = line
if key == 'cookbook':
datamap.setdefault('cookbook', {})
value = [utils.ruby_strip(v) for v in value.split(',')]
lib, detail = value[0], value[1:]
datamap['cookbook'].setdefault(lib, {})
# if there is additional dependency data but its
# not the ruby hash, its the version constraint
if detail and not any("".join(detail).startswith(o)
for o in self.berks_options):
constraint, detail = detail[0], detail[1:]
datamap['cookbook'][lib]['constraint'] = constraint
if detail:
for deet in detail:
opt, val = [
utils.ruby_strip(i)
for i in deet.split(':', 1)
]
if not any(opt == o for o in self.berks_options):
raise ValueError(
"Cookbook detail '%s' does not specify "
"one of '%s'" % (opt, self.berks_options))
else:
datamap['cookbook'][lib][opt.strip(':')] = (
utils.ruby_strip(val))
elif key == 'source':
datamap.setdefault(key, [])
datamap[key].append(utils.ruby_strip(value))
elif key:
datamap[key] = utils.ruby_strip(value)
self.seek(0)
return datamap | [
"def",
"parse",
"(",
"self",
")",
":",
"self",
".",
"flush",
"(",
")",
"self",
".",
"seek",
"(",
"0",
")",
"data",
"=",
"utils",
".",
"ruby_lines",
"(",
"self",
".",
"readlines",
"(",
")",
")",
"data",
"=",
"[",
"tuple",
"(",
"j",
".",
"strip",... | Parse this Berksfile into a dict. | [
"Parse",
"this",
"Berksfile",
"into",
"a",
"dict",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/book.py#L168-L211 | train | 43,747 |
rackerlabs/fastfood | fastfood/book.py | Berksfile.from_dict | def from_dict(cls, dictionary):
"""Create a Berksfile instance from a dict."""
cookbooks = set()
sources = set()
other = set()
# put these in order
groups = [sources, cookbooks, other]
for key, val in dictionary.items():
if key == 'cookbook':
cookbooks.update({cls.cookbook_statement(cbn, meta)
for cbn, meta in val.items()})
elif key == 'source':
sources.update({"source '%s'" % src for src in val})
elif key == 'metadata':
other.add('metadata')
body = ''
for group in groups:
if group:
body += '\n'
body += '\n'.join(group)
return cls.from_string(body) | python | def from_dict(cls, dictionary):
"""Create a Berksfile instance from a dict."""
cookbooks = set()
sources = set()
other = set()
# put these in order
groups = [sources, cookbooks, other]
for key, val in dictionary.items():
if key == 'cookbook':
cookbooks.update({cls.cookbook_statement(cbn, meta)
for cbn, meta in val.items()})
elif key == 'source':
sources.update({"source '%s'" % src for src in val})
elif key == 'metadata':
other.add('metadata')
body = ''
for group in groups:
if group:
body += '\n'
body += '\n'.join(group)
return cls.from_string(body) | [
"def",
"from_dict",
"(",
"cls",
",",
"dictionary",
")",
":",
"cookbooks",
"=",
"set",
"(",
")",
"sources",
"=",
"set",
"(",
")",
"other",
"=",
"set",
"(",
")",
"# put these in order",
"groups",
"=",
"[",
"sources",
",",
"cookbooks",
",",
"other",
"]",
... | Create a Berksfile instance from a dict. | [
"Create",
"a",
"Berksfile",
"instance",
"from",
"a",
"dict",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/book.py#L214-L236 | train | 43,748 |
rackerlabs/fastfood | fastfood/book.py | Berksfile.cookbook_statement | def cookbook_statement(cookbook_name, metadata=None):
"""Return a valid Ruby 'cookbook' statement for the Berksfile."""
line = "cookbook '%s'" % cookbook_name
if metadata:
if not isinstance(metadata, dict):
raise TypeError("Berksfile dependency hash for %s "
"should be a dict of options, not %s."
% (cookbook_name, metadata))
# not like the others...
if 'constraint' in metadata:
line += ", '%s'" % metadata.pop('constraint')
for opt, spec in metadata.items():
line += ", %s: '%s'" % (opt, spec)
return line | python | def cookbook_statement(cookbook_name, metadata=None):
"""Return a valid Ruby 'cookbook' statement for the Berksfile."""
line = "cookbook '%s'" % cookbook_name
if metadata:
if not isinstance(metadata, dict):
raise TypeError("Berksfile dependency hash for %s "
"should be a dict of options, not %s."
% (cookbook_name, metadata))
# not like the others...
if 'constraint' in metadata:
line += ", '%s'" % metadata.pop('constraint')
for opt, spec in metadata.items():
line += ", %s: '%s'" % (opt, spec)
return line | [
"def",
"cookbook_statement",
"(",
"cookbook_name",
",",
"metadata",
"=",
"None",
")",
":",
"line",
"=",
"\"cookbook '%s'\"",
"%",
"cookbook_name",
"if",
"metadata",
":",
"if",
"not",
"isinstance",
"(",
"metadata",
",",
"dict",
")",
":",
"raise",
"TypeError",
... | Return a valid Ruby 'cookbook' statement for the Berksfile. | [
"Return",
"a",
"valid",
"Ruby",
"cookbook",
"statement",
"for",
"the",
"Berksfile",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/book.py#L239-L252 | train | 43,749 |
rackerlabs/fastfood | fastfood/book.py | Berksfile.merge | def merge(self, other):
"""Add requirements from 'other' Berksfile into this one."""
if not isinstance(other, Berksfile):
raise TypeError("Berksfile to merge should be a 'Berksfile' "
"instance, not %s.", type(other))
current = self.to_dict()
new = other.to_dict()
# compare and gather cookbook dependencies
berks_writelines = ['%s\n' % self.cookbook_statement(cbn, meta)
for cbn, meta in new.get('cookbook', {}).items()
if cbn not in current.get('cookbook', {})]
# compare and gather 'source' requirements
berks_writelines.extend(["source '%s'\n" % src for src
in new.get('source', [])
if src not in current.get('source', [])])
self.write_statements(berks_writelines)
return self.to_dict() | python | def merge(self, other):
"""Add requirements from 'other' Berksfile into this one."""
if not isinstance(other, Berksfile):
raise TypeError("Berksfile to merge should be a 'Berksfile' "
"instance, not %s.", type(other))
current = self.to_dict()
new = other.to_dict()
# compare and gather cookbook dependencies
berks_writelines = ['%s\n' % self.cookbook_statement(cbn, meta)
for cbn, meta in new.get('cookbook', {}).items()
if cbn not in current.get('cookbook', {})]
# compare and gather 'source' requirements
berks_writelines.extend(["source '%s'\n" % src for src
in new.get('source', [])
if src not in current.get('source', [])])
self.write_statements(berks_writelines)
return self.to_dict() | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"Berksfile",
")",
":",
"raise",
"TypeError",
"(",
"\"Berksfile to merge should be a 'Berksfile' \"",
"\"instance, not %s.\"",
",",
"type",
"(",
"other",
")",
")",
... | Add requirements from 'other' Berksfile into this one. | [
"Add",
"requirements",
"from",
"other",
"Berksfile",
"into",
"this",
"one",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/book.py#L254-L273 | train | 43,750 |
rackerlabs/fastfood | fastfood/stencil.py | StencilSet.manifest | def manifest(self):
"""The manifest definition of the stencilset as a dict."""
if not self._manifest:
with open(self.manifest_path) as man:
self._manifest = json.load(man)
return self._manifest | python | def manifest(self):
"""The manifest definition of the stencilset as a dict."""
if not self._manifest:
with open(self.manifest_path) as man:
self._manifest = json.load(man)
return self._manifest | [
"def",
"manifest",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_manifest",
":",
"with",
"open",
"(",
"self",
".",
"manifest_path",
")",
"as",
"man",
":",
"self",
".",
"_manifest",
"=",
"json",
".",
"load",
"(",
"man",
")",
"return",
"self",
"... | The manifest definition of the stencilset as a dict. | [
"The",
"manifest",
"definition",
"of",
"the",
"stencilset",
"as",
"a",
"dict",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/stencil.py#L69-L74 | train | 43,751 |
rackerlabs/fastfood | fastfood/stencil.py | StencilSet.stencils | def stencils(self):
"""List of stencils."""
if not self._stencils:
self._stencils = self.manifest['stencils']
return self._stencils | python | def stencils(self):
"""List of stencils."""
if not self._stencils:
self._stencils = self.manifest['stencils']
return self._stencils | [
"def",
"stencils",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_stencils",
":",
"self",
".",
"_stencils",
"=",
"self",
".",
"manifest",
"[",
"'stencils'",
"]",
"return",
"self",
".",
"_stencils"
] | List of stencils. | [
"List",
"of",
"stencils",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/stencil.py#L77-L81 | train | 43,752 |
rackerlabs/fastfood | fastfood/stencil.py | StencilSet.get_stencil | def get_stencil(self, stencil_name, **options):
"""Return a Stencil instance given a stencil name."""
if stencil_name not in self.manifest.get('stencils', {}):
raise ValueError("Stencil '%s' not declared in StencilSet "
"manifest." % stencil_name)
stencil = copy.deepcopy(self.manifest)
allstencils = stencil.pop('stencils')
stencil.pop('default_stencil', None)
override = allstencils[stencil_name]
utils.deepupdate(stencil, override)
# merge options, prefer **options (probably user-supplied)
for opt, data in stencil.get('options', {}).items():
if opt not in options:
options[opt] = data.get('default', '')
stencil['options'] = options
name = stencil['options'].get('name')
files = stencil['files'].copy()
for fil, templ in files.items():
if '<NAME>' in fil:
# check for the option b/c there are
# cases in which it may not exist
if not name:
raise ValueError("Stencil does not include a name option")
stencil['files'].pop(fil)
fil = fil.replace('<NAME>', name)
stencil['files'][fil] = templ
return stencil | python | def get_stencil(self, stencil_name, **options):
"""Return a Stencil instance given a stencil name."""
if stencil_name not in self.manifest.get('stencils', {}):
raise ValueError("Stencil '%s' not declared in StencilSet "
"manifest." % stencil_name)
stencil = copy.deepcopy(self.manifest)
allstencils = stencil.pop('stencils')
stencil.pop('default_stencil', None)
override = allstencils[stencil_name]
utils.deepupdate(stencil, override)
# merge options, prefer **options (probably user-supplied)
for opt, data in stencil.get('options', {}).items():
if opt not in options:
options[opt] = data.get('default', '')
stencil['options'] = options
name = stencil['options'].get('name')
files = stencil['files'].copy()
for fil, templ in files.items():
if '<NAME>' in fil:
# check for the option b/c there are
# cases in which it may not exist
if not name:
raise ValueError("Stencil does not include a name option")
stencil['files'].pop(fil)
fil = fil.replace('<NAME>', name)
stencil['files'][fil] = templ
return stencil | [
"def",
"get_stencil",
"(",
"self",
",",
"stencil_name",
",",
"*",
"*",
"options",
")",
":",
"if",
"stencil_name",
"not",
"in",
"self",
".",
"manifest",
".",
"get",
"(",
"'stencils'",
",",
"{",
"}",
")",
":",
"raise",
"ValueError",
"(",
"\"Stencil '%s' no... | Return a Stencil instance given a stencil name. | [
"Return",
"a",
"Stencil",
"instance",
"given",
"a",
"stencil",
"name",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/stencil.py#L83-L113 | train | 43,753 |
rackerlabs/fastfood | fastfood/food.py | _determine_selected_stencil | def _determine_selected_stencil(stencil_set, stencil_definition):
"""Determine appropriate stencil name for stencil definition.
Given a fastfood.json stencil definition with a stencil set, figure out
what the name of the stencil within the set should be, or use the default
"""
if 'stencil' not in stencil_definition:
selected_stencil_name = stencil_set.manifest.get('default_stencil')
else:
selected_stencil_name = stencil_definition.get('stencil')
if not selected_stencil_name:
raise ValueError("No stencil name, within stencil set %s, specified."
% stencil_definition['name'])
return selected_stencil_name | python | def _determine_selected_stencil(stencil_set, stencil_definition):
"""Determine appropriate stencil name for stencil definition.
Given a fastfood.json stencil definition with a stencil set, figure out
what the name of the stencil within the set should be, or use the default
"""
if 'stencil' not in stencil_definition:
selected_stencil_name = stencil_set.manifest.get('default_stencil')
else:
selected_stencil_name = stencil_definition.get('stencil')
if not selected_stencil_name:
raise ValueError("No stencil name, within stencil set %s, specified."
% stencil_definition['name'])
return selected_stencil_name | [
"def",
"_determine_selected_stencil",
"(",
"stencil_set",
",",
"stencil_definition",
")",
":",
"if",
"'stencil'",
"not",
"in",
"stencil_definition",
":",
"selected_stencil_name",
"=",
"stencil_set",
".",
"manifest",
".",
"get",
"(",
"'default_stencil'",
")",
"else",
... | Determine appropriate stencil name for stencil definition.
Given a fastfood.json stencil definition with a stencil set, figure out
what the name of the stencil within the set should be, or use the default | [
"Determine",
"appropriate",
"stencil",
"name",
"for",
"stencil",
"definition",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/food.py#L35-L50 | train | 43,754 |
rackerlabs/fastfood | fastfood/food.py | _build_template_map | def _build_template_map(cookbook, cookbook_name, stencil):
"""Build a map of variables for this generated cookbook and stencil.
Get template variables from stencil option values, adding the default ones
like cookbook and cookbook year.
"""
template_map = {
'cookbook': {"name": cookbook_name},
'options': stencil['options']
}
# Cookbooks may not yet have metadata, so we pass an empty dict if so
try:
template_map['cookbook'] = cookbook.metadata.to_dict().copy()
except ValueError:
# ValueError may be returned if this cookbook does not yet have any
# metadata.rb written by a stencil. This is okay, as everyone should
# be using the base stencil first, and then we'll try to call
# cookbook.metadata again in this method later down.
pass
template_map['cookbook']['year'] = datetime.datetime.now().year
return template_map | python | def _build_template_map(cookbook, cookbook_name, stencil):
"""Build a map of variables for this generated cookbook and stencil.
Get template variables from stencil option values, adding the default ones
like cookbook and cookbook year.
"""
template_map = {
'cookbook': {"name": cookbook_name},
'options': stencil['options']
}
# Cookbooks may not yet have metadata, so we pass an empty dict if so
try:
template_map['cookbook'] = cookbook.metadata.to_dict().copy()
except ValueError:
# ValueError may be returned if this cookbook does not yet have any
# metadata.rb written by a stencil. This is okay, as everyone should
# be using the base stencil first, and then we'll try to call
# cookbook.metadata again in this method later down.
pass
template_map['cookbook']['year'] = datetime.datetime.now().year
return template_map | [
"def",
"_build_template_map",
"(",
"cookbook",
",",
"cookbook_name",
",",
"stencil",
")",
":",
"template_map",
"=",
"{",
"'cookbook'",
":",
"{",
"\"name\"",
":",
"cookbook_name",
"}",
",",
"'options'",
":",
"stencil",
"[",
"'options'",
"]",
"}",
"# Cookbooks m... | Build a map of variables for this generated cookbook and stencil.
Get template variables from stencil option values, adding the default ones
like cookbook and cookbook year. | [
"Build",
"a",
"map",
"of",
"variables",
"for",
"this",
"generated",
"cookbook",
"and",
"stencil",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/food.py#L53-L75 | train | 43,755 |
rackerlabs/fastfood | fastfood/food.py | _render_binaries | def _render_binaries(files, written_files):
"""Write binary contents from filetable into files.
Using filetable for the input files, and the list of files, render
all the templates into actual files on disk, forcing to overwrite the file
as appropriate, and using the given open mode for the file.
"""
for source_path, target_path in files.items():
needdir = os.path.dirname(target_path)
assert needdir, "Target should have valid parent dir"
try:
os.makedirs(needdir)
except OSError as err:
if err.errno != errno.EEXIST:
raise
if os.path.isfile(target_path):
if target_path in written_files:
LOG.warning("Previous stencil has already written file %s.",
target_path)
else:
print("Skipping existing file %s" % target_path)
LOG.info("Skipping existing file %s", target_path)
continue
print("Writing rendered file %s" % target_path)
LOG.info("Writing rendered file %s", target_path)
shutil.copy(source_path, target_path)
if os.path.exists(target_path):
written_files.append(target_path) | python | def _render_binaries(files, written_files):
"""Write binary contents from filetable into files.
Using filetable for the input files, and the list of files, render
all the templates into actual files on disk, forcing to overwrite the file
as appropriate, and using the given open mode for the file.
"""
for source_path, target_path in files.items():
needdir = os.path.dirname(target_path)
assert needdir, "Target should have valid parent dir"
try:
os.makedirs(needdir)
except OSError as err:
if err.errno != errno.EEXIST:
raise
if os.path.isfile(target_path):
if target_path in written_files:
LOG.warning("Previous stencil has already written file %s.",
target_path)
else:
print("Skipping existing file %s" % target_path)
LOG.info("Skipping existing file %s", target_path)
continue
print("Writing rendered file %s" % target_path)
LOG.info("Writing rendered file %s", target_path)
shutil.copy(source_path, target_path)
if os.path.exists(target_path):
written_files.append(target_path) | [
"def",
"_render_binaries",
"(",
"files",
",",
"written_files",
")",
":",
"for",
"source_path",
",",
"target_path",
"in",
"files",
".",
"items",
"(",
")",
":",
"needdir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"target_path",
")",
"assert",
"needdir",
... | Write binary contents from filetable into files.
Using filetable for the input files, and the list of files, render
all the templates into actual files on disk, forcing to overwrite the file
as appropriate, and using the given open mode for the file. | [
"Write",
"binary",
"contents",
"from",
"filetable",
"into",
"files",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/food.py#L78-L108 | train | 43,756 |
rackerlabs/fastfood | fastfood/food.py | _render_templates | def _render_templates(files, filetable, written_files, force, open_mode='w'):
"""Write template contents from filetable into files.
Using filetable for the rendered templates, and the list of files, render
all the templates into actual files on disk, forcing to overwrite the file
as appropriate, and using the given open mode for the file.
"""
for tpl_path, content in filetable:
target_path = files[tpl_path]
needdir = os.path.dirname(target_path)
assert needdir, "Target should have valid parent dir"
try:
os.makedirs(needdir)
except OSError as err:
if err.errno != errno.EEXIST:
raise
if os.path.isfile(target_path):
if force:
LOG.warning("Forcing overwrite of existing file %s.",
target_path)
elif target_path in written_files:
LOG.warning("Previous stencil has already written file %s.",
target_path)
else:
print("Skipping existing file %s" % target_path)
LOG.info("Skipping existing file %s", target_path)
continue
with open(target_path, open_mode) as newfile:
print("Writing rendered file %s" % target_path)
LOG.info("Writing rendered file %s", target_path)
newfile.write(content)
written_files.append(target_path) | python | def _render_templates(files, filetable, written_files, force, open_mode='w'):
"""Write template contents from filetable into files.
Using filetable for the rendered templates, and the list of files, render
all the templates into actual files on disk, forcing to overwrite the file
as appropriate, and using the given open mode for the file.
"""
for tpl_path, content in filetable:
target_path = files[tpl_path]
needdir = os.path.dirname(target_path)
assert needdir, "Target should have valid parent dir"
try:
os.makedirs(needdir)
except OSError as err:
if err.errno != errno.EEXIST:
raise
if os.path.isfile(target_path):
if force:
LOG.warning("Forcing overwrite of existing file %s.",
target_path)
elif target_path in written_files:
LOG.warning("Previous stencil has already written file %s.",
target_path)
else:
print("Skipping existing file %s" % target_path)
LOG.info("Skipping existing file %s", target_path)
continue
with open(target_path, open_mode) as newfile:
print("Writing rendered file %s" % target_path)
LOG.info("Writing rendered file %s", target_path)
newfile.write(content)
written_files.append(target_path) | [
"def",
"_render_templates",
"(",
"files",
",",
"filetable",
",",
"written_files",
",",
"force",
",",
"open_mode",
"=",
"'w'",
")",
":",
"for",
"tpl_path",
",",
"content",
"in",
"filetable",
":",
"target_path",
"=",
"files",
"[",
"tpl_path",
"]",
"needdir",
... | Write template contents from filetable into files.
Using filetable for the rendered templates, and the list of files, render
all the templates into actual files on disk, forcing to overwrite the file
as appropriate, and using the given open mode for the file. | [
"Write",
"template",
"contents",
"from",
"filetable",
"into",
"files",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/food.py#L111-L144 | train | 43,757 |
rackerlabs/fastfood | fastfood/food.py | build_cookbook | def build_cookbook(build_config, templatepack_path,
cookbooks_home, force=False):
"""Build a cookbook from a fastfood.json file.
Can build on an existing cookbook, otherwise this will
create a new cookbook for you based on your templatepack.
"""
with open(build_config) as cfg:
cfg = json.load(cfg)
cookbook_name = cfg['name']
template_pack = pack.TemplatePack(templatepack_path)
written_files = []
cookbook = create_new_cookbook(cookbook_name, cookbooks_home)
for stencil_definition in cfg['stencils']:
selected_stencil_set_name = stencil_definition.get('stencil_set')
stencil_set = template_pack.load_stencil_set(selected_stencil_set_name)
selected_stencil_name = _determine_selected_stencil(
stencil_set,
stencil_definition
)
stencil = stencil_set.get_stencil(selected_stencil_name,
**stencil_definition)
updated_cookbook = process_stencil(
cookbook,
cookbook_name, # in case no metadata.rb yet
template_pack,
force,
stencil_set,
stencil,
written_files
)
return written_files, updated_cookbook | python | def build_cookbook(build_config, templatepack_path,
cookbooks_home, force=False):
"""Build a cookbook from a fastfood.json file.
Can build on an existing cookbook, otherwise this will
create a new cookbook for you based on your templatepack.
"""
with open(build_config) as cfg:
cfg = json.load(cfg)
cookbook_name = cfg['name']
template_pack = pack.TemplatePack(templatepack_path)
written_files = []
cookbook = create_new_cookbook(cookbook_name, cookbooks_home)
for stencil_definition in cfg['stencils']:
selected_stencil_set_name = stencil_definition.get('stencil_set')
stencil_set = template_pack.load_stencil_set(selected_stencil_set_name)
selected_stencil_name = _determine_selected_stencil(
stencil_set,
stencil_definition
)
stencil = stencil_set.get_stencil(selected_stencil_name,
**stencil_definition)
updated_cookbook = process_stencil(
cookbook,
cookbook_name, # in case no metadata.rb yet
template_pack,
force,
stencil_set,
stencil,
written_files
)
return written_files, updated_cookbook | [
"def",
"build_cookbook",
"(",
"build_config",
",",
"templatepack_path",
",",
"cookbooks_home",
",",
"force",
"=",
"False",
")",
":",
"with",
"open",
"(",
"build_config",
")",
"as",
"cfg",
":",
"cfg",
"=",
"json",
".",
"load",
"(",
"cfg",
")",
"cookbook_nam... | Build a cookbook from a fastfood.json file.
Can build on an existing cookbook, otherwise this will
create a new cookbook for you based on your templatepack. | [
"Build",
"a",
"cookbook",
"from",
"a",
"fastfood",
".",
"json",
"file",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/food.py#L147-L186 | train | 43,758 |
rackerlabs/fastfood | fastfood/food.py | process_stencil | def process_stencil(cookbook, cookbook_name, template_pack,
force_argument, stencil_set, stencil, written_files):
"""Process the stencil requested, writing any missing files as needed.
The stencil named 'stencilset_name' should be one of
templatepack's stencils.
"""
# force can be passed on the command line or forced in a stencil's options
force = force_argument or stencil['options'].get('force', False)
stencil['files'] = stencil.get('files') or {}
files = {
# files.keys() are template paths, files.values() are target paths
# {path to template: rendered target path, ... }
os.path.join(stencil_set.path, tpl): os.path.join(cookbook.path, tgt)
for tgt, tpl in stencil['files'].items()
}
stencil['partials'] = stencil.get('partials') or {}
partials = {
# files.keys() are template paths, files.values() are target paths
# {path to template: rendered target path, ... }
os.path.join(stencil_set.path, tpl): os.path.join(cookbook.path, tgt)
for tgt, tpl in stencil['partials'].items()
}
stencil['binaries'] = stencil.get('binaries') or {}
binaries = {
# files.keys() are binary paths, files.values() are target paths
# {path to binary: rendered target path, ... }
os.path.join(stencil_set.path, tpl): os.path.join(cookbook.path, tgt)
for tgt, tpl in stencil['binaries'].items()
}
template_map = _build_template_map(cookbook, cookbook_name, stencil)
filetable = templating.render_templates(*files.keys(), **template_map)
_render_templates(files, filetable, written_files, force)
parttable = templating.render_templates(*partials.keys(), **template_map)
_render_templates(partials, parttable, written_files, force, open_mode='a')
# no templating needed for binaries, just pass off to the copy method
_render_binaries(binaries, written_files)
# merge metadata.rb dependencies
stencil_metadata_deps = {'depends': stencil.get('dependencies', {})}
stencil_metadata = book.MetadataRb.from_dict(stencil_metadata_deps)
cookbook.metadata.merge(stencil_metadata)
# merge Berksfile dependencies
stencil_berks_deps = {'cookbook': stencil.get('berks_dependencies', {})}
stencil_berks = book.Berksfile.from_dict(stencil_berks_deps)
cookbook.berksfile.merge(stencil_berks)
return cookbook | python | def process_stencil(cookbook, cookbook_name, template_pack,
force_argument, stencil_set, stencil, written_files):
"""Process the stencil requested, writing any missing files as needed.
The stencil named 'stencilset_name' should be one of
templatepack's stencils.
"""
# force can be passed on the command line or forced in a stencil's options
force = force_argument or stencil['options'].get('force', False)
stencil['files'] = stencil.get('files') or {}
files = {
# files.keys() are template paths, files.values() are target paths
# {path to template: rendered target path, ... }
os.path.join(stencil_set.path, tpl): os.path.join(cookbook.path, tgt)
for tgt, tpl in stencil['files'].items()
}
stencil['partials'] = stencil.get('partials') or {}
partials = {
# files.keys() are template paths, files.values() are target paths
# {path to template: rendered target path, ... }
os.path.join(stencil_set.path, tpl): os.path.join(cookbook.path, tgt)
for tgt, tpl in stencil['partials'].items()
}
stencil['binaries'] = stencil.get('binaries') or {}
binaries = {
# files.keys() are binary paths, files.values() are target paths
# {path to binary: rendered target path, ... }
os.path.join(stencil_set.path, tpl): os.path.join(cookbook.path, tgt)
for tgt, tpl in stencil['binaries'].items()
}
template_map = _build_template_map(cookbook, cookbook_name, stencil)
filetable = templating.render_templates(*files.keys(), **template_map)
_render_templates(files, filetable, written_files, force)
parttable = templating.render_templates(*partials.keys(), **template_map)
_render_templates(partials, parttable, written_files, force, open_mode='a')
# no templating needed for binaries, just pass off to the copy method
_render_binaries(binaries, written_files)
# merge metadata.rb dependencies
stencil_metadata_deps = {'depends': stencil.get('dependencies', {})}
stencil_metadata = book.MetadataRb.from_dict(stencil_metadata_deps)
cookbook.metadata.merge(stencil_metadata)
# merge Berksfile dependencies
stencil_berks_deps = {'cookbook': stencil.get('berks_dependencies', {})}
stencil_berks = book.Berksfile.from_dict(stencil_berks_deps)
cookbook.berksfile.merge(stencil_berks)
return cookbook | [
"def",
"process_stencil",
"(",
"cookbook",
",",
"cookbook_name",
",",
"template_pack",
",",
"force_argument",
",",
"stencil_set",
",",
"stencil",
",",
"written_files",
")",
":",
"# force can be passed on the command line or forced in a stencil's options",
"force",
"=",
"for... | Process the stencil requested, writing any missing files as needed.
The stencil named 'stencilset_name' should be one of
templatepack's stencils. | [
"Process",
"the",
"stencil",
"requested",
"writing",
"any",
"missing",
"files",
"as",
"needed",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/food.py#L189-L244 | train | 43,759 |
rackerlabs/fastfood | fastfood/food.py | create_new_cookbook | def create_new_cookbook(cookbook_name, cookbooks_home):
"""Create a new cookbook.
:param cookbook_name: Name of the new cookbook.
:param cookbooks_home: Target dir for new cookbook.
"""
cookbooks_home = utils.normalize_path(cookbooks_home)
if not os.path.exists(cookbooks_home):
raise ValueError("Target cookbook dir %s does not exist."
% os.path.relpath(cookbooks_home))
target_dir = os.path.join(cookbooks_home, cookbook_name)
LOG.debug("Creating dir -> %s", target_dir)
try:
os.makedirs(target_dir)
except OSError as err:
if err.errno != errno.EEXIST:
raise
else:
LOG.info("Skipping existing directory %s", target_dir)
cookbook_path = os.path.join(cookbooks_home, cookbook_name)
cookbook = book.CookBook(cookbook_path)
return cookbook | python | def create_new_cookbook(cookbook_name, cookbooks_home):
"""Create a new cookbook.
:param cookbook_name: Name of the new cookbook.
:param cookbooks_home: Target dir for new cookbook.
"""
cookbooks_home = utils.normalize_path(cookbooks_home)
if not os.path.exists(cookbooks_home):
raise ValueError("Target cookbook dir %s does not exist."
% os.path.relpath(cookbooks_home))
target_dir = os.path.join(cookbooks_home, cookbook_name)
LOG.debug("Creating dir -> %s", target_dir)
try:
os.makedirs(target_dir)
except OSError as err:
if err.errno != errno.EEXIST:
raise
else:
LOG.info("Skipping existing directory %s", target_dir)
cookbook_path = os.path.join(cookbooks_home, cookbook_name)
cookbook = book.CookBook(cookbook_path)
return cookbook | [
"def",
"create_new_cookbook",
"(",
"cookbook_name",
",",
"cookbooks_home",
")",
":",
"cookbooks_home",
"=",
"utils",
".",
"normalize_path",
"(",
"cookbooks_home",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"cookbooks_home",
")",
":",
"raise",
"Va... | Create a new cookbook.
:param cookbook_name: Name of the new cookbook.
:param cookbooks_home: Target dir for new cookbook. | [
"Create",
"a",
"new",
"cookbook",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/food.py#L247-L272 | train | 43,760 |
rackerlabs/fastfood | fastfood/utils.py | deepupdate | def deepupdate(original, update, levels=5):
"""Update, like dict.update, but deeper.
Update 'original' from dict/iterable 'update'.
I.e., it recurses on dicts 'levels' times if necessary.
A standard dict.update is levels=0
"""
if not isinstance(update, dict):
update = dict(update)
if not levels > 0:
original.update(update)
else:
for key, val in update.items():
if isinstance(original.get(key), dict):
# might need a force=True to override this
if not isinstance(val, dict):
raise TypeError("Trying to update dict %s with "
"non-dict %s" % (original[key], val))
deepupdate(original[key], val, levels=levels-1)
else:
original.update({key: val}) | python | def deepupdate(original, update, levels=5):
"""Update, like dict.update, but deeper.
Update 'original' from dict/iterable 'update'.
I.e., it recurses on dicts 'levels' times if necessary.
A standard dict.update is levels=0
"""
if not isinstance(update, dict):
update = dict(update)
if not levels > 0:
original.update(update)
else:
for key, val in update.items():
if isinstance(original.get(key), dict):
# might need a force=True to override this
if not isinstance(val, dict):
raise TypeError("Trying to update dict %s with "
"non-dict %s" % (original[key], val))
deepupdate(original[key], val, levels=levels-1)
else:
original.update({key: val}) | [
"def",
"deepupdate",
"(",
"original",
",",
"update",
",",
"levels",
"=",
"5",
")",
":",
"if",
"not",
"isinstance",
"(",
"update",
",",
"dict",
")",
":",
"update",
"=",
"dict",
"(",
"update",
")",
"if",
"not",
"levels",
">",
"0",
":",
"original",
".... | Update, like dict.update, but deeper.
Update 'original' from dict/iterable 'update'.
I.e., it recurses on dicts 'levels' times if necessary.
A standard dict.update is levels=0 | [
"Update",
"like",
"dict",
".",
"update",
"but",
"deeper",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/utils.py#L63-L85 | train | 43,761 |
rackerlabs/fastfood | fastfood/utils.py | FileWrapper.write_statements | def write_statements(self, statements):
"""Insert the statements into the file neatly.
Ex:
statements = ["good 'dog'", "good 'cat'", "bad 'rat'", "fat 'emu'"]
# stream.txt ... animals = FileWrapper(open('stream.txt'))
good 'cow'
nice 'man'
bad 'news'
animals.write_statements(statements)
# stream.txt
good 'cow'
good 'dog'
good 'cat'
nice 'man'
bad 'news'
bad 'rat'
fat 'emu'
"""
self.seek(0)
original_content_lines = self.readlines()
new_content_lines = copy.copy(original_content_lines)
# ignore blanks and sort statements to be written
statements = sorted([stmnt for stmnt in statements if stmnt])
# find all the insert points for each statement
uniqs = {stmnt.split(None, 1)[0] for stmnt in statements}
insert_locations = {}
for line in reversed(original_content_lines):
if not uniqs:
break
if not line:
continue
for word in uniqs.copy():
if line.startswith(word):
index = original_content_lines.index(line) + 1
insert_locations[word] = index
uniqs.remove(word)
for statement in statements:
print("writing to %s : %s" % (self, statement))
startswith = statement.split(None, 1)[0]
# insert new statement with similar OR at the end of the file
new_content_lines.insert(
insert_locations.get(startswith, len(new_content_lines)),
statement)
if new_content_lines != original_content_lines:
self.seek(0)
self.writelines(new_content_lines)
self.flush() | python | def write_statements(self, statements):
"""Insert the statements into the file neatly.
Ex:
statements = ["good 'dog'", "good 'cat'", "bad 'rat'", "fat 'emu'"]
# stream.txt ... animals = FileWrapper(open('stream.txt'))
good 'cow'
nice 'man'
bad 'news'
animals.write_statements(statements)
# stream.txt
good 'cow'
good 'dog'
good 'cat'
nice 'man'
bad 'news'
bad 'rat'
fat 'emu'
"""
self.seek(0)
original_content_lines = self.readlines()
new_content_lines = copy.copy(original_content_lines)
# ignore blanks and sort statements to be written
statements = sorted([stmnt for stmnt in statements if stmnt])
# find all the insert points for each statement
uniqs = {stmnt.split(None, 1)[0] for stmnt in statements}
insert_locations = {}
for line in reversed(original_content_lines):
if not uniqs:
break
if not line:
continue
for word in uniqs.copy():
if line.startswith(word):
index = original_content_lines.index(line) + 1
insert_locations[word] = index
uniqs.remove(word)
for statement in statements:
print("writing to %s : %s" % (self, statement))
startswith = statement.split(None, 1)[0]
# insert new statement with similar OR at the end of the file
new_content_lines.insert(
insert_locations.get(startswith, len(new_content_lines)),
statement)
if new_content_lines != original_content_lines:
self.seek(0)
self.writelines(new_content_lines)
self.flush() | [
"def",
"write_statements",
"(",
"self",
",",
"statements",
")",
":",
"self",
".",
"seek",
"(",
"0",
")",
"original_content_lines",
"=",
"self",
".",
"readlines",
"(",
")",
"new_content_lines",
"=",
"copy",
".",
"copy",
"(",
"original_content_lines",
")",
"# ... | Insert the statements into the file neatly.
Ex:
statements = ["good 'dog'", "good 'cat'", "bad 'rat'", "fat 'emu'"]
# stream.txt ... animals = FileWrapper(open('stream.txt'))
good 'cow'
nice 'man'
bad 'news'
animals.write_statements(statements)
# stream.txt
good 'cow'
good 'dog'
good 'cat'
nice 'man'
bad 'news'
bad 'rat'
fat 'emu' | [
"Insert",
"the",
"statements",
"into",
"the",
"file",
"neatly",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/utils.py#L123-L177 | train | 43,762 |
rackerlabs/fastfood | fastfood/shell.py | _fastfood_build | def _fastfood_build(args):
"""Run on `fastfood build`."""
written_files, cookbook = food.build_cookbook(
args.config_file, args.template_pack,
args.cookbooks, args.force)
if len(written_files) > 0:
print("%s: %s files written" % (cookbook,
len(written_files)))
else:
print("%s up to date" % cookbook)
return written_files, cookbook | python | def _fastfood_build(args):
"""Run on `fastfood build`."""
written_files, cookbook = food.build_cookbook(
args.config_file, args.template_pack,
args.cookbooks, args.force)
if len(written_files) > 0:
print("%s: %s files written" % (cookbook,
len(written_files)))
else:
print("%s up to date" % cookbook)
return written_files, cookbook | [
"def",
"_fastfood_build",
"(",
"args",
")",
":",
"written_files",
",",
"cookbook",
"=",
"food",
".",
"build_cookbook",
"(",
"args",
".",
"config_file",
",",
"args",
".",
"template_pack",
",",
"args",
".",
"cookbooks",
",",
"args",
".",
"force",
")",
"if",
... | Run on `fastfood build`. | [
"Run",
"on",
"fastfood",
"build",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/shell.py#L49-L61 | train | 43,763 |
rackerlabs/fastfood | fastfood/shell.py | _fastfood_list | def _fastfood_list(args):
"""Run on `fastfood list`."""
template_pack = pack.TemplatePack(args.template_pack)
if args.stencil_set:
stencil_set = template_pack.load_stencil_set(args.stencil_set)
print("Available Stencils for %s:" % args.stencil_set)
for stencil in stencil_set.stencils:
print(" %s" % stencil)
else:
print('Available Stencil Sets:')
for name, vals in template_pack.stencil_sets.items():
print(" %12s - %12s" % (name, vals['help'])) | python | def _fastfood_list(args):
"""Run on `fastfood list`."""
template_pack = pack.TemplatePack(args.template_pack)
if args.stencil_set:
stencil_set = template_pack.load_stencil_set(args.stencil_set)
print("Available Stencils for %s:" % args.stencil_set)
for stencil in stencil_set.stencils:
print(" %s" % stencil)
else:
print('Available Stencil Sets:')
for name, vals in template_pack.stencil_sets.items():
print(" %12s - %12s" % (name, vals['help'])) | [
"def",
"_fastfood_list",
"(",
"args",
")",
":",
"template_pack",
"=",
"pack",
".",
"TemplatePack",
"(",
"args",
".",
"template_pack",
")",
"if",
"args",
".",
"stencil_set",
":",
"stencil_set",
"=",
"template_pack",
".",
"load_stencil_set",
"(",
"args",
".",
... | Run on `fastfood list`. | [
"Run",
"on",
"fastfood",
"list",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/shell.py#L64-L75 | train | 43,764 |
rackerlabs/fastfood | fastfood/shell.py | _fastfood_show | def _fastfood_show(args):
"""Run on `fastfood show`."""
template_pack = pack.TemplatePack(args.template_pack)
if args.stencil_set:
stencil_set = template_pack.load_stencil_set(args.stencil_set)
print("Stencil Set %s:" % args.stencil_set)
print(' Stencils:')
for stencil in stencil_set.stencils:
print(" %s" % stencil)
print(' Options:')
for opt, vals in stencil_set.manifest['options'].items():
print(" %s - %s" % (opt, vals['help'])) | python | def _fastfood_show(args):
"""Run on `fastfood show`."""
template_pack = pack.TemplatePack(args.template_pack)
if args.stencil_set:
stencil_set = template_pack.load_stencil_set(args.stencil_set)
print("Stencil Set %s:" % args.stencil_set)
print(' Stencils:')
for stencil in stencil_set.stencils:
print(" %s" % stencil)
print(' Options:')
for opt, vals in stencil_set.manifest['options'].items():
print(" %s - %s" % (opt, vals['help'])) | [
"def",
"_fastfood_show",
"(",
"args",
")",
":",
"template_pack",
"=",
"pack",
".",
"TemplatePack",
"(",
"args",
".",
"template_pack",
")",
"if",
"args",
".",
"stencil_set",
":",
"stencil_set",
"=",
"template_pack",
".",
"load_stencil_set",
"(",
"args",
".",
... | Run on `fastfood show`. | [
"Run",
"on",
"fastfood",
"show",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/shell.py#L78-L89 | train | 43,765 |
rackerlabs/fastfood | fastfood/shell.py | _release_info | def _release_info():
"""Check latest fastfood release info from PyPI."""
pypi_url = 'http://pypi.python.org/pypi/fastfood/json'
headers = {
'Accept': 'application/json',
}
request = urllib.Request(pypi_url, headers=headers)
response = urllib.urlopen(request).read().decode('utf_8')
data = json.loads(response)
return data | python | def _release_info():
"""Check latest fastfood release info from PyPI."""
pypi_url = 'http://pypi.python.org/pypi/fastfood/json'
headers = {
'Accept': 'application/json',
}
request = urllib.Request(pypi_url, headers=headers)
response = urllib.urlopen(request).read().decode('utf_8')
data = json.loads(response)
return data | [
"def",
"_release_info",
"(",
")",
":",
"pypi_url",
"=",
"'http://pypi.python.org/pypi/fastfood/json'",
"headers",
"=",
"{",
"'Accept'",
":",
"'application/json'",
",",
"}",
"request",
"=",
"urllib",
".",
"Request",
"(",
"pypi_url",
",",
"headers",
"=",
"headers",
... | Check latest fastfood release info from PyPI. | [
"Check",
"latest",
"fastfood",
"release",
"info",
"from",
"PyPI",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/shell.py#L92-L101 | train | 43,766 |
rackerlabs/fastfood | fastfood/shell.py | getenv | def getenv(option_name, default=None):
"""Return the option from the environment in the FASTFOOD namespace."""
env = "%s_%s" % (NAMESPACE.upper(), option_name.upper())
return os.environ.get(env, default) | python | def getenv(option_name, default=None):
"""Return the option from the environment in the FASTFOOD namespace."""
env = "%s_%s" % (NAMESPACE.upper(), option_name.upper())
return os.environ.get(env, default) | [
"def",
"getenv",
"(",
"option_name",
",",
"default",
"=",
"None",
")",
":",
"env",
"=",
"\"%s_%s\"",
"%",
"(",
"NAMESPACE",
".",
"upper",
"(",
")",
",",
"option_name",
".",
"upper",
"(",
")",
")",
"return",
"os",
".",
"environ",
".",
"get",
"(",
"e... | Return the option from the environment in the FASTFOOD namespace. | [
"Return",
"the",
"option",
"from",
"the",
"environment",
"in",
"the",
"FASTFOOD",
"namespace",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/shell.py#L111-L114 | train | 43,767 |
rackerlabs/fastfood | fastfood/pack.py | TemplatePack._validate | def _validate(self, key, cls=None):
"""Verify the manifest schema."""
if key not in self.manifest:
raise ValueError("Manifest %s requires '%s'."
% (self.manifest_path, key))
if cls:
if not isinstance(self.manifest[key], cls):
raise TypeError("Manifest value '%s' should be %s, not %s"
% (key, cls, type(self.manifest[key]))) | python | def _validate(self, key, cls=None):
"""Verify the manifest schema."""
if key not in self.manifest:
raise ValueError("Manifest %s requires '%s'."
% (self.manifest_path, key))
if cls:
if not isinstance(self.manifest[key], cls):
raise TypeError("Manifest value '%s' should be %s, not %s"
% (key, cls, type(self.manifest[key]))) | [
"def",
"_validate",
"(",
"self",
",",
"key",
",",
"cls",
"=",
"None",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"manifest",
":",
"raise",
"ValueError",
"(",
"\"Manifest %s requires '%s'.\"",
"%",
"(",
"self",
".",
"manifest_path",
",",
"key",
")",... | Verify the manifest schema. | [
"Verify",
"the",
"manifest",
"schema",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/pack.py#L48-L56 | train | 43,768 |
rackerlabs/fastfood | fastfood/pack.py | TemplatePack.stencil_sets | def stencil_sets(self):
"""List of stencil sets."""
if not self._stencil_sets:
self._stencil_sets = self.manifest['stencil_sets']
return self._stencil_sets | python | def stencil_sets(self):
"""List of stencil sets."""
if not self._stencil_sets:
self._stencil_sets = self.manifest['stencil_sets']
return self._stencil_sets | [
"def",
"stencil_sets",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_stencil_sets",
":",
"self",
".",
"_stencil_sets",
"=",
"self",
".",
"manifest",
"[",
"'stencil_sets'",
"]",
"return",
"self",
".",
"_stencil_sets"
] | List of stencil sets. | [
"List",
"of",
"stencil",
"sets",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/pack.py#L67-L71 | train | 43,769 |
rackerlabs/fastfood | fastfood/pack.py | TemplatePack.load_stencil_set | def load_stencil_set(self, stencilset_name):
"""Return the Stencil Set from this template pack."""
if stencilset_name not in self._stencil_sets:
if stencilset_name not in self.manifest['stencil_sets'].keys():
raise exc.FastfoodStencilSetNotListed(
"Stencil set '%s' not listed in %s under stencil_sets."
% (stencilset_name, self.manifest_path))
stencil_path = os.path.join(
self.path, 'stencils', stencilset_name)
self._stencil_sets[stencilset_name] = (
stencil_module.StencilSet(stencil_path))
return self._stencil_sets[stencilset_name] | python | def load_stencil_set(self, stencilset_name):
"""Return the Stencil Set from this template pack."""
if stencilset_name not in self._stencil_sets:
if stencilset_name not in self.manifest['stencil_sets'].keys():
raise exc.FastfoodStencilSetNotListed(
"Stencil set '%s' not listed in %s under stencil_sets."
% (stencilset_name, self.manifest_path))
stencil_path = os.path.join(
self.path, 'stencils', stencilset_name)
self._stencil_sets[stencilset_name] = (
stencil_module.StencilSet(stencil_path))
return self._stencil_sets[stencilset_name] | [
"def",
"load_stencil_set",
"(",
"self",
",",
"stencilset_name",
")",
":",
"if",
"stencilset_name",
"not",
"in",
"self",
".",
"_stencil_sets",
":",
"if",
"stencilset_name",
"not",
"in",
"self",
".",
"manifest",
"[",
"'stencil_sets'",
"]",
".",
"keys",
"(",
")... | Return the Stencil Set from this template pack. | [
"Return",
"the",
"Stencil",
"Set",
"from",
"this",
"template",
"pack",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/pack.py#L89-L100 | train | 43,770 |
rackerlabs/fastfood | fastfood/templating.py | qstring | def qstring(option):
"""Custom quoting method for jinja."""
if (re.match(NODE_ATTR_RE, option) is None and
re.match(CHEF_CONST_RE, option) is None):
return "'%s'" % option
else:
return option | python | def qstring(option):
"""Custom quoting method for jinja."""
if (re.match(NODE_ATTR_RE, option) is None and
re.match(CHEF_CONST_RE, option) is None):
return "'%s'" % option
else:
return option | [
"def",
"qstring",
"(",
"option",
")",
":",
"if",
"(",
"re",
".",
"match",
"(",
"NODE_ATTR_RE",
",",
"option",
")",
"is",
"None",
"and",
"re",
".",
"match",
"(",
"CHEF_CONST_RE",
",",
"option",
")",
"is",
"None",
")",
":",
"return",
"\"'%s'\"",
"%",
... | Custom quoting method for jinja. | [
"Custom",
"quoting",
"method",
"for",
"jinja",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/templating.py#L31-L37 | train | 43,771 |
rackerlabs/fastfood | fastfood/templating.py | render_templates_generator | def render_templates_generator(*files, **template_map):
"""Render jinja templates according to template_map.
Yields (path, result)
"""
for path in files:
if not os.path.isfile(path):
raise ValueError("Template file %s not found"
% os.path.relpath(path))
else:
try:
with codecs.open(path, encoding='utf-8') as f:
text = f.read()
template = JINJA_ENV.from_string(text)
except jinja2.TemplateSyntaxError as err:
msg = ("Error rendering jinja2 template for file %s "
"on line %s. Error: %s"
% (path, err.lineno, err.message))
raise type(err)(
msg, err.lineno, filename=os.path.basename(path))
result = template.render(**template_map)
if not result.endswith('\n'):
result += '\n'
yield path, result | python | def render_templates_generator(*files, **template_map):
"""Render jinja templates according to template_map.
Yields (path, result)
"""
for path in files:
if not os.path.isfile(path):
raise ValueError("Template file %s not found"
% os.path.relpath(path))
else:
try:
with codecs.open(path, encoding='utf-8') as f:
text = f.read()
template = JINJA_ENV.from_string(text)
except jinja2.TemplateSyntaxError as err:
msg = ("Error rendering jinja2 template for file %s "
"on line %s. Error: %s"
% (path, err.lineno, err.message))
raise type(err)(
msg, err.lineno, filename=os.path.basename(path))
result = template.render(**template_map)
if not result.endswith('\n'):
result += '\n'
yield path, result | [
"def",
"render_templates_generator",
"(",
"*",
"files",
",",
"*",
"*",
"template_map",
")",
":",
"for",
"path",
"in",
"files",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"raise",
"ValueError",
"(",
"\"Template file %s not fo... | Render jinja templates according to template_map.
Yields (path, result) | [
"Render",
"jinja",
"templates",
"according",
"to",
"template_map",
"."
] | 543970c4cedbb3956e84a7986469fdd7e4ee8fc8 | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/templating.py#L51-L75 | train | 43,772 |
moltob/pymultigen | multigen/generator.py | Task.run | def run(self, element, outfolder):
"""Apply this task to model element."""
filepath = self.relative_path_for_element(element)
if outfolder and not os.path.isabs(filepath):
filepath = os.path.join(outfolder, filepath)
_logger.debug('{!r} --> {!r}'.format(element, filepath))
self.ensure_folder(filepath)
self.generate_file(element, filepath) | python | def run(self, element, outfolder):
"""Apply this task to model element."""
filepath = self.relative_path_for_element(element)
if outfolder and not os.path.isabs(filepath):
filepath = os.path.join(outfolder, filepath)
_logger.debug('{!r} --> {!r}'.format(element, filepath))
self.ensure_folder(filepath)
self.generate_file(element, filepath) | [
"def",
"run",
"(",
"self",
",",
"element",
",",
"outfolder",
")",
":",
"filepath",
"=",
"self",
".",
"relative_path_for_element",
"(",
"element",
")",
"if",
"outfolder",
"and",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"filepath",
")",
":",
"filepath"... | Apply this task to model element. | [
"Apply",
"this",
"task",
"to",
"model",
"element",
"."
] | 3095c7579ab29199cb421b2e70d3088067a450bd | https://github.com/moltob/pymultigen/blob/3095c7579ab29199cb421b2e70d3088067a450bd/multigen/generator.py#L56-L65 | train | 43,773 |
moltob/pymultigen | multigen/generator.py | TemplateFileTask.create_template_context | def create_template_context(self, element, **kwargs):
"""Code generation context, specific to template and current element."""
context = dict(element=element, **kwargs)
if self.global_context:
context.update(**self.global_context)
return context | python | def create_template_context(self, element, **kwargs):
"""Code generation context, specific to template and current element."""
context = dict(element=element, **kwargs)
if self.global_context:
context.update(**self.global_context)
return context | [
"def",
"create_template_context",
"(",
"self",
",",
"element",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"dict",
"(",
"element",
"=",
"element",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"global_context",
":",
"context",
".",
"update",
... | Code generation context, specific to template and current element. | [
"Code",
"generation",
"context",
"specific",
"to",
"template",
"and",
"current",
"element",
"."
] | 3095c7579ab29199cb421b2e70d3088067a450bd | https://github.com/moltob/pymultigen/blob/3095c7579ab29199cb421b2e70d3088067a450bd/multigen/generator.py#L113-L118 | train | 43,774 |
moltob/pymultigen | multigen/jinja.py | JinjaGenerator.create_environment | def create_environment(self, **kwargs):
"""
Return a new Jinja environment.
Derived classes may override method to pass additional parameters or to change the template
loader type.
"""
return jinja2.Environment(
loader=jinja2.FileSystemLoader(self.templates_path),
**kwargs
) | python | def create_environment(self, **kwargs):
"""
Return a new Jinja environment.
Derived classes may override method to pass additional parameters or to change the template
loader type.
"""
return jinja2.Environment(
loader=jinja2.FileSystemLoader(self.templates_path),
**kwargs
) | [
"def",
"create_environment",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"jinja2",
".",
"Environment",
"(",
"loader",
"=",
"jinja2",
".",
"FileSystemLoader",
"(",
"self",
".",
"templates_path",
")",
",",
"*",
"*",
"kwargs",
")"
] | Return a new Jinja environment.
Derived classes may override method to pass additional parameters or to change the template
loader type. | [
"Return",
"a",
"new",
"Jinja",
"environment",
".",
"Derived",
"classes",
"may",
"override",
"method",
"to",
"pass",
"additional",
"parameters",
"or",
"to",
"change",
"the",
"template",
"loader",
"type",
"."
] | 3095c7579ab29199cb421b2e70d3088067a450bd | https://github.com/moltob/pymultigen/blob/3095c7579ab29199cb421b2e70d3088067a450bd/multigen/jinja.py#L18-L28 | train | 43,775 |
gabrielelanaro/chemview | chemview/gg.py | pairs | def pairs(a):
"""Return array of pairs of adjacent elements in a.
>>> pairs([1, 2, 3, 4])
array([[1, 2],
[2, 3],
[3, 4]])
"""
a = np.asarray(a)
return as_strided(a, shape=(a.size - 1, 2), strides=a.strides * 2) | python | def pairs(a):
"""Return array of pairs of adjacent elements in a.
>>> pairs([1, 2, 3, 4])
array([[1, 2],
[2, 3],
[3, 4]])
"""
a = np.asarray(a)
return as_strided(a, shape=(a.size - 1, 2), strides=a.strides * 2) | [
"def",
"pairs",
"(",
"a",
")",
":",
"a",
"=",
"np",
".",
"asarray",
"(",
"a",
")",
"return",
"as_strided",
"(",
"a",
",",
"shape",
"=",
"(",
"a",
".",
"size",
"-",
"1",
",",
"2",
")",
",",
"strides",
"=",
"a",
".",
"strides",
"*",
"2",
")"
... | Return array of pairs of adjacent elements in a.
>>> pairs([1, 2, 3, 4])
array([[1, 2],
[2, 3],
[3, 4]]) | [
"Return",
"array",
"of",
"pairs",
"of",
"adjacent",
"elements",
"in",
"a",
"."
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/gg.py#L240-L250 | train | 43,776 |
openvax/topiary | topiary/cli/args.py | predict_epitopes_from_args | def predict_epitopes_from_args(args):
"""
Returns an epitope collection from the given commandline arguments.
Parameters
----------
args : argparse.Namespace
Parsed commandline arguments for Topiary
"""
mhc_model = mhc_binding_predictor_from_args(args)
variants = variant_collection_from_args(args)
gene_expression_dict = rna_gene_expression_dict_from_args(args)
transcript_expression_dict = rna_transcript_expression_dict_from_args(args)
predictor = TopiaryPredictor(
mhc_model=mhc_model,
padding_around_mutation=args.padding_around_mutation,
ic50_cutoff=args.ic50_cutoff,
percentile_cutoff=args.percentile_cutoff,
min_transcript_expression=args.rna_min_transcript_expression,
min_gene_expression=args.rna_min_gene_expression,
only_novel_epitopes=args.only_novel_epitopes,
raise_on_error=not args.skip_variant_errors)
return predictor.predict_from_variants(
variants=variants,
transcript_expression_dict=transcript_expression_dict,
gene_expression_dict=gene_expression_dict) | python | def predict_epitopes_from_args(args):
"""
Returns an epitope collection from the given commandline arguments.
Parameters
----------
args : argparse.Namespace
Parsed commandline arguments for Topiary
"""
mhc_model = mhc_binding_predictor_from_args(args)
variants = variant_collection_from_args(args)
gene_expression_dict = rna_gene_expression_dict_from_args(args)
transcript_expression_dict = rna_transcript_expression_dict_from_args(args)
predictor = TopiaryPredictor(
mhc_model=mhc_model,
padding_around_mutation=args.padding_around_mutation,
ic50_cutoff=args.ic50_cutoff,
percentile_cutoff=args.percentile_cutoff,
min_transcript_expression=args.rna_min_transcript_expression,
min_gene_expression=args.rna_min_gene_expression,
only_novel_epitopes=args.only_novel_epitopes,
raise_on_error=not args.skip_variant_errors)
return predictor.predict_from_variants(
variants=variants,
transcript_expression_dict=transcript_expression_dict,
gene_expression_dict=gene_expression_dict) | [
"def",
"predict_epitopes_from_args",
"(",
"args",
")",
":",
"mhc_model",
"=",
"mhc_binding_predictor_from_args",
"(",
"args",
")",
"variants",
"=",
"variant_collection_from_args",
"(",
"args",
")",
"gene_expression_dict",
"=",
"rna_gene_expression_dict_from_args",
"(",
"a... | Returns an epitope collection from the given commandline arguments.
Parameters
----------
args : argparse.Namespace
Parsed commandline arguments for Topiary | [
"Returns",
"an",
"epitope",
"collection",
"from",
"the",
"given",
"commandline",
"arguments",
"."
] | 04f0077bc4bf1ad350a0e78c26fa48c55fe7813b | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/cli/args.py#L68-L94 | train | 43,777 |
gabfl/password-generator-py | src/pwgenerator.py | get_random_word | def get_random_word(dictionary, min_word_length=3, max_word_length=8):
"""
Returns a random word from the dictionary
"""
while True:
# Choose a random word
word = choice(dictionary)
# Stop looping as soon as we have a valid candidate
if len(word) >= min_word_length and len(word) <= max_word_length:
break
return word | python | def get_random_word(dictionary, min_word_length=3, max_word_length=8):
"""
Returns a random word from the dictionary
"""
while True:
# Choose a random word
word = choice(dictionary)
# Stop looping as soon as we have a valid candidate
if len(word) >= min_word_length and len(word) <= max_word_length:
break
return word | [
"def",
"get_random_word",
"(",
"dictionary",
",",
"min_word_length",
"=",
"3",
",",
"max_word_length",
"=",
"8",
")",
":",
"while",
"True",
":",
"# Choose a random word",
"word",
"=",
"choice",
"(",
"dictionary",
")",
"# Stop looping as soon as we have a valid candida... | Returns a random word from the dictionary | [
"Returns",
"a",
"random",
"word",
"from",
"the",
"dictionary"
] | cd59078fd3e6ea85b7acd9bfcf6d04014c0f7220 | https://github.com/gabfl/password-generator-py/blob/cd59078fd3e6ea85b7acd9bfcf6d04014c0f7220/src/pwgenerator.py#L26-L38 | train | 43,778 |
gabfl/password-generator-py | src/pwgenerator.py | pw | def pw(min_word_length=3, max_word_length=8, max_int_value=1000, number_of_elements=4, no_special_characters=False):
"""
Generate a password
"""
# Set the position of the integer
int_position = set_int_position(number_of_elements)
# Load dictionary
dictionary = load_dictionary()
password = ''
for i in range(number_of_elements):
# Add word or integer
if i == int_position:
password += str(get_random_int(max_int_value))
else:
password += get_random_word(dictionary,
min_word_length,
max_word_length).title()
# Add separator
if i != number_of_elements - 1:
password += get_random_separator(no_special_characters)
return password | python | def pw(min_word_length=3, max_word_length=8, max_int_value=1000, number_of_elements=4, no_special_characters=False):
"""
Generate a password
"""
# Set the position of the integer
int_position = set_int_position(number_of_elements)
# Load dictionary
dictionary = load_dictionary()
password = ''
for i in range(number_of_elements):
# Add word or integer
if i == int_position:
password += str(get_random_int(max_int_value))
else:
password += get_random_word(dictionary,
min_word_length,
max_word_length).title()
# Add separator
if i != number_of_elements - 1:
password += get_random_separator(no_special_characters)
return password | [
"def",
"pw",
"(",
"min_word_length",
"=",
"3",
",",
"max_word_length",
"=",
"8",
",",
"max_int_value",
"=",
"1000",
",",
"number_of_elements",
"=",
"4",
",",
"no_special_characters",
"=",
"False",
")",
":",
"# Set the position of the integer",
"int_position",
"=",... | Generate a password | [
"Generate",
"a",
"password"
] | cd59078fd3e6ea85b7acd9bfcf6d04014c0f7220 | https://github.com/gabfl/password-generator-py/blob/cd59078fd3e6ea85b7acd9bfcf6d04014c0f7220/src/pwgenerator.py#L71-L96 | train | 43,779 |
openvax/topiary | topiary/sequence_helpers.py | check_padding_around_mutation | def check_padding_around_mutation(given_padding, epitope_lengths):
"""
If user doesn't provide any padding around the mutation we need
to at least include enough of the surrounding non-mutated
esidues to construct candidate epitopes of the specified lengths.
"""
min_required_padding = max(epitope_lengths) - 1
if not given_padding:
return min_required_padding
else:
require_integer(given_padding, "Padding around mutation")
if given_padding < min_required_padding:
raise ValueError(
"Padding around mutation %d cannot be less than %d "
"for epitope lengths %s" % (
given_padding,
min_required_padding,
epitope_lengths))
return given_padding | python | def check_padding_around_mutation(given_padding, epitope_lengths):
"""
If user doesn't provide any padding around the mutation we need
to at least include enough of the surrounding non-mutated
esidues to construct candidate epitopes of the specified lengths.
"""
min_required_padding = max(epitope_lengths) - 1
if not given_padding:
return min_required_padding
else:
require_integer(given_padding, "Padding around mutation")
if given_padding < min_required_padding:
raise ValueError(
"Padding around mutation %d cannot be less than %d "
"for epitope lengths %s" % (
given_padding,
min_required_padding,
epitope_lengths))
return given_padding | [
"def",
"check_padding_around_mutation",
"(",
"given_padding",
",",
"epitope_lengths",
")",
":",
"min_required_padding",
"=",
"max",
"(",
"epitope_lengths",
")",
"-",
"1",
"if",
"not",
"given_padding",
":",
"return",
"min_required_padding",
"else",
":",
"require_intege... | If user doesn't provide any padding around the mutation we need
to at least include enough of the surrounding non-mutated
esidues to construct candidate epitopes of the specified lengths. | [
"If",
"user",
"doesn",
"t",
"provide",
"any",
"padding",
"around",
"the",
"mutation",
"we",
"need",
"to",
"at",
"least",
"include",
"enough",
"of",
"the",
"surrounding",
"non",
"-",
"mutated",
"esidues",
"to",
"construct",
"candidate",
"epitopes",
"of",
"the... | 04f0077bc4bf1ad350a0e78c26fa48c55fe7813b | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/sequence_helpers.py#L52-L70 | train | 43,780 |
openvax/topiary | topiary/sequence_helpers.py | peptide_mutation_interval | def peptide_mutation_interval(
peptide_start_in_protein,
peptide_length,
mutation_start_in_protein,
mutation_end_in_protein):
"""
Half-open interval of mutated residues in the peptide, determined
from the mutation interval in the original protein sequence.
Parameters
----------
peptide_start_in_protein : int
Position of the first peptide residue within the protein
(starting from 0)
peptide_length : int
mutation_start_in_protein : int
Position of the first mutated residue starting from 0. In the case of a
deletion, the position where the first residue had been.
mutation_end_in_protein : int
Position of the last mutated residue in the mutant protein. In the case
of a deletion, this is equal to the mutation_start_in_protein.
)
"""
if peptide_start_in_protein > mutation_end_in_protein:
raise ValueError("Peptide starts after mutation")
elif peptide_start_in_protein + peptide_length < mutation_start_in_protein:
raise ValueError("Peptide ends before mutation")
# need a half-open start/end interval
peptide_mutation_start_offset = min(
peptide_length,
max(0, mutation_start_in_protein - peptide_start_in_protein))
peptide_mutation_end_offset = min(
peptide_length,
max(0, mutation_end_in_protein - peptide_start_in_protein))
return (peptide_mutation_start_offset, peptide_mutation_end_offset) | python | def peptide_mutation_interval(
peptide_start_in_protein,
peptide_length,
mutation_start_in_protein,
mutation_end_in_protein):
"""
Half-open interval of mutated residues in the peptide, determined
from the mutation interval in the original protein sequence.
Parameters
----------
peptide_start_in_protein : int
Position of the first peptide residue within the protein
(starting from 0)
peptide_length : int
mutation_start_in_protein : int
Position of the first mutated residue starting from 0. In the case of a
deletion, the position where the first residue had been.
mutation_end_in_protein : int
Position of the last mutated residue in the mutant protein. In the case
of a deletion, this is equal to the mutation_start_in_protein.
)
"""
if peptide_start_in_protein > mutation_end_in_protein:
raise ValueError("Peptide starts after mutation")
elif peptide_start_in_protein + peptide_length < mutation_start_in_protein:
raise ValueError("Peptide ends before mutation")
# need a half-open start/end interval
peptide_mutation_start_offset = min(
peptide_length,
max(0, mutation_start_in_protein - peptide_start_in_protein))
peptide_mutation_end_offset = min(
peptide_length,
max(0, mutation_end_in_protein - peptide_start_in_protein))
return (peptide_mutation_start_offset, peptide_mutation_end_offset) | [
"def",
"peptide_mutation_interval",
"(",
"peptide_start_in_protein",
",",
"peptide_length",
",",
"mutation_start_in_protein",
",",
"mutation_end_in_protein",
")",
":",
"if",
"peptide_start_in_protein",
">",
"mutation_end_in_protein",
":",
"raise",
"ValueError",
"(",
"\"Peptid... | Half-open interval of mutated residues in the peptide, determined
from the mutation interval in the original protein sequence.
Parameters
----------
peptide_start_in_protein : int
Position of the first peptide residue within the protein
(starting from 0)
peptide_length : int
mutation_start_in_protein : int
Position of the first mutated residue starting from 0. In the case of a
deletion, the position where the first residue had been.
mutation_end_in_protein : int
Position of the last mutated residue in the mutant protein. In the case
of a deletion, this is equal to the mutation_start_in_protein.
) | [
"Half",
"-",
"open",
"interval",
"of",
"mutated",
"residues",
"in",
"the",
"peptide",
"determined",
"from",
"the",
"mutation",
"interval",
"in",
"the",
"original",
"protein",
"sequence",
"."
] | 04f0077bc4bf1ad350a0e78c26fa48c55fe7813b | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/sequence_helpers.py#L83-L121 | train | 43,781 |
trustar/trustar-python | trustar/models/indicator.py | Indicator.from_dict | def from_dict(cls, indicator):
"""
Create an indicator object from a dictionary.
:param indicator: The dictionary.
:return: The indicator object.
"""
tags = indicator.get('tags')
if tags is not None:
tags = [Tag.from_dict(tag) for tag in tags]
return Indicator(value=indicator.get('value'),
type=indicator.get('indicatorType'),
priority_level=indicator.get('priorityLevel'),
correlation_count=indicator.get('correlationCount'),
whitelisted=indicator.get('whitelisted'),
weight=indicator.get('weight'),
reason=indicator.get('reason'),
first_seen=indicator.get('firstSeen'),
last_seen=indicator.get('lastSeen'),
sightings=indicator.get('sightings'),
source=indicator.get('source'),
notes=indicator.get('notes'),
tags=tags,
enclave_ids=indicator.get('enclaveIds')) | python | def from_dict(cls, indicator):
"""
Create an indicator object from a dictionary.
:param indicator: The dictionary.
:return: The indicator object.
"""
tags = indicator.get('tags')
if tags is not None:
tags = [Tag.from_dict(tag) for tag in tags]
return Indicator(value=indicator.get('value'),
type=indicator.get('indicatorType'),
priority_level=indicator.get('priorityLevel'),
correlation_count=indicator.get('correlationCount'),
whitelisted=indicator.get('whitelisted'),
weight=indicator.get('weight'),
reason=indicator.get('reason'),
first_seen=indicator.get('firstSeen'),
last_seen=indicator.get('lastSeen'),
sightings=indicator.get('sightings'),
source=indicator.get('source'),
notes=indicator.get('notes'),
tags=tags,
enclave_ids=indicator.get('enclaveIds')) | [
"def",
"from_dict",
"(",
"cls",
",",
"indicator",
")",
":",
"tags",
"=",
"indicator",
".",
"get",
"(",
"'tags'",
")",
"if",
"tags",
"is",
"not",
"None",
":",
"tags",
"=",
"[",
"Tag",
".",
"from_dict",
"(",
"tag",
")",
"for",
"tag",
"in",
"tags",
... | Create an indicator object from a dictionary.
:param indicator: The dictionary.
:return: The indicator object. | [
"Create",
"an",
"indicator",
"object",
"from",
"a",
"dictionary",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/models/indicator.py#L71-L96 | train | 43,782 |
trustar/trustar-python | trustar/models/indicator.py | Indicator.to_dict | def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the indicator.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the indicator.
"""
if remove_nones:
return super().to_dict(remove_nones=True)
tags = None
if self.tags is not None:
tags = [tag.to_dict(remove_nones=remove_nones) for tag in self.tags]
return {
'value': self.value,
'indicatorType': self.type,
'priorityLevel': self.priority_level,
'correlationCount': self.correlation_count,
'whitelisted': self.whitelisted,
'weight': self.weight,
'reason': self.reason,
'firstSeen': self.first_seen,
'lastSeen': self.last_seen,
'source': self.source,
'notes': self.notes,
'tags': tags,
'enclaveIds': self.enclave_ids
} | python | def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the indicator.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the indicator.
"""
if remove_nones:
return super().to_dict(remove_nones=True)
tags = None
if self.tags is not None:
tags = [tag.to_dict(remove_nones=remove_nones) for tag in self.tags]
return {
'value': self.value,
'indicatorType': self.type,
'priorityLevel': self.priority_level,
'correlationCount': self.correlation_count,
'whitelisted': self.whitelisted,
'weight': self.weight,
'reason': self.reason,
'firstSeen': self.first_seen,
'lastSeen': self.last_seen,
'source': self.source,
'notes': self.notes,
'tags': tags,
'enclaveIds': self.enclave_ids
} | [
"def",
"to_dict",
"(",
"self",
",",
"remove_nones",
"=",
"False",
")",
":",
"if",
"remove_nones",
":",
"return",
"super",
"(",
")",
".",
"to_dict",
"(",
"remove_nones",
"=",
"True",
")",
"tags",
"=",
"None",
"if",
"self",
".",
"tags",
"is",
"not",
"N... | Creates a dictionary representation of the indicator.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the indicator. | [
"Creates",
"a",
"dictionary",
"representation",
"of",
"the",
"indicator",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/models/indicator.py#L98-L127 | train | 43,783 |
openvax/topiary | topiary/filters.py | apply_filter | def apply_filter(
filter_fn,
collection,
result_fn=None,
filter_name="",
collection_name=""):
"""
Apply filter to effect collection and print number of dropped elements
Parameters
----------
"""
n_before = len(collection)
filtered = [x for x in collection if filter_fn(x)]
n_after = len(filtered)
if not collection_name:
collection_name = collection.__class__.__name__
logging.info(
"%s filtering removed %d/%d entries of %s",
filter_name,
(n_before - n_after),
n_before,
collection_name)
return result_fn(filtered) if result_fn else collection.__class__(filtered) | python | def apply_filter(
filter_fn,
collection,
result_fn=None,
filter_name="",
collection_name=""):
"""
Apply filter to effect collection and print number of dropped elements
Parameters
----------
"""
n_before = len(collection)
filtered = [x for x in collection if filter_fn(x)]
n_after = len(filtered)
if not collection_name:
collection_name = collection.__class__.__name__
logging.info(
"%s filtering removed %d/%d entries of %s",
filter_name,
(n_before - n_after),
n_before,
collection_name)
return result_fn(filtered) if result_fn else collection.__class__(filtered) | [
"def",
"apply_filter",
"(",
"filter_fn",
",",
"collection",
",",
"result_fn",
"=",
"None",
",",
"filter_name",
"=",
"\"\"",
",",
"collection_name",
"=",
"\"\"",
")",
":",
"n_before",
"=",
"len",
"(",
"collection",
")",
"filtered",
"=",
"[",
"x",
"for",
"... | Apply filter to effect collection and print number of dropped elements
Parameters
---------- | [
"Apply",
"filter",
"to",
"effect",
"collection",
"and",
"print",
"number",
"of",
"dropped",
"elements"
] | 04f0077bc4bf1ad350a0e78c26fa48c55fe7813b | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/filters.py#L24-L47 | train | 43,784 |
openvax/topiary | topiary/filters.py | filter_silent_and_noncoding_effects | def filter_silent_and_noncoding_effects(effects):
"""
Keep only variant effects which result in modified proteins.
Parameters
----------
effects : varcode.EffectCollection
"""
return apply_filter(
filter_fn=lambda effect: isinstance(effect, NonsilentCodingMutation),
collection=effects,
result_fn=effects.clone_with_new_elements,
filter_name="Silent mutation") | python | def filter_silent_and_noncoding_effects(effects):
"""
Keep only variant effects which result in modified proteins.
Parameters
----------
effects : varcode.EffectCollection
"""
return apply_filter(
filter_fn=lambda effect: isinstance(effect, NonsilentCodingMutation),
collection=effects,
result_fn=effects.clone_with_new_elements,
filter_name="Silent mutation") | [
"def",
"filter_silent_and_noncoding_effects",
"(",
"effects",
")",
":",
"return",
"apply_filter",
"(",
"filter_fn",
"=",
"lambda",
"effect",
":",
"isinstance",
"(",
"effect",
",",
"NonsilentCodingMutation",
")",
",",
"collection",
"=",
"effects",
",",
"result_fn",
... | Keep only variant effects which result in modified proteins.
Parameters
----------
effects : varcode.EffectCollection | [
"Keep",
"only",
"variant",
"effects",
"which",
"result",
"in",
"modified",
"proteins",
"."
] | 04f0077bc4bf1ad350a0e78c26fa48c55fe7813b | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/filters.py#L49-L61 | train | 43,785 |
openvax/topiary | topiary/filters.py | apply_variant_expression_filters | def apply_variant_expression_filters(
variants,
gene_expression_dict,
gene_expression_threshold,
transcript_expression_dict,
transcript_expression_threshold):
"""
Filter a collection of variants by gene and transcript expression thresholds
Parameters
----------
variants : varcode.VariantCollection
gene_expression_dict : dict
gene_expression_threshold : float
transcript_expression_dict : dict
transcript_expression_threshold : float
"""
if gene_expression_dict:
variants = apply_filter(
lambda variant: any(
gene_expression_dict.get(gene_id, 0.0) >=
gene_expression_threshold
for gene_id in variant.gene_ids
),
variants,
result_fn=variants.clone_with_new_elements,
filter_name="Variant gene expression (min=%0.4f)" % gene_expression_threshold)
if transcript_expression_dict:
variants = apply_filter(
lambda variant: any(
transcript_expression_dict.get(transcript_id, 0.0) >=
transcript_expression_threshold
for transcript_id in variant.transcript_ids
),
variants,
result_fn=variants.clone_with_new_elements,
filter_name=(
"Variant transcript expression (min=%0.4f)" % (
transcript_expression_threshold,)))
return variants | python | def apply_variant_expression_filters(
variants,
gene_expression_dict,
gene_expression_threshold,
transcript_expression_dict,
transcript_expression_threshold):
"""
Filter a collection of variants by gene and transcript expression thresholds
Parameters
----------
variants : varcode.VariantCollection
gene_expression_dict : dict
gene_expression_threshold : float
transcript_expression_dict : dict
transcript_expression_threshold : float
"""
if gene_expression_dict:
variants = apply_filter(
lambda variant: any(
gene_expression_dict.get(gene_id, 0.0) >=
gene_expression_threshold
for gene_id in variant.gene_ids
),
variants,
result_fn=variants.clone_with_new_elements,
filter_name="Variant gene expression (min=%0.4f)" % gene_expression_threshold)
if transcript_expression_dict:
variants = apply_filter(
lambda variant: any(
transcript_expression_dict.get(transcript_id, 0.0) >=
transcript_expression_threshold
for transcript_id in variant.transcript_ids
),
variants,
result_fn=variants.clone_with_new_elements,
filter_name=(
"Variant transcript expression (min=%0.4f)" % (
transcript_expression_threshold,)))
return variants | [
"def",
"apply_variant_expression_filters",
"(",
"variants",
",",
"gene_expression_dict",
",",
"gene_expression_threshold",
",",
"transcript_expression_dict",
",",
"transcript_expression_threshold",
")",
":",
"if",
"gene_expression_dict",
":",
"variants",
"=",
"apply_filter",
... | Filter a collection of variants by gene and transcript expression thresholds
Parameters
----------
variants : varcode.VariantCollection
gene_expression_dict : dict
gene_expression_threshold : float
transcript_expression_dict : dict
transcript_expression_threshold : float | [
"Filter",
"a",
"collection",
"of",
"variants",
"by",
"gene",
"and",
"transcript",
"expression",
"thresholds"
] | 04f0077bc4bf1ad350a0e78c26fa48c55fe7813b | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/filters.py#L64-L107 | train | 43,786 |
openvax/topiary | topiary/filters.py | apply_effect_expression_filters | def apply_effect_expression_filters(
effects,
gene_expression_dict,
gene_expression_threshold,
transcript_expression_dict,
transcript_expression_threshold):
"""
Filter collection of varcode effects by given gene
and transcript expression thresholds.
Parameters
----------
effects : varcode.EffectCollection
gene_expression_dict : dict
gene_expression_threshold : float
transcript_expression_dict : dict
transcript_expression_threshold : float
"""
if gene_expression_dict:
effects = apply_filter(
lambda effect: (
gene_expression_dict.get(effect.gene_id, 0.0) >=
gene_expression_threshold),
effects,
result_fn=effects.clone_with_new_elements,
filter_name="Effect gene expression (min = %0.4f)" % gene_expression_threshold)
if transcript_expression_dict:
effects = apply_filter(
lambda effect: (
transcript_expression_dict.get(effect.transcript_id, 0.0) >=
transcript_expression_threshold
),
effects,
result_fn=effects.clone_with_new_elements,
filter_name=(
"Effect transcript expression (min=%0.4f)" % (
transcript_expression_threshold,)))
return effects | python | def apply_effect_expression_filters(
effects,
gene_expression_dict,
gene_expression_threshold,
transcript_expression_dict,
transcript_expression_threshold):
"""
Filter collection of varcode effects by given gene
and transcript expression thresholds.
Parameters
----------
effects : varcode.EffectCollection
gene_expression_dict : dict
gene_expression_threshold : float
transcript_expression_dict : dict
transcript_expression_threshold : float
"""
if gene_expression_dict:
effects = apply_filter(
lambda effect: (
gene_expression_dict.get(effect.gene_id, 0.0) >=
gene_expression_threshold),
effects,
result_fn=effects.clone_with_new_elements,
filter_name="Effect gene expression (min = %0.4f)" % gene_expression_threshold)
if transcript_expression_dict:
effects = apply_filter(
lambda effect: (
transcript_expression_dict.get(effect.transcript_id, 0.0) >=
transcript_expression_threshold
),
effects,
result_fn=effects.clone_with_new_elements,
filter_name=(
"Effect transcript expression (min=%0.4f)" % (
transcript_expression_threshold,)))
return effects | [
"def",
"apply_effect_expression_filters",
"(",
"effects",
",",
"gene_expression_dict",
",",
"gene_expression_threshold",
",",
"transcript_expression_dict",
",",
"transcript_expression_threshold",
")",
":",
"if",
"gene_expression_dict",
":",
"effects",
"=",
"apply_filter",
"("... | Filter collection of varcode effects by given gene
and transcript expression thresholds.
Parameters
----------
effects : varcode.EffectCollection
gene_expression_dict : dict
gene_expression_threshold : float
transcript_expression_dict : dict
transcript_expression_threshold : float | [
"Filter",
"collection",
"of",
"varcode",
"effects",
"by",
"given",
"gene",
"and",
"transcript",
"expression",
"thresholds",
"."
] | 04f0077bc4bf1ad350a0e78c26fa48c55fe7813b | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/filters.py#L109-L151 | train | 43,787 |
trustar/trustar-python | trustar/indicator_client.py | IndicatorClient.get_indicators | def get_indicators(self, from_time=None, to_time=None, enclave_ids=None,
included_tag_ids=None, excluded_tag_ids=None,
start_page=0, page_size=None):
"""
Creates a generator from the |get_indicators_page| method that returns each successive indicator as an
|Indicator| object containing values for the 'value' and 'type' attributes only; all
other |Indicator| object attributes will contain Null values.
:param int from_time: start of time window in milliseconds since epoch (defaults to 7 days ago).
:param int to_time: end of time window in milliseconds since epoch (defaults to current time).
:param list(string) enclave_ids: a list of enclave IDs from which to get indicators from.
:param list(string) included_tag_ids: only indicators containing ALL of these tag GUIDs will be returned.
:param list(string) excluded_tag_ids: only indicators containing NONE of these tags GUIDs be returned.
:param int start_page: see 'page_size' explanation.
:param int page_size: Passing the integer 1000 as the argument to this parameter should result in your script
making fewer API calls because it returns the largest quantity of indicators with each API call. An API call
has to be made to fetch each |Page|.
:return: A generator of |Indicator| objects containing values for the "value" and "type" attributes only.
All other attributes of the |Indicator| object will contain Null values.
"""
indicators_page_generator = self._get_indicators_page_generator(
from_time=from_time,
to_time=to_time,
enclave_ids=enclave_ids,
included_tag_ids=included_tag_ids,
excluded_tag_ids=excluded_tag_ids,
page_number=start_page,
page_size=page_size
)
indicators_generator = Page.get_generator(page_generator=indicators_page_generator)
return indicators_generator | python | def get_indicators(self, from_time=None, to_time=None, enclave_ids=None,
included_tag_ids=None, excluded_tag_ids=None,
start_page=0, page_size=None):
"""
Creates a generator from the |get_indicators_page| method that returns each successive indicator as an
|Indicator| object containing values for the 'value' and 'type' attributes only; all
other |Indicator| object attributes will contain Null values.
:param int from_time: start of time window in milliseconds since epoch (defaults to 7 days ago).
:param int to_time: end of time window in milliseconds since epoch (defaults to current time).
:param list(string) enclave_ids: a list of enclave IDs from which to get indicators from.
:param list(string) included_tag_ids: only indicators containing ALL of these tag GUIDs will be returned.
:param list(string) excluded_tag_ids: only indicators containing NONE of these tags GUIDs be returned.
:param int start_page: see 'page_size' explanation.
:param int page_size: Passing the integer 1000 as the argument to this parameter should result in your script
making fewer API calls because it returns the largest quantity of indicators with each API call. An API call
has to be made to fetch each |Page|.
:return: A generator of |Indicator| objects containing values for the "value" and "type" attributes only.
All other attributes of the |Indicator| object will contain Null values.
"""
indicators_page_generator = self._get_indicators_page_generator(
from_time=from_time,
to_time=to_time,
enclave_ids=enclave_ids,
included_tag_ids=included_tag_ids,
excluded_tag_ids=excluded_tag_ids,
page_number=start_page,
page_size=page_size
)
indicators_generator = Page.get_generator(page_generator=indicators_page_generator)
return indicators_generator | [
"def",
"get_indicators",
"(",
"self",
",",
"from_time",
"=",
"None",
",",
"to_time",
"=",
"None",
",",
"enclave_ids",
"=",
"None",
",",
"included_tag_ids",
"=",
"None",
",",
"excluded_tag_ids",
"=",
"None",
",",
"start_page",
"=",
"0",
",",
"page_size",
"=... | Creates a generator from the |get_indicators_page| method that returns each successive indicator as an
|Indicator| object containing values for the 'value' and 'type' attributes only; all
other |Indicator| object attributes will contain Null values.
:param int from_time: start of time window in milliseconds since epoch (defaults to 7 days ago).
:param int to_time: end of time window in milliseconds since epoch (defaults to current time).
:param list(string) enclave_ids: a list of enclave IDs from which to get indicators from.
:param list(string) included_tag_ids: only indicators containing ALL of these tag GUIDs will be returned.
:param list(string) excluded_tag_ids: only indicators containing NONE of these tags GUIDs be returned.
:param int start_page: see 'page_size' explanation.
:param int page_size: Passing the integer 1000 as the argument to this parameter should result in your script
making fewer API calls because it returns the largest quantity of indicators with each API call. An API call
has to be made to fetch each |Page|.
:return: A generator of |Indicator| objects containing values for the "value" and "type" attributes only.
All other attributes of the |Indicator| object will contain Null values. | [
"Creates",
"a",
"generator",
"from",
"the",
"|get_indicators_page|",
"method",
"that",
"returns",
"each",
"successive",
"indicator",
"as",
"an",
"|Indicator|",
"object",
"containing",
"values",
"for",
"the",
"value",
"and",
"type",
"attributes",
"only",
";",
"all"... | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L57-L90 | train | 43,788 |
trustar/trustar-python | trustar/indicator_client.py | IndicatorClient._get_indicators_page_generator | def _get_indicators_page_generator(self, from_time=None, to_time=None, page_number=0, page_size=None,
enclave_ids=None, included_tag_ids=None, excluded_tag_ids=None):
"""
Creates a generator from the |get_indicators_page| method that returns each successive page.
:param int from_time: start of time window in milliseconds since epoch (defaults to 7 days ago)
:param int to_time: end of time window in milliseconds since epoch (defaults to current time)
:param int page_number: the page number
:param int page_size: the page size
:param list(string) enclave_ids: a list of enclave IDs to filter by
:param list(string) included_tag_ids: only indicators containing ALL of these tags will be returned
:param list(string) excluded_tag_ids: only indicators containing NONE of these tags will be returned
:return: a |Page| of |Indicator| objects
"""
get_page = functools.partial(
self.get_indicators_page,
from_time=from_time,
to_time=to_time,
page_number=page_number,
page_size=page_size,
enclave_ids=enclave_ids,
included_tag_ids=included_tag_ids,
excluded_tag_ids=excluded_tag_ids
)
return Page.get_page_generator(get_page, page_number, page_size) | python | def _get_indicators_page_generator(self, from_time=None, to_time=None, page_number=0, page_size=None,
enclave_ids=None, included_tag_ids=None, excluded_tag_ids=None):
"""
Creates a generator from the |get_indicators_page| method that returns each successive page.
:param int from_time: start of time window in milliseconds since epoch (defaults to 7 days ago)
:param int to_time: end of time window in milliseconds since epoch (defaults to current time)
:param int page_number: the page number
:param int page_size: the page size
:param list(string) enclave_ids: a list of enclave IDs to filter by
:param list(string) included_tag_ids: only indicators containing ALL of these tags will be returned
:param list(string) excluded_tag_ids: only indicators containing NONE of these tags will be returned
:return: a |Page| of |Indicator| objects
"""
get_page = functools.partial(
self.get_indicators_page,
from_time=from_time,
to_time=to_time,
page_number=page_number,
page_size=page_size,
enclave_ids=enclave_ids,
included_tag_ids=included_tag_ids,
excluded_tag_ids=excluded_tag_ids
)
return Page.get_page_generator(get_page, page_number, page_size) | [
"def",
"_get_indicators_page_generator",
"(",
"self",
",",
"from_time",
"=",
"None",
",",
"to_time",
"=",
"None",
",",
"page_number",
"=",
"0",
",",
"page_size",
"=",
"None",
",",
"enclave_ids",
"=",
"None",
",",
"included_tag_ids",
"=",
"None",
",",
"exclud... | Creates a generator from the |get_indicators_page| method that returns each successive page.
:param int from_time: start of time window in milliseconds since epoch (defaults to 7 days ago)
:param int to_time: end of time window in milliseconds since epoch (defaults to current time)
:param int page_number: the page number
:param int page_size: the page size
:param list(string) enclave_ids: a list of enclave IDs to filter by
:param list(string) included_tag_ids: only indicators containing ALL of these tags will be returned
:param list(string) excluded_tag_ids: only indicators containing NONE of these tags will be returned
:return: a |Page| of |Indicator| objects | [
"Creates",
"a",
"generator",
"from",
"the",
"|get_indicators_page|",
"method",
"that",
"returns",
"each",
"successive",
"page",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L92-L117 | train | 43,789 |
trustar/trustar-python | trustar/indicator_client.py | IndicatorClient.get_indicators_page | def get_indicators_page(self, from_time=None, to_time=None, page_number=None, page_size=None,
enclave_ids=None, included_tag_ids=None, excluded_tag_ids=None):
"""
Get a page of indicators matching the provided filters.
:param int from_time: start of time window in milliseconds since epoch (defaults to 7 days ago)
:param int to_time: end of time window in milliseconds since epoch (defaults to current time)
:param int page_number: the page number
:param int page_size: the page size
:param list(string) enclave_ids: a list of enclave IDs to filter by
:param list(string) included_tag_ids: only indicators containing ALL of these tags will be returned
:param list(string) excluded_tag_ids: only indicators containing NONE of these tags will be returned
:return: a |Page| of indicators
"""
params = {
'from': from_time,
'to': to_time,
'pageSize': page_size,
'pageNumber': page_number,
'enclaveIds': enclave_ids,
'tagIds': included_tag_ids,
'excludedTagIds': excluded_tag_ids
}
resp = self._client.get("indicators", params=params)
page_of_indicators = Page.from_dict(resp.json(), content_type=Indicator)
return page_of_indicators | python | def get_indicators_page(self, from_time=None, to_time=None, page_number=None, page_size=None,
enclave_ids=None, included_tag_ids=None, excluded_tag_ids=None):
"""
Get a page of indicators matching the provided filters.
:param int from_time: start of time window in milliseconds since epoch (defaults to 7 days ago)
:param int to_time: end of time window in milliseconds since epoch (defaults to current time)
:param int page_number: the page number
:param int page_size: the page size
:param list(string) enclave_ids: a list of enclave IDs to filter by
:param list(string) included_tag_ids: only indicators containing ALL of these tags will be returned
:param list(string) excluded_tag_ids: only indicators containing NONE of these tags will be returned
:return: a |Page| of indicators
"""
params = {
'from': from_time,
'to': to_time,
'pageSize': page_size,
'pageNumber': page_number,
'enclaveIds': enclave_ids,
'tagIds': included_tag_ids,
'excludedTagIds': excluded_tag_ids
}
resp = self._client.get("indicators", params=params)
page_of_indicators = Page.from_dict(resp.json(), content_type=Indicator)
return page_of_indicators | [
"def",
"get_indicators_page",
"(",
"self",
",",
"from_time",
"=",
"None",
",",
"to_time",
"=",
"None",
",",
"page_number",
"=",
"None",
",",
"page_size",
"=",
"None",
",",
"enclave_ids",
"=",
"None",
",",
"included_tag_ids",
"=",
"None",
",",
"excluded_tag_i... | Get a page of indicators matching the provided filters.
:param int from_time: start of time window in milliseconds since epoch (defaults to 7 days ago)
:param int to_time: end of time window in milliseconds since epoch (defaults to current time)
:param int page_number: the page number
:param int page_size: the page size
:param list(string) enclave_ids: a list of enclave IDs to filter by
:param list(string) included_tag_ids: only indicators containing ALL of these tags will be returned
:param list(string) excluded_tag_ids: only indicators containing NONE of these tags will be returned
:return: a |Page| of indicators | [
"Get",
"a",
"page",
"of",
"indicators",
"matching",
"the",
"provided",
"filters",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L119-L148 | train | 43,790 |
trustar/trustar-python | trustar/indicator_client.py | IndicatorClient.search_indicators | def search_indicators(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
indicator_types=None,
tags=None,
excluded_tags=None):
"""
Uses the |search_indicators_page| method to create a generator that returns each successive indicator.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict indicators to specific enclaves (optional - by
default indicators from all of user's enclaves are returned)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) indicator_types: a list of indicator types to filter by (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter indicators by. Only indicators containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Indicators containing ANY of these tags will be excluded from the results.
:return: The generator.
"""
return Page.get_generator(page_generator=self._search_indicators_page_generator(search_term, enclave_ids,
from_time, to_time,
indicator_types, tags,
excluded_tags)) | python | def search_indicators(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
indicator_types=None,
tags=None,
excluded_tags=None):
"""
Uses the |search_indicators_page| method to create a generator that returns each successive indicator.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict indicators to specific enclaves (optional - by
default indicators from all of user's enclaves are returned)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) indicator_types: a list of indicator types to filter by (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter indicators by. Only indicators containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Indicators containing ANY of these tags will be excluded from the results.
:return: The generator.
"""
return Page.get_generator(page_generator=self._search_indicators_page_generator(search_term, enclave_ids,
from_time, to_time,
indicator_types, tags,
excluded_tags)) | [
"def",
"search_indicators",
"(",
"self",
",",
"search_term",
"=",
"None",
",",
"enclave_ids",
"=",
"None",
",",
"from_time",
"=",
"None",
",",
"to_time",
"=",
"None",
",",
"indicator_types",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"excluded_tags",
"=",... | Uses the |search_indicators_page| method to create a generator that returns each successive indicator.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict indicators to specific enclaves (optional - by
default indicators from all of user's enclaves are returned)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) indicator_types: a list of indicator types to filter by (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter indicators by. Only indicators containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Indicators containing ANY of these tags will be excluded from the results.
:return: The generator. | [
"Uses",
"the",
"|search_indicators_page|",
"method",
"to",
"create",
"a",
"generator",
"that",
"returns",
"each",
"successive",
"indicator",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L150-L176 | train | 43,791 |
trustar/trustar-python | trustar/indicator_client.py | IndicatorClient._search_indicators_page_generator | def _search_indicators_page_generator(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
indicator_types=None,
tags=None,
excluded_tags=None,
start_page=0,
page_size=None):
"""
Creates a generator from the |search_indicators_page| method that returns each successive page.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict indicators to specific enclaves (optional - by
default indicators from all of user's enclaves are returned)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) indicator_types: a list of indicator types to filter by (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter indicators by. Only indicators containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Indicators containing ANY of these tags will be excluded from the results.
:param int start_page: The page to start on.
:param page_size: The size of each page.
:return: The generator.
"""
get_page = functools.partial(self.search_indicators_page, search_term, enclave_ids,
from_time, to_time, indicator_types, tags, excluded_tags)
return Page.get_page_generator(get_page, start_page, page_size) | python | def _search_indicators_page_generator(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
indicator_types=None,
tags=None,
excluded_tags=None,
start_page=0,
page_size=None):
"""
Creates a generator from the |search_indicators_page| method that returns each successive page.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict indicators to specific enclaves (optional - by
default indicators from all of user's enclaves are returned)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) indicator_types: a list of indicator types to filter by (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter indicators by. Only indicators containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Indicators containing ANY of these tags will be excluded from the results.
:param int start_page: The page to start on.
:param page_size: The size of each page.
:return: The generator.
"""
get_page = functools.partial(self.search_indicators_page, search_term, enclave_ids,
from_time, to_time, indicator_types, tags, excluded_tags)
return Page.get_page_generator(get_page, start_page, page_size) | [
"def",
"_search_indicators_page_generator",
"(",
"self",
",",
"search_term",
"=",
"None",
",",
"enclave_ids",
"=",
"None",
",",
"from_time",
"=",
"None",
",",
"to_time",
"=",
"None",
",",
"indicator_types",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"exclud... | Creates a generator from the |search_indicators_page| method that returns each successive page.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict indicators to specific enclaves (optional - by
default indicators from all of user's enclaves are returned)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) indicator_types: a list of indicator types to filter by (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter indicators by. Only indicators containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Indicators containing ANY of these tags will be excluded from the results.
:param int start_page: The page to start on.
:param page_size: The size of each page.
:return: The generator. | [
"Creates",
"a",
"generator",
"from",
"the",
"|search_indicators_page|",
"method",
"that",
"returns",
"each",
"successive",
"page",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L178-L207 | train | 43,792 |
trustar/trustar-python | trustar/indicator_client.py | IndicatorClient.search_indicators_page | def search_indicators_page(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
indicator_types=None,
tags=None,
excluded_tags=None,
page_size=None,
page_number=None):
"""
Search for indicators containing a search term.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict to indicators found in reports in specific
enclaves (optional - by default reports from all of the user's enclaves are used)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) indicator_types: a list of indicator types to filter by (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter indicators by. Only indicators containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Indicators containing ANY of these tags will be excluded from the results.
:param int page_number: the page number to get.
:param int page_size: the size of the page to be returned.
:return: a |Page| of |Indicator| objects.
"""
body = {
'searchTerm': search_term
}
params = {
'enclaveIds': enclave_ids,
'from': from_time,
'to': to_time,
'entityTypes': indicator_types,
'tags': tags,
'excludedTags': excluded_tags,
'pageSize': page_size,
'pageNumber': page_number
}
resp = self._client.post("indicators/search", params=params, data=json.dumps(body))
return Page.from_dict(resp.json(), content_type=Indicator) | python | def search_indicators_page(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
indicator_types=None,
tags=None,
excluded_tags=None,
page_size=None,
page_number=None):
"""
Search for indicators containing a search term.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict to indicators found in reports in specific
enclaves (optional - by default reports from all of the user's enclaves are used)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) indicator_types: a list of indicator types to filter by (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter indicators by. Only indicators containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Indicators containing ANY of these tags will be excluded from the results.
:param int page_number: the page number to get.
:param int page_size: the size of the page to be returned.
:return: a |Page| of |Indicator| objects.
"""
body = {
'searchTerm': search_term
}
params = {
'enclaveIds': enclave_ids,
'from': from_time,
'to': to_time,
'entityTypes': indicator_types,
'tags': tags,
'excludedTags': excluded_tags,
'pageSize': page_size,
'pageNumber': page_number
}
resp = self._client.post("indicators/search", params=params, data=json.dumps(body))
return Page.from_dict(resp.json(), content_type=Indicator) | [
"def",
"search_indicators_page",
"(",
"self",
",",
"search_term",
"=",
"None",
",",
"enclave_ids",
"=",
"None",
",",
"from_time",
"=",
"None",
",",
"to_time",
"=",
"None",
",",
"indicator_types",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"excluded_tags",
... | Search for indicators containing a search term.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict to indicators found in reports in specific
enclaves (optional - by default reports from all of the user's enclaves are used)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) indicator_types: a list of indicator types to filter by (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter indicators by. Only indicators containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Indicators containing ANY of these tags will be excluded from the results.
:param int page_number: the page number to get.
:param int page_size: the size of the page to be returned.
:return: a |Page| of |Indicator| objects. | [
"Search",
"for",
"indicators",
"containing",
"a",
"search",
"term",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L209-L253 | train | 43,793 |
trustar/trustar-python | trustar/indicator_client.py | IndicatorClient.get_related_indicators | def get_related_indicators(self, indicators=None, enclave_ids=None):
"""
Uses the |get_related_indicators_page| method to create a generator that returns each successive report.
:param list(string) indicators: list of indicator values to search for
:param list(string) enclave_ids: list of GUIDs of enclaves to search in
:return: The generator.
"""
return Page.get_generator(page_generator=self._get_related_indicators_page_generator(indicators, enclave_ids)) | python | def get_related_indicators(self, indicators=None, enclave_ids=None):
"""
Uses the |get_related_indicators_page| method to create a generator that returns each successive report.
:param list(string) indicators: list of indicator values to search for
:param list(string) enclave_ids: list of GUIDs of enclaves to search in
:return: The generator.
"""
return Page.get_generator(page_generator=self._get_related_indicators_page_generator(indicators, enclave_ids)) | [
"def",
"get_related_indicators",
"(",
"self",
",",
"indicators",
"=",
"None",
",",
"enclave_ids",
"=",
"None",
")",
":",
"return",
"Page",
".",
"get_generator",
"(",
"page_generator",
"=",
"self",
".",
"_get_related_indicators_page_generator",
"(",
"indicators",
"... | Uses the |get_related_indicators_page| method to create a generator that returns each successive report.
:param list(string) indicators: list of indicator values to search for
:param list(string) enclave_ids: list of GUIDs of enclaves to search in
:return: The generator. | [
"Uses",
"the",
"|get_related_indicators_page|",
"method",
"to",
"create",
"a",
"generator",
"that",
"returns",
"each",
"successive",
"report",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L255-L264 | train | 43,794 |
trustar/trustar-python | trustar/indicator_client.py | IndicatorClient.get_indicator_metadata | def get_indicator_metadata(self, value):
"""
Provide metadata associated with a single indicators, including value, indicatorType, noteCount,
sightings, lastSeen, enclaveIds, and tags. The metadata is determined based on the enclaves the user making the
request has READ access to.
:param value: an indicator value to query.
:return: A dict containing three fields: 'indicator' (an |Indicator| object), 'tags' (a list of |Tag|
objects), and 'enclaveIds' (a list of enclave IDs that the indicator was found in).
.. warning:: This method is deprecated. Please use |get_indicators_metadata| instead.
"""
result = self.get_indicators_metadata([Indicator(value=value)])
if len(result) > 0:
indicator = result[0]
return {
'indicator': indicator,
'tags': indicator.tags,
'enclaveIds': indicator.enclave_ids
}
else:
return None | python | def get_indicator_metadata(self, value):
"""
Provide metadata associated with a single indicators, including value, indicatorType, noteCount,
sightings, lastSeen, enclaveIds, and tags. The metadata is determined based on the enclaves the user making the
request has READ access to.
:param value: an indicator value to query.
:return: A dict containing three fields: 'indicator' (an |Indicator| object), 'tags' (a list of |Tag|
objects), and 'enclaveIds' (a list of enclave IDs that the indicator was found in).
.. warning:: This method is deprecated. Please use |get_indicators_metadata| instead.
"""
result = self.get_indicators_metadata([Indicator(value=value)])
if len(result) > 0:
indicator = result[0]
return {
'indicator': indicator,
'tags': indicator.tags,
'enclaveIds': indicator.enclave_ids
}
else:
return None | [
"def",
"get_indicator_metadata",
"(",
"self",
",",
"value",
")",
":",
"result",
"=",
"self",
".",
"get_indicators_metadata",
"(",
"[",
"Indicator",
"(",
"value",
"=",
"value",
")",
"]",
")",
"if",
"len",
"(",
"result",
")",
">",
"0",
":",
"indicator",
... | Provide metadata associated with a single indicators, including value, indicatorType, noteCount,
sightings, lastSeen, enclaveIds, and tags. The metadata is determined based on the enclaves the user making the
request has READ access to.
:param value: an indicator value to query.
:return: A dict containing three fields: 'indicator' (an |Indicator| object), 'tags' (a list of |Tag|
objects), and 'enclaveIds' (a list of enclave IDs that the indicator was found in).
.. warning:: This method is deprecated. Please use |get_indicators_metadata| instead. | [
"Provide",
"metadata",
"associated",
"with",
"a",
"single",
"indicators",
"including",
"value",
"indicatorType",
"noteCount",
"sightings",
"lastSeen",
"enclaveIds",
"and",
"tags",
".",
"The",
"metadata",
"is",
"determined",
"based",
"on",
"the",
"enclaves",
"the",
... | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L276-L298 | train | 43,795 |
trustar/trustar-python | trustar/indicator_client.py | IndicatorClient.get_indicators_metadata | def get_indicators_metadata(self, indicators):
"""
Provide metadata associated with an list of indicators, including value, indicatorType, noteCount, sightings,
lastSeen, enclaveIds, and tags. The metadata is determined based on the enclaves the user making the request has
READ access to.
:param indicators: a list of |Indicator| objects to query. Values are required, types are optional. Types
might be required to distinguish in a case where one indicator value has been associated with multiple types
based on different contexts.
:return: A list of |Indicator| objects. The following attributes of the objects will be returned:
correlation_count, last_seen, sightings, notes, tags, enclave_ids. All other attributes of the Indicator
objects will have Null values.
"""
data = [{
'value': i.value,
'indicatorType': i.type
} for i in indicators]
resp = self._client.post("indicators/metadata", data=json.dumps(data))
return [Indicator.from_dict(x) for x in resp.json()] | python | def get_indicators_metadata(self, indicators):
"""
Provide metadata associated with an list of indicators, including value, indicatorType, noteCount, sightings,
lastSeen, enclaveIds, and tags. The metadata is determined based on the enclaves the user making the request has
READ access to.
:param indicators: a list of |Indicator| objects to query. Values are required, types are optional. Types
might be required to distinguish in a case where one indicator value has been associated with multiple types
based on different contexts.
:return: A list of |Indicator| objects. The following attributes of the objects will be returned:
correlation_count, last_seen, sightings, notes, tags, enclave_ids. All other attributes of the Indicator
objects will have Null values.
"""
data = [{
'value': i.value,
'indicatorType': i.type
} for i in indicators]
resp = self._client.post("indicators/metadata", data=json.dumps(data))
return [Indicator.from_dict(x) for x in resp.json()] | [
"def",
"get_indicators_metadata",
"(",
"self",
",",
"indicators",
")",
":",
"data",
"=",
"[",
"{",
"'value'",
":",
"i",
".",
"value",
",",
"'indicatorType'",
":",
"i",
".",
"type",
"}",
"for",
"i",
"in",
"indicators",
"]",
"resp",
"=",
"self",
".",
"... | Provide metadata associated with an list of indicators, including value, indicatorType, noteCount, sightings,
lastSeen, enclaveIds, and tags. The metadata is determined based on the enclaves the user making the request has
READ access to.
:param indicators: a list of |Indicator| objects to query. Values are required, types are optional. Types
might be required to distinguish in a case where one indicator value has been associated with multiple types
based on different contexts.
:return: A list of |Indicator| objects. The following attributes of the objects will be returned:
correlation_count, last_seen, sightings, notes, tags, enclave_ids. All other attributes of the Indicator
objects will have Null values. | [
"Provide",
"metadata",
"associated",
"with",
"an",
"list",
"of",
"indicators",
"including",
"value",
"indicatorType",
"noteCount",
"sightings",
"lastSeen",
"enclaveIds",
"and",
"tags",
".",
"The",
"metadata",
"is",
"determined",
"based",
"on",
"the",
"enclaves",
"... | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L300-L321 | train | 43,796 |
trustar/trustar-python | trustar/indicator_client.py | IndicatorClient.add_terms_to_whitelist | def add_terms_to_whitelist(self, terms):
"""
Add a list of terms to the user's company's whitelist.
:param terms: The list of terms to whitelist.
:return: The list of extracted |Indicator| objects that were whitelisted.
"""
resp = self._client.post("whitelist", json=terms)
return [Indicator.from_dict(indicator) for indicator in resp.json()] | python | def add_terms_to_whitelist(self, terms):
"""
Add a list of terms to the user's company's whitelist.
:param terms: The list of terms to whitelist.
:return: The list of extracted |Indicator| objects that were whitelisted.
"""
resp = self._client.post("whitelist", json=terms)
return [Indicator.from_dict(indicator) for indicator in resp.json()] | [
"def",
"add_terms_to_whitelist",
"(",
"self",
",",
"terms",
")",
":",
"resp",
"=",
"self",
".",
"_client",
".",
"post",
"(",
"\"whitelist\"",
",",
"json",
"=",
"terms",
")",
"return",
"[",
"Indicator",
".",
"from_dict",
"(",
"indicator",
")",
"for",
"ind... | Add a list of terms to the user's company's whitelist.
:param terms: The list of terms to whitelist.
:return: The list of extracted |Indicator| objects that were whitelisted. | [
"Add",
"a",
"list",
"of",
"terms",
"to",
"the",
"user",
"s",
"company",
"s",
"whitelist",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L359-L368 | train | 43,797 |
trustar/trustar-python | trustar/indicator_client.py | IndicatorClient.delete_indicator_from_whitelist | def delete_indicator_from_whitelist(self, indicator):
"""
Delete an indicator from the user's company's whitelist.
:param indicator: An |Indicator| object, representing the indicator to delete.
"""
params = indicator.to_dict()
self._client.delete("whitelist", params=params) | python | def delete_indicator_from_whitelist(self, indicator):
"""
Delete an indicator from the user's company's whitelist.
:param indicator: An |Indicator| object, representing the indicator to delete.
"""
params = indicator.to_dict()
self._client.delete("whitelist", params=params) | [
"def",
"delete_indicator_from_whitelist",
"(",
"self",
",",
"indicator",
")",
":",
"params",
"=",
"indicator",
".",
"to_dict",
"(",
")",
"self",
".",
"_client",
".",
"delete",
"(",
"\"whitelist\"",
",",
"params",
"=",
"params",
")"
] | Delete an indicator from the user's company's whitelist.
:param indicator: An |Indicator| object, representing the indicator to delete. | [
"Delete",
"an",
"indicator",
"from",
"the",
"user",
"s",
"company",
"s",
"whitelist",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L370-L378 | train | 43,798 |
trustar/trustar-python | trustar/indicator_client.py | IndicatorClient.get_community_trends | def get_community_trends(self, indicator_type=None, days_back=None):
"""
Find indicators that are trending in the community.
:param indicator_type: A type of indicator to filter by. If ``None``, will get all types of indicators except
for MALWARE and CVEs (this convention is for parity with the corresponding view on the Dashboard).
:param days_back: The number of days back to search. Any integer between 1 and 30 is allowed.
:return: A list of |Indicator| objects.
"""
params = {
'type': indicator_type,
'daysBack': days_back
}
resp = self._client.get("indicators/community-trending", params=params)
body = resp.json()
# parse items in response as indicators
return [Indicator.from_dict(indicator) for indicator in body] | python | def get_community_trends(self, indicator_type=None, days_back=None):
"""
Find indicators that are trending in the community.
:param indicator_type: A type of indicator to filter by. If ``None``, will get all types of indicators except
for MALWARE and CVEs (this convention is for parity with the corresponding view on the Dashboard).
:param days_back: The number of days back to search. Any integer between 1 and 30 is allowed.
:return: A list of |Indicator| objects.
"""
params = {
'type': indicator_type,
'daysBack': days_back
}
resp = self._client.get("indicators/community-trending", params=params)
body = resp.json()
# parse items in response as indicators
return [Indicator.from_dict(indicator) for indicator in body] | [
"def",
"get_community_trends",
"(",
"self",
",",
"indicator_type",
"=",
"None",
",",
"days_back",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'type'",
":",
"indicator_type",
",",
"'daysBack'",
":",
"days_back",
"}",
"resp",
"=",
"self",
".",
"_client",
"."... | Find indicators that are trending in the community.
:param indicator_type: A type of indicator to filter by. If ``None``, will get all types of indicators except
for MALWARE and CVEs (this convention is for parity with the corresponding view on the Dashboard).
:param days_back: The number of days back to search. Any integer between 1 and 30 is allowed.
:return: A list of |Indicator| objects. | [
"Find",
"indicators",
"that",
"are",
"trending",
"in",
"the",
"community",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L380-L399 | train | 43,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.