code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def cancel(self): """Detach strategy from its sensor and cancel ioloop callbacks.""" if self.OBSERVE_UPDATES: self.detach() self.ioloop.add_callback(self.cancel_timeouts)
Detach strategy from its sensor and cancel ioloop callbacks.
def pdna_network_from_bbox( lat_min=None, lng_min=None, lat_max=None, lng_max=None, bbox=None, network_type='walk', two_way=True, timeout=180, memory=None, max_query_area_size=50 * 1000 * 50 * 1000): """ Make a Pandana network from a bounding lat/lon box request to the Overpass API. ...
Make a Pandana network from a bounding lat/lon box request to the Overpass API. Distance will be in the default units meters. Parameters ---------- lat_min, lng_min, lat_max, lng_max : float bbox : tuple Bounding box formatted as a 4 element tuple: (lng_max, lat_min, lng_min, lat_ma...
def validate_format(self, obj, pointer=None): """ ================= ============ Expected draft04 Alias of ----------------- ------------ date-time rfc3339.datetime email email hostname hostname ipv4 ipv4 ...
================= ============ Expected draft04 Alias of ----------------- ------------ date-time rfc3339.datetime email email hostname hostname ipv4 ipv4 ipv6 ipv6 uri uri =====...
def set_chat_description( self, chat_id: Union[int, str], description: str ) -> bool: """Use this method to change the description of a supergroup or a channel. You must be an administrator in the chat for this to work and must have the appropriate admin rights. Args...
Use this method to change the description of a supergroup or a channel. You must be an administrator in the chat for this to work and must have the appropriate admin rights. Args: chat_id (``int`` | ``str``): Unique identifier (int) or username (str) of the target chat. ...
def from_str(text): """Construct :class:`ChatMessageSegment` list parsed from a string. Args: text (str): Text to parse. May contain line breaks, URLs and formatting markup (simplified Markdown and HTML) to be converted into equivalent segments. Retu...
Construct :class:`ChatMessageSegment` list parsed from a string. Args: text (str): Text to parse. May contain line breaks, URLs and formatting markup (simplified Markdown and HTML) to be converted into equivalent segments. Returns: List of :class...
def readTempC(self): """Return the thermocouple temperature value in degrees celsius.""" v = self._read32() # Check for error reading value. if v & 0x7: return float('NaN') # Check if signed bit is set. if v & 0x80000000: # Negative value, take 2's...
Return the thermocouple temperature value in degrees celsius.
def get_none_policy_text(none_policy, # type: int verbose=False # type: bool ): """ Returns a user-friendly description of a NonePolicy taking into account NoneArgPolicy :param none_policy: :param verbose: :return: """ if none_policy is N...
Returns a user-friendly description of a NonePolicy taking into account NoneArgPolicy :param none_policy: :param verbose: :return:
def _make_2d_array(self, data): """ Convert a 1D array of mesh values to a masked 2D mesh array given the 1D mesh indices ``mesh_idx``. Parameters ---------- data : 1D `~numpy.ndarray` A 1D array of mesh values. Returns ------- result...
Convert a 1D array of mesh values to a masked 2D mesh array given the 1D mesh indices ``mesh_idx``. Parameters ---------- data : 1D `~numpy.ndarray` A 1D array of mesh values. Returns ------- result : 2D `~numpy.ma.MaskedArray` A 2D maske...
def _bitResponseToValue(bytestring): """Convert a response string to a numerical value. Args: bytestring (str): A string of length 1. Can be for example ``\\x01``. Returns: The converted value (int). Raises: TypeError, ValueError """ _checkString(bytestring, descripti...
Convert a response string to a numerical value. Args: bytestring (str): A string of length 1. Can be for example ``\\x01``. Returns: The converted value (int). Raises: TypeError, ValueError
def get_results(self, *, block=False, timeout=None): """Get the results of each job in the pipeline. Parameters: block(bool): Whether or not to block until a result is set. timeout(int): The maximum amount of time, in ms, to wait for a result when block is True. Default...
Get the results of each job in the pipeline. Parameters: block(bool): Whether or not to block until a result is set. timeout(int): The maximum amount of time, in ms, to wait for a result when block is True. Defaults to 10 seconds. Raises: ResultMissing: When ...
def generate_map_from_dataset(self, l_dataset): """ creates a map file (in the standard CSV format) based on columns of a dataset. 1. read column names, lookup names in list 2. read column content, get highest match of distinct values from ontology lists (eg, Years...
creates a map file (in the standard CSV format) based on columns of a dataset. 1. read column names, lookup names in list 2. read column content, get highest match of distinct values from ontology lists (eg, Years, countries, cities, ages)
def asset_save_callback(self, *args, **kwargs): """Callback for the shot open button :returns: None :rtype: None :raises: None """ tasksel = self.browser.assetbrws.selected_indexes(2) if not tasksel or not tasksel[0].isValid(): self.statusbar.showMess...
Callback for the shot open button :returns: None :rtype: None :raises: None
def get_auth_settings(): """ Returns all the key/secret settings for Twitter access, only if they're all defined. """ from yacms.conf import settings try: auth_settings = (settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET, s...
Returns all the key/secret settings for Twitter access, only if they're all defined.
def fetch(self, category=CATEGORY_ENTRY): """Fetch the entries from the url. The method retrieves all entries from a RSS url :param category: the category of items to fetch :returns: a generator of entries """ kwargs = {} items = super().fetch(category, **kwarg...
Fetch the entries from the url. The method retrieves all entries from a RSS url :param category: the category of items to fetch :returns: a generator of entries
def register_views(app_name, view_filename, urlpatterns=None): """ app_name APP名 view_filename views 所在的文件 urlpatterns url中已经存在的urlpatterns return urlpatterns 只导入View结尾的,是类的视图 """ app_module = __import__(app_name) view_module = getattr(app_module, view_filename) v...
app_name APP名 view_filename views 所在的文件 urlpatterns url中已经存在的urlpatterns return urlpatterns 只导入View结尾的,是类的视图
def chunk(sentence, format=None): """ Vietnamese chunking Parameters ========== sentence: {unicode, str} raw sentence Returns ======= tokens: list of tuple with word, pos tag, chunking tag tagged sentence Examples -------- >>> # -*- coding: utf-8 -*- ...
Vietnamese chunking Parameters ========== sentence: {unicode, str} raw sentence Returns ======= tokens: list of tuple with word, pos tag, chunking tag tagged sentence Examples -------- >>> # -*- coding: utf-8 -*- >>> from underthesea import chunk >>> sen...
def disembowel(rest): "Disembowel some(one|thing)!" if rest: stabee = rest karma.Karma.store.change(stabee, -1) else: stabee = "someone nearby" return ( "/me takes %s, brings them down to the basement, ties them to a " "leaky pipe, and once bored of playing with them mercifully " "ritually disembowels t...
Disembowel some(one|thing)!
def set_resource(self, service_name, resource_name, to_cache): """ Sets the resource class within the cache. :param service_name: The service a given ``Resource`` talks to. Ex. ``sqs``, ``sns``, ``dynamodb``, etc. :type service_name: string :param resource_name: The...
Sets the resource class within the cache. :param service_name: The service a given ``Resource`` talks to. Ex. ``sqs``, ``sns``, ``dynamodb``, etc. :type service_name: string :param resource_name: The name of the ``Resource``. Ex. ``Queue``, ``Notification``, ``Table``, ...
def plot_kde(data, ax, title=None, color='r', fill_bt=True): """ Plot a smoothed (by kernel density estimate) histogram. :type data: numpy array :param data: An array containing the data to be plotted :type ax: matplotlib.Axes :param ax: The Axes object to draw to :type title: str :par...
Plot a smoothed (by kernel density estimate) histogram. :type data: numpy array :param data: An array containing the data to be plotted :type ax: matplotlib.Axes :param ax: The Axes object to draw to :type title: str :param title: The plot title :type color: str :param color: The colo...
def global_instance(cls): """Return a per-thread global batcher instance.""" try: return GLOBAL_BATCHER.instance except AttributeError: instance = PrioritizedBatcher( **getattr(settings, 'PRIORITIZED_BATCHER', {}) ) GLOBAL_BATCHER....
Return a per-thread global batcher instance.
def get_modules(self): """Get modules by project_abspath and packages_scan. Traverse all files under folder packages_scan which set by customer. And get all modules name. """ if not self.project_abspath: raise TypeError("project_abspath can not be empty.") pa...
Get modules by project_abspath and packages_scan. Traverse all files under folder packages_scan which set by customer. And get all modules name.
def config_hook(self, func): """ Decorator to add a config hook to this ingredient. Config hooks need to be a function that takes 3 parameters and returns a dictionary: (config, command_name, logger) --> dict Config hooks are run after the configuration of this Ingredie...
Decorator to add a config hook to this ingredient. Config hooks need to be a function that takes 3 parameters and returns a dictionary: (config, command_name, logger) --> dict Config hooks are run after the configuration of this Ingredient, but before any further ingredient-con...
def _get_band(self, high_res, low_res, color, ratio): """Figure out what data should represent this color.""" if self.high_resolution_band == color: ret = high_res else: ret = low_res * ratio ret.attrs = low_res.attrs.copy() return ret
Figure out what data should represent this color.
def bare_except(logical_line, noqa): r"""When catching exceptions, mention specific exceptions whenever possible. Okay: except Exception: Okay: except BaseException: E722: except: """ if noqa: return regex = re.compile(r"except\s*:") match = regex.match(logical_line) if mat...
r"""When catching exceptions, mention specific exceptions whenever possible. Okay: except Exception: Okay: except BaseException: E722: except:
def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width))
Outputs or returns a horizontal line of the given character and width. Returns printed string.
def _color_level(str_, level): """ Return the string wrapped with the appropriate styling for the message level. The styling will be determined based on the rez configuration. Args: str_ (str): The string to be wrapped. level (str): The message level. Should be one of 'critical', 'error', ...
Return the string wrapped with the appropriate styling for the message level. The styling will be determined based on the rez configuration. Args: str_ (str): The string to be wrapped. level (str): The message level. Should be one of 'critical', 'error', 'warning', 'info' or 'debug'. ...
def clear(self): """Clears the server list""" if len(self.list): self._LOG.debug("List cleared.") self.list.clear()
Clears the server list
def get_validators_description(view): """ Returns validators description in format: ### Validators: * validator1 name * validator1 docstring * validator2 name * validator2 docstring """ action = getattr(view, 'action', None) if action is None: return '' description...
Returns validators description in format: ### Validators: * validator1 name * validator1 docstring * validator2 name * validator2 docstring
def run_task(message): """Internal ``RUN_TASK`` consumer to run the task's callable""" task = Task.objects.get(pk=message['id']) if task.allow_overlap: task.run(message) else: if not task.running: task.running = True task.save() try: ta...
Internal ``RUN_TASK`` consumer to run the task's callable
def nacm_rule_list_rule_comment(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") nacm = ET.SubElement(config, "nacm", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-acm") rule_list = ET.SubElement(nacm, "rule-list") name_key = ET.SubElement(rule_...
Auto Generated Code
def expand(doc, doc_url="param://", params=None): """ ASSUMING YOU ALREADY PULED THE doc FROM doc_url, YOU CAN STILL USE THE EXPANDING FEATURE USE mo_json_config.expand({}) TO ASSUME CURRENT WORKING DIRECTORY :param doc: THE DATA STRUCTURE FROM JSON SOURCE :param doc_url: THE URL THIS doc CAME...
ASSUMING YOU ALREADY PULED THE doc FROM doc_url, YOU CAN STILL USE THE EXPANDING FEATURE USE mo_json_config.expand({}) TO ASSUME CURRENT WORKING DIRECTORY :param doc: THE DATA STRUCTURE FROM JSON SOURCE :param doc_url: THE URL THIS doc CAME FROM (DEFAULT USES params AS A DOCUMENT SOURCE) :param pa...
def run_mash(self): """ Run MASH to determine the closest refseq genomes """ self.pipeline = True mash.Mash(inputobject=self, analysistype='mash')
Run MASH to determine the closest refseq genomes
def has_comic(name): """Check if comic name already exists.""" names = [ ("Creators/%s" % name).lower(), ("DrunkDuck/%s" % name).lower(), ("GoComics/%s" % name).lower(), ("KeenSpot/%s" % name).lower(), ("ComicGenesis/%s" % name).lower(), ("SmackJeeves/%s" % name)....
Check if comic name already exists.
def _finish(self): """Mark transition as finished and execute callback.""" self.finished = True if self._callback: self._callback(self) self._finish_event.set()
Mark transition as finished and execute callback.
def __ordinal(self, num): """Returns the ordinal number of a given integer, as a string. eg. 1 -> 1st, 2 -> 2nd, 3 -> 3rd, etc. """ if 10 <= num % 100 < 20: return str(num) + 'th' else: ord_info = {1: 'st', 2: 'nd', 3: 'rd'}.get(num % 10, 'th') ...
Returns the ordinal number of a given integer, as a string. eg. 1 -> 1st, 2 -> 2nd, 3 -> 3rd, etc.
def profile_device_delete(name, device_name, remote_addr=None, cert=None, key=None, verify_cert=True): ''' Delete a profile device. name : The name of the profile to delete the device. device_name : The name of the device to delete. remote...
Delete a profile device. name : The name of the profile to delete the device. device_name : The name of the device to delete. remote_addr : An URL to a remote Server, you also have to give cert and key if you provide remote_addr and its a TCP Ad...
def set(self, instance, value, **kw): """Set the value of the field """ return self._set(instance, value, **kw)
Set the value of the field
def key_to_dimension(self, fact_key, fact_join_col, dimension_name, dimension_join_col, dimension_key): """ create SQL to join a fact table key based on "join_col" to a dimension The fact table is aliased as "op" and the join dimension is aliased as "ip" meaning you can pass substrings...
create SQL to join a fact table key based on "join_col" to a dimension The fact table is aliased as "op" and the join dimension is aliased as "ip" meaning you can pass substrings or SQL to match values. e.g. the command: aup.key_to_dimension('GENDER_KEY', 'substr(op.GENDER, 1,1)', 'tbl_...
def ReverseComplementMembership(x, y, **kwargs): """Change (x doesn't contain y) to not(y in x).""" return ast.Complement( ast.Membership(y, x, **kwargs), **kwargs)
Change (x doesn't contain y) to not(y in x).
def _options(): """Collect all command line options""" opts = sys.argv[1:] return [click.Option((v.split('=')[0],)) for v in opts if v[0] == '-' and v != '--help']
Collect all command line options
def is_valid_pep484_type_hint(typ_hint, allow_forward_refs: bool = False): """ Returns True if the provided type is a valid PEP484 type hint, False otherwise. Note: string type hints (forward references) are not supported by default, since callers of this function in parsyfiles lib actually require the...
Returns True if the provided type is a valid PEP484 type hint, False otherwise. Note: string type hints (forward references) are not supported by default, since callers of this function in parsyfiles lib actually require them to be resolved already. :param typ_hint: :param allow_forward_refs: :ret...
def _endpoint_from_socksport_line(reactor, socks_config): """ Internal helper. Returns an IStreamClientEndpoint for the given config, which is of the same format expected by the SOCKSPort option in Tor. """ if socks_config.startswith('unix:'): # XXX wait, can SOCKSPort lines with "unix:...
Internal helper. Returns an IStreamClientEndpoint for the given config, which is of the same format expected by the SOCKSPort option in Tor.
def build_row(self, line): """ Line describes an image or images to show Returns a dict with a list of dicts of image names or text items Examples: # A single image to display >>> x.build_row('foo.png') [{'image': 'foo.png'}] # Two images with text in between:...
Line describes an image or images to show Returns a dict with a list of dicts of image names or text items Examples: # A single image to display >>> x.build_row('foo.png') [{'image': 'foo.png'}] # Two images with text in between: >>> x.build_row('foo.png or ba...
def filter_queryset(self, attrs, queryset): """ Filter the queryset to all instances matching the given attributes. """ # If this is an update, then any unprovided field should # have it's value set based on the existing instance attribute. if self.instance is not None: ...
Filter the queryset to all instances matching the given attributes.
def writeFromDict(dataDict, headers, csvFile): """ Write dictionary to a CSV, where keys are row numbers and values are a list. """ with open(csvFile, "wb") as f: writer = csv.writer(f, delimiter=",") writer.writerow(headers) for row in sorted(dataDict.keys()): writer.writerow(dataDict[row])
Write dictionary to a CSV, where keys are row numbers and values are a list.
def get_game_for_worker(map_name, directory_id): """Get game for the given worker (directory) id.""" if map_name == "v100unfriendly": games = ["chopper_command", "boxing", "asterix", "seaquest"] worker_per_game = 5 elif map_name == "human_nice": games = gym_env.ATARI_GAMES_WITH_HUMAN_SCORE_NICE wo...
Get game for the given worker (directory) id.
def provision_system_user(items, database_name, overwrite=False, clear=False, skip_user_check=False): """Provision a system user""" from hfos.provisions.base import provisionList from hfos.database import objectmodels # TODO: Add a root user and make sure owner can access it later. # Setting up de...
Provision a system user
def main_update(self): """ Main function called by the updater thread. Direct call is unnecessary. """ # Renice updater thread to limit overload try: os.nice(1) except AttributeError as er: pass # os.nice is not available on windows time.sleep(self.refresh) try: while True: # We pick a t...
Main function called by the updater thread. Direct call is unnecessary.
def clean_year_month(year, month, month_orig): """ If 'month_orig', which is the month given in the url BEFORE any next/prev query strings have been applied, is out of range, sets month to the current month and returns an error message. Also Returns an error message if the year given is +/- 50 years...
If 'month_orig', which is the month given in the url BEFORE any next/prev query strings have been applied, is out of range, sets month to the current month and returns an error message. Also Returns an error message if the year given is +/- 50 years from now. If 'month', which is the month given in the ...
def playlist_create( self, name, description='', *, make_public=False, songs=None ): """Create a playlist. Parameters: name (str): Name to give the playlist. description (str): Description to give the playlist. make_public (bool, Optional): If ``True`` and account has a subscription, make...
Create a playlist. Parameters: name (str): Name to give the playlist. description (str): Description to give the playlist. make_public (bool, Optional): If ``True`` and account has a subscription, make playlist public. Default: ``False`` songs (list, Optional): A list of song dicts to add to the ...
def getAssemblies(pth): """ Return the dependent assemblies of a binary. """ if not os.path.isfile(pth): pth = check_extract_from_egg(pth)[0][0] if pth.lower().endswith(".manifest"): return [] # check for manifest file manifestnm = pth + ".manifest" if os.path.isfile(mani...
Return the dependent assemblies of a binary.
def __geometryToGeomTemplate(self, geometry): """ Converts a single geometry object to a geometry service geometry template value. Input: geometry - ArcREST geometry object Output: python dictionary of geometry template """ ...
Converts a single geometry object to a geometry service geometry template value. Input: geometry - ArcREST geometry object Output: python dictionary of geometry template
def bios_settings(self): """Property to provide reference to `BIOSSettings` instance It is calculated once when the first time it is queried. On refresh, this property gets reset. """ return bios.BIOSSettings( self._conn, utils.get_subresource_path_by(self, 'Bios'), ...
Property to provide reference to `BIOSSettings` instance It is calculated once when the first time it is queried. On refresh, this property gets reset.
def enforce_periodic_boundary_conditions( self ): """ Ensure that all lattice sites are within the central periodic image of the simulation cell. Sites that are outside the central simulation cell are mapped back into this cell. Args: None Returns: ...
Ensure that all lattice sites are within the central periodic image of the simulation cell. Sites that are outside the central simulation cell are mapped back into this cell. Args: None Returns: None
def xception_entry(inputs, hidden_dim): """Xception entry flow.""" with tf.variable_scope("xception_entry"): def xnet_resblock(x, filters, res_relu, name): """Resblock.""" with tf.variable_scope(name): y = common_layers.separable_conv_block( x, filters, [((1, 1), (3,...
Xception entry flow.
def get_deposit(self, deposit_id, **params): """https://developers.coinbase.com/api/v2#show-a-deposit""" return self.api_client.get_deposit(self.id, deposit_id, **params)
https://developers.coinbase.com/api/v2#show-a-deposit
def nintegral(wave, indep_min=None, indep_max=None): r""" Return the numerical integral of a waveform's dependent variable vector. The method used is the `trapezoidal <https://en.wikipedia.org/wiki/Trapezoidal_rule>`_ method :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` ...
r""" Return the numerical integral of a waveform's dependent variable vector. The method used is the `trapezoidal <https://en.wikipedia.org/wiki/Trapezoidal_rule>`_ method :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param indep_min: Independent vector start point of comp...
def envCheckFilter(self, name, attr): """Check if a specific graph attribute is enabled or disabled through the use of a filter based on include_<name> and exclude_<name> environment variables. @param name: Name of the Filter. @param attr: Name of the Attribute. ...
Check if a specific graph attribute is enabled or disabled through the use of a filter based on include_<name> and exclude_<name> environment variables. @param name: Name of the Filter. @param attr: Name of the Attribute. @return: Return True if the attribute is en...
def highres_imu_send(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated, force_mavlink1=False): ''' The IMU readings in SI units in NED body frame time_usec : Ti...
The IMU readings in SI units in NED body frame time_usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) xacc : X acceleration (m/s^2) (float) yacc : Y acceleration (m/s^2) (float) ...
def convert_html_to_text(value, preserve_urls=False): r""" >>> convert_html_to_text( ... ''' ... <html><body> ... Look &amp; click ... <a href="https://example.com">here</a> ... </body></html>''', preserve_urls=True) 'Look & click here (https://example.com)' ...
r""" >>> convert_html_to_text( ... ''' ... <html><body> ... Look &amp; click ... <a href="https://example.com">here</a> ... </body></html>''', preserve_urls=True) 'Look & click here (https://example.com)' >>> convert_html_to_text( ... ''' ... <...
def rename_in_module(occurrences_finder, new_name, resource=None, pymodule=None, replace_primary=False, region=None, reads=True, writes=True): """Returns the changed source or `None` if there is no changes""" if resource is not None: source_code = resource.read(...
Returns the changed source or `None` if there is no changes
def change_parameters(self,params): """ Utility function for changing the approximate distribution parameters """ no_of_params = 0 for core_param in range(len(self.q)): for approx_param in range(self.q[core_param].param_no): self.q[core_param].vi_chang...
Utility function for changing the approximate distribution parameters
def wrapComponent(comp): """Wraps a StimulusComponent with a class containing methods for painting and editing. Class will in fact, be the same as the component provided, but will also be a subclass of QStimulusComponent :param comp: Component to wrap :type comp: subclass of AbstractStimulusC...
Wraps a StimulusComponent with a class containing methods for painting and editing. Class will in fact, be the same as the component provided, but will also be a subclass of QStimulusComponent :param comp: Component to wrap :type comp: subclass of AbstractStimulusComponent :returns: sublass o...
def read(self, limit=-1): """Read content. See file.read""" remaining = self.len - self.parent_fd.tell() + self.offset if limit > remaining or limit == -1: limit = remaining return self.parent_fd.read(limit)
Read content. See file.read
def rows_to_columns(data, schema=None): """ :param data: array of objects :param schema: Known schema, will be extended to include all properties found in data :return: Table """ if not schema: schema = SchemaTree() all_schema = schema all_leaves = schema.leaves values = {ful...
:param data: array of objects :param schema: Known schema, will be extended to include all properties found in data :return: Table
def run(self, command, application): """Get or set the profile. If .profile is called with no args, the current profile is displayed. If the .profile command is called with a single arg, then the current profile for the application will be set to the new value. """ ...
Get or set the profile. If .profile is called with no args, the current profile is displayed. If the .profile command is called with a single arg, then the current profile for the application will be set to the new value.
def _wrap_value_with_context(self, tokens: List[Token], start: int, end: int) -> Extraction: """Wraps the final result""" return Extraction(' '.join([x.orth_ if isinstance(x, Token) else x for x in tokens[start:end]]), self.name, start_token=start, ...
Wraps the final result
def pbis(a): """End point of a reflected sun ray, given an angle a.""" return(math.cos(3*a - math.pi), (math.sin(3*a - math.pi)))
End point of a reflected sun ray, given an angle a.
def main(argv=None): """Count the hits from logfile.""" parser = create_parser('hits_counter', description=__doc__) parser.add_argument('--hostname', default='cnx.org', help="hostname of the site (default: cnx.org)") parser.add_argument('--log-format', def...
Count the hits from logfile.
def parse_rawprofile_blocks(text): """ Split the file into blocks along delimters and and put delimeters back in the list """ # The total time reported in the raw output is from pystone not kernprof # The pystone total time is actually the average time spent in the function delim = 'Total ti...
Split the file into blocks along delimters and and put delimeters back in the list
def get_lyrics_genius(song_title): ''' Scrapes the lyrics from Genius.com ''' base_url = "http://api.genius.com" headers = {'Authorization': 'Bearer %s' %(GENIUS_KEY)} search_url = base_url + "/search" data = {'q': song_title} response = requests.get(search_url, data=data, headers=heade...
Scrapes the lyrics from Genius.com
def _viewbox_set(self, viewbox): """ Friend method of viewbox to register itself. """ self._viewbox = viewbox # Connect viewbox.events.mouse_press.connect(self.viewbox_mouse_event) viewbox.events.mouse_release.connect(self.viewbox_mouse_event) viewbox.events.mouse...
Friend method of viewbox to register itself.
def partialReleaseComplete(): """PARTIAL RELEASE COMPLETE Section 9.1.27""" a = TpPd(pd=0x6) b = MessageType(mesType=0xf) # 00001111 packet = a / b return packet
PARTIAL RELEASE COMPLETE Section 9.1.27
def _init_append(self): """ Initializes file on 'a' mode. """ # Require to load the full file content in buffer self._write_buffer[:] = self._readall() # Make initial seek position to current end of file self._seek = self._size
Initializes file on 'a' mode.
def connect(filename: str, mode: str = 'r+', *, validate: bool = True, spec_version: str = "2.0.1") -> LoomConnection: """ Establish a connection to a .loom file. Args: filename: Path to the Loom file to open mode: Read/write mode, 'r+' (read/write) or 'r' (read-only), defaults to 'r+' validate: Validate ...
Establish a connection to a .loom file. Args: filename: Path to the Loom file to open mode: Read/write mode, 'r+' (read/write) or 'r' (read-only), defaults to 'r+' validate: Validate the file structure against the Loom file format specification spec_version: The loom file spec version to validate against ...
def MobileDeviceConfigurationProfile(self, data=None, subset=None): """{dynamic_docstring}""" return self.factory.get_object( jssobjects.MobileDeviceConfigurationProfile, data, subset)
{dynamic_docstring}
def from_s3_json(cls, bucket_name, key, json_path=None, key_mapping=None, aws_profile=None, aws_access_key_id=None, aws_secret_access_key=None, region_name=None): # pragma: no cover """ Load databas...
Load database credential from json on s3. :param bucket_name: str :param key: str :param aws_profile: if None, assume that you are using this from AWS cloud. (service on the same cloud doesn't need profile name) :param aws_access_key_id: str, not recommend to use :pa...
def __modify(self, checkout_id, **kwargs): """Call documentation: `/checkout/modify <https://www.wepay.com/developer/reference/checkout#modify>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``bat...
Call documentation: `/checkout/modify <https://www.wepay.com/developer/reference/checkout#modify>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `authorization` par...
def _map_from_binaries(self, eopatch, dst_shape, request_data): """ Each request represents a binary class which will be mapped to the scalar `raster_value` """ if self.feature_name in eopatch[self.feature_type]: raster = eopatch[self.feature_type][self.feature_name].squeeze(...
Each request represents a binary class which will be mapped to the scalar `raster_value`
def synchronizeResponse(self, pid, vendorSpecific=None): """CNRead.synchronize(session, pid) → boolean POST /synchronize. Args: pid: vendorSpecific: """ mmp_dict = {'pid': pid} return self.POST(['synchronize'], fields=mmp_dict, headers=vendorSpecific)
CNRead.synchronize(session, pid) → boolean POST /synchronize. Args: pid: vendorSpecific:
def userInformation(MoreData_presence=0): """USER INFORMATION Section 9.3.31""" a = TpPd(pd=0x3) b = MessageType(mesType=0x20) # 000100000 c = UserUser() packet = a / b / c if MoreData_presence is 1: d = MoreDataHdr(ieiMD=0xA0, eightBitMD=0x0) packet = packet / d return pack...
USER INFORMATION Section 9.3.31
def register_dataframe_method(method): """Register a function as a method attached to the Pandas DataFrame. Example ------- .. code-block:: python @register_dataframe_method def print_column(df, col): '''Print the dataframe column given''' print(df[col]) ""...
Register a function as a method attached to the Pandas DataFrame. Example ------- .. code-block:: python @register_dataframe_method def print_column(df, col): '''Print the dataframe column given''' print(df[col])
def points_are_in_a_straight_line( points, tolerance=1e-7 ): """ Check whether a set of points fall on a straight line. Calculates the areas of triangles formed by triplets of the points. Returns False is any of these areas are larger than the tolerance. Args: points (list(np.array)): list ...
Check whether a set of points fall on a straight line. Calculates the areas of triangles formed by triplets of the points. Returns False is any of these areas are larger than the tolerance. Args: points (list(np.array)): list of Cartesian coordinates for each point. tolerance (optional:floa...
def serviceViewChangerOutBox(self, limit: int = None) -> int: """ Service at most `limit` number of messages from the view_changer's outBox. :return: the number of messages successfully serviced. """ msgCount = 0 while self.view_changer.outBox and (not limit or msgCount ...
Service at most `limit` number of messages from the view_changer's outBox. :return: the number of messages successfully serviced.
def z(self, position=None): """Set/Get actor position along z axis.""" p = self.GetPosition() if position is None: return p[2] self.SetPosition(p[0], p[1], position) if self.trail: self.updateTrail() return self
Set/Get actor position along z axis.
def pop_parameter(key): '''Remove and get parameter by key. Args: key(str): Key of parameter. Returns: ~nnabla.Variable Parameter if key found, otherwise None. ''' names = key.split('/') if len(names) > 1: with parameter_scope(names[0]): return pop_paramete...
Remove and get parameter by key. Args: key(str): Key of parameter. Returns: ~nnabla.Variable Parameter if key found, otherwise None.
def _coligative(self, rho, A, fav): """Miscelaneous properties of humid air Parameters ---------- rho : float Density, [kg/m³] A : float Mass fraction of dry air in humid air, [kg/kg] fav : dict dictionary with helmholtz energy and der...
Miscelaneous properties of humid air Parameters ---------- rho : float Density, [kg/m³] A : float Mass fraction of dry air in humid air, [kg/kg] fav : dict dictionary with helmholtz energy and derivatives Returns ------- ...
def to_csv(self, file): """ Write all the trajectories of a collection to a csv file with the headers 'description', 'time' and 'value'. :param file: a file object to write to :type file: :class:`file` :return: """ file.write("description,time,value\n") f...
Write all the trajectories of a collection to a csv file with the headers 'description', 'time' and 'value'. :param file: a file object to write to :type file: :class:`file` :return:
def start(self): """ Creates a SSL connection to the iDigi Server and sends a ConnectionRequest message. """ self.log.info("Starting SSL Session for Monitor %s." % self.monitor_id) if self.socket is not None: raise Exception("Socket alrea...
Creates a SSL connection to the iDigi Server and sends a ConnectionRequest message.
def center_text_cursor(object): """ Centers the text cursor position. :param object: Object to decorate. :type object: object :return: Object. :rtype: object """ @functools.wraps(object) def center_text_cursor_wrapper(*args, **kwargs): """ Centers the text cursor po...
Centers the text cursor position. :param object: Object to decorate. :type object: object :return: Object. :rtype: object
def copy_vpcs_configs(source, target): """ Copy any VPCS configs to the converted topology :param str source: Source topology directory :param str target: Target topology files directory """ # Prepare a list of files to copy vpcs_files = glob.glob(os.path.join(source, 'configs', '*.vpc')) ...
Copy any VPCS configs to the converted topology :param str source: Source topology directory :param str target: Target topology files directory
def read_string(self, content): """ Reads a Python string that contains C++ code, and return the declarations tree. """ header_file = utils.create_temp_file_name(suffix='.h') with open(header_file, "w+") as f: f.write(content) try: decls...
Reads a Python string that contains C++ code, and return the declarations tree.
def log_images(self, name, images, step=None): """Log new images for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). images (list): list of images to visualize step (int): non...
Log new images for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). images (list): list of images to visualize step (int): non-negative integer used for visualization
def remotes_get(self): """Return remotes like git remote -v. :rtype: dict of tuples """ remotes = {} cmd = self.run(['remote']) ret = filter(None, cmd.split('\n')) for remote_name in ret: remotes[remote_name] = self.remote_get(remote_name) r...
Return remotes like git remote -v. :rtype: dict of tuples
def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._remind...
UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file
def check_backslashes(self, definition, docstring): r'''D301: Use r""" if any backslashes in a docstring. Use r"""raw triple double quotes""" if you use any backslashes (\) in your docstrings. ''' # Just check that docstring is raw, check_triple_double_quotes # ensures ...
r'''D301: Use r""" if any backslashes in a docstring. Use r"""raw triple double quotes""" if you use any backslashes (\) in your docstrings.
def all_dims(self): """The dimensions for each of the arrays in this list""" return [ _get_dims(arr) if not isinstance(arr, ArrayList) else arr.all_dims for arr in self]
The dimensions for each of the arrays in this list
def run_with_tornado(self): """ runs the tornado/websockets based test server """ from zengine.tornado_server.server import runserver runserver(self.manager.args.addr, int(self.manager.args.port))
runs the tornado/websockets based test server
def _collapse_edge_passing_predicates(graph: BELGraph, edge_predicates: EdgePredicates = None) -> None: """Collapse all edges passing the given edge predicates.""" for u, v, _ in filter_edges(graph, edge_predicates=edge_predicates): collapse_pair(graph, survivor=u, victim=v)
Collapse all edges passing the given edge predicates.
def read_csv(csv_name, usecols=None): """Returns a DataFrame from a .csv file stored in /data/raw/""" csv_path = os.path.join(DATA_FOLDER, csv_name) csv = pd.read_csv(csv_path, low_memory=False, usecols=usecols, encoding="utf-8") return csv
Returns a DataFrame from a .csv file stored in /data/raw/