signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def __bounce(self, **kwargs):
start_point = kwargs.pop('<STR_LIT>')<EOL>hit_point = kwargs.pop('<STR_LIT>')<EOL>end_point = kwargs.pop('<STR_LIT>')<EOL>feature = kwargs.pop('<STR_LIT>')<EOL>distance = kwargs.pop('<STR_LIT>')<EOL>angle = kwargs.pop('<STR_LIT>')<EOL>points_in_shore = [Point(x) for x in list(feature.coords)]<EOL>points_in_shore = sort...
Bounce off of the shoreline. NOTE: This does not work, but left here for future implementation feature = Linestring of two points, being the line segment the particle hit. angle = decimal degrees from 0 (x-axis), couter-clockwise (math style)
f3628:c0:m11
def __reverse(self, **kwargs):
start_point = kwargs.pop('<STR_LIT>')<EOL>hit_point = kwargs.pop('<STR_LIT>')<EOL>distance = kwargs.pop('<STR_LIT>')<EOL>azimuth = kwargs.pop('<STR_LIT>')<EOL>reverse_azimuth = kwargs.pop('<STR_LIT>')<EOL>reverse_distance = kwargs.get('<STR_LIT>', None)<EOL>if reverse_distance is None:<EOL><INDENT>reverse_distance = <N...
Reverse particle just off of the shore in the direction that it came in. Adds a slight random factor to the distance and angle it is reversed in.
f3628:c0:m12
def __init__(self, file=None, path=None, **kwargs):
if path is not None:<EOL><INDENT>self._file = os.path.normpath(path)<EOL><DEDENT>elif file is not None:<EOL><INDENT>self._file = os.path.normpath(file)<EOL><DEDENT>else:<EOL><INDENT>self._file = os.path.normpath(os.path.join(__file__,"<STR_LIT>"))<EOL><DEDENT>self._source = ogr.Open(self._file, GA_ReadOnly)<EOL>if not ...
Optional named arguments: * file (local path to OGC complient file) * path (used instead of file) MUST BE land polygons!!
f3628:c1:m0
def get_capabilities(self):
d = {}<EOL>ext = self._layer.GetExtent() <EOL>llbb = [round(float(v), <NUM_LIT:4>) for v in ext]<EOL>d['<STR_LIT>'] = box(llbb[<NUM_LIT:0>], llbb[<NUM_LIT:2>], llbb[<NUM_LIT:1>], llbb[<NUM_LIT:3>])<EOL>d['<STR_LIT:Name>'] = self._file.split('<STR_LIT:/>')[-<NUM_LIT:1>].split('<STR_LIT:.>')[<NUM_LIT:...
Gets capabilities. This is a simulation of a GetCapabilities WFS request. Returns a python dict with LatLongBoundingBox and Name keys defined.
f3628:c1:m2
def get_feature_type_info(self):
return self.get_capabilities()<EOL>
Gets FeatureType as a python dict. On ShorelineFile this is a passthrough to the simulated get_capabilities.
f3628:c1:m3
def get_geoms_for_bounds(self, bounds):
poly = ogr.CreateGeometryFromWkt(bounds)<EOL>self._layer.SetSpatialFilter(poly)<EOL>poly.Destroy()<EOL>return [json.loads(e.GetGeometryRef().ExportToJson()) for e in self._layer]<EOL>
Helper method to get geometries within a certain bounds (as WKT). Returns GeoJSON (loaded as a list of python dictionaries).
f3628:c1:m4
def index(self, point=None, spatialbuffer=None):
spatialbuffer = spatialbuffer or self._spatialbuffer<EOL>self._layer.SetSpatialFilter(None)<EOL>self._spatial_query_object = None<EOL>geoms = []<EOL>if point:<EOL><INDENT>self._spatial_query_object = point.buffer(spatialbuffer)<EOL>geoms = self.get_geoms_for_bounds(self._spatial_query_object.wkt)<E...
This queries the shapefile around a buffer of a point The results of this spatial query are used for shoreline detection. Using the entire shapefile without the spatial query takes over 30 times the time with world land polygons.
f3628:c1:m5
def get_capabilities(self):
params = {'<STR_LIT>' : '<STR_LIT>',<EOL>'<STR_LIT>' : '<STR_LIT>',<EOL>'<STR_LIT:version>' : '<STR_LIT>'}<EOL>caps_response = requests.get(self._wfs_server, params=params)<EOL>caps_response.raise_for_status()<EOL>return ET.fromstring(caps_response.content)<EOL>
Gets capabilities. Queries WFS server for its capabilities. Internally used by get_feature_type_info.
f3628:c2:m1
def get_feature_type_info(self):
caps = self.get_capabilities()<EOL>if caps is None:<EOL><INDENT>return None<EOL><DEDENT>el = caps.find('<STR_LIT>')<EOL>for e in el.findall('<STR_LIT>'):<EOL><INDENT>if e.find('<STR_LIT>').text == self._feature_name:<EOL><INDENT>d = {sube.tag[<NUM_LIT>:]:sube.text or sube.attrib or None for sube in e.getchildren()}<EOL...
Gets FeatureType as a python dict. Transforms feature_name info into python dict.
f3628:c2:m2
def get_geoms_for_bounds(self, bounds):
params = {'<STR_LIT>' : '<STR_LIT>',<EOL>'<STR_LIT>' : '<STR_LIT>',<EOL>'<STR_LIT>' : self._feature_name,<EOL>'<STR_LIT>' : '<STR_LIT>',<EOL>'<STR_LIT:version>' : '<STR_LIT>',<EOL>'<STR_LIT>' : '<STR_LIT:U+002C>'.join((str(b) for b in wkt.loads(bounds).bounds))}<EOL>raw_geojson_response = req...
Helper method to get geometries within a certain bounds (as WKT). Returns GeoJSON (loaded as a list of python dictionaries).
f3628:c2:m3
def __init__(self, task_queue, result_queue, n_run, nproc_lock, active, get_data, **kwargs):
multiprocessing.Process.__init__(self, **kwargs)<EOL>self.task_queue = task_queue<EOL>self.result_queue = result_queue<EOL>self.n_run = n_run<EOL>self.nproc_lock = nproc_lock<EOL>self.active = active<EOL>self.get_data = get_data<EOL>
This is the process class that does all the handling of queued tasks
f3630:c0:m0
def __init__(self, hydrodataset, common_variables, n_run, get_data, write_lock, has_write_lock, read_lock, read_count,<EOL>time_chunk, horiz_chunk, times, start_time, point_get, start, **kwargs):
assert "<STR_LIT>" in kwargs<EOL>self.cache_path = kwargs["<STR_LIT>"]<EOL>self.caching = kwargs.get("<STR_LIT>", True)<EOL>self.hydrodataset = hydrodataset<EOL>if self.cache_path == self.hydrodataset and self.caching is True:<EOL><INDENT>raise DataControllerError("<STR_LIT>")<EOL><DEDENT>self.n_run = n_run<EOL>self.ge...
The data controller controls the updating of the local netcdf data cache
f3630:c1:m0
def get_remote_data(self, localvars, remotevars, inds, shape):
<EOL>if self.horiz_size == '<STR_LIT:all>':<EOL><INDENT>y, y_1 = <NUM_LIT:0>, shape[-<NUM_LIT:2>]<EOL>x, x_1 = <NUM_LIT:0>, shape[-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>r = self.horiz_size<EOL>x, x_1 = self.point_get.value[<NUM_LIT:2>]-r, self.point_get.value[<NUM_LIT:2>]+r+<NUM_LIT:1><EOL>y, y_1 = self.point_get....
Method that does the updating of local netcdf cache with remote data
f3630:c1:m1
def __init__(self, hydrodataset, part, common_variables, timevar, times, start_time, models,<EOL>release_location_centroid, usebathy, useshore, usesurface,<EOL>get_data, n_run, read_lock, has_read_lock, read_count,<EOL>point_get, data_request_lock, has_data_request_lock, reverse_distance=None, bathy=None,<EOL>shoreline...
assert "<STR_LIT>" is not None<EOL>self.hydrodataset = hydrodataset<EOL>self.bathy = bathy<EOL>self.common_variables = common_variables<EOL>self.release_location_centroid = release_location_centroid<EOL>self.part = part<EOL>self.times = times<EOL>self.start_time = start_time<EOL>self.models = models<EOL>self.usebathy =...
This is the task/class/object/job that forces an individual particle and communicates with the other particles and data controller for local cache updates
f3630:c2:m1
def need_data(self, i):
<EOL>if self.caching is False:<EOL><INDENT>return False<EOL><DEDENT>logger.debug("<STR_LIT>" % self.part.location.logstring())<EOL>try:<EOL><INDENT>with self.read_lock:<EOL><INDENT>self.read_count.value += <NUM_LIT:1><EOL>self.has_read_lock.append(os.getpid())<EOL><DEDENT>self.dataset.opennc()<EOL>cached_lookup = self....
Method to test if cache contains the data that the particle needs
f3630:c2:m2
def linterp(self, setx, sety, x):
if math.isnan(sety[<NUM_LIT:0>]) or math.isnan(setx[<NUM_LIT:0>]):<EOL><INDENT>return np.nan<EOL><DEDENT>return sety[<NUM_LIT:0>] + (x - setx[<NUM_LIT:0>]) * ( (sety[<NUM_LIT:1>]-sety[<NUM_LIT:0>]) / (setx[<NUM_LIT:1>]-setx[<NUM_LIT:0>]) )<EOL>
Linear interp of model data values between time steps
f3630:c2:m3
def data_interp(self, i, currenttime):
if self.active.value is True:<EOL><INDENT>while self.get_data.value is True:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>timer.sleep(<NUM_LIT:2>)<EOL>pass<EOL><DEDENT><DEDENT>if self.need_data(i+<NUM_LIT:1>):<EOL><INDENT>self.data_request_lock.acquire()<EOL>self.has_data_request_lock.value = os.getpid()<EOL>try:<EOL><IND...
Method to streamline request for data from cache, Uses linear interpolation bewtween timesteps to get u,v,w,temp,salt
f3630:c2:m4
def data_nearest(self, i, currenttime):
if self.active.value is True:<EOL><INDENT>while self.get_data.value is True:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>timer.sleep(<NUM_LIT:2>)<EOL>pass<EOL><DEDENT><DEDENT>if self.need_data(i):<EOL><INDENT>self.data_request_lock.acquire()<EOL>self.has_data_request_lock.value = os.getpid()<EOL>try:<EOL><INDENT>if self....
Method to streamline request for data from cache, Uses nearest time to get u,v,w,temp,salt
f3630:c2:m5
def boundary_interaction(self, **kwargs):
particle = kwargs.pop('<STR_LIT>')<EOL>starting = kwargs.pop('<STR_LIT>')<EOL>ending = kwargs.pop('<STR_LIT>')<EOL>if self.useshore:<EOL><INDENT>intersection_point = self._shoreline.intersect(start_point=starting.point, end_point=ending.point)<EOL>if intersection_point:<EOL><INDENT>hitpoint = Location4D(point=intersect...
Returns a list of Location4D objects
f3630:c2:m7
def __init__(self, **kwargs):
<EOL>self._dataset = None<EOL>self._use_shoreline = kwargs.pop('<STR_LIT>', True)<EOL>self._use_bathymetry = kwargs.pop('<STR_LIT>', True)<EOL>self._use_seasurface = kwargs.pop('<STR_LIT>', True)<EOL>self._depth = kwargs.pop('<STR_LIT>', <NUM_LIT:0>)<EOL>self._npart = kwargs.pop('<STR_LIT>', <NUM_LIT:1>)<EOL>self.start...
Mandatory named arguments: * geometry (Shapely Geometry Object) no default * depth (meters) default 0 * start (DateTime Object) none * step (seconds) default 3600 * npart (number of particles) default 1 * nstep (number of steps) no default * models (list object) no default, so far there is a transport model and a behav...
f3631:c0:m0
def export(self, folder_path, format=None):
if format is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>format = format.lower()<EOL>if format == "<STR_LIT>" or format[-<NUM_LIT:4>:] == "<STR_LIT>":<EOL><INDENT>ex.Trackline.export(folder=folder_path, particles=self.particles, datetimes=self.datetimes)<EOL><DEDENT>elif format == "<STR_LIT>" or format ...
General purpose export method, gets file type from filepath extension Valid output formats currently are: Trackline: trackline or trkl or *.trkl Shapefile: shapefile or shape or shp or *.shp NetCDF: netcdf or nc or *.nc
f3631:c0:m11
def new(arg_name, annotated_with=None):
if annotated_with is not None:<EOL><INDENT>annotation = annotations.Annotation(annotated_with)<EOL><DEDENT>else:<EOL><INDENT>annotation = annotations.NO_ANNOTATION<EOL><DEDENT>return BindingKey(arg_name, annotation)<EOL>
Creates a BindingKey. Args: arg_name: the name of the bound arg annotation: an Annotation, or None to create an unannotated binding key Returns: a new BindingKey
f3634:m0
def __init__(self, name, annotation):
self._name = name<EOL>self._annotation = annotation<EOL>
Initializer. Args: name: the name of the bound arg annotation: an Annotation
f3634:c0:m0
def copy_args_to_internal_fields(fn):
return _copy_args_to_fields(fn, '<STR_LIT>', '<STR_LIT:_>')<EOL>
Copies the initializer args to internal member fields. This is a decorator that applies to __init__.
f3639:m0
def copy_args_to_public_fields(fn):
return _copy_args_to_fields(fn, '<STR_LIT>', '<STR_LIT>')<EOL>
Copies the initializer args to public member fields. This is a decorator that applies to __init__.
f3639:m1
def get_unbound_arg_names(arg_names, arg_binding_keys):
bound_arg_names = [abk._arg_name for abk in arg_binding_keys]<EOL>return [arg_name for arg_name in arg_names<EOL>if arg_name not in bound_arg_names]<EOL>
Determines which args have no arg binding keys. Args: arg_names: a sequence of the names of possibly bound args arg_binding_keys: a sequence of ArgBindingKey each of whose arg names is in arg_names Returns: a sequence of arg names that is a (possibly empty, possibly non-proper) ...
f3641:m0
def create_kwargs(arg_binding_keys, provider_fn):
return {arg_binding_key._arg_name: provider_fn(arg_binding_key)<EOL>for arg_binding_key in arg_binding_keys}<EOL>
Creates a kwargs map for the given arg binding keys. Args: arg_binding_keys: a sequence of ArgBindingKey for some function's args provider_fn: a function that takes an ArgBindingKey and returns whatever is bound to that binding key Returns: a (possibly empty) map from arg name to pr...
f3641:m1
def new(arg_name, annotated_with=None):
if arg_name.startswith(_PROVIDE_PREFIX):<EOL><INDENT>binding_key_name = arg_name[_PROVIDE_PREFIX_LEN:]<EOL>provider_indirection = provider_indirections.INDIRECTION<EOL><DEDENT>else:<EOL><INDENT>binding_key_name = arg_name<EOL>provider_indirection = provider_indirections.NO_INDIRECTION<EOL><DEDENT>binding_key = binding_...
Creates an ArgBindingKey. Args: arg_name: the name of the bound arg annotation: an Annotation, or None to create an unannotated arg binding key Returns: a new ArgBindingKey
f3641:m2
def can_apply_to_one_of_arg_names(self, arg_names):
return self._arg_name in arg_names<EOL>
Returns whether this object can apply to one of the arg names.
f3641:c0:m6
def conflicts_with_any_arg_binding_key(self, arg_binding_keys):
return self._arg_name in [abk._arg_name for abk in arg_binding_keys]<EOL>
Returns whether this arg binding key conflicts with others. One arg binding key conflicts with another if they are for the same arg name, regardless of whether they have the same annotation (or lack thereof). Args: arg_binding_keys: a sequence of ArgBindingKey Returns...
f3641:c0:m7
def _get_type_name(target_thing):
thing = target_thing<EOL>if hasattr(thing, '<STR_LIT>'):<EOL><INDENT>return thing.im_class.__name__<EOL><DEDENT>if inspect.ismethod(thing):<EOL><INDENT>for cls in inspect.getmro(thing.__self__.__class__):<EOL><INDENT>if cls.__dict__.get(thing.__name__) is thing:<EOL><INDENT>return cls.__name__<EOL><DEDENT><DEDENT>thing...
Functions, bound methods and unbound methods change significantly in Python 3. For instance: class SomeObject(object): def method(): pass In Python 2: - Unbound method inspect.ismethod(SomeObject.method) returns True - Unbound inspect.isfunction(SomeObject.method) returns False - Unbound hasattr(SomeObje...
f3643:m3
def new_object_graph(<EOL>modules=finding.ALL_IMPORTED_MODULES, classes=None, binding_specs=None,<EOL>only_use_explicit_bindings=False, allow_injecting_none=False,<EOL>configure_method_name='<STR_LIT>',<EOL>dependencies_method_name='<STR_LIT>',<EOL>get_arg_names_from_class_name=(<EOL>bindings.default_get_arg_names_from...
try:<EOL><INDENT>if modules is not None and modules is not finding.ALL_IMPORTED_MODULES:<EOL><INDENT>support.verify_module_types(modules, '<STR_LIT>')<EOL><DEDENT>if classes is not None:<EOL><INDENT>support.verify_class_types(classes, '<STR_LIT>')<EOL><DEDENT>if binding_specs is not None:<EOL><INDENT>support.verify_sub...
Creates a new object graph. Args: modules: the modules in which to search for classes for which to create implicit bindings; if None, then no modules; by default, all modules imported at the time of calling this method classes: the classes for which to create implicit bindings; if N...
f3646:m0
def provide(self, cls):
support.verify_class_type(cls, '<STR_LIT>')<EOL>if not self._is_injectable_fn(cls):<EOL><INDENT>provide_loc = locations.get_back_frame_loc()<EOL>raise errors.NonExplicitlyBoundClassError(provide_loc, cls)<EOL><DEDENT>try:<EOL><INDENT>return self._obj_provider.provide_class(<EOL>cls, self._injection_context_factory.new(...
Provides an instance of the given class. Args: cls: a class (not an instance) Returns: an instance of cls Raises: Error: an instance of cls is not providable
f3646:c0:m1
def __init__(self, is_scope_usable_from_scope_fn):
self._is_scope_usable_from_scope_fn = is_scope_usable_from_scope_fn<EOL>
Initializer. Args: is_scope_usable_from_scope_fn: a function taking two scope IDs and returning whether an object in the first scope can be injected into an object from the second scope
f3648:c0:m0
def new(self, injection_site_fn):
return _InjectionContext(<EOL>injection_site_fn, binding_stack=[], scope_id=scoping.UNSCOPED,<EOL>is_scope_usable_from_scope_fn=self._is_scope_usable_from_scope_fn)<EOL>
Creates a _InjectionContext. Args: injection_site_fn: the initial function being injected into Returns: a new empty _InjectionContext in the default scope
f3648:c0:m1
def __init__(self, injection_site_fn, binding_stack, scope_id,<EOL>is_scope_usable_from_scope_fn):
self._injection_site_fn = injection_site_fn<EOL>self._binding_stack = binding_stack<EOL>self._scope_id = scope_id<EOL>self._is_scope_usable_from_scope_fn = is_scope_usable_from_scope_fn<EOL>
Initializer. Args: injection_site_fn: the function currently being injected into binding_stack: a sequence of the bindings whose use in injection is in-progress, from the highest level (first) to the current level (last) scope_id: the scope ID of the cu...
f3648:c1:m0
def get_child(self, injection_site_fn, binding):
child_scope_id = binding.scope_id<EOL>new_binding_stack = self._binding_stack + [binding]<EOL>if binding in self._binding_stack:<EOL><INDENT>raise errors.CyclicInjectionError(new_binding_stack)<EOL><DEDENT>if not self._is_scope_usable_from_scope_fn(<EOL>child_scope_id, self._scope_id):<EOL><INDENT>raise errors.BadDepen...
Creates a child injection context. A "child" injection context is a context for a binding used to inject something into the current binding's provided value. Args: injection_site_fn: the child function being injected into binding: a Binding Returns: a new ...
f3648:c1:m1
def get_injection_site_desc(self):
return locations.get_name_and_loc(self._injection_site_fn)<EOL>
Returns a description of the current injection site.
f3648:c1:m2
def __init__(self, annotation_obj):
self._annotation_obj = annotation_obj<EOL>
Initializer. Args: annotation_obj: the annotation object, which can be any object that implements __eq__() and __hash__()
f3650:c0:m0
def as_adjective(self):
return '<STR_LIT>'.format(self._annotation_obj)<EOL>
Returns the annotation as an adjective phrase. For example, if the annotation object is '3', then the annotation adjective phrase is 'annotated with "3"'. Returns: an annotation adjective phrase
f3650:c0:m1
def annotate_arg(arg_name, with_annotation):
arg_binding_key = arg_binding_keys.new(arg_name, with_annotation)<EOL>return _get_pinject_wrapper(locations.get_back_frame_loc(),<EOL>arg_binding_key=arg_binding_key)<EOL>
Adds an annotation to an injected arg. arg_name must be one of the named args of the decorated function, i.e., @annotate_arg('foo', with_annotation='something') def a_function(foo): # ... is OK, but @annotate_arg('foo', with_annotation='something') def a_function(bar, **kwargs): # ......
f3651:m0
def inject(arg_names=None, all_except=None):
back_frame_loc = locations.get_back_frame_loc()<EOL>if arg_names is not None and all_except is not None:<EOL><INDENT>raise errors.TooManyArgsToInjectDecoratorError(back_frame_loc)<EOL><DEDENT>for arg, arg_value in [('<STR_LIT>', arg_names), ('<STR_LIT>', all_except)]:<EOL><INDENT>if arg_value is not None:<EOL><INDENT>i...
Marks an initializer explicitly as injectable. An initializer marked with @inject will be usable even when setting only_use_explicit_bindings=True when calling new_object_graph(). This decorator can be used on an initializer or provider method to separate the injectable args from the args that will be...
f3651:m1
def injectable(fn):
return inject()(fn)<EOL>
Deprecated. Use @inject() instead. TODO(kurts): remove after 2014/6/30.
f3651:m2
def provides(arg_name=None, annotated_with=None, in_scope=None):
if arg_name is None and annotated_with is None and in_scope is None:<EOL><INDENT>raise errors.EmptyProvidesDecoratorError(locations.get_back_frame_loc())<EOL><DEDENT>return _get_pinject_wrapper(locations.get_back_frame_loc(),<EOL>provider_arg_name=arg_name,<EOL>provider_annotated_with=annotated_with,<EOL>provider_in_sc...
Modifies the binding of a provider method. If arg_name is specified, then the created binding is for that arg name instead of the one gotten from the provider method name (e.g., 'foo' from 'provide_foo'). If annotated_with is specified, then the created binding includes that annotation object. ...
f3651:m3
def get_provider_fn_decorations(provider_fn, default_arg_names):
if hasattr(provider_fn, _IS_WRAPPER_ATTR):<EOL><INDENT>provider_decorations = getattr(provider_fn, _PROVIDER_DECORATIONS_ATTR)<EOL>if provider_decorations:<EOL><INDENT>expanded_provider_decorations = []<EOL>for provider_decoration in provider_decorations:<EOL><INDENT>if provider_decoration.in_scope_id is None:<EOL><IND...
Retrieves the provider method-relevant info set by decorators. If any info wasn't set by decorators, then defaults are returned. Args: provider_fn: a (possibly decorated) provider function default_arg_names: the (possibly empty) arg names to use if none were specified via @provides() ...
f3651:m4
def get_overall_binding_key_to_binding_maps(bindings_lists):
binding_key_to_binding = {}<EOL>collided_binding_key_to_bindings = {}<EOL>for index, bindings in enumerate(bindings_lists):<EOL><INDENT>is_final_index = (index == (len(bindings_lists) - <NUM_LIT:1>))<EOL>handle_binding_collision_fn = {<EOL>True: _handle_explicit_binding_collision,<EOL>False: _handle_implicit_binding_co...
bindings_lists from lowest to highest priority. Last item in bindings_lists is assumed explicit.
f3653:m3
def default_get_arg_names_from_class_name(class_name):
parts = []<EOL>rest = class_name<EOL>if rest.startswith('<STR_LIT:_>'):<EOL><INDENT>rest = rest[<NUM_LIT:1>:]<EOL><DEDENT>while True:<EOL><INDENT>m = re.match(r'<STR_LIT>', rest)<EOL>if m is None:<EOL><INDENT>break<EOL><DEDENT>parts.append(m.group(<NUM_LIT:1>))<EOL>rest = m.group(<NUM_LIT:2>)<EOL><DEDENT>if not parts:<...
Converts normal class names into normal arg names. Normal class names are assumed to be CamelCase with an optional leading underscore. Normal arg names are assumed to be lower_with_underscores. Args: class_name: a class name, e.g., "FooBar" or "_FooBar" Returns: all likely corresponding a...
f3653:m4
def new_in_default_scope(binding_key):
return bindings_lib.new_binding_to_instance(<EOL>binding_key, '<STR_LIT>', scoping.DEFAULT_SCOPE,<EOL>get_binding_loc_fn=lambda: '<STR_LIT>')<EOL>
Returns a new Binding in the default scope. Args: binding_key: a BindingKey proviser_fn: a function taking a InjectionContext and ObjectGraph and returning an instance of the bound value Returns: a Binding
f3658:m0
def MOSQ_MSB(A):
return (( A & <NUM_LIT>) >> <NUM_LIT:8>)<EOL>
get most significant byte.
f3680:m0
def MOSQ_LSB(A):
return (A & <NUM_LIT>)<EOL>
get less significant byte.
f3680:m1
def connect(sock, addr):
try:<EOL><INDENT>sock.connect(addr)<EOL><DEDENT>except ssl.SSLError as e:<EOL><INDENT>return (ssl.SSLError, e.strerror if e.strerror else e.message)<EOL><DEDENT>except socket.herror as xxx_todo_changeme:<EOL><INDENT>(_, msg) = xxx_todo_changeme.args<EOL>return (socket.herror, msg)<EOL><DEDENT>except socket.gaierror as ...
Connect to some addr.
f3680:m2
def read(sock, count):
data = None<EOL>try:<EOL><INDENT>data = sock.recv(count)<EOL><DEDENT>except ssl.SSLError as e:<EOL><INDENT>return data, e.errno, e.strerror if strerror else e.message<EOL><DEDENT>except socket.herror as xxx_todo_changeme2:<EOL><INDENT>(errnum, errmsg) = xxx_todo_changeme2.args<EOL>return data, errnum, errmsg<EOL><DEDEN...
Read from socket and return it's byte array representation. count = number of bytes to read
f3680:m3
def write(sock, payload):
try:<EOL><INDENT>length = sock.send(payload)<EOL><DEDENT>except ssl.SSLError as e:<EOL><INDENT>return -<NUM_LIT:1>, (ssl.SSLError, e.strerror if strerror else e.message)<EOL><DEDENT>except socket.herror as xxx_todo_changeme5:<EOL><INDENT>(_, msg) = xxx_todo_changeme5.args<EOL>return -<NUM_LIT:1>, (socket.error, msg)<EO...
Write payload to socket.
f3680:m4
def setkeepalives(sock):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, <NUM_LIT:1>)<EOL>
set sock to be keepalive socket.
f3680:m5
def loop(self, timeout = <NUM_LIT:1>):
rlist = [self.sock]<EOL>wlist = []<EOL>if len(self.out_packet) > <NUM_LIT:0>:<EOL><INDENT>wlist.append(self.sock)<EOL><DEDENT>to_read, to_write, _ = select.select(rlist, wlist, [], timeout)<EOL>if len(to_read) > <NUM_LIT:0>:<EOL><INDENT>ret, _ = self.loop_read()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL>...
Main loop.
f3682:c0:m1
def loop_read(self):
ret, bytes_received = self.packet_read()<EOL>return ret, bytes_received<EOL>
Read loop.
f3682:c0:m2
def loop_write(self):
ret, bytes_written = self.packet_write()<EOL>return ret, bytes_written<EOL>
Write loop.
f3682:c0:m3
def loop_misc(self):
self.check_keepalive()<EOL>if self.last_retry_check + <NUM_LIT:1> < time.time():<EOL><INDENT>pass<EOL><DEDENT>return NC.ERR_SUCCESS<EOL>
Misc loop.
f3682:c0:m4
def check_keepalive(self):
if self.sock != NC.INVALID_SOCKET and time.time() - self.last_msg_out >= self.keep_alive:<EOL><INDENT>if self.state == NC.CS_CONNECTED:<EOL><INDENT>self.send_pingreq()<EOL><DEDENT>else:<EOL><INDENT>self.socket_close()<EOL><DEDENT><DEDENT>
Send keepalive/PING if necessary.
f3682:c0:m5
def packet_handle(self):
cmd = self.in_packet.command & <NUM_LIT><EOL>if cmd == NC.CMD_CONNACK:<EOL><INDENT>return self.handle_connack()<EOL><DEDENT>elif cmd == NC.CMD_PINGRESP:<EOL><INDENT>return self.handle_pingresp()<EOL><DEDENT>elif cmd == NC.CMD_PUBLISH:<EOL><INDENT>return self.handle_publish()<EOL><DEDENT>elif cmd == NC.CMD_PUBACK:<EOL><...
Incoming packet handler dispatcher.
f3682:c0:m6
def connect(self, version = <NUM_LIT:3>, clean_session = <NUM_LIT:1>, will = None):
self.clean_session = clean_session<EOL>self.will = None<EOL>if will is not None:<EOL><INDENT>self.will = NyamukMsg(<EOL>topic = will['<STR_LIT>'],<EOL>payload = utf8encode(will.get('<STR_LIT:message>','<STR_LIT>')),<EOL>qos = will.get('<STR_LIT>', <NUM_LIT:0>),<EOL>retain = will.get('<STR_LIT>', False)<EOL>)<E...
Connect to server.
f3682:c0:m7
def disconnect(self):
self.logger.info("<STR_LIT>")<EOL>if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.state = NC.CS_DISCONNECTING<EOL>ret = self.send_disconnect()<EOL>ret2, bytes_written = self.packet_write()<EOL>self.socket_close()<EOL>return ret<EOL>
Disconnect from server.
f3682:c0:m8
def subscribe(self, topic, qos):
if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.logger.info("<STR_LIT>", topic)<EOL>return self.send_subscribe(False, [(utf8encode(topic), qos)])<EOL>
Subscribe to some topic.
f3682:c0:m9
def subscribe_multi(self, topics):
if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.logger.info("<STR_LIT>", '<STR_LIT:U+002CU+0020>'.join([t for (t,q) in topics]))<EOL>return self.send_subscribe(False, [(utf8encode(topic), qos) for (topic, qos) in topics])<EOL>
Subscribe to some topics.
f3682:c0:m10
def unsubscribe(self, topic):
if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.logger.info("<STR_LIT>", topic)<EOL>return self.send_unsubscribe(False, [utf8encode(topic)])<EOL>
Unsubscribe to some topic.
f3682:c0:m11
def unsubscribe_multi(self, topics):
if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.logger.info("<STR_LIT>", '<STR_LIT:U+002CU+0020>'.join(topics))<EOL>return self.send_unsubscribe(False, [utf8encode(topic) for topic in topics])<EOL>
Unsubscribe to some topics.
f3682:c0:m12
def send_disconnect(self):
return self.send_simple_command(NC.CMD_DISCONNECT)<EOL>
Send disconnect command.
f3682:c0:m13
def send_subscribe(self, dup, topics):
pkt = MqttPkt()<EOL>pktlen = <NUM_LIT:2> + sum([<NUM_LIT:2>+len(topic)+<NUM_LIT:1> for (topic, qos) in topics])<EOL>pkt.command = NC.CMD_SUBSCRIBE | (dup << <NUM_LIT:3>) | (<NUM_LIT:1> << <NUM_LIT:1>)<EOL>pkt.remaining_length = pktlen<EOL>ret = pkt.alloc()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDEN...
Send subscribe COMMAND to server.
f3682:c0:m14
def send_unsubscribe(self, dup, topics):
pkt = MqttPkt()<EOL>pktlen = <NUM_LIT:2> + sum([<NUM_LIT:2>+len(topic) for topic in topics])<EOL>pkt.command = NC.CMD_UNSUBSCRIBE | (dup << <NUM_LIT:3>) | (<NUM_LIT:1> << <NUM_LIT:1>)<EOL>pkt.remaining_length = pktlen<EOL>ret = pkt.alloc()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>mid = self.mid_...
Send unsubscribe COMMAND to server.
f3682:c0:m15
def publish(self, topic, payload = None, qos = <NUM_LIT:0>, retain = False):
<EOL>payloadlen = len(payload)<EOL>if topic is None or qos < <NUM_LIT:0> or qos > <NUM_LIT:2>:<EOL><INDENT>print("<STR_LIT>")<EOL>return NC.ERR_INVAL<EOL><DEDENT>if payloadlen > (<NUM_LIT> * <NUM_LIT> * <NUM_LIT>):<EOL><INDENT>self.logger.error("<STR_LIT>", payloadlen)<EOL>return NC.ERR_PAYLOAD_SIZE<EOL><DEDENT>mid = s...
Publish some payload to server.
f3682:c0:m16
def handle_connack(self):
self.logger.info("<STR_LIT>")<EOL>ret, flags = self.in_packet.read_byte()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>self.logger.error("<STR_LIT>")<EOL>return ret<EOL><DEDENT>session_present = flags & <NUM_LIT><EOL>ret, retcode = self.in_packet.read_byte()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT...
Handle incoming CONNACK command.
f3682:c0:m17
def handle_pingresp(self):
self.logger.debug("<STR_LIT>")<EOL>self.push_event(event.EventPingResp())<EOL>return NC.ERR_SUCCESS<EOL>
Handle incoming PINGRESP packet.
f3682:c0:m18
def handle_suback(self):
self.logger.info("<STR_LIT>")<EOL>ret, mid = self.in_packet.read_uint16()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>qos_count = self.in_packet.remaining_length - self.in_packet.pos<EOL>granted_qos = bytearray(qos_count)<EOL>if granted_qos is None:<EOL><INDENT>return NC.ERR_NO_MEM<EOL><DEDENT>i = ...
Handle incoming SUBACK packet.
f3682:c0:m19
def handle_unsuback(self):
self.logger.info("<STR_LIT>")<EOL>ret, mid = self.in_packet.read_uint16()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>evt = event.EventUnsuback(mid)<EOL>self.push_event(evt)<EOL>return NC.ERR_SUCCESS<EOL>
Handle incoming UNSUBACK packet.
f3682:c0:m20
def send_pingreq(self):
self.logger.debug("<STR_LIT>")<EOL>return self.send_simple_command(NC.CMD_PINGREQ)<EOL>
Send PINGREQ command to server.
f3682:c0:m21
def handle_publish(self):
self.logger.debug("<STR_LIT>")<EOL>header = self.in_packet.command<EOL>message = NyamukMsgAll()<EOL>message.direction = NC.DIRECTION_IN<EOL>message.dup = (header & <NUM_LIT>) >> <NUM_LIT:3><EOL>message.msg.qos = (header & <NUM_LIT>) >> <NUM_LIT:1><EOL>message.msg.retain = (header & <NUM_LIT>)<EOL>ret, ba_data = self.in...
Handle incoming PUBLISH packet.
f3682:c0:m22
def send_publish(self, mid, topic, payload, qos, retain, dup):
self.logger.debug("<STR_LIT>")<EOL>if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>return self._do_send_publish(mid, utf8encode(topic), utf8encode(payload), qos, retain, dup)<EOL>
Send PUBLISH.
f3682:c0:m23
def handle_puback(self):
self.logger.info("<STR_LIT>")<EOL>ret, mid = self.in_packet.read_uint16()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>evt = event.EventPuback(mid)<EOL>self.push_event(evt)<EOL>return NC.ERR_SUCCESS<EOL>
Handle incoming PUBACK packet.
f3682:c0:m25
def handle_pubrec(self):
self.logger.info("<STR_LIT>")<EOL>ret, mid = self.in_packet.read_uint16()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>evt = event.EventPubrec(mid)<EOL>self.push_event(evt)<EOL>return NC.ERR_SUCCESS<EOL>
Handle incoming PUBREC packet.
f3682:c0:m26
def handle_pubrel(self):
self.logger.info("<STR_LIT>")<EOL>ret, mid = self.in_packet.read_uint16()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>evt = event.EventPubrel(mid)<EOL>self.push_event(evt)<EOL>return NC.ERR_SUCCESS<EOL>
Handle incoming PUBREL packet.
f3682:c0:m27
def handle_pubcomp(self):
self.logger.info("<STR_LIT>")<EOL>ret, mid = self.in_packet.read_uint16()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>evt = event.EventPubcomp(mid)<EOL>self.push_event(evt)<EOL>return NC.ERR_SUCCESS<EOL>
Handle incoming PUBCOMP packet.
f3682:c0:m28
def puback(self, mid):
if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.logger.info("<STR_LIT>", mid)<EOL>pkt = MqttPkt()<EOL>pkt.command = NC.CMD_PUBACK<EOL>pkt.remaining_length = <NUM_LIT:2><EOL>ret = pkt.alloc()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>pkt.write_uint16(mid)<EOL>...
Send PUBACK response to server.
f3682:c0:m29
def pubrel(self, mid):
if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.logger.info("<STR_LIT>", mid)<EOL>pkt = MqttPkt()<EOL>pkt.command = NC.CMD_PUBREL | (<NUM_LIT:1> << <NUM_LIT:1>)<EOL>pkt.remaining_length = <NUM_LIT:2><EOL>ret = pkt.alloc()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DE...
Send PUBREL response to server.
f3682:c0:m30
def pubrec(self, mid):
if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.logger.info("<STR_LIT>", mid)<EOL>pkt = MqttPkt()<EOL>pkt.command = NC.CMD_PUBREC<EOL>pkt.remaining_length = <NUM_LIT:2><EOL>ret = pkt.alloc()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>pkt.write_uint16(mid)<EOL>...
Send PUBREC response to server.
f3682:c0:m31
def pubcomp(self, mid):
if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.logger.info("<STR_LIT>", mid)<EOL>pkt = MqttPkt()<EOL>pkt.command = NC.CMD_PUBCOMP<EOL>pkt.remaining_length = <NUM_LIT:2><EOL>ret = pkt.alloc()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>pkt.write_uint16(mid)<EOL...
Send PUBCOMP response to server.
f3682:c0:m32
def dump(self):
print("<STR_LIT>")<EOL>print("<STR_LIT>", self.command)<EOL>print("<STR_LIT>", self.have_remaining)<EOL>print("<STR_LIT>", self.remaining_count)<EOL>print("<STR_LIT>", self.mid)<EOL>print("<STR_LIT>", self.remaining_mult)<EOL>print("<STR_LIT>", self.remaining_length)<EOL>print("<STR_LIT>", self.packet_length)<EOL>print...
Print packet content.
f3685:c0:m1
def alloc(self):
byte = <NUM_LIT:0><EOL>remaining_bytes = bytearray(<NUM_LIT:5>)<EOL>i = <NUM_LIT:0><EOL>remaining_length = self.remaining_length<EOL>self.payload = None<EOL>self.remaining_count = <NUM_LIT:0><EOL>loop_flag = True<EOL>while loop_flag:<EOL><INDENT>byte = remaining_length % <NUM_LIT><EOL>remaining_length = remaining_lengt...
from _mosquitto_packet_alloc.
f3685:c0:m2
def connect_build(self, nyamuk, keepalive, clean_session, retain = <NUM_LIT:0>, dup = <NUM_LIT:0>, version = <NUM_LIT:3>):
will = <NUM_LIT:0>; will_topic = None<EOL>byte = <NUM_LIT:0><EOL>client_id = utf8encode(nyamuk.client_id)<EOL>username = utf8encode(nyamuk.username) if nyamuk.username is not None else None<EOL>password = utf8encode(nyamuk.password) if nyamuk.password is not None else None<EOL>payload_len = <NUM_LIT:2> + len(client_i...
Build packet for CONNECT command.
f3685:c0:m4
def write_string(self, string):
self.write_uint16(len(string))<EOL>self.write_bytes(string, len(string))<EOL>
Write a string to this packet.
f3685:c0:m5
def write_uint16(self, word):
self.write_byte(nyamuk_net.MOSQ_MSB(word))<EOL>self.write_byte(nyamuk_net.MOSQ_LSB(word))<EOL>
Write 2 bytes.
f3685:c0:m6
def write_byte(self, byte):
self.payload[self.pos] = byte<EOL>self.pos = self.pos + <NUM_LIT:1><EOL>
Write one byte.
f3685:c0:m7
def write_bytes(self, data, n):
for pos in range(<NUM_LIT:0>, n):<EOL><INDENT>self.payload[self.pos + pos] = data[pos]<EOL><DEDENT>self.pos += n<EOL>
Write n number of bytes to this packet.
f3685:c0:m8
def read_byte(self):
if self.pos + <NUM_LIT:1> > self.remaining_length:<EOL><INDENT>return NC.ERR_PROTOCOL, None<EOL><DEDENT>byte = self.payload[self.pos]<EOL>self.pos += <NUM_LIT:1><EOL>return NC.ERR_SUCCESS, byte<EOL>
Read a byte.
f3685:c0:m9
def read_uint16(self):
if self.pos + <NUM_LIT:2> > self.remaining_length:<EOL><INDENT>return NC.ERR_PROTOCOL<EOL><DEDENT>msb = self.payload[self.pos]<EOL>self.pos += <NUM_LIT:1><EOL>lsb = self.payload[self.pos]<EOL>self.pos += <NUM_LIT:1><EOL>word = (msb << <NUM_LIT:8>) + lsb<EOL>return NC.ERR_SUCCESS, word<EOL>
Read 2 bytes.
f3685:c0:m10
def read_bytes(self, count):
if self.pos + count > self.remaining_length:<EOL><INDENT>return NC.ERR_PROTOCOL, None<EOL><DEDENT>ba = bytearray(count)<EOL>for x in range(<NUM_LIT:0>, count):<EOL><INDENT>ba[x] = self.payload[self.pos]<EOL>self.pos += <NUM_LIT:1><EOL><DEDENT>return NC.ERR_SUCCESS, ba<EOL>
Read count number of bytes.
f3685:c0:m11
def read_string(self):
rc, length = self.read_uint16()<EOL>if rc != NC.ERR_SUCCESS:<EOL><INDENT>return rc, None<EOL><DEDENT>if self.pos + length > self.remaining_length:<EOL><INDENT>return NC.ERR_PROTOCOL, None<EOL><DEDENT>ba = bytearray(length)<EOL>if ba is None:<EOL><INDENT>return NC.ERR_NO_MEM, None<EOL><DEDENT>for x in range(<NUM_LIT:0>,...
Read string.
f3685:c0:m12
def __init__(self, client_id, username, password,<EOL>server, port, keepalive, ssl, ssl_opts):
self.client_id = client_id<EOL>self.username = username<EOL>self.password = password<EOL>self.server = server<EOL>self.port = port<EOL>self.ssl = ssl<EOL>self.ssl_opts = ssl_opts<EOL>self.address = "<STR_LIT>"<EOL>self.keep_alive = keepalive<EOL>self.clean_session = <NUM_LIT:1><EOL>self.state = NC.CS_NEW<EOL>self.last_...
Constructor
f3688:c0:m0
def pop_event(self):
if len(self.event_list) > <NUM_LIT:0>:<EOL><INDENT>evt = self.event_list.pop(<NUM_LIT:0>)<EOL>return evt<EOL><DEDENT>return None<EOL>
Pop an event from event_list.
f3688:c0:m1
def push_event(self, evt):
self.event_list.append(evt)<EOL>
Add an event to event_list.
f3688:c0:m2
def mid_generate(self):
self.last_mid += <NUM_LIT:1><EOL>if self.last_mid == <NUM_LIT:0>:<EOL><INDENT>self.last_mid += <NUM_LIT:1><EOL><DEDENT>return self.last_mid<EOL>
Generate mid. TODO : check.
f3688:c0:m3