INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Adds events to the queue. Will ignore events that occur before the settle time for that pin/ direction. Such events are assumed to be bouncing.
def add_event(self, event): """Adds events to the queue. Will ignore events that occur before the settle time for that pin/direction. Such events are assumed to be bouncing. """ # print("Trying to add event:") # print(event) # find out the pin settle time ...
Registers a pin number and direction to a callback function.
def register(self, pin_num, direction, callback, settle_time=DEFAULT_SETTLE_TIME): """Registers a pin number and direction to a callback function. :param pin_num: The pin pin number. :type pin_num: int :param direction: The event direction (use: IODIR_ON/IOD...
De - registers callback functions
def deregister(self, pin_num=None, direction=None): """De-registers callback functions :param pin_num: The pin number. If None then all functions are de-registered :type pin_num: int :param direction: The event direction. If None then all functions for the give...
When deactivated the: class: PortEventListener will not run anything.
def deactivate(self): """When deactivated the :class:`PortEventListener` will not run anything. """ self.event_queue.put(self.TERMINATE_SIGNAL) self.dispatcher.join() self.detector.terminate() self.detector.join()
Enables GPIO interrupts.
def gpio_interrupts_enable(self): """Enables GPIO interrupts.""" try: bring_gpio_interrupt_into_userspace() set_gpio_interrupt_edge() except Timeout as e: raise InterruptEnableException( "There was an error bringing gpio%d into userspace. %s" %...
Sends bytes via the SPI bus.
def spisend(self, bytes_to_send): """Sends bytes via the SPI bus. :param bytes_to_send: The bytes to send on the SPI device. :type bytes_to_send: bytes :returns: bytes -- returned bytes from SPI device :raises: InitError """ # make some buffer space to store read...
Re - implement almost the same code from crispy_forms but passing form instance to item render_link method.
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK): """ Re-implement almost the same code from crispy_forms but passing ``form`` instance to item ``render_link`` method. """ links, content = '', '' # accordion group needs the parent div id to set `d...
Find tab fields listed as invalid
def has_errors(self, form): """ Find tab fields listed as invalid """ return any([fieldname_error for fieldname_error in form.errors.keys() if fieldname_error in self])
Render the link for the tab - pane. It must be called after render so css_class is updated with active class name if needed.
def render_link(self, form, template_pack=TEMPLATE_PACK, **kwargs): """ Render the link for the tab-pane. It must be called after render so ``css_class`` is updated with ``active`` class name if needed. """ link_template = self.link_template % template_pack return render_...
Get package version from installed distribution or configuration file if not installed
def _extract_version(package_name): """ Get package version from installed distribution or configuration file if not installed """ try: return pkg_resources.get_distribution(package_name).version except pkg_resources.DistributionNotFound: _conf = read_configuration(os.path.join(P...
Pass template pack argument
def get_form_kwargs(self): """ Pass template pack argument """ kwargs = super(FormContainersMixin, self).get_form_kwargs() kwargs.update({ 'pack': "foundation-{}".format(self.kwargs.get('foundation_version')) }) return kwargs
Check the status of the incoming response raise exception if status is not 200.
def _check_status(cls, response_json): """Check the status of the incoming response, raise exception if status is not 200. Args: response_json (dict): results of the response of the GET request. Returns: None """ status = response_json['status'] ...
Used by every other method it makes a GET request with the given params.
def _get(self, url, params=None): """Used by every other method, it makes a GET request with the given params. Args: url (str): relative path of a specific service (account_info, ...). params (:obj:`dict`, optional): contains parameters to be sent in the GET request. Re...
Requests direct download link for requested file this method makes use of the response of prepare_download prepare_download must be called first.
def get_download_link(self, file_id, ticket, captcha_response=None): """Requests direct download link for requested file, this method makes use of the response of prepare_download, prepare_download must be called first. Args: file_id (str): id of the file to be downloaded. ...
Makes a request to prepare for file upload.
def upload_link(self, folder_id=None, sha1=None, httponly=False): """Makes a request to prepare for file upload. Note: If folder_id is not provided, it will make and upload link to the ``Home`` folder. Args: folder_id (:obj:`str`, optional): folder-ID to upload to. ...
Calls upload_link request to get valid url then it makes a post request with given file to be uploaded. No need to call upload_link explicitly since upload_file calls it.
def upload_file(self, file_path, folder_id=None, sha1=None, httponly=False): """Calls upload_link request to get valid url, then it makes a post request with given file to be uploaded. No need to call upload_link explicitly since upload_file calls it. Note: If folder_id is not provi...
Used to make a remote file upload to openload. co
def remote_upload(self, remote_url, folder_id=None, headers=None): """Used to make a remote file upload to openload.co Note: If folder_id is not provided, the file will be uploaded to ``Home`` folder. Args: remote_url (str): direct link of file to be remotely downloaded...
Checks a remote file upload to status.
def remote_upload_status(self, limit=None, remote_upload_id=None): """Checks a remote file upload to status. Args: limit (:obj:`int`, optional): Maximum number of results (Default: 5, Maximum: 100). remote_upload_id (:obj:`str`, optional): Remote Upload ID. Returns: ...
Request a list of files and folders in specified folder.
def list_folder(self, folder_id=None): """Request a list of files and folders in specified folder. Note: if folder_id is not provided, ``Home`` folder will be listed Args: folder_id (:obj:`str`, optional): id of the folder to be listed. Returns: dic...
Shows running file converts by folder
def running_conversions(self, folder_id=None): """Shows running file converts by folder Note: If folder_id is not provided, ``Home`` folder will be used. Args: folder_id (:obj:`str`, optional): id of the folder to list conversions of files exist in it. Returns:...
calculates the heat index based upon temperature ( in F ) and humidity. http:// www. srh. noaa. gov/ bmx/ tables/ heat_index. html
def calc_heat_index(temp, hum): ''' calculates the heat index based upon temperature (in F) and humidity. http://www.srh.noaa.gov/bmx/tables/heat_index.html returns the heat index in degrees F. ''' if (temp < 80): return temp else: return -42.379 + 2.04901523 * temp + 1...
calculates the wind chill value based upon the temperature ( F ) and wind.
def calc_wind_chill(t, windspeed, windspeed10min=None): ''' calculates the wind chill value based upon the temperature (F) and wind. returns the wind chill in degrees F. ''' w = max(windspeed10min, windspeed) return 35.74 + 0.6215 * t - 35.75 * (w ** 0.16) + 0.4275 * t * (w ** 0.16);
calculates the humidity via the formula from weatherwise. org return the relative humidity
def calc_humidity(temp, dewpoint): ''' calculates the humidity via the formula from weatherwise.org return the relative humidity ''' t = fahrenheit_to_celsius(temp) td = fahrenheit_to_celsius(dewpoint) num = 112 - (0.1 * t) + td denom = 112 + (0.9 * t) rh = math.pow((num / denom),...
calculates the dewpoint via the formula from weatherwise. org return the dewpoint in degrees F.
def calc_dewpoint(temp, hum): ''' calculates the dewpoint via the formula from weatherwise.org return the dewpoint in degrees F. ''' c = fahrenheit_to_celsius(temp) x = 1 - 0.01 * hum; dewpoint = (14.55 + 0.114 * c) * x; dewpoint = dewpoint + ((2.5 + 0.007 * c) * x) ** 3; dewpoint ...
Perform HTTP session to transmit defined weather values.
def publish(self): ''' Perform HTTP session to transmit defined weather values. ''' return self._publish( self.args, self.server, self.URI)
return CRC calc value from raw serial data
def get(data): ''' return CRC calc value from raw serial data ''' crc = 0 for byte in array('B', data): crc = (VProCRC.CRC_TABLE[(crc >> 8) ^ byte] ^ ((crc & 0xFF) << 8)) return crc
perform CRC check on raw serial data return true if valid. a valid CRC == 0.
def verify(data): ''' perform CRC check on raw serial data, return true if valid. a valid CRC == 0. ''' if len(data) == 0: return False crc = VProCRC.get(data) if crc: log.info("CRC Bad") else: log.debug("CRC OK") ...
given a packed storm date field unpack and return YYYY - MM - DD string.
def _unpack_storm_date(date): ''' given a packed storm date field, unpack and return 'YYYY-MM-DD' string. ''' year = (date & 0x7f) + 2000 # 7 bits day = (date >> 7) & 0x01f # 5 bits month = (date >> 12) & 0x0f # 4 bits return "%s-%s-%s" % (year, month, day)
return True if weather station returns Rev. B archives
def _use_rev_b_archive(self, records, offset): ''' return True if weather station returns Rev.B archives ''' # if pre-determined, return result if type(self._ARCHIVE_REV_B) is bool: return self._ARCHIVE_REV_B # assume, B and check 'RecType' field data ...
issue wakeup command to device to take out of standby mode.
def _wakeup(self): ''' issue wakeup command to device to take out of standby mode. ''' log.info("send: WAKEUP") for i in xrange(3): self.port.write('\n') # wakeup device ack = self.port.read(len(self.WAKE_ACK)) # read wakeup string log_raw('r...
write a single command with variable number of arguments. after the command the device must return ACK
def _cmd(self, cmd, *args, **kw): ''' write a single command, with variable number of arguments. after the command, the device must return ACK ''' ok = kw.setdefault('ok', False) self._wakeup() if args: cmd = "%s %s" % (cmd, ' '.join(str(a) for a in a...
reads a raw string containing data read from the device provided ( in/ dev/ XXX ) format. all reads are non - blocking.
def _loop_cmd(self): ''' reads a raw string containing data read from the device provided (in /dev/XXX) format. all reads are non-blocking. ''' self._cmd('LOOP', 1) raw = self.port.read(LoopStruct.size) # read data log_raw('read', raw) return raw
issue a command to read the archive records after a known time stamp.
def _dmpaft_cmd(self, time_fields): ''' issue a command to read the archive records after a known time stamp. ''' records = [] # convert time stamp fields to buffer tbuf = struct.pack('2H', *time_fields) # 1. send 'DMPAFT' cmd self._cmd('DMPAFT') ...
returns a dictionary of fields from the newest archive record in the device. return None when no records are new.
def _get_new_archive_fields(self): ''' returns a dictionary of fields from the newest archive record in the device. return None when no records are new. ''' for i in xrange(3): records = self._dmpaft_cmd(self._archive_time) if records is not None: break ...
calculates the derived fields ( those fields that are calculated )
def _calc_derived_fields(self, fields): ''' calculates the derived fields (those fields that are calculated) ''' # convenience variables for the calculations below temp = fields['TempOut'] hum = fields['HumOut'] wind = fields['WindSpeed'] wind10min = field...
read and parse a set of data read from the console. after the data is parsed it is available in the fields variable.
def parse(self): ''' read and parse a set of data read from the console. after the data is parsed it is available in the fields variable. ''' fields = self._get_loop_fields() fields['Archive'] = self._get_new_archive_fields() self._calc_derived_fields(fields) ...
unpacks data from buf and returns a dication of named fields. the fields can be post - processed by extending the _post_unpack () method.
def unpack_from(self, buf, offset=0 ): ''' unpacks data from 'buf' and returns a dication of named fields. the fields can be post-processed by extending the _post_unpack() method. ''' data = super(Struct,self).unpack_from( buf, offset) items = dict(zip(self.fields,data)) ...
main execution loop. query weather data and post to online service.
def weather_update(station, pub_sites, interval): ''' main execution loop. query weather data and post to online service. ''' station.parse() # read weather data # santity check weather data if station.fields['TempOut'] > 200: raise NoSensorException( 'Out of range temperature ...
setup system logging to desired verbosity.
def init_log( quiet, debug ): ''' setup system logging to desired verbosity. ''' from logging.handlers import SysLogHandler fmt = logging.Formatter( os.path.basename(sys.argv[0]) + ".%(name)s %(levelname)s - %(message)s") facility = SysLogHandler.LOG_DAEMON syslog = SysLogHandler(address='...
use values in opts data to generate instances of publication services.
def get_pub_services(opts): ''' use values in opts data to generate instances of publication services. ''' sites = [] for p_key in vars(opts).keys(): args = getattr(opts,p_key) if p_key in PUB_SERVICES and args: if isinstance(args,tuple): ps = PUB_SERVICES[p_key](*args) ...
read command line options to configure program behavior.
def get_options(parser): ''' read command line options to configure program behavior. ''' # station services # publication services pub_g = optparse.OptionGroup( parser, "Publication Services", '''One or more publication service must be specified to enable upload of weather data.''',...
return gust data if above threshold value and current time is inside reporting window period
def get( self, station, interval ): ''' return gust data, if above threshold value and current time is inside reporting window period ''' rec = station.fields['Archive'] # process new data if rec: threshold = station.fields['WindSpeed10Min'] + GUST_MPH_MIN if ...
Useful for defining weather data published to the server. Parameters not set will be reset and not sent to server. Unknown keyword args will be silently ignored so be careful. This is necessary for publishers that support more fields than others.
def set( self, pressure='NA', dewpoint='NA', humidity='NA', tempf='NA', rainin='NA', rainday='NA', dateutc='NA', windgust='NA', windgustdir='NA', windspeed='NA', winddir='NA', clouds='NA', weather='NA', *args, **kw): ''' Useful for defining weather data published to t...
Store keyword args to be written to output file.
def set( self, **kw): ''' Store keyword args to be written to output file. ''' self.args = kw log.debug( self.args )
Write output file.
def publish(self): ''' Write output file. ''' with open( self.file_name, 'w') as fh: for k,v in self.args.iteritems(): buf = StringIO.StringIO() buf.write(k) self._append_vals(buf,v) fh.write(buf.getvalue() + '\n') buf.close()
Standalone decorator to apply requirements to routes either function handlers or class based views::
def requires(*requirements, **opts): """ Standalone decorator to apply requirements to routes, either function handlers or class based views:: @requires(MyRequirement()) def a_view(): pass class AView(View): decorators = [requires(MyRequirement())] :par...
Used to protect an entire blueprint with a set of requirements. If a route handler inside the blueprint should be exempt then it may be decorated with the: func: ~flask_allows. views. exempt_from_requirements decorator.
def guard_entire(requirements, identity=None, throws=None, on_fail=None): """ Used to protect an entire blueprint with a set of requirements. If a route handler inside the blueprint should be exempt, then it may be decorated with the :func:`~flask_allows.views.exempt_from_requirements` decorator. T...
Helper decorator for transitioning to user - only requirements this aids in situations where the request may be marked optional and causes an incorrect flow into user - only requirements.
def wants_request(f): """ Helper decorator for transitioning to user-only requirements, this aids in situations where the request may be marked optional and causes an incorrect flow into user-only requirements. This decorator causes the requirement to look like a user-only requirement but passe...
Short cut helper to construct a combinator that uses: meth: operator. and_ to reduce requirement results and stops evaluating on the first False.
def And(cls, *requirements): """ Short cut helper to construct a combinator that uses :meth:`operator.and_` to reduce requirement results and stops evaluating on the first False. This is also exported at the module level as ``And`` """ return cls(*requirements, o...
Short cut helper to construct a combinator that uses: meth: operator. or_ to reduce requirement results and stops evaluating on the first True.
def Or(cls, *requirements): """ Short cut helper to construct a combinator that uses :meth:`operator.or_` to reduce requirement results and stops evaluating on the first True. This is also exported at the module level as ``Or`` """ return cls(*requirements, op=op...
Initializes the Flask - Allows object against the provided application
def init_app(self, app): """ Initializes the Flask-Allows object against the provided application """ if not hasattr(app, "extensions"): # pragma: no cover app.extensions = {} app.extensions["allows"] = self @app.before_request def start_context(*a, ...
Checks that the provided or current identity meets each requirement passed to this method.
def fulfill(self, requirements, identity=None): """ Checks that the provided or current identity meets each requirement passed to this method. This method takes into account both additional and overridden requirements, with overridden requirements taking precedence:: ...
Used to preform a full run of the requirements and the options given this method will invoke on_fail and/ or throw the appropriate exception type. Can be passed arguments to call on_fail with via f_args ( which are passed positionally ) and f_kwargs ( which are passed as keyword ).
def run( self, requirements, identity=None, throws=None, on_fail=None, f_args=(), f_kwargs=ImmutableDict(), # noqa: B008 use_on_fail_return=True, ): """ Used to preform a full run of the requirements and the options given, this...
Binds an override to the current context optionally use the current overrides in conjunction with this override
def push(self, override, use_parent=False): """ Binds an override to the current context, optionally use the current overrides in conjunction with this override If ``use_parent`` is true, a new override is created from the parent and child overrides rather than manipulating eith...
Pops the latest override context.
def pop(self): """ Pops the latest override context. If the override context was pushed by a different override manager, a ``RuntimeError`` is raised. """ rv = _override_ctx_stack.pop() if rv is None or rv[0] is not self: raise RuntimeError( ...
Allows temporarily pushing an override context yields the new context into the following block.
def override(self, override, use_parent=False): """ Allows temporarily pushing an override context, yields the new context into the following block. """ self.push(override, use_parent) yield self.current self.pop()
Binds an additional to the current context optionally use the current additionals in conjunction with this additional
def push(self, additional, use_parent=False): """ Binds an additional to the current context, optionally use the current additionals in conjunction with this additional If ``use_parent`` is true, a new additional is created from the parent and child additionals rather than manip...
Pops the latest additional context.
def pop(self): """ Pops the latest additional context. If the additional context was pushed by a different additional manager, a ``RuntimeError`` is raised. """ rv = _additional_ctx_stack.pop() if rv is None or rv[0] is not self: raise RuntimeError( ...
Allows temporarily pushing an additional context yields the new context into the following block.
def additional(self, additional, use_parent=False): """ Allows temporarily pushing an additional context, yields the new context into the following block. """ self.push(additional, use_parent) yield self.current self.pop()
Append a number to duplicate field names to make them unique.
def unduplicate_field_names(field_names): """Append a number to duplicate field names to make them unique. """ res = [] for k in field_names: if k in res: i = 1 while k + '_' + str(i) in res: i += 1 k += '_' + str(i) res.append(k) retur...
Generates the string to be shown as updates after the execution of a Cypher query
def interpret_stats(results): """Generates the string to be shown as updates after the execution of a Cypher query :param results: ``ResultSet`` with the raw results of the execution of the Cypher query """ stats = results.stats contains_updates = stats.pop("contains_updates...
Generates a dictionary with safe keys and values to pass onto Neo4j
def extract_params_from_query(query, user_ns): """Generates a dictionary with safe keys and values to pass onto Neo4j :param query: string with the Cypher query to execute :param user_ns: dictionary with the IPython user space """ # TODO: Optmize this function params = {} for k, v in user_n...
Executes a query and depending on the options of the extensions will return raw data a ResultSet a Pandas DataFrame or a NetworkX graph.
def run(query, params=None, config=None, conn=None, **kwargs): """Executes a query and depending on the options of the extensions will return raw data, a ``ResultSet``, a Pandas ``DataFrame`` or a NetworkX graph. :param query: string with the Cypher query :param params: dictionary with parameters f...
Returns a Pandas DataFrame instance built from the result set.
def get_dataframe(self): """Returns a Pandas DataFrame instance built from the result set.""" if pd is None: raise ImportError("Try installing Pandas first.") frame = pd.DataFrame(self[:], columns=(self and self.keys) or []) return frame
Returns a NetworkX multi - graph instance built from the result set
def get_graph(self, directed=True): """Returns a NetworkX multi-graph instance built from the result set :param directed: boolean, optional (default=`True`). Whether to create a direted or an undirected graph. """ if nx is None: raise ImportError("Try installing ...
Plot of a NetworkX multi - graph instance
def draw(self, directed=True, layout="spring", node_label_attr=None, show_node_labels=True, edge_label_attr=None, show_edge_labels=True, node_size=1600, node_color='blue', node_alpha=0.3, node_text_size=12, edge_color='blue', edge_alpha=0.3, edge_tickness...
Generates a pylab pie chart from the result set.
def pie(self, key_word_sep=" ", title=None, **kwargs): """Generates a pylab pie chart from the result set. ``matplotlib`` must be installed, and in an IPython Notebook, inlining must be on:: %%matplotlib inline Values (pie slice sizes) are taken from the rightmost ...
Generates a pylab plot from the result set.
def plot(self, title=None, **kwargs): """Generates a pylab plot from the result set. ``matplotlib`` must be installed, and in an IPython Notebook, inlining must be on:: %%matplotlib inline The first and last columns are taken as the X and Y values. Any columns bet...
Generates a pylab bar plot from the result set.
def bar(self, key_word_sep=" ", title=None, **kwargs): """Generates a pylab bar plot from the result set. ``matplotlib`` must be installed, and in an IPython Notebook, inlining must be on:: %%matplotlib inline The last quantitative column is taken as the Y values; ...
Generates results in comma - separated form. Write to filename if given. Any other parameter will be passed on to csv. writer.
def csv(self, filename=None, **format_params): """Generates results in comma-separated form. Write to ``filename`` if given. Any other parameter will be passed on to ``csv.writer``. :param filename: if given, the CSV will be written to filename. Any additional keyword arguments will b...
Re - implementation of the permission_required decorator honors settings.
def permission_required(perm, login_url=None, raise_exception=False): """ Re-implementation of the permission_required decorator, honors settings. If ``DASHBOARD_REQUIRE_LOGIN`` is False, this decorator will always return ``True``, otherwise it will check for the permission as usual. """ def c...
Adds is_rendered to the context and the widget s context data.
def get_context_data(self, **kwargs): """ Adds ``is_rendered`` to the context and the widget's context data. ``is_rendered`` signals that the AJAX view has been called and that we are displaying the full widget now. When ``is_rendered`` is not found in the widget template it mea...
Returns the widgets sorted by position.
def get_widgets_sorted(self): """Returns the widgets sorted by position.""" result = [] for widget_name, widget in self.get_widgets().items(): result.append((widget_name, widget, widget.position)) result.sort(key=lambda x: x[2]) return result
Returns all widgets that need an update.
def get_widgets_that_need_update(self): """ Returns all widgets that need an update. This should be scheduled every minute via crontab. """ result = [] for widget_name, widget in self.get_widgets().items(): if widget.should_update(): result.a...
Registers the given widget.
def register_widget(self, widget_cls, **widget_kwargs): """ Registers the given widget. Widgets must inherit ``DashboardWidgetBase`` and you cannot register the same widget twice. :widget_cls: A class that inherits ``DashboardWidgetBase``. """ if not issubclass...
Unregisters the given widget.
def unregister_widget(self, widget_cls): """Unregisters the given widget.""" if widget_cls.__name__ in self.widgets: del self.widgets[widget_cls().get_name()]
Gets or creates the last update object for this widget.
def get_last_update(self): """Gets or creates the last update object for this widget.""" instance, created = \ models.DashboardWidgetLastUpdate.objects.get_or_create( widget_name=self.get_name()) return instance
Returns the setting for this widget from the database.
def get_setting(self, setting_name, default=None): """ Returns the setting for this widget from the database. :setting_name: The name of the setting. :default: Optional default value if the setting cannot be found. """ try: setting = models.DashboardWidgetSe...
Saves the setting value into the database.
def save_setting(self, setting_name, value): """Saves the setting value into the database.""" setting = self.get_setting(setting_name) if setting is None: setting = models.DashboardWidgetSettings.objects.create( widget_name=self.get_name(), setting_nam...
Checks if an update is needed.
def should_update(self): """ Checks if an update is needed. Checks against ``self.update_interval`` and this widgets ``DashboardWidgetLastUpdate`` instance if an update is overdue. This should be called by ``DashboardWidgetPool.get_widgets_that_need_update()``, which in...
: param q: query by city name: param lat: latitude: param lon: longitude: param city_ids: comma separated city_id values: param count: number of max results to display
def getCityDetails(self, **kwargs): """ :param q: query by city name :param lat: latitude :param lon: longitude :param city_ids: comma separated city_id values :param count: number of max results to display Find the Zomato ID and other details for a city . You ca...
: param city_id: id of the city for which collections are needed: param lat: latitude: param lon: longitude: param count: number of max results to display Returns Zomato Restaurant Collections in a City. The location/ City input can be provided in the following ways - Using Zomato City ID - Using coordinates of any loc...
def getCollectionsViaCityId(self, city_id, **kwargs): """ :param city_id: id of the city for which collections are needed :param lat: latitude :param lon: longitude :param count: number of max results to display Returns Zomato Restaurant Collections in a City. The locatio...
: param city_id: id of the city for which collections are needed: param lat: latitude: param lon: longitude Get a list of restaurant types in a city. The location/ City input can be provided in the following ways - Using Zomato City ID - Using coordinates of any location within a city List of all restaurants categorize...
def getEstablishments(self, city_id, **kwargs): """ :param city_id: id of the city for which collections are needed :param lat: latitude :param lon: longitude Get a list of restaurant types in a city. The location/City input can be provided in the following ways - Using Z...
: param lat: latitude: param lon: longitude Get Foodie and Nightlife Index list of popular cuisines and nearby restaurants around the given coordinates
def getByGeocode(self, lat, lon): """ :param lat: latitude :param lon: longitude Get Foodie and Nightlife Index, list of popular cuisines and nearby restaurants around the given coordinates """ params = {"lat": lat, "lon": lon} response = self.api.get("/geocode", ...
: param entity_id: location id obtained from locations api: param entity_type: location type obtained from locations api: return: Get Foodie Index Nightlife Index Top Cuisines and Best rated restaurants in a given location
def getLocationDetails(self, entity_id, entity_type): """ :param entity_id: location id obtained from locations api :param entity_type: location type obtained from locations api :return: Get Foodie Index, Nightlife Index, Top Cuisines and Best rated restaurants in a given locatio...
: param query: suggestion for location name: param lat: latitude: param lon: longitude: param count: number of max results to display: return: json response Search for Zomato locations by keyword. Provide coordinates to get better search results
def getLocations(self, query, **kwargs): """ :param query: suggestion for location name :param lat: latitude :param lon: longitude :param count: number of max results to display :return: json response Search for Zomato locations by keyword. Provide coordinates to ...
: param restaurant_id: id of restaurant whose details are requested: return: json response Get daily menu using Zomato restaurant ID.
def getDailyMenu(self, restaurant_id): """ :param restaurant_id: id of restaurant whose details are requested :return: json response Get daily menu using Zomato restaurant ID. """ params = {"res_id": restaurant_id} daily_menu = self.api.get("/dailymenu", params) ...
: param restaurant_id: id of restaurant whose details are requested: return: json response Get detailed restaurant information using Zomato restaurant ID. Partner Access is required to access photos and reviews.
def getRestaurantDetails(self, restaurant_id): """ :param restaurant_id: id of restaurant whose details are requested :return: json response Get detailed restaurant information using Zomato restaurant ID. Partner Access is required to access photos and reviews. """ ...
: param restaurant_id: id of restaurant whose details are requested: param start: fetch results after this offset: param count: max number of results to retrieve: return: json response Get restaurant reviews using the Zomato restaurant ID
def getRestaurantReviews(self, restaurant_id, **kwargs): """ :param restaurant_id: id of restaurant whose details are requested :param start: fetch results after this offset :param count: max number of results to retrieve :return: json response Get restaurant reviews usin...
: param entity_id: location id: param entity_type: location type ( city subzone zone lanmark metro group ): param q: search keyword: param start: fetch results after offset: param count: max number of results to display: param lat: latitude: param lon: longitude: param radius: radius around ( lat lon ) ; to define sear...
def search(self, **kwargs): """ :param entity_id: location id :param entity_type: location type (city, subzone, zone, lanmark, metro , group) :param q: search keyword :param start: fetch results after offset :param count: max number of results to display :param la...
Create a spark bolt array from a local array.
def array(a, context=None, axis=(0,), dtype=None, npartitions=None): """ Create a spark bolt array from a local array. Parameters ---------- a : array-like An array, any object exposing the array interface, an object whose __array__ method returns an arra...
Create a spark bolt array of ones.
def ones(shape, context=None, axis=(0,), dtype=float64, npartitions=None): """ Create a spark bolt array of ones. Parameters ---------- shape : tuple The desired shape of the array. context : SparkContext A context running Spark. (see pyspark) ...
Join two bolt arrays together at least one of which is in spark.
def concatenate(arrays, axis=0): """ Join two bolt arrays together, at least one of which is in spark. Parameters ---------- arrays : tuple A pair of arrays. At least one must be a spark array, the other can be a local bolt array, a local numpy array, ...
Check that arguments are consistent with spark array construction.
def _argcheck(*args, **kwargs): """ Check that arguments are consistent with spark array construction. Conditions are: (1) a positional argument is a SparkContext (2) keyword arg 'context' is a SparkContext (3) an argument is a BoltArraySpark, or (4) an argument ...
Format target axes given an array shape
def _format_axes(axes, shape): """ Format target axes given an array shape """ if isinstance(axes, int): axes = (axes,) elif isinstance(axes, list) or hasattr(axes, '__iter__'): axes = tuple(axes) if not isinstance(axes, tuple): raise V...
Wrap an existing numpy constructor in a parallelized construction
def _wrap(func, shape, context=None, axis=(0,), dtype=None, npartitions=None): """ Wrap an existing numpy constructor in a parallelized construction """ if isinstance(shape, int): shape = (shape,) key_shape, value_shape = get_kv_shape(shape, ConstructSpark._format_axe...
Align local bolt array so that axes for iteration are in the keys.
def _align(self, axes, key_shape=None): """ Align local bolt array so that axes for iteration are in the keys. This operation is applied before most functional operators. It ensures that the specified axes are valid, and might transpose/reshape the underlying array so that the f...
Filter array along an axis.
def filter(self, func, axis=(0,)): """ Filter array along an axis. Applies a function which should evaluate to boolean, along a single axis or multiple axes. Array will be aligned so that the desired set of axes are in the keys, which may require a transpose/reshape. ...
Apply a function across an axis.
def map(self, func, axis=(0,)): """ Apply a function across an axis. Array will be aligned so that the desired set of axes are in the keys, which may require a transpose/reshape. Parameters ---------- func : function Function of a single array to app...
Reduce an array along an axis.
def reduce(self, func, axis=0): """ Reduce an array along an axis. Applies an associative/commutative function of two arguments cumulatively to all arrays along an axis. Array will be aligned so that the desired set of axes are in the keys, which may require a transpose/...