_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q26500
_arithmetic_helper
train
def _arithmetic_helper( a: "BitVecFunc", b: Union[BitVec, int], operation: Callable ) -> "BitVecFunc": """ Helper function for arithmetic operations on BitVecFuncs. :param a: The BitVecFunc to perform the operation on. :param b: A BitVec or int to perform the operation on. :param operation: The arithmetic operation to perform. :return: The resulting BitVecFunc """ if isinstance(b, int): b = BitVec(z3.BitVecVal(b, a.size())) raw = operation(a.raw, b.raw) union = a.annotations + b.annotations if isinstance(b, BitVecFunc): # TODO: Find better value to set input and name to in this case? return BitVecFunc(raw=raw, func_name=None, input_=None, annotations=union) return BitVecFunc( raw=raw, func_name=a.func_name, input_=a.input_, annotations=union )
python
{ "resource": "" }
q26501
_comparison_helper
train
def _comparison_helper( a: "BitVecFunc", b: Union[BitVec, int], operation: Callable, default_value: bool, inputs_equal: bool, ) -> Bool: """ Helper function for comparison operations with BitVecFuncs. :param a: The BitVecFunc to compare. :param b: A BitVec or int to compare to. :param operation: The comparison operation to perform. :return: The resulting Bool """ # Is there some hack for gt/lt comparisons? if isinstance(b, int): b = BitVec(z3.BitVecVal(b, a.size())) union = a.annotations + b.annotations if not a.symbolic and not b.symbolic: return Bool(z3.BoolVal(operation(a.value, b.value)), annotations=union) if ( not isinstance(b, BitVecFunc) or not a.func_name or not a.input_ or not a.func_name == b.func_name ): return Bool(z3.BoolVal(default_value), annotations=union) return And( Bool(cast(z3.BoolRef, operation(a.raw, b.raw)), annotations=union), a.input_ == b.input_ if inputs_equal else a.input_ != b.input_, )
python
{ "resource": "" }
q26502
Expression.annotate
train
def annotate(self, annotation: Any) -> None: """Annotates this expression with the given annotation. :param annotation: """ if isinstance(annotation, list): self._annotations += annotation else: self._annotations.append(annotation)
python
{ "resource": "" }
q26503
Expression.simplify
train
def simplify(self) -> None: """Simplify this expression.""" self.raw = cast(T, z3.simplify(self.raw))
python
{ "resource": "" }
q26504
execute_message_call
train
def execute_message_call( laser_evm, callee_address, caller_address, origin_address, code, data, gas_limit, gas_price, value, track_gas=False, ) -> Union[None, List[GlobalState]]: """Execute a message call transaction from all open states. :param laser_evm: :param callee_address: :param caller_address: :param origin_address: :param code: :param data: :param gas_limit: :param gas_price: :param value: :param track_gas: :return: """ # TODO: Resolve circular import between .transaction and ..svm to import LaserEVM here open_states = laser_evm.open_states[:] del laser_evm.open_states[:] for open_world_state in open_states: next_transaction_id = get_next_transaction_id() transaction = MessageCallTransaction( world_state=open_world_state, identifier=next_transaction_id, gas_price=gas_price, gas_limit=gas_limit, origin=origin_address, code=Disassembly(code), caller=caller_address, callee_account=open_world_state[callee_address], call_data=ConcreteCalldata(next_transaction_id, data), call_value=value, ) _setup_global_state_for_execution(laser_evm, transaction) return laser_evm.exec(track_gas=track_gas)
python
{ "resource": "" }
q26505
detect_mode
train
def detect_mode(term_hint="xterm-256color"): """Poor-mans color mode detection.""" if "ANSICON" in os.environ: return 16 elif os.environ.get("ConEmuANSI", "OFF") == "ON": return 256 else: term = os.environ.get("TERM", term_hint) if term.endswith("-256color") or term in ("xterm", "screen"): return 256 elif term.endswith("-color") or term in ("rxvt",): return 16 else: return 256
python
{ "resource": "" }
q26506
Account.blank_account
train
def blank_account(cls, db, addr, initial_nonce=0): """creates a blank account. :param db: :param addr: :param initial_nonce: :return: """ db.put(BLANK_HASH, b"") o = cls(initial_nonce, 0, trie.BLANK_ROOT, BLANK_HASH, db, addr) o.existent_at_start = False return o
python
{ "resource": "" }
q26507
State.get_and_cache_account
train
def get_and_cache_account(self, addr): """Gets and caches an account for an addres, creates blank if not found. :param addr: :return: """ if addr in self.cache: return self.cache[addr] rlpdata = self.secure_trie.get(addr) if ( rlpdata == trie.BLANK_NODE and len(addr) == 32 ): # support for hashed addresses rlpdata = self.trie.get(addr) if rlpdata != trie.BLANK_NODE: o = rlp.decode(rlpdata, Account, db=self.db, addr=addr) else: o = Account.blank_account(self.db, addr, 0) self.cache[addr] = o o._mutable = True o._cached_rlp = None return o
python
{ "resource": "" }
q26508
State.get_all_accounts
train
def get_all_accounts(self): """iterates through trie to and yields non-blank leafs as accounts.""" for address_hash, rlpdata in self.secure_trie.trie.iter_branch(): if rlpdata != trie.BLANK_NODE: yield rlp.decode(rlpdata, Account, db=self.db, addr=address_hash)
python
{ "resource": "" }
q26509
BaseCalldata.get_word_at
train
def get_word_at(self, offset: int) -> Expression: """Gets word at offset. :param offset: :return: """ parts = self[offset : offset + 32] return simplify(Concat(parts))
python
{ "resource": "" }
q26510
MutationPruner.initialize
train
def initialize(self, symbolic_vm: LaserEVM): """Initializes the mutation pruner Introduces hooks for SSTORE operations :param symbolic_vm: :return: """ @symbolic_vm.pre_hook("SSTORE") def mutator_hook(global_state: GlobalState): global_state.annotate(MutationAnnotation()) @symbolic_vm.laser_hook("add_world_state") def world_state_filter_hook(global_state: GlobalState): if And( *global_state.mstate.constraints[:] + [ global_state.environment.callvalue > symbol_factory.BitVecVal(0, 256) ] ).is_false: return if isinstance( global_state.current_transaction, ContractCreationTransaction ): return if len(list(global_state.get_annotations(MutationAnnotation))) == 0: raise PluginSkipWorldState
python
{ "resource": "" }
q26511
CoverageStrategy._is_covered
train
def _is_covered(self, global_state: GlobalState) -> bool: """ Checks if the instruction for the given global state is already covered""" bytecode = global_state.environment.code.bytecode index = global_state.mstate.pc return self.instruction_coverage_plugin.is_instruction_covered(bytecode, index)
python
{ "resource": "" }
q26512
_SmtSymbolFactory.BitVecFuncVal
train
def BitVecFuncVal( value: int, func_name: str, size: int, annotations: Annotations = None, input_: Union[int, "BitVec"] = None, ) -> BitVecFunc: """Creates a new bit vector function with a concrete value.""" raw = z3.BitVecVal(value, size) return BitVecFunc(raw, func_name, input_, annotations)
python
{ "resource": "" }
q26513
MachineState.mem_extend
train
def mem_extend(self, start: int, size: int) -> None: """Extends the memory of this machine state. :param start: Start of memory extension :param size: Size of memory extension """ m_extend = self.calculate_extension_size(start, size) if m_extend: extend_gas = self.calculate_memory_gas(start, size) self.min_gas_used += extend_gas self.max_gas_used += extend_gas self.check_gas() self.memory.extend(m_extend)
python
{ "resource": "" }
q26514
MachineState.memory_write
train
def memory_write(self, offset: int, data: List[Union[int, BitVec]]) -> None: """Writes data to memory starting at offset. :param offset: :param data: """ self.mem_extend(offset, len(data)) self.memory[offset : offset + len(data)] = data
python
{ "resource": "" }
q26515
MachineState.pop
train
def pop(self, amount=1) -> Union[BitVec, List[BitVec]]: """Pops amount elements from the stack. :param amount: :return: """ if amount > len(self.stack): raise StackUnderflowException values = self.stack[-amount:][::-1] del self.stack[-amount:] return values[0] if amount == 1 else values
python
{ "resource": "" }
q26516
If
train
def If(a: Union[Bool, bool], b: Union[BitVec, int], c: Union[BitVec, int]) -> BitVec: """Create an if-then-else expression. :param a: :param b: :param c: :return: """ # TODO: Handle BitVecFunc if not isinstance(a, Bool): a = Bool(z3.BoolVal(a)) if not isinstance(b, BitVec): b = BitVec(z3.BitVecVal(b, 256)) if not isinstance(c, BitVec): c = BitVec(z3.BitVecVal(c, 256)) union = a.annotations + b.annotations + c.annotations return BitVec(z3.If(a.raw, b.raw, c.raw), union)
python
{ "resource": "" }
q26517
UGT
train
def UGT(a: BitVec, b: BitVec) -> Bool: """Create an unsigned greater than expression. :param a: :param b: :return: """ return _comparison_helper(a, b, z3.UGT, default_value=False, inputs_equal=False)
python
{ "resource": "" }
q26518
UGE
train
def UGE(a: BitVec, b: BitVec) -> Bool: """Create an unsigned greater or equals expression. :param a: :param b: :return: """ return Or(UGT(a, b), a == b)
python
{ "resource": "" }
q26519
ULE
train
def ULE(a: BitVec, b: BitVec) -> Bool: """Create an unsigned less than expression. :param a: :param b: :return: """ return Or(ULT(a, b), a == b)
python
{ "resource": "" }
q26520
Concat
train
def Concat(*args: Union[BitVec, List[BitVec]]) -> BitVec: """Create a concatenation expression. :param args: :return: """ # The following statement is used if a list is provided as an argument to concat if len(args) == 1 and isinstance(args[0], list): bvs = args[0] # type: List[BitVec] else: bvs = cast(List[BitVec], args) nraw = z3.Concat([a.raw for a in bvs]) annotations = [] # type: Annotations bitvecfunc = False for bv in bvs: annotations += bv.annotations if isinstance(bv, BitVecFunc): bitvecfunc = True if bitvecfunc: # Is there a better value to set func_name and input to in this case? return BitVecFunc( raw=nraw, func_name=None, input_=None, annotations=annotations ) return BitVec(nraw, annotations)
python
{ "resource": "" }
q26521
Extract
train
def Extract(high: int, low: int, bv: BitVec) -> BitVec: """Create an extract expression. :param high: :param low: :param bv: :return: """ raw = z3.Extract(high, low, bv.raw) if isinstance(bv, BitVecFunc): # Is there a better value to set func_name and input to in this case? return BitVecFunc( raw=raw, func_name=None, input_=None, annotations=bv.annotations ) return BitVec(raw, annotations=bv.annotations)
python
{ "resource": "" }
q26522
URem
train
def URem(a: BitVec, b: BitVec) -> BitVec: """Create an unsigned remainder expression. :param a: :param b: :return: """ return _arithmetic_helper(a, b, z3.URem)
python
{ "resource": "" }
q26523
SRem
train
def SRem(a: BitVec, b: BitVec) -> BitVec: """Create a signed remainder expression. :param a: :param b: :return: """ return _arithmetic_helper(a, b, z3.SRem)
python
{ "resource": "" }
q26524
UDiv
train
def UDiv(a: BitVec, b: BitVec) -> BitVec: """Create an unsigned division expression. :param a: :param b: :return: """ return _arithmetic_helper(a, b, z3.UDiv)
python
{ "resource": "" }
q26525
Sum
train
def Sum(*args: BitVec) -> BitVec: """Create sum expression. :return: """ raw = z3.Sum([a.raw for a in args]) annotations = [] # type: Annotations bitvecfuncs = [] for bv in args: annotations += bv.annotations if isinstance(bv, BitVecFunc): bitvecfuncs.append(bv) if len(bitvecfuncs) >= 2: return BitVecFunc(raw=raw, func_name=None, input_=None, annotations=annotations) elif len(bitvecfuncs) == 1: return BitVecFunc( raw=raw, func_name=bitvecfuncs[0].func_name, input_=bitvecfuncs[0].input_, annotations=annotations, ) return BitVec(raw, annotations)
python
{ "resource": "" }
q26526
BVAddNoOverflow
train
def BVAddNoOverflow(a: Union[BitVec, int], b: Union[BitVec, int], signed: bool) -> Bool: """Creates predicate that verifies that the addition doesn't overflow. :param a: :param b: :param signed: :return: """ if not isinstance(a, BitVec): a = BitVec(z3.BitVecVal(a, 256)) if not isinstance(b, BitVec): b = BitVec(z3.BitVecVal(b, 256)) return Bool(z3.BVAddNoOverflow(a.raw, b.raw, signed))
python
{ "resource": "" }
q26527
BitVec.symbolic
train
def symbolic(self) -> bool: """Returns whether this symbol doesn't have a concrete value. :return: """ self.simplify() return not isinstance(self.raw, z3.BitVecNumRef)
python
{ "resource": "" }
q26528
BitVec.value
train
def value(self) -> Optional[int]: """Returns the value of this symbol if concrete, otherwise None. :return: """ if self.symbolic: return None assert isinstance(self.raw, z3.BitVecNumRef) return self.raw.as_long()
python
{ "resource": "" }
q26529
MessageCallTransaction.initial_global_state
train
def initial_global_state(self) -> GlobalState: """Initialize the execution environment.""" environment = Environment( self.callee_account, self.caller, self.call_data, self.gas_price, self.call_value, self.origin, code=self.code or self.callee_account.code, ) return super().initial_global_state_from_environment( environment, active_function="fallback" )
python
{ "resource": "" }
q26530
Issue._set_internal_compiler_error
train
def _set_internal_compiler_error(self): """ Adds the false positive to description and changes severity to low """ self.severity = "Low" self.description_tail += ( " This issue is reported for internal compiler generated code." ) self.description = "%s\n%s" % (self.description_head, self.description_tail) self.code = ""
python
{ "resource": "" }
q26531
Report.as_swc_standard_format
train
def as_swc_standard_format(self): """Format defined for integration and correlation. :return: """ _issues = [] source_list = [] for key, issue in self.issues.items(): idx = self.source.get_source_index(issue.bytecode_hash) try: title = SWC_TO_TITLE[issue.swc_id] except KeyError: title = "Unspecified Security Issue" _issues.append( { "swcID": "SWC-" + issue.swc_id, "swcTitle": title, "description": { "head": issue.description_head, "tail": issue.description_tail, }, "severity": issue.severity, "locations": [{"sourceMap": "%d:1:%d" % (issue.address, idx)}], "extra": {"discoveryTime": int(issue.discovery_time * 10 ** 9)}, } ) meta_data = self._get_exception_data() result = [ { "issues": _issues, "sourceType": self.source.source_type, "sourceFormat": self.source.source_format, "sourceList": self.source.source_list, "meta": meta_data, } ] return json.dumps(result, sort_keys=True)
python
{ "resource": "" }
q26532
Instruction.evaluate
train
def evaluate(self, global_state: GlobalState, post=False) -> List[GlobalState]: """Performs the mutation for this instruction. :param global_state: :param post: :return: """ # Generalize some ops log.debug("Evaluating {}".format(self.op_code)) op = self.op_code.lower() if self.op_code.startswith("PUSH"): op = "push" elif self.op_code.startswith("DUP"): op = "dup" elif self.op_code.startswith("SWAP"): op = "swap" elif self.op_code.startswith("LOG"): op = "log" instruction_mutator = ( getattr(self, op + "_", None) if not post else getattr(self, op + "_" + "post", None) ) if instruction_mutator is None: raise NotImplementedError if self.iprof is None: result = instruction_mutator(global_state) else: start_time = datetime.now() result = instruction_mutator(global_state) end_time = datetime.now() self.iprof.record(op, start_time, end_time) return result
python
{ "resource": "" }
q26533
Optimize.minimize
train
def minimize(self, element: Expression[z3.ExprRef]) -> None: """In solving this solver will try to minimize the passed expression. :param element: """ self.raw.minimize(element.raw)
python
{ "resource": "" }
q26534
Optimize.maximize
train
def maximize(self, element: Expression[z3.ExprRef]) -> None: """In solving this solver will try to maximize the passed expression. :param element: """ self.raw.maximize(element.raw)
python
{ "resource": "" }
q26535
Model.decls
train
def decls(self) -> List[z3.ExprRef]: """Get the declarations for this model""" result = [] # type: List[z3.ExprRef] for internal_model in self.raw: result.extend(internal_model.decls()) return result
python
{ "resource": "" }
q26536
Model.eval
train
def eval( self, expression: z3.ExprRef, model_completion: bool = False ) -> Union[None, z3.ExprRef]: """ Evaluate the expression using this model :param expression: The expression to evaluate :param model_completion: Use the default value if the model has no interpretation of the given expression :return: The evaluated expression """ for internal_model in self.raw: is_last_model = self.raw.index(internal_model) == len(self.raw) - 1 is_relevant_model = expression.decl() in list(internal_model.decls()) if is_relevant_model or is_last_model: return internal_model.eval(expression, model_completion) return None
python
{ "resource": "" }
q26537
LaserEVM._execute_transactions
train
def _execute_transactions(self, address): """This function executes multiple transactions on the address :param address: Address of the contract :return: """ for i in range(self.transaction_count): self.time = datetime.now() log.info( "Starting message call transaction, iteration: {}, {} initial states".format( i, len(self.open_states) ) ) for hook in self._start_sym_trans_hooks: hook() execute_message_call(self, address) for hook in self._stop_sym_trans_hooks: hook()
python
{ "resource": "" }
q26538
LaserEVM._add_world_state
train
def _add_world_state(self, global_state: GlobalState): """ Stores the world_state of the passed global state in the open states""" for hook in self._add_world_state_hooks: try: hook(global_state) except PluginSkipWorldState: return self.open_states.append(global_state.world_state)
python
{ "resource": "" }
q26539
LaserEVM.register_laser_hooks
train
def register_laser_hooks(self, hook_type: str, hook: Callable): """registers the hook with this Laser VM""" if hook_type == "add_world_state": self._add_world_state_hooks.append(hook) elif hook_type == "execute_state": self._execute_state_hooks.append(hook) elif hook_type == "start_sym_exec": self._start_sym_exec_hooks.append(hook) elif hook_type == "stop_sym_exec": self._stop_sym_exec_hooks.append(hook) elif hook_type == "start_sym_trans": self._start_sym_trans_hooks.append(hook) elif hook_type == "stop_sym_trans": self._stop_sym_trans_hooks.append(hook) else: raise ValueError( "Invalid hook type %s. Must be one of {add_world_state}", hook_type )
python
{ "resource": "" }
q26540
LaserEVM.laser_hook
train
def laser_hook(self, hook_type: str) -> Callable: """Registers the annotated function with register_laser_hooks :param hook_type: :return: hook decorator """ def hook_decorator(func: Callable): """ Hook decorator generated by laser_hook :param func: Decorated function """ self.register_laser_hooks(hook_type, func) return func return hook_decorator
python
{ "resource": "" }
q26541
GlobalState.get_current_instruction
train
def get_current_instruction(self) -> Dict: """Gets the current instruction for this GlobalState. :return: """ instructions = self.environment.code.instruction_list return instructions[self.mstate.pc]
python
{ "resource": "" }
q26542
OAuthHandler.get_oauth_request
train
def get_oauth_request(self): """Return an OAuth Request object for the current request.""" try: method = os.environ['REQUEST_METHOD'] except: method = 'GET' postdata = None if method in ('POST', 'PUT'): postdata = self.request.body return oauth.Request.from_request(method, self.request.uri, headers=self.request.headers, query_string=postdata)
python
{ "resource": "" }
q26543
OAuthHandler.get_client
train
def get_client(self, request=None): """Return the client from the OAuth parameters.""" if not isinstance(request, oauth.Request): request = self.get_oauth_request() client_key = request.get_parameter('oauth_consumer_key') if not client_key: raise Exception('Missing "oauth_consumer_key" parameter in ' \ 'OAuth "Authorization" header') client = models.Client.get_by_key_name(client_key) if not client: raise Exception('Client "%s" not found.' % client_key) return client
python
{ "resource": "" }
q26544
OAuthHandler.is_valid
train
def is_valid(self): """Returns a Client object if this is a valid OAuth request.""" try: request = self.get_oauth_request() client = self.get_client(request) params = self._server.verify_request(request, client, None) except Exception as e: raise e return client
python
{ "resource": "" }
q26545
to_unicode_optional_iterator
train
def to_unicode_optional_iterator(x): """ Raise TypeError if x is a str containing non-utf8 bytes or if x is an iterable which contains such a str. """ if isinstance(x, STRING_TYPES): return to_unicode(x) try: l = list(x) except TypeError as e: assert 'is not iterable' in str(e) return x else: return [ to_unicode(e) for e in l ]
python
{ "resource": "" }
q26546
to_utf8_optional_iterator
train
def to_utf8_optional_iterator(x): """ Raise TypeError if x is a str or if x is an iterable which contains a str. """ if isinstance(x, STRING_TYPES): return to_utf8(x) try: l = list(x) except TypeError as e: assert 'is not iterable' in str(e) return x else: return [ to_utf8_if_string(e) for e in l ]
python
{ "resource": "" }
q26547
generate_nonce
train
def generate_nonce(length=8): """Generate pseudorandom number.""" return ''.join([str(random.SystemRandom().randint(0, 9)) for i in range(length)])
python
{ "resource": "" }
q26548
Token.to_string
train
def to_string(self): """Returns this token as a plain string, suitable for storage. The resulting string includes the token's secret, so you should never send or store this string where a third party can read it. """ items = [ ('oauth_token', self.key), ('oauth_token_secret', self.secret), ] if self.callback_confirmed is not None: items.append(('oauth_callback_confirmed', self.callback_confirmed)) return urlencode(items)
python
{ "resource": "" }
q26549
Request.get_nonoauth_parameters
train
def get_nonoauth_parameters(self): """Get any non-OAuth parameters.""" return dict([(k, v) for k, v in self.items() if not k.startswith('oauth_')])
python
{ "resource": "" }
q26550
Request.to_header
train
def to_header(self, realm=''): """Serialize as a header for an HTTPAuth request.""" oauth_params = ((k, v) for k, v in self.items() if k.startswith('oauth_')) stringy_params = ((k, escape(v)) for k, v in oauth_params) header_params = ('%s="%s"' % (k, v) for k, v in stringy_params) params_header = ', '.join(header_params) auth_header = 'OAuth realm="%s"' % realm if params_header: auth_header = "%s, %s" % (auth_header, params_header) return {'Authorization': auth_header}
python
{ "resource": "" }
q26551
Request.get_normalized_parameters
train
def get_normalized_parameters(self): """Return a string that contains the parameters that must be signed.""" items = [] for key, value in self.items(): if key == 'oauth_signature': continue # 1.0a/9.1.1 states that kvp must be sorted by key, then by value, # so we unpack sequence values into multiple items for sorting. if isinstance(value, STRING_TYPES): items.append((to_utf8_if_string(key), to_utf8(value))) else: try: value = list(value) except TypeError as e: assert 'is not iterable' in str(e) items.append((to_utf8_if_string(key), to_utf8_if_string(value))) else: items.extend((to_utf8_if_string(key), to_utf8_if_string(item)) for item in value) # Include any query string parameters from the provided URL query = urlparse(self.url)[4] url_items = self._split_url_string(query).items() url_items = [(to_utf8(k), to_utf8_optional_iterator(v)) for k, v in url_items if k != 'oauth_signature' ] items.extend(url_items) items.sort() encoded_str = urlencode(items, True) # Encode signature parameters per Oauth Core 1.0 protocol # spec draft 7, section 3.6 # (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6) # Spaces must be encoded with "%20" instead of "+" return encoded_str.replace('+', '%20').replace('%7E', '~')
python
{ "resource": "" }
q26552
Request.sign_request
train
def sign_request(self, signature_method, consumer, token): """Set the signature parameter to the result of sign.""" if not self.is_form_encoded: # according to # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html # section 4.1.1 "OAuth Consumers MUST NOT include an # oauth_body_hash parameter on requests with form-encoded # request bodies." if not self.body: self.body = '' self['oauth_body_hash'] = base64.b64encode(sha1(to_utf8(self.body)).digest()) if 'oauth_consumer_key' not in self: self['oauth_consumer_key'] = consumer.key if token and 'oauth_token' not in self: self['oauth_token'] = token.key self['oauth_signature_method'] = signature_method.name self['oauth_signature'] = signature_method.sign(self, consumer, token)
python
{ "resource": "" }
q26553
Request.from_request
train
def from_request(cls, http_method, http_url, headers=None, parameters=None, query_string=None): """Combines multiple parameter sources.""" if parameters is None: parameters = {} # Headers if headers: auth_header = None for k, v in headers.items(): if k.lower() == 'authorization' or \ k.upper() == 'HTTP_AUTHORIZATION': auth_header = v # Check that the authorization header is OAuth. if auth_header and auth_header[:6] == 'OAuth ': auth_header = auth_header[6:] try: # Get the parameters from the header. header_params = cls._split_header(auth_header) parameters.update(header_params) except: raise Error('Unable to parse OAuth parameters from ' 'Authorization header.') # GET or POST query string. if query_string: query_params = cls._split_url_string(query_string) parameters.update(query_params) # URL parameters. param_str = urlparse(http_url)[4] # query url_params = cls._split_url_string(param_str) parameters.update(url_params) if parameters: return cls(http_method, http_url, parameters) return None
python
{ "resource": "" }
q26554
Request._split_url_string
train
def _split_url_string(param_str): """Turn URL string into parameters.""" if not PY3: # If passed unicode with quoted UTF8, Python2's parse_qs leaves # mojibake'd uniocde after unquoting, so encode first. param_str = b(param_str, 'utf-8') parameters = parse_qs(param_str, keep_blank_values=True) for k, v in parameters.items(): if len(v) == 1: parameters[k] = unquote(v[0]) else: parameters[k] = sorted([unquote(s) for s in v]) return parameters
python
{ "resource": "" }
q26555
Server.verify_request
train
def verify_request(self, request, consumer, token): """Verifies an api call and checks all the parameters.""" self._check_version(request) self._check_signature(request, consumer, token) parameters = request.get_nonoauth_parameters() return parameters
python
{ "resource": "" }
q26556
Server._check_version
train
def _check_version(self, request): """Verify the correct version of the request for this server.""" version = self._get_version(request) if version and version != self.version: raise Error('OAuth version %s not supported.' % str(version))
python
{ "resource": "" }
q26557
Server._get_signature_method
train
def _get_signature_method(self, request): """Figure out the signature with some defaults.""" signature_method = request.get('oauth_signature_method') if signature_method is None: signature_method = SIGNATURE_METHOD try: # Get the signature method object. return self.signature_methods[signature_method] except KeyError: signature_method_names = ', '.join(self.signature_methods.keys()) raise Error('Signature method %s not supported try one of the ' 'following: %s' % (signature_method, signature_method_names))
python
{ "resource": "" }
q26558
Server._check_timestamp
train
def _check_timestamp(self, timestamp): """Verify that timestamp is recentish.""" timestamp = int(timestamp) now = int(time.time()) lapsed = now - timestamp if lapsed > self.timestamp_threshold: raise Error('Expired timestamp: given %d and now %s has a ' 'greater difference than threshold %d' % (timestamp, now, self.timestamp_threshold))
python
{ "resource": "" }
q26559
SignatureMethod_HMAC_SHA1.sign
train
def sign(self, request, consumer, token): """Builds the base signature string.""" key, raw = self.signing_base(request, consumer, token) hashed = hmac.new(key, raw, sha1) # Calculate the digest base 64. return binascii.b2a_base64(hashed.digest())[:-1]
python
{ "resource": "" }
q26560
SignatureMethod_PLAINTEXT.signing_base
train
def signing_base(self, request, consumer, token): """Concatenates the consumer key and secret with the token's secret.""" sig = '%s&' % escape(consumer.secret) if token: sig = sig + escape(token.secret) return sig, sig
python
{ "resource": "" }
q26561
_safe_timezone
train
def _safe_timezone(obj): # type: (Union[str, int, float, _datetime.tzinfo]) -> _Timezone """ Creates a timezone instance from a string, Timezone, TimezoneInfo or integer offset. """ if isinstance(obj, _Timezone): return obj if obj is None or obj == "local": return local_timezone() if isinstance(obj, (int, float)): obj = int(obj * 60 * 60) elif isinstance(obj, _datetime.tzinfo): # pytz if hasattr(obj, "localize"): obj = obj.zone else: offset = obj.utcoffset(None) if offset is None: offset = _datetime.timedelta(0) obj = int(offset.total_seconds()) return timezone(obj)
python
{ "resource": "" }
q26562
datetime
train
def datetime( year, # type: int month, # type: int day, # type: int hour=0, # type: int minute=0, # type: int second=0, # type: int microsecond=0, # type: int tz=UTC, # type: Union[str, _Timezone] dst_rule=POST_TRANSITION, # type: str ): # type: (...) -> DateTime """ Creates a new DateTime instance from a specific date and time. """ if tz is not None: tz = _safe_timezone(tz) if not _HAS_FOLD: dt = naive(year, month, day, hour, minute, second, microsecond) else: dt = _datetime.datetime(year, month, day, hour, minute, second, microsecond) if tz is not None: dt = tz.convert(dt, dst_rule=dst_rule) return DateTime( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, tzinfo=dt.tzinfo, fold=dt.fold, )
python
{ "resource": "" }
q26563
local
train
def local( year, month, day, hour=0, minute=0, second=0, microsecond=0 ): # type: (int, int, int, int, int, int, int) -> DateTime """ Return a DateTime in the local timezone. """ return datetime( year, month, day, hour, minute, second, microsecond, tz=local_timezone() )
python
{ "resource": "" }
q26564
naive
train
def naive( year, month, day, hour=0, minute=0, second=0, microsecond=0 ): # type: (int, int, int, int, int, int, int) -> DateTime """ Return a naive DateTime. """ return DateTime(year, month, day, hour, minute, second, microsecond)
python
{ "resource": "" }
q26565
time
train
def time(hour, minute=0, second=0, microsecond=0): # type: (int, int, int, int) -> Time """ Create a new Time instance. """ return Time(hour, minute, second, microsecond)
python
{ "resource": "" }
q26566
instance
train
def instance( dt, tz=UTC # type: _datetime.datetime # type: Union[str, _Timezone, None] ): # type: (...) -> DateTime """ Create a DateTime instance from a datetime one. """ if not isinstance(dt, _datetime.datetime): raise ValueError("instance() only accepts datetime objects.") if isinstance(dt, DateTime): return dt tz = dt.tzinfo or tz # Checking for pytz/tzinfo if isinstance(tz, _datetime.tzinfo) and not isinstance(tz, _Timezone): # pytz if hasattr(tz, "localize") and tz.zone: tz = tz.zone else: # We have no sure way to figure out # the timezone name, we fallback # on a fixed offset tz = tz.utcoffset(dt).total_seconds() / 3600 return datetime( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, tz=tz )
python
{ "resource": "" }
q26567
now
train
def now(tz=None): # type: (Union[str, _Timezone, None]) -> DateTime """ Get a DateTime instance for the current date and time. """ if has_test_now(): test_instance = get_test_now() _tz = _safe_timezone(tz) if tz is not None and _tz != test_instance.timezone: test_instance = test_instance.in_tz(_tz) return test_instance if tz is None or tz == "local": dt = _datetime.datetime.now(local_timezone()) elif tz is UTC or tz == "UTC": dt = _datetime.datetime.now(UTC) else: dt = _datetime.datetime.now(UTC) tz = _safe_timezone(tz) dt = tz.convert(dt) return instance(dt, tz)
python
{ "resource": "" }
q26568
from_format
train
def from_format( string, # type: str fmt, # type: str tz=UTC, # type: Union[str, _Timezone] locale=None, # type: Union[str, None] ): # type: (...) -> DateTime """ Creates a DateTime instance from a specific format. """ parts = _formatter.parse(string, fmt, now(), locale=locale) if parts["tz"] is None: parts["tz"] = tz return datetime(**parts)
python
{ "resource": "" }
q26569
from_timestamp
train
def from_timestamp( timestamp, tz=UTC # type: Union[int, float] # type: Union[str, _Timezone] ): # type: (...) -> DateTime """ Create a DateTime instance from a timestamp. """ dt = _datetime.datetime.utcfromtimestamp(timestamp) dt = datetime( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond ) if tz is not UTC or tz != "UTC": dt = dt.in_timezone(tz) return dt
python
{ "resource": "" }
q26570
duration
train
def duration( days=0, # type: float seconds=0, # type: float microseconds=0, # type: float milliseconds=0, # type: float minutes=0, # type: float hours=0, # type: float weeks=0, # type: float years=0, # type: float months=0, # type: float ): # type: (...) -> Duration """ Create a Duration instance. """ return Duration( days=days, seconds=seconds, microseconds=microseconds, milliseconds=milliseconds, minutes=minutes, hours=hours, weeks=weeks, years=years, months=months, )
python
{ "resource": "" }
q26571
period
train
def period( start, end, absolute=False # type: DateTime # type: DateTime # type: bool ): # type: (...) -> Period """ Create a Period instance. """ return Period(start, end, absolute=absolute)
python
{ "resource": "" }
q26572
_divide_and_round
train
def _divide_and_round(a, b): """divide a by b and round result to the nearest integer When the ratio is exactly half-way between two integers, the even integer is returned. """ # Based on the reference implementation for divmod_near # in Objects/longobject.c. q, r = divmod(a, b) # round up if either r / b > 0.5, or r / b == 0.5 and q is odd. # The expression r / b > 0.5 is equivalent to 2 * r > b if b is # positive, 2 * r < b if b negative. r *= 2 greater_than_half = r > b if b > 0 else r < b if greater_than_half or r == b and q % 2 == 1: q += 1 return q
python
{ "resource": "" }
q26573
Duration.in_words
train
def in_words(self, locale=None, separator=" "): """ Get the current interval in words in the current locale. Ex: 6 jours 23 heures 58 minutes :param locale: The locale to use. Defaults to current locale. :type locale: str :param separator: The separator to use between each unit :type separator: str :rtype: str """ periods = [ ("year", self.years), ("month", self.months), ("week", self.weeks), ("day", self.remaining_days), ("hour", self.hours), ("minute", self.minutes), ("second", self.remaining_seconds), ] if locale is None: locale = pendulum.get_locale() locale = pendulum.locale(locale) parts = [] for period in periods: unit, count = period if abs(count) > 0: translation = locale.translation( "units.{}.{}".format(unit, locale.plural(abs(count))) ) parts.append(translation.format(count)) if not parts and abs(self.microseconds) > 0: translation = locale.translation("units.second.{}".format(locale.plural(1))) us = abs(self.microseconds) / 1e6 parts.append(translation.format("{:.2f}".format(us))) return decode(separator.join(parts))
python
{ "resource": "" }
q26574
DifferenceFormatter.format
train
def format(self, diff, is_now=True, absolute=False, locale=None): """ Formats a difference. :param diff: The difference to format :type diff: pendulum.period.Period :param is_now: Whether the difference includes now :type is_now: bool :param absolute: Whether it's an absolute difference or not :type absolute: bool :param locale: The locale to use :type locale: str or None :rtype: str """ if locale is None: locale = self._locale else: locale = Locale.load(locale) count = diff.remaining_seconds if diff.years > 0: unit = "year" count = diff.years if diff.months > 6: count += 1 elif diff.months == 11 and (diff.weeks * 7 + diff.remaining_days) > 15: unit = "year" count = 1 elif diff.months > 0: unit = "month" count = diff.months if (diff.weeks * 7 + diff.remaining_days) >= 27: count += 1 elif diff.weeks > 0: unit = "week" count = diff.weeks if diff.remaining_days > 3: count += 1 elif diff.remaining_days > 0: unit = "day" count = diff.remaining_days if diff.hours >= 22: count += 1 elif diff.hours > 0: unit = "hour" count = diff.hours elif diff.minutes > 0: unit = "minute" count = diff.minutes elif 10 < diff.remaining_seconds <= 59: unit = "second" count = diff.remaining_seconds else: # We check if the "a few seconds" unit exists time = locale.get("custom.units.few_second") if time is not None: if absolute: return time key = "custom" is_future = diff.invert if is_now: if is_future: key += ".from_now" else: key += ".ago" else: if is_future: key += ".after" else: key += ".before" return locale.get(key).format(time) else: unit = "second" count = diff.remaining_seconds if count == 0: count = 1 if absolute: key = "translations.units.{}".format(unit) else: is_future = diff.invert if is_now: # Relative to now, so we can use # the CLDR data key = "translations.relative.{}".format(unit) if is_future: key += ".future" else: key += ".past" else: # Absolute comparison # So we have to use the custom locale data # Checking for special pluralization rules key = "custom.units_relative" if is_future: key += ".{}.future".format(unit) else: key += ".{}.past".format(unit) trans = locale.get(key) if not trans: # No special rule time = locale.get( "translations.units.{}.{}".format(unit, locale.plural(count)) ).format(count) else: time = trans[locale.plural(count)].format(count) key = "custom" if is_future: key += ".after" else: key += ".before" return locale.get(key).format(decode(time)) key += ".{}".format(locale.plural(count)) return decode(locale.get(key).format(count))
python
{ "resource": "" }
q26575
Time.closest
train
def closest(self, dt1, dt2): """ Get the closest time from the instance. :type dt1: Time or time :type dt2: Time or time :rtype: Time """ dt1 = self.__class__(dt1.hour, dt1.minute, dt1.second, dt1.microsecond) dt2 = self.__class__(dt2.hour, dt2.minute, dt2.second, dt2.microsecond) if self.diff(dt1).in_seconds() < self.diff(dt2).in_seconds(): return dt1 return dt2
python
{ "resource": "" }
q26576
Time.diff
train
def diff(self, dt=None, abs=True): """ Returns the difference between two Time objects as an Duration. :type dt: Time or None :param abs: Whether to return an absolute interval or not :type abs: bool :rtype: Duration """ if dt is None: dt = pendulum.now().time() else: dt = self.__class__(dt.hour, dt.minute, dt.second, dt.microsecond) us1 = ( self.hour * SECS_PER_HOUR + self.minute * SECS_PER_MIN + self.second ) * USECS_PER_SEC us2 = ( dt.hour * SECS_PER_HOUR + dt.minute * SECS_PER_MIN + dt.second ) * USECS_PER_SEC klass = Duration if abs: klass = AbsoluteDuration return klass(microseconds=us2 - us1)
python
{ "resource": "" }
q26577
Reader.read_for
train
def read_for(self, timezone): # type: (str) -> Timezone """ Read the zoneinfo structure for a given timezone name. :param timezone: The timezone. """ try: file_path = pytzdata.tz_path(timezone) except TimezoneNotFound: raise InvalidTimezone(timezone) return self.read(file_path)
python
{ "resource": "" }
q26578
Reader.read
train
def read(self, file_path): # type: (str) -> Timezone """ Read a zoneinfo structure from the given path. :param file_path: The path of a zoneinfo file. """ if not os.path.exists(file_path): raise InvalidZoneinfoFile("The tzinfo file does not exist") with open(file_path, "rb") as fd: return self._parse(fd)
python
{ "resource": "" }
q26579
Reader._check_read
train
def _check_read(self, fd, nbytes): # type: (...) -> bytes """ Reads the given number of bytes from the given file and checks that the correct number of bytes could be read. """ result = fd.read(nbytes) if (not result and nbytes > 0) or len(result) != nbytes: raise InvalidZoneinfoFile( "Expected {} bytes reading {}, " "but got {}".format(nbytes, fd.name, len(result) if result else 0) ) if PY2: return bytearray(result) return result
python
{ "resource": "" }
q26580
Reader._parse
train
def _parse(self, fd): # type: (...) -> Timezone """ Parse a zoneinfo file. """ hdr = self._parse_header(fd) if hdr.version in (2, 3): # We're skipping the entire v1 file since # at least the same data will be found in TZFile 2. fd.seek( hdr.transitions * 5 + hdr.types * 6 + hdr.abbr_size + hdr.leaps * 4 + hdr.stdwalls + hdr.utclocals, 1, ) # Parse the second header hdr = self._parse_header(fd) if hdr.version != 2 and hdr.version != 3: raise InvalidZoneinfoFile( "Header versions mismatch for file {}".format(fd.name) ) # Parse the v2 data trans = self._parse_trans_64(fd, hdr.transitions) type_idx = self._parse_type_idx(fd, hdr.transitions) types = self._parse_types(fd, hdr.types) abbrs = self._parse_abbrs(fd, hdr.abbr_size, types) fd.seek(hdr.leaps * 8 + hdr.stdwalls + hdr.utclocals, 1) trule = self._parse_posix_tz(fd) else: # TZFile v1 trans = self._parse_trans_32(fd, hdr.transitions) type_idx = self._parse_type_idx(fd, hdr.transitions) types = self._parse_types(fd, hdr.types) abbrs = self._parse_abbrs(fd, hdr.abbr_size, types) trule = None types = [ TransitionType(off, is_dst, abbrs[abbr]) for off, is_dst, abbr in types ] transitions = [] previous = None for trans, idx in zip(trans, type_idx): transition = Transition(trans, types[idx], previous) transitions.append(transition) previous = transition if not transitions: transitions.append(Transition(0, types[0], None)) return Timezone(transitions, posix_rule=trule, extended=self._extend)
python
{ "resource": "" }
q26581
timezone
train
def timezone(name, extended=True): # type: (Union[str, int]) -> _Timezone """ Return a Timezone instance given its name. """ if isinstance(name, int): return fixed_timezone(name) if name.lower() == "utc": return UTC if name in _tz_cache: return _tz_cache[name] tz = _Timezone(name, extended=extended) _tz_cache[name] = tz return tz
python
{ "resource": "" }
q26582
fixed_timezone
train
def fixed_timezone(offset): # type: (int) -> _FixedTimezone """ Return a Timezone instance given its offset in seconds. """ if offset in _tz_cache: return _tz_cache[offset] tz = _FixedTimezone(offset) _tz_cache[offset] = tz return tz
python
{ "resource": "" }
q26583
Timezone.convert
train
def convert( self, dt, dst_rule=None # type: datetime # type: Union[str, None] ): # type: (...) -> datetime """ Converts a datetime in the current timezone. If the datetime is naive, it will be normalized. >>> from datetime import datetime >>> from pendulum import timezone >>> paris = timezone('Europe/Paris') >>> dt = datetime(2013, 3, 31, 2, 30, fold=1) >>> in_paris = paris.convert(dt) >>> in_paris.isoformat() '2013-03-31T03:30:00+02:00' If the datetime is aware, it will be properly converted. >>> new_york = timezone('America/New_York') >>> in_new_york = new_york.convert(in_paris) >>> in_new_york.isoformat() '2013-03-30T21:30:00-04:00' """ if dt.tzinfo is None: return self._normalize(dt, dst_rule=dst_rule) return self._convert(dt)
python
{ "resource": "" }
q26584
Timezone.datetime
train
def datetime( self, year, month, day, hour=0, minute=0, second=0, microsecond=0 ): # type: (int, int, int, int, int, int, int) -> datetime """ Return a normalized datetime for the current timezone. """ if _HAS_FOLD: return self.convert( datetime(year, month, day, hour, minute, second, microsecond, fold=1) ) return self.convert( datetime(year, month, day, hour, minute, second, microsecond), dst_rule=POST_TRANSITION, )
python
{ "resource": "" }
q26585
DateTime.naive
train
def naive(self): # type: () -> DateTime """ Return the DateTime without timezone information. """ return self.__class__( self.year, self.month, self.day, self.hour, self.minute, self.second, self.microsecond, )
python
{ "resource": "" }
q26586
DateTime.on
train
def on(self, year, month, day): """ Returns a new instance with the current date set to a different date. :param year: The year :type year: int :param month: The month :type month: int :param day: The day :type day: int :rtype: DateTime """ return self.set(year=int(year), month=int(month), day=int(day))
python
{ "resource": "" }
q26587
DateTime.at
train
def at(self, hour, minute=0, second=0, microsecond=0): """ Returns a new instance with the current time to a different time. :param hour: The hour :type hour: int :param minute: The minute :type minute: int :param second: The second :type second: int :param microsecond: The microsecond :type microsecond: int :rtype: DateTime """ return self.set( hour=hour, minute=minute, second=second, microsecond=microsecond )
python
{ "resource": "" }
q26588
DateTime.in_timezone
train
def in_timezone(self, tz): # type: (Union[str, Timezone]) -> DateTime """ Set the instance's timezone from a string or object. """ tz = pendulum._safe_timezone(tz) return tz.convert(self, dst_rule=pendulum.POST_TRANSITION)
python
{ "resource": "" }
q26589
DateTime.to_iso8601_string
train
def to_iso8601_string(self): """ Format the instance as ISO 8601. :rtype: str """ string = self._to_string("iso8601") if self.tz and self.tz.name == "UTC": string = string.replace("+00:00", "Z") return string
python
{ "resource": "" }
q26590
DateTime._to_string
train
def _to_string(self, fmt, locale=None): """ Format the instance to a common string format. :param fmt: The name of the string format :type fmt: string :param locale: The locale to use :type locale: str or None :rtype: str """ if fmt not in self._FORMATS: raise ValueError("Format [{}] is not supported".format(fmt)) fmt = self._FORMATS[fmt] if callable(fmt): return fmt(self) return self.format(fmt, locale=locale)
python
{ "resource": "" }
q26591
DateTime.is_long_year
train
def is_long_year(self): """ Determines if the instance is a long year See link `https://en.wikipedia.org/wiki/ISO_8601#Week_dates`_ :rtype: bool """ return ( pendulum.datetime(self.year, 12, 28, 0, 0, 0, tz=self.tz).isocalendar()[1] == 53 )
python
{ "resource": "" }
q26592
DateTime.is_same_day
train
def is_same_day(self, dt): """ Checks if the passed in date is the same day as the instance current day. :type dt: DateTime or datetime or str or int :rtype: bool """ dt = pendulum.instance(dt) return self.to_date_string() == dt.to_date_string()
python
{ "resource": "" }
q26593
DateTime.add
train
def add( self, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0, ): # type: (int, int, int, int, int, int, int) -> DateTime """ Add a duration to the instance. If we're adding units of variable length (i.e., years, months), move forward from curren time, otherwise move forward from utc, for accuracy when moving across DST boundaries. """ units_of_variable_length = any([years, months, weeks, days]) current_dt = datetime.datetime( self.year, self.month, self.day, self.hour, self.minute, self.second, self.microsecond, ) if not units_of_variable_length: offset = self.utcoffset() if offset: current_dt = current_dt - offset dt = add_duration( current_dt, years=years, months=months, weeks=weeks, days=days, hours=hours, minutes=minutes, seconds=seconds, microseconds=microseconds, ) if units_of_variable_length or self.tzinfo is None: return pendulum.datetime( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, tz=self.tz, ) dt = self.__class__( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, tzinfo=UTC, ) dt = self.tz.convert(dt) return self.__class__( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, tzinfo=self.tz, fold=dt.fold, )
python
{ "resource": "" }
q26594
DateTime.diff
train
def diff(self, dt=None, abs=True): """ Returns the difference between two DateTime objects represented as a Duration. :type dt: DateTime or None :param abs: Whether to return an absolute interval or not :type abs: bool :rtype: Period """ if dt is None: dt = self.now(self.tz) return Period(self, dt, absolute=abs)
python
{ "resource": "" }
q26595
DateTime.next
train
def next(self, day_of_week=None, keep_time=False): """ Modify to the next occurrence of a given day of the week. If no day_of_week is provided, modify to the next occurrence of the current day of the week. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. :param day_of_week: The next day of week to reset to. :type day_of_week: int or None :param keep_time: Whether to keep the time information or not. :type keep_time: bool :rtype: DateTime """ if day_of_week is None: day_of_week = self.day_of_week if day_of_week < SUNDAY or day_of_week > SATURDAY: raise ValueError("Invalid day of week") if keep_time: dt = self else: dt = self.start_of("day") dt = dt.add(days=1) while dt.day_of_week != day_of_week: dt = dt.add(days=1) return dt
python
{ "resource": "" }
q26596
DateTime.previous
train
def previous(self, day_of_week=None, keep_time=False): """ Modify to the previous occurrence of a given day of the week. If no day_of_week is provided, modify to the previous occurrence of the current day of the week. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. :param day_of_week: The previous day of week to reset to. :type day_of_week: int or None :param keep_time: Whether to keep the time information or not. :type keep_time: bool :rtype: DateTime """ if day_of_week is None: day_of_week = self.day_of_week if day_of_week < SUNDAY or day_of_week > SATURDAY: raise ValueError("Invalid day of week") if keep_time: dt = self else: dt = self.start_of("day") dt = dt.subtract(days=1) while dt.day_of_week != day_of_week: dt = dt.subtract(days=1) return dt
python
{ "resource": "" }
q26597
DateTime.first_of
train
def first_of(self, unit, day_of_week=None): """ Returns an instance set to the first occurrence of a given day of the week in the current unit. If no day_of_week is provided, modify to the first day of the unit. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. Supported units are month, quarter and year. :param unit: The unit to use :type unit: str :type day_of_week: int or None :rtype: DateTime """ if unit not in ["month", "quarter", "year"]: raise ValueError('Invalid unit "{}" for first_of()'.format(unit)) return getattr(self, "_first_of_{}".format(unit))(day_of_week)
python
{ "resource": "" }
q26598
DateTime.last_of
train
def last_of(self, unit, day_of_week=None): """ Returns an instance set to the last occurrence of a given day of the week in the current unit. If no day_of_week is provided, modify to the last day of the unit. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. Supported units are month, quarter and year. :param unit: The unit to use :type unit: str :type day_of_week: int or None :rtype: DateTime """ if unit not in ["month", "quarter", "year"]: raise ValueError('Invalid unit "{}" for first_of()'.format(unit)) return getattr(self, "_last_of_{}".format(unit))(day_of_week)
python
{ "resource": "" }
q26599
DateTime.nth_of
train
def nth_of(self, unit, nth, day_of_week): """ Returns a new instance set to the given occurrence of a given day of the week in the current unit. If the calculated occurrence is outside the scope of the current unit, then raise an error. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. Supported units are month, quarter and year. :param unit: The unit to use :type unit: str :type nth: int :type day_of_week: int or None :rtype: DateTime """ if unit not in ["month", "quarter", "year"]: raise ValueError('Invalid unit "{}" for first_of()'.format(unit)) dt = getattr(self, "_nth_of_{}".format(unit))(nth, day_of_week) if dt is False: raise PendulumException( "Unable to find occurence {} of {} in {}".format( nth, self._days[day_of_week], unit ) ) return dt
python
{ "resource": "" }