code stringlengths 1 18.2k |
|---|
def files_size(fs0, fs1, files): """Gets the file size of the given files.""" for file_meta in files['deleted_files']: file_meta['size'] = fs0.stat(file_meta['path'])['size'] for file_meta in files['created_files'] + files['modified_files']: file_meta['size'] = fs1.stat(file_meta['path'])['size'] return files |
def parse_registries(filesystem, registries): """Returns a dictionary with the content of the given registry hives. {"\\Registry\\Key\\", (("ValueKey", "ValueType", ValueValue))} """ results = {} for path in registries: with NamedTemporaryFile(buffering=0) as tempfile: filesystem.download(path, tempfile.name) registry ... |
def makedirs(path): """Creates the directory tree if non existing.""" path = Path(path) if not path.exists(): path.mkdir(parents=True) |
def compare(self, concurrent=False, identify=False, size=False): """Compares the two disks according to flags. Generates the following report: :: {'created_files': [{'path': '/file/in/disk1/not/in/disk0', 'sha1': 'sha1_of_the_file'}], 'deleted_files': [{'path': '/file/in/disk0/not/in/disk1', 'original_sha1': 'sha1_of_t... |
def extract(self, disk, files, path='.'): """Extracts the given files from the given disk. Disk must be an integer (1 or 2) indicating from which of the two disks to extract. Files must be a list of dictionaries containing the keys 'path' and 'sha1'. Files will be extracted in path and will be named with their sha1. Re... |
def compare_registry(self, concurrent=False): """Compares the Windows Registry contained within the two File Systems. It parses all the registry hive files contained within the disks and generates the following report. {'created_keys': {'\\Reg\\Key': (('Key', 'Type', 'Value'))} 'deleted_keys': ['\\Reg\\Key', ...], 'cre... |
def _create_error(self, status_code): """ Construct an error message in jsend format. :param int status_code: The status code to translate into an error message :return: A dictionary in jsend format with the error and the code :rtype: dict """ return jsend.error(message=ComodoCA.status_code[status_code], code=status_co... |
def get_cert_types(self): """ Collect the certificate types that are available to the customer. :return: A list of dictionaries of certificate types :rtype: list """ result = self.client.service.getCustomerCertTypes(authData=self.auth) if result.statusCode == 0: return jsend.success({'cert_types': result.types}) else: ... |
def collect(self, cert_id, format_type): """ Poll for certificate availability after submission. :param int cert_id: The certificate ID :param str format_type: The format type to use (example: 'X509 PEM Certificate only') :return: The certificate_id or the certificate depending on whether the certificate is ready (chec... |
def revoke(self, cert_id, reason=''): """ Revoke a certificate. :param int cert_id: The certificate ID :param str reason: Reason for revocation (up to 256 characters), can be blank: '' :return: The result of the operation, 'Successful' on success :rtype: dict """ result = self.client.service.revoke(authData=self.auth, ... |
def submit(self, cert_type_name, csr, revoke_password, term, subject_alt_names='', server_type='OTHER'): """ Submit a certificate request to Comodo. :param string cert_type_name: The full cert type name (Example: 'PlatinumSSL Certificate') the supported certificate types for your account can be obtained with the get_ce... |
if cert_types['status'] == 'error': return cert_types # We do this because we need to pass the entire cert type definition back to Comodo # not just the name. for cert_type in cert_types['data']['cert_types']: if cert_type.name == cert_type_name: cert_type_def = cert_type result = self.client.service.enroll(authData=se... |
def build_from_source(version, **kwargs): """ Builds specified Spark version from source. :param version: :param kwargs: :return: (Integer) Status code of build/mvn command. """ mvn = os.path.join(Spark.svm_version_path(version), 'build', 'mvn') Spark.chmod_add_excute(mvn) p = subprocess.Popen([mvn, '-DskipTests', 'cle... |
def chmod_add_excute(filename): """ Adds execute permission to file. :param filename: :return: """ st = os.stat(filename) os.chmod(filename, st.st_mode | stat.S_IEXEC) |
def download_source(version): """ Download Spark version. Uses same name as release tag without the leading 'v'. :param version: Version number to download. :return: None """ local_filename = 'v{}.zip'.format(Spark.svm_version_path(version)) Spark.download(Spark.spark_versions()['v{}'.format(version)], local_filename) |
def svm_version_path(version): """ Path to specified spark version. Accepts semantic version numbering. :param version: Spark version as String :return: String. """ return os.path.join(Spark.HOME_DIR, Spark.SVM_DIR, 'v{}'.format(version)) |
def unzip(filename): """ Unzips specified file into ~/.svm :param filename: :return: """ with zipfile.ZipFile(filename, "r") as zip_ref: zip_ref.extractall(Spark.svm_path()) return True |
def rename_unzipped_folder(version): """ Renames unzipped spark version folder to the release tag. :param version: version from release tag. :return: """ for filename in os.listdir(Spark.svm_path()): if fnmatch.fnmatch(filename, 'apache-spark-*'): return os.rename(os.path.join(Spark.svm_path(), filename), Spark.svm_ver... |
def fromType(datatype): """Use this method to create a MultiValue type from a specific GP Value type. >>> gpmultistr = arcrest.GPMultiValue.fromType(arcrest.GPString) >>> gpvalue = gpmultistr(["a", "b", "c"]) """ if issubclass(datatype, GPBaseType): return GPBaseType._get_type_by_name("GPMultiValue:%s" % datatype.__nam... |
def gradient(self, y_true, y_pred): """Returns the gradient of the L1 loss with respect to each prediction. Example: >>> import starboost as sb >>> y_true = [0, 0, 1] >>> y_pred = [0.3, 0, 0.8] >>> sb.losses.L1Loss().gradient(y_true, y_pred) array([ 1., 0., -1.]) """ return np.sign(np.subtract(y_pred, y_true)) |
def get_parents(): """Return sorted list of names of packages without dependants.""" distributions = get_installed_distributions(user_only=ENABLE_USER_SITE) remaining = {d.project_name.lower() for d in distributions} requirements = {r.project_name.lower() for d in distributions for r in d.requires()} return get_realnam... |
def get_realnames(packages): """ Return list of unique case-correct package names. Packages are listed in a case-insensitive sorted order. """ return sorted({get_distribution(p).project_name for p in packages}, key=lambda n: n.lower()) |
def authenticate_redirect(self, callback_uri=None, ask_for=["name", "email", "language", "username"]): """ Performs a redirect to the authentication URL for this service. After authentication, the service will redirect back to the given callback URI. We request the given attributes for the authenticated user by default... |
def get_authenticated_user(self, callback): """Fetches the authenticated user data upon redirect. This method should be called by the handler that receives the redirect from the authenticate_redirect() or authorize_redirect() methods. """ # Verify the OpenID response via direct request to the OP args = dict((k, v) for ... |
def _on_auth(self, user): """ This is called when login with OpenID succeeded and it's not necessary to figure out if this is the users's first login or not. """ app = current_app._get_current_object() if not user: # Google auth failed. login_error.send(app, user=None) abort(403) session["openid"] = user login.send(app... |
def required(self, fn): """Request decorator. Forces authentication.""" @functools.wraps(fn) def decorated(*args, **kwargs): if (not self._check_auth() # Don't try to force authentication if the request is part # of the authentication process - otherwise we end up in a # loop. and request.blueprint != self.blueprint.na... |
def parse_journal_file(journal_file): """Iterates over the journal's file taking care of paddings.""" counter = count() for block in read_next_block(journal_file): block = remove_nullchars(block) while len(block) > MIN_RECORD_SIZE: header = RECORD_HEADER.unpack_from(block) size = header[0] try: yield parse_record(heade... |
def parse_record(header, record): """Parses a record according to its version.""" major_version = header[1] try: return RECORD_PARSER[major_version](header, record) except (KeyError, struct.error) as error: raise RuntimeError("Corrupted USN Record") from error |
def usn_v2_record(header, record): """Extracts USN V2 record information.""" length, major_version, minor_version = header fields = V2_RECORD.unpack_from(record, RECORD_HEADER.size) return UsnRecord(length, float('{}.{}'.format(major_version, minor_version)), fields[0] | fields[1] << 16, # 6 bytes little endian mft fie... |
def usn_v4_record(header, record): """Extracts USN V4 record information.""" length, major_version, minor_version = header fields = V4_RECORD.unpack_from(record, RECORD_HEADER.size) raise NotImplementedError('Not implemented') |
def unpack_flags(value, flags): """Multiple flags might be packed in the same field.""" try: return [flags[value]] except KeyError: return [flags[k] for k in sorted(flags.keys()) if k & value > 0] |
def read_next_block(infile, block_size=io.DEFAULT_BUFFER_SIZE): """Iterates over the file in blocks.""" chunk = infile.read(block_size) while chunk: yield chunk chunk = infile.read(block_size) |
def remove_nullchars(block): """Strips NULL chars taking care of bytes alignment.""" data = block.lstrip(b'\00') padding = b'\00' * ((len(block) - len(data)) % 8) return padding + data |
def timetopythonvalue(time_val): "Convert a time or time range from ArcGIS REST server format to Python" if isinstance(time_val, sequence): return map(timetopythonvalue, time_val) elif isinstance(time_val, numeric): return datetime.datetime(*(time.gmtime(time_val))[:6]) elif isinstance(time_val, numeric): values = [] t... |
def pythonvaluetotime(time_val): "Convert a time or time range from Python datetime to ArcGIS REST server" if time_val is None: return None elif isinstance(time_val, numeric): return str(long(time_val * 1000.0)) elif isinstance(time_val, date): dtlist = [time_val.year, time_val.month, time_val.day] if isinstance(time_v... |
def get_hosts(self, group=None): ''' Get the hosts ''' hostlist = [] if group: groupobj = self.inventory.groups.get(group) if not groupobj: print "Group [%s] not found in inventory" % group return None groupdict = {} groupdict['hostlist'] = [] for host in groupobj.get_hosts(): groupdict['hostlist'].append(host.name) ho... |
def make_random_MLdataset(max_num_classes = 20, min_class_size = 20, max_class_size = 50, max_dim = 100, stratified = True): "Generates a random MLDataset for use in testing." smallest = min(min_class_size, max_class_size) max_class_size = max(min_class_size, max_class_size) largest = max(50, max_class_size) largest = ... |
def forProperty(instance,propertyName,useGetter=False): """ 2-way binds to an instance property. Parameters: - instance -- the object instance - propertyName -- the name of the property to bind to - useGetter: when True, calls the getter method to obtain the value. When False, the signal argument is used as input for t... |
= "get" + propertyName[3:] setterName = "set" + propertyName[3:] if len(propertyName[3:]) > 1: signalName = propertyName[3].lower() + propertyName[4:] + "Changed" else: signalName = propertyName.lower() + "Changed" assert hasattr(instance,getterName) assert hasattr(instance,setterName) assert hasattr(instance,signalNam... |
and setPropertyName methods if len(propertyName) > 1: getterName = "get" + propertyName[0].upper() + propertyName[1:] setterName = "set" + propertyName[0].upper() + propertyName[1:] signalName = propertyName + "Changed" else: getterName = "get" + propertyName.upper() setterName = "set" + propertyName.upper() signalName... |
def bind(self,instance,setter,valueChangedSignal,getter = None): """ Creates an endpoint and call bindToEndpoint(endpoint). This is a convenience method. Parameters: instance -- the object instance to which the getter, setter and changedSignal belong setter -- the value setter method valueChangedSignal -- the pyqtSigna... |
def bindToEndPoint(self,bindingEndpoint): """ 2-way binds the target endpoint to all other registered endpoints. """ self.bindings[bindingEndpoint.instanceId] = bindingEndpoint bindingEndpoint.valueChangedSignal.connect(self._updateEndpoints) |
def bindToProperty(self,instance,propertyName,useGetter=False): """ 2-way binds to an instance property. Parameters: - instance -- the object instance - propertyName -- the name of the property to bind to - useGetter: when True, calls the getter method to obtain the value. When False, the signal argument is used as inp... |
def _updateEndpoints(self,*args,**kwargs): """ Updates all endpoints except the one from which this slot was called. Note: this method is probably not complete threadsafe. Maybe a lock is needed when setter self.ignoreEvents """ sender = self.sender() if not self.ignoreEvents: self.ignoreEvents = True for binding in se... |
def _anonymize_table(cls, table_data, pii_fields): """Anonymize in `table_data` the fields in `pii_fields`. Args: table_data (pandas.DataFrame): Original dataframe/table. pii_fields (list[dict]): Metadata for the fields to transform. Result: pandas.DataFrame: Anonymized table. """ for pii_field in pii_fields: field_nam... |
def _get_tables(self, base_dir): """Load the contents of meta_file and the corresponding data. If fields containing Personally Identifiable Information are detected in the metadata they are anonymized before asign them into `table_dict`. Args: base_dir(str): Root folder of the dataset files. Returns: dict: Mapping str ... |
def _get_transformers(self): """Load the contents of meta_file and extract information about the transformers. Returns: dict: tuple(str, str) -> Transformer. """ transformer_dict = {} for table in self.metadata['tables']: table_name = table['name'] for field in table['fields']: transformer_type = field.get('type') if t... |
def _fit_transform_column(self, table, metadata, transformer_name, table_name): """Transform a column from table using transformer and given parameters. Args: table (pandas.DataFrame): Dataframe containing column to transform. metadata (dict): Metadata for given column. transformer_name (str): Name of transformer to us... |
def _reverse_transform_column(self, table, metadata, table_name): """Reverses the transformtion on a column from table using the given parameters. Args: table (pandas.DataFrame): Dataframe containing column to transform. metadata (dict): Metadata for given column. table_name (str): Name of table in original dataset. Re... |
def fit_transform_table( self, table, table_meta, transformer_dict=None, transformer_list=None, missing=None): """Create, apply and store the specified transformers for `table`. Args: table(pandas.DataFrame): Contents of the table to be transformed. table_meta(dict): Metadata for the given table. transformer_dict(dict)... |
= pd.concat([result, transformed], axis=1) elif (table_name, col_name) in transformer_dict: transformer_name = TRANSFORMERS[transformer_dict[(table_name, col_name)]] transformed = self._fit_transform_column( table, field, transformer_name, table_name) result = pd.concat([result, transformed], axis=1) return result |
def transform_table(self, table, table_meta, missing=None): """Apply the stored transformers to `table`. Args: table(pandas.DataFrame): Contents of the table to be transformed. table_meta(dict): Metadata for the given table. missing(bool): Wheter or not use NullTransformer to handle missing values. Returns: pandas.Data... |
def reverse_transform_table(self, table, table_meta, missing=None): """Transform a `table` back to its original format. Args: table(pandas.DataFrame): Contents of the table to be transformed. table_meta(dict): Metadata for the given table. missing(bool): Wheter or not use NullTransformer to handle missing values. Retur... |
def fit_transform( self, tables=None, transformer_dict=None, transformer_list=None, missing=None): """Create, apply and store the specified transformers for the given tables. Args: tables(dict): Mapping of table names to `tuple` where each tuple is on the form (`pandas.DataFrame`, `dict`). The `DataFrame` contains the ... |
transformer_dict is None and transformer_list is None: transformer_dict = self.transformer_dict for table_name in tables: table, table_meta = tables[table_name] transformed_table = self.fit_transform_table( table, table_meta, transformer_dict, transformer_list) transformed[table_name] = transformed_table return transfo... |
def transform(self, tables, table_metas=None, missing=None): """Apply all the saved transformers to `tables`. Args: tables(dict): mapping of table names to `tuple` where each tuple is on the form (`pandas.DataFrame`, `dict`). The `DataFrame` contains the table data and the `dict` the corresponding meta information. If ... |
def reverse_transform(self, tables, table_metas=None, missing=None): """Transform data back to its original format. Args: tables(dict): mapping of table names to `tuple` where each tuple is on the form (`pandas.DataFrame`, `dict`). The `DataFrame` contains the transformed data and the `dict` the corresponding meta info... |
def echo(msg, *args, **kwargs): '''Wraps click.echo, handles formatting and check encoding''' file = kwargs.pop('file', None) nl = kwargs.pop('nl', True) err = kwargs.pop('err', False) color = kwargs.pop('color', None) msg = safe_unicode(msg).format(*args, **kwargs) click.echo(msg, file=file, nl=nl, err=err, color=colo... |
def header(msg, *args, **kwargs): '''Display an header''' msg = ' '.join((yellow(HEADER), white(msg), yellow(HEADER))) echo(msg, *args, **kwargs) |
def success(msg, *args, **kwargs): '''Display a success message''' echo('{0} {1}'.format(green(OK), white(msg)), *args, **kwargs) |
def warning(msg, *args, **kwargs): '''Display a warning message''' msg = '{0} {1}'.format(yellow(WARNING), msg) echo(msg, *args, **kwargs) |
def error(msg, details=None, *args, **kwargs): '''Display an error message with optionnal details''' msg = '{0} {1}'.format(red(KO), white(msg)) if details: msg = '\n'.join((msg, safe_unicode(details))) echo(format_multiline(msg), *args, **kwargs) |
def exit_with_error(msg='Aborted', details=None, code=-1, *args, **kwargs): '''Exit with error''' error(msg, details=details, *args, **kwargs) sys.exit(code) |
def load(patterns, full_reindex): ''' Load one or more CADA CSV files matching patterns ''' header('Loading CSV files') for pattern in patterns: for filename in iglob(pattern): echo('Loading {}'.format(white(filename))) with open(filename) as f: reader = csv.reader(f) # Skip header reader.next() for idx, row in enumera... |
def reindex(): '''Reindex all advices''' header('Reindexing all advices') echo('Deleting index {0}', white(es.index_name)) if es.indices.exists(es.index_name): es.indices.delete(index=es.index_name) es.initialize() idx = 0 for idx, advice in enumerate(Advice.objects, 1): index(advice) echo('.' if idx % 50 else white(id... |
def static(path, no_input): '''Compile and collect static files into path''' log = logging.getLogger('webassets') log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) cmdenv = CommandLineEnvironment(assets, log) cmdenv.build() if exists(path): warning('{0} directory already exists and will be {1}', white... |
def anon(): '''Check for candidates to anonymization''' header(anon.__doc__) filename = 'urls_to_check.csv' candidates = Advice.objects(__raw__={ '$or': [ {'subject': { '$regex': '(Monsieur|Madame|Docteur|Mademoiselle)\s+[^X\s\.]{3}', '$options': 'imx', }}, {'content': { '$regex': '(Monsieur|Madame|Docteur|Mademoiselle... |
def fix(csvfile): '''Apply a fix (ie. remove plain names)''' header('Apply fixes from {}', csvfile.name) bads = [] reader = csv.reader(csvfile) reader.next() # Skip header for id, _, sources, dests in reader: advice = Advice.objects.get(id=id) sources = [s.strip() for s in sources.split(',') if s.strip()] dests = [d.st... |
def build_channel(namespace, name, user_ids): """ Creates complete channel information as described here https://fzambia.gitbooks.io/centrifugal/content/server/channels.html. """ ids = ','.join(map(str, user_ids)) return "{0}:{1}#{2}".format(namespace, name, ids) |
def login(self, **kwargs): """Logs the current user into the server with the passed in credentials. If successful the apiToken will be changed to match the passed in credentials. :param apiToken: use the passed apiToken to authenticate :param user_id: optional instead of apiToken, must be passed with token :param token... |
def createAssetFromURL(self, url, async=False, metadata=None, callback=None): """Users the passed URL to load data. If async=false a json with the result is returned otherwise a json with an asset_id is returned. :param url: :param metadata: arbitrary additional description information for the asset :param async: :para... |
def uploadAsset(self, data, async=False, metadata=None, callback=None): """Takes an array of bytes or a BufferedReader and uploads it. If async=false a json with the result is returned otherwise a json with an asset_id is returned. :param data: array of bytes or BufferedReader :param metadata: arbitrary additional desc... |
def load(filename=None, url=r"https://raw.githubusercontent.com/googlei18n/emoji4unicode/master/data/emoji4unicode.xml", loader_class=None): u"""load google's `emoji4unicode` project's xml file. must call this method first to use `e4u` library. this method never work twice if you want to reload, use `e4u.reload()` inst... |
def reload(filename=None, url=r"https://raw.githubusercontent.com/googlei18n/emoji4unicode/master/data/emoji4unicode.xml", loader_class=None): u"""reload google's `emoji4unicode` project's xml file. must call this method first to use `e4u` library.""" if loader_class is None: loader_class = loader.Loader global _loader... |
def translate_char(source_char, carrier, reverse=False, encoding=False): u"""translate unicode emoji character to unicode carrier emoji character (or reverse) Attributes: source_char - emoji character. it must be unicode instance or have to set `encoding` attribute to decode carrier - the target carrier reverse - if yo... |
def translate(source, carrier, reverse=False, encoding=None): u"""translate unicode text contain emoji character to unicode carrier text (or reverse) Attributes: source - text contain emoji character. it must be unicode instance or have to set `encoding` attribute to decode carrier - the target carrier reverse - if you... |
source) |
def is_file_encrypted(self, filename): ''' Given a file. Check if it is already encrypted. ''' if not os.path.exists(filename): print "Invalid filename %s. Does not exist" % filename return False fhandle = open(filename, "rb") data = fhandle.read() fhandle.close() if data.startswith(AnsiVault.HEADER): return True else:... |
def encrpyt_file(self, filename): ''' Encrypt File Args: filename: Pass the filename to encrypt. Returns: No return. ''' if not os.path.exists(filename): print "Invalid filename %s. Does not exist" % filename return if self.vault_password is None: print "ENV Variable PYANSI_VAULT_PASSWORD not set" return if self.is_fil... |
def decrypt_file(self, filename): ''' Decrypt File Args: filename: Pass the filename to encrypt. Returns: No return. ''' if not os.path.exists(filename): print "Invalid filename %s. Does not exist" % filename return if self.vault_password is None: print "ENV Variable PYANSI_VAULT_PASSWORD not set" return if not self.is... |
def common_start(*args): """ returns the longest common substring from the beginning of sa and sb """ def _iter(): for s in zip(*args): if len(set(s)) < len(args): yield s[0] else: return out = "".join(_iter()).strip() result = [s for s in args if not s.startswith(out)] result.insert(0, out) return ', '.join(result) |
def determine_json_encoding(json_bytes): ''' Given the fact that the first 2 characters in json are guaranteed to be ASCII, we can use these to determine the encoding. See: http://tools.ietf.org/html/rfc4627#section-3 Copied here: Since the first two characters of a JSON text will always be ASCII characters [RFC0020], ... |
== 0 and b2 == 0 and b3 == 0 and b4 != 0: return "UTF-32BE" elif b1 == 0 and b2 != 0 and b3 == 0 and b4 != 0: return "UTF-16BE" elif b1 != 0 and b2 == 0 and b3 == 0 and b4 == 0: return "UTF-32LE" elif b1 != 0 and b2 == 0 and b3 != 0 and b4 == 0: return "UTF-16LE" elif b1 != 0 and b2 != 0 and b3 != 0 and b4 != 0: return... |
0: raise Exceptions.ContentTypeError("Json string too short to definitively infer encoding.") elif b1 != 0 and b2 != 0: return "UTF-8" else: raise Exceptions.ContentTypeError("Unknown encoding!") raise Exceptions.ContentTypeError("Input string too short to guess encoding!") |
def passgen(length=12, punctuation=False, digits=True, letters=True, case="both", **kwargs): """Generate random password. Args: length (int): The length of the password. Must be greater than zero. Defaults to 12. punctuation (bool): Whether to use punctuation or not. Defaults to False. limit_punctuation (str): Limits t... |
p_min = punctuation p_max = 0 if punctuation is False else length d_min = digits d_max = 0 if digits is False else length a_min = letters a_max = 0 if letters is False else length if d_min + p_min + a_min > length: raise ValueError("Minimum punctuation and digits number cannot be greater than length") if not digits and... |
kwargs.get('limit_punctuation', '') if limit_punctuation == '': punctuation_set = string.punctuation else: # In case limit_punctuation contains non-punctuation characters punctuation_set = ''.join([p for p in limit_punctuation if p in string.punctuation]) else: punctuation_set = string.punctuation srandom = random.Syst... |
def main(): """The main entry point for command line invocation. It's output is adjusted by command line arguments. By default it outputs 10 passwords. For help on accepted arguments, run:: $ passgen -h Or:: $ python -m passgen -h """ parser = argparse.ArgumentParser( description="Generate random password." ) parser.ad... |
than zero") if args.number < 1: _error("argument -n/--number must be greater than zero") if args.lower: case = "lower" elif args.upper: case = "upper" else: case = "both" for _ in range(args.number): print(passgen(args.length, punctuation=args.punctuation, limit_punctuation=args.limit_punctuation, digits=args.digits, l... |
def convert(self, language, *args, **kwargs): """ Run converter. Args: language: (unicode) language code. """ for f in find_pos(language): PoToXls(src=f, **kwargs).convert() |
def main(cls): """Setuptools console-script entrypoint""" cmd = cls() cmd._parse_args() cmd._setup_logging() response = cmd._run() output = cmd._handle_response(response) if output is not None: print(output) |
def set_language(self, request, org): """Set the current language from the org configuration.""" if org: lang = org.language or settings.DEFAULT_LANGUAGE translation.activate(lang) |
def set_timezone(self, request, org): """Set the current timezone from the org configuration.""" if org and org.timezone: timezone.activate(org.timezone) |
def transform(self, col): """Prepare the transformer to convert data and return the processed table. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame """ out = pd.DataFrame(index=col.index) out[self.col_name] = col.fillna(self.default_value) out[self.new_name] = (pd.notnull(col) * 1).astype(int... |
def reverse_transform(self, col): """Converts data back into original format. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame """ output = pd.DataFrame() new_name = '?' + self.col_name col.loc[col[new_name] == 0, self.col_name] = np.nan output[self.col_name] = col[self.col_name] return output |
def _is_private_ip(ip): """ Taken from https://stackoverflow.com/a/39656628/268006 Check if the IP belongs to private network blocks. @param ip: IP address to verify. @return: boolean representing whether the IP belongs or not to a private network block. """ networks = [ "0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127... |
def add(self, obj): """ Add pre-created tracks. If the tracks are already created, we hijack the data. This way the pointer to the pre-created tracks are still valid. """ obj.controller = self.controller # Is the track already loaded or created? track = self.tracks.get(obj.name) if track: if track == obj: return # hija... |
def row_value(self, row): """Get the tracks value at row""" irow = int(row) i = self._get_key_index(irow) if i == -1: return 0.0 # Are we dealing with the last key? if i == len(self.keys) - 1: return self.keys[-1].value return TrackKey.interpolate(self.keys[i], self.keys[i + 1], row) |
def add_or_update(self, row, value, kind): """Add or update a track value""" i = bisect.bisect_left(self.keys, row) # Are we simply replacing a key? if i < len(self.keys) and self.keys[i].row == row: self.keys[i].update(value, kind) else: self.keys.insert(i, TrackKey(row, value, kind)) |
def delete(self, row): """Delete a track value""" i = self._get_key_index(row) del self.keys[i] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.