INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Notify other windows that the environment has changed (following http://support.microsoft.com/kb/104011).
def notify(class_): """ Notify other windows that the environment has changed (following http://support.microsoft.com/kb/104011). """ # TODO: Implement Microsoft UIPI (User Interface Privilege Isolation) to # elevate privilege to system level so the system gets this notification # for now, this must be r...
Windows Platform SDK GetTimeZoneInformation
def current(class_): "Windows Platform SDK GetTimeZoneInformation" tzi = class_() kernel32 = ctypes.windll.kernel32 getter = kernel32.GetTimeZoneInformation getter = getattr(kernel32, 'GetDynamicTimeZoneInformation', getter) code = getter(ctypes.byref(tzi)) return code, tzi
Return a map that for a given year will return the correct Info
def dynamic_info(self): "Return a map that for a given year will return the correct Info" if self.key_name: dyn_key = self.get_key().subkey('Dynamic DST') del dyn_key['FirstEntry'] del dyn_key['LastEntry'] years = map(int, dyn_key.keys()) values = map(Info, dyn_key.values()) # create a range mappi...
Takes a SYSTEMTIME object, such as retrieved from a TIME_ZONE_INFORMATION structure or call to GetTimeZoneInformation and interprets it based on the given year to identify the actual day. This method is necessary because the SYSTEMTIME structure refers to a day by its day of the week and week of the month ...
def _locate_day(year, cutoff): """ Takes a SYSTEMTIME object, such as retrieved from a TIME_ZONE_INFORMATION structure or call to GetTimeZoneInformation and interprets it based on the given year to identify the actual day. This method is necessary because the SYSTEMTIME structure refers to a day by its ...
Return a url matcher that will stop the redirect middleware and force Django to continue with regular URL matching. For use when you have a URL pattern you want to serve, and a broad catch-all pattern you want to redirect. :param pattern: regex URL patter that will definitely not redirect. :param locale...
def no_redirect(pattern, locale_prefix=True, re_flags=None): """ Return a url matcher that will stop the redirect middleware and force Django to continue with regular URL matching. For use when you have a URL pattern you want to serve, and a broad catch-all pattern you want to redirect. :param patte...
Return a url matcher suited for urlpatterns. pattern: the regex against which to match the requested URL. to: either a url name that `reverse` will find, a url that will simply be returned, or a function that will be given the request and url captures, and return the destination. permanent:...
def redirect(pattern, to, permanent=True, locale_prefix=True, anchor=None, name=None, query=None, vary=None, cache_timeout=12, decorators=None, re_flags=None, to_args=None, to_kwargs=None, prepend_locale=True, merge_query=False): """ Return a url matcher suited for urlpatterns. pa...
r""" Find a path from start to target where target is relative to start. >>> orig_wd = os.getcwd() >>> os.chdir('c:\\windows') # so we know what the working directory is >>> findpath('d:\\') 'd:\\' >>> findpath('d:\\', 'c:\\windows') 'd:\\' >>> findpath('\\bar', 'd:\\') 'd:\\bar' >>> find...
def findpath(target, start=os.path.curdir): r""" Find a path from start to target where target is relative to start. >>> orig_wd = os.getcwd() >>> os.chdir('c:\\windows') # so we know what the working directory is >>> findpath('d:\\') 'd:\\' >>> findpath('d:\\', 'c:\\windows') 'd:\\' >>> find...
Retrieve the size of the buffer needed by calling the method with a null pointer and length of zero. This should trigger an insufficient buffer error and return the size needed for the buffer.
def __get_table_size(self): """ Retrieve the size of the buffer needed by calling the method with a null pointer and length of zero. This should trigger an insufficient buffer error and return the size needed for the buffer. """ length = ctypes.wintypes.DWORD() res = self.method(None, length, False) i...
Get the table
def get_table(self): """ Get the table """ buffer_length = self.__get_table_size() returned_buffer_length = ctypes.wintypes.DWORD(buffer_length) buffer = ctypes.create_string_buffer(buffer_length) pointer_type = ctypes.POINTER(self.structure) table_p = ctypes.cast(buffer, pointer_type) res = self.meth...
Using the table structure, return the array of entries based on the table size.
def entries(self): """ Using the table structure, return the array of entries based on the table size. """ table = self.get_table() entries_array = self.row_structure * table.num_entries pointer_type = ctypes.POINTER(entries_array) return ctypes.cast(table.entries, pointer_type).contents
Set up owncloud. Package 'owncloud' pulls package 'mysql' which asks for a password.
def owncloud(): '''Set up owncloud. Package 'owncloud' pulls package 'mysql' which asks for a password. ''' hostname = re.sub(r'^[^@]+@', '', env.host) # without username if any sitename = query_input( question='\nEnter site-name of Your Owncloud web service', ...
Set up an F-Droid App Repo. More infos: * https://f-droid.org/wiki/page/Setup_an_FDroid_App_Repo * https://f-droid.org/wiki/page/Installing_the_Server_and_Repo_Tools
def fdroid(): '''Set up an F-Droid App Repo. More infos: * https://f-droid.org/wiki/page/Setup_an_FDroid_App_Repo * https://f-droid.org/wiki/page/Installing_the_Server_and_Repo_Tools ''' hostname = re.sub(r'^[^@]+@', '', env.host) # without username if any sitename = query_input( ...
Install and configure dispmanx_vnc server on osmc (raspberry pi). More Infos: * https://github.com/patrikolausson/dispmanx_vnc * https://discourse.osmc.tv/t/howto-install-a-vnc-server-on-the-raspberry-pi/1517 * tightvnc: * http://raspberry.tips/raspberrypi-einsteiger/raspberry-pi-einsteiger-g...
def vnc_raspi_osmc(): '''Install and configure dispmanx_vnc server on osmc (raspberry pi). More Infos: * https://github.com/patrikolausson/dispmanx_vnc * https://discourse.osmc.tv/t/howto-install-a-vnc-server-on-the-raspberry-pi/1517 * tightvnc: * http://raspberry.tips/raspberrypi-einstei...
Install and start a Logitech Media Server (lms). More infos: * http://wiki.slimdevices.com/index.php/Logitech_Media_Server * http://wiki.slimdevices.com/index.php/DebianPackage * http://www.mysqueezebox.com/download * XSqueeze on Kodi: * http://kodi.wiki/view/Add-on:XSqueeze * htt...
def lms(): '''Install and start a Logitech Media Server (lms). More infos: * http://wiki.slimdevices.com/index.php/Logitech_Media_Server * http://wiki.slimdevices.com/index.php/DebianPackage * http://www.mysqueezebox.com/download * XSqueeze on Kodi: * http://kodi.wiki/view/Add-on:XSq...
Install smb server samba and create a share (common read-write-access). More infos: * https://wiki.ubuntuusers.de/Samba%20Server/
def samba(): '''Install smb server samba and create a share (common read-write-access). More infos: * https://wiki.ubuntuusers.de/Samba%20Server/ ''' username = env.user install_packages(['samba']) run(flo('sudo smbpasswd -a {username}')) path = '$HOME/shared' sharename = 'shared'...
scalar : DOUBLEQUOTE_START SCALAR DOUBLEQUOTE_END
def p_scalar__doublequote(self, p): """ scalar : DOUBLEQUOTE_START SCALAR DOUBLEQUOTE_END """ scalar = re.sub('\n\s+', ' ', str(p[2])) p[0] = Str(scalar.replace('\\"', '"'))
scalar : B_LITERAL_START scalar_group B_LITERAL_END
def p_scalar__literal(self, p): """ scalar : B_LITERAL_START scalar_group B_LITERAL_END """ scalar_group = ''.join(p[2]) p[0] = ScalarDispatch('%s\n' % dedent(scalar_group).replace('\n\n\n', '\n'), cast='str')
scalar : B_FOLD_START scalar_group B_FOLD_END
def p_scalar__folded(self, p): """ scalar : B_FOLD_START scalar_group B_FOLD_END """ scalar_group = ''.join(p[2]) folded_scalar = fold(dedent(scalar_group)).rstrip() p[0] = ScalarDispatch('%s\n' % folded_scalar, cast='str')
scalar : INDENT scalar_group DEDENT
def p_scalar__indented_flow(self, p): """ scalar : INDENT scalar_group DEDENT """ scalar_group = '\n'.join(p[2]) folded_scalar = fold(dedent(scalar_group)) p[0] = ScalarDispatch(folded_scalar, cast='str')
scalar : scalar INDENT SCALAR DEDENT
def p_scalar__string_indented_multi_line(self, p): """ scalar : scalar INDENT SCALAR DEDENT """ scalar = '\n'.join([p[1].value, p[3]]) p[0] = ScalarDispatch(fold(scalar), cast='str')
scalar_group : SCALAR | scalar_group SCALAR
def p_scalar_group(self, p): """ scalar_group : SCALAR | scalar_group SCALAR """ if len(p) == 2: p[0] = (str(p[1]),) if len(p) == 3: p[0] = p[1] + (str(p[2]),) if len(p) == 4: p[0] = p[1] + (str(p[3]),)
Add 'orphan' to metadata for partials :type app: sphinx.application.Sphinx :type doctree: docutils.nodes.document
def doctree_read_handler(app, doctree): """ Add 'orphan' to metadata for partials :type app: sphinx.application.Sphinx :type doctree: docutils.nodes.document """ # noinspection PyProtectedMember docname = sys._getframe(2).f_locals['docname'] if docname.startswith('_partial'): ap...
Skip un parseable functions. :type app: sphinx.application.Sphinx :param str what: the type of the object which the docstring belongs to (one of "module", "class", "exception", "function", "method", "attribute") :param str name: the fully qualified name of the object :param type obj: the object...
def autodoc_skip_member_handler(app, what, name, obj, skip, options): """ Skip un parseable functions. :type app: sphinx.application.Sphinx :param str what: the type of the object which the docstring belongs to (one of "module", "class", "exception", "function", "method", "attribute") :para...
Wraps a try / except and a check for self.filename around ConfigParser as it talks to the configuration file. Also, checks for existence of configuration file so this won't execute (and fail) when no configuration file is provided (e.g., running in coupled mode with CSDMS entirely with getters and set...
def configGet(self, vartype, category, name, optional=False, specialReturnMessage=None): """ Wraps a try / except and a check for self.filename around ConfigParser as it talks to the configuration file. Also, checks for existence of configuration file so this won't execute (and fail) when no config...
Returns the great circle distance between two points. Useful when using the SAS_NG solution in lat/lon coordinates Modified from http://www.johndcook.com/blog/python_longitude_latitude/ It should be able to take numpy arrays.
def greatCircleDistance(self, lat1, long1, lat2, long2, radius): """ Returns the great circle distance between two points. Useful when using the SAS_NG solution in lat/lon coordinates Modified from http://www.johndcook.com/blog/python_longitude_latitude/ It should be able to take numpy arrays. "...
This is experimental code that could be used in the spatialDomainNoGrid section to build a grid of points on which to generate the solution. However, the current development plan (as of 27 Jan 2015) is to have the end user supply the list of points where they want a solution (and/or for it to be provi...
def define_points_grid(self): """ This is experimental code that could be used in the spatialDomainNoGrid section to build a grid of points on which to generate the solution. However, the current development plan (as of 27 Jan 2015) is to have the end user supply the list of points where they want ...
A special function to replate a variable name that is a string file path with the loaded file. var is a string on input output is a numpy array or a None-type object (success vs. failure)
def loadFile(self, var, close_on_fail = True): """ A special function to replate a variable name that is a string file path with the loaded file. var is a string on input output is a numpy array or a None-type object (success vs. failure) """ out = None try: # First see if it is a ...
Plot if you want to - for troubleshooting - 1 figure
def surfplot(self, z, titletext): """ Plot if you want to - for troubleshooting - 1 figure """ if self.latlon: plt.imshow(z, extent=(0, self.dx*z.shape[0], self.dy*z.shape[1], 0)) #,interpolation='nearest' plt.xlabel('longitude [deg E]', fontsize=12, fontweight='bold') plt.ylabel('lati...
Plot multiple subplot figure for 2D array
def twoSurfplots(self): """ Plot multiple subplot figure for 2D array """ # Could more elegantly just call surfplot twice # And also could include xyzinterp as an option inside surfplot. # Noted here in case anyone wants to take that on in the future... plt.subplot(211) plt.title('Load ...
Interpolates and plots ungridded model outputs from SAS_NG solution
def xyzinterp(self, x, y, z, titletext): """ Interpolates and plots ungridded model outputs from SAS_NG solution """ # Help from http://wiki.scipy.org/Cookbook/Matplotlib/Gridding_irregularly_spaced_data if self.Verbose: print("Starting to interpolate grid for plotting -- can be a slow pr...
Outputs a grid of deflections if an output directory is defined in the configuration file If the filename given in the configuration file ends in ".npy", then a binary numpy grid will be exported. Otherwise, an ASCII grid will be exported.
def outputDeflections(self): """ Outputs a grid of deflections if an output directory is defined in the configuration file If the filename given in the configuration file ends in ".npy", then a binary numpy grid will be exported. Otherwise, an ASCII grid will be exported. """ ...
Make sure that q0 and coefficient array are the right size compared to each other (for finite difference if loading a pre-build coefficient array). Otherwise, exit.
def coeffArraySizeCheck(self): """ Make sure that q0 and coefficient array are the right size compared to each other (for finite difference if loading a pre-build coefficient array). Otherwise, exit. """ if prod(self.coeff_matrix.shape) != long(prod(np.array(self.qs.shape,dtype=int64)+2)**2): ...
Checks that Te and q0 array sizes are compatible For finite difference solution.
def TeArraySizeCheck(self): """ Checks that Te and q0 array sizes are compatible For finite difference solution. """ # Only if they are both defined and are arrays # Both being arrays is a possible bug in this check routine that I have # intentionally introduced if type(self.Te) == np.n...
Set-up for the finite difference solution method
def FD(self): """ Set-up for the finite difference solution method """ if self.Verbose: print("Finite Difference Solution Technique") # Used to check for coeff_matrix here, but now doing so in self.bc_check() # called by f1d and f2d at the start # # Define a stress-based qs = q0 ...
Set-up for the rectangularly-gridded superposition of analytical solutions method for solving flexure
def SAS(self): """ Set-up for the rectangularly-gridded superposition of analytical solutions method for solving flexure """ if self.x is None: self.x = np.arange(self.dx/2., self.dx * self.qs.shape[0], self.dx) if self.filename: # Define the (scalar) elastic thickness self.Te...
Set-up for the ungridded superposition of analytical solutions method for solving flexure
def SAS_NG(self): """ Set-up for the ungridded superposition of analytical solutions method for solving flexure """ if self.filename: # Define the (scalar) elastic thickness self.Te = self.configGet("float", "input", "ElasticThickness") # See if it wants to be run in lat/lon ...
Merges MROs in *sequences* to a single MRO using the C3 algorithm. Adapted from http://www.python.org/download/releases/2.3/mro/.
def _c3_merge(sequences): # noqa """Merges MROs in *sequences* to a single MRO using the C3 algorithm. Adapted from http://www.python.org/download/releases/2.3/mro/. """ result = [] while True: sequences = [s for s in sequences if s] # purge empty sequences if not sequences: ...
Computes the method resolution order using extended C3 linearization. If no *abcs* are given, the algorithm works exactly like the built-in C3 linearization used for method resolution. If given, *abcs* is a list of abstract base classes that should be inserted into the resulting MRO. Unrelated ABCs ar...
def _c3_mro(cls, abcs=None): """Computes the method resolution order using extended C3 linearization. If no *abcs* are given, the algorithm works exactly like the built-in C3 linearization used for method resolution. If given, *abcs* is a list of abstract base classes that should be inserted into ...
Calculates the method resolution order for a given class *cls*. Includes relevant abstract base classes (with their respective bases) from the *types* iterable. Uses a modified C3 linearization algorithm.
def _compose_mro(cls, types): # noqa """Calculates the method resolution order for a given class *cls*. Includes relevant abstract base classes (with their respective bases) from the *types* iterable. Uses a modified C3 linearization algorithm. """ bases = set(cls.__mro__) # Remove entries w...
Returns the best matching implementation from *registry* for type *cls*. Where there is no registered implementation for a specific type, its method resolution order is used to find a more generic implementation. Note: if *registry* does not contain an implementation for the base *object* type, this f...
def _find_impl(cls, registry): """Returns the best matching implementation from *registry* for type *cls*. Where there is no registered implementation for a specific type, its method resolution order is used to find a more generic implementation. Note: if *registry* does not contain an implementation ...
Single-dispatch generic function decorator. Transforms a function into a generic function, which can have different behaviours depending upon the type of its first argument. The decorated function acts as the default implementation, and additional implementations can be registered using the register() ...
def singledispatch(function): # noqa """Single-dispatch generic function decorator. Transforms a function into a generic function, which can have different behaviours depending upon the type of its first argument. The decorated function acts as the default implementation, and additional implementa...
Modeled after http://msdn.microsoft.com /en-us/library/ms649016%28VS.85%29.aspx #_win32_Copying_Information_to_the_Clipboard
def SetClipboardData(type, content): """ Modeled after http://msdn.microsoft.com /en-us/library/ms649016%28VS.85%29.aspx #_win32_Copying_Information_to_the_Clipboard """ allocators = { clipboard.CF_TEXT: ctypes.create_string_buffer, clipboard.CF_UNICODETEXT: ctypes.create_unicode_buffer, clipboard.CF_HTML: ...
The main (cli) interface for the pylint runner.
def main(output=None, error=None, verbose=False): """ The main (cli) interface for the pylint runner. """ runner = Runner(args=["--verbose"] if verbose is not False else None) runner.run(output, error)
Parses any supplied command-line args and provides help text.
def _parse_args(self, args): """Parses any supplied command-line args and provides help text. """ parser = ArgumentParser(description="Runs pylint recursively on a directory") parser.add_argument( "-v", "--verbose", dest="verbose", action="store_...
Parse the ignores setting from the pylintrc file if available.
def _parse_ignores(self): """ Parse the ignores setting from the pylintrc file if available. """ error_message = ( colorama.Fore.RED + "{} does not appear to be a valid pylintrc file".format(self.rcfile) + colorama.Fore.RESET ) if not os.path.isfile(...
Recursively walk through a directory and get all python files and then walk through any potential directories that are found off current directory, so long as not within self.IGNORE_FOLDERS :return: all python files that were found off current_dir
def get_files_from_dir(self, current_dir): """ Recursively walk through a directory and get all python files and then walk through any potential directories that are found off current directory, so long as not within self.IGNORE_FOLDERS :return: all python files that were found o...
Runs pylint on all python files in the current directory
def run(self, output=None, error=None): """ Runs pylint on all python files in the current directory """ pylint_output = output if output is not None else sys.stdout pylint_error = error if error is not None else sys.stderr savedout, savederr = sys.__stdout__, sys.__stderr__ sys...
Decorator, type check production rule output
def strict(*types): """Decorator, type check production rule output""" def decorate(func): @wraps(func) def wrapper(self, p): func(self, p) if not isinstance(p[0], types): raise YAMLStrictTypeError(p[0], types, func) wrapper.co_firstlineno = func...
Get cursor position, based on previous newline
def find_column(t): """Get cursor position, based on previous newline""" pos = t.lexer.lexpos data = t.lexer.lexdata last_cr = data.rfind('\n', 0, pos) if last_cr < 0: last_cr = -1 column = pos - last_cr return column
:param payload: a key/value object containing the scimeta you want to store e.g. {"weather": "sunny", "temperature": "80C" } :return: empty (200 status code)
def custom(self, payload): """ :param payload: a key/value object containing the scimeta you want to store e.g. {"weather": "sunny", "temperature": "80C" } :return: empty (200 status code) """ url = "{url_base}/resource/{pid}/scimeta/...
:param payload: a key/value object containing the scimeta you want to store e.g. {"weather": "sunny", "temperature": "80C" } :return: empty (200 status code)
def get(self): """ :param payload: a key/value object containing the scimeta you want to store e.g. {"weather": "sunny", "temperature": "80C" } :return: empty (200 status code) """ url = "{url_base}/resource/{pid}/scimeta/custom/".for...
:return: array of file objects (200 status code)
def all(self): """ :return: array of file objects (200 status code) """ url = "{url_base}/resource/{pid}/files/".format(url_base=self.hs.url_base, pid=self.pid) r = self.hs._request('GET', url) ...
:params: title: string keywords: array extra_metadata: array temporal_coverage: coverage object spatial_coverage: coverage object :return: file metadata object (200 status code)
def metadata(self, file_path, params=None): """ :params: title: string keywords: array extra_metadata: array temporal_coverage: coverage object spatial_coverage: coverage object :return: file metadata object (200 ...
Unzips a file :param payload: zip_with_rel_path: string remove_original_zip: boolean :return: (object) unzipped_path: string
def unzip(self, payload): """ Unzips a file :param payload: zip_with_rel_path: string remove_original_zip: boolean :return: (object) unzipped_path: string """ zip_with_rel_path = payload.pop('zip_with_rel_path') ur...
Sets a file to a specific HydroShare file type (e.g. NetCDF, GeoRaster, GeoFeature etc) :param payload: file_path: string (relative path of the file to be set to a specific file type) hs_file_type: string (one of the supported files types: SingleFile, NetCDF, GeoRaster, ...
def set_file_type(self, payload): """ Sets a file to a specific HydroShare file type (e.g. NetCDF, GeoRaster, GeoFeature etc) :param payload: file_path: string (relative path of the file to be set to a specific file type) hs_file_type: string (one of the supported ...
Set a single flag on a resource. :param payload: t: can be one of make_public, make_private, make_shareable, make_not_shareable, make_discoverable, make_not_discoverable :return: empty but with 202 status_code
def flag(self, payload): """Set a single flag on a resource. :param payload: t: can be one of make_public, make_private, make_shareable, make_not_shareable, make_discoverable, make_not_discoverable :return: empty but with 202 status_code """ ...
Upload a file to a hydroshare resource. :param payload: file: File object to upload to server folder: folder path to upload the file to :return: json object resource_id: string resource id, file_name: string name of file
def files(self, payload): """Upload a file to a hydroshare resource. :param payload: file: File object to upload to server folder: folder path to upload the file to :return: json object resource_id: string resource id, file_name: string na...
Pass through helper function for flag function.
def public(self, boolean): """Pass through helper function for flag function.""" if(boolean): r = self.flag({ "flag": "make_public" }) else: r = self.flag({ "flag": "make_private" }) return r
Pass through helper function for flag function.
def discoverable(self, boolean): """Pass through helper function for flag function.""" if(boolean): r = self.flag({ "flag": "make_discoverable" }) else: r = self.flag({ "flag": "make_not_discoverable" }) ...
Pass through helper function for flag function.
def shareable(self, boolean): """Pass through helper function for flag function.""" if(boolean): r = self.flag({ "flag": "make_shareable" }) else: r = self.flag({ "flag": "make_not_shareable" }) r...
Context that prevents the computer from going to sleep.
def no_sleep(): """ Context that prevents the computer from going to sleep. """ mode = power.ES.continuous | power.ES.system_required handle_nonzero_success(power.SetThreadExecutionState(mode)) try: yield finally: handle_nonzero_success(power.SetThreadExecutionState(power.ES.continuous))
Install, update and set up selfoss. This selfoss installation uses sqlite (selfoss-default), php5-fpm and nginx. The connection is https-only and secured by a letsencrypt certificate. This certificate must be created separately with task setup.server_letsencrypt. More infos: https://selfoss.ad...
def selfoss(reset_password=False): '''Install, update and set up selfoss. This selfoss installation uses sqlite (selfoss-default), php5-fpm and nginx. The connection is https-only and secured by a letsencrypt certificate. This certificate must be created separately with task setup.server_letsencrypt....
get file path
def get_cache_path(filename): """ get file path """ cwd = os.path.dirname(os.path.realpath(__file__)) return os.path.join(cwd, filename)
parameter: file_path - path to cache file return: data after parsing json file
def read(filename='cache'): """ parameter: file_path - path to cache file return: data after parsing json file""" cache_path = get_cache_path(filename) if not os.path.exists(cache_path) or os.stat(cache_path).st_size == 0: return None with open(cache_path, 'r') as file: return json.load(file)
write data to cache file parameters: cache_path - path to cache file content - a data structure to save into cache file
def write(content, filename='cache'): """ write data to cache file parameters: cache_path - path to cache file content - a data structure to save into cache file""" cache_path = get_cache_path(filename) with open(cache_path, 'w') as file: if content is not None: json.dump(content, file, indent=3, sort_keys...
Return a SECURITY_ATTRIBUTES structure with the SID set to the specified user (uses current user if none is specified).
def get_security_attributes_for_user(user=None): """ Return a SECURITY_ATTRIBUTES structure with the SID set to the specified user (uses current user if none is specified). """ if user is None: user = get_current_user() assert isinstance(user, security.TOKEN_USER), ( "user must be TOKEN_USER instance") SD ...
Get the current process token
def get_process_token(): """ Get the current process token """ token = wintypes.HANDLE() res = process.OpenProcessToken( process.GetCurrentProcess(), process.TOKEN_ALL_ACCESS, token) if not res > 0: raise RuntimeError("Couldn't get process token") return token
Get the LUID for the SeCreateSymbolicLinkPrivilege
def get_symlink_luid(): """ Get the LUID for the SeCreateSymbolicLinkPrivilege """ symlink_luid = privilege.LUID() res = privilege.LookupPrivilegeValue( None, "SeCreateSymbolicLinkPrivilege", symlink_luid) if not res > 0: raise RuntimeError("Couldn't lookup privilege value") return symlink_luid
Get all privileges associated with the current process.
def get_privilege_information(): """ Get all privileges associated with the current process. """ # first call with zero length to determine what size buffer we need return_length = wintypes.DWORD() params = [ get_process_token(), privilege.TOKEN_INFORMATION_CLASS.TokenPrivileges, None, 0, return_length...
Try to assign the symlink privilege to the current process token. Return True if the assignment is successful.
def enable_symlink_privilege(): """ Try to assign the symlink privilege to the current process token. Return True if the assignment is successful. """ # create a space in memory for a TOKEN_PRIVILEGES structure # with one element size = ctypes.sizeof(privilege.TOKEN_PRIVILEGES) size += ctypes.sizeof(privilege....
Grant the 'create symlink' privilege to who. Based on http://support.microsoft.com/kb/132958
def grant_symlink_privilege(who, machine=''): """ Grant the 'create symlink' privilege to who. Based on http://support.microsoft.com/kb/132958 """ flags = security.POLICY_CREATE_ACCOUNT | security.POLICY_LOOKUP_NAMES policy = OpenPolicy(machine, flags) return policy
Return a base-module (e.g. 'theno') or a sub-module (e.g. 'theno.service.raccoon') from the dict addon_modules given by param 'module_name'. If the highest module (e.g. 'theno') not exists, an empty module will be created. This will be continued recursively until the lowest sub-module exists which...
def get_or_create_module_r(module_name, base_module=None): '''Return a base-module (e.g. 'theno') or a sub-module (e.g. 'theno.service.raccoon') from the dict addon_modules given by param 'module_name'. If the highest module (e.g. 'theno') not exists, an empty module will be created. This will be ...
Recursively iterate through 'package_module' and add every fabric task to the 'addon_module' keeping the task hierarchy. Args: addon_module(types.ModuleType) package_module(types.ModuleType) package_name(str): Required, to avoid redundant addition of tasks Return: None
def add_tasks_r(addon_module, package_module, package_name): '''Recursively iterate through 'package_module' and add every fabric task to the 'addon_module' keeping the task hierarchy. Args: addon_module(types.ModuleType) package_module(types.ModuleType) package_name(str): Required,...
Load an fabsetup addon given by 'package_name' and hook it in the base task namespace 'username'. Args: username(str) package_name(str) _globals(dict): the globals() namespace of the fabric script. Return: None
def load_addon(username, package_name, _globals): '''Load an fabsetup addon given by 'package_name' and hook it in the base task namespace 'username'. Args: username(str) package_name(str) _globals(dict): the globals() namespace of the fabric script. Return: None ''' ad...
Load all known fabsetup addons which are installed as pypi pip-packages. Args: _globals(dict): the globals() namespace of the fabric script. Return: None
def load_pip_addons(_globals): '''Load all known fabsetup addons which are installed as pypi pip-packages. Args: _globals(dict): the globals() namespace of the fabric script. Return: None ''' for package_name in known_pip_addons: _, username = package_username(package_name) ...
>>> package_user('fabsetup-theno-termdown') (termdown, theno)
def package_username(repo): ''' >>> package_user('fabsetup-theno-termdown') (termdown, theno) ''' package = repo.replace('-', '_') username = repo.split('-')[1] return package, username
Load all fabsetup addons which are stored under ~/.fabsetup-addon-repos as git repositories. Args: _globals(dict): the globals() namespace of the fabric script. Return: None
def load_repo_addons(_globals): '''Load all fabsetup addons which are stored under ~/.fabsetup-addon-repos as git repositories. Args: _globals(dict): the globals() namespace of the fabric script. Return: None ''' repos_dir = os.path.expanduser('~/.fabsetup-addon-repos') if os.path....
Put custom commands at '~/bin/' For the conversion of diagrams into the pdf format: * dia2pdf, ep2svg, svg2pdf * alldia2pdf, allep2svg, alldia2pdf
def users_bin_dir(): '''Put custom commands at '~/bin/' For the conversion of diagrams into the pdf format: * dia2pdf, ep2svg, svg2pdf * alldia2pdf, allep2svg, alldia2pdf ''' # circumvent circular import, cf. http://stackoverflow.com/a/18486863 from fabfile.setup import pencil2 pencil2(...
r'\n\s*
def t_ignore_INDENT(self, t): r'\n\s*' indent_status, curr_depth, next_depth = self.get_indent_status(t) if indent_status == 'NODENT': return if indent_status == 'INDENT': # note: also set by # * t_B_SEQUENCE_COMPACT_START # * t_B_MA...
r"(?<!\\)
def t_begin_singlequote(self, t): r"(?<!\\)'" t.lexer.push_state('singlequote') # t.lexer.begin('singlequote') t.type = 'CAST_TYPE' t.type = 'SINGLEQUOTE_START' return t
r'\n+\ *
def t_fold_end(self, t): r'\n+\ *' column = find_column(t) indent = self.indent_stack[-1] if column < indent: rollback_lexpos(t) if column <= indent: t.lexer.pop_state() t.type = 'B_FOLD_END' if column > indent: t.type = 'SC...
r""" \-\ + (?= -\ ) # ^ ^ sequence indicator | \-\ + (?= [\{\[]\ | [^:\n]*:\s ) # ^ ^ ^^^ map indicator # ^ ^ flow indicator
def t_B_SEQUENCE_COMPACT_START(self, t): r""" \-\ + (?= -\ ) # ^ ^ sequence indicator | \-\ + (?= [\{\[]\ | [^:\n]*:\s ) # ^ ^ ^^^ map indicator # ^ ^ flow indicator """ indent_status, curr_depth, n...
r""" Find the DLL for a given library. Accepts a string or loaded module >>> print(find_lib('kernel32').lower()) c:\windows\system32\kernel32.dll
def find_lib(lib): r""" Find the DLL for a given library. Accepts a string or loaded module >>> print(find_lib('kernel32').lower()) c:\windows\system32\kernel32.dll """ if isinstance(lib, str): lib = getattr(ctypes.windll, lib) size = 1024 result = ctypes.create_unicode_buffer(size) library.GetModuleFile...
Get science metadata for a resource in XML+RDF format :param pid: The HydroShare ID of the resource :raises: HydroShareNotAuthorized if the user is not authorized to view the metadata. :raises: HydroShareNotFound if the resource was not found. :raises: HydroShareHTTPException to signal ...
def getScienceMetadataRDF(self, pid): """ Get science metadata for a resource in XML+RDF format :param pid: The HydroShare ID of the resource :raises: HydroShareNotAuthorized if the user is not authorized to view the metadata. :raises: HydroShareNotFound if the resource was not found. ...
Get a resource in BagIt format :param pid: The HydroShare ID of the resource :param destination: String representing the directory to save bag to. Bag will be saved to file named $(PID).zip in destination; existing file of the same name will be overwritten. If None, a stream to the ...
def getResource(self, pid, destination=None, unzip=False, wait_for_bag_creation=True): """ Get a resource in BagIt format :param pid: The HydroShare ID of the resource :param destination: String representing the directory to save bag to. Bag will be saved to file named $(PID).zip in...
Get the list of resource types supported by the HydroShare server :return: A set of strings representing the HydroShare resource types :raises: HydroShareHTTPException to signal an HTTP error
def getResourceTypes(self): """ Get the list of resource types supported by the HydroShare server :return: A set of strings representing the HydroShare resource types :raises: HydroShareHTTPException to signal an HTTP error """ url = "{url_base}/resource/types".format(url_base=...
Create a new resource. :param resource_type: string representing the a HydroShare resource type recognized by this server. :param title: string representing the title of the new resource :param resource_file: a read-only binary file-like object (i.e. opened with the flag 'rb') or a ...
def createResource(self, resource_type, title, resource_file=None, resource_filename=None, abstract=None, keywords=None, edit_users=None, view_users=None, edit_groups=None, view_groups=None, metadata=None, extra_metadata=None, progress_callback=None):...
Delete a resource. :param pid: The HydroShare ID of the resource
def deleteResource(self, pid): """ Delete a resource. :param pid: The HydroShare ID of the resource """ url = "{url_base}/resource/{pid}/".format(url_base=self.url_base, pid=pid) r = self._request('DELETE', url) ...
Set access rules for a resource. Current only allows for setting the public or private setting. :param pid: The HydroShare ID of the resource :param public: True if the resource should be made public.
def setAccessRules(self, pid, public=False): """ Set access rules for a resource. Current only allows for setting the public or private setting. :param pid: The HydroShare ID of the resource :param public: True if the resource should be made public. """ url = "{url_base...
Add a new file to an existing resource :param pid: The HydroShare ID of the resource :param resource_file: a read-only binary file-like object (i.e. opened with the flag 'rb') or a string representing path to file to be uploaded as part of the new resource :param resource_filename: ...
def addResourceFile(self, pid, resource_file, resource_filename=None, progress_callback=None): """ Add a new file to an existing resource :param pid: The HydroShare ID of the resource :param resource_file: a read-only binary file-like object (i.e. opened with the flag 'rb') or a string ...
Get a file within a resource. :param pid: The HydroShare ID of the resource :param filename: String representing the name of the resource file to get. :param destination: String representing the directory to save the resource file to. If None, a stream to the resource file will be r...
def getResourceFile(self, pid, filename, destination=None): """ Get a file within a resource. :param pid: The HydroShare ID of the resource :param filename: String representing the name of the resource file to get. :param destination: String representing the directory to save the resour...
Delete a resource file :param pid: The HydroShare ID of the resource :param filename: String representing the name of the resource file to delete :return: Dictionary containing 'resource_id' the ID of the resource from which the file was deleted, and 'file_name' the filename of the...
def deleteResourceFile(self, pid, filename): """ Delete a resource file :param pid: The HydroShare ID of the resource :param filename: String representing the name of the resource file to delete :return: Dictionary containing 'resource_id' the ID of the resource from which the ...
Get a listing of files within a resource. :param pid: The HydroShare ID of the resource whose resource files are to be listed. :raises: HydroShareArgumentException if any parameters are invalid. :raises: HydroShareNotAuthorized if user is not authorized to perform action. :raises: Hydr...
def getResourceFileList(self, pid): """ Get a listing of files within a resource. :param pid: The HydroShare ID of the resource whose resource files are to be listed. :raises: HydroShareArgumentException if any parameters are invalid. :raises: HydroShareNotAuthorized if user is not aut...
Get a listing of files and folders for a resource at the specified path (*pathname*) :param pid: The HydroShare ID of the resource whose folder contents to be listed :param pathname: Folder path for which contents (files and folders) need to be listed :return: A JSON object representing the con...
def getResourceFolderContents(self, pid, pathname): """ Get a listing of files and folders for a resource at the specified path (*pathname*) :param pid: The HydroShare ID of the resource whose folder contents to be listed :param pathname: Folder path for which contents (files and folders) need ...
Create a Referenced Content File (.url) :param pid: The HydroShare ID of the resource for which the file should be created :param name: Filename for the referenced file :param ref_url: url to be used in the referenced file :...
def createReferenceURL(self, pid, name, ref_url, path="", validate=True): """Create a Referenced Content File (.url) :param pid: The HydroShare ID of the resource for which the file should be created :param name: Filename for the referenced file ...
Update a Referenced Content File (.url) :param pid: The HydroShare ID of the resource for which the file should be updated :param name: Filename for the referenced file :param ref_url: url to be updated in the referenced file ...
def updateReferenceURL(self, pid, name, ref_url, path=""): """Update a Referenced Content File (.url) :param pid: The HydroShare ID of the resource for which the file should be updated :param name: Filename for the referenced file :param r...
Deprecated, use updateReferenceURL. Update a Referenced Content File (.url) :param pid: The HydroShare ID of the resource for which the file should be updated :param path: Folder path for the file to be updated in :param name: Filename for the referenced file ...
def updateReferencedFile(self, pid, path, name, ref_url): """Deprecated, use updateReferenceURL. Update a Referenced Content File (.url) :param pid: The HydroShare ID of the resource for which the file should be updated :param path: Folder path for the file to be updated in ...
Get the decrypted value of an SSM parameter Args: parameter_name - the name of the stored parameter of interest Return: Value if allowed and present else None
def get_ssm_parameter(parameter_name): ''' Get the decrypted value of an SSM parameter Args: parameter_name - the name of the stored parameter of interest Return: Value if allowed and present else None ''' try: response = boto3.client('ssm').get_parameters( ...
Query the GET /hsapi/userInfo/ REST end point of the HydroShare server. :raises: HydroShareHTTPException to signal an HTTP error :return: A JSON object representing user info, for example: { "username": "username", "first_name": "First", "last_name": "Last"...
def getUserInfo(self): """ Query the GET /hsapi/userInfo/ REST end point of the HydroShare server. :raises: HydroShareHTTPException to signal an HTTP error :return: A JSON object representing user info, for example: { "username": "username", "first_name...
Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where setuptools will be downloaded, if it is n...
def use_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15 ): """Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `downlo...