docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. Raises: Exc...
def unpack(self, buff, offset=0): header = UBInt16() header.unpack(buff[offset:offset+2]) self.tlv_type = header.value >> 9 length = header.value & 511 begin, end = offset + 2, offset + 2 + length sub_type = UBInt8() sub_type.unpack(buff[begin:begin+1]) ...
593,091
Unpack the OpenFlow Packet and returns a message. Args: packet: buffer with the openflow packet. Returns: GenericMessage: Message unpacked based on openflow packet. Raises: UnpackException: if the packet can't be unpacked.
def unpack(packet): validate_packet(packet) version = packet[0] try: pyof_lib = PYOF_VERSION_LIBS[version] except KeyError: raise UnpackException('Version not supported') try: message = pyof_lib.common.utils.unpack_message(packet) return message except (Unp...
593,096
Create a SetConfig with the optional parameters below. Args: xid (int): xid to be used on the message header. flags (:class:`~pyof.v0x01.controller2switch.common.ConfigFlag`): OFPC_* flags. miss_send_len (int): UBInt16 max bytes of new flow that the ...
def __init__(self, xid=None, flags=ConfigFlag.OFPC_FRAG_NORMAL, miss_send_len=ControllerMaxLen.OFPCML_NO_BUFFER): super().__init__(xid, flags, miss_send_len) self.header.message_type = Type.OFPT_SET_CONFIG
593,102
Create a ExperimenterHeader with the optional parameters below. Args: xid (int): xid to be used on the message header. experimenter (int): Vendor ID: MSB 0: low-order bytes are IEEE OUI. MSB != 0: defined by ONF. exp_type (int): Experimenter d...
def __init__(self, xid=None, experimenter=None, exp_type=None, data=b''): super().__init__(xid) self.experimenter = experimenter self.exp_type = exp_type self.data = data
593,106
Create a GroupMod with the optional parameters below. Args: xid (int): Header's transaction id. Defaults to random. command (GroupModCommand): One of OFPGC_*. group_type (GroupType): One of OFPGT_*. group_id (int): Group identifier. buckets (:class:`L...
def __init__(self, xid=None, command=None, group_type=None, group_id=None, buckets=None): super().__init__(xid) self.command = command self.group_type = group_type self.group_id = group_id self.buckets = buckets
593,107
Create a QueuePropHeader with the optional parameters below. Args: queue_property (~pyof.v0x04.common.queue.QueueProperties): The queue property. length (int): Length of property, including this header.
def __init__(self, queue_property=None, length=None): super().__init__() self.queue_property = queue_property self.length = length
593,108
Create a PacketQueue with the optional parameters below. Args: queue_id (int): ID of the specific queue. port (int): Port his queue is attached to. length (int): Length in bytes of this queue desc. properties(~pyof.v0x04.common.queue.ListOfProperties): ...
def __init__(self, queue_id=None, port=None, length=None, properties=None): super().__init__() self.queue_id = queue_id self.port = port self.length = length self.properties = [] if properties is None else properties
593,109
Create a QueuePropExperimenter with the optional parameters below. Args: experimenter (int): Experimenter ID which takes the same form as in struct ofp_experimenter_header. data (bytes): Experimenter defined data.
def __init__(self, experimenter=None, data=None): super().__init__() self.experimenter = experimenter self.data = data
593,110
Create a QueueGetConfigReply with the optional parameters below. Args: xid (int): xid of OpenFlow header. port (:class:`~pyof.v0x04.common.port.PortNo`): Target port for the query. queue (:class:`~pyof.v0x04.common.queue.ListOfQueues`): List o...
def __init__(self, xid=None, port=None, queues=None): super().__init__(xid) self.port = port self.queues = [] if queues is None else queues
593,111
Assing parameters to object attributes. Args: xid (int): :class:`~pyof.v0x04.common.header.Header`'s xid. Defaults to random. table_id (int): ID of the table, OFPTT_ALL indicates all tables. config (int): Bitmap of OFPTC_* flags
def __init__(self, xid=None, table_id=Table.OFPTT_ALL, config=3): super().__init__(xid) self.table_id = table_id # This is reserved for future used. The default value is the only valid # one from the Enum. self.config = config
593,112
Create a SetConfig with the optional parameters below. Args: xid (int): xid to be used on the message header. flags (~pyof.v0x01.controller2switch.common.ConfigFlag): OFPC_* flags. miss_send_len (int): UBInt16 max bytes of new flow that the da...
def __init__(self, xid=None, flags=None, miss_send_len=None): super().__init__(xid, flags, miss_send_len) self.header.message_type = Type.OFPT_SET_CONFIG
593,113
Registers a new operator function in the test engine. Arguments: *args: variadic arguments. **kw: variadic keyword arguments. Returns: function
def operator(name=None, operators=None, aliases=None, kind=None): def delegator(assertion, subject, expected, *args, **kw): return assertion.test(subject, expected, *args, **kw) def decorator(fn): operator = Operator(fn=fn, aliases=aliases, kind=kind) _name = name if isinstance(nam...
593,757
Registers a new attribute only operator function in the test engine. Arguments: *args: variadic arguments. **kw: variadic keyword arguments. Returns: function
def attribute(*args, **kw): return operator(kind=Operator.Type.ATTRIBUTE, *args, **kw)
593,758
This will return a node with a param_list (declared in a function declaration) Parameters: -node: A SymbolPARAMLIST instance or None -params: SymbolPARAMDECL insances
def make_node(clss, node, *params): if node is None: node = clss() if node.token != 'PARAMLIST': return clss.make_node(None, node, *params) for i in params: if i is not None: node.appendChild(i) return node
594,404
Creates a binary node for a binary operation, e.g. A + 6 => '+' (A, 6) in prefix notation. Parameters: -operator: the binary operation token. e.g. 'PLUS' for A + 6 -left: left operand -right: right operand -func: is a lambda function used when con...
def make_node(cls, operator, left, right, lineno, func=None, type_=None): if left is None or right is None: return None a, b = left, right # short form names # Check for constant non-numeric operations c_type = common_type(a, b) # Resulting opera...
594,408
Creates a node for a unary operation. E.g. -x or LEN(a$) Parameters: -func: function used on constant folding when possible -type_: the resulting type (by default, the same as the argument). For example, for LEN (str$), result type is 'u16' and arg type i...
def make_node(cls, lineno, fname, func=None, type_=None, *operands): if func is not None and len(operands) == 1: # Try constant-folding if is_number(operands[0]) or is_string(operands[0]): # e.g. ABS(-5) return SymbolNUMBER(func(operands[0].value), type_=type_, lineno=line...
594,869
Creates a node for a unary operation. E.g. -x or LEN(a$) Parameters: -func: lambda function used on constant folding when possible -type_: the resulting type (by default, the same as the argument). For example, for LEN (str$), result type is 'u16' and arg...
def make_node(cls, lineno, operator, operand, func=None, type_=None): assert type_ is None or isinstance(type_, SymbolTYPE) if func is not None: # Try constant-folding if is_number(operand): # e.g. ABS(-5) return SymbolNUMBER(func(operand.value), lineno=lineno) ...
595,109
This function will delete tplot variables that are already stored in memory. Parameters: name : str Name of the tplot variable to be deleted. If no name is provided, then all tplot variables will be deleted. Returns: None Examples: ...
def del_data(name=None): if name is None: tplot_names = list(data_quants.keys()) for i in tplot_names: del data_quants[i] return if not isinstance(name, list): name = [name] entries = [] ### for i in name: if ('?' in i) or ('*'...
595,263
This function will rename tplot variables that are already stored in memory. Parameters: old_name : str Old name of the Tplot Variable new_name : str New name of the Tplot Variable Returns: None Examples: >>> # Rename Variabl...
def tplot_rename(old_name, new_name): #check if old name is in current dictionary if old_name not in pytplot.data_quants.keys(): print("That name is currently not in pytplot") return #if old name input is a number, convert to corresponding name if isinstance(old_name, int): ...
595,366
Selecting array elements by bitwise and comparison to a given value. Parameters: value : int Value to which array elements are compared to. Returns: array : np.array
def arr_select(value): # function factory def f_eq(arr): return np.equal(np.bitwise_and(arr, value), value) f_eq.__name__ = "arr_bitwise_and_" + str(value) # or use inspect module: inspect.stack()[0][3] return f_eq
595,972
Change dtype of array. Parameters: arr_type : str, np.dtype Character codes (e.g. 'b', '>H'), type strings (e.g. 'i4', 'f8'), Python types (e.g. float, int) and numpy dtypes (e.g. np.uint32) are allowed. Returns: array : np.array
def arr_astype(arr_type): # function factory def f_astype(arr): return arr.astype(arr_type) f_astype.__name__ = "arr_astype_" + str(arr_type) # or use inspect module: inspect.stack()[0][3] return f_astype
595,973
Creates metrics, creating an Indicator if it doesn't already exists Metrics are created for projects that are in pronacs and saved in database. args: metrics: list of names of metrics that will be calculated pronacs: pronacs in dataset that is used to calculate those metrics
def create_finance_metrics(metrics: list, pronacs: list): missing = missing_metrics(metrics, pronacs) print(f"There are {len(missing)} missing metrics!") processors = mp.cpu_count() print(f"Using {processors} processors to calculate metrics!") indicators_qs = FinancialIndicator.objects.filter...
596,655
Calculates indicator value according to metrics weights Uses metrics in database args: recalculate_metrics: If true metrics values are updated before using weights
def fetch_weighted_complexity(self, recalculate_metrics=False): # TODO: implment metrics recalculation max_total = sum( [self.metrics_weights[metric_name] for metric_name in self.metrics_weights] ) total = 0 if recalculate_metrics: self.calculate_...
596,691
Verify if a item is an outlier compared to the other occurrences of the same item, based on his price. Args: item_id: idPlanilhaItens segment_id: idSegmento price: VlUnitarioAprovado
def is_outlier(df, item_id, segment_id, price): if (segment_id, item_id) not in df.index: return False mean = df.loc[(segment_id, item_id)]['mean'] std = df.loc[(segment_id, item_id)]['std'] return gaussian_outlier.is_outlier( x=price, mean=mean, standard_deviation=std )
596,696
Annotate a set of records with stored fields. Args: records: A list or iterator (can be a Query object) chunk_size: The number of records to annotate at once (max 500). Returns: A generator that yields one annotated record at a time.
def annotate(self, records, **kwargs): # Update annotator_params with any kwargs self.annotator_params.update(**kwargs) chunk_size = self.annotator_params.get('chunk_size', self.CHUNK_SIZE) chunk = [] for i, record in enumerate(records): chunk.append(record)...
597,138
Confirms that the keywords don't contain special characters Args: keywords (str) Raises: django.forms.ValidationError
def keywords_special_characters(keywords): invalid_chars = '!\"#$%&\'()*+-./:;<=>?@[\\]^_{|}~\t\n' if any(char in invalid_chars for char in keywords): raise ValidationError(MESSAGE_KEYWORD_SPECIAL_CHARS)
597,155
Confirms that the uploaded image is of supported format. Args: value (File): The file with an `image` property containing the image Raises: django.forms.ValidationError
def image_format(value): if value.image.format.upper() not in constants.ALLOWED_IMAGE_FORMATS: raise ValidationError(MESSAGE_INVALID_IMAGE_FORMAT)
597,156
Confirms that the social media url is pointed at the correct domain. Args: value (string): The url to check. Raises: django.forms.ValidationError
def case_study_social_link_facebook(value): parsed = parse.urlparse(value.lower()) if not parsed.netloc.endswith('facebook.com'): raise ValidationError(MESSAGE_NOT_FACEBOOK)
597,157
Confirms that the social media url is pointed at the correct domain. Args: value (string): The url to check. Raises: django.forms.ValidationError
def case_study_social_link_twitter(value): parsed = parse.urlparse(value.lower()) if not parsed.netloc.endswith('twitter.com'): raise ValidationError(MESSAGE_NOT_TWITTER)
597,158
Confirms that the social media url is pointed at the correct domain. Args: value (string): The url to check. Raises: django.forms.ValidationError
def case_study_social_link_linkedin(value): parsed = parse.urlparse(value.lower()) if not parsed.netloc.endswith('linkedin.com'): raise ValidationError(MESSAGE_NOT_LINKEDIN)
597,159
Confirms that the company number is not for for a company that Companies House does not hold information on. Args: value (string): The company number to check. Raises: django.forms.ValidationError
def no_company_with_insufficient_companies_house_data(value): for prefix, name in company_types_with_insufficient_companies_house_data: if value.upper().startswith(prefix): raise ValidationError( MESSAGE_INSUFFICIENT_DATA, params={'name': name} )
597,160
Removes obvious noise points Checks time consistency, removing points that appear out of order Args: points (:obj:`list` of :obj:`Point`) Returns: :obj:`list` of :obj:`Point`
def remove_liers(points): result = [points[0]] for i in range(1, len(points) - 2): prv = points[i-1] crr = points[i] nxt = points[i+1] if prv.time <= crr.time and crr.time <= nxt.time: result.append(crr) result.append(points[-1]) return result
597,164
Computes the bounds of the segment, or part of it Args: lower_index (int, optional): Start index. Defaults to 0 upper_index (int, optional): End index. Defaults to 0 Returns: :obj:`tuple` of :obj:`float`: Bounds of the (sub)segment, such that (min_lat...
def bounds(self, thr=0, lower_index=0, upper_index=-1): points = self.points[lower_index:upper_index] min_lat = float("inf") min_lon = float("inf") max_lat = -float("inf") max_lon = -float("inf") for point in points: min_lat = min(min_lat, point.lat...
597,166
In-place smoothing See smooth_segment function Args: noise (float): Noise expected strategy (int): Strategy to use. Either smooth.INVERSE_STRATEGY or smooth.EXTRAPOLATE_STRATEGY Returns: :obj:`Segment`
def smooth(self, noise, strategy=INVERSE_STRATEGY): if strategy is INVERSE_STRATEGY: self.points = with_inverse(self.points, noise) elif strategy is EXTRAPOLATE_STRATEGY: self.points = with_extrapolation(self.points, noise, 30) elif strategy is NO_STRATEGY: ...
597,167
In-place segment simplification See `drp` and `compression` modules Args: eps (float): Distance threshold for the `drp` function max_dist_error (float): Max distance error, in meters max_speed_error (float): Max speed error, in km/h topology_only (bool, ...
def simplify(self, eps, max_dist_error, max_speed_error, topology_only=False): if topology_only: self.points = drp(self.points, eps) else: self.points = spt(self.points, max_dist_error, max_speed_error) return self
597,168
In-place location inferring See infer_location function Args: Returns: :obj:`Segment`: self
def infer_location( self, location_query, max_distance, google_key, foursquare_client_id, foursquare_client_secret, limit ): self.location_from = infer_location( self.points[0], location...
597,170
In-place transportation mode inferring See infer_transportation_mode function Args: Returns: :obj:`Segment`: self
def infer_transportation_mode(self, clf, min_time): self.transportation_modes = speed_clustering(clf, self.points, min_time) return self
597,171
Merges another segment with this one, ordering the points based on a distance heuristic Args: segment (:obj:`Segment`): Segment to merge with Returns: :obj:`Segment`: self
def merge_and_fit(self, segment): self.points = sort_segment_points(self.points, segment.points) return self
597,172
Finds the closest point in the segment to a given point Args: point (:obj:`Point`) thr (float, optional): Distance threshold, in meters, to be considered the same point. Defaults to 20.0 Returns: (int, Point): Index of the point. -1 if doesn't exist. ...
def closest_point_to(self, point, thr=20.0): i = 0 point_arr = point.gen2arr() def closest_in_line(pointA, pointB): temp = closest_point(pointA.gen2arr(), pointB.gen2arr(), point_arr) return Point(temp[1], temp[0], None) for (p_a, p_b) in pairwise(self....
597,173
Creates a copy of the current segment between indexes. If end > start, points are reverted Args: start (int): Start index end (int): End index Returns: :obj:`Segment`
def slice(self, start, end): reverse = False if start > end: temp = start start = end end = temp reverse = True seg = self.copy() seg.points = seg.points[start:end+1] if reverse: seg.points = list(reversed(seg...
597,174
Creates a segment from a GPX format. No preprocessing is done. Arguments: gpx_segment (:obj:`gpxpy.GPXTrackSegment`) Return: :obj:`Segment`
def from_gpx(gpx_segment): points = [] for point in gpx_segment.points: points.append(Point.from_gpx(point)) return Segment(points)
597,176
Creates a segment from a JSON file. No preprocessing is done. Arguments: json (:obj:`dict`): JSON representation. See to_json. Return: :obj:`Segment`
def from_json(json): points = [] for point in json['points']: points.append(Point.from_json(point)) return Segment(points)
597,177
Extrapolate a number of points, based on the first ones Args: points (:obj:`list` of :obj:`Point`) n_points (int): number of points to extrapolate Returns: :obj:`list` of :obj:`Point`
def extrapolate_points(points, n_points): points = points[:n_points] lat = [] lon = [] last = None for point in points: if last is not None: lat.append(last.lat-point.lat) lon.append(last.lon-point.lon) last = point dts = np.mean([p.dt for p in point...
597,178
Smooths a set of points, but it extrapolates some points at the beginning Args: points (:obj:`list` of :obj:`Point`) noise (float): Expected noise, the higher it is the more the path will be smoothed. Returns: :obj:`list` of :obj:`Point`
def with_extrapolation(points, noise, n_points): n_points = 10 return kalman_filter(extrapolate_points(points, n_points) + points, noise)[n_points:]
597,179
Smooths a set of points It smooths them twice, once in given order, another one in the reverse order. The the first half of the results will be taken from the reverse order and the second half from the normal order. Args: points (:obj:`list` of :obj:`Point`) noise (float): Expected...
def with_inverse(points, noise): # noise_sample = 20 n_points = len(points)/2 break_point = n_points points_part = copy.deepcopy(points) points_part = list(reversed(points_part)) part = kalman_filter(points_part, noise) total = kalman_filter(points, noise) result = list(reversed(p...
597,181
Segments based on time distant points Args: segments (:obj:`list` of :obj:`list` of :obj:`Point`): segment points min_time (int): minimum required time for segmentation
def temporal_segmentation(segments, min_time): final_segments = [] for segment in segments: final_segments.append([]) for point in segment: if point.dt > min_time: final_segments.append([]) final_segments[-1].append(point) return final_segments
597,182
Corrects the predicted segmentation This process prevents over segmentation Args: segments (:obj:`list` of :obj:`list` of :obj:`Point`): segments to correct min_time (int): minimum required time for segmentation
def correct_segmentation(segments, clusters, min_time): # segments = [points for points in segments if len(points) > 1] result_segments = [] prev_segment = None for i, segment in enumerate(segments): if len(segment) >= 1: continue cluster = clusters[i] if prev_...
597,183
Smooths points with kalman filter See https://github.com/open-city/ikalman Args: points (:obj:`list` of :obj:`Point`): points to smooth noise (float): expected noise
def kalman_filter(points, noise): kalman = ikalman.filter(noise) for point in points: kalman.update_velocity2d(point.lat, point.lon, point.dt) (lat, lon) = kalman.get_lat_long() point.lat = lat point.lon = lon return points
597,185
Inserts transportation modes of a track into a classifier Args: track (:obj:`Track`) clf (:obj:`Classifier`)
def learn_transportation_mode(track, clf): for segment in track.segments: tmodes = segment.transportation_modes points = segment.points features = [] labels = [] for tmode in tmodes: points_part = points[tmode['from']:tmode['to']] if len(points_p...
597,190
Feature extractor Args: points (:obj:`list` of :obj:`Point`) n_tops (int): Number of top speeds to extract Returns: :obj:`list` of float: with length (n_tops*2). Where the ith even element is the ith top speed and the i+1 element is the percentage of time spent o...
def extract_features(points, n_tops): max_bin = -1 for point in points: max_bin = max(max_bin, point.vel) max_bin = int(round(max_bin)) + 1 # inits histogram histogram = [0] * max_bin time = 0 # fills histogram for point in points: bin_index = int(round(point.vel))...
597,191
Computes the speed difference between each adjacent point Args: points (:obj:`Point`) Returns: :obj:`list` of int: Indexes of changepoints
def speed_difference(points): data = [0] for before, after in pairwise(points): data.append(before.vel - after.vel) return data
597,192
Computes the accelaration difference between each adjacent point Args: points (:obj:`Point`) Returns: :obj:`list` of int: Indexes of changepoints
def acc_difference(points): data = [0] for before, after in pairwise(points): data.append(before.acc - after.acc) return data
597,193
Detects changepoints on points that have at least a specific duration Args: points (:obj:`Point`) min_time (float): Min time that a sub-segmented, bounded by two changepoints, must have data_processor (function): Function to extract data to feed to the changepoint algorithm. Def...
def detect_changepoints(points, min_time, data_processor=acc_difference): data = data_processor(points) changepoints = pelt(normal_mean(data, np.std(data)), len(data)) changepoints.append(len(points) - 1) result = [] for start, end in pairwise(changepoints): time_diff = points[end].tim...
597,194
Groups consecutive transportation modes with same label, into one Args: modes (:obj:`list` of :obj:`dict`) Returns: :obj:`list` of :obj:`dict`
def group_modes(modes): if len(modes) > 0: previous = modes[0] grouped = [] for changep in modes[1:]: if changep['label'] != previous['label']: previous['to'] = changep['from'] grouped.append(previous) previous = changep ...
597,195
Transportation mode infering, based on changepoint segmentation Args: clf (:obj:`Classifier`): Classifier to use points (:obj:`list` of :obj:`Point`) min_time (float): Min time, in seconds, before do another segmentation Returns: :obj:`list` of :obj:`dict`
def speed_clustering(clf, points, min_time): # get changepoint indexes changepoints = detect_changepoints(points, min_time) # info for each changepoint cp_info = [] for i in range(0, len(changepoints) - 1): from_index = changepoints[i] to_index = changepoints[i+1] info...
597,197
Euclidean distance, between two points Args: p_a (:obj:`Point`) p_b (:obj:`Point`) Returns: float: distance, in degrees
def distance(p_a, p_b): return sqrt((p_a.lat - p_b.lat) ** 2 + (p_a.lon - p_b.lon) ** 2)
597,198
Distance from a point to a line, formed by two points Args: point (:obj:`Point`) start (:obj:`Point`): line point end (:obj:`Point`): line point Returns: float: distance to line, in degrees
def point_line_distance(point, start, end): if start == end: return distance(point, start) else: un_dist = abs( (end.lat-start.lat)*(start.lon-point.lon) - (start.lat-point.lat)*(end.lon-start.lon) ) n_dist = sqrt( (end.lat-start.lat)**2 + (end.lon-st...
597,199
Douglas ramer peucker Based on https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm Args: points (:obj:`list` of :obj:`Point`) epsilon (float): drp threshold Returns: :obj:`list` of :obj:`Point`
def drp(points, epsilon): dmax = 0.0 index = 0 for i in range(1, len(points)-1): dist = point_line_distance(points[i], points[0], points[-1]) if dist > dmax: index = i dmax = dist if dmax > epsilon: return drp(points[:index+1], epsilon)[:-1] + drp(p...
597,200
Top-Down Speed-Based Trajectory Compression Algorithm Detailed in https://www.itc.nl/library/Papers_2003/peer_ref_conf/meratnia_new.pdf Args: points (:obj:`list` of :obj:`Point`): trajectory or part of it speed_threshold (float): max speed error, in km/h Returns: :obj:`list` of :ob...
def td_sp(points, speed_threshold): if len(points) <= 2: return points else: max_speed_threshold = 0 found_index = 0 for i in range(1, len(points)-1): dt1 = time_dist(points[i], points[i-1]) if dt1 == 0: dt1 = 0.000000001 v...
597,201
Top-Down Time-Ratio Trajectory Compression Algorithm Detailed in https://www.itc.nl/library/Papers_2003/peer_ref_conf/meratnia_new.pdf Args: points (:obj:`list` of :obj:`Point`): trajectory or part of it dist_threshold (float): max distance error, in meters Returns: :obj:`list` of ...
def td_tr(points, dist_threshold): if len(points) <= 2: return points else: max_dist_threshold = 0 found_index = 0 delta_e = time_dist(points[-1], points[0]) * I_3600 d_lat = points[-1].lat - points[0].lat d_lon = points[-1].lon - points[0].lon for i...
597,202
Constructor When constructing a track it's not guaranteed that the segments have their properties computed. Call preprocess method over this class, or over each segment to guarantee it. Args: name (:obj:`str`) segments(:obj:`list` of :obj:`Segment`)
def __init__(self, name, segments): self.name = name self.meta = [] self.segments = sorted(segments, key=lambda s: s.points[0].time)
597,204
Generates a name for the track The name is generated based on the date of the first point of the track, or in case it doesn't exist, "EmptyTrack" Args: name_format (str, optional): Name formar to give to the track, based on its start time. Defaults to DEFAULT_FILE_N...
def generate_name(self, name_format=DEFAULT_FILE_NAME_FORMAT): if len(self.segments) > 0: return self.segments[0].points[0].time.strftime(name_format) + ".gpx" else: return "EmptyTrack"
597,205
Merges another track with this one, ordering the points based on a distance heuristic Args: track (:obj:`Track`): Track to merge with pairings Returns: :obj:`Segment`: self
def merge_and_fit(self, track, pairings): for (self_seg_index, track_seg_index, _) in pairings: self_s = self.segments[self_seg_index] ss_start = self_s.points[0] track_s = track.segments[track_seg_index] tt_start = track_s.points[0] tt_end =...
597,214
Gets of the closest first point Args: point (:obj:`Point`) Returns: (int, int): Segment id and point index in that segment
def get_point_index(self, point): for i, segment in enumerate(self.segments): idx = segment.getPointIndex(point) if idx != -1: return i, idx return -1, -1
597,215
Compares two tracks based on their topology This method compares the given track against this instance. It only verifies if given track is close to this one, not the other way arround Args: track (:obj:`Track`) Returns: Two-tuple with global similarity b...
def similarity(self, track): idx = index.Index() i = 0 for i, segment in enumerate(self.segments): idx.insert(i, segment.bounds(), obj=segment) final_siml = [] final_diff = [] for i, segment in enumerate(track.segments): query = idx.inter...
597,217
Sets the timezone of the entire track Args: timezone (int): Timezone hour delta
def timezone(self, timezone=0): tz_dt = timedelta(hours=timezone) for segment in self.segments: for point in segment.points: point.time = point.time + tz_dt return self
597,219
Creates a Track from a GPX file. No preprocessing is done. Arguments: file_path (str): file path and name to the GPX file Return: :obj:`list` of :obj:`Track`
def from_gpx(file_path): gpx = gpxpy.parse(open(file_path, 'r')) file_name = basename(file_path) tracks = [] for i, track in enumerate(gpx.tracks): segments = [] for segment in track.segments: segments.append(Segment.from_gpx(segment)) ...
597,221
Creates a Track from a JSON file. No preprocessing is done. Arguments: json: map with the keys: name (optional) and segments. Return: A track instance
def from_json(json): segments = [Segment.from_json(s) for s in json['segments']] return Track(json['name'], segments).compute_metrics()
597,222
Normalizes a point/vector Args: p ([float, float]): x and y coordinates Returns: float
def normalize(p): l = math.sqrt(p[0]**2 + p[1]**2) return [0.0, 0.0] if l == 0 else [p[0]/l, p[1]/l]
597,223
Creates a line from two points From http://stackoverflow.com/a/20679579 Args: p1 ([float, float]): x and y coordinates p2 ([float, float]): x and y coordinates Returns: (float, float, float): x, y and _
def line(p1, p2): A = (p1[1] - p2[1]) B = (p2[0] - p1[0]) C = (p1[0]*p2[1] - p2[0]*p1[1]) return A, B, -C
597,224
Intersects two line segments Args: L1 ([float, float]): x and y coordinates L2 ([float, float]): x and y coordinates Returns: bool: if they intersect (float, float): x and y of intersection, if they do
def intersection(L1, L2): D = L1[0] * L2[1] - L1[1] * L2[0] Dx = L1[2] * L2[1] - L1[1] * L2[2] Dy = L1[0] * L2[2] - L1[2] * L2[0] if D != 0: x = Dx / D y = Dy / D return x, y else: return False
597,225
Euclidean distance between two (tracktotrip) points Args: a (:obj:`Point`) b (:obj:`Point`) Returns: float
def distance_tt_point(a, b): return math.sqrt((b.lat-a.lat)**2 + (b.lon-a.lon)**2)
597,226
Finds closest point in a line segment Args: a ([float, float]): x and y coordinates. Line start b ([float, float]): x and y coordinates. Line end p ([float, float]): x and y coordinates. Point to find in the segment Returns: (float, float): x and y coordinates of the closest poi...
def closest_point(a, b, p): ap = [p[0]-a[0], p[1]-a[1]] ab = [b[0]-a[0], b[1]-a[1]] mag = float(ab[0]**2 + ab[1]**2) proj = dot(ap, ab) if mag ==0 : dist = 0 else: dist = proj / mag if dist < 0: return [a[0], a[1]] elif dist > 1: return [b[0], b[1]] ...
597,227
Closest distance between a line segment and a point Args: a ([float, float]): x and y coordinates. Line start b ([float, float]): x and y coordinates. Line end p ([float, float]): x and y coordinates. Point to compute the distance Returns: float
def distance_to_line(a, b, p): return distance(closest_point(a, b, p), p)
597,228
Computes the distance similarity between a line segment and a point Args: a ([float, float]): x and y coordinates. Line start b ([float, float]): x and y coordinates. Line end p ([float, float]): x and y coordinates. Point to compute the distance Returns: float: between 0 an...
def distance_similarity(a, b, p, T=CLOSE_DISTANCE_THRESHOLD): d = distance_to_line(a, b, p) r = (-1/float(T)) * abs(d) + 1 return r if r > 0 else 0
597,229
Line distance similarity between two line segments Args: p1a ([float, float]): x and y coordinates. Line A start p1b ([float, float]): x and y coordinates. Line A end p2a ([float, float]): x and y coordinates. Line B start p2b ([float, float]): x and y coordinates. Line B end Re...
def line_distance_similarity(p1a, p1b, p2a, p2b, T=CLOSE_DISTANCE_THRESHOLD): d1 = distance_similarity(p1a, p1b, p2a, T=T) d2 = distance_similarity(p1a, p1b, p2b, T=T) return abs(d1 + d2) * 0.5
597,230
Similarity between two lines Args: p1a ([float, float]): x and y coordinates. Line A start p1b ([float, float]): x and y coordinates. Line A end p2a ([float, float]): x and y coordinates. Line B start p2b ([float, float]): x and y coordinates. Line B end Returns: float: ...
def line_similarity(p1a, p1b, p2a, p2b, T=CLOSE_DISTANCE_THRESHOLD): d = line_distance_similarity(p1a, p1b, p2a, p2b, T=T) a = abs(angle_similarity(normalize(line(p1a, p1b)), normalize(line(p2a, p2b)))) return d * a
597,231
Creates bounding box for a line segment Args: points (:obj:`list` of :obj:`Point`) i (int): Line segment start, index in points array i1 (int): Line segment end, index in points array Returns: (float, float, float, float): with bounding box min x, min y, max x and max y
def bounding_box_from(points, i, i1, thr): pi = points[i] pi1 = points[i1] min_lat = min(pi.lat, pi1.lat) min_lon = min(pi.lon, pi1.lon) max_lat = max(pi.lat, pi1.lat) max_lon = max(pi.lon, pi1.lon) return min_lat-thr, min_lon-thr, max_lat+thr, max_lon+thr
597,232
Computes the similarity between two segments Args: A (:obj:`Segment`) B (:obj:`Segment`) Returns: float: between 0 and 1. Where 1 is very similar and 0 is completely different
def segment_similarity(A, B, T=CLOSE_DISTANCE_THRESHOLD): l_a = len(A.points) l_b = len(B.points) idx = index.Index() dex = 0 for i in range(l_a-1): idx.insert(dex, bounding_box_from(A.points, i, i+1, T), obj=[A.points[i], A.points[i+1]]) dex = dex + 1 prox_acc = [] f...
597,233
Takes two line segments and sorts all their points, so that they form a continuous path Args: Aps: Array of tracktotrip.Point Bps: Array of tracktotrip.Point Returns: Array with points ordered
def sort_segment_points(Aps, Bps): mid = [] j = 0 mid.append(Aps[0]) for i in range(len(Aps)-1): dist = distance_tt_point(Aps[i], Aps[i+1]) for m in range(j, len(Bps)): distm = distance_tt_point(Aps[i], Bps[m]) if dist > distm: direction = dot...
597,234
Distance between points Args: other (:obj:`Point`) Returns: float: Distance in km
def distance(self, other): return distance(self.lat, self.lon, None, other.lat, other.lon, None)
597,238
Computes the metrics of this point Computes and updates the dt, vel and acc attributes. Args: previous (:obj:`Point`): Point before Returns: :obj:`Point`: Self
def compute_metrics(self, previous): delta_t = self.time_difference(previous) delta_x = self.distance(previous) vel = 0 delta_v = 0 acc = 0 if delta_t != 0: vel = delta_x/delta_t delta_v = vel - previous.vel acc = delta_v/delta...
597,239
Creates a point from GPX representation Arguments: gpx_track_point (:obj:`gpxpy.GPXTrackPoint`) Returns: :obj:`Point`
def from_gpx(gpx_track_point): return Point( lat=gpx_track_point.latitude, lon=gpx_track_point.longitude, time=gpx_track_point.time )
597,240
Creates Point instance from JSON representation Args: json (:obj:`dict`): Must have at least the following keys: lat (float), lon (float), time (string in iso format). Example, { "lat": 9.3470298, "lon": 3.79274, ...
def from_json(json): return Point( lat=json['lat'], lon=json['lon'], time=isostr_to_datetime(json['time']) )
597,242
Computes the centroid of set of points Args: points (:obj:`list` of :obj:`Point`) Returns: :obj:`Point`
def compute_centroid(points): lats = [p[1] for p in points] lons = [p[0] for p in points] return Point(np.mean(lats), np.mean(lons), None)
597,244
Updates the centroid of a location cluster with another point Args: point (:obj:`Point`): Point to add to the cluster cluster (:obj:`list` of :obj:`Point`): Location cluster max_distance (float): Max neighbour distance min_samples (int): Minimum number of samples Returns: ...
def update_location_centroid(point, cluster, max_distance, min_samples): cluster.append(point) points = [p.gen2arr() for p in cluster] # Estimates the epsilon eps = estimate_meters_to_deg(max_distance, precision=6) p_cluster = DBSCAN(eps=eps, min_samples=min_samples) p_cluster.fit(points)...
597,245
Queries google maps API for a location Args: point (:obj:`Point`): Point location to query max_distance (float): Search radius, in meters key (str): Valid google maps api key Returns: :obj:`list` of :obj:`dict`: List of locations with the following format: { ...
def query_google(point, max_distance, key): if not key: return [] if from_cache(GG_CACHE, point, max_distance): return from_cache(GG_CACHE, point, max_distance) req = requests.get(GOOGLE_PLACES_URL % ( point.lat, point.lon, max_distance, key )) ...
597,247
Meters to degrees estimation See https://en.wikipedia.org/wiki/Decimal_degrees Args: meters (float) precision (float) Returns: float: meters in degrees approximation
def estimate_meters_to_deg(meters, precision=PRECISION_PERSON): line = PRECISION_TABLE[precision] dec = 1/float(10 ** precision) return meters / line[3] * dec
597,250
Converts iso formated text string into a datetime object Args: dt_str (str): ISO formated text string Returns: :obj:`datetime.datetime`
def isostr_to_datetime(dt_str): if len(dt_str) <= 20: return datetime.datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%SZ") else: dt_str = dt_str.split(".") return isostr_to_datetime("%sZ" % dt_str[0])
597,251
Learns new labels, this method is intended for internal use Args: labels (:obj:`list` of :obj:`str`): Labels to learn
def __learn_labels(self, labels): if self.feature_length > 0: result = list(self.labels.classes_) else: result = [] for label in labels: result.append(label) self.labels.fit(result)
597,254
Fits the classifier If it's state is empty, the classifier is fitted, if not the classifier is partially fitted. See sklearn's SGDClassifier fit and partial_fit methods. Args: features (:obj:`list` of :obj:`list` of :obj:`float`) labels (:obj:`list` of :obj:`str...
def learn(self, features, labels): labels = np.ravel(labels) self.__learn_labels(labels) if len(labels) == 0: return labels = self.labels.transform(labels) if self.feature_length > 0 and hasattr(self.clf, 'partial_fit'): # FIXME? check docs, may ...
597,255
Create an endpoint to serve predictions. Arguments: - input_validation (fn): takes a numpy array as input; returns True if validation passes and False otherwise - data_loader (fn): reads flask request and returns data preprocessed to be used in the `predi...
def _create_prediction_endpoint( self, to_numpy=True, data_loader=json_numpy_loader, preprocessor=lambda x: x, input_validation=lambda data: (True, None), postprocessor=lambda x: x, make_serializable_post=True): # copy ...
597,302
Print an error message Args: message: the message to print
def raiseError(cls, message): error_message = "[error] %s" % message if cls.__raise_exception__: raise Exception(error_message) cls.colorprint(error_message, Fore.RED) sys.exit(1)
597,776
Print a nice JSON output Args: message: the message to print
def json(cls, message): if type(message) is OrderedDict: pprint(dict(message)) else: pprint(message)
597,777
Process apis for the given model Args: model: the model processed apis: the list of apis availble for the current model relations: dict containing all relations between resources
def _get_apis(self, apis): ret = [] for data in apis: ret.append(SpecificationAPI(specification=self, data=data)) return sorted(ret, key=lambda x: x.rest_name[1:])
597,789
Start a task in a separate thread Args: method: the method to start in a separate thread args: Accept args/kwargs arguments
def start_task(self, method, *args, **kwargs): thread = threading.Thread(target=method, args=args, kwargs=kwargs) thread.is_daemon = False thread.start() self.threads.append(thread)
597,813
Adds a given report with the given specification_name as key to the reports list and computes the number of success, failures and errors Args: specification_name: string representing the specification (with ".spec") report: The
def add_report(self, specification_name, report): self._reports[specification_name] = report self._total = self._total + report.testsRun self._failures = self._failures + len(report.failures) self._errors = self._errors + len(report.errors) self._success = self._total -...
597,823
Get the name for the given language Args: name (str): the name to convert language (str): the language to use Returns: a name in the given language Example: get_idiomatic_name_in_language("EnterpriseNetwork", "python"...
def get_idiomatic_name_in_language(cls, name, language): if language in cls.idiomatic_methods_cache: m = cls.idiomatic_methods_cache[language] if not m: return name return m(name) found, method = load_language_plugins(language, 'get_idiomatic...
597,828
Get the type for the given language Args: type_name (str): the type to convert language (str): the language to use Returns: a type name in the given language Example: get_type_name_in_language("Varchar", "python") ...
def get_type_name_in_language(cls, type_name, sub_type, language): if language in cls.type_methods_cache: m = cls.type_methods_cache[language] if not m: return type_name return m(type_name) found, method = load_language_plugins(language, 'get...
597,829
Check if the attribute meet all the given conditions Args: attribute: the attribute information conditions: a dictionary of condition to match Returns: True if the attribute match all conditions. False otherwise
def does_attribute_meet_condition(self, attribute, conditions): if conditions is None or len(conditions) == 0: return True for attribute_name, attribute_value in conditions.items(): value = getattr(attribute, attribute_name, False) if value != attribute_valu...
597,882