_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q2600 | SMB2QueryDirectoryRequest.unpack_response | train | def unpack_response(file_information_class, buffer):
"""
Pass in the buffer value from the response object to unpack it and
return a list of query response structures for the request.
:param buffer: The raw bytes value of the SMB2QueryDirectoryResponse
buffer field.
... | python | {
"resource": ""
} |
q2601 | Open.read | train | def read(self, offset, length, min_length=0, unbuffered=False, wait=True,
send=True):
"""
Reads from an opened file or pipe
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2ReadRequest, receive_func) instead of
sending... | python | {
"resource": ""
} |
q2602 | Open.write | train | def write(self, data, offset=0, write_through=False, unbuffered=False,
wait=True, send=True):
"""
Writes data to an opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMBWriteRequest, receive_func) instead of
s... | python | {
"resource": ""
} |
q2603 | Open.flush | train | def flush(self, send=True):
"""
A command sent by the client to request that a server flush all cached
file information for the opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2FlushRequest, receive_func) instead of
... | python | {
"resource": ""
} |
q2604 | Open.close | train | def close(self, get_attributes=False, send=True):
"""
Closes an opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2CloseRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_... | python | {
"resource": ""
} |
q2605 | SIDPacket.from_string | train | def from_string(self, sid_string):
"""
Used to set the structure parameters based on the input string
:param sid_string: String of the sid in S-x-x-x-x form
"""
if not sid_string.startswith("S-"):
raise ValueError("A SID string must start with S-")
sid_entri... | python | {
"resource": ""
} |
q2606 | Pushover.sounds | train | def sounds(self):
"""Return a dictionary of sounds recognized by Pushover and that can be
used in a notification message.
"""
if not Pushover._SOUNDS:
request = Request("get", SOUND_URL, {"token": self.token})
Pushover._SOUNDS = request.answer["sounds"]
re... | python | {
"resource": ""
} |
q2607 | Pushover.message | train | def message(self, user, message, **kwargs):
"""Send `message` to the user specified by `user`. It is possible
to specify additional properties of the message by passing keyword
arguments. The list of valid keywords is ``title, priority, sound,
callback, timestamp, url, url_title, device,... | python | {
"resource": ""
} |
q2608 | Pushover.glance | train | def glance(self, user, **kwargs):
"""Send a glance to the user. The default property is ``text``, as this
is used on most glances, however a valid glance does not need to
require text and can be constructed using any combination of valid
keyword properties. The list of valid keywords is ... | python | {
"resource": ""
} |
q2609 | mswe | train | def mswe(w, v):
"""
Calculate mean squared weight error between estimated and true filter
coefficients, in respect to iterations.
Parameters
----------
v : array-like
True coefficients used to generate desired signal, must be a
one-dimensional array.
w : array-like
E... | python | {
"resource": ""
} |
q2610 | BaseAutoCompleteField.has_changed | train | def has_changed(self, initial, data):
"Detects if the data was changed. This is added in 1.6."
if initial is None and data is None:
return False
if data and not hasattr(data, '__iter__'):
data = self.widget.decompress(data)
initial = self.to_python(initial)
... | python | {
"resource": ""
} |
q2611 | results_decorator | train | def results_decorator(func):
"""
Helper for constructing simple decorators around Lookup.results.
func is a function which takes a request as the first parameter. If func
returns an HttpReponse it is returned otherwise the original Lookup.results
is returned.
"""
# Wrap function to maintian... | python | {
"resource": ""
} |
q2612 | login_required | train | def login_required(request):
"Lookup decorator to require the user to be authenticated."
user = getattr(request, 'user', None)
if user is None or not user.is_authenticated:
return HttpResponse(status=401) | python | {
"resource": ""
} |
q2613 | staff_member_required | train | def staff_member_required(request):
"Lookup decorator to require the user is a staff member."
user = getattr(request, 'user', None)
if user is None or not user.is_authenticated:
return HttpResponse(status=401) # Unauthorized
elif not user.is_staff:
return HttpResponseForbidden() | python | {
"resource": ""
} |
q2614 | LookupBase.format_item | train | def format_item(self, item):
"Construct result dictionary for the match item."
result = {
'id': self.get_item_id(item),
'value': self.get_item_value(item),
'label': self.get_item_label(item),
}
for key in settings.SELECTABLE_ESCAPED_KEYS:
i... | python | {
"resource": ""
} |
q2615 | LookupBase.paginate_results | train | def paginate_results(self, results, options):
"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)
... | python | {
"resource": ""
} |
q2616 | LookupBase.results | train | def results(self, request):
"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(reques... | python | {
"resource": ""
} |
q2617 | LookupBase.format_results | train | 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
'''
page_data = self.paginate_results(raw_data,... | python | {
"resource": ""
} |
q2618 | import_lookup_class | train | def import_lookup_class(lookup_class):
"""
Import lookup_class as a dotted base and ensure it extends LookupBase
"""
from selectable.base import LookupBase
if isinstance(lookup_class, string_types):
mod_str, cls_str = lookup_class.rsplit('.', 1)
mod = import_module(mod_str)
l... | python | {
"resource": ""
} |
q2619 | BaseLookupForm.clean_limit | train | def clean_limit(self):
"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
... | python | {
"resource": ""
} |
q2620 | AccessRateWatcher.waitAccessAsync | train | async def waitAccessAsync(self):
""" Wait the needed time before sending a request to honor rate limit. """
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]
... | python | {
"resource": ""
} |
q2621 | AccessRateWatcher.__access | train | def __access(self, ts):
""" Record an API access. """
with self.connection:
self.connection.execute("INSERT OR REPLACE INTO access_timestamp (timestamp, domain) VALUES (?, ?)",
(ts, self.domain)) | python | {
"resource": ""
} |
q2622 | aiohttp_socket_timeout | train | def aiohttp_socket_timeout(socket_timeout_s):
""" Return a aiohttp.ClientTimeout object with only socket timeouts set. """
return aiohttp.ClientTimeout(total=None,
connect=None,
sock_connect=socket_timeout_s,
sock_read=sock... | python | {
"resource": ""
} |
q2623 | Http.isReachable | train | 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. """
if (cache is not None) and (url in cache):
# try from cache first
sel... | python | {
"resource": ""
} |
q2624 | Http.fastStreamedQuery | train | async def fastStreamedQuery(self, url, *, headers=None, verify=True):
""" Send a GET request with short timeout, do not retry, and return streamed response. """
response = await self.session.get(url,
headers=self._buildHeaders(headers),
... | python | {
"resource": ""
} |
q2625 | LastFmCoverSource.processQueryString | train | def processQueryString(self, s):
""" See CoverSource.processQueryString. """
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) | python | {
"resource": ""
} |
q2626 | search_and_download | train | 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. """
# register sources
source_args = (size, size_tolerance_prct)
cover_s... | python | {
"resource": ""
} |
q2627 | AmazonDigitalCoverSource.generateImgUrls | train | def generateImgUrls(self, product_id, dynapi_key, format_id, slice_count):
""" Generate URLs for slice_count^2 subimages of a product. """
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 +
... | python | {
"resource": ""
} |
q2628 | retrier | train | 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. """
assert(max_attempts > 1)
assert(sleeptime >= 0)
assert(0 <= jitter <= sleeptime)
assert(sleepscale >= 1)
cur_sleeptime = min(max_sleeptime, sleep... | python | {
"resource": ""
} |
q2629 | CoverSourceResult.get | train | async def get(self, target_format, target_size, size_tolerance_prct, out_filepath):
""" Download cover and process it. """
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")
... | python | {
"resource": ""
} |
q2630 | CoverSourceResult.setFormatMetadata | train | def setFormatMetadata(self, format):
""" Set format image metadata to what has been reliably identified. """
assert((self.needMetadataUpdate(CoverImageMetadata.FORMAT)) or
(self.format is format))
self.format = format
self.check_metadata &= ~CoverImageMetadata.FORMAT | python | {
"resource": ""
} |
q2631 | CoverSourceResult.setSizeMetadata | train | def setSizeMetadata(self, size):
""" Set size image metadata to what has been reliably identified. """
assert((self.needMetadataUpdate(CoverImageMetadata.SIZE)) or
(self.size == size))
self.size = size
self.check_metadata &= ~CoverImageMetadata.SIZE | python | {
"resource": ""
} |
q2632 | CoverSourceResult.updateSignature | train | async def updateSignature(self):
""" Calculate a cover's "signature" using its thumbnail url. """
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").... | python | {
"resource": ""
} |
q2633 | CoverSourceResult.crunch | train | async def crunch(image_data, format, silent=False):
""" Crunch image data, and return the processed data, or orignal data if operation failed. """
if (((format is CoverImageFormat.PNG) and (not HAS_OPTIPNG)) or
((format is CoverImageFormat.JPEG) and (not HAS_JPEGOPTIM))):
return image_data
... | python | {
"resource": ""
} |
q2634 | CoverSourceResult.guessImageMetadataFromData | train | def guessImageMetadataFromData(img_data):
""" Identify an image format and size from its first bytes. """
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 =... | python | {
"resource": ""
} |
q2635 | CoverSourceResult.guessImageMetadataFromHttpData | train | async def guessImageMetadataFromHttpData(response):
""" Identify an image format and size from the beginning of its HTTP data. """
metadata = None
img_data = bytearray()
while len(img_data) < CoverSourceResult.MAX_FILE_METADATA_PEEK_SIZE:
new_img_data = await response.content.read(__class__.METAD... | python | {
"resource": ""
} |
q2636 | CoverSourceResult.guessImageFormatFromHttpResponse | train | def guessImageFormatFromHttpResponse(response):
""" Guess file format from HTTP response, return format or None. """
extensions = []
# try to guess extension from response content-type header
try:
content_type = response.headers["Content-Type"]
except KeyError:
pass
else:
ext ... | python | {
"resource": ""
} |
q2637 | CoverSourceResult.preProcessForComparison | train | async def preProcessForComparison(results, target_size, size_tolerance_prct):
""" Process results to prepare them for future comparison and sorting. """
# find reference (=image most likely to match target cover ignoring factors like size and format)
reference = None
for result in results:
if resu... | python | {
"resource": ""
} |
q2638 | CoverSourceResult.computeImgSignature | train | 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
"""
parser = PIL.ImageFile.Parser()
parser.feed(image_data)
img = parser.cl... | python | {
"resource": ""
} |
q2639 | get_metadata | train | def get_metadata(audio_filepaths):
""" Return a tuple of album, artist, has_embedded_album_art from a list of audio files. """
artist, album, has_embedded_album_art = None, None, None
for audio_filepath in audio_filepaths:
try:
mf = mutagen.File(audio_filepath)
except Exception:
continue
i... | python | {
"resource": ""
} |
q2640 | embed_album_art | train | def embed_album_art(cover_filepath, path):
""" Embed album art into audio files. """
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_EXTENSIO... | python | {
"resource": ""
} |
q2641 | ichunk | train | def ichunk(iterable, n):
""" Split an iterable into n-sized chunks. """
it = iter(iterable)
while True:
chunk = tuple(itertools.islice(it, n))
if not chunk:
return
yield chunk | python | {
"resource": ""
} |
q2642 | redirect_logging | train | def redirect_logging(tqdm_obj, logger=logging.getLogger()):
""" Context manager to redirect logging to a TqdmLoggingHandler object and then restore the original. """
# remove current handler
assert(len(logger.handlers) == 1)
prev_handler = logger.handlers[0]
logger.removeHandler(prev_handler)
# add tqdm ha... | python | {
"resource": ""
} |
q2643 | CoverSource.probeUrl | train | async def probeUrl(self, url, response_headers=None):
""" Probe URL reachability from cache or HEAD request. """
self.logger.debug("Probing URL '%s'..." % (url))
headers = {}
self.updateHttpHeaders(headers)
resp_headers = {}
resp_ok = await self.http.isReachable(url,
... | python | {
"resource": ""
} |
q2644 | CoverSource.unaccentuate | train | def unaccentuate(s):
""" Replace accentuated chars in string by their non accentuated equivalent. """
return "".join(c for c in unicodedata.normalize("NFKD", s) if not unicodedata.combining(c)) | python | {
"resource": ""
} |
q2645 | CoverSource.unpunctuate | train | def unpunctuate(s, *, char_blacklist=string.punctuation):
""" Remove punctuation from string s. """
# remove punctuation
s = "".join(c for c in s if c not in char_blacklist)
# remove consecutive spaces
return " ".join(filter(None, s.split(" "))) | python | {
"resource": ""
} |
q2646 | _glfw_get_version | train | def _glfw_get_version(filename):
'''
Queries and returns the library version tuple or None by using a
subprocess.
'''
version_checker_source = """
import sys
import ctypes
def get_version(library_handle):
'''
Queries and returns the library version tu... | python | {
"resource": ""
} |
q2647 | set_error_callback | train | def set_error_callback(cbfun):
'''
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 =... | python | {
"resource": ""
} |
q2648 | destroy_window | train | def destroy_window(window):
'''
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)).con... | python | {
"resource": ""
} |
q2649 | normalize | train | def normalize(vector):
'''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) | python | {
"resource": ""
} |
q2650 | distance | train | def distance(p1, p2):
'''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 | python | {
"resource": ""
} |
q2651 | cross | train | def cross(v1, v2):
'''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],
) | python | {
"resource": ""
} |
q2652 | dot | train | def dot(v1, v2):
'''Computes the dot product of two vectors.
'''
x1, y1, z1 = v1
x2, y2, z2 = v2
return x1 * x2 + y1 * y2 + z1 * z2 | python | {
"resource": ""
} |
q2653 | add | train | def add(v1, v2):
'''Adds two vectors.
'''
return tuple(a + b for a, b in zip(v1, v2)) | python | {
"resource": ""
} |
q2654 | sub | train | def sub(v1, v2):
'''Subtracts two vectors.
'''
return tuple(a - b for a, b in zip(v1, v2)) | python | {
"resource": ""
} |
q2655 | interpolate | train | def interpolate(v1, v2, t):
'''Interpolate from one vector to another.
'''
return add(v1, mul(sub(v2, v1), t)) | python | {
"resource": ""
} |
q2656 | normal_from_points | train | def normal_from_points(a, b, c):
'''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 /... | python | {
"resource": ""
} |
q2657 | smooth_normals | train | def smooth_normals(positions, normals):
'''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 positio... | python | {
"resource": ""
} |
q2658 | bounding_box | train | def bounding_box(positions):
'''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(... | python | {
"resource": ""
} |
q2659 | recenter | train | def recenter(positions):
'''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 - ... | python | {
"resource": ""
} |
q2660 | interleave | train | 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 verte... | python | {
"resource": ""
} |
q2661 | distinct | train | def distinct(iterable, keyfunc=None):
'''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 | python | {
"resource": ""
} |
q2662 | ray_triangle_intersection | train | def ray_triangle_intersection(v1, v2, v3, o, d):
'''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... | python | {
"resource": ""
} |
q2663 | pack_list | train | 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)
'''
func = struct.Struct(fmt).pack
return create_string_buffer(''.join([func(x) for x in data])) | python | {
"resource": ""
} |
q2664 | Clickable.click | train | def click(self, jquery=False):
"""
Click by WebElement, if not, JQuery click
"""
if jquery:
e = JQuery(self)
e.click()
else:
super(Clickable, self).click() | python | {
"resource": ""
} |
q2665 | add_cookies_to_web_driver | train | def add_cookies_to_web_driver(driver, cookies):
"""
Sets cookies in an existing WebDriver session.
"""
for cookie in cookies:
driver.add_cookie(convert_cookie_to_dict(cookie))
return driver | python | {
"resource": ""
} |
q2666 | BrowserCloserPlugin.configure | train | def configure(self, options, conf):
"""Configure plugin. Plugin is enabled by default.
"""
self.conf = conf
self.when = options.browser_closer_when | python | {
"resource": ""
} |
q2667 | SymbolIndex.index_path | train | def index_path(self, root):
"""Index a path.
:param root: Either a package directory, a .so or a .py module.
"""
basename = os.path.basename(root)
if os.path.splitext(basename)[0] != '__init__' and basename.startswith('_'):
return
location = self._determine_l... | python | {
"resource": ""
} |
q2668 | SymbolIndex.get_or_create_index | train | 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.
"""
if not paths:
paths = sys.path
if not name:
name = 'default'
self._name = name
idx_dir = get_ca... | python | {
"resource": ""
} |
q2669 | SymbolIndex.symbol_scores | train | 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.
"""
scores = []
path = []
... | python | {
"resource": ""
} |
q2670 | SymbolIndex.find | train | def find(self, path):
"""Return the node for a path, or None."""
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:
... | python | {
"resource": ""
} |
q2671 | SymbolIndex.location_for | train | def location_for(self, path):
"""Return the location code for a path."""
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 ... | python | {
"resource": ""
} |
q2672 | Select.select_option | train | def select_option(self, option):
"""
Performs selection of provided item from Web List
@params option - string item name
"""
items_list = self.get_options()
for item in items_list:
if item.get_attribute("value") == option:
item.click()
... | python | {
"resource": ""
} |
q2673 | Select.get_attribute_selected | train | def get_attribute_selected(self, attribute):
"""
Performs search of selected item from Web List
Return attribute of selected item
@params attribute - string attribute name
"""
items_list = self.get_options()
return next(iter([item.get_attribute(attribute) for ite... | python | {
"resource": ""
} |
q2674 | Select.select_by_visible_text | train | def select_by_visible_text(self, text):
"""
Performs search of selected item from Web List
@params text - string visible text
"""
xpath = './/option[normalize-space(.) = {0}]'.format(self._escape_string(text))
opts = self.find_elements_by_xpath(xpath)
matched = F... | python | {
"resource": ""
} |
q2675 | parse_ast | train | def parse_ast(source, filename=None):
"""Parse source into a Python AST, taking care of encoding."""
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', sourc... | python | {
"resource": ""
} |
q2676 | Scope.find_unresolved_and_unreferenced_symbols | train | def find_unresolved_and_unreferenced_symbols(self):
"""Find any unresolved symbols, and unreferenced symbols from this scope.
:returns: ({unresolved}, {unreferenced})
"""
unresolved = set()
unreferenced = self._definitions.copy()
self._collect_unresolved_and_unreferenced... | python | {
"resource": ""
} |
q2677 | get_item | train | def get_item(key):
"""Return content in cached file in JSON format"""
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 | python | {
"resource": ""
} |
q2678 | set_item | train | def set_item(key,value):
"""Write JSON content from value argument to cached file and return"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
open(CACHED_KEY_FILE, "wb").write(json.dumps({"_": value}).encode('UTF-8'))
return value | python | {
"resource": ""
} |
q2679 | delete_item | train | def delete_item(key):
"""Delete cached file if present"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
if os.path.isfile(CACHED_KEY_FILE):
os.remove(CACHED_KEY_FILE) | python | {
"resource": ""
} |
q2680 | JsonQ.__parse_json_data | train | def __parse_json_data(self, data):
"""Process Json data
:@param data
:@type data: json/dict
:throws TypeError
"""
if isinstance(data, dict) or isinstance(data, list):
self._raw_data = data
self._json_data = copy.deepcopy(self._raw_data)
e... | python | {
"resource": ""
} |
q2681 | JsonQ.__parse_json_file | train | def __parse_json_file(self, file_path):
"""Process Json file data
:@param file_path
:@type file_path: string
:@throws IOError
"""
if file_path == '' or os.path.splitext(file_path)[1] != '.json':
raise IOError('Invalid Json file')
with open(file_path... | python | {
"resource": ""
} |
q2682 | JsonQ.__get_value_from_data | train | 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
"""
if key.isdigit():
return data[int(key)]
if key not in dat... | python | {
"resource": ""
} |
q2683 | JsonQ.at | train | def at(self, root):
"""Set root where PyJsonq start to prepare
:@param root
:@type root: string
:@return self
:@throws KeyError
"""
leafs = root.strip(" ").split('.')
for leaf in leafs:
if leaf:
self._json_data = self.__get_va... | python | {
"resource": ""
} |
q2684 | JsonQ.reset | train | 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
"""
if data and (isinstance(data, dict) or isinstance(data, list)):
... | python | {
"resource": ""
} |
q2685 | JsonQ.__execute_queries | train | def __execute_queries(self):
"""Execute all condition and filter result data"""
def func(item):
or_check = False
for queries in self._queries:
and_check = True
for query in queries:
and_check &= self._matcher._match(
... | python | {
"resource": ""
} |
q2686 | JsonQ.or_where | train | def or_where(self, key, operator, value):
"""Make or_where clause
:@param key
:@param operator
:@param value
:@type key, operator, value: string
:@return self
"""
if len(self._queries) > 0:
self._current_query_index += 1
self.__store_... | python | {
"resource": ""
} |
q2687 | JsonQ.nth | train | def nth(self, index):
"""Getting the nth element of the collection
:@param index
:@type index: int
:@return object
"""
self.__prepare()
return None if self.count() < math.fabs(index) else self._json_data[index] | python | {
"resource": ""
} |
q2688 | JsonQ.sum | train | def sum(self, property):
"""Getting the sum according to the given property
:@param property
:@type property: string
:@return int/float
"""
self.__prepare()
total = 0
for i in self._json_data:
total += i.get(property)
return total | python | {
"resource": ""
} |
q2689 | JsonQ.max | train | def max(self, property):
"""Getting the maximum value from the prepared data
:@param property
:@type property: string
:@return object
:@throws KeyError
"""
self.__prepare()
try:
return max(self._json_data, key=lambda x: x[property]).get(prope... | python | {
"resource": ""
} |
q2690 | JsonQ.avg | train | def avg(self, property):
"""Getting average according to given property
:@param property
:@type property: string
:@return average: int/float
"""
self.__prepare()
return self.sum(property) / self.count() | python | {
"resource": ""
} |
q2691 | JsonQ.chunk | train | def chunk(self, size=0):
"""Group the resulted collection to multiple chunk
:@param size: 0
:@type size: integer
:@return Chunked List
"""
if size == 0:
raise ValueError('Invalid chunk size')
self.__prepare()
_new_content = []
whil... | python | {
"resource": ""
} |
q2692 | JsonQ.group_by | train | def group_by(self, property):
"""Getting the grouped result by the given property
:@param property
:@type property: string
:@return self
"""
self.__prepare()
group_data = {}
for data in self._json_data:
if data[property] not in group_data:
... | python | {
"resource": ""
} |
q2693 | JsonQ.sort | train | def sort(self, order="asc"):
"""Getting the sorted result of the given list
:@param order: "asc"
:@type order: string
:@return self
"""
self.__prepare()
if isinstance(self._json_data, list):
if order == "asc":
self._json_data = sorted... | python | {
"resource": ""
} |
q2694 | JsonQ.sort_by | train | def sort_by(self, property, order="asc"):
"""Getting the sorted result by the given property
:@param property, order: "asc"
:@type property, order: string
:@return self
"""
self.__prepare()
if isinstance(self._json_data, list):
if order == "asc":
... | python | {
"resource": ""
} |
q2695 | Matcher._match | train | def _match(self, x, op, y):
"""Compare the given `x` and `y` based on `op`
:@param x, y, op
:@type x, y: mixed
:@type op: string
:@return bool
:@throws ValueError
"""
if (op not in self.condition_mapper):
raise ValueError('Invalid where condi... | python | {
"resource": ""
} |
q2696 | overrides | train | def overrides(method):
"""Decorator to indicate that the decorated method overrides a method in
superclass.
The decorator code is executed while loading class. Using this method
should have minimal runtime performance implications.
This is based on my idea about how to do this and fwc:s highly impr... | python | {
"resource": ""
} |
q2697 | _get_base_class_names | train | def _get_base_class_names(frame):
""" Get baseclass names from the code object """
co, lasti = frame.f_code, frame.f_lasti
code = co.co_code
extends = []
for (op, oparg) in op_stream(code, lasti):
if op in dis.hasconst:
if type(co.co_consts[oparg]) == str:
extend... | python | {
"resource": ""
} |
q2698 | load_tlds | train | def load_tlds():
"""Load all legal TLD extensions from assets
"""
file = os.path.join(os.path.dirname(__file__),
'assets',
'tlds-alpha-by-domain.txt')
with open(file) as fobj:
return [elem for elem in fobj.read().lower().splitlines()[1:]
... | python | {
"resource": ""
} |
q2699 | parse_text_urls | train | def parse_text_urls(mesg):
"""Parse a block of text, splitting it into its url and non-url
components."""
rval = []
loc = 0
for match in URLRE.finditer(mesg):
if loc < match.start():
rval.append(Chunk(mesg[loc:match.start()], None))
# Turn email addresses into mailto: ... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.