code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if model: resource_key = get_model_table(model) elif instance: resource_key = instance._meta.db_table elif resource_name: resource_key = resource_name_map[resource_name] if resource_key not in resource_map: return None r...
def get_canonical_serializer( resource_key, model=None, instance=None, resource_name=None )
Return canonical serializer for a given resource name. Arguments: resource_key - Resource key, usually DB table for model-based resources, otherwise the plural name. model - (Optional) Model class to look up by. instance - (Optional) Model object i...
3.157029
3.09143
1.021219
routes = super(DynamicRouter, self).get_routes(viewset) routes += self.get_relation_routes(viewset) return routes
def get_routes(self, viewset)
DREST routes injection, overrides DRF's get_routes() method, which gets called for each registered viewset.
3.97238
3.836855
1.035322
routes = [] if not hasattr(viewset, 'serializer_class'): return routes if not hasattr(viewset, 'list_related'): return routes serializer = viewset.serializer_class() fields = getattr(serializer, 'get_link_fields', lambda: [])() route_n...
def get_relation_routes(self, viewset)
Generate routes to serve relational objects. This method will add a sub-URL for each relational field. e.g. A viewset for the following serializer: class UserSerializer(..): events = DynamicRelationField(EventSerializer, many=True) groups = DynamicRelation...
3.841315
4.105567
0.935636
paths = [] for key, child in six.iteritems(self): if isinstance(child, TreeMap) and child: # current child is an intermediate node for path in child.get_paths(): path.insert(0, key) paths.append(path) ...
def get_paths(self)
Get all paths from the root to the leaves. For example, given a chain like `{'a':{'b':{'c':None}}}`, this method would return `[['a', 'b', 'c']]`. Returns: A list of lists of paths.
3.789695
3.894013
0.973211
tree = self if not parts: return tree cur = tree last = len(parts) - 1 for i, part in enumerate(parts): if part not in cur: cur[part] = TreeMap() if i != last else leaf_value elif i == last: # found leaf ...
def insert(self, parts, leaf_value, update=False)
Add a list of nodes into the tree. The list will be converted into a TreeMap (chain) and then merged with the current TreeMap. For example, this method would insert `['a','b','c']` as `{'a':{'b':{'c':{}}}}`. Arguments: parts: List of nodes representing a chain. ...
2.859587
2.926147
0.977253
if isinstance(obj, OrderedDict): return _TaggedOrderedDict(obj, *args, **kwargs) else: return _TaggedPlainDict(obj, *args, **kwargs)
def tag_dict(obj, *args, **kwargs)
Create a TaggedDict instance. Will either be a TaggedOrderedDict or TaggedPlainDict depending on the type of `obj`.
3.524932
2.042351
1.725919
for join in six.itervalues(queryset.query.alias_map): if join.join_type: return True return False
def has_joins(queryset)
Return True iff. a queryset includes joins. If this is the case, it is possible for the queryset to return duplicate results.
4.105365
4.559932
0.900313
rewritten = [] last = len(self.field) - 1 s = serializer field = None for i, field_name in enumerate(self.field): # Note: .fields can be empty for related serializers that aren't # sideloaded. Fields that are deferred also won't be present. ...
def generate_query_key(self, serializer)
Get the key that can be passed to Django's filter method. To account for serialier field name rewrites, this method translates serializer field names to model field names by inspecting `serializer`. For example, a query like `filter{users.events}` would be returned as `users__e...
3.901089
3.838785
1.01623
self.request = request self.view = view # enable addition of extra filters (i.e., a Q()) # so custom filters can be added to the queryset without # running into https://code.djangoproject.com/ticket/18437 # which, without this, would mean that filters added to t...
def filter_queryset(self, request, queryset, view)
Filter the queryset. This is the main entry-point to this class, and is called by DRF's list handler.
6.121601
6.200184
0.987326
filters_map = ( kwargs.get('filters_map') or self.view.get_request_feature(self.view.FILTER) ) out = TreeMap() for spec, value in six.iteritems(filters_map): # Inclusion or exclusion? if spec[0] == '-': spec = s...
def _get_requested_filters(self, **kwargs)
Convert 'filters' query params into a dict that can be passed to Q. Returns a dict with two fields, 'include' and 'exclude', which can be used like: result = self._get_requested_filters() q = Q(**result['include'] & ~Q(**result['exclude'])
4.284481
4.249173
1.008309
def rewrite_filters(filters, serializer): out = {} for k, node in six.iteritems(filters): filter_key, field = node.generate_query_key(serializer) if isinstance(field, (BooleanField, NullBooleanField)): node.value = is_truthy(n...
def _filters_to_query(self, includes, excludes, serializer, q=None)
Construct Django Query object from request. Arguments are dictionaries, which will be passed to Q() as kwargs. e.g. includes = { 'foo' : 'bar', 'baz__in' : [1, 2] } produces: Q(foo='bar', baz__in=[1, 2]) Arguments: includes: TreeMap representing incl...
2.903503
2.964891
0.979295
for source, remainder in six.iteritems(requirements): if not remainder or isinstance(remainder, six.string_types): # no further requirements to prefetch continue related_field = get_model_field(model, source) related_model = get_rela...
def _build_implicit_prefetches( self, model, prefetches, requirements )
Build a prefetch dictionary based on internal requirements.
3.824718
3.720181
1.0281
queryset = self._make_model_queryset(model) prefetches = {} self._build_implicit_prefetches( model, prefetches, requirements ) prefetch = prefetches.values() queryset = queryset.prefetch_related(*prefetch).distinct() i...
def _build_implicit_queryset(self, model, requirements)
Build a queryset based on implicit requirements.
5.247133
5.054183
1.038176
for name, field in six.iteritems(fields): original_field = field if isinstance(field, DynamicRelationField): field = field.serializer if isinstance(field, serializers.ListSerializer): field = field.child if not isinstance(...
def _build_requested_prefetches( self, prefetches, requirements, model, fields, filters )
Build a prefetch dictionary based on request requirements.
4.801482
4.716257
1.01807
for name, field in six.iteritems(fields): source = field.source # Requires may be manually set on the field -- if not, # assume the field requires only its source. requires = getattr(field, 'requires', None) or [source] for require in requires...
def _get_implicit_requirements( self, fields, requirements )
Extract internal prefetch requirements from serializer fields.
7.83876
7.1955
1.089398
is_root_level = False if not serializer: serializer = self.view.get_serializer() is_root_level = True queryset = self._get_queryset(queryset=queryset, serializer=serializer) model = getattr(serializer.Meta, 'model', None) if not model: ...
def _build_queryset( self, serializer=None, filters=None, queryset=None, requirements=None, extra_filters=None, disable_prefetches=False, )
Build a queryset that pulls in all data required by this request. Handles nested prefetching of related data and deferring fields at the queryset level. Arguments: serializer: An optional serializer to use a base for the queryset. If no serializer is passed, the `ge...
5.128579
5.210115
0.98435
self.ordering_param = view.SORT ordering = self.get_ordering(request, queryset, view) if ordering: return queryset.order_by(*ordering) return queryset
def filter_queryset(self, request, queryset, view)
Filter the queryset, applying the ordering. The `ordering_param` can be overwritten here. In DRF, the ordering_param is 'ordering', but we support changing it to allow the viewset to control the parameter.
4.064722
3.342917
1.21592
params = view.get_request_feature(view.SORT) if params: fields = [param.strip() for param in params] valid_ordering, invalid_ordering = self.remove_invalid_fields( queryset, fields, view ) # if any of the sort fields are invalid, ...
def get_ordering(self, request, queryset, view)
Return an ordering for a given request. DRF expects a comma separated list, while DREST expects an array. This method overwrites the DRF default so it can parse the array.
5.04222
4.589079
1.098743
valid_orderings = [] invalid_orderings = [] # for each field sent down from the query param, # determine if its valid or invalid for term in fields: stripped_term = term.lstrip('-') # add back the '-' add the end if necessary reverse...
def remove_invalid_fields(self, queryset, fields, view)
Remove invalid fields from an ordering. Overwrites the DRF default remove_invalid_fields method to return both the valid orderings and any invalid orderings.
4.744948
4.196001
1.130826
if not self._is_allowed_term(term, view): return None serializer = self._get_serializer_class(view)() serializer_chain = term.split('.') model_chain = [] for segment in serializer_chain[:-1]: field = serializer.get_all_fields().get(segment) ...
def ordering_for(self, term, view)
Return ordering (model field chain) for term (serializer field chain) or None if invalid Raise ImproperlyConfigured if serializer_class not set on view
3.060701
2.834386
1.079846
retval = "" if encoder is None: encoder = TomlEncoder(o.__class__) addtoretval, sections = encoder.dump_sections(o, "") retval += addtoretval outer_objs = [id(o)] while sections: section_ids = [id(section) for section in sections] for outer_obj in outer_objs: ...
def dumps(o, encoder=None)
Stringifies input dict as toml Args: o: Object to dump into toml preserve: Boolean parameter. If true, preserve inline tables. Returns: String containing the toml corresponding to dict
3.550509
3.714633
0.955817
# Yield left border. if left: yield left # Yield items with intersect characters. if intersect: try: for j, i in enumerate(line, start=-len(line) + 1): yield i if j: yield intersect except TypeError: # Generat...
def combine(line, left, intersect, right)
Zip borders between items in `line`. e.g. ('l', '1', 'c', '2', 'c', '3', 'r') :param iter line: List to iterate. :param left: Left border. :param intersect: Column separator. :param right: Right border. :return: Yields combined objects.
4.110333
3.697084
1.111777
length = 0 # Hide title if it doesn't fit. if title is not None and outer_widths: try: length = visible_width(title) except TypeError: title = str(title) length = visible_width(title) if length > sum(outer_widths) + len(intersect) * (len(oute...
def build_border(outer_widths, horizontal, left, intersect, right, title=None)
Build the top/bottom/middle row. Optionally embed the table title within the border. Title is hidden if it doesn't fit between the left/right characters/edges. Example return value: ('<', '-----', '+', '------', '+', '-------', '>') ('<', 'My Table', '----', '+', '------->') :param iter outer_wid...
3.661193
3.656146
1.001381
if not row or not row[0]: yield combine((), left, center, right) return for row_index in range(len(row[0])): yield combine((c[row_index] for c in row), left, center, right)
def build_row(row, left, center, right)
Combine single or multi-lined cells into a single row of list of lists including borders. Row must already be padded and extended so each cell has the same number of lines. Example return value: [ ['>', 'Left ', '|', 'Center', '|', 'Right', '<'], ['>', 'Cell1', '|', 'Cell2 ', '|', 'Cell3',...
4.060206
4.656195
0.872001
project = __import__(IMPORT, fromlist=['']) for expected, var in [('@Robpol86', '__author__'), (LICENSE, '__license__'), (VERSION, '__version__')]: if getattr(project, var) != expected: raise SystemExit('Mismatch: {0}'.format(var)) # Check changelog. ...
def run(cls)
Check variables.
5.243244
5.054718
1.037297
if handle == INVALID_HANDLE_VALUE: raise OSError('Invalid handle.') # Query Win32 API. lpcsbi = ctypes.create_string_buffer(22) # Populated by GetConsoleScreenBufferInfo. if not kernel32.GetConsoleScreenBufferInfo(handle, lpcsbi): raise ctypes.WinError() # Subclass of OSError. ...
def get_console_info(kernel32, handle)
Get information about this current console window (Windows only). https://github.com/Robpol86/colorclass/blob/ab42da59/colorclass/windows.py#L111 :raise OSError: When handle is invalid or GetConsoleScreenBufferInfo API call fails. :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance. :par...
3.399062
3.519606
0.965751
if IS_WINDOWS: kernel32 = kernel32 or ctypes.windll.kernel32 try: return get_console_info(kernel32, kernel32.GetStdHandle(STD_ERROR_HANDLE)) except OSError: try: return get_console_info(kernel32, kernel32.GetStdHandle(STD_OUTPUT_HANDLE)) ...
def terminal_size(kernel32=None)
Get the width and height of the terminal. http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/ http://stackoverflow.com/questions/17993814/why-the-irrelevant-code-made-a-difference :param kernel32: Optional mock kernel32 object. For testing. :return: Width (number o...
2.187274
2.321512
0.942176
try: title_bytes = title.encode('utf-8') except AttributeError: title_bytes = title if IS_WINDOWS: kernel32 = kernel32 or ctypes.windll.kernel32 try: is_ascii = all(ord(c) < 128 for c in title) # str/unicode. except TypeError: is_ascii =...
def set_terminal_title(title, kernel32=None)
Set the terminal title. :param title: The title to set (string, unicode, bytes accepted). :param kernel32: Optional mock kernel32 object. For testing. :return: If title changed successfully (Windows only, always True on Linux/OSX). :rtype: bool
2.409054
2.301673
1.046653
table_data = [ [Color('{autogreen}<10ms{/autogreen}'), '192.168.0.100, 192.168.0.101'], [Color('{autoyellow}10ms <= 100ms{/autoyellow}'), '192.168.0.102, 192.168.0.103'], [Color('{autored}>100ms{/autored}'), '192.168.0.105'], ] table_instance = SingleTable(table_data) table_...
def table_server_timings()
Return table string to be printed.
2.505861
2.496695
1.003671
table_data = [ [Color('Low Space'), Color('{autocyan}Nominal Space{/autocyan}'), Color('Excessive Space')], [Color('Low Load'), Color('Nominal Load'), Color('{autored}High Load{/autored}')], [Color('{autocyan}Low Free RAM{/autocyan}'), Color('Nominal Free RAM'), Color('High Free RAM')],...
def table_server_status()
Return table string to be printed.
3.381498
3.335776
1.013706
table_instance = SingleTable([['A', 'B'], ['C', 'D']]) # Get first table lines. table_instance.outer_border = False table_inner_borders = table_instance.table.splitlines() # Get second table lines. table_instance.outer_border = True table_instance.inner_heading_row_border = False ...
def table_abcd()
Return table string to be printed. Two tables on one line.
3.325281
3.121938
1.065134
Windows.enable(auto_colors=True, reset_atexit=True) # Does nothing if not on Windows. # Server timings. print(table_server_timings()) print() # Server status. print(table_server_status()) print() # Two A B C D tables. print(table_abcd()) print() # Instructions. ...
def main()
Main function.
10.221087
9.997876
1.022326
inner_widths = max_dimensions(self.table_data)[0] outer_border = 2 if self.outer_border else 0 inner_border = 1 if self.inner_column_border else 0 padding = self.padding_left + self.padding_right return column_max_width(inner_widths, column_number, outer_border, inner_bo...
def column_max_width(self, column_number)
Return the maximum width of a column based on the current terminal width. :param int column_number: The column number to query. :return: The max width of the column. :rtype: int
3.654681
4.123455
0.886315
outer_widths = max_dimensions(self.table_data, self.padding_left, self.padding_right)[2] outer_border = 2 if self.outer_border else 0 inner_border = 1 if self.inner_column_border else 0 return table_width(outer_widths, outer_border, inner_border)
def table_width(self)
Return the width of the table including padding and borders.
4.390187
4.016578
1.093017
horizontal = str(self.CHAR_INNER_HORIZONTAL) left = self.CHAR_OUTER_LEFT_VERTICAL intersect = self.CHAR_INNER_VERTICAL right = self.CHAR_OUTER_RIGHT_VERTICAL columns = list() for i, width in enumerate(outer_widths): justify = self.justify_columns.get...
def horizontal_border(self, _, outer_widths)
Handle the GitHub heading border. E.g.: |:---|:---:|---:|----| :param _: Unused. :param iter outer_widths: List of widths (with padding) for each column. :return: Prepared border strings in a generator. :rtype: iter
3.177056
3.239721
0.980657
for i, row in enumerate(self.table_data): # Yield the row line by line (e.g. multi-line rows). for line in self.gen_row_lines(row, 'row', inner_widths, inner_heights[i]): yield line # Yield heading separator. if i == 0: yie...
def gen_table(self, inner_widths, inner_heights, outer_widths)
Combine everything and yield every line of the entire table with borders. :param iter inner_widths: List of widths (no padding) for each column. :param iter inner_heights: List of heights (no padding) for each row. :param iter outer_widths: List of widths (with padding) for each column. ...
5.258654
5.593904
0.940069
if '\033' in string: string = RE_COLOR_ANSI.sub('', string) # Convert to unicode. try: string = string.decode('u8') except (AttributeError, UnicodeEncodeError): pass width = 0 for char in string: if unicodedata.east_asian_width(char) in ('F', 'W'): ...
def visible_width(string)
Get the visible width of a unicode string. Some CJK unicode characters are more than one byte unlike ASCII and latin unicode characters. From: https://github.com/Robpol86/terminaltables/pull/9 :param str string: String to measure. :return: String's width. :rtype: int
2.794967
3.064211
0.912132
if not hasattr(string, 'splitlines'): string = str(string) # Handle trailing newlines or empty strings, str.splitlines() does not satisfy. lines = string.splitlines() or [''] if string.endswith('\n'): lines.append('') # Vertically align and pad. if 'bottom' in align: ...
def align_and_pad_cell(string, align, inner_dimensions, padding, space=' ')
Align a string horizontally and vertically. Also add additional padding in both dimensions. :param str string: Input string to operate on. :param tuple align: Tuple that contains one of left/center/right and/or top/middle/bottom. :param tuple inner_dimensions: Width and height ints to expand string to with...
2.331966
2.266461
1.028902
inner_widths = [0] * (max(len(r) for r in table_data) if table_data else 0) inner_heights = [0] * len(table_data) # Find max width and heights. for j, row in enumerate(table_data): for i, cell in enumerate(row): if not hasattr(cell, 'count') or not hasattr(cell, 'splitlines'): ...
def max_dimensions(table_data, padding_left=0, padding_right=0, padding_top=0, padding_bottom=0)
Get maximum widths of each column and maximum height of each row. :param iter table_data: List of list of strings (unmodified table data). :param int padding_left: Number of space chars on left side of cell. :param int padding_right: Number of space chars on right side of cell. :param int padding_top: ...
2.308759
2.309049
0.999874
column_count = len(inner_widths) terminal_width = terminal_size()[0] # Count how much space padding, outer, and inner borders take up. non_data_space = outer_border non_data_space += inner_border * (column_count - 1) non_data_space += column_count * padding # Exclude selected column's...
def column_max_width(inner_widths, column_number, outer_border, inner_border, padding)
Determine the maximum width of a column based on the current terminal width. :param iter inner_widths: List of widths (no padding) for each column. :param int column_number: The column number to query. :param int outer_border: Sum of left and right outer border visible widths. :param int inner_border: ...
3.80507
4.389714
0.866815
column_count = len(outer_widths) # Count how much space outer and inner borders take up. non_data_space = outer_border if column_count: non_data_space += inner_border * (column_count - 1) # Space of all columns and their padding. data_space = sum(outer_widths) return data_spac...
def table_width(outer_widths, outer_border, inner_border)
Determine the width of the entire table including borders and padding. :param iter outer_widths: List of widths (with padding) for each column. :param int outer_border: Sum of left and right outer border visible widths. :param int inner_border: Visible width of the inner border character. :return: The...
4.613008
4.863552
0.948485
if style == 'top': horizontal = self.CHAR_OUTER_TOP_HORIZONTAL left = self.CHAR_OUTER_TOP_LEFT intersect = self.CHAR_OUTER_TOP_INTERSECT if self.inner_column_border else '' right = self.CHAR_OUTER_TOP_RIGHT title = self.title elif styl...
def horizontal_border(self, style, outer_widths)
Build any kind of horizontal border for the table. :param str style: Type of border to return. :param iter outer_widths: List of widths (with padding) for each column. :return: Prepared border as a tuple of strings. :rtype: tuple
1.59751
1.589352
1.005133
r cells_in_row = list() # Resize row if it doesn't have enough cells. if len(row) != len(inner_widths): row = row + [''] * (len(inner_widths) - len(row)) # Pad and align each cell. Split each cell into lines to support multi-line cells. for i, cell in enumer...
def gen_row_lines(self, row, style, inner_widths, height)
r"""Combine cells in row and group them into lines with vertical borders. Caller is expected to pass yielded lines to ''.join() to combine them into a printable line. Caller must append newline character to the end of joined line. In: ['Row One Column One', 'Two', 'Three'] Out:...
2.380077
2.376388
1.001552
# Yield top border. if self.outer_border: yield self.horizontal_border('top', outer_widths) # Yield table body. row_count = len(self.table_data) last_row_index, before_last_row_index = row_count - 1, row_count - 2 for i, row in enumerate(self.table_d...
def gen_table(self, inner_widths, inner_heights, outer_widths)
Combine everything and yield every line of the entire table with borders. :param iter inner_widths: List of widths (no padding) for each column. :param iter inner_heights: List of heights (no padding) for each row. :param iter outer_widths: List of widths (with padding) for each column. ...
2.210457
2.250359
0.982268
dimensions = max_dimensions(self.table_data, self.padding_left, self.padding_right)[:3] return flatten(self.gen_table(*dimensions))
def table(self)
Return a large string of the entire table ready to be printed to the terminal.
11.655906
9.653984
1.207367
ascii_table = super(UnixTable, self).table optimized = ascii_table.replace('\033(B\033(0', '') return optimized
def table(self)
Return a large string of the entire table ready to be printed to the terminal.
11.92993
9.790643
1.218503
title = 'Jetta SportWagen' # AsciiTable. table_instance = AsciiTable(TABLE_DATA, title) table_instance.justify_columns[2] = 'right' print(table_instance.table) print() # SingleTable. table_instance = SingleTable(TABLE_DATA, title) table_instance.justify_columns[2] = 'right' ...
def main()
Main function.
2.563854
2.521467
1.01681
table_data = [ ['Long String', ''], # One row. Two columns. Long string will replace this empty string. ] table = SingleTable(table_data) # Calculate newlines. max_width = table.column_max_width(1) wrapped_string = '\n'.join(wrap(LONG_STRING, max_width)) table.table_data[0][1]...
def main()
Main function.
6.306911
6.047026
1.042977
r if (arr.max() > 1.0 + epsilon) or (arr.min() < 0 - epsilon): raise ValueError("Input array must have float values between 0 and 1") if (bias > 1.0 + epsilon) or (bias < 0 - epsilon): raise ValueError("bias must be a scalar float between 0 and 1") alpha, beta = bias, contrast # We...
def sigmoidal(arr, contrast, bias)
r""" Sigmoidal contrast is type of contrast control that adjusts the contrast without saturating highlights or shadows. It allows control over two factors: the contrast range from light to dark, and where the middle value of the mid-tones falls. The result is a non-linear and smooth contrast cha...
3.230598
3.141237
1.028448
r if (arr.max() > 1.0 + epsilon) or (arr.min() < 0 - epsilon): raise ValueError("Input array must have float values between 0 and 1") if g <= 0 or np.isnan(g): raise ValueError("gamma must be greater than 0") return arr ** (1.0 / g)
def gamma(arr, g)
r""" Gamma correction is a nonlinear operation that adjusts the image's channel values pixel-by-pixel according to a power-law: .. math:: pixel_{out} = pixel_{in} ^ {\gamma} Setting gamma (:math:`\gamma`) to be less than 1.0 darkens the image and setting gamma to be greater than 1.0 lightens i...
3.589374
3.633906
0.987745
gamma_b = 1 - haze gamma_g = 1 - (haze / 3.0) ops = ( "gamma g {gamma_g}, " "gamma b {gamma_b}, " "sigmoidal rgb {contrast} {bias}" ).format(gamma_g=gamma_g, gamma_b=gamma_b, contrast=contrast, bias=bias) return ops
def simple_atmo_opstring(haze, contrast, bias)
Make a simple atmospheric correction formula.
3.818087
3.895514
0.980124
gamma_b = 1 - haze gamma_g = 1 - (haze / 3.0) arr = np.empty(shape=(3, rgb.shape[1], rgb.shape[2])) arr[0] = rgb[0] arr[1] = gamma(rgb[1], gamma_g) arr[2] = gamma(rgb[2], gamma_b) output = rgb.copy() output[0:3] = sigmoidal(arr, contrast, bias) return output
def simple_atmo(rgb, haze, contrast, bias)
A simple, static (non-adaptive) atmospheric correction function. Parameters ---------- haze: float Amount of haze to adjust for. For example, 0.03 contrast : integer Enhances the intensity differences between the lighter and darker elements of the image. For example, 0 is none, ...
3.095839
3.494291
0.885971
def f(arr): # Avoid mutation by copying newarr = arr.copy() if rgb_op: # apply func to array's first 3 bands, assumed r,g,b # additional band(s) are untouched newarr[0:3] = func(newarr[0:3], **kwargs) else: # apply func to array b...
def _op_factory(func, kwargs, opname, bands, rgb_op=False)
create an operation function closure don't call directly, use parse_operations returns a function which itself takes and returns ndarrays
4.120519
4.145517
0.99397
band_lookup = {"r": 1, "g": 2, "b": 3} count = len(band_lookup) opfuncs = {"saturation": saturation, "sigmoidal": sigmoidal, "gamma": gamma} opkwargs = { "saturation": ("proportion",), "sigmoidal": ("contrast", "bias"), "gamma": ("g",), } # Operations that assume ...
def parse_operations(ops_string)
Takes a string of operations written with a handy DSL "OPERATION-NAME BANDS ARG1 ARG2 OPERATION-NAME BANDS ARG" And returns a list of functions, each of which take and return ndarrays
3.260816
3.288648
0.991537
if jobs == 0: raise click.UsageError("Jobs must be >= 1 or == -1") elif jobs < 0: import multiprocessing jobs = multiprocessing.cpu_count() return jobs
def check_jobs(jobs)
Validate number of jobs.
5.936637
4.999826
1.187369
with rasterio.open(src_path) as src: opts = src.profile.copy() windows = [(window, ij) for ij, window in src.block_windows()] opts.update(**creation_options) opts["transform"] = guard_transform(opts["transform"]) out_dtype = out_dtype if out_dtype else opts["dtype"] opts["dtyp...
def color(ctx, jobs, out_dtype, src_path, dst_path, operations, creation_options)
Color correction Operations will be applied to the src image in the specified order. Available OPERATIONS include: \b "gamma BANDS VALUE" Applies a gamma curve, brightening or darkening midtones. VALUE > 1 brightens the image. \b "sigmoidal BANDS CONTRAST BIAS" Adjusts the contrast a...
4.03118
4.357277
0.92516
if as_color: click.echo( "rio color {} {} {}".format( src_path, dst_path, simple_atmo_opstring(atmo, contrast, bias) ) ) exit(0) with rasterio.open(src_path) as src: opts = src.profile.copy() windows = [(window, ij) for ij, wi...
def atmos( ctx, atmo, contrast, bias, jobs, out_dtype, src_path, dst_path, creation_options, as_color, )
Atmospheric correction
3.115274
3.100151
1.004878
max_int = np.iinfo(arr.dtype).max return arr.astype(math_type) / max_int
def to_math_type(arr)
Convert an array from native integer dtype range to 0..1 scaling down linearly
4.301767
4.772754
0.901318
max_int = np.iinfo(dtype).max return (arr * max_int).astype(dtype)
def scale_dtype(arr, dtype)
Convert an array from 0..1 to dtype, scaling up linearly
3.412909
3.467562
0.984239
ops = [] bands = None def set_band(x): global bands if x.upper() == "RGB": x = "RGB" bands = x.upper() set_band("RGB") def append_sig(arg): global bands args = list(filter(None, re.split("[,x]+", arg))) if len(args) == 1: ...
def magick_to_rio(convert_opts)
Translate a limited subset of imagemagick convert commands to rio color operations Parameters ---------- convert_opts: String, imagemagick convert options Returns ------- operations string, ordered rio color operations
2.92764
3.00491
0.974285
s = int(round(seconds)) # round to nearest second h, s = divmod(s, 3600) # get hours and remainder m, s = divmod(s, 60) # split remainder into minutes and seconds return "%2i:%02i:%02i" % (h, m, s)
def time_string(seconds)
Returns time in seconds as a string formatted HHHH:MM:SS.
2.452749
2.301557
1.065691
text = .format( **locals() ) return text
def progress_report( curr, best, curr_score, best_score, step, totalsteps, accept, improv, elaps, remain )
Report progress
27.649345
20.009493
1.381811
eps = 1e-6 assert arr1.min() > 0 - eps assert arr1.max() < 1 + eps assert arr2.min() > 0 - eps assert arr2.max() < 1 + eps if not bins: bins = [x / 10 for x in range(11)] hist1 = np.histogram(arr1, bins=bins)[0] / arr1.size hist2 = np.histogram(arr2, bins=bins)[0] / arr2.si...
def histogram_distance(arr1, arr2, bins=None)
This function returns the sum of the squared error Parameters: two arrays constrained to 0..1 Returns: sum of the squared error between the histograms
1.852405
1.928688
0.960448
if w > h: return h / target elif h >= w: return w / target
def calc_downsample(w, h, target=400)
Calculate downsampling value.
4.927862
4.24332
1.161322
global fig, txt, imgs click.echo("Reading source data...", err=True) with rasterio.open(source) as src: if downsample is None: ratio = calc_downsample(src.width, src.height) else: ratio = downsample w = int(src.width // ratio) h = int(src.height ...
def main(source, reference, downsample, steps, plot)
Given a source image and a reference image, Find the rio color formula which results in an output with similar histogram to the reference image. Uses simulated annealing to determine optimal settings. Increase the --downsample option to speed things up. Increase the --steps to get better results (...
2.670158
2.57964
1.035089
k = random.choice(self.keys) multiplier = random.choice((0.95, 1.05)) invalid_key = True while invalid_key: # make sure bias doesn't exceed 1.0 if k == "bias": if self.state[k] > 0.909: k = random.choice(self.keys) ...
def move(self)
Create a state change.
4.401003
4.202369
1.047267
ops = self.cmd(state) for func in parse_operations(ops): arr = func(arr) return arr
def apply_color(self, arr, state)
Apply color formula to an array.
12.344332
10.635267
1.160698
arr = self.src.copy() arr = self.apply_color(arr, self.state) scores = [histogram_distance(self.ref[i], arr[i]) for i in range(3)] # Important: scale by 100 for readability return sum(scores) * 100
def energy(self)
Calculate state's energy.
8.502007
8.54991
0.994397
if acceptance is None: acceptance = 0 if improvement is None: improvement = 0 if step > 0: elapsed = time.time() - self.start remain = (self.steps - step) * (elapsed / step) # print('Time {} ({} Remaing)'.format(time_string(el...
def update(self, step, T, E, acceptance, improvement)
Print progress.
3.262991
3.213576
1.015377
src = srcs[0] rgb = src.read(window=window) rgb = to_math_type(rgb) atmos = simple_atmo(rgb, args["atmo"], args["contrast"], args["bias"]) # should be scaled 0 to 1, scale to outtype return scale_dtype(atmos, args["out_dtype"])
def atmos_worker(srcs, window, ij, args)
A simple atmospheric correction user function.
8.387779
8.461586
0.991277
src = srcs[0] arr = src.read(window=window) arr = to_math_type(arr) for func in parse_operations(args["ops_string"]): arr = func(arr) # scaled 0 to 1, now scale to outtype return scale_dtype(arr, args["out_dtype"])
def color_worker(srcs, window, ij, args)
A user function.
8.6116
8.936687
0.963623
if holes is None: holes = [] else: assert make_surface # Define points that make the circle (midpoint and the four cardinal # directions). X = numpy.zeros((num_sections + 1, len(x0))) if num_sections == 4: # For accuracy, the ...
def add_circle( self, x0, radius, lcar=None, R=None, compound=False, num_sections=3, holes=None, make_surface=True, )
Add circle in the :math:`x`-:math:`y`-plane.
2.416158
2.410197
1.002473
if _is_string(string_or_list): self._GMSH_CODE.append(string_or_list) else: assert isinstance(string_or_list, list) for string in string_or_list: self._GMSH_CODE.append(string) return
def add_raw_code(self, string_or_list)
Add raw Gmsh code.
2.714393
2.139814
1.268518
self.add_comment("Torus") # Add circle x0t = numpy.dot(R, numpy.array([0.0, orad, 0.0])) # Get circles in y-z plane Rc = numpy.array([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]) c = self.add_circle(x0 + x0t, irad, lcar=lcar, R=numpy.dot(R, Rc)) ...
def _add_torus_extrude_lines( self, irad, orad, lcar=None, R=numpy.eye(3), x0=numpy.array([0.0, 0.0, 0.0]) )
Create Gmsh code for the torus in the x-y plane under the coordinate transformation .. math:: \\hat{x} = R x + x_0. :param irad: inner radius of the torus :param orad: outer radius of the torus
4.413547
4.49758
0.981316
self.add_comment(76 * "-") self.add_comment("Torus") # Add circle x0t = numpy.dot(R, numpy.array([0.0, orad, 0.0])) Rc = numpy.array([[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]) c = self.add_circle(x0 + x0t, irad, lcar=lcar, R=numpy.dot(R, Rc)) ...
def _add_torus_extrude_circle( self, irad, orad, lcar=None, R=numpy.eye(3), x0=numpy.array([0.0, 0.0, 0.0]) )
Create Gmsh code for the torus under the coordinate transformation .. math:: \\hat{x} = R x + x_0. :param irad: inner radius of the torus :param orad: outer radius of the torus
4.128109
4.216258
0.979093
self.add_comment("Define rectangle.") X = numpy.array( [ [0.0, outer_radius, -0.5 * length], [0.0, outer_radius, +0.5 * length], [0.0, inner_radius, +0.5 * length], [0.0, inner_radius, -0.5 * length], ] ...
def _add_pipe_by_rectangle_rotation( self, outer_radius, inner_radius, length, R=numpy.eye(3), x0=numpy.array([0.0, 0.0, 0.0]), lcar=None, )
Hollow cylinder. Define a rectangle, extrude it by rotation.
3.118899
3.100935
1.005793
# Define ring which to Extrude by translation. Rc = numpy.array([[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]) c_inner = self.add_circle( x0, inner_radius, lcar=lcar, R=numpy.dot(R, Rc), make_surface=False ) circ = self.add_circle( x0, outer...
def _add_pipe_by_circle_extrusion( self, outer_radius, inner_radius, length, R=numpy.eye(3), x0=numpy.array([0.0, 0.0, 0.0]), lcar=None, )
Hollow cylinder. Define a ring, extrude it by translation.
3.489988
3.362623
1.037877
d = {1: "Line", 2: "Surface", 3: "Volume"} self._GMSH_CODE.append( "Translate {{{}}} {{ {}{{{}}}; }}".format( ", ".join([str(co) for co in vector]), d[input_entity.dimension], input_entity.id, ) ) return
def translate(self, input_entity, vector)
Translates input_entity itself by vector. Changes the input object.
6.621375
6.793502
0.974663
d = {1: "Line", 2: "Surface", 3: "Volume"} entity = "{}{{{}}};".format(d[input_entity.dimension], input_entity.id) if duplicate: entity = "Duplicata{{{}}}".format(entity) self._GMSH_CODE.append( "Symmetry {{{}}} {{{}}}".format( ", ".join...
def symmetry(self, input_entity, coefficients, duplicate=True)
Transforms all elementary entities symmetrically to a plane. The vector should contain four expressions giving the coefficients of the plane's equation.
5.261308
5.768439
0.912085
self._BOOLEAN_ID += 1 # assert that all entities are of the same dimensionality dim = None legal_dim_types = {1: "Line", 2: "Surface", 3: "Volume"} for ldt in legal_dim_types: if input_entities[0].dimension == ldt: dim = ldt b...
def _boolean_operation( self, operation, input_entities, tool_entities, delete_first=True, delete_other=True, )
Boolean operations, see https://gmsh.info/doc/texinfo/gmsh.html#Boolean-operations input_entity and tool_entity are called object and tool in gmsh documentation.
3.076843
2.958345
1.040056
assert len(entities) > 1 return self._boolean_operation( "BooleanIntersection", [entities[0]], entities[1:], delete_first=delete_first, delete_other=delete_other, )
def boolean_intersection(self, entities, delete_first=True, delete_other=True)
Boolean intersection, see https://gmsh.info/doc/texinfo/gmsh.html#Boolean-operations input_entity and tool_entity are called object and tool in gmsh documentation.
3.218185
3.045224
1.056798
out = self._boolean_operation( "BooleanUnion", [entities[0]], entities[1:], delete_first=delete_first, delete_other=delete_other, ) # Cannot add Compound Surface yet; see # <https://gitlab.onelab.info/gmsh/gmsh/issues/5...
def boolean_union(self, entities, delete_first=True, delete_other=True)
Boolean union, see https://gmsh.info/doc/texinfo/gmsh.html#Boolean-operations input_entity and tool_entity are called object and tool in gmsh documentation.
5.83848
5.727369
1.0194
assert numpy.isclose(numpy.inner(u, u), 1.0), "the rotation axis must be unitary" # Cross-product matrix. cpm = numpy.array([[0.0, -u[2], u[1]], [u[2], 0.0, -u[0]], [-u[1], u[0], 0.0]]) c = numpy.cos(theta) s = numpy.sin(theta) R = numpy.eye(3) * c + s * cpm + (1.0 - c) * numpy.outer(u, u)...
def rotation_matrix(u, theta)
Return matrix that implements the rotation around the vector :math:`u` by the angle :math:`\\theta`, cf. https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle. :param u: rotation vector :param theta: rotation angle
2.158355
2.328215
0.927043
def getexistingdirectory(parent=None, caption='', basedir='', options=QFileDialog.ShowDirsOnly): # Calling QFileDialog static method if sys.platform == "win32": # On Windows platforms: redirect standard outputs _temp1, _temp2 = sys.stdout, sys.stderr ...
Wrapper around QtGui.QFileDialog.getExistingDirectory static method Compatible with PyQt >=v4.4 (API #1 and #2) and PySide >=v1.0
null
null
null
def getopenfilename(parent=None, caption='', basedir='', filters='', selectedfilter='', options=None): return _qfiledialog_wrapper('getOpenFileName', parent=parent, caption=caption, basedir=basedir, filters=filters, select...
Wrapper around QtGui.QFileDialog.getOpenFileName static method Returns a tuple (filename, selectedfilter) -- when dialog box is canceled, returns a tuple of empty strings Compatible with PyQt >=v4.4 (API #1 and #2) and PySide >=v1.0
null
null
null
def getopenfilenames(parent=None, caption='', basedir='', filters='', selectedfilter='', options=None): return _qfiledialog_wrapper('getOpenFileNames', parent=parent, caption=caption, basedir=basedir, filters=filters, sel...
Wrapper around QtGui.QFileDialog.getOpenFileNames static method Returns a tuple (filenames, selectedfilter) -- when dialog box is canceled, returns a tuple (empty list, empty string) Compatible with PyQt >=v4.4 (API #1 and #2) and PySide >=v1.0
null
null
null
def getsavefilename(parent=None, caption='', basedir='', filters='', selectedfilter='', options=None): return _qfiledialog_wrapper('getSaveFileName', parent=parent, caption=caption, basedir=basedir, filters=filters, select...
Wrapper around QtGui.QFileDialog.getSaveFileName static method Returns a tuple (filename, selectedfilter) -- when dialog box is canceled, returns a tuple of empty strings Compatible with PyQt >=v4.4 (API #1 and #2) and PySide >=v1.0
null
null
null
from ..QtGui import QIcon from ..QtCore import Qt, QObject class userDataWrapper(): def __init__(self, data): self.data = data _addItem = QComboBox.addItem def addItem(self, *args, **kwargs): if len(args) == 3 or (not isinstance(args[0], QIcon) ...
def patch_qcombobox(QComboBox)
In PySide, using Python objects as userData in QComboBox causes Segmentation faults under certain conditions. Even in cases where it doesn't, findData does not work correctly. Likewise, findData also does not work correctly with Python objects when using PyQt4. On the other hand, PyQt5 deals with this c...
1.727875
1.702693
1.01479
if isinstance(traffic, Traffic): if "baro_altitude" in traffic.data.columns: traffic = traffic.query("baro_altitude == baro_altitude") elif "altitude" in traffic.data.columns: traffic = traffic.query("altitude == altitude") if minimum_time is not None: mini...
def to_czml( traffic: Union[Traffic, SO6], filename: Union[str, Path], minimum_time: Optional[timelike] = None, ) -> None
Generates a CesiumJS scenario file.
2.974452
2.864708
1.038309
return ax.scatter( self.df.longitude, self.df.latitude, s=s, transform=PlateCarree(), c=-self.df.altitude, cmap=cmap, **kwargs, )
def plot( self, ax: GeoAxesSubplot, cmap: str = "inferno", s: int = 5, **kwargs ) -> Artist
Plotting function. All arguments are passed to ax.scatter
2.781139
2.711514
1.025677
if "facecolor" not in kwargs: kwargs["facecolor"] = "None" if "edgecolor" not in kwargs: kwargs["edgecolor"] = ax._get_lines.get_next_color() if "projection" in ax.__dict__: return ax.add_geometries([self.shape], crs=PlateCarree(), **kwargs) ...
def plot(self, ax: GeoAxesSubplot, **kwargs) -> Artist
Plotting function. All arguments are passed to the geometry
2.960919
3.099264
0.955362
what = "own" if (own and self.auth is not None) else "all" if bounds is not None: try: # thinking of shapely bounds attribute (in this order) # I just don't want to add the shapely dependency here west, south, east, north = bounds.bo...
def api_states( self, own: bool = False, bounds: Union[ BaseGeometry, Tuple[float, float, float, float], None ] = None, ) -> StateVectors
Returns the current state vectors from OpenSky REST API. If own parameter is set to True, returns only the state vectors associated to own sensors (requires authentication) bounds parameter can be a shape or a tuple of float. Official documentation ---------------------- ...
4.418771
4.562349
0.96853
c = requests.get( f"https://opensky-network.org/api/tracks/?icao24={icao24}" ) if c.status_code != 200: raise ValueError(c.content.decode()) json = c.json() df = pd.DataFrame.from_records( json["path"], columns=[ ...
def api_tracks(self, icao24: str) -> Flight
Returns a Flight corresponding to a given aircraft. Official documentation ---------------------- Retrieve the trajectory for a certain aircraft at a given time. The trajectory is a list of waypoints containing position, barometric altitude, true track and an on-ground flag. ...
3.099209
3.276657
0.945845
from .. import airports c = requests.get( f"https://opensky-network.org/api/routes?callsign={callsign}" ) if c.status_code == 404: raise ValueError("Unknown callsign") if c.status_code != 200: raise ValueError(c.content.decode()) ...
def api_routes(self, callsign: str) -> Tuple[Airport, ...]
Returns the route associated to a callsign.
2.971398
2.808924
1.057842
if begin is None: begin = round_time(datetime.now(timezone.utc), by=timedelta(days=1)) begin = to_datetime(begin) if end is None: end = begin + timedelta(days=1) else: end = to_datetime(end) begin = int(begin.timestamp()) end...
def api_aircraft( self, icao24: str, begin: Optional[timelike] = None, end: Optional[timelike] = None, ) -> pd.DataFrame
Returns a flight table associated to an aircraft. Official documentation ---------------------- This API call retrieves flights for a particular aircraft within a certain time interval. Resulting flights departed and arrived within [begin, end]. If no flights are found for the ...
2.086445
2.20181
0.947604
today = round_time(datetime.now(timezone.utc), by=timedelta(days=1)) c = requests.get( f"https://opensky-network.org/api/sensor/myStats" f"?days={int(today.timestamp())}", auth=self.auth, ) if c.status_code != 200: raise ValueError...
def api_sensors(self) -> Set[str]
The set of sensors serials you own (require authentication).
4.290527
4.109511
1.044048
if date is None: date = round_time(datetime.now(timezone.utc), by=timedelta(days=1)) else: date = to_datetime(date) date = int(date.timestamp()) c = requests.get( f"https://opensky-network.org/api/range/days" f"?days={date}&seria...
def api_range( self, serial: str, date: Optional[timelike] = None ) -> SensorRange
Wraps a polygon representing a sensor's range. By default, returns the current range. Otherwise, you may enter a specific day (as a string, as an epoch or as a datetime)
3.428815
3.583991
0.956703
if isinstance(airport, str): from .. import airports airport_code = airports[airport].icao else: airport_code = airport.icao if begin is None: begin = round_time(datetime.now(timezone.utc), by=timedelta(days=1)) begin = to_datet...
def api_arrival( self, airport: Union[str, Airport], begin: Optional[timelike] = None, end: Optional[timelike] = None, ) -> pd.DataFrame
Returns a flight table associated to an airport. By default, returns the current table. Otherwise, you may enter a specific date (as a string, as an epoch or as a datetime) Official documentation ---------------------- Retrieve flights for a certain airport which arrived withi...
2.159962
2.233968
0.966872
start = self.data.timestamp.min() self.data = self.data.assign(start=start) return start
def start(self) -> pd.Timestamp
Returns the minimum timestamp value of the DataFrame.
5.059557
3.97067
1.274233
if "number" not in self.data.columns: return None if all(self.data.number.isna()): return None tmp = set(self.data.number) if len(tmp) == 1: return tmp.pop() logging.warn("Several numbers for one flight, consider splitting") re...
def number(self) -> Optional[Union[str, Set[str]]]
Returns the unique number value(s) of the DataFrame.
4.163469
4.188702
0.993976