Search is not available for this dataset
text
stringlengths
75
104k
def get_pixel(framebuf, x, y): """Get the color of a given pixel""" index = (y >> 3) * framebuf.stride + x offset = y & 0x07 return (framebuf.buf[index] >> offset) & 0x01
def fill_rect(framebuf, x, y, width, height, color): """Draw a rectangle at the given location, size and color. The ``fill_rect`` method draws both the outline and interior.""" # pylint: disable=too-many-arguments while height > 0: index = (y >> 3) * framebuf.stride + x ...
def fill_rect(self, x, y, width, height, color): """Draw a rectangle at the given location, size and color. The ``fill_rect`` method draws both the outline and interior.""" # pylint: disable=too-many-arguments, too-many-boolean-expressions self.rect(x, y, width, height, color, fill=True)
def pixel(self, x, y, color=None): """If ``color`` is not given, get the color value of the specified pixel. If ``color`` is given, set the specified pixel to the given color.""" if self.rotation == 1: x, y = y, x x = self.width - x - 1 if self.rotation == 2: ...
def hline(self, x, y, width, color): """Draw a horizontal line up to a given length.""" self.rect(x, y, width, 1, color, fill=True)
def vline(self, x, y, height, color): """Draw a vertical line up to a given length.""" self.rect(x, y, 1, height, color, fill=True)
def rect(self, x, y, width, height, color, *, fill=False): """Draw a rectangle at the given location, size and color. The ```rect``` method draws only a 1 pixel outline.""" # pylint: disable=too-many-arguments if self.rotation == 1: x, y = y, x width, height = hei...
def line(self, x_0, y_0, x_1, y_1, color): # pylint: disable=too-many-arguments """Bresenham's line algorithm""" d_x = abs(x_1 - x_0) d_y = abs(y_1 - y_0) x, y = x_0, y_0 s_x = -1 if x_0 > x_1 else 1 s_y = -1 if y_0 > y_1 else 1 if d_x > d_y: e...
def scroll(self, delta_x, delta_y): """shifts framebuf in x and y direction""" if delta_x < 0: shift_x = 0 xend = self.width + delta_x dt_x = 1 else: shift_x = self.width - 1 xend = delta_x - 1 dt_x = -1 if delta_y <...
def text(self, string, x, y, color, *, font_name="font5x8.bin"): """text is not yet implemented""" if not self._font or self._font.font_name != font_name: # load the font! self._font = BitmapFont() w = self._font.font_width for i, char in enumerate(st...
def image(self, img): """Set buffer to value of Python Imaging Library image. The image should be in 1 bit mode and a size equal to the display size.""" if img.mode != '1': raise ValueError('Image must be in mode 1.') imwidth, imheight = img.size if imwidth != self.w...
def draw_char(self, char, x, y, framebuffer, color): # pylint: disable=too-many-arguments """Draw one character at position (x,y) to a framebuffer in a given color""" # Don't draw the character if it will be clipped off the visible area. #if x < -self.font_width or x >= framebuffer.width...
def parse_auth_token_from_request(self, auth_header): """ Parses and returns Auth token from the request header. Raises `falcon.HTTPUnauthoried exception` with proper error message """ if not auth_header: raise falcon.HTTPUnauthorized( description='Mis...
def get_auth_header(self, user_payload): """ Returns the value for authorization header Args: user_payload(dict, required): A `dict` containing required information to create authentication token """ auth_token = self.get_auth_token(user_payload) ...
def authenticate(self, req, resp, resource): """ Extract auth token from request `authorization` header, decode jwt token, verify configured claims and return either a ``user`` object if successful else raise an `falcon.HTTPUnauthoried exception` """ payload = self._decod...
def get_auth_token(self, user_payload): """ Create a JWT authentication token from ``user_payload`` Args: user_payload(dict, required): A `dict` containing required information to create authentication token """ now = datetime.utcnow() payload...
def authenticate(self, req, resp, resource): """ Extract basic auth token from request `authorization` header, deocode the token, verifies the username/password and return either a ``user`` object if successful else raise an `falcon.HTTPUnauthoried exception` """ usernam...
def get_auth_token(self, user_payload): """ Extracts username, password from the `user_payload` and encode the credentials `username:password` in `base64` form """ username = user_payload.get('username') or None password = user_payload.get('password') or None if ...
def get_auth_token(self, user_payload): """ Extracts token from the `user_payload` """ token = user_payload.get('token') or None if not token: raise ValueError('`user_payload` must provide api token') return '{auth_header_prefix} {token}'.format( ...
def parse_auth_token_from_request(self, auth_header): """ Parses and returns the Hawk Authorization header if it is present and well-formed. Raises `falcon.HTTPUnauthoried exception` with proper error message """ if not auth_header: raise falcon.HTTPUnauthorized( ...
def _apply_base_theme(app): """ Apply base theme to the application. Args: app (QApplication): QApplication instance. """ if QT_VERSION < (5,): app.setStyle('plastique') else: app.setStyle('Fusion') with open(_STYLESHEET) as stylesheet: app.setStyleShee...
def dark(app): """ Apply Dark Theme to the Qt application instance. Args: app (QApplication): QApplication instance. """ _apply_base_theme(app) darkPalette = QPalette() # base darkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180)) darkPalette.setColor(QPalet...
def pkgconfig(*packages, **kw): """Based on http://code.activestate.com/recipes/502261-python-distutils-pkg-config/#c2""" flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'} output = sp.Popen(["pkg-config", "--libs", "--cflags"] + list(packages), stdout=sp.PIPE)...
def inheritance_diagram_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """ Run when the inheritance_diagram directive is first encountered. """ node = inheritance_diagram() c...
def html_output_graph(self, node): """ Output the graph for HTML. This will insert a PNG with clickable image map. """ graph = node['graph'] parts = node['parts'] graph_hash = get_graph_hash(node) name = "inheritance%s" % graph_hash path = '_images' dest_path = os.path.join(set...
def latex_output_graph(self, node): """ Output the graph for LaTeX. This will insert a PDF. """ graph = node['graph'] parts = node['parts'] graph_hash = get_graph_hash(node) name = "inheritance%s" % graph_hash dest_path = os.path.abspath(os.path.join(setup.app.builder.outdir, '_images'...
def visit_inheritance_diagram(inner_func): """ This is just a wrapper around html/latex_output_graph to make it easier to handle errors and insert warnings. """ def visitor(self, node): try: content = inner_func(self, node) except DotException, e: # Insert the...
def _import_class_or_module(self, name): """ Import a class using its fully-qualified *name*. """ try: path, base = self.py_sig_re.match(name).groups() except: raise ValueError( "Invalid class or module '%s' specified for inheritance diagra...
def _import_classes(self, class_names): """ Import a list of classes. """ classes = [] for name in class_names: classes.extend(self._import_class_or_module(name)) return classes
def _all_classes(self, classes): """ Return a list of all classes that are ancestors of *classes*. """ all_classes = {} def recurse(cls): all_classes[cls] = None for c in cls.__bases__: if c not in all_classes: recurse(...
def generate_dot(self, fd, name, parts=0, urls={}, graph_options={}, node_options={}, edge_options={}): """ Generate a graphviz dot graph from the classes that were passed in to __init__. *fd* is a Python file-like object to write to. *...
def run_dot(self, args, name, parts=0, urls={}, graph_options={}, node_options={}, edge_options={}): """ Run graphviz 'dot' over this graph, returning whatever 'dot' writes to stdout. *args* will be passed along as commandline arguments. *name* is the name of th...
def minimize_ipopt(fun, x0, args=(), kwargs=None, method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None): """ Minimize a function using ipopt. The call signature is exactly like for `scipy.optimize.mimize`. In options, all options...
def parse_md_to_rst(file): """Read Markdown file and convert to ReStructured Text.""" try: from m2r import parse_from_file return parse_from_file(file).replace( "artwork/", "http://198.27.119.65/" ) except ImportError: # m2r may not be installed in user environmen...
def deleted_count(self): """The number of documents deleted.""" if isinstance(self.raw_result, list): return len(self.raw_result) else: return self.raw_result
def generate_id(): """Generate new UUID""" # TODO: Use six.string_type to Py3 compat try: return unicode(uuid1()).replace(u"-", u"") except NameError: return str(uuid1()).replace(u"-", u"")
def build_table(self): """ Builds a new tinydb table at the parent database :return: """ self.table = self.parent.tinydb.table(self.tablename)
def drop(self, **kwargs): """ Removes a collection from the database. **kwargs only because of the optional "writeConcern" field, but does nothing in the TinyDB database. :return: Returns True when successfully drops a collection. Returns False when collection to drop does not ex...
def insert(self, docs, *args, **kwargs): """Backwards compatibility with insert""" if isinstance(docs, list): return self.insert_many(docs, *args, **kwargs) else: return self.insert_one(docs, *args, **kwargs)
def insert_one(self, doc, *args, **kwargs): """ Inserts one document into the collection If contains '_id' key it is used, else it is generated. :param doc: the document :return: InsertOneResult """ if self.table is None: self.build_table() if...
def insert_many(self, docs, *args, **kwargs): """ Inserts several documents into the collection :param docs: a list of documents :return: InsertManyResult """ if self.table is None: self.build_table() if not isinstance(docs, list): raise V...
def parse_query(self, query): """ Creates a tinydb Query() object from the query dict :param query: object containing the dictionary representation of the query :return: composite Query() """ logger.debug(u'query to parse2: {}'.format(query)) # this shou...
def parse_condition(self, query, prev_key=None, last_prev_key=None): """ Creates a recursive generator for parsing some types of Query() conditions :param query: Query object :param prev_key: The key at the next-higher level :return: generator object, the last of which w...
def update(self, query, doc, *args, **kwargs): """BAckwards compatibility with update""" if isinstance(doc, list): return [ self.update_one(query, item, *args, **kwargs) for item in doc ] else: return self.update_one(query, doc,...
def update_one(self, query, doc): """ Updates one element of the collection :param query: dictionary representing the mongo query :param doc: dictionary representing the item to be updated :return: UpdateResult """ if self.table is None: self.build_ta...
def find(self, filter=None, sort=None, skip=None, limit=None, *args, **kwargs): """ Finds all matching results :param query: dictionary representing the mongo query :return: cursor containing the search results """ if self.table is None: self.bui...
def find_one(self, filter=None): """ Finds one matching query element :param query: dictionary representing the mongo query :return: the resulting document (if found) """ if self.table is None: self.build_table() allcond = self.parse_query(filter) ...
def remove(self, spec_or_id, multi=True, *args, **kwargs): """Backwards compatibility with remove""" if multi: return self.delete_many(spec_or_id) return self.delete_one(spec_or_id)
def delete_one(self, query): """ Deletes one document from the collection :param query: dictionary representing the mongo query :return: DeleteResult """ item = self.find_one(query) result = self.table.remove(where(u'_id') == item[u'_id']) return DeleteR...
def delete_many(self, query): """ Removes all items matching the mongo query :param query: dictionary representing the mongo query :return: DeleteResult """ items = self.find(query) result = [ self.table.remove(where(u'_id') == item[u'_id']) ...
def paginate(self, skip, limit): """Paginate list of records""" if not self.count() or not limit: return skip = skip or 0 pages = int(ceil(self.count() / float(limit))) limits = {} last = 0 for i in range(pages): current = limit * i ...
def _order(self, value, is_reverse=None): """Parsing data to a sortable form By giving each data type an ID(int), and assemble with the value into a sortable tuple. """ def _dict_parser(dict_doc): """ dict ordered by: valueType_N -> key_N -> value_N ...
def sort(self, key_or_list, direction=None): """ Sorts a cursor object based on the input :param key_or_list: a list/tuple containing the sort specification, i.e. ('user_number': -1), or a basestring :param direction: sorting direction, 1 or -1, needed if key_or_list ...
def hasNext(self): """ Returns True if the cursor has a next position, False if not :return: """ cursor_pos = self.cursorpos + 1 try: self.cursordat[cursor_pos] return True except IndexError: return False
def display(self, image): """ Takes a 1-bit :py:mod:`PIL.Image` and dumps it to the PCD8544 LCD display. """ assert(image.mode == self.mode) assert(image.size == self.size) image = self.preprocess(image) self.command(0x20, 0x80, 0x40) buf = byte...
def display(self, image): """ Takes a 1-bit :py:mod:`PIL.Image` and dumps it to the ST7567 LCD display """ assert(image.mode == self.mode) assert(image.size == self.size) image = self.preprocess(image) set_page_address = 0xB0 image_data = image....
def should_stream(proxy_response): """Function to verify if the proxy_response must be converted into a stream.This will be done by checking the proxy_response content-length and verify if its length is bigger than one stipulated by MIN_STREAMING_LENGTH. :param proxy_response: An Instance of urllib...
def get_charset(content_type): """Function used to retrieve the charset from a content-type.If there is no charset in the content type then the charset defined on DEFAULT_CHARSET will be returned :param content_type: A string containing a Content-Type header :returns: A string cont...
def required_header(header): """Function that verify if the header parameter is a essential header :param header: A string represented a header :returns: A boolean value that represent if the header is required """ if header in IGNORE_HEADERS: return False if header.startswith('...
def normalize_request_headers(request): r"""Function used to transform header, replacing 'HTTP\_' to '' and replace '_' to '-' :param request: A HttpRequest that will be transformed :returns: A dictionary with the normalized headers """ norm_headers = {} for header, value in request...
def encode_items(items): """Function that encode all elements in the list of items passed as a parameter :param items: A list of tuple :returns: A list of tuple with all items encoded in 'utf-8' """ encoded = [] for key, values in items: for value in values: encode...
def cookie_from_string(cookie_string, strict_cookies=False): """Parser for HTTP header set-cookie The return from this function will be used as parameters for django's response.set_cookie method. Because set_cookie doesn't have parameter comment, this cookie attribute will be ignored. :param cooki...
def unquote(value): """Remove wrapping quotes from a string. :param value: A string that might be wrapped in double quotes, such as a HTTP cookie value. :returns: Beginning and ending quotes removed and escaped quotes (``\"``) unescaped """ if len(value) > 1 and valu...
def asbool(value): """Function used to convert certain string values into an appropriated boolean value.If value is not a string the built-in python bool function will be used to convert the passed parameter :param value: an object to be converted to a boolean value :returns: A boolean value...
def should_transform(self): """Determine if we should transform the response :returns: A boolean value """ if not HAS_DIAZO: self.log.info("HAS_DIAZO: false") return False if asbool(self.request.META.get(DIAZO_OFF_REQUEST_HEADER)): self.log...
def transform(self, rules, theme_template, is_html5, context_data=None): """Method used to make a transformation on the content of the http response based on the rules and theme_templates passed as paremters :param rules: A file with a set of diazo rules to make a ...
def set_html5_doctype(self): """Method used to transform a doctype in to a properly html5 doctype """ doctype = b'<!DOCTYPE html>\n' content = doctype_re.subn(doctype, self.response.content, 1)[0] self.response.content = content
def _output(self, s): """Host header should always be first""" if s.lower().startswith(b'host: '): self._buffer.insert(1, s) else: self._buffer.append(s)
def get_django_response(proxy_response, strict_cookies=False): """This method is used to create an appropriate response based on the Content-Length of the proxy_response. If the content is bigger than MIN_STREAMING_LENGTH, which is found on utils.py, than django.http.StreamingHttpResponse will be create...
def get_request_headers(self): """Return request headers that will be sent to upstream. The header REMOTE_USER is set to the current user if AuthenticationMiddleware is enabled and the view's add_remote_user property is True. .. versionadded:: 0.9.8 """ request...
def get_encoded_query_params(self): """Return encoded query params to be used in proxied request""" get_data = encode_items(self.request.GET.lists()) return urlencode(get_data)
def stream_download(url, target_path, verbose=False): """ Download a large file without loading it into memory. """ response = requests.get(url, stream=True) handle = open(target_path, "wb") if verbose: print("Beginning streaming download of %s" % url) start = datetime.now() try:...
def validate_object_id(object_id): """ It's easy to make a mistake entering these, validate the format """ result = re.match(OBJECT_ID_RE, str(object_id)) if not result: print("'%s' appears not to be a valid 990 object_id" % object_id) raise RuntimeError(OBJECT_ID_MSG) return object_id
def _get_table_start(self): """ prefill the columns we need for all tables """ if self.documentation: standardized_table_start = { 'object_id': { 'value': self.object_id, 'ordering': -1, 'line_number': 'NA', ...
def debracket(string): """ Eliminate the bracketed var names in doc, line strings """ result = re.sub(BRACKET_RE, ';', str(string)) result = result.lstrip(';') result = result.lstrip(' ') result = result.replace('; ;',';') return result
def run_sked(self, object_id, sked, verbose=False): """ sked is the proper name of the schedule: IRS990, IRS990EZ, IRS990PF, IRS990ScheduleA, etc. """ self.whole_filing_data = [] self.filing_keyerr_data = [] this_filing = Filing(object_id) this_filing.proc...
def _download(self, force_overwrite=False, verbose=False): """ Download the file if it's not already there. We shouldn't *need* to overwrite; the xml is not supposed to update. """ if not force_overwrite: # If the file is already there, we're done if os.pa...
def _set_schedules(self): """ Attach the known and unknown schedules """ self.schedules = ['ReturnHeader990x', ] self.otherforms = [] for sked in self.raw_irs_dict['Return']['ReturnData'].keys(): if not sked.startswith("@"): if sked in KNOWN_SCHEDULES: ...
def get_parsed_sked(self, skedname): """ Returns an array because multiple sked K's are allowed""" if not self.processed: raise Exception("Filing must be processed to return parsed sked") if skedname in self.schedules: matching_skeds = [] for sked in self.resu...
def headers(self): """ Return headers of the uploader instance. This would include the headers of the client instance. """ client_headers = getattr(self.client, 'headers', {}) return dict(self.DEFAULT_HEADERS, **client_headers)
def headers_as_list(self): """ Does the same as 'headers' except it is returned as a list. """ headers = self.headers headers_list = ['{}: {}'.format(key, value) for key, value in iteritems(headers)] return headers_list
def get_offset(self): """ Return offset from tus server. This is different from the instance attribute 'offset' because this makes an http request to the tus server to retrieve the offset. """ resp = requests.head(self.url, headers=self.headers) offset = resp.hea...
def encode_metadata(self): """ Return list of encoded metadata as defined by the Tus protocol. """ encoded_list = [] for key, value in iteritems(self.metadata): key_str = str(key) # dict keys may be of any object type. # confirm that the key does not con...
def get_url(self): """ Return the tus upload url. If resumability is enabled, this would try to get the url from storage if available, otherwise it would request a new upload url from the tus server. """ if self.store_url and self.url_storage: key = self.fing...
def create_url(self): """ Return upload url. Makes request to tus server to create a new upload url for the required file upload. """ headers = self.headers headers['upload-length'] = str(self.file_size) headers['upload-metadata'] = ','.join(self.encode_metadata(...
def request_length(self): """ Return length of next chunk upload. """ remainder = self.stop_at - self.offset return self.chunk_size if remainder > self.chunk_size else remainder
def verify_upload(self): """ Confirm that the last upload was sucessful. Raises TusUploadFailed exception if the upload was not sucessful. """ if self.request.status_code == 204: return True else: raise TusUploadFailed('', self.request.status_code,...
def get_file_stream(self): """ Return a file stream instance of the upload. """ if self.file_stream: self.file_stream.seek(0) return self.file_stream elif os.path.isfile(self.file_path): return open(self.file_path, 'rb') else: ...
def file_size(self): """ Return size of the file. """ stream = self.get_file_stream() stream.seek(0, os.SEEK_END) return stream.tell()
def upload(self, stop_at=None): """ Perform file upload. Performs continous upload of chunks of the file. The size uploaded at each cycle is the value of the attribute 'chunk_size'. :Args: - stop_at (Optional[int]): Determines at what offset value th...
def upload_chunk(self): """ Upload chunk of file. """ self._retried = 0 self._do_request() self.offset = int(self.request.response_headers.get('upload-offset')) if self.log_func: msg = '{} bytes uploaded ...'.format(self.offset) self.log_fu...
def get_item(self, key): """ Return the tus url of a file, identified by the key specified. :Args: - key[str]: The unique id for the stored item (in this case, url) :Returns: url[str] """ result = self._db.search(self._urls.key == key) return result[0...
def set_item(self, key, url): """ Store the url value under the unique key. :Args: - key[str]: The unique id to which the item (in this case, url) would be stored. - value[str]: The actual url value to be stored. """ if self._db.search(self._urls.key == k...
def remove_item(self, key): """ Remove/Delete the url value under the unique key from storage. """ self._db.remove(self._urls.key==key)
def perform(self): """ Perform actual request. """ try: host = '{}://{}'.format(self._url.scheme, self._url.netloc) path = self._url.geturl().replace(host, '', 1) chunk = self.file.read(self._content_length) if self._upload_checksum: ...
def get_fingerprint(self, fs): """ Return a unique fingerprint string value based on the file stream recevied :Args: - fs[file]: The file stream instance of the file for which a fingerprint would be generated. :Returns: fingerprint[str] """ hasher = hashlib.m...
def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs): """Called to initialize the HTTPAdapter when no proxy is used.""" try: pool_kwargs['ssl_version'] = ssl.PROTOCOL_TLS except AttributeError: pool_kwargs['ssl_version'] = ssl.PROTOCOL_SSLv23 ...
def proxy_manager_for(self, proxy, **proxy_kwargs): """Called to initialize the HTTPAdapter when a proxy is used.""" try: proxy_kwargs['ssl_version'] = ssl.PROTOCOL_TLS except AttributeError: proxy_kwargs['ssl_version'] = ssl.PROTOCOL_SSLv23 return super(SSLAdapte...
def make_calls(self, num_calls=1): """Adds appropriate sleep to avoid making too many calls. Args: num_calls: int the number of calls which will be made """ self._cull() while self._outstanding_calls + num_calls > self._max_calls_per_second: time.sleep(0)...
def _cull(self): """Remove calls more than 1 second old from the queue.""" right_now = time.time() cull_from = -1 for index in range(len(self._call_times)): if right_now - self._call_times[index].time >= 1.0: cull_from = index self._outstandin...