text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Moves the email to the folder specified by the folder parameter. <END_TASK> <USER_TASK:> Description: def move_to(self, folder): """Moves the email to the folder specified by the folder parameter. Args: folder: A string containing the folder ID the message should be moved to, or a Folder instance """
if isinstance(folder, Folder): self.move_to(folder.id) else: self._move_to(folder)
<SYSTEM_TASK:> transforms image from RGB to CMY <END_TASK> <USER_TASK:> Description: def rgb2cmy(self, img, whitebg=False): """transforms image from RGB to CMY"""
tmp = img*1.0 if whitebg: tmp = (1.0 - (img - img.min())/(img.max() - img.min())) out = tmp*0.0 out[:,:,0] = (tmp[:,:,1] + tmp[:,:,2])/2.0 out[:,:,1] = (tmp[:,:,0] + tmp[:,:,2])/2.0 out[:,:,2] = (tmp[:,:,0] + tmp[:,:,1])/2.0 return out
<SYSTEM_TASK:> checks to see if plugin ends with one of the <END_TASK> <USER_TASK:> Description: def plugin_valid(self, filepath): """ checks to see if plugin ends with one of the approved extensions """
plugin_valid = False for extension in self.extensions: if filepath.endswith(".{}".format(extension)): plugin_valid = True break return plugin_valid
<SYSTEM_TASK:> Returns the JSON formatting required by Outlook's API for contacts <END_TASK> <USER_TASK:> Description: def api_representation(self): """ Returns the JSON formatting required by Outlook's API for contacts """
return dict(EmailAddress=dict(Name=self.name, Address=self.email))
<SYSTEM_TASK:> Emails from this contact will either always be put in the Focused inbox, or always put in Other, based on <END_TASK> <USER_TASK:> Description: def set_focused(self, account, is_focused): # type: (OutlookAccount, bool) -> bool """ Emails from this contact will either always be put in the Focused inbox, or always put in Other, based on the value of is_focused. Args: account (OutlookAccount): The :class:`OutlookAccount <pyOutlook.core.main.OutlookAccount>` the override should be set for is_focused (bool): Whether this contact should be set to Focused, or Other. Returns: True if the request was successful """
endpoint = 'https://outlook.office.com/api/v2.0/me/InferenceClassification/Overrides' if is_focused: classification = 'Focused' else: classification = 'Other' data = dict(ClassifyAs=classification, SenderEmailAddress=dict(Address=self.email)) r = requests.post(endpoint, headers=account._headers, data=json.dumps(data)) # Will raise an error if necessary, otherwise returns True result = check_response(r) self.focused = is_focused return result
<SYSTEM_TASK:> Checks that a response is successful, raising the appropriate Exceptions otherwise. <END_TASK> <USER_TASK:> Description: def check_response(response): """ Checks that a response is successful, raising the appropriate Exceptions otherwise. """
status_code = response.status_code if 100 < status_code < 299: return True elif status_code == 401 or status_code == 403: message = get_response_data(response) raise AuthError('Access Token Error, Received ' + str(status_code) + ' from Outlook REST Endpoint with the message: {}'.format(message)) elif status_code == 400: message = get_response_data(response) raise RequestError('The request made to the Outlook API was invalid. Received the following message: {}'. format(message)) else: message = get_response_data(response) raise APIError('Encountered an unknown error from the Outlook API: {}'.format(message))
<SYSTEM_TASK:> Gets out the plugins from the internal state. Returns a list object. <END_TASK> <USER_TASK:> Description: def get_plugins(self, filter_function=None): """ Gets out the plugins from the internal state. Returns a list object. If the optional filter_function is supplied, applies the filter function to the arguments before returning them. Filters should be callable and take a list argument of plugins. """
plugins = self.plugins if filter_function is not None: plugins = filter_function(plugins) return plugins
<SYSTEM_TASK:> internal method that gets every instance of the klasses <END_TASK> <USER_TASK:> Description: def _get_instance(self, klasses): """ internal method that gets every instance of the klasses out of the internal plugin state. """
return [x for x in self.plugins if isinstance(x, klasses)]
<SYSTEM_TASK:> Gets instances out of the internal state using <END_TASK> <USER_TASK:> Description: def get_instances(self, filter_function=IPlugin): """ Gets instances out of the internal state using the default filter supplied in filter_function. By default, it is the class IPlugin. Can optionally pass in a list or tuple of classes in for `filter_function` which will accomplish the same goal. lastly, a callable can be passed in, however it is up to the user to determine if the objects are instances or not. """
if isinstance(filter_function, (list, tuple)): return self._get_instance(filter_function) elif inspect.isclass(filter_function): return self._get_instance(filter_function) elif filter_function is None: return self.plugins else: return filter_function(self.plugins)
<SYSTEM_TASK:> Register classes as plugins that are not subclassed from <END_TASK> <USER_TASK:> Description: def register_classes(self, classes): """ Register classes as plugins that are not subclassed from IPlugin. `classes` may be a single object or an iterable. """
classes = util.return_list(classes) for klass in classes: IPlugin.register(klass)
<SYSTEM_TASK:> internal method to parse instances of plugins. <END_TASK> <USER_TASK:> Description: def _instance_parser(self, plugins): """ internal method to parse instances of plugins. Determines if each class is a class instance or object instance and calls the appropiate handler method. """
plugins = util.return_list(plugins) for instance in plugins: if inspect.isclass(instance): self._handle_class_instance(instance) else: self._handle_object_instance(instance)
<SYSTEM_TASK:> handles class instances. If a class is blacklisted, returns. <END_TASK> <USER_TASK:> Description: def _handle_class_instance(self, klass): """ handles class instances. If a class is blacklisted, returns. If uniuqe_instances is True and the class is unique, instantiates the class and adds the new object to plugins. If not unique_instances, creates and adds new instance to plugin state """
if (klass in self.blacklisted_plugins or not self.instantiate_classes or klass == IPlugin): return elif self.unique_instances and self._unique_class(klass): self.plugins.append(klass()) elif not self.unique_instances: self.plugins.append(klass())
<SYSTEM_TASK:> internal method to check if any of the plugins are instances <END_TASK> <USER_TASK:> Description: def _unique_class(self, cls): """ internal method to check if any of the plugins are instances of a given cls """
return not any(isinstance(obj, cls) for obj in self.plugins)
<SYSTEM_TASK:> add blacklisted plugins. <END_TASK> <USER_TASK:> Description: def add_blacklisted_plugins(self, plugins): """ add blacklisted plugins. `plugins` may be a single object or iterable. """
plugins = util.return_list(plugins) self.blacklisted_plugins.extend(plugins)
<SYSTEM_TASK:> sets blacklisted plugins. <END_TASK> <USER_TASK:> Description: def set_blacklisted_plugins(self, plugins): """ sets blacklisted plugins. `plugins` may be a single object or iterable. """
plugins = util.return_list(plugins) self.blacklisted_plugins = plugins
<SYSTEM_TASK:> Collects all the plugins from `modules`. <END_TASK> <USER_TASK:> Description: def collect_plugins(self, modules=None): """ Collects all the plugins from `modules`. If modules is None, collects the plugins from the loaded modules. All plugins are passed through the module filters, if any are any, and returned as a list. """
if modules is None: modules = self.get_loaded_modules() else: modules = util.return_list(modules) plugins = [] for module in modules: module_plugins = [(item[1], item[0]) for item in inspect.getmembers(module) if item[1] and item[0] != '__builtins__'] module_plugins, names = zip(*module_plugins) module_plugins = self._filter_modules(module_plugins, names) plugins.extend(module_plugins) return plugins
<SYSTEM_TASK:> Sets the internal module filters to `module_plugin_filters` <END_TASK> <USER_TASK:> Description: def set_module_plugin_filters(self, module_plugin_filters): """ Sets the internal module filters to `module_plugin_filters` `module_plugin_filters` may be a single object or an iterable. Every module filters must be a callable and take in a list of plugins and their associated names. """
module_plugin_filters = util.return_list(module_plugin_filters) self.module_plugin_filters = module_plugin_filters
<SYSTEM_TASK:> Adds `module_plugin_filters` to the internal module filters. <END_TASK> <USER_TASK:> Description: def add_module_plugin_filters(self, module_plugin_filters): """ Adds `module_plugin_filters` to the internal module filters. May be a single object or an iterable. Every module filters must be a callable and take in a list of plugins and their associated names. """
module_plugin_filters = util.return_list(module_plugin_filters) self.module_plugin_filters.extend(module_plugin_filters)
<SYSTEM_TASK:> An internal method that gets the `names` from sys.modules and returns <END_TASK> <USER_TASK:> Description: def _get_modules(self, names): """ An internal method that gets the `names` from sys.modules and returns them as a list """
loaded_modules = [] for name in names: loaded_modules.append(sys.modules[name]) return loaded_modules
<SYSTEM_TASK:> Manually add in `modules` to be tracked by the module manager. <END_TASK> <USER_TASK:> Description: def add_to_loaded_modules(self, modules): """ Manually add in `modules` to be tracked by the module manager. `modules` may be a single object or an iterable. """
modules = util.return_set(modules) for module in modules: if not isinstance(module, str): module = module.__name__ self.loaded_modules.add(module)
<SYSTEM_TASK:> Internal helper method to parse all of the plugins and names <END_TASK> <USER_TASK:> Description: def _filter_modules(self, plugins, names): """ Internal helper method to parse all of the plugins and names through each of the module filters """
if self.module_plugin_filters: # check to make sure the number of plugins isn't changing original_length_plugins = len(plugins) module_plugins = set() for module_filter in self.module_plugin_filters: module_plugins.update(module_filter(plugins, names)) if len(plugins) < original_length_plugins: warning = """Module Filter removing plugins from original data member! Suggest creating a new list in each module filter and returning new list instead of modifying the original data member so subsequent module filters can have access to all the possible plugins.\n {}""" self._log.info(warning.format(module_filter)) plugins = module_plugins return plugins
<SYSTEM_TASK:> processes the filepath by checking if it is a directory or not <END_TASK> <USER_TASK:> Description: def _clean_filepath(self, filepath): """ processes the filepath by checking if it is a directory or not and adding `.py` if not present. """
if (os.path.isdir(filepath) and os.path.isfile(os.path.join(filepath, '__init__.py'))): filepath = os.path.join(filepath, '__init__.py') if (not filepath.endswith('.py') and os.path.isfile(filepath + '.py')): filepath += '.py' return filepath
<SYSTEM_TASK:> checks to see if the filepath has already been processed <END_TASK> <USER_TASK:> Description: def _processed_filepath(self, filepath): """ checks to see if the filepath has already been processed """
processed = False if filepath in self.processed_filepaths.values(): processed = True return processed
<SYSTEM_TASK:> Updates the loaded modules by checking if they are still in sys.modules <END_TASK> <USER_TASK:> Description: def _update_loaded_modules(self): """ Updates the loaded modules by checking if they are still in sys.modules """
system_modules = sys.modules.keys() for module in list(self.loaded_modules): if module not in system_modules: self.processed_filepaths.pop(module) self.loaded_modules.remove(module)
<SYSTEM_TASK:> finish wx event, forward it to other wx objects <END_TASK> <USER_TASK:> Description: def ForwardEvent(self, event=None): """finish wx event, forward it to other wx objects"""
if event is not None: event.Skip() if self.HasCapture(): try: self.ReleaseMouse() except: pass
<SYSTEM_TASK:> formatter for date x-data. primitive, and probably needs <END_TASK> <USER_TASK:> Description: def __date_format(self, x): """ formatter for date x-data. primitive, and probably needs improvement, following matplotlib's date methods. """
if x < 1: x = 1 span = self.axes.xaxis.get_view_interval() tmin = max(1.0, span[0]) tmax = max(2.0, span[1]) tmin = time.mktime(dates.num2date(tmin).timetuple()) tmax = time.mktime(dates.num2date(tmax).timetuple()) nhours = (tmax - tmin)/3600.0 fmt = "%m/%d" if nhours < 0.1: fmt = "%H:%M\n%Ssec" elif nhours < 4: fmt = "%m/%d\n%H:%M" elif nhours < 24*8: fmt = "%m/%d\n%H:%M" try: return time.strftime(fmt, dates.num2date(x).timetuple()) except: return "?"
<SYSTEM_TASK:> motion event handler for zoom mode <END_TASK> <USER_TASK:> Description: def zoom_motion(self, event=None): """motion event handler for zoom mode"""
try: x, y = event.x, event.y except: return self.report_motion(event=event) if self.zoom_ini is None: return ini_x, ini_y, ini_xd, ini_yd = self.zoom_ini if event.xdata is not None: self.x_lastmove = event.xdata if event.ydata is not None: self.y_lastmove = event.ydata x0 = min(x, ini_x) ymax = max(y, ini_y) width = abs(x-ini_x) height = abs(y-ini_y) y0 = self.canvas.figure.bbox.height - ymax zdc = wx.ClientDC(self.canvas) zdc.SetLogicalFunction(wx.XOR) zdc.SetBrush(wx.TRANSPARENT_BRUSH) zdc.SetPen(wx.Pen('White', 2, wx.SOLID)) zdc.ResetBoundingBox() if not is_wxPhoenix: zdc.BeginDrawing() # erase previous box if self.rbbox is not None: zdc.DrawRectangle(*self.rbbox) self.rbbox = (x0, y0, width, height) zdc.DrawRectangle(*self.rbbox) if not is_wxPhoenix: zdc.EndDrawing()
<SYSTEM_TASK:> leftdown event handler for zoom mode <END_TASK> <USER_TASK:> Description: def zoom_leftdown(self, event=None): """leftdown event handler for zoom mode"""
self.x_lastmove, self.y_lastmove = None, None self.zoom_ini = (event.x, event.y, event.xdata, event.ydata) self.report_leftdown(event=event)
<SYSTEM_TASK:> leftdown event handler for lasso mode <END_TASK> <USER_TASK:> Description: def lasso_leftdown(self, event=None): """leftdown event handler for lasso mode"""
try: self.report_leftdown(event=event) except: return if event.inaxes: # set lasso color color='goldenrod' cmap = getattr(self.conf, 'cmap', None) if isinstance(cmap, dict): cmap = cmap['int'] try: if cmap is not None: rgb = (int(i*255)^255 for i in cmap._lut[0][:3]) color = '#%02x%02x%02x' % tuple(rgb) except: pass self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.lassoHandler) self.lasso.line.set_color(color)
<SYSTEM_TASK:> Renames the Folder to the provided name. <END_TASK> <USER_TASK:> Description: def rename(self, new_folder_name): """Renames the Folder to the provided name. Args: new_folder_name: A string of the replacement name. Raises: AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token. Returns: A new Folder representing the folder with the new name on Outlook. """
headers = self.headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self.id payload = '{ "DisplayName": "' + new_folder_name + '"}' r = requests.patch(endpoint, headers=headers, data=payload) if check_response(r): return_folder = r.json() return self._json_to_folder(self.account, return_folder)
<SYSTEM_TASK:> Retrieve all child Folders inside of this Folder. <END_TASK> <USER_TASK:> Description: def get_subfolders(self): """Retrieve all child Folders inside of this Folder. Raises: AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token. Returns: List[:class:`Folder <pyOutlook.core.folder.Folder>`] """
headers = self.headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self.id + '/childfolders' r = requests.get(endpoint, headers=headers) if check_response(r): return self._json_to_folders(self.account, r.json())
<SYSTEM_TASK:> Deletes this Folder. <END_TASK> <USER_TASK:> Description: def delete(self): """Deletes this Folder. Raises: AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token. """
headers = self.headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self.id r = requests.delete(endpoint, headers=headers) check_response(r)
<SYSTEM_TASK:> Move the Folder into a different folder. <END_TASK> <USER_TASK:> Description: def move_into(self, destination_folder): # type: (Folder) -> None """Move the Folder into a different folder. This makes the Folder provided a child folder of the destination_folder. Raises: AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token. Args: destination_folder: A :class:`Folder <pyOutlook.core.folder.Folder>` that should become the parent Returns: A new :class:`Folder <pyOutlook.core.folder.Folder>` that is now inside of the destination_folder. """
headers = self.headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self.id + '/move' payload = '{ "DestinationId": "' + destination_folder.id + '"}' r = requests.post(endpoint, headers=headers, data=payload) if check_response(r): return_folder = r.json() return self._json_to_folder(self.account, return_folder)
<SYSTEM_TASK:> Creates a child folder within the Folder it is called from and returns the new Folder object. <END_TASK> <USER_TASK:> Description: def create_child_folder(self, folder_name): """Creates a child folder within the Folder it is called from and returns the new Folder object. Args: folder_name: The name of the folder to create Returns: :class:`Folder <pyOutlook.core.folder.Folder>` """
headers = self.headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self.id + '/childfolders' payload = '{ "DisplayName": "' + folder_name + '"}' r = requests.post(endpoint, headers=headers, data=payload) if check_response(r): return_folder = r.json() return self._json_to_folder(self.account, return_folder)
<SYSTEM_TASK:> Format a number with '%g'-like format, except that <END_TASK> <USER_TASK:> Description: def gformat(val, length=11): """Format a number with '%g'-like format, except that a) the length of the output string will be the requested length. b) positive numbers will have a leading blank. b) the precision will be as high as possible. c) trailing zeros will not be trimmed. The precision will typically be length-7. Arguments --------- val value to be formatted length length of output string Returns ------- string of specified length. Notes ------ Positive values will have leading blank. """
try: expon = int(log10(abs(val))) except (OverflowError, ValueError): expon = 0 length = max(length, 7) form = 'e' prec = length - 7 if abs(expon) > 99: prec -= 1 elif ((expon > 0 and expon < (prec+4)) or (expon <= 0 and -expon < (prec-1))): form = 'f' prec += 4 if expon > 0: prec -= expon fmt = '{0: %i.%i%s}' % (length, prec, form) return fmt.format(val)
<SYSTEM_TASK:> set up figure for printing. Using the standard wx Printer <END_TASK> <USER_TASK:> Description: def Setup(self, event=None): """set up figure for printing. Using the standard wx Printer Setup Dialog. """
if hasattr(self, 'printerData'): data = wx.PageSetupDialogData() data.SetPrintData(self.printerData) else: data = wx.PageSetupDialogData() data.SetMarginTopLeft( (15, 15) ) data.SetMarginBottomRight( (15, 15) ) dlg = wx.PageSetupDialog(None, data) if dlg.ShowModal() == wx.ID_OK: data = dlg.GetPageSetupData() tl = data.GetMarginTopLeft() br = data.GetMarginBottomRight() self.printerData = wx.PrintData(data.GetPrintData()) dlg.Destroy()
<SYSTEM_TASK:> utility to set a floating value, <END_TASK> <USER_TASK:> Description: def set_float(val): """ utility to set a floating value, useful for converting from strings """
out = None if not val in (None, ''): try: out = float(val) except ValueError: return None if numpy.isnan(out): out = default return out
<SYSTEM_TASK:> add arrow supplied x, y position <END_TASK> <USER_TASK:> Description: def add_arrow(self, x1, y1, x2, y2, side='left', shape='full', color='black', width=0.01, head_width=0.03, overhang=0, **kws): """add arrow supplied x, y position"""
dx, dy = x2-x1, y2-y1 axes = self.axes if side == 'right': axes = self.get_right_axes() axes.arrow(x1, y1, dx, dy, shape=shape, length_includes_head=True, fc=color, edgecolor=color, width=width, head_width=head_width, overhang=overhang, **kws) self.draw()
<SYSTEM_TASK:> show configuration frame <END_TASK> <USER_TASK:> Description: def configure(self, event=None): """show configuration frame"""
if self.win_config is not None: try: self.win_config.Raise() except: self.win_config = None if self.win_config is None: self.win_config = PlotConfigFrame(parent=self, config=self.conf, trace_color_callback=self.trace_color_callback) self.win_config.Raise()
<SYSTEM_TASK:> Overload of the draw function that update <END_TASK> <USER_TASK:> Description: def _updateCanvasDraw(self): """ Overload of the draw function that update axes position before each draw"""
fn = self.canvas.draw def draw2(*a,**k): self._updateGridSpec() return fn(*a,**k) self.canvas.draw = draw2
<SYSTEM_TASK:> Enable periodically monitoring. <END_TASK> <USER_TASK:> Description: def start_monitoring(self): """Enable periodically monitoring. """
if self.__monitoring is False: self.__monitoring = True self.__monitoring_action()
<SYSTEM_TASK:> Returns the decoded claims without verification of any kind. <END_TASK> <USER_TASK:> Description: def get_unverified_claims(token): """Returns the decoded claims without verification of any kind. Args: token (str): A signed JWT to decode the headers from. Returns: dict: The dict representation of the token claims. Raises: JWTError: If there is an exception decoding the token. """
try: claims = jws.get_unverified_claims(token) except: raise JWTError('Error decoding token claims.') try: claims = json.loads(claims.decode('utf-8')) except ValueError as e: raise JWTError('Invalid claims string: %s' % e) if not isinstance(claims, Mapping): raise JWTError('Invalid claims string: must be a json object') return claims
<SYSTEM_TASK:> Validates that the 'at_hash' parameter included in the claims matches <END_TASK> <USER_TASK:> Description: def _validate_at_hash(claims, access_token, algorithm): """ Validates that the 'at_hash' parameter included in the claims matches with the access_token returned alongside the id token as part of the authorization_code flow. Args: claims (dict): The claims dictionary to validate. access_token (str): The access token returned by the OpenID Provider. algorithm (str): The algorithm used to sign the JWT, as specified by the token headers. """
if 'at_hash' not in claims and not access_token: return elif 'at_hash' in claims and not access_token: msg = 'No access_token provided to compare against at_hash claim.' raise JWTClaimsError(msg) elif access_token and 'at_hash' not in claims: msg = 'at_hash claim missing from token.' raise JWTClaimsError(msg) try: expected_hash = calculate_at_hash(access_token, ALGORITHMS.HASHES[algorithm]) except (TypeError, ValueError): msg = 'Unable to calculate at_hash to verify against token claims.' raise JWTClaimsError(msg) if claims['at_hash'] != expected_hash: raise JWTClaimsError('at_hash claim does not match access_token.')
<SYSTEM_TASK:> Given a path to a KML file, convert it to a a GeoJSON FeatureCollection file and save it to the given output directory. <END_TASK> <USER_TASK:> Description: def k2g(kml_path, output_dir, separate_folders, style_type, style_filename): """ Given a path to a KML file, convert it to a a GeoJSON FeatureCollection file and save it to the given output directory. If ``--separate_folders``, then create several GeoJSON files, one for each folder in the KML file that contains geodata or that has a descendant node that contains geodata. Warning: this can produce GeoJSON files with the same geodata in case the KML file has nested folders with geodata. If ``--style_type`` is specified, then also build a JSON style file of the given style type and save it to the output directory under the file name given by ``--style_filename``. """
m.convert(kml_path, output_dir, separate_folders, style_type, style_filename)
<SYSTEM_TASK:> Given a list of strings ``names``, return a new list of names where repeated names have been disambiguated by repeatedly appending the given mark. <END_TASK> <USER_TASK:> Description: def disambiguate(names, mark='1'): """ Given a list of strings ``names``, return a new list of names where repeated names have been disambiguated by repeatedly appending the given mark. EXAMPLE:: >>> disambiguate(['sing', 'song', 'sing', 'sing']) ['sing', 'song', 'sing1', 'sing11'] """
names_seen = set() new_names = [] for name in names: new_name = name while new_name in names_seen: new_name += mark new_names.append(new_name) names_seen.add(new_name) return new_names
<SYSTEM_TASK:> Given a KML color string, return an equivalent RGB hex color string and an opacity float rounded to 2 decimal places. <END_TASK> <USER_TASK:> Description: def build_rgb_and_opacity(s): """ Given a KML color string, return an equivalent RGB hex color string and an opacity float rounded to 2 decimal places. EXAMPLE:: >>> build_rgb_and_opacity('ee001122') ('#221100', 0.93) """
# Set defaults color = '000000' opacity = 1 if s.startswith('#'): s = s[1:] if len(s) == 8: color = s[6:8] + s[4:6] + s[2:4] opacity = round(int(s[0:2], 16)/256, 2) elif len(s) == 6: color = s[4:6] + s[2:4] + s[0:2] elif len(s) == 3: color = s[::-1] return '#' + color, opacity
<SYSTEM_TASK:> Given a DOM node, grab its top-level Style nodes, convert every one into a SVG style dictionary, put them in a master dictionary of the form <END_TASK> <USER_TASK:> Description: def build_svg_style(node): """ Given a DOM node, grab its top-level Style nodes, convert every one into a SVG style dictionary, put them in a master dictionary of the form #style ID -> SVG style dictionary, and return the result. The possible keys and values of each SVG style dictionary, the style options, are - ``iconUrl``: URL of icon - ``stroke``: stroke color; RGB hex string - ``stroke-opacity``: stroke opacity - ``stroke-width``: stroke width in pixels - ``fill``: fill color; RGB hex string - ``fill-opacity``: fill opacity """
d = {} for item in get(node, 'Style'): style_id = '#' + attr(item, 'id') # Create style properties props = {} for x in get(item, 'PolyStyle'): color = val(get1(x, 'color')) if color: rgb, opacity = build_rgb_and_opacity(color) props['fill'] = rgb props['fill-opacity'] = opacity # Set default border style props['stroke'] = rgb props['stroke-opacity'] = opacity props['stroke-width'] = 1 fill = valf(get1(x, 'fill')) if fill == 0: props['fill-opacity'] = fill elif fill == 1 and 'fill-opacity' not in props: props['fill-opacity'] = fill outline = valf(get1(x, 'outline')) if outline == 0: props['stroke-opacity'] = outline elif outline == 1 and 'stroke-opacity' not in props: props['stroke-opacity'] = outline for x in get(item, 'LineStyle'): color = val(get1(x, 'color')) if color: rgb, opacity = build_rgb_and_opacity(color) props['stroke'] = rgb props['stroke-opacity'] = opacity width = valf(get1(x, 'width')) if width is not None: props['stroke-width'] = width for x in get(item, 'IconStyle'): icon = get1(x, 'Icon') if not icon: continue # Clear previous style properties props = {} props['iconUrl'] = val(get1(icon, 'href')) d[style_id] = props return d
<SYSTEM_TASK:> Synchronization to deal with elements that are present, and are visible <END_TASK> <USER_TASK:> Description: def wait_for_available(self, locator): """ Synchronization to deal with elements that are present, and are visible :raises: ElementVisiblityTimeout """
for i in range(timeout_seconds): try: if self.is_element_available(locator): break except: pass time.sleep(1) else: raise ElementVisiblityTimeout("%s availability timed out" % locator) return True
<SYSTEM_TASK:> Synchronization to deal with elements that are present, but are disabled until some action <END_TASK> <USER_TASK:> Description: def wait_for_visible(self, locator): """ Synchronization to deal with elements that are present, but are disabled until some action triggers their visibility. :raises: ElementVisiblityTimeout """
for i in range(timeout_seconds): try: if self.driver.is_visible(locator): break except: pass time.sleep(1) else: raise ElementVisiblityTimeout("%s visibility timed out" % locator) return True
<SYSTEM_TASK:> Synchronization on some text being displayed in a particular element. <END_TASK> <USER_TASK:> Description: def wait_for_text(self, locator, text): """ Synchronization on some text being displayed in a particular element. :raises: ElementVisiblityTimeout """
for i in range(timeout_seconds): try: e = self.driver.find_element_by_locator(locator) if e.text == text: break except: pass time.sleep(1) else: raise ElementTextTimeout("%s value timed out" % locator) return True
<SYSTEM_TASK:> Synchronization helper to wait until some element is removed from the page <END_TASK> <USER_TASK:> Description: def wait_for_element_not_present(self, locator): """ Synchronization helper to wait until some element is removed from the page :raises: ElementVisiblityTimeout """
for i in range(timeout_seconds): if self.driver.is_element_present(locator): time.sleep(1) else: break else: raise ElementVisiblityTimeout("%s presence timed out" % locator) return True
<SYSTEM_TASK:> Constructs form from POST method using self.form_class. <END_TASK> <USER_TASK:> Description: def construct_form(self, request): """ Constructs form from POST method using self.form_class. """
if not hasattr(self, 'form_class'): return None if request.method == 'POST': form = self.form_class(self.model, request.POST, request.FILES) else: form = self.form_class(self.model) return form
<SYSTEM_TASK:> Returns True if the given request has permission to use the tool. <END_TASK> <USER_TASK:> Description: def has_permission(self, user): """ Returns True if the given request has permission to use the tool. Can be overriden by the user in subclasses. """
return user.has_perm( self.model._meta.app_label + '.' + self.get_permission() )
<SYSTEM_TASK:> Collects admin and form media. <END_TASK> <USER_TASK:> Description: def media(self, form): """ Collects admin and form media. """
js = ['admin/js/core.js', 'admin/js/admin/RelatedObjectLookups.js', 'admin/js/jquery.min.js', 'admin/js/jquery.init.js'] media = forms.Media( js=['%s%s' % (settings.STATIC_URL, u) for u in js], ) if form: for name, field in form.fields.items(): media = media + field.widget.media return media
<SYSTEM_TASK:> URL patterns for tool linked to _view method. <END_TASK> <USER_TASK:> Description: def _urls(self): """ URL patterns for tool linked to _view method. """
info = ( self.model._meta.app_label, self.model._meta.model_name, self.name, ) urlpatterns = [ url(r'^%s/$' % self.name, self._view, name='%s_%s_%s' % info) ] return urlpatterns
<SYSTEM_TASK:> Builds context with various required variables. <END_TASK> <USER_TASK:> Description: def construct_context(self, request): """ Builds context with various required variables. """
opts = self.model._meta app_label = opts.app_label object_name = opts.object_name.lower() form = self.construct_form(request) media = self.media(form) context = { 'user': request.user, 'title': '%s %s' % (self.label, opts.verbose_name_plural.lower()), 'tool': self, 'opts': opts, 'app_label': app_label, 'media': media, 'form': form, 'changelist_url': reverse('admin:%s_%s_changelist' % ( app_label, object_name )) } # Pass along fieldset if sepcififed. if hasattr(form, 'fieldsets'): admin_form = helpers.AdminForm(form, form.fieldsets, {}) context['adminform'] = admin_form return context
<SYSTEM_TASK:> View wrapper taking care of houskeeping for painless form rendering. <END_TASK> <USER_TASK:> Description: def _view(self, request, extra_context=None): """ View wrapper taking care of houskeeping for painless form rendering. """
if not self.has_permission(request.user): raise PermissionDenied return self.view(request, self.construct_context(request))
<SYSTEM_TASK:> Gets a random row from the provider <END_TASK> <USER_TASK:> Description: def randomRow(self): """ Gets a random row from the provider :returns: List """
l = [] for row in self.data: l.append(row) return random.choice(l)
<SYSTEM_TASK:> Soft assert for equality <END_TASK> <USER_TASK:> Description: def verify_equal(self, first, second, msg=""): """ Soft assert for equality :params want: the value to compare against :params second: the value to compare with :params msg: (Optional) msg explaining the difference """
try: self.assert_equal(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<SYSTEM_TASK:> Soft assert for inequality <END_TASK> <USER_TASK:> Description: def verify_not_equal(self, first, second, msg=""): """ Soft assert for inequality :params want: the value to compare against :params second: the value to compare with :params msg: (Optional) msg explaining the difference """
try: self.assert_not_equal(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<SYSTEM_TASK:> Soft assert for whether the condition is true <END_TASK> <USER_TASK:> Description: def verify_true(self, expr, msg=None): """ Soft assert for whether the condition is true :params expr: the statement to evaluate :params msg: (Optional) msg explaining the difference """
try: self.assert_true(expr, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<SYSTEM_TASK:> Soft assert for whether the condition is false <END_TASK> <USER_TASK:> Description: def verify_false(self, expr, msg=None): """ Soft assert for whether the condition is false :params expr: the statement to evaluate :params msg: (Optional) msg explaining the difference """
try: self.assert_false(expr, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<SYSTEM_TASK:> Soft assert for whether the parameters evaluate to the same object <END_TASK> <USER_TASK:> Description: def verify_is(self, first, second, msg=None): """ Soft assert for whether the parameters evaluate to the same object :params want: the object to compare against :params second: the object to compare with :params msg: (Optional) msg explaining the difference """
try: self.assert_is(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<SYSTEM_TASK:> Soft assert for whether the parameters do not evaluate to the same object <END_TASK> <USER_TASK:> Description: def verify_is_not(self, first, second, msg=None): """ Soft assert for whether the parameters do not evaluate to the same object :params want: the object to compare against :params second: the object to compare with :params msg: (Optional) msg explaining the difference """
try: self.assert_is_not(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<SYSTEM_TASK:> Soft assert for whether the expr is None <END_TASK> <USER_TASK:> Description: def verify_is_none(self, expr, msg=None): """ Soft assert for whether the expr is None :params want: the object to compare against :params second: the object to compare with :params msg: (Optional) msg explaining the difference """
try: self.assert_is_none(expr, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<SYSTEM_TASK:> Soft assert for whether the expr is not None <END_TASK> <USER_TASK:> Description: def verify_is_not_none(self, expr, msg=None): """ Soft assert for whether the expr is not None :params want: the object to compare against :params second: the object to compare with :params msg: (Optional) msg explaining the difference """
try: self.assert_is_not_none(expr, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<SYSTEM_TASK:> Soft assert for whether the first is in second <END_TASK> <USER_TASK:> Description: def verify_in(self, first, second, msg=""): """ Soft assert for whether the first is in second :params first: the value to check :params second: the container to check in :params msg: (Optional) msg explaining the difference """
try: self.assert_in(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<SYSTEM_TASK:> Soft assert for whether the first is not in second <END_TASK> <USER_TASK:> Description: def verify_not_in(self, first, second, msg=""): """ Soft assert for whether the first is not in second :params first: the value to check :params second: the container to check in :params msg: (Optional) msg explaining the difference """
try: self.assert_not_in(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<SYSTEM_TASK:> Soft assert for whether the is an instance of cls <END_TASK> <USER_TASK:> Description: def verify_is_instance(self, obj, cls, msg=""): """ Soft assert for whether the is an instance of cls :params obj: the object instance :params cls: the class to compare against :params msg: (Optional) msg explaining the difference """
try: self.assert_is_instance(obj, cls, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<SYSTEM_TASK:> Soft assert for whether the is not an instance of cls <END_TASK> <USER_TASK:> Description: def verify_is_not_instance(self, obj, cls, msg=""): """ Soft assert for whether the is not an instance of cls :params obj: the object instance :params cls: the class to compare against :params msg: (Optional) msg explaining the difference """
try: self.assert_is_not_instance(obj, cls, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<SYSTEM_TASK:> Returns passed object but if chain method is used <END_TASK> <USER_TASK:> Description: def obj(self): """ Returns passed object but if chain method is used returns the last processed result """
if self._wrapped is not self.Null: return self._wrapped else: return self.object
<SYSTEM_TASK:> Returns result but ig chain method is used <END_TASK> <USER_TASK:> Description: def _wrap(self, ret): """ Returns result but ig chain method is used returns the object itself so we can chain """
if self.chained: self._wrapped = ret return self else: return ret
<SYSTEM_TASK:> Pitty attempt to convert itertools result into a real object <END_TASK> <USER_TASK:> Description: def _toOriginal(self, val): """ Pitty attempt to convert itertools result into a real object """
if self._clean.isTuple(): return tuple(val) elif self._clean.isList(): return list(val) elif self._clean.isDict(): return dict(val) else: return val
<SYSTEM_TASK:> Return the results of applying the iterator to each element. <END_TASK> <USER_TASK:> Description: def map(self, func): """ Return the results of applying the iterator to each element. """
ns = self.Namespace() ns.results = [] def by(value, index, list, *args): ns.results.append(func(value, index, list)) _(self.obj).each(by) return self._wrap(ns.results)
<SYSTEM_TASK:> The right-associative version of reduce, also known as `foldr`. <END_TASK> <USER_TASK:> Description: def reduceRight(self, func): """ The right-associative version of reduce, also known as `foldr`. """
#foldr = lambda f, i: lambda s: reduce(f, s, i) x = self.obj[:] x.reverse() return self._wrap(functools.reduce(func, x))
<SYSTEM_TASK:> Return the first value which passes a truth test. <END_TASK> <USER_TASK:> Description: def find(self, func): """ Return the first value which passes a truth test. Aliased as `detect`. """
self.ftmp = None def test(value, index, list): if func(value, index, list) is True: self.ftmp = value return True self._clean.any(test) return self._wrap(self.ftmp)
<SYSTEM_TASK:> Return all the elements that pass a truth test. <END_TASK> <USER_TASK:> Description: def filter(self, func): """ Return all the elements that pass a truth test. """
return self._wrap(list(filter(func, self.obj)))
<SYSTEM_TASK:> Return all the elements for which a truth test fails. <END_TASK> <USER_TASK:> Description: def reject(self, func): """ Return all the elements for which a truth test fails. """
return self._wrap(list(filter(lambda val: not func(val), self.obj)))
<SYSTEM_TASK:> Determine whether all of the elements match a truth test. <END_TASK> <USER_TASK:> Description: def all(self, func=None): """ Determine whether all of the elements match a truth test. """
if func is None: func = lambda x, *args: x self.altmp = True def testEach(value, index, *args): if func(value, index, *args) is False: self.altmp = False self._clean.each(testEach) return self._wrap(self.altmp)
<SYSTEM_TASK:> Determine if at least one element in the object <END_TASK> <USER_TASK:> Description: def any(self, func=None): """ Determine if at least one element in the object matches a truth test. """
if func is None: func = lambda x, *args: x self.antmp = False def testEach(value, index, *args): if func(value, index, *args) is True: self.antmp = True return "breaker" self._clean.each(testEach) return self._wrap(self.antmp)
<SYSTEM_TASK:> Determine if a given value is included in the <END_TASK> <USER_TASK:> Description: def include(self, target): """ Determine if a given value is included in the array or object using `is`. """
if self._clean.isDict(): return self._wrap(target in self.obj.values()) else: return self._wrap(target in self.obj)
<SYSTEM_TASK:> Sort the object's values by a criterion produced by an iterator. <END_TASK> <USER_TASK:> Description: def sortBy(self, val=None): """ Sort the object's values by a criterion produced by an iterator. """
if val is not None: if _(val).isString(): return self._wrap(sorted(self.obj, key=lambda x, *args: x.get(val))) else: return self._wrap(sorted(self.obj, key=val)) else: return self._wrap(sorted(self.obj))
<SYSTEM_TASK:> An internal function used for aggregate "group by" operations. <END_TASK> <USER_TASK:> Description: def _group(self, obj, val, behavior): """ An internal function used for aggregate "group by" operations. """
ns = self.Namespace() ns.result = {} iterator = self._lookupIterator(val) def e(value, index, *args): key = iterator(value, index) behavior(ns.result, key, value) _.each(obj, e) if len(ns.result) == 1: try: return ns.result[0] except KeyError: return list(ns.result.values())[0] return ns.result
<SYSTEM_TASK:> Groups the object's values by a criterion. Pass either a string <END_TASK> <USER_TASK:> Description: def groupBy(self, val): """ Groups the object's values by a criterion. Pass either a string attribute to group by, or a function that returns the criterion. """
def by(result, key, value): if key not in result: result[key] = [] result[key].append(value) res = self._group(self.obj, val, by) return self._wrap(res)
<SYSTEM_TASK:> Indexes the object's values by a criterion, similar to <END_TASK> <USER_TASK:> Description: def indexBy(self, val=None): """ Indexes the object's values by a criterion, similar to `groupBy`, but for when you know that your index values will be unique. """
if val is None: val = lambda *args: args[0] def by(result, key, value): result[key] = value res = self._group(self.obj, val, by) return self._wrap(res)
<SYSTEM_TASK:> Counts instances of an object that group by a certain criterion. Pass <END_TASK> <USER_TASK:> Description: def countBy(self, val): """ Counts instances of an object that group by a certain criterion. Pass either a string attribute to count by, or a function that returns the criterion. """
def by(result, key, value): if key not in result: result[key] = 0 result[key] += 1 res = self._group(self.obj, val, by) return self._wrap(res)
<SYSTEM_TASK:> Use a comparator function to figure out the smallest index at which <END_TASK> <USER_TASK:> Description: def sortedIndex(self, obj, iterator=lambda x: x): """ Use a comparator function to figure out the smallest index at which an object should be inserted so as to maintain order. Uses binary search. """
array = self.obj value = iterator(obj) low = 0 high = len(array) while low < high: mid = (low + high) >> 1 if iterator(array[mid]) < value: low = mid + 1 else: high = mid return self._wrap(low)
<SYSTEM_TASK:> Return a completely flattened version of an array. <END_TASK> <USER_TASK:> Description: def flatten(self, shallow=None): """ Return a completely flattened version of an array. """
return self._wrap(self._flatten(self.obj, shallow))
<SYSTEM_TASK:> Produce a duplicate-free version of the array. If the array has already <END_TASK> <USER_TASK:> Description: def uniq(self, isSorted=False, iterator=None): """ Produce a duplicate-free version of the array. If the array has already been sorted, you have the option of using a faster algorithm. Aliased as `unique`. """
ns = self.Namespace() ns.results = [] ns.array = self.obj initial = self.obj if iterator is not None: initial = _(ns.array).map(iterator) def by(memo, value, index): if ((_.last(memo) != value or not len(memo)) if isSorted else not _.include(memo, value)): memo.append(value) ns.results.append(ns.array[index]) return memo ret = _.reduce(initial, by) return self._wrap(ret)
<SYSTEM_TASK:> Produce an array that contains every item shared between all the <END_TASK> <USER_TASK:> Description: def intersection(self, *args): """ Produce an array that contains every item shared between all the passed-in arrays. """
if type(self.obj[0]) is int: a = self.obj else: a = tuple(self.obj[0]) setobj = set(a) for i, v in enumerate(args): setobj = setobj & set(args[i]) return self._wrap(list(setobj))
<SYSTEM_TASK:> Take the difference between one array and a number of other arrays. <END_TASK> <USER_TASK:> Description: def difference(self, *args): """ Take the difference between one array and a number of other arrays. Only the elements present in just the first array will remain. """
setobj = set(self.obj) for i, v in enumerate(args): setobj = setobj - set(args[i]) return self._wrap(self._clean._toOriginal(setobj))
<SYSTEM_TASK:> Return the position of the first occurrence of an <END_TASK> <USER_TASK:> Description: def indexOf(self, item, isSorted=False): """ Return the position of the first occurrence of an item in an array, or -1 if the item is not included in the array. """
array = self.obj ret = -1 if not (self._clean.isList() or self._clean.isTuple()): return self._wrap(-1) if isSorted: i = _.sortedIndex(array, item) ret = i if array[i] is item else -1 else: i = 0 l = len(array) while i < l: if array[i] is item: return self._wrap(i) i += 1 return self._wrap(ret)
<SYSTEM_TASK:> Return the position of the last occurrence of an <END_TASK> <USER_TASK:> Description: def lastIndexOf(self, item): """ Return the position of the last occurrence of an item in an array, or -1 if the item is not included in the array. """
array = self.obj i = len(array) - 1 if not (self._clean.isList() or self._clean.isTuple()): return self._wrap(-1) while i > -1: if array[i] is item: return self._wrap(i) i -= 1 return self._wrap(-1)
<SYSTEM_TASK:> Generate an integer Array containing an arithmetic progression. <END_TASK> <USER_TASK:> Description: def range(self, *args): """ Generate an integer Array containing an arithmetic progression. """
args = list(args) args.insert(0, self.obj) return self._wrap(range(*args))
<SYSTEM_TASK:> Partially apply a function by creating a version that has had some of <END_TASK> <USER_TASK:> Description: def partial(self, *args): """ Partially apply a function by creating a version that has had some of its arguments pre-filled, without changing its dynamic `this` context. """
def part(*args2): args3 = args + args2 return self.obj(*args3) return self._wrap(part)
<SYSTEM_TASK:> Memoize an expensive function by storing its results. <END_TASK> <USER_TASK:> Description: def memoize(self, hasher=None): """ Memoize an expensive function by storing its results. """
ns = self.Namespace() ns.memo = {} if hasher is None: hasher = lambda x: x def memoized(*args, **kwargs): key = hasher(*args) if key not in ns.memo: ns.memo[key] = self.obj(*args, **kwargs) return ns.memo[key] return self._wrap(memoized)
<SYSTEM_TASK:> Delays a function for the given number of milliseconds, and then calls <END_TASK> <USER_TASK:> Description: def delay(self, wait, *args): """ Delays a function for the given number of milliseconds, and then calls it with the arguments supplied. """
def call_it(): self.obj(*args) t = Timer((float(wait) / float(1000)), call_it) t.start() return self._wrap(self.obj)
<SYSTEM_TASK:> Returns a function, that, when invoked, will only be triggered <END_TASK> <USER_TASK:> Description: def throttle(self, wait): """ Returns a function, that, when invoked, will only be triggered at most once during a given window of time. """
ns = self.Namespace() ns.timeout = None ns.throttling = None ns.more = None ns.result = None def done(): ns.more = ns.throttling = False whenDone = _.debounce(done, wait) wait = (float(wait) / float(1000)) def throttled(*args, **kwargs): def later(): ns.timeout = None if ns.more: self.obj(*args, **kwargs) whenDone() if not ns.timeout: ns.timeout = Timer(wait, later) ns.timeout.start() if ns.throttling: ns.more = True else: ns.throttling = True ns.result = self.obj(*args, **kwargs) whenDone() return ns.result return self._wrap(throttled)
<SYSTEM_TASK:> Returns a function, that, as long as it continues to be invoked, <END_TASK> <USER_TASK:> Description: def debounce(self, wait, immediate=None): """ Returns a function, that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. If `immediate` is passed, trigger the function on the leading edge, instead of the trailing. """
wait = (float(wait) / float(1000)) def debounced(*args, **kwargs): def call_it(): self.obj(*args, **kwargs) try: debounced.t.cancel() except(AttributeError): pass debounced.t = Timer(wait, call_it) debounced.t.start() return self._wrap(debounced)
<SYSTEM_TASK:> Returns a function that will be executed at most one time, <END_TASK> <USER_TASK:> Description: def once(self): """ Returns a function that will be executed at most one time, no matter how often you call it. Useful for lazy initialization. """
ns = self.Namespace() ns.memo = None ns.run = False def work_once(*args, **kwargs): if ns.run is False: ns.memo = self.obj(*args, **kwargs) ns.run = True return ns.memo return self._wrap(work_once)