sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def unreserve_resources(role):
""" Unreserves all the resources for all the slaves for the role.
"""
state = dcos_agents_state()
if not state or 'slaves' not in state.keys():
return False
all_success = True
for agent in state['slaves']:
if not unreserve_resource(agent, role):
... | Unreserves all the resources for all the slaves for the role. | entailment |
def wait_for_service_endpoint(service_name, timeout_sec=120):
"""Checks the service url if available it returns true, on expiration
it returns false"""
master_count = len(get_all_masters())
return time_wait(lambda: service_available_predicate(service_name),
timeout_seconds=timeout_... | Checks the service url if available it returns true, on expiration
it returns false | entailment |
def task_states_predicate(service_name, expected_task_count, expected_task_states):
""" Returns whether the provided service_names's tasks have expected_task_count tasks
in any of expected_task_states. For example, if service 'foo' has 5 tasks which are
TASK_STAGING or TASK_RUNNING.
:param ... | Returns whether the provided service_names's tasks have expected_task_count tasks
in any of expected_task_states. For example, if service 'foo' has 5 tasks which are
TASK_STAGING or TASK_RUNNING.
:param service_name: the service name
:type service_name: str
:param expected_task_... | entailment |
def wait_for_service_tasks_state(
service_name,
expected_task_count,
expected_task_states,
timeout_sec=120
):
""" Returns once the service has at least N tasks in one of the specified state(s)
:param service_name: the service name
:type service_name: str
:par... | Returns once the service has at least N tasks in one of the specified state(s)
:param service_name: the service name
:type service_name: str
:param expected_task_count: the expected number of tasks in the specified state(s)
:type expected_task_count: int
:param expected_task_sta... | entailment |
def tasks_all_replaced_predicate(
service_name,
old_task_ids,
task_predicate=None
):
""" Returns whether ALL of old_task_ids have been replaced with new tasks
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids... | Returns whether ALL of old_task_ids have been replaced with new tasks
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use w... | entailment |
def tasks_missing_predicate(
service_name,
old_task_ids,
task_predicate=None
):
""" Returns whether any of old_task_ids are no longer present
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by g... | Returns whether any of old_task_ids are no longer present
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use when searchin... | entailment |
def wait_for_service_tasks_all_changed(
service_name,
old_task_ids,
task_predicate=None,
timeout_sec=120
):
""" Returns once ALL of old_task_ids have been replaced with new tasks
:param service_name: the service name
:type service_name: str
:param old_task_id... | Returns once ALL of old_task_ids have been replaced with new tasks
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use when... | entailment |
def wait_for_service_tasks_all_unchanged(
service_name,
old_task_ids,
task_predicate=None,
timeout_sec=30
):
""" Returns after verifying that NONE of old_task_ids have been removed or replaced from the service
:param service_name: the service name
:type service_name:... | Returns after verifying that NONE of old_task_ids have been removed or replaced from the service
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task... | entailment |
def docker_version(host=None, component='server'):
""" Return the version of Docker [Server]
:param host: host or IP of the machine Docker is running on
:type host: str
:param component: Docker component
:type component: str
:return: Docker version
:rtype: str
""... | Return the version of Docker [Server]
:param host: host or IP of the machine Docker is running on
:type host: str
:param component: Docker component
:type component: str
:return: Docker version
:rtype: str | entailment |
def create_docker_credentials_file(
username,
password,
file_name='docker.tar.gz'):
""" Create a docker credentials file.
Docker username and password are used to create a `{file_name}`
with `.docker/config.json` containing the credentials.
:param username: docker us... | Create a docker credentials file.
Docker username and password are used to create a `{file_name}`
with `.docker/config.json` containing the credentials.
:param username: docker username
:type username: str
:param password: docker password
:type password: str
:par... | entailment |
def distribute_docker_credentials_to_private_agents(
username,
password,
file_name='docker.tar.gz'):
""" Create and distributes a docker credentials file to all private agents
:param username: docker username
:type username: str
:param password: docker password
... | Create and distributes a docker credentials file to all private agents
:param username: docker username
:type username: str
:param password: docker password
:type password: str
:param file_name: credentials file name `docker.tar.gz` by default
:type file_name: str | entailment |
def prefetch_docker_image_on_private_agents(
image,
timeout=timedelta(minutes=5).total_seconds()):
""" Given a docker image. An app with the image is scale across the private
agents to ensure that the image is prefetched to all nodes.
:param image: docker image name
:type im... | Given a docker image. An app with the image is scale across the private
agents to ensure that the image is prefetched to all nodes.
:param image: docker image name
:type image: str
:param timeout: timeout for deployment wait in secs (default: 5m)
:type password: int | entailment |
def _get_options(options_file=None):
""" Read in options_file as JSON.
:param options_file: filename to return
:type options_file: str
:return: options as dictionary
:rtype: dict
"""
if options_file is not None:
with open(options_file, 'r') as opt_file:
... | Read in options_file as JSON.
:param options_file: filename to return
:type options_file: str
:return: options as dictionary
:rtype: dict | entailment |
def install_package(
package_name,
package_version=None,
service_name=None,
options_file=None,
options_json=None,
wait_for_completion=False,
timeout_sec=600,
expected_running_tasks=0
):
""" Install a package via the DC/OS library
:param packag... | Install a package via the DC/OS library
:param package_name: name of the package
:type package_name: str
:param package_version: version of the package (defaults to latest)
:type package_version: str
:param service_name: unique service name for the package
:type service_... | entailment |
def install_package_and_wait(
package_name,
package_version=None,
service_name=None,
options_file=None,
options_json=None,
wait_for_completion=True,
timeout_sec=600,
expected_running_tasks=0
):
""" Install a package via the DC/OS library and wait for c... | Install a package via the DC/OS library and wait for completion | entailment |
def package_installed(package_name, service_name=None):
""" Check whether the package package_name is currently installed.
:param package_name: package name
:type package_name: str
:param service_name: service_name
:type service_name: str
:return: True if installed, False o... | Check whether the package package_name is currently installed.
:param package_name: package name
:type package_name: str
:param service_name: service_name
:type service_name: str
:return: True if installed, False otherwise
:rtype: bool | entailment |
def uninstall_package(
package_name,
service_name=None,
all_instances=False,
wait_for_completion=False,
timeout_sec=600
):
""" Uninstall a package using the DC/OS library.
:param package_name: name of the package
:type package_name: str
:param service... | Uninstall a package using the DC/OS library.
:param package_name: name of the package
:type package_name: str
:param service_name: unique service name for the package
:type service_name: str
:param all_instances: uninstall all instances of package
:type all_instances: bo... | entailment |
def uninstall_package_and_wait(
package_name,
service_name=None,
all_instances=False,
wait_for_completion=True,
timeout_sec=600
):
""" Uninstall a package via the DC/OS library and wait for completion
:param package_name: name of the package
:type package_nam... | Uninstall a package via the DC/OS library and wait for completion
:param package_name: name of the package
:type package_name: str
:param service_name: unique service name for the package
:type service_name: str
:param all_instances: uninstall all instances of package
:t... | entailment |
def uninstall_package_and_data(
package_name,
service_name=None,
role=None,
principal=None,
zk_node=None,
timeout_sec=600):
""" Uninstall a package via the DC/OS library, wait for completion, and delete any persistent data
:param package_name: name of the pac... | Uninstall a package via the DC/OS library, wait for completion, and delete any persistent data
:param package_name: name of the package
:type package_name: str
:param service_name: unique service name for the package
:type service_name: str
:param role: role to use when deleting... | entailment |
def add_package_repo(
repo_name,
repo_url,
index=None,
wait_for_package=None,
expect_prev_version=None):
""" Add a repository to the list of package sources
:param repo_name: name of the repository to add
:type repo_name: str
:param repo_url: location... | Add a repository to the list of package sources
:param repo_name: name of the repository to add
:type repo_name: str
:param repo_url: location of the repository to add
:type repo_url: str
:param index: index (precedence) for this repository
:type index: int
:para... | entailment |
def remove_package_repo(repo_name, wait_for_package=None):
""" Remove a repository from the list of package sources
:param repo_name: name of the repository to remove
:type repo_name: str
:param wait_for_package: the package whose version should change after the repo is removed
:typ... | Remove a repository from the list of package sources
:param repo_name: name of the repository to remove
:type repo_name: str
:param wait_for_package: the package whose version should change after the repo is removed
:type wait_for_package: str, or None
:returns: True if success... | entailment |
def get_package_versions(package_name):
""" Returns the list of versions of a given package
:param package_name: name of the package
:type package_name: str
"""
package_manager = _get_package_manager()
pkg = package_manager.get_package_version(package_name, None)
return pkg.package_v... | Returns the list of versions of a given package
:param package_name: name of the package
:type package_name: str | entailment |
def cli(**args):
""" Shakedown is a DC/OS test-harness wrapper for the pytest tool.
"""
import shakedown
# Read configuration options from ~/.shakedown (if exists)
args = read_config(args)
# Set configuration defaults
args = set_config_defaults(args)
if args['quiet']:
shakedow... | Shakedown is a DC/OS test-harness wrapper for the pytest tool. | entailment |
def find_coverage(self, zoom):
"""
Returns the bounding box (minx, miny, maxx, maxy) of an adjacent
group of tiles at this zoom level.
"""
# Find a group of adjacent available tiles at this zoom level
rows = self._query('''SELECT tile_column, tile_row FROM tiles
... | Returns the bounding box (minx, miny, maxx, maxy) of an adjacent
group of tiles at this zoom level. | entailment |
def tile(self, z, x, y):
"""
Download the specified tile from `tiles_url`
"""
logger.debug(_("Download tile %s") % ((z, x, y),))
# Render each keyword in URL ({s}, {x}, {y}, {z}, {size} ... )
size = self.tilesize
s = self.tiles_subdomains[(x + y) % len(self.tiles_... | Download the specified tile from `tiles_url` | entailment |
def tile(self, z, x, y):
"""
Render the specified tile with Mapnik
"""
logger.debug(_("Render tile %s") % ((z, x, y),))
proj = GoogleProjection(self.tilesize, [z])
return self.render(proj.tile_bbox((z, x, y))) | Render the specified tile with Mapnik | entailment |
def render(self, bbox, width=None, height=None):
"""
Render the specified tile with Mapnik
"""
width = width or self.tilesize
height = height or self.tilesize
self._prepare_rendering(bbox, width=width, height=height)
# Render image with default Agg renderer
... | Render the specified tile with Mapnik | entailment |
def grid(self, z, x, y, fields, layer):
"""
Render the specified grid with Mapnik
"""
logger.debug(_("Render grid %s") % ((z, x, y),))
proj = GoogleProjection(self.tilesize, [z])
return self.render_grid(proj.tile_bbox((z, x, y)), fields, layer) | Render the specified grid with Mapnik | entailment |
def render_grid(self, bbox, grid_fields, layer, width=None, height=None):
"""
Render the specified grid with Mapnik
"""
width = width or self.tilesize
height = height or self.tilesize
self._prepare_rendering(bbox, width=width, height=height)
grid = mapnik.Grid(wi... | Render the specified grid with Mapnik | entailment |
def tile_at(self, zoom, position):
"""
Returns a tuple of (z, x, y)
"""
x, y = self.project_pixels(position, zoom)
return (zoom, int(x/self.tilesize), int(y/self.tilesize)) | Returns a tuple of (z, x, y) | entailment |
def project(self, lng_lat):
"""
Returns the coordinates in meters from WGS84
"""
(lng, lat) = lng_lat
x = lng * DEG_TO_RAD
lat = max(min(MAX_LATITUDE, lat), -MAX_LATITUDE)
y = lat * DEG_TO_RAD
y = log(tan((pi / 4) + (y / 2)))
return (x*EARTH_RADIUS... | Returns the coordinates in meters from WGS84 | entailment |
def string2rgba(cls, colorstring):
""" Convert #RRGGBBAA to an (R, G, B, A) tuple """
colorstring = colorstring.strip()
if colorstring[0] == '#':
colorstring = colorstring[1:]
if len(colorstring) < 6:
raise ValueError("input #%s is not in #RRGGBB format" % colorst... | Convert #RRGGBBAA to an (R, G, B, A) tuple | entailment |
def tileslist(self, bbox, zoomlevels):
"""
Build the tiles list within the bottom-left/top-right bounding
box (minx, miny, maxx, maxy) at the specified zoom levels.
Return a list of tuples (z,x,y)
"""
proj = GoogleProjection(self.tile_size, zoomlevels, self.tile_scheme)
... | Build the tiles list within the bottom-left/top-right bounding
box (minx, miny, maxx, maxy) at the specified zoom levels.
Return a list of tuples (z,x,y) | entailment |
def add_layer(self, tilemanager, opacity=1.0):
"""
Add a layer to be blended (alpha-composite) on top of the tile.
tilemanager -- a `TileManager` instance
opacity -- transparency factor for compositing
"""
assert has_pil, _("Cannot blend layers without python PIL")
... | Add a layer to be blended (alpha-composite) on top of the tile.
tilemanager -- a `TileManager` instance
opacity -- transparency factor for compositing | entailment |
def add_filter(self, filter_):
""" Add an image filter for post-processing """
assert has_pil, _("Cannot add filters without python PIL")
self.cache.basename += filter_.basename
self._filters.append(filter_) | Add an image filter for post-processing | entailment |
def tile(self, z_x_y):
"""
Return the tile (binary) content of the tile and seed the cache.
"""
(z, x, y) = z_x_y
logger.debug(_("tile method called with %s") % ([z, x, y]))
output = self.cache.read((z, x, y))
if output is None:
output = self.reader.t... | Return the tile (binary) content of the tile and seed the cache. | entailment |
def grid(self, z_x_y):
""" Return the UTFGrid content """
# sources.py -> MapnikRenderer -> grid
(z, x, y) = z_x_y
content = self.reader.grid(z, x, y, self.grid_fields, self.grid_layer)
return content | Return the UTFGrid content | entailment |
def _blend_layers(self, imagecontent, z_x_y):
"""
Merge tiles of all layers into the specified tile path
"""
(z, x, y) = z_x_y
result = self._tile_image(imagecontent)
# Paste each layer
for (layer, opacity) in self._layers:
try:
# Prepa... | Merge tiles of all layers into the specified tile path | entailment |
def _tile_image(self, data):
"""
Tile binary content as PIL Image.
"""
image = Image.open(BytesIO(data))
return image.convert('RGBA') | Tile binary content as PIL Image. | entailment |
def zoomlevels(self):
"""
Return the list of covered zoom levels, in ascending order
"""
zooms = set()
for coverage in self._bboxes:
for zoom in coverage[1]:
zooms.add(zoom)
return sorted(zooms) | Return the list of covered zoom levels, in ascending order | entailment |
def run(self, force=False):
"""
Build a MBTile file.
force -- overwrite if MBTiles file already exists.
"""
if os.path.exists(self.filepath):
if force:
logger.warn(_("%s already exists. Overwrite.") % self.filepath)
os.remove(self.file... | Build a MBTile file.
force -- overwrite if MBTiles file already exists. | entailment |
def grid_tiles(self, bbox, zoomlevel):
"""
Return a grid of (x, y) tuples representing the juxtaposition
of tiles on the specified ``bbox`` at the specified ``zoomlevel``.
"""
tiles = self.tileslist(bbox, [zoomlevel])
grid = {}
for (z, x, y) in tiles:
... | Return a grid of (x, y) tuples representing the juxtaposition
of tiles on the specified ``bbox`` at the specified ``zoomlevel``. | entailment |
def export_image(self, bbox, zoomlevel, imagepath):
"""
Writes to ``imagepath`` the tiles for the specified bounding box and zoomlevel.
"""
assert has_pil, _("Cannot export image without python PIL")
grid = self.grid_tiles(bbox, zoomlevel)
width = len(grid[0])
hei... | Writes to ``imagepath`` the tiles for the specified bounding box and zoomlevel. | entailment |
def _makeScriptOrder(gpos):
"""
Run therough GPOS and make an alphabetically
ordered list of scripts. If DFLT is in the list,
move it to the front.
"""
scripts = []
for scriptRecord in gpos.ScriptList.ScriptRecord:
scripts.append(scriptRecord.ScriptTag)
if "DFLT" in scripts:
... | Run therough GPOS and make an alphabetically
ordered list of scripts. If DFLT is in the list,
move it to the front. | entailment |
def _gatherDataFromLookups(gpos, scriptOrder):
"""
Gather kerning and classes from the applicable lookups
and return them in script order.
"""
lookupIndexes = _gatherLookupIndexes(gpos)
seenLookups = set()
kerningDictionaries = []
leftClassDictionaries = []
rightClassDictionaries = [... | Gather kerning and classes from the applicable lookups
and return them in script order. | entailment |
def _gatherLookupIndexes(gpos):
"""
Gather a mapping of script to lookup indexes
referenced by the kern feature for each script.
Returns a dictionary of this structure:
{
"latn" : [0],
"DFLT" : [0]
}
"""
# gather the indexes of the kern features
kernFe... | Gather a mapping of script to lookup indexes
referenced by the kern feature for each script.
Returns a dictionary of this structure:
{
"latn" : [0],
"DFLT" : [0]
} | entailment |
def _gatherKerningForLookup(gpos, lookupIndex):
"""
Gather the kerning and class data for a particular lookup.
Returns kerning, left clases, right classes.
The kerning dictionary is of this structure:
{
("a", "a") : 10,
((1, 1, 3), "a") : -20
}
The class dicti... | Gather the kerning and class data for a particular lookup.
Returns kerning, left clases, right classes.
The kerning dictionary is of this structure:
{
("a", "a") : 10,
((1, 1, 3), "a") : -20
}
The class dictionaries have this structure:
{
(1, 1, 3)... | entailment |
def _handleLookupType2Format1(subtable):
"""
Extract a kerning dictionary from a Lookup Type 2 Format 1.
"""
kerning = {}
coverage = subtable.Coverage.glyphs
valueFormat1 = subtable.ValueFormat1
pairSets = subtable.PairSet
for index, leftGlyphName in enumerate(coverage):
pairSet ... | Extract a kerning dictionary from a Lookup Type 2 Format 1. | entailment |
def _handleLookupType2Format2(subtable, lookupIndex, subtableIndex):
"""
Extract kerning, left class and right class dictionaries from a Lookup Type 2 Format 2.
"""
# extract the classes
leftClasses = _extractFeatureClasses(lookupIndex=lookupIndex, subtableIndex=subtableIndex, classDefs=subtable.Cla... | Extract kerning, left class and right class dictionaries from a Lookup Type 2 Format 2. | entailment |
def _mergeKerningDictionaries(kerningDictionaries):
"""
Merge all of the kerning dictionaries found into
one flat dictionary.
"""
# work through the dictionaries backwards since
# this uses an update to load the kerning. this
# will ensure that the script order is honored.
kerning = {}
... | Merge all of the kerning dictionaries found into
one flat dictionary. | entailment |
def _findSingleMemberGroups(classDictionaries):
"""
Find all classes that have only one member.
"""
toRemove = {}
for classDictionaryGroup in classDictionaries:
for classDictionary in classDictionaryGroup:
for name, members in list(classDictionary.items()):
if len... | Find all classes that have only one member. | entailment |
def _removeSingleMemberGroupReferences(kerning, leftGroups, rightGroups):
"""
Translate group names into glyph names in pairs
if the group only contains one glyph.
"""
new = {}
for (left, right), value in kerning.items():
left = leftGroups.get(left, left)
right = rightGroups.get(... | Translate group names into glyph names in pairs
if the group only contains one glyph. | entailment |
def _mergeClasses(classDictionaries):
"""
Look for classes that have the exact same list
of members and flag them for removal.
This returns left classes, left rename map,
right classes and right rename map.
The classes have the standard class structure.
The rename maps have this structure:
... | Look for classes that have the exact same list
of members and flag them for removal.
This returns left classes, left rename map,
right classes and right rename map.
The classes have the standard class structure.
The rename maps have this structure:
{
(1, 1, 3) : (2, 3, 4),
... | entailment |
def _setGroupNames(classes, classRename):
"""
Set the final names into the groups.
"""
groups = {}
for groupName, glyphList in classes.items():
groupName = classRename.get(groupName, groupName)
# if the glyph list has only one member,
# the glyph name will be used in the pair... | Set the final names into the groups. | entailment |
def _validateClasses(classes):
"""
Check to make sure that a glyph is not part of more than
one class. If this is found, an ExtractorError is raised.
"""
glyphToClass = {}
for className, glyphList in classes.items():
for glyphName in glyphList:
if glyphName not in glyphToClas... | Check to make sure that a glyph is not part of more than
one class. If this is found, an ExtractorError is raised. | entailment |
def _replaceRenamedPairMembers(kerning, leftRename, rightRename):
"""
Populate the renamed pair members into the kerning.
"""
renamedKerning = {}
for (left, right), value in kerning.items():
left = leftRename.get(left, left)
right = rightRename.get(right, right)
renamedKernin... | Populate the renamed pair members into the kerning. | entailment |
def _renameClasses(classes, prefix):
"""
Replace class IDs with nice strings.
"""
renameMap = {}
for classID, glyphList in classes.items():
if len(glyphList) == 0:
groupName = "%s_empty_lu.%d_st.%d_cl.%d" % (prefix, classID[0], classID[1], classID[2])
elif len(glyphList) ... | Replace class IDs with nice strings. | entailment |
def _extractFeatureClasses(lookupIndex, subtableIndex, classDefs, coverage=None):
"""
Extract classes for a specific lookup in a specific subtable.
This is relatively straightforward, except for class 0 interpretation.
Some fonts don't have class 0. Some fonts have a list of class
members that are c... | Extract classes for a specific lookup in a specific subtable.
This is relatively straightforward, except for class 0 interpretation.
Some fonts don't have class 0. Some fonts have a list of class
members that are clearly not all to be used in kerning pairs.
In the case of a missing class 0, the coverage... | entailment |
def _get_voters(cls, session, owner_id, poll_id, answer_id):
"""
https://vk.com/dev/polls.getVoters
"""
from .users import User
return session.fetch_items("polls.getVoters", User._get_users, count=100, owner_id=owner_id, poll_id=poll_id, answer_ids=answer_id) | https://vk.com/dev/polls.getVoters | entailment |
def add_include(self, name, module_spec):
"""Adds a module as an included module.
:param name:
Name under which the included module should be exposed in the
current module.
:param module_spec:
ModuleSpec of the included module.
"""
assert name... | Adds a module as an included module.
:param name:
Name under which the included module should be exposed in the
current module.
:param module_spec:
ModuleSpec of the included module. | entailment |
def link(self):
"""Link all the types in this module and all included modules."""
if self.linked:
return self
self.linked = True
included_modules = []
# Link includes
for include in self.includes.values():
included_modules.append(include.link().... | Link all the types in this module and all included modules. | entailment |
def compile(self, name, contents, path=None):
"""Compile the given Thrift document into a Python module.
The generated module contains,
.. py:attribute:: __services__
A collection of generated classes for all services defined in the
thrift file.
.. version... | Compile the given Thrift document into a Python module.
The generated module contains,
.. py:attribute:: __services__
A collection of generated classes for all services defined in the
thrift file.
.. versionchanged:: 1.0
Renamed from ``services`` ... | entailment |
def t_HEXCONSTANT(self, t):
r'0x[0-9A-Fa-f]+'
t.value = int(t.value, 16)
t.type = 'INTCONSTANT'
return t | r'0x[0-9A-Fa-f]+ | entailment |
def t_LITERAL(self, t):
r'(\"([^\\\n]|(\\.))*?\")|\'([^\\\n]|(\\.))*?\''
s = t.value[1:-1]
maps = {
't': '\t',
'r': '\r',
'n': '\n',
'\\': '\\',
'\'': '\'',
'"': '\"'
}
i = 0
length = len(s)
v... | r'(\"([^\\\n]|(\\.))*?\")|\'([^\\\n]|(\\.))*?\ | entailment |
def t_IDENTIFIER(self, t):
r'[a-zA-Z_](\.[a-zA-Z_0-9]|[a-zA-Z_0-9])*'
if t.value in THRIFT_KEYWORDS:
# Not an identifier after all.
t.type = t.value.upper()
return t | r'[a-zA-Z_](\.[a-zA-Z_0-9]|[a-zA-Z_0-9])* | entailment |
def input(self, data):
"""Reset the lexer and feed in new input.
:param data:
String of input data.
"""
# input(..) doesn't reset the lineno. We have to do that manually.
self._lexer.lineno = 1
return self._lexer.input(data) | Reset the lexer and feed in new input.
:param data:
String of input data. | entailment |
def from_json(cls, session, photo_json):
"""
https://vk.com/dev/objects/photo
"""
photo = cls()
photo.id = photo_json.get('id')
photo.album_id = photo_json.get('album_id')
photo.owner_id = photo_json.get('owner_id')
photo.user_id = photo_json.get('user_id'... | https://vk.com/dev/objects/photo | entailment |
def _get_photos(session, user_or_group_id):
"""
https://vk.com/dev/photos.getAll
"""
response = session.fetch_items("photos.getAll", Photo.from_json, count=200, owner_id=user_or_group_id)
return response | https://vk.com/dev/photos.getAll | entailment |
def _get_owner_cover_photo_upload_server(session, group_id, crop_x=0, crop_y=0, crop_x2=795, crop_y2=200):
"""
https://vk.com/dev/photos.getOwnerCoverPhotoUploadServer
"""
group_id = abs(group_id)
response = session.fetch("photos.getOwnerCoverPhotoUploadServer", group_id=group_id... | https://vk.com/dev/photos.getOwnerCoverPhotoUploadServer | entailment |
def _save_owner_cover_photo(session, hash, photo):
"""
https://vk.com/dev/photos.saveOwnerCoverPhoto
"""
response = session.fetch('photos.saveOwnerCoverPhoto', hash=hash, photo=photo)
return response | https://vk.com/dev/photos.saveOwnerCoverPhoto | entailment |
def _get_save_wall_photo(session, photo, server, hash, user_id=None, group_id=None):
"""
https://vk.com/dev/photos.saveWallPhoto
"""
if group_id < 0:
group_id = abs(group_id)
response = session.fetch("photos.saveWallPhoto", photo=photo, server=server, hash=hash, user... | https://vk.com/dev/photos.saveWallPhoto | entailment |
def _get_save_messages_photo(session, photo, server, hash):
"""
https://vk.com/dev/photos.saveMessagesPhoto
"""
response = session.fetch("photos.saveMessagesPhoto", photo=photo, server=server, hash=hash)[0]
return response['id'], response['owner_id'] | https://vk.com/dev/photos.saveMessagesPhoto | entailment |
def get_city(self):
"""
:return: City or None
"""
response = self._session.fetch("users.get", user_ids=self.id, fields="city")[0]
if response.get('city'):
return City.from_json(self._session, response.get('city')) | :return: City or None | entailment |
def get_country(self):
"""
:return: Country or None
"""
response = self._session.fetch("users.get", user_ids=self.id, fields="country")[0]
if response.get('country'):
return Country.from_json(self._session, response.get('country')) | :return: Country or None | entailment |
def get_followers(self):
"""
https://vk.com/dev/users.getFollowers
"""
response = self._session.fetch_items("users.getFollowers", self.from_json, self._session, count=1000, user_id=self.id, fields=self.USER_FIELDS)
return response | https://vk.com/dev/users.getFollowers | entailment |
def _get_user(session, slug_or_user_id):
"""
:param slug_or_user_id: str or int
:return: User
"""
user_json_items = session.fetch('users.get', user_ids=slug_or_user_id, fields=User.USER_FIELDS)
return User.from_json(session, user_json_items[0]) | :param slug_or_user_id: str or int
:return: User | entailment |
def get_data():
"""
Currently pretends to talk to an instrument and get back the magnitud
and phase of the measurement.
"""
# pretend we're measuring a noisy resonance at zero
y = 1.0 / (1.0 + 1j*(n_x.get_value()-0.002)*1000) + _n.random.rand()*0.1
# and that it takes time to do so
_t.... | Currently pretends to talk to an instrument and get back the magnitud
and phase of the measurement. | entailment |
def List(self):
"""
Lists the keys and values.
"""
print()
for key in list(self.keys()):
print(key,'=',self[key])
print() | Lists the keys and values. | entailment |
def Set(self, key, value):
"""
Sets the key-value pair and dumps to the preferences file.
"""
if not value == None: self.prefs[key] = value
else: self.prefs.pop(key)
self.Dump() | Sets the key-value pair and dumps to the preferences file. | entailment |
def MakeDir(self, path="temp"):
"""
Creates a directory of the specified path in the .spinmob directory.
"""
full_path = _os.path.join(self.path_home, path)
# only make it if it doesn't exist!
if not _os.path.exists(full_path): _os.makedirs(full_path) | Creates a directory of the specified path in the .spinmob directory. | entailment |
def ListDir(self, path="temp"):
"""
Returns a list of files in the specified path (directory), or an
empty list if the directory doesn't exist.
"""
full_path = _os.path.join(self.path_home, path)
# only if the path exists!
if _os.path.exists(full_path) and _os.pa... | Returns a list of files in the specified path (directory), or an
empty list if the directory doesn't exist. | entailment |
def _convert_list2str(self, fields):
"""
:param fields: ('bdate', 'domain')
:return: 'bdate,domain'
"""
if isinstance(fields, tuple) or isinstance(fields, list):
return ','.join(fields)
return fields | :param fields: ('bdate', 'domain')
:return: 'bdate,domain' | entailment |
def p_start(self, p):
'''start : header definition'''
p[0] = ast.Program(headers=p[1], definitions=p[2]) | start : header definition | entailment |
def p_include(self, p):
'''include : INCLUDE IDENTIFIER LITERAL
| INCLUDE LITERAL'''
if len(p) == 4:
p[0] = ast.Include(name=p[2], path=p[3], lineno=p.lineno(1))
else:
p[0] = ast.Include(name=None, path=p[2], lineno=p.lineno(1)) | include : INCLUDE IDENTIFIER LITERAL
| INCLUDE LITERAL | entailment |
def p_namespace(self, p):
'''namespace : NAMESPACE namespace_scope IDENTIFIER'''
p[0] = ast.Namespace(scope=p[2], name=p[3], lineno=p.lineno(1)) | namespace : NAMESPACE namespace_scope IDENTIFIER | entailment |
def p_const(self, p):
'''const : CONST field_type IDENTIFIER '=' const_value
| CONST field_type IDENTIFIER '=' const_value sep'''
p[0] = ast.Const(
name=p[3],
value_type=p[2],
value=p[5],
lineno=p.lineno(3),
) | const : CONST field_type IDENTIFIER '=' const_value
| CONST field_type IDENTIFIER '=' const_value sep | entailment |
def p_const_value_primitive(self, p):
'''const_value_primitive : INTCONSTANT
| DUBCONSTANT
| LITERAL
| const_bool'''
p[0] = ast.ConstPrimitiveValue(p[1], lineno=p.lineno(1)) | const_value_primitive : INTCONSTANT
| DUBCONSTANT
| LITERAL
| const_bool | entailment |
def p_const_list(self, p):
'''const_list : '[' const_list_seq ']' '''
p[0] = ast.ConstList(list(p[2]), p.lineno(1)) | const_list : '[' const_list_seq ']' | entailment |
def p_const_map(self, p):
'''const_map : '{' const_map_seq '}' '''
p[0] = ast.ConstMap(dict(p[2]), p.lineno(1)) | const_map : '{' const_map_seq '}' | entailment |
def p_const_ref(self, p):
'''const_ref : IDENTIFIER'''
p[0] = ast.ConstReference(p[1], lineno=p.lineno(1)) | const_ref : IDENTIFIER | entailment |
def p_typedef(self, p):
'''typedef : TYPEDEF field_type IDENTIFIER annotations'''
p[0] = ast.Typedef(
name=p[3], target_type=p[2], annotations=p[4], lineno=p.lineno(3)
) | typedef : TYPEDEF field_type IDENTIFIER annotations | entailment |
def p_enum(self, p): # noqa
'''enum : ENUM IDENTIFIER '{' enum_seq '}' annotations'''
p[0] = ast.Enum(
name=p[2], items=p[4], annotations=p[6], lineno=p.lineno(2)
) | enum : ENUM IDENTIFIER '{' enum_seq '}' annotations | entailment |
def p_enum_item(self, p):
'''enum_item : IDENTIFIER '=' INTCONSTANT annotations
| IDENTIFIER annotations'''
if len(p) == 5:
p[0] = ast.EnumItem(
name=p[1], value=p[3], annotations=p[4], lineno=p.lineno(1)
)
else:
p[0] = ast... | enum_item : IDENTIFIER '=' INTCONSTANT annotations
| IDENTIFIER annotations | entailment |
def p_struct(self, p):
'''struct : STRUCT IDENTIFIER '{' field_seq '}' annotations'''
p[0] = ast.Struct(
name=p[2], fields=p[4], annotations=p[6], lineno=p.lineno(2)
) | struct : STRUCT IDENTIFIER '{' field_seq '}' annotations | entailment |
def p_union(self, p):
'''union : UNION IDENTIFIER '{' field_seq '}' annotations'''
p[0] = ast.Union(
name=p[2], fields=p[4], annotations=p[6], lineno=p.lineno(2)
) | union : UNION IDENTIFIER '{' field_seq '}' annotations | entailment |
def p_exception(self, p):
'''exception : EXCEPTION IDENTIFIER '{' field_seq '}' annotations'''
p[0] = ast.Exc(
name=p[2], fields=p[4], annotations=p[6], lineno=p.lineno(2)
) | exception : EXCEPTION IDENTIFIER '{' field_seq '}' annotations | entailment |
def p_service(self, p):
'''service : SERVICE IDENTIFIER '{' function_seq '}' annotations
| SERVICE IDENTIFIER EXTENDS IDENTIFIER \
'{' function_seq '}' annotations
'''
if len(p) == 7:
p[0] = ast.Service(
name=p[2],
... | service : SERVICE IDENTIFIER '{' function_seq '}' annotations
| SERVICE IDENTIFIER EXTENDS IDENTIFIER \
'{' function_seq '}' annotations | entailment |
def p_function(self, p):
'''function : oneway function_type IDENTIFIER '(' field_seq ')' \
throws annotations '''
p[0] = ast.Function(
name=p[3],
parameters=p[5],
return_type=p[2],
exceptions=p[7],
oneway=p[1],
... | function : oneway function_type IDENTIFIER '(' field_seq ')' \
throws annotations | entailment |
def p_field(self, p):
'''field : field_id field_req field_type IDENTIFIER annotations
| field_id field_req field_type IDENTIFIER '=' const_value \
annotations'''
if len(p) == 8:
default = p[6]
annotations = p[7]
else:
defau... | field : field_id field_req field_type IDENTIFIER annotations
| field_id field_req field_type IDENTIFIER '=' const_value \
annotations | entailment |
def p_field_id(self, p):
'''field_id : INTCONSTANT ':'
| '''
if len(p) == 3:
if p[1] == 0:
# Prevent users from ever using field ID 0. It's reserved for
# internal use only.
raise ThriftParserError(
'Lin... | field_id : INTCONSTANT ':'
| | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.