Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _StructMessageToJsonObject(message, unused_including_default=False):
"""Converts Struct message according to Proto3 JSON Specification."""
fields = message.fields
ret = {}
for key in fields:
ret[key] = _ValueMessageToJsonObject(fields[key])
return ret |
def Parse(text, message):
"""Parses a JSON representation of a protocol message into a message.
Args:
text: Message JSON representation.
message: A protocol beffer message to merge into.
Returns:
The same message passed as argument.
Raises::
ParseError: On JSON parsing problems.
"""
if no... |
def _ConvertFieldValuePair(js, message):
"""Convert field value pairs into regular message.
Args:
js: A JSON object to convert the field value pairs.
message: A regular protocol message to record the data.
Raises:
ParseError: In case of problems converting.
"""
names = []
message_descriptor = ... |
def _ConvertMessage(value, message):
"""Convert a JSON object into a message.
Args:
value: A JSON object.
message: A WKT or regular protocol message to record the data.
Raises:
ParseError: In case of convert problems.
"""
message_descriptor = message.DESCRIPTOR
full_name = message_descriptor.f... |
def _ConvertValueMessage(value, message):
"""Convert a JSON representation into Value message."""
if isinstance(value, dict):
_ConvertStructMessage(value, message.struct_value)
elif isinstance(value, list):
_ConvertListValueMessage(value, message.list_value)
elif value is None:
message.null_value = ... |
def _ConvertListValueMessage(value, message):
"""Convert a JSON representation into ListValue message."""
if not isinstance(value, list):
raise ParseError(
'ListValue must be in [] which is {0}.'.format(value))
message.ClearField('values')
for item in value:
_ConvertValueMessage(item, message.va... |
def _ConvertStructMessage(value, message):
"""Convert a JSON representation into Struct message."""
if not isinstance(value, dict):
raise ParseError(
'Struct must be in a dict which is {0}.'.format(value))
for key in value:
_ConvertValueMessage(value[key], message.fields[key])
return |
def update_config(new_config):
""" Update config options with the provided dictionary of options.
"""
flask_app.base_config.update(new_config)
# Check for changed working directory.
if new_config.has_key('working_directory'):
wd = os.path.abspath(new_config['working_directory'])
if ... |
def set_config(new_config={}):
""" Reset config options to defaults, and then update (optionally)
with the provided dictionary of options. """
# The default base configuration.
flask_app.base_config = dict(working_directory='.',
template='collapse-input',
... |
def execute(self, correlation_id, args):
"""
Executes the command given specific arguments as an input.
Args:
correlation_id: a unique correlation/transaction id
args: command arguments
Returns: an execution result.
Rai... |
def optimize(function, x0, cons=[], ftol=0.2, disp=0, plot=False):
"""
**Optimization method based on Brent's method**
First, a bracket (a b c) is sought that contains the minimum (b value is
smaller than both a or c).
The bracket is then recursively halfed. Here we apply some modifications
to ensure our sug... |
def cache2errors(function, cache, disp=0, ftol=0.05):
"""
This function will attempt to identify 1 sigma errors, assuming your
function is a chi^2. For this, the 1-sigma is bracketed.
If you were smart enough to build a cache list of [x,y] into your function,
you can pass it here. The values bracketing 1 sigma w... |
def end_timing(self):
"""
Completes measuring time interval and updates counter.
"""
if self._callback != None:
elapsed = time.clock() * 1000 - self._start
self._callback.end_timing(self._counter, elapsed) |
def ToJsonString(self):
"""Converts Duration to string format.
Returns:
A string converted from self. The string format will contains
3, 6, or 9 fractional digits depending on the precision required to
represent the exact Duration value. For example: "1s", "1.010s",
"1.000000100s", "-3.... |
def FromJsonString(self, value):
"""Converts a string to Duration.
Args:
value: A string to be converted. The string must end with 's'. Any
fractional digits (or none) are accepted as long as they fit into
precision. For example: "1s", "1.01s", "1.0000001s", "-3.100s
Raises:
... |
def FromJsonString(self, value):
"""Converts string to FieldMask according to proto3 JSON spec."""
self.Clear()
for path in value.split(','):
self.paths.append(path) |
def get_doc(doc_id, db_name, server_url='http://127.0.0.1:5984/', rev=None):
"""Return a CouchDB document, given its ID, revision and database name."""
db = get_server(server_url)[db_name]
if rev:
headers, response = db.resource.get(doc_id, rev=rev)
return couchdb.client.Document(response)
... |
def get_or_create_db(db_name, server_url='http://127.0.0.1:5984/'):
"""Return an (optionally existing) CouchDB database instance."""
server = get_server(server_url)
if db_name in server:
return server[db_name]
return server.create(db_name) |
def read(readme):
"""Give reST format README for pypi."""
extend = os.path.splitext(readme)[1]
if (extend == '.rst'):
import codecs
return codecs.open(readme, 'r', 'utf-8').read()
elif (extend == '.md'):
import pypandoc
return pypandoc.convert(readme, 'rst') |
def main():
"""Register your own mode and handle method here."""
plugin = Register()
if plugin.args.option == 'sql':
plugin.sql_handle()
elif plugin.args.option == 'database-used':
plugin.database_used_handle()
elif plugin.args.option == 'databaselog-used':
plugin.database_lo... |
def parse(self, args):
"""
:param args: arguments
:type args: None or string or list of string
:return: formatted arguments if specified else ``self.default_args``
:rtype: list of string
"""
if args is None:
args = self._default_args
if isinsta... |
def _request(self, method, *relative_path_parts, **kwargs):
"""Sends an HTTP request to the REST API and receives the requested data.
:param str method: HTTP method name
:param relative_path_parts: the relative paths for the request URI
:param kwargs: argument keywords
:returns: requested data
... |
def _place_order(self,
side,
product_id='BTC-USD',
client_oid=None,
type=None,
stp=None,
price=None,
size=None,
funds=None,
time_in_force=None,
... |
def place_limit_order(self,
side,
price,
size,
product_id='BTC-USD',
client_oid=None,
stp=None,
time_in_force=None,
cancel_after... |
def place_market_order(self,
side,
product_id='BTC-USD',
size=None,
funds=None,
client_oid=None,
stp=None):
"""`<https://docs.exchange.coinbase.com/#orders>`_"""
... |
def _deposit_withdraw(self, type, amount, coinbase_account_id):
"""`<https://docs.exchange.coinbase.com/#depositwithdraw>`_"""
data = {
'type':type,
'amount':amount,
'coinbase_account_id':coinbase_account_id
}
return self._post('transfers', data=data) |
def _new_report(self,
type,
start_date,
end_date,
product_id='BTC-USD',
account_id=None,
format=None,
email=None):
"""`<https://docs.exchange.coinbase.com/#create-a-new-report>`_"""
data... |
def new_fills_report(self,
start_date,
end_date,
account_id=None,
product_id='BTC-USD',
format=None,
email=None):
"""`<https://docs.exchange.coinbase.com/#create-a-new-report>`_"... |
def _request(self, method, *relative_path_parts, **kwargs):
"""Sends an HTTP request to the REST API and receives the requested data.
Additionally sets up pagination cursors.
:param str method: HTTP method name
:param relative_path_parts: the relative paths for the request URI
:param kwargs: argume... |
def fetch(self, collection, **kwargs):
'''
return one record from the collection whose parameters match kwargs
---
kwargs should be a dictionary whose keys match column names (in
traditional SQL / fields in NoSQL) and whose values are the values of
those fields.
e... |
def remove(self, collection, **kwargs):
'''
remove records from collection whose parameters match kwargs
'''
callback = kwargs.pop('callback')
yield Op(self.db[collection].remove, kwargs)
callback() |
def store(self, collection, **kwargs):
'''
validate the passed values in kwargs based on the collection,
store them in the mongodb collection
'''
callback = kwargs.pop('callback')
key = validate(collection, **kwargs)
data = yield Task(self.fetch, collection, **{ke... |
def generate_api(version):
"""
Generates a factory function to instantiate the API with the given
version.
"""
def get_partial_api(key, token=None):
return TrelloAPI(ENDPOINTS[version], version, key, token=token)
get_partial_api.__doc__ = \
"""Interfaz REST con Trello. Versión ... |
def _url(self):
"""
Resolve the URL to this point.
>>> trello = TrelloAPIV1('APIKEY')
>>> trello.batch._url
'1/batch'
>>> trello.boards(board_id='BOARD_ID')._url
'1/boards/BOARD_ID'
>>> trello.boards(board_id='BOARD_ID')(field='FIELD')._url
'1/boa... |
def _api_call(self, method_name, *args, **kwargs):
"""
Makes the HTTP request.
"""
params = kwargs.setdefault('params', {})
params.update({'key': self._apikey})
if self._token is not None:
params.update({'token': self._token})
http_method = getattr(r... |
def Merge(text, message, allow_unknown_extension=False,
allow_field_number=False):
"""Parses an text representation of a protocol message into a message.
Like Parse(), but allows repeated values for a non-repeated field, and uses
the last one.
Args:
text: Message text representation.
message... |
def ParseLines(lines, message, allow_unknown_extension=False,
allow_field_number=False):
"""Parses an text representation of a protocol message into a message.
Args:
lines: An iterable of lines of a message's text representation.
message: A protocol buffer message to merge into.
allow_un... |
def _SkipFieldValue(tokenizer):
"""Skips over a field value.
Args:
tokenizer: A tokenizer to parse the field name and values.
Raises:
ParseError: In case an invalid field value is found.
"""
# String/bytes tokens can come in multiple adjacent string literals.
# If we can consume one, consume as ma... |
def ParseInteger(text, is_signed=False, is_long=False):
"""Parses an integer.
Args:
text: The text to parse.
is_signed: True if a signed integer must be parsed.
is_long: True if a long integer must be parsed.
Returns:
The integer value.
Raises:
ValueError: Thrown Iff the text is not a val... |
def PrintMessage(self, message):
"""Convert protobuf message to text format.
Args:
message: The protocol buffers message.
"""
fields = message.ListFields()
if self.use_index_order:
fields.sort(key=lambda x: x[0].index)
for field, value in fields:
if _IsMapEntry(field):
... |
def PrintFieldValue(self, field, value):
"""Print a single field value (not including name).
For repeated fields, the value should be a single element.
Args:
field: The descriptor of the field to be printed.
value: The value of the field.
"""
out = self.out
if self.pointy_brackets:... |
def _ParseOrMerge(self, lines, message):
"""Converts an text representation of a protocol message into a message.
Args:
lines: Lines of a message's text representation.
message: A protocol buffer message to merge into.
Raises:
ParseError: On text parsing problems.
"""
tokenizer =... |
def _MergeMessageField(self, tokenizer, message, field):
"""Merges a single scalar field into a message.
Args:
tokenizer: A tokenizer to parse the field value.
message: The message of which field is a member.
field: The descriptor of the field to be merged.
Raises:
ParseError: In c... |
def ConsumeIdentifier(self):
"""Consumes protocol message field identifier.
Returns:
Identifier string.
Raises:
ParseError: If an identifier couldn't be consumed.
"""
result = self.token
if not self._IDENTIFIER.match(result):
raise self._ParseError('Expected identifier.')
... |
def ConsumeInt32(self):
"""Consumes a signed 32bit integer number.
Returns:
The integer parsed.
Raises:
ParseError: If a signed 32bit integer couldn't be consumed.
"""
try:
result = ParseInteger(self.token, is_signed=True, is_long=False)
except ValueError as e:
raise se... |
def ConsumeFloat(self):
"""Consumes an floating point number.
Returns:
The number parsed.
Raises:
ParseError: If a floating point number couldn't be consumed.
"""
try:
result = ParseFloat(self.token)
except ValueError as e:
raise self._ParseError(str(e))
self.NextTo... |
def ConsumeBool(self):
"""Consumes a boolean value.
Returns:
The bool parsed.
Raises:
ParseError: If a boolean value couldn't be consumed.
"""
try:
result = ParseBool(self.token)
except ValueError as e:
raise self._ParseError(str(e))
self.NextToken()
return resu... |
def _ConsumeSingleByteString(self):
"""Consume one token of a string literal.
String literals (whether bytes or text) can come in multiple adjacent
tokens which are automatically concatenated, like in C or Python. This
method only consumes one token.
Returns:
The token parsed.
Raises:
... |
def timestamp(t = None, forfilename=False):
"""Returns a human-readable timestamp given a Unix timestamp 't' or
for the current time. The Unix timestamp is the number of seconds since
start of epoch (1970-01-01 00:00:00).
When forfilename is True, then spaces and semicolons are replace with
hyphens.... |
def arktimestamp(arkt, forfilename=False):
"""Returns a human-readable timestamp given an Ark timestamp 'arct'.
An Ark timestamp is the number of seconds since Genesis block,
2017:03:21 15:55:44."""
t = arkt + time.mktime((2017, 3, 21, 15, 55, 44, 0, 0, 0))
return '%d %s' % (arkt, timestamp(t)) |
def arkt_to_unixt(ark_timestamp):
""" convert ark timestamp to unix timestamp"""
res = datetime.datetime(2017, 3, 21, 15, 55, 44) + datetime.timedelta(seconds=ark_timestamp)
return res.timestamp() |
def close(self):
"""Close the connection."""
try:
self.conn.close()
self.logger.debug("Close connect succeed.")
except pymssql.Error as e:
self.unknown("Close connect error: %s" % e) |
def get_version():
"""Extract package __version__"""
with open(VERSION_FILE, encoding='utf-8') as fp:
content = fp.read()
match = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', content, re.M)
if match:
return match.group(1)
raise RuntimeError("Could not extract package __version__"... |
def de(output_basename, parameter_names, transform, loglikelihood, prior, nsteps=40000, vizfunc=None, printfunc=None, **problem):
"""
**Differential evolution**
via `inspyred <http://inspyred.github.io/>`_
specially tuned. steady state replacement, n-point crossover,
pop size 20, gaussian mutation noise... |
def process_macros(self, content: str) -> str:
'''Replace macros with content defined in the config.
:param content: Markdown content
:returns: Markdown content without macros
'''
def _sub(macro):
name = macro.group('body')
params = self.get_options(mac... |
def _request(self, method, *relative_path_parts, **kwargs):
"""Sends an HTTP request to the REST API and receives the requested data.
:param str method: HTTP method name
:param relative_path_parts: the relative paths for the request URI
:param kwargs: argument keywords
:returns: requested data
... |
def get_historic_trades(self, start, end, granularity, product_id='BTC-USD'):
"""`<https://docs.exchange.coinbase.com/#get-historic-rates>`_
:param start: either datetime.datetime or str in ISO 8601
:param end: either datetime.datetime or str in ISO 8601
:pram int granularity: desired timeslice in seco... |
def _request(self, method, *relative_path_parts, **kwargs):
"""Sends an HTTP request to the REST API and receives the requested data.
Additionally sets up pagination cursors.
:param str method: HTTP method name
:param relative_path_parts: the relative paths for the request URI
:param kwargs: argume... |
def get_unique_pathname(path, root=''):
"""Return a pathname possibly with a number appended to it so that it is
unique in the directory."""
path = os.path.join(root, path)
# consider the path supplied, then the paths with numbers appended
potentialPaths = itertools.chain((path,), __get_numbered_paths(path))
... |
def __get_numbered_paths(filepath):
"""Append numbers in sequential order to the filename or folder name
Numbers should be appended before the extension on a filename."""
format = '%s (%%d)%s' % splitext_files_only(filepath)
return map(lambda n: format % n, itertools.count(1)) |
def splitext_files_only(filepath):
"Custom version of splitext that doesn't perform splitext on directories"
return (
(filepath, '') if os.path.isdir(filepath) else os.path.splitext(filepath)
) |
def set_time(filename, mod_time):
"""
Set the modified time of a file
"""
log.debug('Setting modified time to %s', mod_time)
mtime = calendar.timegm(mod_time.utctimetuple())
# utctimetuple discards microseconds, so restore it (for consistency)
mtime += mod_time.microsecond / 1000000
atime = os.stat(file... |
def get_time(filename):
"""
Get the modified time for a file as a datetime instance
"""
ts = os.stat(filename).st_mtime
return datetime.datetime.utcfromtimestamp(ts) |
def insert_before_extension(filename, content):
"""
Given a filename and some content, insert the content just before
the extension.
>>> insert_before_extension('pages.pdf', '-old')
'pages-old.pdf'
"""
parts = list(os.path.splitext(filename))
parts[1:1] = [content]
return ''.join(parts) |
def recursive_glob(root, spec):
"""
Like iglob, but recurse directories
>>> any('path.py' in result for result in recursive_glob('.', '*.py'))
True
>>> all(result.startswith('.') for result in recursive_glob('.', '*.py'))
True
>>> len(list(recursive_glob('.', '*.foo')))
0
"""
specs = (
os... |
def encode(name, system='NTFS'):
"""
Encode the name for a suitable name in the given filesystem
>>> encode('Test :1')
'Test _1'
"""
assert system == 'NTFS', 'unsupported filesystem'
special_characters = r'<>:"/\|?*' + ''.join(map(chr, range(32)))
pattern = '|'.join(map(re.escape, special_characters))
... |
def ensure_dir_exists(func):
"wrap a function that returns a dir, making sure it exists"
@functools.wraps(func)
def make_if_not_present():
dir = func()
if not os.path.isdir(dir):
os.makedirs(dir)
return dir
return make_if_not_present |
def read_chunks(file, chunk_size=2048, update_func=lambda x: None):
"""
Read file in chunks of size chunk_size (or smaller).
If update_func is specified, call it on every chunk with the amount
read.
"""
while(True):
res = file.read(chunk_size)
if not res:
break
update_func(len(res))
yield re... |
def is_hidden(path):
"""
Check whether a file is presumed hidden, either because
the pathname starts with dot or because the platform
indicates such.
"""
full_path = os.path.abspath(path)
name = os.path.basename(full_path)
def no(path):
return False
platform_hidden = globals().get('is_hidden_' + ... |
def age(self):
"""
Get closer to your EOL
"""
# 0 means this composer will never decompose
if self.rounds == 1:
self.do_run = False
elif self.rounds > 1:
self.rounds -= 1 |
def run(self):
"""
Open a connection over the serial line and receive data lines
"""
if not self.device:
return
try:
data = ""
while (self.do_run):
try:
if (self.device.inWaiting() > 1):
... |
def append_main_thread(self):
"""create & start main thread
:return: None
"""
thread = MainThread(main_queue=self.main_queue,
main_spider=self.main_spider,
branch_spider=self.branch_spider)
thread.daemon = True
thre... |
def getTextFromNode(node):
"""
Scans through all children of node and gathers the
text. If node has non-text child-nodes then
NotTextNodeError is raised.
"""
t = ""
for n in node.childNodes:
if n.nodeType == n.TEXT_NODE:
t += n.nodeValue
else:
raise No... |
def getbalance(self, url='http://services.ambientmobile.co.za/credits'):
"""
Get the number of credits remaining at AmbientSMS
"""
postXMLList = []
postXMLList.append("<api-key>%s</api-key>" % self.api_key)
postXMLList.append("<password>%s</password>" % self.password)
... |
def sendmsg(self,
message,
recipient_mobiles=[],
url='http://services.ambientmobile.co.za/sms',
concatenate_message=True,
message_id=str(time()).replace(".", ""),
reply_path=None,
allow_duplicates=True,
... |
def curl(self, url, post):
"""
Inteface for sending web requests to the AmbientSMS API Server
"""
try:
req = urllib2.Request(url)
req.add_header("Content-type", "application/xml")
data = urllib2.urlopen(req, post.encode('utf-8')).read()
except ... |
def execute(self, correlation_id, args):
"""
Executes the command given specific arguments as an input.
Args:
correlation_id: a unique correlation/transaction id
args: command arguments
Returns: an execution result.
Rai... |
def contents(self, f, text):
"""
Called for each file
Must return file content
Can be wrapped
:type f: static_bundle.files.StaticFileResult
:type text: str|unicode
:rtype: str|unicode
"""
text += self._read(f.abs_path) + "\r\n"
return text |
def is_date_type(cls):
"""Return True if the class is a date type."""
if not isinstance(cls, type):
return False
return issubclass(cls, date) and not issubclass(cls, datetime) |
def to_datetime(when):
"""
Convert a date or time to a datetime. If when is a date then it sets the time to midnight. If
when is a time it sets the date to the epoch. If when is None or a datetime it returns when.
Otherwise a TypeError is raised. Returned datetimes have tzinfo set to None unless when is... |
def totz(when, tz=None):
"""
Return a date, time, or datetime converted to a datetime in the given timezone. If when is a
datetime and has no timezone it is assumed to be local time. Date and time objects are also
assumed to be UTC. The tz value defaults to UTC. Raise TypeError if when cannot be convert... |
def timeago(tz=None, *args, **kwargs):
"""Return a datetime so much time ago. Takes the same arguments as timedelta()."""
return totz(datetime.now(), tz) - timedelta(*args, **kwargs) |
def ts(when, tz=None):
"""
Return a Unix timestamp in seconds for the provided datetime. The `totz` function is called
on the datetime to convert it to the provided timezone. It will be converted to UTC if no
timezone is provided.
"""
if not when:
return None
when = totz(when, tz)
... |
def tsms(when, tz=None):
"""
Return a Unix timestamp in milliseconds for the provided datetime. The `totz` function is
called on the datetime to convert it to the provided timezone. It will be converted to UTC if
no timezone is provided.
"""
if not when:
return None
when = totz(when,... |
def fromts(ts, tzin=None, tzout=None):
"""
Return the datetime representation of the provided Unix timestamp. By defaults the timestamp is
interpreted as UTC. If tzin is set it will be interpreted as this timestamp instead. By default
the output datetime will have UTC time. If tzout is set it will be co... |
def fromtsms(ts, tzin=None, tzout=None):
"""
Return the Unix timestamp in milliseconds as a datetime object. If tz is set it will be
converted to the requested timezone otherwise it defaults to UTC.
"""
if ts is None:
return None
when = datetime.utcfromtimestamp(ts / 1000).replace(micros... |
def truncate(when, unit, week_start=mon):
"""Return the datetime truncated to the precision of the provided unit."""
if is_datetime(when):
if unit == millisecond:
return when.replace(microsecond=int(round(when.microsecond / 1000.0)) * 1000)
elif unit == second:
return whe... |
def weekday(when, weekday, start=mon):
"""Return the date for the day of this week."""
if isinstance(when, datetime):
when = when.date()
today = when.weekday()
delta = weekday - today
if weekday < start and today >= start:
delta += 7
elif weekday >= start and today < start:
... |
def prevweekday(when, weekday, inclusive=True):
"""
Return the date for the most recent day of the week. If inclusive is True (the default) today
may count as the weekday we're looking for.
"""
if isinstance(when, datetime):
when = when.date()
delta = weekday - when.weekday()
if (inc... |
def opt_normalizations(params, func, limits, abandon_threshold=100, noimprovement_threshold=1e-3,
disp=0):
"""
**optimization algorithm for scale variables (positive value of unknown magnitude)**
Each parameter is a normalization of a feature, and its value is sought.
The parameters are handled in order (assumed... |
def opt_grid(params, func, limits, ftol=0.01, disp=0, compute_errors=True):
"""
see :func:`optimize1d.optimize`, considers each parameter in order
:param ftol:
difference in values at which the function can be considered flat
:param compute_errors:
compute standard deviation of gaussian around optimum
"""
... |
def opt_grid_parallel(params, func, limits, ftol=0.01, disp=0, compute_errors=True):
"""
parallelized version of :func:`opt_grid`
"""
import multiprocessing
def spawn(f):
def fun(q_in,q_out):
while True:
i,x = q_in.get()
if i == None:
break
q_out.put((i,f(x)))
return fun
... |
def _GetNativeEolStyle(platform=sys.platform):
'''
Internal function that determines EOL_STYLE_NATIVE constant with the proper value for the
current platform.
'''
_NATIVE_EOL_STYLE_MAP = {
'win32' : EOL_STYLE_WINDOWS,
'linux2' : EOL_STYLE_UNIX,
'linux' : EOL_STYLE_UNIX,
... |
def Cwd(directory):
'''
Context manager for current directory (uses with_statement)
e.g.:
# working on some directory
with Cwd('/home/new_dir'):
# working on new_dir
# working on some directory again
:param unicode directory:
Target directory to enter
'... |
def NormalizePath(path):
'''
Normalizes a path maintaining the final slashes.
Some environment variables need the final slash in order to work.
Ex. The SOURCES_DIR set by subversion must end with a slash because of the way it is used
in the Visual Studio projects.
:param unicode path:
... |
def CanonicalPath(path):
'''
Returns a version of a path that is unique.
Given two paths path1 and path2:
CanonicalPath(path1) == CanonicalPath(path2) if and only if they represent the same file on
the host OS. Takes account of case, slashes and relative paths.
:param unicode path:
... |
def StandardizePath(path, strip=False):
'''
Replaces all slashes and backslashes with the target separator
StandardPath:
We are defining that the standard-path is the one with only back-slashes in it, either
on Windows or any other platform.
:param bool strip:
If True, removes ... |
def NormStandardPath(path):
'''
Normalizes a standard path (posixpath.normpath) maintaining any slashes at the end of the path.
Normalize:
Removes any local references in the path "/../"
StandardPath:
We are defining that the standard-path is the one with only back-slashes in it, eithe... |
def CreateMD5(source_filename, target_filename=None):
'''
Creates a md5 file from a source file (contents are the md5 hash of source file)
:param unicode source_filename:
Path to source file
:type target_filename: unicode or None
:param target_filename:
Name of the target file with... |
def CopyFile(source_filename, target_filename, override=True, md5_check=False, copy_symlink=True):
'''
Copy a file from source to target.
:param source_filename:
@see _DoCopyFile
:param target_filename:
@see _DoCopyFile
:param bool md5_check:
If True, checks md5 files (o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.