_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q265600
DescriptorPool.FindEnumTypeByName
validation
def FindEnumTypeByName(self, full_name): """Loads the named enum descriptor from the pool. Args: full_name: The full name of the enum descriptor to load. Returns: The enum descriptor for the named type. """ full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in se...
python
{ "resource": "" }
q265601
DescriptorPool.FindExtensionByName
validation
def FindExtensionByName(self, full_name): """Loads the named extension descriptor from the pool. Args: full_name: The full name of the extension descriptor to load. Returns: A FieldDescriptor, describing the named extension. """ full_name = _NormalizeFullyQualifiedName(full_name) m...
python
{ "resource": "" }
q265602
DescriptorPool._ConvertEnumDescriptor
validation
def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None, containing_type=None, scope=None): """Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf. Args: enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message. package: Opt...
python
{ "resource": "" }
q265603
DescriptorPool._MakeFieldDescriptor
validation
def _MakeFieldDescriptor(self, field_proto, message_name, index, is_extension=False): """Creates a field descriptor from a FieldDescriptorProto. For message and enum type fields, this method will do a look up in the pool for the appropriate descriptor for that type. If it is ...
python
{ "resource": "" }
q265604
get_tm_session
validation
def get_tm_session(session_factory, transaction_manager): """ Get a ``sqlalchemy.orm.Session`` instance backed by a transaction. This function will hook the session to the transaction manager which will take care of committing any changes. - When using pyramid_tm it will automatically be committed...
python
{ "resource": "" }
q265605
generate
validation
def generate(length=DEFAULT_LENGTH): """ Generate a random string of the specified length. The returned string is composed of an alphabet that shouldn't include any characters that are easily mistakeable for one another (I, 1, O, 0), and hopefully won't accidentally contain any English-language cur...
python
{ "resource": "" }
q265606
require
validation
def require(name, field, data_type): """Require that the named `field` has the right `data_type`""" if not isinstance(field, data_type): msg = '{0} must have {1}, got: {2}'.format(name, data_type, field) raise AssertionError(msg)
python
{ "resource": "" }
q265607
Client.flush
validation
def flush(self): """Forces a flush from the internal queue to the server""" queue = self.queue size = queue.qsize() queue.join() self.log.debug('successfully flushed %s items.', size)
python
{ "resource": "" }
q265608
open
validation
def open(name=None, fileobj=None, closefd=True): """ Use all decompressor possible to make the stream """ return Guesser().open(name=name, fileobj=fileobj, closefd=closefd)
python
{ "resource": "" }
q265609
marv
validation
def marv(ctx, config, loglevel, logfilter, verbosity): """Manage a Marv site""" if config is None: cwd = os.path.abspath(os.path.curdir) while cwd != os.path.sep: config = os.path.join(cwd, 'marv.conf') if os.path.exists(config): break cwd = os...
python
{ "resource": "" }
q265610
MessageSetItemDecoder
validation
def MessageSetItemDecoder(extensions_by_number): """Returns a decoder for a MessageSet item. The parameter is the _extensions_by_number map for the message class. The message set message looks like this: message MessageSet { repeated group Item = 1 { required int32 type_id = 2; require...
python
{ "resource": "" }
q265611
get_app_name
validation
def get_app_name(): """Flask like implementation of getting the applicaiton name via the filename of the including file """ fn = getattr(sys.modules['__main__'], '__file__', None) if fn is None: return '__main__' return os.path.splitext(os.path.basename(fn))[0]
python
{ "resource": "" }
q265612
get_function
validation
def get_function(function_name): """ Given a Python function name, return the function it refers to. """ module, basename = str(function_name).rsplit('.', 1) try: return getattr(__import__(module, fromlist=[basename]), basename) except (ImportError, AttributeError): raise Functio...
python
{ "resource": "" }
q265613
ViewServerRequestHandler.handle_add_fun
validation
def handle_add_fun(self, function_name): """Add a function to the function list, in order.""" function_name = function_name.strip() try: function = get_function(function_name) except Exception, exc: self.wfile.write(js_error(exc) + NEWLINE) return ...
python
{ "resource": "" }
q265614
ViewServerRequestHandler.handle_map_doc
validation
def handle_map_doc(self, document): """Return the mapping of a document according to the function list.""" # This uses the stored set of functions, sorted by order of addition. for function in sorted(self.functions.values(), key=lambda x: x[0]): try: # It has to be ru...
python
{ "resource": "" }
q265615
ViewServerRequestHandler.handle_reduce
validation
def handle_reduce(self, reduce_function_names, mapped_docs): """Reduce several mapped documents by several reduction functions.""" reduce_functions = [] # This gets a large list of reduction functions, given their names. for reduce_function_name in reduce_function_names: try:...
python
{ "resource": "" }
q265616
ViewServerRequestHandler.handle_rereduce
validation
def handle_rereduce(self, reduce_function_names, values): """Re-reduce a set of values, with a list of rereduction functions.""" # This gets a large list of reduction functions, given their names. reduce_functions = [] for reduce_function_name in reduce_function_names: try: ...
python
{ "resource": "" }
q265617
ViewServerRequestHandler.handle_validate
validation
def handle_validate(self, function_name, new_doc, old_doc, user_ctx): """Validate...this function is undocumented, but still in CouchDB.""" try: function = get_function(function_name) except Exception, exc: self.log(repr(exc)) return False try: ...
python
{ "resource": "" }
q265618
ViewServerRequestHandler.handle
validation
def handle(self): """The main function called to handle a request.""" while True: try: line = self.rfile.readline() try: # All input data are lines of JSON like the following: # ["<cmd_name>" "<cmd_arg1>" "<cmd_arg2>" ...
python
{ "resource": "" }
q265619
ViewServerRequestHandler.log
validation
def log(self, string): """Log an event on the CouchDB server.""" self.wfile.write(json.dumps({'log': string}) + NEWLINE)
python
{ "resource": "" }
q265620
guid
validation
def guid(*args): """ Generates a universally unique ID. Any arguments only create more randomness. """ t = float(time.time() * 1000) r = float(random.random()*10000000000000) a = random.random() * 10000000000000 data = str(t) + ' ' + str(r) + ' ' + str(a) + ' ' + str(args) data = ha...
python
{ "resource": "" }
q265621
AsyncProauth2.revoke_token
validation
def revoke_token(self, token, callback): ''' revoke_token removes the access token from the data_store ''' yield Task(self.data_store.remove, 'tokens', token=token) callback()
python
{ "resource": "" }
q265622
AsyncProauth2._auth
validation
def _auth(self, client_id, key, method, callback): ''' _auth - internal method to ensure the client_id and client_secret passed with the nonce match ''' available = auth_methods.keys() if method not in available: raise Proauth2Error('invalid_request', ...
python
{ "resource": "" }
q265623
AsyncProauth2._validate_request_code
validation
def _validate_request_code(self, code, client_id, callback): ''' _validate_request_code - internal method for verifying the the given nonce. also removes the nonce from the data_store, as they are intended for one-time use. ''' nonce = yield Task(self.data_store.fetch, 'n...
python
{ "resource": "" }
q265624
AsyncProauth2._generate_token
validation
def _generate_token(self, length=32): ''' _generate_token - internal function for generating randomized alphanumberic strings of a given length ''' return ''.join(choice(ascii_letters + digits) for x in range(length))
python
{ "resource": "" }
q265625
merge_ordered
validation
def merge_ordered(ordereds: typing.Iterable[typing.Any]) -> typing.Iterable[typing.Any]: """Merge multiple ordered so that within-ordered order is preserved """ seen_set = set() add_seen = seen_set.add return reversed(tuple(map( lambda obj: add_seen(obj) or obj, filterfalse( ...
python
{ "resource": "" }
q265626
validate_params
validation
def validate_params(required, optional, params): """ Helps us validate the parameters for the request :param valid_options: a list of strings of valid options for the api request :param params: a dict, the key-value store which we really only care about the ...
python
{ "resource": "" }
q265627
FileAge.__get_current_datetime
validation
def __get_current_datetime(self): """Get current datetime for every file.""" self.wql_time = "SELECT LocalDateTime FROM Win32_OperatingSystem" self.current_time = self.query(self.wql_time) # [{'LocalDateTime': '20160824161431.977000+480'}]' self.current_time_string = str( ...
python
{ "resource": "" }
q265628
BranchThread.run
validation
def run(self): """run your main spider here as for branch spider result data, you can return everything or do whatever with it in your own code :return: None """ config = config_creator() debug = config.debug branch_thread_sleep = config.branch_thread_sle...
python
{ "resource": "" }
q265629
get_version
validation
def get_version(relpath): """Read version info from a file without importing it""" from os.path import dirname, join if '__file__' not in globals(): # Allow to use function interactively root = '.' else: root = dirname(__file__) # The code below reads text file with unknown...
python
{ "resource": "" }
q265630
MakeDescriptor
validation
def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True, syntax=None): """Make a protobuf Descriptor given a DescriptorProto protobuf. Handles nested descriptors. Note that this is limited to the scope of defining a message inside of another message. Composite fields can currently on...
python
{ "resource": "" }
q265631
_NestedDescriptorBase.GetTopLevelContainingType
validation
def GetTopLevelContainingType(self): """Returns the root if this is a nested type, or itself if its the root.""" desc = self while desc.containing_type is not None: desc = desc.containing_type return desc
python
{ "resource": "" }
q265632
ServiceDescriptor.FindMethodByName
validation
def FindMethodByName(self, name): """Searches for the specified method, and returns its descriptor.""" for method in self.methods: if name == method.name: return method return None
python
{ "resource": "" }
q265633
MessageToJson
validation
def MessageToJson(message, including_default_value_fields=False): """Converts protobuf message to JSON format. Args: message: The protocol buffers message instance to serialize. including_default_value_fields: If True, singular primitive fields, repeated fields, and map fields will always be serial...
python
{ "resource": "" }
q265634
_MessageToJsonObject
validation
def _MessageToJsonObject(message, including_default_value_fields): """Converts message to an object according to Proto3 JSON Specification.""" message_descriptor = message.DESCRIPTOR full_name = message_descriptor.full_name if _IsWrapperMessage(message_descriptor): return _WrapperMessageToJsonObject(message...
python
{ "resource": "" }
q265635
_StructMessageToJsonObject
validation
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
python
{ "resource": "" }
q265636
Parse
validation
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...
python
{ "resource": "" }
q265637
_ConvertFieldValuePair
validation
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 = ...
python
{ "resource": "" }
q265638
_ConvertMessage
validation
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...
python
{ "resource": "" }
q265639
_ConvertValueMessage
validation
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 = ...
python
{ "resource": "" }
q265640
_ConvertListValueMessage
validation
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...
python
{ "resource": "" }
q265641
_ConvertStructMessage
validation
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
python
{ "resource": "" }
q265642
update_config
validation
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 ...
python
{ "resource": "" }
q265643
Timing.end_timing
validation
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)
python
{ "resource": "" }
q265644
Duration.ToJsonString
validation
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....
python
{ "resource": "" }
q265645
Duration.FromJsonString
validation
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: ...
python
{ "resource": "" }
q265646
FieldMask.FromJsonString
validation
def FromJsonString(self, value): """Converts string to FieldMask according to proto3 JSON spec.""" self.Clear() for path in value.split(','): self.paths.append(path)
python
{ "resource": "" }
q265647
get_doc
validation
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) ...
python
{ "resource": "" }
q265648
read
validation
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')
python
{ "resource": "" }
q265649
DataStore.remove
validation
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()
python
{ "resource": "" }
q265650
TrelloAPI._url
validation
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...
python
{ "resource": "" }
q265651
TrelloAPI._api_call
validation
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...
python
{ "resource": "" }
q265652
_SkipFieldValue
validation
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...
python
{ "resource": "" }
q265653
ParseInteger
validation
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...
python
{ "resource": "" }
q265654
_Printer.PrintMessage
validation
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): ...
python
{ "resource": "" }
q265655
_Parser._ParseOrMerge
validation
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 =...
python
{ "resource": "" }
q265656
_Parser._MergeMessageField
validation
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...
python
{ "resource": "" }
q265657
_Tokenizer.ConsumeIdentifier
validation
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.') ...
python
{ "resource": "" }
q265658
_Tokenizer.ConsumeInt32
validation
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...
python
{ "resource": "" }
q265659
_Tokenizer.ConsumeFloat
validation
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...
python
{ "resource": "" }
q265660
_Tokenizer.ConsumeBool
validation
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...
python
{ "resource": "" }
q265661
_Tokenizer._ConsumeSingleByteString
validation
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: ...
python
{ "resource": "" }
q265662
arkt_to_unixt
validation
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()
python
{ "resource": "" }
q265663
Mssql.close
validation
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)
python
{ "resource": "" }
q265664
Preprocessor.process_macros
validation
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...
python
{ "resource": "" }
q265665
get_unique_pathname
validation
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)) ...
python
{ "resource": "" }
q265666
__get_numbered_paths
validation
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))
python
{ "resource": "" }
q265667
splitext_files_only
validation
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) )
python
{ "resource": "" }
q265668
set_time
validation
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...
python
{ "resource": "" }
q265669
get_time
validation
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)
python
{ "resource": "" }
q265670
ensure_dir_exists
validation
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
python
{ "resource": "" }
q265671
is_hidden
validation
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_' + ...
python
{ "resource": "" }
q265672
SerialReader.age
validation
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
python
{ "resource": "" }
q265673
SerialReader.run
validation
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): ...
python
{ "resource": "" }
q265674
ThreadCreator.append_main_thread
validation
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...
python
{ "resource": "" }
q265675
getTextFromNode
validation
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...
python
{ "resource": "" }
q265676
AmbientSMS.getbalance
validation
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) ...
python
{ "resource": "" }
q265677
AmbientSMS.sendmsg
validation
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, ...
python
{ "resource": "" }
q265678
AmbientSMS.curl
validation
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 ...
python
{ "resource": "" }
q265679
DefaultMinifier.contents
validation
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
python
{ "resource": "" }
q265680
is_date_type
validation
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)
python
{ "resource": "" }
q265681
to_datetime
validation
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...
python
{ "resource": "" }
q265682
totz
validation
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...
python
{ "resource": "" }
q265683
ts
validation
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) ...
python
{ "resource": "" }
q265684
tsms
validation
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,...
python
{ "resource": "" }
q265685
fromts
validation
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...
python
{ "resource": "" }
q265686
fromtsms
validation
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...
python
{ "resource": "" }
q265687
truncate
validation
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...
python
{ "resource": "" }
q265688
weekday
validation
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: ...
python
{ "resource": "" }
q265689
_GetNativeEolStyle
validation
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, ...
python
{ "resource": "" }
q265690
NormalizePath
validation
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: ...
python
{ "resource": "" }
q265691
CanonicalPath
validation
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: ...
python
{ "resource": "" }
q265692
StandardizePath
validation
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 ...
python
{ "resource": "" }
q265693
CopyFile
validation
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...
python
{ "resource": "" }
q265694
_CopyFileLocal
validation
def _CopyFileLocal(source_filename, target_filename, copy_symlink=True): ''' Copy a file locally to a directory. :param unicode source_filename: The filename to copy from. :param unicode target_filename: The filename to copy to. :param bool copy_symlink: If True and source...
python
{ "resource": "" }
q265695
CopyFiles
validation
def CopyFiles(source_dir, target_dir, create_target_dir=False, md5_check=False): ''' Copy files from the given source to the target. :param unicode source_dir: A filename, URL or a file mask. Ex. x:\coilib50 x:\coilib50\* http://server/directory/file ...
python
{ "resource": "" }
q265696
CopyFilesX
validation
def CopyFilesX(file_mapping): ''' Copies files into directories, according to a file mapping :param list(tuple(unicode,unicode)) file_mapping: A list of mappings between the directory in the target and the source. For syntax, @see: ExtendedPathMask :rtype: list(tuple(unicode,unicode)) ...
python
{ "resource": "" }
q265697
CopyDirectory
validation
def CopyDirectory(source_dir, target_dir, override=False): ''' Recursively copy a directory tree. :param unicode source_dir: Where files will come from :param unicode target_dir: Where files will go to :param bool override: If True and target_dir already exists, it will be...
python
{ "resource": "" }
q265698
DeleteFile
validation
def DeleteFile(target_filename): ''' Deletes the given local filename. .. note:: If file doesn't exist this method has no effect. :param unicode target_filename: A local filename :raises NotImplementedForRemotePathError: If trying to delete a non-local path :raises FileOnlyAc...
python
{ "resource": "" }
q265699
AppendToFile
validation
def AppendToFile(filename, contents, eol_style=EOL_STYLE_NATIVE, encoding=None, binary=False): ''' Appends content to a local file. :param unicode filename: :param unicode contents: :type eol_style: EOL_STYLE_XXX constant :param eol_style: Replaces the EOL by the appropriate EOL depen...
python
{ "resource": "" }