code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def spin2_polar(self): return coordinates.cartesian_to_spherical_polar( self.spin2x, self.spin2y, self.spin2z)
Returns the polar spin angle of mass 2.
def tag_path(cls, project, incident, tag): return google.api_core.path_template.expand( "projects/{project}/incidents/{incident}/tags/{tag}", project=project, incident=incident, tag=tag, )
Return a fully-qualified tag string.
def record_coverage_zero(self, rule, offset): self.coverage_lines.append('DA:{},0'.format(rule.source_line + offset))
Add entry to coverage saying this selector was parsed
def _get_url(ssl, url, port, path): if ssl: return 'https://{0}:{1}/management/domain/{2}'.format(url, port, path) else: return 'http://{0}:{1}/management/domain/{2}'.format(url, port, path)
Returns the URL of the endpoint
def check_future(self, fut): done = self.done = fut.done() if done and not self.prev_done: self.done_since = self.ioloop.time() self.prev_done = done
Call with each future that is to be yielded on
def _collect_for_instance(self, instance, connection): with connection.cursor() as cursor: for queue, metrics in self.get_queue_info(instance, cursor): for name, metric in metrics.items(): self.publish('.'.join((instance, queue, name)), metric) with connec...
Collects metrics for a named connection.
def update_order(self, order_id, order_deets): request = self._put("transactions/orders/" + str(order_id), order_deets) return self.responder(request)
Updates an existing order transaction.
def query(self, model_cls): self._filters_cmd = list() self.query_filters = list() self._order_by_cmd = None self._offset = 0 self._limit = 0 self.query_class = model_cls._name return self
SQLAlchemy query like method
def ScheduleKillNotification(self): kill_timestamp = (rdfvalue.RDFDatetime().Now() + self.stuck_flows_timeout) with queue_manager.QueueManager(token=self.token) as manager: manager.QueueNotification( session_id=self.session_id, in_progress=True, timestamp=kill_timestamp) ...
Schedules a kill notification for this flow.
def format_command( command_args, command_output, ): text = 'Command arguments: {}\n'.format(command_args) if not command_output: text += 'Command output: None' elif logger.getEffectiveLevel() > logging.DEBUG: text += 'Command output: [use --verbose to show]' else: if not...
Format command information for logging.
def isDeleteKeyEvent(self, keyEvent): return self._start is not None and \ (keyEvent.matches(QKeySequence.Delete) or \ (keyEvent.key() == Qt.Key_Backspace and keyEvent.modifiers() == Qt.NoModifier))
Check if key event should be handled as Delete command
def _GetServiceKey(): global _service_key if _service_key is None: hive = getattr(winreg, config.CONFIG["Client.config_hive"]) path = config.CONFIG["Client.config_key"] _service_key = winreg.CreateKeyEx(hive, path, 0, winreg.KEY_ALL_ACCESS) return _service_key
Returns the service key.
def s3path(self, rel_path): import urlparse path = self.path(rel_path, public_url=True) parts = list(urlparse.urlparse(path)) parts[0] = 's3' parts[1] = self.bucket_name return urlparse.urlunparse(parts)
Return the path as an S3 schema
def clearAnnouncements(self): try: q = models.Announcement.delete().where( models.Announcement.id > 0) q.execute() except Exception as e: raise exceptions.RepoManagerException(e)
Flushes the announcement table.
def update_channels(self): if not self.gui_up: return self.logger.debug("channel configuration has changed--updating gui") try: channel = self.fv.get_channel(self.chname) except KeyError: channel = self.fv.get_channel_info() if channel is None:...
Update the GUI to reflect channels and image listing.
def _detach_children(self): children = [val[0] for val in self._children.values()] for child in children: child()._parent = list(self) self._children.clear()
Remove all children and give them independent parent copies.
def cnormpath (path): path = normpath(path) if os.name == 'nt': path = path.replace("/", "\\") if not os.path.isabs(path): path = normpath(os.path.join(sys.prefix, path)) return path
Norm a path name to platform specific notation and make it absolute.
def show_service_profile(self, flavor_profile, **_params): return self.get(self.service_profile_path % (flavor_profile), params=_params)
Fetches information for a certain Neutron service flavor profile.
def default_arguments(cls): func = cls.__init__ args = func.__code__.co_varnames defaults = func.__defaults__ index = -len(defaults) return {k: v for k, v in zip(args[index:], defaults)}
Returns the available kwargs of the called class
def __SetBody(self, http_request, method_config, request, upload): if not method_config.request_field: return request_type = _LoadClass( method_config.request_type_name, self.__client.MESSAGES_MODULE) if method_config.request_field == REQUEST_IS_BODY: body_val...
Fill in the body on http_request.
def transformToNative(obj): if obj.isNative: return obj obj.isNative = True if obj.value == '': obj.value = [] return obj tzinfo = getTzid(getattr(obj, 'tzid_param', None)) obj.value = [stringToPeriod(x, tzinfo) for x in obj.value.split(",")] ...
Convert comma separated periods into tuples.
def bills(self, member_id, type='introduced'): "Same as BillsClient.by_member" path = "members/{0}/bills/{1}.json".format(member_id, type) return self.fetch(path)
Same as BillsClient.by_member
def update_window(turn_from, tick_from, turn_to, tick_to, updfun, branchd): if turn_from in branchd: for past_state in branchd[turn_from][tick_from+1:]: updfun(*past_state) for midturn in range(turn_from+1, turn_to): if midturn in branchd: for past_state in branchd[midtur...
Iterate over a window of time in ``branchd`` and call ``updfun`` on the values
def clear(self): for sample in self.metadata: try: delattr(sample.depth, 'bases') delattr(sample.depth, 'coverage') delattr(sample.depth, 'length') delattr(sample.depth, 'stddev') except AttributeError: pass
Clear out large attributes from the metadata objects
def cmd_signing_key(self, args): if len(args) == 0: print("usage: signing setup passphrase") return if not self.master.mavlink20(): print("You must be using MAVLink2 for signing") return passphrase = args[0] key = self.passphrase_to_key(pas...
set signing key on connection
def search(self, initial_ids, initial_cache): state, state_shapes = self._create_initial_state(initial_ids, initial_cache) finished_state = tf.while_loop( self._continue_search, self._search_step, loop_vars=[state], shape_invariants=[state_shapes], parallel_iterations=1, back_prop=False) fin...
Beam search for sequences with highest scores.
def rank(): rank_data_url = 'https://raw.githubusercontent.com/Microsoft/LightGBM/master/examples/lambdarank/' x_train, y_train = sklearn.datasets.load_svmlight_file(cache(rank_data_url + 'rank.train')) x_test, y_test = sklearn.datasets.load_svmlight_file(cache(rank_data_url + 'rank.test')) q_train = np...
Ranking datasets from lightgbm repository.
def frombits(cls, bits='0'): if len(bits) > cls._len: raise ValueError('too many bits %r' % (bits,)) return cls.fromint(bits[::-1], 2)
Create a set from binary string.
def _segment_with_tokens(text, tokens): list_form = [] text_ptr = 0 for token in tokens: inter_token_string = [] while not text[text_ptr:].startswith(token): inter_token_string.append(text[text_ptr]) text_ptr += 1 if text_pt...
Segment a string around the tokens created by a passed-in tokenizer
def from_file(cls, source): if hasattr(source, 'read'): relations = cls.from_string(source.read()) else: with open(source) as f: relations = cls.from_string(f.read()) return relations
Instantiate Relations from a relations file.
def cancel(self, order_id): response = self.request(E.cancelSslCertRequest( E.id(order_id) )) return int(response.data.id)
Cancel an ordered SSL certificate.
def _handle_blacklisted_tag(self): strip = lambda text: text.rstrip().lower() while True: this, next = self._read(), self._read(1) if this is self.END: self._fail_route() elif this == "<" and next == "/": self._head += 3 ...
Handle the body of an HTML tag that is parser-blacklisted.
def wid_to_gid(wid): widval = wid[1:] if len(wid) > 3 else wid xorval = 474 if len(wid) > 3 else 31578 return str(int(widval, 36) ^ xorval)
Calculate gid of a worksheet from its wid.
def send_trending_data(events): bodies = {} top_hits = sorted( [(key, count) for key, count in events.items()], key=lambda x: x[1], reverse=True )[:100] for (site, content_id), count in top_hits: if not len(site) or not re.match(CONTENT_ID_REGEX, content_id): ...
creates data point payloads for trending data to influxdb
def DCM_update(IMU, ATT, MAG, GPS): global dcm_state if dcm_state is None: dcm_state = DCM_State(ATT.Roll, ATT.Pitch, ATT.Yaw) mag = Vector3(MAG.MagX, MAG.MagY, MAG.MagZ) gyro = Vector3(IMU.GyrX, IMU.GyrY, IMU.GyrZ) accel = Vector3(IMU.AccX, IMU.AccY, IMU.AccZ) accel2 = Vector3(IMU.Ac...
implement full DCM system
def cancel_email_change(self): if not self.email_new: return self.email_new = None self.email_confirmed = True self.email_link = None self.email_new = None self.email_link_expires = None
Cancel email change for new users and roll back data
def wait_until_finished(self): try: self.thread.join() except KeyboardInterrupt: self._logger.debug('Keyboard interrupt detected, stopping driver.') self._active = False self._wake_queue()
Blocking method to wait until the driver finished its execution.
def osu_run1(data_set='osu_run1', sample_every=4): path = os.path.join(data_path, data_set) if not data_available(data_set): import zipfile download_data(data_set) zip = zipfile.ZipFile(os.path.join(data_path, data_set, 'run1TXT.ZIP'), 'r') for name in zip.namelist(): ...
Ohio State University's Run1 motion capture data set.
def _convert_seconds(self, packed_seconds): seconds = struct.unpack("!H", packed_seconds[:2])[0] seconds += struct.unpack("!I", packed_seconds[2:])[0] return seconds
Unpack the internal representation.
def randomise_labels( self, inplace=False, ): if not inplace: t = self.copy() else: t = self names = list(t.labels) random.shuffle(names) for l in t._tree.leaf_node_iter(): l.taxon._label = names.pop() t._dir...
Shuffles the leaf labels, but doesn't alter the tree structure
def add_for_targets(self, targets, classpath_elements): for target in targets: self.add_for_target(target, classpath_elements)
Adds classpath path elements to the products of all the provided targets.
def _request(self, request, proxies, timeout, verify, **_): settings = self.http.merge_environment_settings( request.url, proxies, False, verify, None) self._delay() response = self.http.send( request, timeout=timeout, allow_redirects=False, **settings) self._upda...
This is where we apply rate limiting and make the HTTP request.
def cartesian_to_homogeneous(cartesian_matrix, matrix_type="numpy"): dimension_x, dimension_y = cartesian_matrix.shape if matrix_type == "numpy": homogeneous_matrix = np.eye(dimension_x + 1) elif matrix_type == "sympy": homogeneous_matrix = sympy.eye(dimension_x + 1) homogeneous_matrix[:...
Converts a cartesian matrix to an homogenous matrix
def _remove_soma_initial_point(tree): if tree.points[0][COLS.TYPE] == POINT_TYPE.SOMA: tree.points = tree.points[1:]
Remove tree's initial point if soma
def users_forgot_password(self, email, **kwargs): return self.__call_api_post('users.forgotPassword', email=email, data=kwargs)
Send email to reset your password.
def exclude_paths(args): results = [] if args.exclude: for excl_path in args.exclude: results.append(os.path.abspath(os.path.join(args.root, excl_path))) return results
Returns the absolute paths for excluded path.
def build_transform(self): cfg = self.cfg if cfg.INPUT.TO_BGR255: to_bgr_transform = T.Lambda(lambda x: x * 255) else: to_bgr_transform = T.Lambda(lambda x: x[[2, 1, 0]]) normalize_transform = T.Normalize( mean=cfg.INPUT.PIXEL_MEAN, std=cfg.INPUT.PIXEL...
Creates a basic transformation that was used to train the models
def loaded(self, request, *args, **kwargs): serializer = self.get_serializer(list(Pack.objects.all()), many=True) return Response(serializer.data)
Return a list of loaded Packs.
def extract_version(): with open('pdftools/__init__.py', 'r') as f: content = f.read() version_match = _version_re.search(content) version = str(ast.literal_eval(version_match.group(1))) return version
Extract the version from the package.
def exists(self, path, **kwargs): try: self.get_file_status(path, **kwargs) return True except HdfsFileNotFoundException: return False
Return true if the given path exists
def filename_to_task_id(fname): fname = os.path.basename(fname) shard_id_increment = { "train": 0, "dev": 800, "test": 900, } parts = fname.split("-") split = parts[1] shard_id = parts[2] task_id = int(shard_id) + shard_id_increment[split] return task_id
Map filename to the task id that created it assuming 1k tasks.
def add_route(app_or_blueprint, fn, context=default_context): transmute_func = TransmuteFunction( fn, args_not_from_request=["request"] ) handler = create_handler(transmute_func, context=context) get_swagger_spec(app_or_blueprint).add_func(transmute_func, context) for p in transmute_...
a decorator that adds a transmute route to the application
def new_event(self, event_data: str) -> None: event = self.parse_event_xml(event_data) if EVENT_OPERATION in event: self.manage_event(event)
New event to process.
def LoadServerCertificate(self, server_certificate=None, ca_certificate=None): try: server_certificate.Verify(ca_certificate.GetPublicKey()) except rdf_crypto.VerificationError as e: self.server_name = None raise IOError("Server cert is invalid: %s" % e) server_cert_serial = server_certifi...
Loads and verifies the server certificate.
def get(self, field, cluster): if _is_list(cluster): return [self.get(field, c) for c in cluster] assert field in self._fields default = self._fields[field] return self._data.get(cluster, {}).get(field, default)
Retrieve the value of one cluster.
def system(self): if self._resources is None: self.__init() if "system" in self._resources: url = self._url + "/system" return _system.System(url=url, securityHandler=self._securityHandler, proxy_url=...
returns an object to work with the site system
def jinja_node_to_python(node): if isinstance(node, nodes.Const): return node.value if isinstance(node, nodes.Neg): return -jinja_node_to_python(node.node) if isinstance(node, nodes.Name): return node.name if isinstance(node, (nodes.List, nodes.Tuple)): value = [] ...
Converts a Jinja2 node to its python equivalent
def _to_diagonally_dominant(mat): mat += np.diag(np.sum(mat != 0, axis=1) + 0.01) return mat
Make matrix unweighted diagonally dominant using the Laplacian.
def save_data(self): if len(self.data.keys()) == 0: return assert 'episode' in self.data sorted_indexes = np.argsort(self.data['episode']) sorted_data = {} for key, values in self.data.items(): assert len(self.data[key]) == len(sorted_indexes) ...
Save metrics in a json file
def new(filename: str, *, file_attrs: Optional[Dict[str, str]] = None) -> LoomConnection: if filename.startswith("~/"): filename = os.path.expanduser(filename) if file_attrs is None: file_attrs = {} f = h5py.File(name=filename, mode='w') f.create_group('/layers') f.create_group('/row_attrs') f.create_group('/...
Create an empty Loom file, and return it as a context manager.
def corrupt_bytes(s, p=0.01, n=None): s = bytes(s) s = array.array("B",s) l = len(s) if n is None: n = max(1,int(l*p)) for i in random.sample(range(l), n): s[i] = (s[i]+random.randint(1,255))%256 return s.tobytes()
Corrupt a given percentage or number of bytes from bytes
def initialize_options(self): self._file_lines_cache = dict() self.suppress_codes = list() self.exclusions = list() self.cache_directory = "" self.stamp_directory = "" self.disable_linters = list() self.show_lint_files = 0
Set all options to their initial values.
def iter_tree_with_handed_function(self, function, *function_args): def iter_all_children(row_iter, function, function_args): if isinstance(row_iter, Gtk.TreeIter): function(row_iter, *function_args) for n in reversed(range(self.tree_store.iter_n_children(row_iter))):...
Iterate tree view with condition check function
def bootstrap_general_election(self, election): election_day = election.election_day page_type, created = PageType.objects.get_or_create( model_type=ContentType.objects.get( app_label="election", model="electionday" ), election_day=election_day, ...
Create a general election page type
def addLineAnnot(self, p1, p2): CheckParent(self) val = _fitz.Page_addLineAnnot(self, p1, p2) if not val: return val.thisown = True val.parent = weakref.proxy(self) self._annot_refs[id(val)] = val return val
Add 'Line' annot for points p1 and p2.
def from_dict(d): query_params_match = d.get('@query_params_match') query_person_match = d.get('@query_person_match') valid_since = d.get('@valid_since') if valid_since: valid_since = str_to_datetime(valid_since) source = Source.from_dict(d.get('source', {})) ...
Transform the dict to a record object and return the record.
def _encode(values, salt, min_length, alphabet, separators, guards): len_alphabet = len(alphabet) len_separators = len(separators) values_hash = sum(x % (i + 100) for i, x in enumerate(values)) encoded = lottery = alphabet[values_hash % len(alphabet)] for i, value in enumerate(values): alpha...
Helper function that does the hash building without argument checks.
def _winapi(self, func, *a, **kw): self.flush() if _DEBUG_RENDER_OUTPUT: self.LOG.write(('%r' % func.__name__).encode('utf-8') + b'\n') self.LOG.write(b' ' + ', '.join(['%r' % i for i in a]).encode('utf-8') + b'\n') self.LOG.write(b' ' + ', '.join(['%r' % type...
Flush and call win API function.
def clean_dict(d): ktd = list() for k, v in d.items(): if not v: ktd.append(k) elif type(v) is dict: d[k] = clean_dict(v) for k in ktd: d.pop(k) return d
remove the keys with None values.
def argsort_k_smallest(x, k): if k == 0: return np.array([], dtype=np.intp) if k is None or k >= len(x): return np.argsort(x) indices = np.argpartition(x, k)[:k] values = x[indices] return indices[np.argsort(values)]
Return no more than ``k`` indices of smallest values.
def find_by_b64ids(self, _ids, **kwargs): return self.find_by_ids([ObjectId(base64.b64decode(_id)) for _id in _ids], **kwargs)
Pass me a list of base64-encoded ObjectId
def top_referrers(self, domain_only=True): referrer = self._referrer_clause(domain_only) return (self.get_query() .select(referrer, fn.Count(PageView.id)) .group_by(referrer) .order_by(fn.Count(PageView.id).desc()) .tuples())
What domains send us the most traffic?
def _make_graphite_api_points_list(influxdb_data): _data = {} for key in influxdb_data.keys(): _data[key[0]] = [(datetime.datetime.fromtimestamp(float(d['time'])), d['value']) for d in influxdb_data.get_points(key[0])] return _data
Make graphite-api data points dictionary from Influxdb ResultSet data
def _name_variation_has_only_initials(name): def _is_initial(name_variation): return len(name_variation) == 1 or u'.' in name_variation parsed_name = ParsedName.loads(name) return all([_is_initial(name_part) for name_part in parsed_name])
Detects whether the name variation consists only from initials.
def process_request(self, unused_request): tasklets._state.clear_all_pending() ctx = tasklets.make_default_context() tasklets.set_context(ctx)
Called by Django before deciding which view to execute.
def get(self, request, *args, **kwargs): private_file = self.get_private_file() if not self.can_access_file(private_file): return HttpResponseForbidden('Private storage access denied') if not private_file.exists(): return self.serve_file_not_found(private_file) el...
Handle incoming GET requests
def build_schema( source: Union[str, Source], assume_valid=False, assume_valid_sdl=False, no_location=False, experimental_fragment_variables=False, ) -> GraphQLSchema: return build_ast_schema( parse( source, no_location=no_location, experimental_fragme...
Build a GraphQLSchema directly from a source document.
def _download_ontology(url, local_file): current_app.logger.debug( "Copying remote ontology '%s' to file '%s'." % (url, local_file) ) try: request = requests.get(url, stream=True) if request.status_code == 200: with open(local_file, 'wb') as f: for chunk i...
Download the ontology and stores it in CLASSIFIER_WORKDIR.
def float(self, **kwargs): for key in kwargs: setattr(self, key, kwargs[key]) self.command = self.COMMAND_FLOAT
Remove power from the motor.
def join_or_die(self): if self._phase_desc.options.timeout_s is not None: self.join(self._phase_desc.options.timeout_s) else: self.join(DEFAULT_PHASE_TIMEOUT_S) if isinstance(self._phase_execution_outcome, PhaseExecutionOutcome): return self._phase_execution_outcome if self.is_alive():...
Wait for thread to finish, returning a PhaseExecutionOutcome instance.
def _get_beacons(self, include_opts=True, include_pillar=True): beacons = {} if include_pillar: pillar_beacons = self.opts.get('pillar', {}).get('beacons', {}) if not isinstance(pillar_beacons, dict): raise ValueError('Bea...
Return the beacons data structure
def check_token(self, token: 'RedisEphemeralTokens') -> bool: if self.get_state() is None: return False correct_token = self.make_token(self) self.clear() return constant_time_compare(correct_token, token)
Check that a token is correct for a given scope token.
def convert_string(string, chars=None): if chars is None: chars = [',', '.', '-', '/', ':', ' '] for ch in chars: if ch in string: string = string.replace(ch, ' ') return string
Remove certain characters from a string.
def run(self): while (self._run_thread): (mode, version, packet) = self._read_packet() if (mode == PROP_PACKET_SENSE): self._decode_sense_packet(version, packet) elif (mode == PROP_PACKET_CTRL): self._decode_ctrl_packet(version, packet)
Main thread that reads from input and populates the sensors.
def _list_variables(self, station_codes): rvar = re.compile(r"\n\s([A-Z]{2}[A-Z0-9]{0,1})\(\w+\)") variables = set() resp = requests.post( self.obs_retrieval_url, data={ "state": "nil", "hsa": "nil", "of": "3", ...
Internal helper to list the variables for the given station codes.
def _path_is_executable_others(path): prevpath = None while path and path != prevpath: try: if not os.stat(path).st_mode & stat.S_IXOTH: return False except OSError: return False prevpath = path path, _ = os.path.split(path) return True
Check every part of path for executable permission
def _update_pwm(self): if self._is_on: values = self._get_pwm_values() else: values = [0] * len(self._driver.pins) self._driver.set_pwm(values)
Update the pwm values of the driver regarding the current state.
def _add_new_methods(cls): for name, method in cls.context.new_methods.items(): if hasattr(cls.context.new_class, name): raise ValueError( "Name collision in state machine class - '{name}'." .format(name) ) setattr(c...
Add all generated methods to result class.
def _altair_hline_(self, xfield, yfield, opts, style, encode): try: rawy = yfield if ":" in yfield: rawy = yfield.split(":")[0] mean = self.df[rawy].mean() l = [] i = 0 while i < len(self.df[rawy]): l.append(...
Get a mean line chart
def run(self, host='0.0.0.0', port=8080): waitress.serve(self.app, host=host, port=port)
Launch a development web server.
def _convert_latitude(self, latitude): return int((180 - (180 / pi * log(tan( pi / 4 + latitude * pi / 360)))) * (2 ** self._zoom) * self._size / 360)
Convert from latitude to the y position in overall map.
def cython_debug_files(): files = [] for path in sys_path: pattern = os.path.join(path, '*', 'cython_debug', 'cython_debug_info_*') files.extend(glob.glob(pattern)) return files
Cython extra debug information files
def _topological_sort(self, targets): target_set = set(targets) return [t for t in reversed(sort_targets(targets)) if t in target_set]
Topologically order a list of targets
def encrypt(self, s, mac_bytes=10): if isinstance(s, six.text_type): raise ValueError( "Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") out = BytesIO() with self.encrypt_to(out, mac_bytes) as f: ...
Encrypt `s' for this pubkey.
def files(self): self._printer('\tFiles Walk') for directory in self.directory: for path in os.listdir(directory): full_path = os.path.join(directory, path) if os.path.isfile(full_path): if not path.startswith('.'): ...
Return list of files in root directory
def remove_key(self, key): try: self._own_keys.discard(key) if self._parent and self._parent.has_key(key): self._container[key] = self._parent[key] else: del self._container[key] except KeyError: pass
Remove own key, value
def _get_zone_name(self): if self._name is None: tags = ["GetZoneName"] root = self.exec_appcommand_post(tags) if root is None: _LOGGER.error("Getting ZoneName failed.") else: zone = self._get_own_zone() try: ...
Get receivers zone name if not set yet.
def delete(self, _key) : "removes a document from the cache" try : doc = self.cacheStore[_key] doc.prev.nextDoc = doc.nextDoc doc.nextDoc.prev = doc.prev del(self.cacheStore[_key]) except KeyError : raise KeyError("Document with _key %s...
removes a document from the cache
def unquote_pre_filter(pre_filter, _regex=re.compile(r'[\\]+')): if pre_filter.startswith('"') and pre_filter.endswith('"'): pre_filter = pre_filter[1:-1] pre_filter = _regex.sub(lambda x: x.group(0)[:len(x.group(0)) // 2], pre_filter) return pre_filter
Unquote a pre-filter condition.
def copyresource( resource, filename, destdir ): data = pkgutil.get_data(resource, os.path.join('resources',filename) ) with open( os.path.join(destdir,filename), 'wb' ) as fp: fp.write(data)
Copy a resource file to a destination