code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
"Return a django.core.paginator.Page of results."
limit = options.get('limit', settings.SELECTABLE_MAX_LIMIT)
paginator = Paginator(results, limit)
page = options.get('page', 1)
try:
results = paginator.page(page)
except (EmptyPage, InvalidPage):
r... | def paginate_results(self, results, options) | Return a django.core.paginator.Page of results. | 2.860694 | 2.334857 | 1.225212 |
"Match results to given term and return the serialized HttpResponse."
results = {}
form = self.form(request.GET)
if form.is_valid():
options = form.cleaned_data
term = options.get('term', '')
raw_data = self.get_query(request, term)
results... | def results(self, request) | Match results to given term and return the serialized HttpResponse. | 4.973774 | 3.153954 | 1.576997 |
'''
Returns a python structure that later gets serialized.
raw_data
full list of objects matching the search term
options
a dictionary of the given options
'''
page_data = self.paginate_results(raw_data, options)
results = {}
meta =... | def format_results(self, raw_data, options) | Returns a python structure that later gets serialized.
raw_data
full list of objects matching the search term
options
a dictionary of the given options | 3.546672 | 2.153901 | 1.646627 |
from selectable.base import LookupBase
if isinstance(lookup_class, string_types):
mod_str, cls_str = lookup_class.rsplit('.', 1)
mod = import_module(mod_str)
lookup_class = getattr(mod, cls_str)
if not issubclass(lookup_class, LookupBase):
raise TypeError('lookup_class m... | def import_lookup_class(lookup_class) | Import lookup_class as a dotted base and ensure it extends LookupBase | 2.05948 | 1.929733 | 1.067236 |
"Ensure given limit is less than default if defined"
limit = self.cleaned_data.get('limit', None)
if (settings.SELECTABLE_MAX_LIMIT is not None and
(not limit or limit > settings.SELECTABLE_MAX_LIMIT)):
limit = settings.SELECTABLE_MAX_LIMIT
return limit | def clean_limit(self) | Ensure given limit is less than default if defined | 4.977926 | 3.514053 | 1.416577 |
# build request url
params = collections.OrderedDict()
params["gbv"] = "2"
params["q"] = "\"%s\" \"%s\" front cover" % (artist, album)
if abs(self.target_size - 500) < 300:
params["tbs"] = "isz:m"
elif self.target_size > 800:
params["tbs"] = "isz:l"
return __class__.assembl... | def getSearchUrl(self, album, artist) | See CoverSource.getSearchUrl. | 5.482882 | 5.284925 | 1.037457 |
results = []
# parse HTML and get results
parser = lxml.etree.HTMLParser()
html = lxml.etree.XML(api_data.decode("latin-1"), parser)
for rank, result in enumerate(__class__.RESULTS_SELECTOR(html), 1):
# extract url
metadata_div = result.find("div")
metadata_json = lxml.etree... | async def parseResults(self, api_data) | See CoverSource.parseResults. | 3.402377 | 3.263541 | 1.042541 |
async with self.lock:
while True:
last_access_ts = self.__getLastAccess()
if last_access_ts is not None:
now = time.time()
last_access_ts = last_access_ts[0]
time_since_last_access = now - last_access_ts
if time_since_last_access < self.min_delay_be... | async def waitAccessAsync(self) | Wait the needed time before sending a request to honor rate limit. | 3.38865 | 3.304513 | 1.025461 |
with self.connection:
self.connection.execute("INSERT OR REPLACE INTO access_timestamp (timestamp, domain) VALUES (?, ?)",
(ts, self.domain)) | def __access(self, ts) | Record an API access. | 6.151445 | 5.241507 | 1.173602 |
return aiohttp.ClientTimeout(total=None,
connect=None,
sock_connect=socket_timeout_s,
sock_read=socket_timeout_s) | def aiohttp_socket_timeout(socket_timeout_s) | Return a aiohttp.ClientTimeout object with only socket timeouts set. | 2.917072 | 2.323689 | 1.255362 |
async def store_in_cache_callback():
pass
if cache is not None:
# try from cache first
if post_data is not None:
if (url, post_data) in cache:
self.logger.debug("Got data for URL '%s' %s from cache" % (url, dict(post_data)))
return store_in_cache_callback, cach... | async def query(self, url, *, post_data=None, headers=None, verify=True, cache=None, pre_cache_callback=None) | Send a GET/POST request or get data from cache, retry if it fails, and return a tuple of store in cache callback, response content. | 2.947827 | 2.849373 | 1.034553 |
if (cache is not None) and (url in cache):
# try from cache first
self.logger.debug("Got headers for URL '%s' from cache" % (url))
resp_ok, response_headers = pickle.loads(cache[url])
return resp_ok
domain_rate_watcher = rate_watcher.AccessRateWatcher(self.watcher_db_filepath,
... | async def isReachable(self, url, *, headers=None, verify=True, response_headers=None, cache=None) | Send a HEAD request with short timeout or get data from cache, return True if ressource has 2xx status code, False instead. | 3.398748 | 3.309471 | 1.026976 |
response = await self.session.get(url,
headers=self._buildHeaders(headers),
timeout=HTTP_SHORT_TIMEOUT,
ssl=verify)
response.raise_for_status()
return response | async def fastStreamedQuery(self, url, *, headers=None, verify=True) | Send a GET request with short timeout, do not retry, and return streamed response. | 4.867872 | 3.733702 | 1.303766 |
# build request url
params = collections.OrderedDict()
params["method"] = "album.getinfo"
params["api_key"] = __class__.API_KEY
params["album"] = album
params["artist"] = artist
return __class__.assembleUrl(__class__.BASE_URL, params) | def getSearchUrl(self, album, artist) | See CoverSource.getSearchUrl. | 3.543509 | 3.350292 | 1.057672 |
char_blacklist = set(string.punctuation)
char_blacklist.remove("'")
char_blacklist.remove("&")
char_blacklist = frozenset(char_blacklist)
return __class__.unpunctuate(s.lower(), char_blacklist=char_blacklist) | def processQueryString(self, s) | See CoverSource.processQueryString. | 5.472283 | 5.337078 | 1.025333 |
results = []
# get xml results list
xml_text = api_data.decode("utf-8")
xml_root = xml.etree.ElementTree.fromstring(xml_text)
status = xml_root.get("status")
if status != "ok":
raise Exception("Unexpected Last.fm response status: %s" % (status))
img_elements = xml_root.findall("a... | async def parseResults(self, api_data) | See CoverSource.parseResults. | 3.531352 | 3.393615 | 1.040587 |
# register sources
source_args = (size, size_tolerance_prct)
cover_sources = [sources.LastFmCoverSource(*source_args),
sources.AmazonCdCoverSource(*source_args),
sources.AmazonDigitalCoverSource(*source_args)]
for tld in amazon_tlds:
cover_sources.append(sources.Amaz... | async def search_and_download(album, artist, format, size, out_filepath, *, size_tolerance_prct, amazon_tlds, no_lq_sources,
async_loop) | Search and download a cover, return True if success, False instead. | 2.850923 | 2.781927 | 1.024801 |
url = "%s/search" % (__class__.BASE_URL)
params = collections.OrderedDict()
params["search-alias"] = "digital-music"
params["field-keywords"] = " ".join((artist, album))
params["sort"] = "relevancerank"
return __class__.assembleUrl(url, params) | def getSearchUrl(self, album, artist) | See CoverSource.getSearchUrl. | 5.969135 | 5.783729 | 1.032057 |
results = []
# parse page
parser = lxml.etree.HTMLParser()
html = lxml.etree.XML(api_data.decode("utf-8"), parser)
for page_struct_version, result_selector in enumerate(__class__.RESULTS_SELECTORS):
result_nodes = result_selector(html)
if result_nodes:
break
for rank,... | async def parseResults(self, api_data) | See CoverSource.parseResults. | 5.833104 | 5.689994 | 1.025151 |
for x in range(slice_count):
for y in range(slice_count):
yield ("http://z2-ec2.images-amazon.com/R/1/a=" + product_id +
"+c=" + dynapi_key +
"+d=_SCR%28" + str(format_id) + "," + str(x) + "," + str(y) + "%29_=.jpg") | def generateImgUrls(self, product_id, dynapi_key, format_id, slice_count) | Generate URLs for slice_count^2 subimages of a product. | 7.190877 | 6.593605 | 1.090584 |
assert(max_attempts > 1)
assert(sleeptime >= 0)
assert(0 <= jitter <= sleeptime)
assert(sleepscale >= 1)
cur_sleeptime = min(max_sleeptime, sleeptime)
for attempt in range(max_attempts):
cur_jitter = random.randint(int(-jitter * 1000), int(jitter * 1000)) / 1000
yield max(0, cur_sleeptime + cur... | def retrier(*, max_attempts, sleeptime, max_sleeptime, sleepscale=1.5, jitter=0.2) | Generator yielding time to wait for, after the attempt, if it failed. | 2.213489 | 2.055659 | 1.076778 |
if self.source_quality.value <= CoverSourceQuality.LOW.value:
logging.getLogger("Cover").warning("Cover is from a potentially unreliable source and may be unrelated to the search")
images_data = []
for i, url in enumerate(self.urls):
# download
logging.getLogger("Cover").info("Downlo... | async def get(self, target_format, target_size, size_tolerance_prct, out_filepath) | Download cover and process it. | 4.076368 | 3.957857 | 1.029943 |
if len(images_data) == 1:
in_bytes = io.BytesIO(images_data[0])
img = PIL.Image.open(in_bytes)
if img.mode != "RGB":
img = img.convert("RGB")
else:
# images need to be joined before further processing
logging.getLogger("Cover").info("Joining %u images..." % (len(image... | def postProcess(self, images_data, new_format, new_size) | Convert image binary data to a target format and/or size (None if no conversion needed), and return the processed data. | 2.936589 | 2.934717 | 1.000638 |
assert(self.needMetadataUpdate())
width_sum, height_sum = 0, 0
# only download metadata for the needed images to get full size
idxs = []
assert(is_square(len(self.urls)))
sq = int(math.sqrt(len(self.urls)))
for x in range(sq):
for y in range(sq):
if x == y:
idx... | async def updateImageMetadata(self) | Partially download image file(s) to get its real metadata, or get it from cache. | 3.235178 | 3.162618 | 1.022943 |
assert((self.needMetadataUpdate(CoverImageMetadata.FORMAT)) or
(self.format is format))
self.format = format
self.check_metadata &= ~CoverImageMetadata.FORMAT | def setFormatMetadata(self, format) | Set format image metadata to what has been reliably identified. | 14.972317 | 14.955585 | 1.001119 |
assert((self.needMetadataUpdate(CoverImageMetadata.SIZE)) or
(self.size == size))
self.size = size
self.check_metadata &= ~CoverImageMetadata.SIZE | def setSizeMetadata(self, size) | Set size image metadata to what has been reliably identified. | 13.137888 | 12.566401 | 1.045477 |
assert(self.thumbnail_sig is None)
if self.thumbnail_url is None:
logging.getLogger("Cover").warning("No thumbnail available for %s" % (self))
return
# download
logging.getLogger("Cover").debug("Downloading cover thumbnail '%s'..." % (self.thumbnail_url))
headers = {}
self.sou... | async def updateSignature(self) | Calculate a cover's "signature" using its thumbnail url. | 3.666364 | 3.411572 | 1.074685 |
for c in (first, second):
assert(c.format is not None)
assert(isinstance(c.size[0], int) and isinstance(c.size[1], int))
# prefer square covers #1
delta_ratio1 = abs(first.size[0] / first.size[1] - 1)
delta_ratio2 = abs(second.size[0] / second.size[1] - 1)
if abs(delta_ratio1 - del... | def compare(first, second, *, target_size, size_tolerance_prct) | Compare cover relevance/quality.
Return -1 if first is a worst match than second, 1 otherwise, or 0 if cover can't be discriminated.
This code is responsible for comparing two cover results to identify the best one, and is used to sort all results.
It is probably the most important piece of code of this t... | 2.448941 | 1.98057 | 1.236483 |
if (((format is CoverImageFormat.PNG) and (not HAS_OPTIPNG)) or
((format is CoverImageFormat.JPEG) and (not HAS_JPEGOPTIM))):
return image_data
with mkstemp_ctx.mkstemp(suffix=".%s" % (format.name.lower())) as tmp_out_filepath:
if not silent:
logging.getLogger("Cover").info(... | async def crunch(image_data, format, silent=False) | Crunch image data, and return the processed data, or orignal data if operation failed. | 2.284969 | 2.247702 | 1.01658 |
format, width, height = None, None, None
img_stream = io.BytesIO(img_data)
try:
img = PIL.Image.open(img_stream)
except IOError:
format = imghdr.what(None, h=img_data)
format = SUPPORTED_IMG_FORMATS.get(format, None)
else:
format = img.format.lower()
format = SUPPO... | def guessImageMetadataFromData(img_data) | Identify an image format and size from its first bytes. | 2.271628 | 2.259923 | 1.00518 |
metadata = None
img_data = bytearray()
while len(img_data) < CoverSourceResult.MAX_FILE_METADATA_PEEK_SIZE:
new_img_data = await response.content.read(__class__.METADATA_PEEK_SIZE_INCREMENT)
if not new_img_data:
break
img_data.extend(new_img_data)
metadata = __class__.... | async def guessImageMetadataFromHttpData(response) | Identify an image format and size from the beginning of its HTTP data. | 4.556139 | 4.403642 | 1.03463 |
extensions = []
# try to guess extension from response content-type header
try:
content_type = response.headers["Content-Type"]
except KeyError:
pass
else:
ext = mimetypes.guess_extension(content_type, strict=False)
if ext is not None:
extensions.append(ext)
... | def guessImageFormatFromHttpResponse(response) | Guess file format from HTTP response, return format or None. | 2.577914 | 2.581778 | 0.998503 |
# find reference (=image most likely to match target cover ignoring factors like size and format)
reference = None
for result in results:
if result.source_quality is CoverSourceQuality.REFERENCE:
if ((reference is None) or
(CoverSourceResult.compare(result,
... | async def preProcessForComparison(results, target_size, size_tolerance_prct) | Process results to prepare them for future comparison and sorting. | 3.047148 | 3.025367 | 1.0072 |
parser = PIL.ImageFile.Parser()
parser.feed(image_data)
img = parser.close()
target_size = (__class__.IMG_SIG_SIZE, __class__.IMG_SIG_SIZE)
img.thumbnail(target_size, PIL.Image.BICUBIC)
if img.size != target_size:
logging.getLogger("Cover").debug("Non square thumbnail after resize to ... | def computeImgSignature(image_data) | Calculate an image signature.
This is similar to ahash but uses 3 colors components
See: https://github.com/JohannesBuchner/imagehash/blob/4.0/imagehash/__init__.py#L125 | 3.469667 | 3.47684 | 0.997937 |
work = {}
stats = collections.OrderedDict(((k, 0) for k in("files", "albums", "missing covers", "errors")))
with tqdm.tqdm(desc="Analyzing library",
unit="dir",
postfix=stats) as progress, \
tqdm_logging.redirect_logging(progress):
for rootpath, rel_dirpaths, rel... | def analyze_lib(lib_dir, cover_filename, *, ignore_existing=False) | Recursively analyze library, and return a dict of path -> (artist, album). | 5.205149 | 4.71732 | 1.103412 |
artist, album, has_embedded_album_art = None, None, None
for audio_filepath in audio_filepaths:
try:
mf = mutagen.File(audio_filepath)
except Exception:
continue
if mf is None:
continue
# artist
for key in ("albumartist", "artist", # ogg
"TPE1", "TPE2", # ... | def get_metadata(audio_filepaths) | Return a tuple of album, artist, has_embedded_album_art from a list of audio files. | 2.587495 | 2.366323 | 1.093467 |
no_metadata = None, None, None
metadata = no_metadata
audio_filepaths = []
for rel_filepath in rel_filepaths:
stats["files"] += 1
try:
ext = os.path.splitext(rel_filepath)[1][1:].lower()
except IndexError:
continue
if ext in AUDIO_EXTENSIONS:
audio_filepaths.append(os.path.j... | def analyze_dir(stats, parent_dir, rel_filepaths, cover_filename, *, ignore_existing=False) | Analyze a directory (non recursively) to get its album metadata if it is one. | 3.420067 | 3.192641 | 1.071235 |
with open(cover_filepath, "rb") as f:
cover_data = f.read()
for filename in os.listdir(path):
try:
ext = os.path.splitext(filename)[1][1:].lower()
except IndexError:
continue
if ext in AUDIO_EXTENSIONS:
filepath = os.path.join(path, filename)
mf = mutagen.File(filepath)
... | def embed_album_art(cover_filepath, path) | Embed album art into audio files. | 2.282792 | 2.225712 | 1.025646 |
it = iter(iterable)
while True:
chunk = tuple(itertools.islice(it, n))
if not chunk:
return
yield chunk | def ichunk(iterable, n) | Split an iterable into n-sized chunks. | 2.090048 | 1.956929 | 1.068024 |
with contextlib.ExitStack() as cm:
if args.filename == EMBEDDED_ALBUM_ART_SYMBOL:
tmp_prefix = "%s_" % (os.path.splitext(os.path.basename(inspect.getfile(inspect.currentframe())))[0])
tmp_dir = cm.enter_context(tempfile.TemporaryDirectory(prefix=tmp_prefix))
# setup progress report
stats ... | def get_covers(work, args) | Get missing covers. | 3.207132 | 3.203401 | 1.001165 |
fd, filename = tempfile.mkstemp(*args, **kwargs)
os.close(fd)
try:
yield filename
finally:
os.remove(filename) | def mkstemp(*args, **kwargs) | Context manager similar to tempfile.NamedTemporaryFile except the file is not deleted on close, and only the filepath
is returned
.. warnings:: Unlike tempfile.mkstemp, this is not secure | 2.213367 | 2.741998 | 0.807209 |
# remove current handler
assert(len(logger.handlers) == 1)
prev_handler = logger.handlers[0]
logger.removeHandler(prev_handler)
# add tqdm handler
tqdm_handler = TqdmLoggingHandler(tqdm_obj)
if prev_handler.formatter is not None:
tqdm_handler.setFormatter(prev_handler.formatter)
logger.addHandle... | def redirect_logging(tqdm_obj, logger=logging.getLogger()) | Context manager to redirect logging to a TqdmLoggingHandler object and then restore the original. | 2.179578 | 2.035889 | 1.070578 |
self.logger.debug("Searching with source '%s'..." % (self.__class__.__name__))
album = self.processAlbumString(album)
artist = self.processArtistString(artist)
url_data = self.getSearchUrl(album, artist)
if isinstance(url_data, tuple):
url, post_data = url_data
else:
url = url_d... | async def search(self, album, artist) | Search for a given album/artist and return an iterable of CoverSourceResult. | 3.453185 | 3.357123 | 1.028615 |
if post_data is not None:
self.logger.debug("Querying URL '%s' %s..." % (url, dict(post_data)))
else:
self.logger.debug("Querying URL '%s'..." % (url))
headers = {}
self.updateHttpHeaders(headers)
return await self.http.query(url,
post_data=post_data... | async def fetchResults(self, url, post_data=None) | Get a (store in cache callback, search results) tuple from an URL. | 3.963827 | 3.667739 | 1.080727 |
self.logger.debug("Probing URL '%s'..." % (url))
headers = {}
self.updateHttpHeaders(headers)
resp_headers = {}
resp_ok = await self.http.isReachable(url,
headers=headers,
response_headers=resp_headers,
... | async def probeUrl(self, url, response_headers=None) | Probe URL reachability from cache or HEAD request. | 4.75603 | 4.211877 | 1.129195 |
return "".join(c for c in unicodedata.normalize("NFKD", s) if not unicodedata.combining(c)) | def unaccentuate(s) | Replace accentuated chars in string by their non accentuated equivalent. | 2.242958 | 2.384171 | 0.940771 |
# remove punctuation
s = "".join(c for c in s if c not in char_blacklist)
# remove consecutive spaces
return " ".join(filter(None, s.split(" "))) | def unpunctuate(s, *, char_blacklist=string.punctuation) | Remove punctuation from string s. | 3.177681 | 3.048123 | 1.042504 |
params = collections.OrderedDict()
params["search-alias"] = "popular"
params["field-artist"] = artist
params["field-title"] = album
params["sort"] = "relevancerank"
return __class__.assembleUrl(self.base_url, params) | def getSearchUrl(self, album, artist) | See CoverSource.getSearchUrl. | 6.435432 | 5.966608 | 1.078575 |
results = []
# parse page
parser = lxml.etree.HTMLParser()
html = lxml.etree.XML(api_data.decode("utf-8", "ignore"), parser)
for page_struct_version, result_selector in enumerate(__class__.RESULTS_SELECTORS):
result_nodes = result_selector(html)
if result_nodes:
break
... | async def parseResults(self, api_data) | See CoverSource.parseResults. | 3.903577 | 3.826011 | 1.020273 |
'''Calls `delete()` on all members of `obj` that are recognized as
instances of `pg` objects.'''
types = tuple([
Shader,
Mesh,
VertexBuffer,
IndexBuffer,
Texture,
Program,
Context,
])
for name in dir(obj):
child = getattr(obj, name)
... | def delete_all(obj) | Calls `delete()` on all members of `obj` that are recognized as
instances of `pg` objects. | 6.931458 | 3.79261 | 1.827622 |
'''
Queries and returns the library version tuple or None by using a
subprocess.
'''
version_checker_source =
args = [sys.executable, '-c', textwrap.dedent(version_checker_source)]
process = subprocess.Popen(args, universal_newlines=True,
stdin=subprocess.PIP... | def _glfw_get_version(filename) | Queries and returns the library version tuple or None by using a
subprocess. | 5.737463 | 3.721128 | 1.541861 |
'''
Sets the error callback.
Wrapper for:
GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun cbfun);
'''
global _error_callback
previous_callback = _error_callback
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWerrorfun(cbfun)
_error_callback = (cbfun, c_cbfun)
cbfun = c... | def set_error_callback(cbfun) | Sets the error callback.
Wrapper for:
GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun cbfun); | 2.994275 | 2.364038 | 1.266593 |
'''
Destroys the specified window and its context.
Wrapper for:
void glfwDestroyWindow(GLFWwindow* window);
'''
_glfw.glfwDestroyWindow(window)
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_ulong)).contents.value
for callback... | def destroy_window(window) | Destroys the specified window and its context.
Wrapper for:
void glfwDestroyWindow(GLFWwindow* window); | 4.351564 | 3.36476 | 1.293276 |
'''
Returns a nested python sequence.
'''
size = self.width, self.height
bits = self.red_bits, self.green_bits, self.blue_bits
return size, bits, self.refresh_rate | def unwrap(self) | Returns a nested python sequence. | 10.053178 | 6.0543 | 1.660502 |
'''
Wraps a nested python sequence.
'''
red, green, blue = gammaramp
size = min(len(red), len(green), len(blue))
array_type = ctypes.c_ushort*size
self.size = ctypes.c_uint(size)
self.red_array = array_type()
self.green_array = array_type()
... | def wrap(self, gammaramp) | Wraps a nested python sequence. | 2.002753 | 1.778411 | 1.126148 |
'''
Returns a nested python sequence.
'''
red = [self.red[i]/65535.0 for i in range(self.size)]
green = [self.green[i]/65535.0 for i in range(self.size)]
blue = [self.blue[i]/65535.0 for i in range(self.size)]
return red, green, blue | def unwrap(self) | Returns a nested python sequence. | 3.063938 | 2.284728 | 1.341052 |
'''Accepts a hexadecimal color `value` in the format ``0xrrggbb`` and
returns an (r, g, b) tuple where 0.0 <= r, g, b <= 1.0.
'''
r = ((value >> (8 * 2)) & 255) / 255.0
g = ((value >> (8 * 1)) & 255) / 255.0
b = ((value >> (8 * 0)) & 255) / 255.0
return (r, g, b) | def hex_color(value) | Accepts a hexadecimal color `value` in the format ``0xrrggbb`` and
returns an (r, g, b) tuple where 0.0 <= r, g, b <= 1.0. | 2.339453 | 1.592646 | 1.468909 |
'''Normalizes the `vector` so that its length is 1. `vector` can have
any number of components.
'''
d = sum(x * x for x in vector) ** 0.5
return tuple(x / d for x in vector) | def normalize(vector) | Normalizes the `vector` so that its length is 1. `vector` can have
any number of components. | 4.154996 | 2.633309 | 1.577861 |
'''Computes and returns the distance between two points, `p1` and `p2`.
The points can have any number of components.
'''
return sum((a - b) ** 2 for a, b in zip(p1, p2)) ** 0.5 | def distance(p1, p2) | Computes and returns the distance between two points, `p1` and `p2`.
The points can have any number of components. | 3.568531 | 2.13982 | 1.667678 |
'''Computes the cross product of two vectors.
'''
return (
v1[1] * v2[2] - v1[2] * v2[1],
v1[2] * v2[0] - v1[0] * v2[2],
v1[0] * v2[1] - v1[1] * v2[0],
) | def cross(v1, v2) | Computes the cross product of two vectors. | 1.553676 | 1.641903 | 0.946266 |
'''Computes the dot product of two vectors.
'''
x1, y1, z1 = v1
x2, y2, z2 = v2
return x1 * x2 + y1 * y2 + z1 * z2 | def dot(v1, v2) | Computes the dot product of two vectors. | 1.978347 | 2.183605 | 0.906 |
'''Adds two vectors.
'''
return tuple(a + b for a, b in zip(v1, v2)) | def add(v1, v2) | Adds two vectors. | 4.158019 | 4.746074 | 0.876097 |
'''Subtracts two vectors.
'''
return tuple(a - b for a, b in zip(v1, v2)) | def sub(v1, v2) | Subtracts two vectors. | 3.675864 | 4.820034 | 0.762622 |
'''Interpolate from one vector to another.
'''
return add(v1, mul(sub(v2, v1), t)) | def interpolate(v1, v2, t) | Interpolate from one vector to another. | 4.065472 | 5.11086 | 0.795457 |
'''Computes a normal vector given three points.
'''
x1, y1, z1 = a
x2, y2, z2 = b
x3, y3, z3 = c
ab = (x2 - x1, y2 - y1, z2 - z1)
ac = (x3 - x1, y3 - y1, z3 - z1)
x, y, z = cross(ab, ac)
d = (x * x + y * y + z * z) ** 0.5
return (x / d, y / d, z / d) | def normal_from_points(a, b, c) | Computes a normal vector given three points. | 1.766028 | 1.752927 | 1.007474 |
'''Assigns an averaged normal to each position based on all of the normals
originally used for the position.
'''
lookup = defaultdict(list)
for position, normal in zip(positions, normals):
lookup[position].append(normal)
result = []
for position in positions:
tx = ty = tz = 0... | def smooth_normals(positions, normals) | Assigns an averaged normal to each position based on all of the normals
originally used for the position. | 3.059401 | 2.195813 | 1.393289 |
'''Computes the bounding box for a list of 3-dimensional points.
'''
(x0, y0, z0) = (x1, y1, z1) = positions[0]
for x, y, z in positions:
x0 = min(x0, x)
y0 = min(y0, y)
z0 = min(z0, z)
x1 = max(x1, x)
y1 = max(y1, y)
z1 = max(z1, z)
return (x0, y0, z0... | def bounding_box(positions) | Computes the bounding box for a list of 3-dimensional points. | 1.71303 | 1.625291 | 1.053983 |
'''Returns a list of new positions centered around the origin.
'''
(x0, y0, z0), (x1, y1, z1) = bounding_box(positions)
dx = x1 - (x1 - x0) / 2.0
dy = y1 - (y1 - y0) / 2.0
dz = z1 - (z1 - z0) / 2.0
result = []
for x, y, z in positions:
result.append((x - dx, y - dy, z - dz))
... | def recenter(positions) | Returns a list of new positions centered around the origin. | 2.034868 | 1.843662 | 1.10371 |
'''Interleaves the elements of the provided arrays.
>>> a = [(0, 0), (1, 0), (2, 0), (3, 0)]
>>> b = [(0, 0), (0, 1), (0, 2), (0, 3)]
>>> interleave(a, b)
[(0, 0, 0, 0), (1, 0, 0, 1), (2, 0, 0, 2), (3, 0, 0, 3)]
This is useful for combining multiple vertex attributes into a sin... | def interleave(*args) | Interleaves the elements of the provided arrays.
>>> a = [(0, 0), (1, 0), (2, 0), (3, 0)]
>>> b = [(0, 0), (0, 1), (0, 2), (0, 3)]
>>> interleave(a, b)
[(0, 0, 0, 0), (1, 0, 0, 1), (2, 0, 0, 2), (3, 0, 0, 3)]
This is useful for combining multiple vertex attributes into a single
... | 2.659945 | 1.505589 | 1.766714 |
'''Yields distinct items from `iterable` in the order that they appear.
'''
seen = set()
for item in iterable:
key = item if keyfunc is None else keyfunc(item)
if key not in seen:
seen.add(key)
yield item | def distinct(iterable, keyfunc=None) | Yields distinct items from `iterable` in the order that they appear. | 2.737202 | 2.209101 | 1.239057 |
'''Computes the distance from a point to a triangle given a ray.
'''
eps = 1e-6
e1 = sub(v2, v1)
e2 = sub(v3, v1)
p = cross(d, e2)
det = dot(e1, p)
if abs(det) < eps:
return None
inv = 1.0 / det
t = sub(o, v1)
u = dot(t, p) * inv
if u < 0 or u > 1:
return ... | def ray_triangle_intersection(v1, v2, v3, o, d) | Computes the distance from a point to a triangle given a ray. | 2.107877 | 1.965891 | 1.072225 |
'''Convert a Python list into a ctypes buffer.
This appears to be faster than the typical method of creating a ctypes
array, e.g. (c_float * len(data))(*data)
'''
func = struct.Struct(fmt).pack
return create_string_buffer(''.join([func(x) for x in data])) | def pack_list(fmt, data) | Convert a Python list into a ctypes buffer.
This appears to be faster than the typical method of creating a ctypes
array, e.g. (c_float * len(data))(*data) | 6.010242 | 2.394659 | 2.509853 |
if jquery:
e = JQuery(self)
e.click()
else:
super(Clickable, self).click() | def click(self, jquery=False) | Click by WebElement, if not, JQuery click | 5.000114 | 4.750831 | 1.052471 |
cookie_dict = dict()
for k in keys_map.keys():
key = _to_unicode_if_str(keys_map[k])
value = _to_unicode_if_str(getattr(cookie, k))
cookie_dict[key] = value
return cookie_dict | def convert_cookie_to_dict(cookie, keys_map=WEB_DRIVER_COOKIE_KEYS_MAP) | Converts an instance of Cookie class from cookielib to a dict.
The names of attributes can be changed according to keys_map:.
For example, this method can be used to create a cookie which compatible with WebDriver format.
:param cookie: Cookie instance received from requests/sessions using url2lib or reque... | 2.701835 | 3.04462 | 0.887413 |
for cookie in cookies:
driver.add_cookie(convert_cookie_to_dict(cookie))
return driver | def add_cookies_to_web_driver(driver, cookies) | Sets cookies in an existing WebDriver session. | 2.893091 | 3.066068 | 0.943583 |
self.conf = conf
self.when = options.browser_closer_when | def configure(self, options, conf) | Configure plugin. Plugin is enabled by default. | 18.189978 | 17.743834 | 1.025144 |
basename = os.path.basename(root)
if os.path.splitext(basename)[0] != '__init__' and basename.startswith('_'):
return
location = self._determine_location_for(root)
if os.path.isfile(root):
self._index_module(root, location)
elif os.path.isdir(root... | def index_path(self, root) | Index a path.
:param root: Either a package directory, a .so or a .py module. | 2.687639 | 2.783634 | 0.965515 |
if not paths:
paths = sys.path
if not name:
name = 'default'
self._name = name
idx_dir = get_cache_dir()
idx_file = os.path.join(idx_dir, name + '.json')
if os.path.exists(idx_file) and not refresh:
with open(idx_file) as fd:... | def get_or_create_index(self, paths=None, name=None, refresh=False) | Get index with given name from cache. Create if it doesn't exists. | 2.352176 | 2.252864 | 1.044082 |
scores = []
path = []
# sys.path sys path -> import sys
# os.path.basename os.path basename -> import os.path
# basename os.path basename -> from os.path import basename
# path.basename os.path basename ... | def symbol_scores(self, symbol) | Find matches for symbol.
:param symbol: A . separated symbol. eg. 'os.path.basename'
:returns: A list of tuples of (score, package, reference|None),
ordered by score from highest to lowest. | 3.864868 | 3.786006 | 1.02083 |
path = path.split('.')
node = self
while node._parent:
node = node._parent
for name in path:
node = node._tree.get(name, None)
if node is None or type(node) is float:
return None
return node | def find(self, path) | Return the node for a path, or None. | 3.654473 | 3.320769 | 1.10049 |
path = path.split('.')
node = self
while node._parent:
node = node._parent
location = node.location
for name in path:
tree = node._tree.get(name, None)
if tree is None or type(tree) is float:
return location
... | def location_for(self, path) | Return the location code for a path. | 4.199203 | 3.858886 | 1.088191 |
items_list = self.get_options()
for item in items_list:
if item.get_attribute("value") == option:
item.click()
break | def select_option(self, option) | Performs selection of provided item from Web List
@params option - string item name | 3.083205 | 3.344587 | 0.921849 |
items_list = self.get_options()
return next(iter([item.get_attribute(attribute) for item in items_list if item.is_selected()]), None) | def get_attribute_selected(self, attribute) | Performs search of selected item from Web List
Return attribute of selected item
@params attribute - string attribute name | 4.791818 | 4.750484 | 1.008701 |
xpath = './/option[normalize-space(.) = {0}]'.format(self._escape_string(text))
opts = self.find_elements_by_xpath(xpath)
matched = False
for opt in opts:
self._set_selected(opt)
if not self.is_multiple:
return
matched = True
... | def select_by_visible_text(self, text) | Performs search of selected item from Web List
@params text - string visible text | 3.350204 | 3.508837 | 0.95479 |
kwargs.setdefault('sleep_seconds', (1, None))
kwargs.setdefault('expected_exceptions', WebDriverException)
kwargs.setdefault('timeout_seconds', webium.settings.wait_timeout)
return wait_lib(*args, **kwargs) | def wait(*args, **kwargs) | Wrapping 'wait()' method of 'waiting' library with default parameter values.
WebDriverException is ignored in the expected exceptions by default. | 6.809405 | 4.869012 | 1.398519 |
if isinstance(source, text_type) and sys.version_info[0] == 2:
# ast.parse() on Python 2 doesn't like encoding declarations
# in Unicode strings
source = CODING_COOKIE_RE.sub(r'\1', source, 1)
return ast.parse(source, filename or '<unknown>') | def parse_ast(source, filename=None) | Parse source into a Python AST, taking care of encoding. | 4.726437 | 4.303702 | 1.098226 |
unresolved = set()
unreferenced = self._definitions.copy()
self._collect_unresolved_and_unreferenced(set(), set(), unresolved, unreferenced,
frozenset(self._definitions), start=True)
return unresolved, unreferenced - Scope.ALL_BU... | def find_unresolved_and_unreferenced_symbols(self) | Find any unresolved symbols, and unreferenced symbols from this scope.
:returns: ({unresolved}, {unreferenced}) | 7.406662 | 8.511763 | 0.870168 |
def get_item(key):
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
try:
return json.loads(open(CACHED_KEY_FILE, "rb").read().decode('UTF-8'))["_"]
except (IOError, ValueError):
return None | Return content in cached file in JSON format | null | null | null | |
def set_item(key,value):
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
open(CACHED_KEY_FILE, "wb").write(json.dumps({"_": value}).encode('UTF-8'))
return value | Write JSON content from value argument to cached file and return | null | null | null | |
def delete_item(key):
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
if os.path.isfile(CACHED_KEY_FILE):
os.remove(CACHED_KEY_FILE) | Delete cached file if present | null | null | null | |
if isinstance(data, dict) or isinstance(data, list):
self._raw_data = data
self._json_data = copy.deepcopy(self._raw_data)
else:
raise TypeError("Provided Data is not json") | def __parse_json_data(self, data) | Process Json data
:@param data
:@type data: json/dict
:throws TypeError | 3.836312 | 3.847749 | 0.997028 |
if file_path == '' or os.path.splitext(file_path)[1] != '.json':
raise IOError('Invalid Json file')
with open(file_path) as json_file:
self._raw_data = json.load(json_file)
self._json_data = copy.deepcopy(self._raw_data) | def __parse_json_file(self, file_path) | Process Json file data
:@param file_path
:@type file_path: string
:@throws IOError | 2.670006 | 2.707599 | 0.986116 |
if key.isdigit():
return data[int(key)]
if key not in data:
raise KeyError("Key not exists")
return data.get(key) | def __get_value_from_data(self, key, data) | Find value from json data
:@pram key
:@type: string
:@pram data
:@type data: dict
:@return object
:@throws KeyError | 4.851429 | 4.911089 | 0.987852 |
leafs = root.strip(" ").split('.')
for leaf in leafs:
if leaf:
self._json_data = self.__get_value_from_data(leaf, self._json_data)
return self | def at(self, root) | Set root where PyJsonq start to prepare
:@param root
:@type root: string
:@return self
:@throws KeyError | 7.047566 | 6.899011 | 1.021533 |
if data and (isinstance(data, dict) or isinstance(data, list)):
self._json_data = data
else:
self._json_data = copy.deepcopy(self._raw_data)
self.__reset_queries()
return self | def reset(self, data={}) | JsonQuery object cen be reset to new data
according to given data or previously given raw Json data
:@param data: {}
:@type data: json/dict
:@return self | 4.158183 | 4.444146 | 0.935654 |
temp_index = self._current_query_index
if len(self._queries) - 1 < temp_index:
self._queries.append([])
self._queries[temp_index].append(query_items) | def __store_query(self, query_items) | Make where clause
:@param query_items
:@type query_items: dict | 3.679477 | 3.835203 | 0.959396 |
def func(item):
or_check = False
for queries in self._queries:
and_check = True
for query in queries:
and_check &= self._matcher._match(
item.get(query.get('key'), None),
query.g... | def __execute_queries(self) | Execute all condition and filter result data | 3.861117 | 3.548559 | 1.08808 |
self.__store_query({"key": key, "operator": operator, "value": value})
return self | def where(self, key, operator, value) | Make where clause
:@param key
:@param operator
:@param value
:@type key,operator,value: string
:@return self | 6.051506 | 8.880305 | 0.681452 |
if len(self._queries) > 0:
self._current_query_index += 1
self.__store_query({"key": key, "operator": operator, "value": value})
return self | def or_where(self, key, operator, value) | Make or_where clause
:@param key
:@param operator
:@param value
:@type key, operator, value: string
:@return self | 4.506608 | 5.22787 | 0.862035 |
self.__prepare()
return None if self.count() < math.fabs(index) else self._json_data[index] | def nth(self, index) | Getting the nth element of the collection
:@param index
:@type index: int
:@return object | 12.392902 | 15.365479 | 0.806542 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.