code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
self._request_params = {'input': input}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if types:
... | def autocomplete(self, input, lat_lng=None, location=None, radius=3200,
language=lang.ENGLISH, types=None, components=[]) | Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict con... | 2.756356 | 2.898343 | 0.951011 |
if keyword is None and name is None and len(types) is 0:
raise ValueError('One of keyword, name or types must be supplied.')
if location is None and lat_lng is None:
raise ValueError('One of location or lat_lng must be passed in.')
try:
radius = int(r... | def radar_search(self, sensor=False, keyword=None, name=None,
language=lang.ENGLISH, lat_lng=None, opennow=False,
radius=3200, type=None, types=[], location=None) | Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, an... | 2.451072 | 2.54631 | 0.962597 |
data = {'placeid': place_id}
url, checkin_response = _fetch_remote_json(
GooglePlaces.CHECKIN_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(data), use_http_post=True)
_validate_response(url, checkin_response) | def checkin(self, place_id, sensor=False) | Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False). | 7.208839 | 7.63393 | 0.944316 |
place_details = _get_place_details(place_id,
self.api_key, sensor, language=language)
return Place(self, place_details) | def get_place(self, place_id, sensor=False, language=lang.ENGLISH) | Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicat... | 4.231815 | 7.254784 | 0.583314 |
required_kwargs = {'name': [str], 'lat_lng': [dict],
'accuracy': [int], 'types': [str, list]}
request_params = {}
for key in required_kwargs:
if key not in kwargs or kwargs[key] is None:
raise ValueError('The %s argument is required... | def add_place(self, **kwargs) | Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
... | 3.029236 | 2.72911 | 1.109972 |
request_params = {'place_id': place_id}
url, delete_response = _fetch_remote_json(
GooglePlaces.DELETE_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, delete_response) | def delete_place(self, place_id, sensor=False) | Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
... | 6.995019 | 6.551627 | 1.067677 |
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types | def types(self) | Returns a list of feature types describing the given result. | 7.277732 | 6.805604 | 1.069374 |
if self._place is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
place = _get_place_details(
self.pla... | def get_details(self, language=None) | Retrieves full information on the place matching the place_id.
Stores the response in the `place` property. | 4.00203 | 3.498663 | 1.143874 |
if self._icon == '' and self.details != None and 'icon' in self.details:
self._icon = self.details['icon']
return self._icon | def icon(self) | Returns the URL of a recommended icon for display. | 3.766361 | 3.118995 | 1.207556 |
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name | def name(self) | Returns the human-readable name of the place. | 3.548166 | 2.900116 | 1.223457 |
if self._vicinity == '' and self.details != None and 'vicinity' in self.details:
self._vicinity = self.details['vicinity']
return self._vicinity | def vicinity(self) | Returns a feature name of a nearby location.
Often this feature refers to a street or neighborhood within the given
results. | 3.304964 | 3.445233 | 0.959286 |
if self._rating == '' and self.details != None and 'rating' in self.details:
self._rating = self.details['rating']
return self._rating | def rating(self) | Returns the Place's rating, from 0.0 to 5.0, based on user reviews.
This method will return None for places that have no rating. | 3.792635 | 3.602756 | 1.052704 |
self._query_instance.checkin(self.place_id,
self._query_instance.sensor) | def checkin(self) | Checks in an anonymous user in. | 17.501377 | 16.547939 | 1.057617 |
if self._details is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
self._details = _get_place_details(
... | def get_details(self, language=None) | Retrieves full information on the place matching the place_id.
Further attributes will be made available on the instance once this
method has been invoked.
keyword arguments:
language -- The language code, indicating in which language the
results should be returned,... | 4.023024 | 3.770149 | 1.067073 |
if not maxheight and not maxwidth:
raise GooglePlacesError('You must specify maxheight or maxwidth!')
result = _get_place_photo(self.photo_reference,
self._query_instance.api_key,
maxheight=maxheight, maxwidth=maxw... | def get(self, maxheight=None, maxwidth=None, sensor=False) | Fetch photo from API. | 5.220582 | 4.75826 | 1.097162 |
# type: (bytes, Tuple[int, int], int, Optional[str]) -> Optional[bytes]
width, height = size
line = width * 3
png_filter = struct.pack(">B", 0)
scanlines = b"".join(
[png_filter + data[y * line : y * line + line] for y in range(height)]
)
magic = struct.pack(">8B", 137, 80, 78... | def to_png(data, size, level=6, output=None) | Dump data to a PNG file. If `output` is `None`, create no file but return
the whole PNG data.
:param bytes data: RGBRGB...RGB data.
:param tuple size: The (width, height) pair.
:param int level: PNG compression level.
:param str output: Output file name. | 1.924654 | 1.971253 | 0.976361 |
# type: () -> None
def cfactory(func, argtypes, restype):
# type: (str, List[Any], Any) -> None
self._cfactory(
attr=self.core, func=func, argtypes=argtypes, restype=restype
)
uint32 = ctypes.c_uint32
void = ctyp... | def _set_cfunctions(self) | Set all ctypes functions and attach them to attributes. | 2.021688 | 2.037845 | 0.992072 |
# type: () -> Monitors
if not self._monitors:
int_ = int
core = self.core
# All monitors
# We need to update the value with every single monitor found
# using CGRectUnion. Else we will end with infinite values.
all_monit... | def monitors(self) | Get positions of monitors (see parent class). | 3.10276 | 3.133069 | 0.990326 |
# type: (Monitor) -> ScreenShot
# pylint: disable=too-many-locals
# Convert PIL bbox style
if isinstance(monitor, tuple):
monitor = {
"left": monitor[0],
"top": monitor[1],
"width": monitor[2] - monitor[0],
... | def grab(self, monitor) | See :meth:`MSSMixin.grab <mss.base.MSSMixin.grab>` for full details. | 2.639365 | 2.673209 | 0.98734 |
# type: (bytearray, int, int) -> ScreenShot
monitor = {"left": 0, "top": 0, "width": width, "height": height}
return cls(data, monitor) | def from_size(cls, data, width, height) | Instantiate a new class given only screen shot's data and size. | 4.489896 | 4.179542 | 1.074255 |
# type: () -> Pixels
if not self.__pixels:
rgb_tuples = zip(
self.raw[2::4], self.raw[1::4], self.raw[0::4]
) # type: Iterator[Pixel]
self.__pixels = list(zip(*[iter(rgb_tuples)] * self.width)) # type: ignore
return self.__pixels | def pixels(self) | :return list: RGB tuples. | 3.809611 | 3.778973 | 1.008107 |
# type: () -> bytes
if not self.__rgb:
rgb = bytearray(self.height * self.width * 3)
raw = self.raw
rgb[0::3] = raw[2::4]
rgb[1::3] = raw[1::4]
rgb[2::3] = raw[0::4]
self.__rgb = bytes(rgb)
return self.__rgb | def rgb(self) | Compute RGB values from the BGRA raw pixels.
:return bytes: RGB pixels. | 2.499783 | 2.71295 | 0.921426 |
# type: (int, int) -> Pixel
try:
return self.pixels[coord_y][coord_x] # type: ignore
except IndexError:
raise ScreenShotError(
"Pixel location ({}, {}) is out of range.".format(coord_x, coord_y)
) | def pixel(self, coord_x, coord_y) | Returns the pixel value at a given position.
:param int coord_x: The x coordinate.
:param int coord_y: The y coordinate.
:return tuple: The pixel value as (R, G, B). | 3.679286 | 4.442433 | 0.828214 |
# type: (Optional[List[str]]) -> int
cli_args = ArgumentParser()
cli_args.add_argument(
"-c",
"--coordinates",
default="",
type=str,
help="the part of the screen to capture: top, left, width, height",
)
cli_args.add_argument(
"-l",
"--lev... | def main(args=None) | Main logic. | 2.281898 | 2.278322 | 1.00157 |
# type: (Any, Any) -> int
evt = event.contents
ERROR.details = {
"type": evt.type,
"serial": evt.serial,
"error_code": evt.error_code,
"request_code": evt.request_code,
"minor_code": evt.minor_code,
}
return 0 | def error_handler(_, event) | Specifies the program's supplied error handler. | 5.152556 | 5.028472 | 1.024676 |
# type: (int, Any, Tuple[Any, Any]) -> Optional[Tuple[Any, Any]]
if retval != 0 and not ERROR.details:
return args
err = "{}() failed".format(func.__name__)
details = {"retval": retval, "args": args}
raise ScreenShotError(err, details=details) | def validate(retval, func, args) | Validate the returned value of a Xlib or XRANDR function. | 6.31192 | 6.478781 | 0.974245 |
def cfactory(attr=self.xlib, func=None, argtypes=None, restype=None):
# type: (Any, str, List[Any], Any) -> None
self._cfactory(
attr=attr,
errcheck=validate,
func=func,
argtypes=argtypes,
... | def _set_cfunctions(self) | Set all ctypes functions and attach them to attributes.
See https://tronche.com/gui/x/xlib/function-index.html for details. | 2.581787 | 2.532644 | 1.019404 |
# type: () -> Optional[Dict[str, Any]]
details = {} # type: Dict[str, Any]
if ERROR.details:
details = {"xerror_details": ERROR.details}
ERROR.details = None
xserver_error = ctypes.create_string_buffer(1024)
self.xlib.XGetErrorText(
... | def get_error_details(self) | Get more information about the latest X server error. | 3.915702 | 3.802524 | 1.029764 |
# type: () -> Monitors
if not self._monitors:
display = MSS.display
int_ = int
xrandr = self.xrandr
# All monitors
gwa = XWindowAttributes()
self.xlib.XGetWindowAttributes(display, self.root, ctypes.byref(gwa))
... | def monitors(self) | Get positions of monitors (see parent class property). | 3.145526 | 3.133867 | 1.00372 |
# type: (Monitor) -> ScreenShot
# Convert PIL bbox style
if isinstance(monitor, tuple):
monitor = {
"left": monitor[0],
"top": monitor[1],
"width": monitor[2] - monitor[0],
"height": monitor[3] - monitor[1],
... | def grab(self, monitor) | Retrieve all pixels from a monitor. Pixels have to be RGB. | 3.551561 | 3.548736 | 1.000796 |
# type: (str) -> None
if os.path.isfile(fname):
newfile = fname + ".old"
print("{} -> {}".format(fname, newfile))
os.rename(fname, newfile) | def on_exists(fname) | Callback example when we try to overwrite an existing screenshot. | 3.856989 | 3.905735 | 0.987519 |
# type: (int, str, Callable[[str], None]) -> Iterator[str]
monitors = self.monitors
if not monitors:
raise ScreenShotError("No monitor found.")
if mon == 0:
# One screen shot by monitor
for idx, monitor in enumerate(monitors[1:], 1):
... | def save(self, mon=0, output="monitor-{mon}.png", callback=None) | Grab a screen shot and save it to a file.
:param int mon: The monitor to screen shot (default=0).
-1: grab one screen shot of all monitors
0: grab one screen shot by monitor
N: grab the screen shot of the monitor N
:param str out... | 3.064772 | 2.800916 | 1.094204 |
# type: (Any) -> str
kwargs["mon"] = kwargs.get("mon", 1)
return next(self.save(**kwargs)) | def shot(self, **kwargs) | Helper to save the screen shot of the 1st monitor, by default.
You can pass the same arguments as for ``save``. | 13.738683 | 10.68077 | 1.286301 |
# type: (Any, str, List[Any], Any, Optional[Callable]) -> None
meth = getattr(attr, func)
meth.argtypes = argtypes
meth.restype = restype
if errcheck:
meth.errcheck = errcheck | def _cfactory(attr, func, argtypes, restype, errcheck=None) | Factory to create a ctypes function and automatically manage errors. | 3.166888 | 3.655634 | 0.866303 |
void = ctypes.c_void_p
pointer = ctypes.POINTER
self._cfactory(
attr=self.user32, func="GetSystemMetrics", argtypes=[INT], restype=INT
)
self._cfactory(
attr=self.user32,
func="EnumDisplayMonitors",
argtypes=[HDC, void, s... | def _set_cfunctions(self) | Set all ctypes functions and attach them to attributes. | 1.937356 | 1.883621 | 1.028527 |
version = sys.getwindowsversion()[:2] # pylint: disable=no-member
if version >= (6, 3):
# Windows 8.1+
# Here 2 = PROCESS_PER_MONITOR_DPI_AWARE, which means:
# per monitor DPI aware. This app checks for the DPI when it is
# created and a... | def _set_dpi_awareness(self) | Set DPI aware to capture full screen on Hi-DPI monitors. | 6.138725 | 5.757597 | 1.066196 |
# type: () -> Monitors
if not self._monitors:
int_ = int
user32 = self.user32
get_system_metrics = user32.GetSystemMetrics
# All monitors
self._monitors.append(
{
"left": int_(get_system_metrics(76... | def monitors(self) | Get positions of monitors (see parent class). | 2.953493 | 2.916119 | 1.012816 |
# type: (Monitor) -> ScreenShot
# Convert PIL bbox style
if isinstance(monitor, tuple):
monitor = {
"left": monitor[0],
"top": monitor[1],
"width": monitor[2] - monitor[0],
"height": monitor[3] - monitor[1],
... | def grab(self, monitor) | Retrieve all pixels from a monitor. Pixels have to be RGB.
In the code, there are few interesting things:
[1] bmi.bmiHeader.biHeight = -height
A bottom-up DIB is specified by setting the height to a
positive number, while a top-down DIB is specified by
sett... | 3.278704 | 3.133801 | 1.046238 |
# type: (Any) -> MSSMixin
os_ = platform.system().lower()
if os_ == "darwin":
from . import darwin
return darwin.MSS(**kwargs)
if os_ == "linux":
from . import linux
return linux.MSS(**kwargs)
if os_ == "windows":
from . import windows
retu... | def mss(**kwargs) | Factory returning a proper MSS class instance.
It detects the plateform we are running on
and choose the most adapted mss_class to take
screenshots.
It then proxies its arguments to the class for
instantiation. | 3.500383 | 3.648004 | 0.959534 |
while vH < 0: vH += 1
while vH > 1: vH -= 1
if 6 * vH < 1: return v1 + (v2 - v1) * 6 * vH
if 2 * vH < 1: return v2
if 3 * vH < 2: return v1 + (v2 - v1) * ((2.0 / 3) - vH) * 6
return v1 | def _hue2rgb(v1, v2, vH) | Private helper function (Do not call directly)
:param vH: rotation around the chromatic circle (between 0..1) | 1.51194 | 1.618844 | 0.933962 |
hx = ''.join(["%02x" % int(c * 255 + 0.5 - FLOAT_ERROR)
for c in rgb])
if not force_long and hx[0::2] == hx[1::2]:
hx = ''.join(hx[0::2])
return "#%s" % hx | def rgb2hex(rgb, force_long=False) | Transform RGB tuple to hex RGB representation
:param rgb: RGB 3-uple of float between 0 and 1
:rtype: 3 hex char or 6 hex char string representation
Usage
-----
>>> from colour import rgb2hex
>>> rgb2hex((0.0,1.0,0.0))
'#0f0'
Rounding try to be as natural as possible:
>>> rgb2h... | 4.153358 | 5.289968 | 0.785138 |
try:
rgb = str_rgb[1:]
if len(rgb) == 6:
r, g, b = rgb[0:2], rgb[2:4], rgb[4:6]
elif len(rgb) == 3:
r, g, b = rgb[0] * 2, rgb[1] * 2, rgb[2] * 2
else:
raise ValueError()
except:
raise ValueError("Invalid value %r provided for rgb... | def hex2rgb(str_rgb) | Transform hex RGB representation to RGB tuple
:param str_rgb: 3 hex char or 6 hex char string representation
:rtype: RGB 3-uple of float between 0 and 1
>>> from colour import hex2rgb
>>> hex2rgb('#00ff00')
(0.0, 1.0, 0.0)
>>> hex2rgb('#0f0')
(0.0, 1.0, 0.0)
>>> hex2rgb('#aaa') # d... | 2.050815 | 1.894263 | 1.082646 |
dec_rgb = tuple(int(v * 255) for v in hex2rgb(hex))
if dec_rgb in RGB_TO_COLOR_NAMES:
## take the first one
color_name = RGB_TO_COLOR_NAMES[dec_rgb][0]
## Enforce full lowercase for single worded color name.
return color_name if len(re.sub(r"[^A-Z]", "", color_name)) > 1 \
... | def hex2web(hex) | Converts HEX representation to WEB
:param rgb: 3 hex char or 6 hex char string representation
:rtype: web string representation (human readable if possible)
WEB representation uses X11 rgb.txt to define conversion
between RGB and english color names.
Usage
=====
>>> from colour import he... | 4.268029 | 4.326445 | 0.986498 |
if web.startswith('#'):
if (LONG_HEX_COLOR.match(web) or
(not force_long and SHORT_HEX_COLOR.match(web))):
return web.lower()
elif SHORT_HEX_COLOR.match(web) and force_long:
return '#' + ''.join([("%s" % (t, )) * 2 for t in web[1:]])
raise AttributeEr... | def web2hex(web, force_long=False) | Converts WEB representation to HEX
:param rgb: web string representation (human readable if possible)
:rtype: 3 hex char or 6 hex char string representation
WEB representation uses X11 rgb.txt to define conversion
between RGB and english color names.
Usage
=====
>>> from colour import we... | 4.136449 | 3.882807 | 1.065324 |
if nb < 0:
raise ValueError(
"Unsupported negative number of colors (nb=%r)." % nb)
step = tuple([float(end_hsl[i] - begin_hsl[i]) / nb for i in range(0, 3)]) \
if nb > 0 else (0, 0, 0)
def mul(step, value):
return tuple([v * value for v in step])
def add_... | def color_scale(begin_hsl, end_hsl, nb) | Returns a list of nb color HSL tuples between begin_hsl and end_hsl
>>> from colour import color_scale
>>> [rgb2hex(hsl2rgb(hsl)) for hsl in color_scale((0, 1, 0.5),
... (1, 1, 0.5), 3)]
['#f00', '#0f0', '#00f', '#f00']
>>> [rgb2hex(hsl2rgb(hsl))
... | 3.143154 | 2.838413 | 1.107363 |
## Turn the input into a by 3-dividable string. SHA-384 is good because it
## divides into 3 components of the same size, which will be used to
## represent the RGB values of the color.
digest = hashlib.sha384(str(obj).encode('utf-8')).hexdigest()
## Split the digest into 3 sub-strings of equ... | def RGB_color_picker(obj) | Build a color representation from the string representation of an object
This allows to quickly get a color from some data, with the
additional benefit that the color will be the same as long as the
(string representation of the) data is the same::
>>> from colour import RGB_color_picker, Color
... | 5.750794 | 5.881786 | 0.977729 |
# type: (List[AnyStr], Optional[AnyStr], Optional[Mapping[S, S]]) -> None
env = os.environ.copy()
if extra_environ:
env.update(extra_environ)
run(
cmd,
cwd=cwd,
env=env,
block=True,
combine_stderr=True,
return_object=False,
write_to_s... | def pep517_subprocess_runner(cmd, cwd=None, extra_environ=None) | The default method of calling the wrapper subprocess. | 3.445209 | 3.678582 | 0.936559 |
# type: (str, Optional[str]) -> Distribution
if not os.path.exists(script_path):
raise FileNotFoundError(script_path)
target_cwd = os.path.dirname(os.path.abspath(script_path))
if egg_base is None:
egg_base = os.path.join(target_cwd, "reqlib-metadata")
with temp_path(), cd(targ... | def run_setup(script_path, egg_base=None) | Run a `setup.py` script with a target **egg_base** if provided.
:param S script_path: The path to the `setup.py` script to run
:param Optional[S] egg_base: The metadata directory to build in
:raises FileNotFoundError: If the provided `script_path` does not exist
:return: The metadata dictionary
:rt... | 3.257938 | 3.351026 | 0.972221 |
ctx.run(f"python setup.py clean")
dist = ROOT.joinpath("dist")
build = ROOT.joinpath("build")
print(f"[clean] Removing {dist} and {build}")
if dist.exists():
shutil.rmtree(str(dist))
if build.exists():
shutil.rmtree(str(build)) | def clean(ctx) | Clean previously built package artifacts. | 2.741307 | 2.593988 | 1.056793 |
if prebump not in REL_TYPES:
raise ValueError(f"{type_} not in {REL_TYPES}")
prebump = REL_TYPES.index(prebump)
version = bump_version(ctx, type_, log=True)
# Needs to happen before Towncrier deletes fragment files.
tag_release(version, yes=yes)
ctx.run(f"python setup.py sdist bdi... | def release(ctx, type_, repo, prebump=PREBUMP, yes=False) | Make a new release. | 4.982463 | 4.912604 | 1.01422 |
filepath = pathlib.Path(filepath)
if not filepath.is_file():
log("profile", f"no such script {filepath!s}", LogLevel.ERROR)
else:
if calltree:
log("profile", f"profiling script {filepath!s} calltree")
ctx.run(
(
f"python -m cP... | def profile(ctx, filepath, calltree=False) | Run and profile a given Python script.
:param str filepath: The filepath of the script to profile | 3.44794 | 3.496806 | 0.986026 |
extra_indexes = []
preceding_operators = ["and"] if elem_name == "extra" else ["and", "or"]
for i, element in enumerate(elements):
if isinstance(element, list):
cancelled = _strip_marker_elem(elem_name, element)
if cancelled:
extra_indexes.append(i)
... | def _strip_marker_elem(elem_name, elements) | Remove the supplied element from the marker.
This is not a comprehensive implementation, but relies on an important
characteristic of metadata generation: The element's operand is always
associated with an "and" operator. This means that we can simply remove the
operand and the "and" operator associate... | 3.695964 | 3.368212 | 1.097307 |
if not marker:
return None
marker = _ensure_marker(marker)
elements = marker._markers
strip_func(elements)
if elements:
return marker
return None | def _get_stripped_marker(marker, strip_func) | Build a new marker which is cleaned according to `strip_func` | 6.402431 | 5.856784 | 1.093165 |
if not marker:
return set()
extras = set()
marker = _ensure_marker(marker)
_markers_collect_extras(marker._markers, extras)
return extras | def get_contained_extras(marker) | Collect "extra == ..." operands from a marker.
Returns a list of str. Each str is a speficied extra in this marker. | 5.727271 | 7.070555 | 0.810017 |
collection = []
if not marker:
return set()
marker = _ensure_marker(marker)
# Collect the (Variable, Op, Value) tuples and string joiners from the marker
_markers_collect_pyversions(marker._markers, collection)
marker_str = " and ".join(sorted(collection))
if not marker_str:
... | def get_contained_pyversions(marker) | Collect all `python_version` operands from a marker. | 6.351284 | 5.913258 | 1.074075 |
if not marker:
return False
marker = _ensure_marker(marker)
return _markers_contains_extra(marker._markers) | def contains_extra(marker) | Check whehter a marker contains an "extra == ..." operand. | 6.44338 | 6.441805 | 1.000244 |
if not marker:
return False
marker = _ensure_marker(marker)
return _markers_contains_pyversion(marker._markers) | def contains_pyversion(marker) | Check whether a marker contains a python_version operand. | 7.11451 | 6.145157 | 1.157742 |
text = item.read_text(encoding='utf-8')
renames = LIBRARY_RENAMES
for k in LIBRARY_RENAMES.keys():
if k not in vendored_libs:
vendored_libs.append(k)
for lib in vendored_libs:
to_lib = lib
if lib in renames:
to_lib = renames[lib]
text = re.sub... | def rewrite_file_imports(item, vendored_libs, vendor_dir) | Rewrite 'import xxx' and 'from xxx import' for vendored_libs | 2.263871 | 2.208043 | 1.025284 |
R = 3963 # radius of Earth (miles)
lat1, lon1 = math.radians(a[0]), math.radians(a[1])
lat2, lon2 = math.radians(b[0]), math.radians(b[1])
return math.acos(math.sin(lat1) * math.sin(lat2) +
math.cos(lat1) * math.cos(lat2) * math.cos(lon1 - lon2)) * R | def distance(a, b) | Calculates distance between two latitude-longitude coordinates. | 1.746937 | 1.580743 | 1.105136 |
e = 0
for i in range(len(self.state)):
e += self.distance_matrix[self.state[i-1]][self.state[i]]
return e | def energy(self) | Calculates the length of the route. | 3.414677 | 2.678255 | 1.274963 |
return round(x, int(n - math.ceil(math.log10(abs(x))))) | def round_figures(x, n) | Returns x rounded to n significant figures. | 3.336861 | 3.638318 | 0.917144 |
if not fname:
date = datetime.datetime.now().strftime("%Y-%m-%dT%Hh%Mm%Ss")
fname = date + "_energy_" + str(self.energy()) + ".state"
with open(fname, "wb") as fh:
pickle.dump(self.state, fh) | def save_state(self, fname=None) | Saves state to pickle | 3.083598 | 3.116329 | 0.989497 |
with open(fname, 'rb') as fh:
self.state = pickle.load(fh) | def load_state(self, fname=None) | Loads state from pickle | 3.230803 | 3.167757 | 1.019902 |
self.Tmax = schedule['tmax']
self.Tmin = schedule['tmin']
self.steps = int(schedule['steps'])
self.updates = int(schedule['updates']) | def set_schedule(self, schedule) | Takes the output from `auto` and sets the attributes | 3.583896 | 3.335516 | 1.074465 |
if self.copy_strategy == 'deepcopy':
return copy.deepcopy(state)
elif self.copy_strategy == 'slice':
return state[:]
elif self.copy_strategy == 'method':
return state.copy()
else:
raise RuntimeError('No implementation found for ' +... | def copy_state(self, state) | Returns an exact copy of the provided state
Implemented according to self.copy_strategy, one of
* deepcopy : use copy.deepcopy (slow but reliable)
* slice: use list slices (faster but only works if state is list-like)
* method: use the state's copy() method | 3.310909 | 2.29921 | 1.440021 |
elapsed = time.time() - self.start
if step == 0:
print(' Temperature Energy Accept Improve Elapsed Remaining',
file=sys.stderr)
print('\r%12.5f %12.2f %s ' %
(T, E, time_string(elapse... | def default_update(self, step, T, E, acceptance, improvement) | Default update, outputs to stderr.
Prints the current temperature, energy, acceptance rate,
improvement rate, elapsed time, and remaining time.
The acceptance rate indicates the percentage of moves since the last
update that were accepted by the Metropolis algorithm. It includes
... | 2.869964 | 2.605627 | 1.101448 |
step = 0
self.start = time.time()
# Precompute factor for exponential cooling from Tmax to Tmin
if self.Tmin <= 0.0:
raise Exception('Exponential cooling requires a minimum "\
"temperature greater than zero.')
Tfactor = -math.log(self.Tmax / ... | def anneal(self) | Minimizes the energy of a system by simulated annealing.
Parameters
state : an initial arrangement of the system
Returns
(state, energy): the best state and energy found. | 3.048275 | 3.054043 | 0.998112 |
def run(T, steps):
E = self.energy()
prevState = self.copy_state(self.state)
prevEnergy = E
accepts, improves = 0, 0
for _ in range(steps):
self.move()
E = self.energy()
dE = E - pr... | def auto(self, minutes, steps=2000) | Explores the annealing landscape and
estimates optimal temperature settings.
Returns a dictionary suitable for the `set_schedule` method. | 2.947127 | 2.966124 | 0.993595 |
def load(self, shapefile=None):
if shapefile:
(shapeName, ext) = os.path.splitext(shapefile)
self.shapeName = shapeName
try:
self.shp = open("%s.shp" % shapeName, "rb")
except IOError:
raise ShapefileException("Unab... | Opens a shapefile from a filename or file-like
object. Normally this method would be called by the
constructor with the file object or file name as an
argument. | null | null | null | |
def __shpHeader(self):
if not self.shp:
raise ShapefileException("Shapefile Reader requires a shapefile or file-like object. (no shp file found")
shp = self.shp
# File length (16-bit word * 2 = bytes)
shp.seek(24)
self.shpLength = unpack(">i", shp.read... | Reads the header information from a .shp or .shx file. | null | null | null | |
def __shape(self):
f = self.__getFileObj(self.shp)
record = _Shape()
nParts = nPoints = zmin = zmax = mmin = mmax = None
(recNum, recLength) = unpack(">2i", f.read(8))
shapeType = unpack("<i", f.read(4))[0]
record.shapeType = shapeType
# For Null ... | Returns the header info and geometry for a single shape. | null | null | null | |
def __shapeIndex(self, i=None):
shx = self.shx
if not shx:
return None
if not self._offsets:
# File length (16-bit word * 2 = bytes) - header length
shx.seek(24)
shxRecordLength = (unpack(">i", shx.read(4))[0] * 2) - 100
... | Returns the offset in a .shp file for a shape based on information
in the .shx index file. | null | null | null | |
def shape(self, i=0):
shp = self.__getFileObj(self.shp)
i = self.__restrictIndex(i)
offset = self.__shapeIndex(i)
if not offset:
# Shx index not available so use the full list.
shapes = self.shapes()
return shapes[i]
shp.seek(... | Returns a shape object for a shape in the the geometry
record file. | null | null | null | |
def shapes(self):
shp = self.__getFileObj(self.shp)
shp.seek(100)
shapes = []
while shp.tell() < self.shpLength:
shapes.append(self.__shape())
return shapes | Returns all shapes in a shapefile. | null | null | null | |
def __dbfHeaderLength(self):
if not self.__dbfHdrLength:
if not self.dbf:
raise ShapefileException("Shapefile Reader requires a shapefile or file-like object. (no dbf file found)")
dbf = self.dbf
(self.numRecords, self.__dbfHdrLength) = \
... | Retrieves the header length of a dbf file header. | null | null | null | |
def __dbfHeader(self):
if not self.dbf:
raise ShapefileException("Shapefile Reader requires a shapefile or file-like object. (no dbf file found)")
dbf = self.dbf
headerLength = self.__dbfHeaderLength()
numFields = (headerLength - 33) // 32
for field in... | Reads a dbf header. Xbase-related code borrows heavily from ActiveState Python Cookbook Recipe 362715 by Raymond Hettinger | null | null | null | |
def __recordFmt(self):
if not self.numRecords:
self.__dbfHeader()
fmt = ''.join(['%ds' % fieldinfo[2] for fieldinfo in self.fields])
fmtSize = calcsize(fmt)
return (fmt, fmtSize) | Calculates the size of a .shp geometry record. | null | null | null | |
def __record(self):
f = self.__getFileObj(self.dbf)
recFmt = self.__recordFmt()
recordContents = unpack(recFmt[0], f.read(recFmt[1]))
if recordContents[0] != b(' '):
# deleted record
return None
record = []
for (name, typ, size, d... | Reads and returns a dbf record row as a list of values. | null | null | null | |
def record(self, i=0):
f = self.__getFileObj(self.dbf)
if not self.numRecords:
self.__dbfHeader()
i = self.__restrictIndex(i)
recSize = self.__recordFmt()[1]
f.seek(0)
f.seek(self.__dbfHeaderLength() + (i * recSize))
return self.__rec... | Returns a specific dbf record based on the supplied index. | null | null | null | |
def records(self):
if not self.numRecords:
self.__dbfHeader()
records = []
f = self.__getFileObj(self.dbf)
f.seek(self.__dbfHeaderLength())
for i in range(self.numRecords):
r = self.__record()
if r:
records.ap... | Returns all records in a dbf file. | null | null | null | |
def shapeRecord(self, i=0):
i = self.__restrictIndex(i)
return _ShapeRecord(shape=self.shape(i),
record=self.record(i)) | Returns a combination geometry and attribute record for the
supplied record index. | null | null | null | |
def shapeRecords(self):
shapeRecords = []
return [_ShapeRecord(shape=rec[0], record=rec[1]) \
for rec in zip(self.shapes(), self.records())] | Returns a list of combination geometry/attribute records for
all records in a shapefile. | null | null | null | |
def __shpFileLength(self):
# Start with header length
size = 100
# Calculate size of all shapes
for s in self._shapes:
# Add in record header and shape type fields
size += 12
# nParts and nPoints do not apply to all shapes
... | Calculates the file length of the shp file. | null | null | null | |
def __shapefileHeader(self, fileObj, headerType='shp'):
f = self.__getFileObj(fileObj)
f.seek(0)
# File code, Unused bytes
f.write(pack(">6i", 9994,0,0,0,0,0))
# File length (Bytes / 2 = 16-bit words)
if headerType == 'shp':
f.write(pack(">i",... | Writes the specified header type to the specified file-like object.
Several of the shapefile formats are so similar that a single generic
method to read or write them is warranted. | null | null | null | |
def __dbfHeader(self):
f = self.__getFileObj(self.dbf)
f.seek(0)
version = 3
year, month, day = time.localtime()[:3]
year -= 1900
# Remove deletion flag placeholder from fields
for field in self.fields:
if field[0].startswith("Deletio... | Writes the dbf header and field descriptors. | null | null | null | |
def __shxRecords(self):
f = self.__getFileObj(self.shx)
f.seek(100)
for i in range(len(self._shapes)):
f.write(pack(">i", self._offsets[i] // 2))
f.write(pack(">i", self._lengths[i])) | Writes the shx records. | null | null | null | |
def __dbfRecords(self):
f = self.__getFileObj(self.dbf)
for record in self.records:
if not self.fields[0][0].startswith("Deletion"):
f.write(b(' ')) # deletion flag
for (fieldName, fieldType, size, dec), value in zip(self.fields, record):
... | Writes the dbf records. | null | null | null | |
def point(self, x, y, z=0, m=0):
pointShape = _Shape(self.shapeType)
pointShape.points.append([x, y, z, m])
self._shapes.append(pointShape) | Creates a point shape. | null | null | null | |
def poly(self, parts=[], shapeType=POLYGON, partTypes=[]):
polyShape = _Shape(shapeType)
polyShape.parts = []
polyShape.points = []
for part in parts:
polyShape.parts.append(len(polyShape.points))
for point in part:
# Ensure point ... | Creates a shape that has multiple collections of points (parts)
including lines, polygons, and even multipoint shapes. If no shape type
is specified it defaults to 'polygon'. If no part types are specified
(which they normally won't be) then all parts default to the shape type. | null | null | null | |
def field(self, name, fieldType="C", size="50", decimal=0):
self.fields.append((name, fieldType, size, decimal)) | Adds a dbf field descriptor to the shapefile. | null | null | null | |
def record(self, *recordList, **recordDict):
record = []
fieldCount = len(self.fields)
# Compensate for deletion flag
if self.fields[0][0].startswith("Deletion"): fieldCount -= 1
if recordList:
[record.append(recordList[i]) for i in range(fieldCount)]
... | Creates a dbf attribute record. You can submit either a sequence of
field values or keyword arguments of field names and values. Before
adding records you must add fields for the record values using the
fields() method. If the record values exceed the number of fields the
extra ones ... | null | null | null | |
def saveShp(self, target):
if not hasattr(target, "write"):
target = os.path.splitext(target)[0] + '.shp'
if not self.shapeType:
self.shapeType = self._shapes[0].shapeType
self.shp = self.__getFileObj(target)
self.__shapefileHeader(self.shp, header... | Save an shp file. | null | null | null | |
def saveShx(self, target):
if not hasattr(target, "write"):
target = os.path.splitext(target)[0] + '.shx'
if not self.shapeType:
self.shapeType = self._shapes[0].shapeType
self.shx = self.__getFileObj(target)
self.__shapefileHeader(self.shx, header... | Save an shx file. | null | null | null | |
def saveDbf(self, target):
if not hasattr(target, "write"):
target = os.path.splitext(target)[0] + '.dbf'
self.dbf = self.__getFileObj(target)
self.__dbfHeader()
self.__dbfRecords() | Save a dbf file. | null | null | null | |
def save(self, target=None, shp=None, shx=None, dbf=None):
# TODO: Create a unique filename for target if None.
if shp:
self.saveShp(shp)
if shx:
self.saveShx(shx)
if dbf:
self.saveDbf(dbf)
elif target:
self.saveS... | Save the shapefile data to three files or
three file-like objects. SHP and DBF files can also
be written exclusively using saveShp, saveShx, and saveDbf respectively. | null | null | null | |
def delete(self, shape=None, part=None, point=None):
# shape, part, point
if shape and part and point:
del self._shapes[shape][part][point]
# shape, part
elif shape and part and not point:
del self._shapes[shape][part]
# shape
eli... | Deletes the specified part of any shape by specifying a shape
number, part number, or point number. | null | null | null | |
def point(self, x=None, y=None, z=None, m=None, shape=None, part=None, point=None, addr=None):
# shape, part, point
if shape and part and point:
try: self._shapes[shape]
except IndexError: self._shapes.append([])
try: self._shapes[shape][part]
... | Creates/updates a point shape. The arguments allows
you to update a specific point by shape, part, point of any
shape type. | null | null | null | |
def balance(self):
if len(self.records) > len(self._shapes):
self.null()
elif len(self.records) < len(self._shapes):
self.record() | Adds a corresponding empty attribute or null geometry record depending
on which type of record was created to make sure all three files
are in synch. | null | null | null | |
def __fieldNorm(self, fieldName):
if len(fieldName) > 11: fieldName = fieldName[:11]
fieldName = fieldName.upper()
fieldName.replace(' ', '_') | Normalizes a dbf field name to fit within the spec and the
expectations of certain ESRI software. | null | null | null | |
# Set a deadline by which time the diff must be complete.
if deadline == None:
# Unlike in most languages, Python counts time in seconds.
if self.Diff_Timeout <= 0:
deadline = sys.maxsize
else:
deadline = time.time() + self.Diff_Timeout
# Check for null inputs.
if... | def diff_main(self, text1, text2, checklines=True, deadline=None) | Find the differences between two texts. Simplifies the problem by
stripping any common prefix or suffix off the texts before diffing.
Args:
text1: Old string to be diffed.
text2: New string to be diffed.
checklines: Optional speedup flag. If present and false, then don't run
a lin... | 2.095952 | 1.799695 | 1.164615 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.