Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def parseWord(word): mapping = {'yes': True, 'true': True, 'no': False, 'false': False} _, key, value = word.split('=', 2) try: value = int(value) except ValueError: value = mapping.get(value, value) return (key, value)
[ "\n Split given attribute word to key, value pair.\n\n Values are casted to python equivalents.\n\n :param word: API word.\n :returns: Key, value pair.\n " ]
Please provide a description of the function:def composeWord(key, value): mapping = {True: 'yes', False: 'no'} # this is necesary because 1 == True, 0 == False if type(value) == int: value = str(value) else: value = mapping.get(value, str(value)) return '={}={}'.format(key, value)
[ "\n Create a attribute word from key, value pair.\n Values are casted to api equivalents.\n " ]
Please provide a description of the function:def login_token(api, username, password): sentence = api('/login') token = tuple(sentence)[0]['ret'] encoded = encode_password(token, password) tuple(api('/login', **{'name': username, 'response': encoded}))
[ "Login using pre routeros 6.43 authorization method." ]
Please provide a description of the function:def check_relations(self, relations): for rel in relations: if not rel: continue fields = rel.split('.', 1) local_field = fields[0] if local_field not in self.fields: raise ValueError('Unknown field "{}"'.format(local_field)) field = self.fields[local_field] if not isinstance(field, BaseRelationship): raise ValueError('Can only include relationships. "{}" is a "{}"' .format(field.name, field.__class__.__name__)) field.include_data = True if len(fields) > 1: field.schema.check_relations(fields[1:])
[ "Recursive function which checks if a relation is valid." ]
Please provide a description of the function:def format_json_api_response(self, data, many): ret = self.format_items(data, many) ret = self.wrap_response(ret, many) ret = self.render_included_data(ret) ret = self.render_meta_document(ret) return ret
[ "Post-dump hook that formats serialized data as a top-level JSON API object.\n\n See: http://jsonapi.org/format/#document-top-level\n " ]
Please provide a description of the function:def on_bind_field(self, field_name, field_obj): if _MARSHMALLOW_VERSION_INFO[0] < 3: if not field_obj.load_from: field_obj.load_from = self.inflect(field_name) else: if not field_obj.data_key: field_obj.data_key = self.inflect(field_name) return None
[ "Schema hook override. When binding fields, set ``data_key`` (on marshmallow 3) or\n load_from (on marshmallow 2) to the inflected form of field_name.\n " ]
Please provide a description of the function:def _do_load(self, data, many=None, **kwargs): many = self.many if many is None else bool(many) # Store this on the instance so we have access to the included data # when processing relationships (``included`` is outside of the # ``data``). self.included_data = data.get('included', {}) self.document_meta = data.get('meta', {}) try: result = super(Schema, self)._do_load(data, many, **kwargs) except ValidationError as err: # strict mode error_messages = err.messages if '_schema' in error_messages: error_messages = error_messages['_schema'] formatted_messages = self.format_errors(error_messages, many=many) err.messages = formatted_messages raise err else: # On marshmallow 2, _do_load returns a tuple (load_data, errors) if _MARSHMALLOW_VERSION_INFO[0] < 3: data, error_messages = result if '_schema' in error_messages: error_messages = error_messages['_schema'] formatted_messages = self.format_errors(error_messages, many=many) return data, formatted_messages return result
[ "Override `marshmallow.Schema._do_load` for custom JSON API handling.\n\n Specifically, we do this to format errors as JSON API Error objects,\n and to support loading of included data.\n " ]
Please provide a description of the function:def _extract_from_included(self, data): return (item for item in self.included_data if item['type'] == data['type'] and str(item['id']) == str(data['id']))
[ "Extract included data matching the items in ``data``.\n\n For each item in ``data``, extract the full data from the included\n data.\n " ]
Please provide a description of the function:def inflect(self, text): return self.opts.inflect(text) if self.opts.inflect else text
[ "Inflect ``text`` if the ``inflect`` class Meta option is defined, otherwise\n do nothing.\n " ]
Please provide a description of the function:def format_errors(self, errors, many): if not errors: return {} if isinstance(errors, (list, tuple)): return {'errors': errors} formatted_errors = [] if many: for index, errors in iteritems(errors): for field_name, field_errors in iteritems(errors): formatted_errors.extend([ self.format_error(field_name, message, index=index) for message in field_errors ]) else: for field_name, field_errors in iteritems(errors): formatted_errors.extend([ self.format_error(field_name, message) for message in field_errors ]) return {'errors': formatted_errors}
[ "Format validation errors as JSON Error objects." ]
Please provide a description of the function:def format_error(self, field_name, message, index=None): pointer = ['/data'] if index is not None: pointer.append(str(index)) relationship = isinstance( self.declared_fields.get(field_name), BaseRelationship, ) if relationship: pointer.append('relationships') elif field_name != 'id': # JSONAPI identifier is a special field that exists above the attribute object. pointer.append('attributes') pointer.append(self.inflect(field_name)) if relationship: pointer.append('data') return { 'detail': message, 'source': { 'pointer': '/'.join(pointer), }, }
[ "Override-able hook to format a single error message as an Error object.\n\n See: http://jsonapi.org/format/#error-objects\n " ]
Please provide a description of the function:def format_item(self, item): # http://jsonapi.org/format/#document-top-level # Primary data MUST be either... a single resource object, a single resource # identifier object, or null, for requests that target single resources if not item: return None ret = self.dict_class() ret[TYPE] = self.opts.type_ # Get the schema attributes so we can confirm `dump-to` values exist attributes = { (get_dump_key(self.fields[field]) or field): field for field in self.fields } for field_name, value in iteritems(item): attribute = attributes[field_name] if attribute == ID: ret[ID] = value elif isinstance(self.fields[attribute], DocumentMeta): if not self.document_meta: self.document_meta = self.dict_class() self.document_meta.update(value) elif isinstance(self.fields[attribute], ResourceMeta): if 'meta' not in ret: ret['meta'] = self.dict_class() ret['meta'].update(value) elif isinstance(self.fields[attribute], BaseRelationship): if value: if 'relationships' not in ret: ret['relationships'] = self.dict_class() ret['relationships'][self.inflect(field_name)] = value else: if 'attributes' not in ret: ret['attributes'] = self.dict_class() ret['attributes'][self.inflect(field_name)] = value links = self.get_resource_links(item) if links: ret['links'] = links return ret
[ "Format a single datum as a Resource object.\n\n See: http://jsonapi.org/format/#document-resource-objects\n " ]
Please provide a description of the function:def format_items(self, data, many): if many: return [self.format_item(item) for item in data] else: return self.format_item(data)
[ "Format data as a Resource object or list of Resource objects.\n\n See: http://jsonapi.org/format/#document-resource-objects\n " ]
Please provide a description of the function:def get_top_level_links(self, data, many): self_link = None if many: if self.opts.self_url_many: self_link = self.generate_url(self.opts.self_url_many) else: if self.opts.self_url: self_link = data.get('links', {}).get('self', None) return {'self': self_link}
[ "Hook for adding links to the root of the response data." ]
Please provide a description of the function:def get_resource_links(self, item): if self.opts.self_url: ret = self.dict_class() kwargs = resolve_params(item, self.opts.self_url_kwargs or {}) ret['self'] = self.generate_url(self.opts.self_url, **kwargs) return ret return None
[ "Hook for adding links to a resource object." ]
Please provide a description of the function:def wrap_response(self, data, many): ret = {'data': data} # self_url_many is still valid when there isn't any data, but self_url # may only be included if there is data in the ret if many or data: top_level_links = self.get_top_level_links(data, many) if top_level_links['self']: ret['links'] = top_level_links return ret
[ "Wrap data and links according to the JSON API " ]
Please provide a description of the function:def extract_value(self, data): errors = [] if 'id' not in data: errors.append('Must have an `id` field') if 'type' not in data: errors.append('Must have a `type` field') elif data['type'] != self.type_: errors.append('Invalid `type` specified') if errors: raise ValidationError(errors) # If ``attributes`` is set, we've folded included data into this # relationship. Unserialize it if we have a schema set; otherwise we # fall back below to old behaviour of only IDs. if 'attributes' in data and self.__schema: result = self.schema.load({'data': data, 'included': self.root.included_data}) return result.data if _MARSHMALLOW_VERSION_INFO[0] < 3 else result id_value = data.get('id') if self.__schema: id_value = self.schema.fields['id'].deserialize(id_value) return id_value
[ "Extract the id key and validate the request structure." ]
Please provide a description of the function:def deserialize(self, value, attr=None, data=None): if value is missing_: return super(Relationship, self).deserialize(value, attr, data) if not isinstance(value, dict) or 'data' not in value: # a relationships object does not need 'data' if 'links' is present if value and 'links' in value: return missing_ else: raise ValidationError('Must include a `data` key') return super(Relationship, self).deserialize(value['data'], attr, data)
[ "Deserialize ``value``.\n\n :raise ValidationError: If the value is not type `dict`, if the\n value does not contain a `data` key, and if the value is\n required but unspecified.\n " ]
Please provide a description of the function:def J(*args, **kwargs): response = jsonify(*args, **kwargs) response.mimetype = 'application/vnd.api+json' return response
[ "Wrapper around jsonify that sets the Content-Type of the response to\n application/vnd.api+json.\n " ]
Please provide a description of the function:def resolve_params(obj, params, default=missing): param_values = {} for name, attr_tpl in iteritems(params): attr_name = tpl(str(attr_tpl)) if attr_name: attribute_value = get_value(obj, attr_name, default=default) if attribute_value is not missing: param_values[name] = attribute_value else: raise AttributeError( '{attr_name!r} is not a valid ' 'attribute of {obj!r}'.format(attr_name=attr_name, obj=obj), ) else: param_values[name] = attr_tpl return param_values
[ "Given a dictionary of keyword arguments, return the same dictionary except with\n values enclosed in `< >` resolved to attributes on `obj`.\n " ]
Please provide a description of the function:def fill_package_digests(generated_project: Project) -> Project: for package_version in chain(generated_project.pipfile_lock.packages, generated_project.pipfile_lock.dev_packages): if package_version.hashes: # Already filled from the last run. continue if package_version.index: scanned_hashes = package_version.index.get_package_hashes( package_version.name, package_version.locked_version ) else: for source in generated_project.pipfile.meta.sources.values(): try: scanned_hashes = source.get_package_hashes(package_version.name, package_version.locked_version) break except Exception: continue else: raise ValueError("Unable to find package hashes") for entry in scanned_hashes: package_version.hashes.append("sha256:" + entry["sha256"]) return generated_project
[ "Temporary fill package digests stated in Pipfile.lock." ]
Please provide a description of the function:def fetch_digests(self, package_name: str, package_version: str) -> dict: report = {} for source in self._sources: try: report[source.url] = source.get_package_hashes(package_name, package_version) except NotFound as exc: _LOGGER.debug( f"Package {package_name} in version {package_version} not " f"found on index {source.name}: {str(exc)}" ) return report
[ "Fetch digests for the given package in specified version from the given package index." ]
Please provide a description of the function:def random_passphrase_from_wordlist(phrase_length, wordlist): passphrase_words = [] numbytes_of_entropy = phrase_length * 2 entropy = list(dev_random_entropy(numbytes_of_entropy, fallback_to_urandom=True)) bytes_per_word = int(ceil(log(len(wordlist), 2) / 8)) if (phrase_length * bytes_per_word > 64): raise Exception("Error! This operation requires too much entropy. \ Try a shorter phrase length or word list.") for i in range(phrase_length): current_entropy = entropy[i*bytes_per_word:(i+1)*bytes_per_word] index = int(''.join(current_entropy).encode('hex'), 16) % len(wordlist) word = wordlist[index] passphrase_words.append(word) return " ".join(passphrase_words)
[ " An extremely entropy efficient passphrase generator.\n\n This function:\n -Pulls entropy from the safer alternative to /dev/urandom: /dev/random\n -Doesn't rely on random.seed (words are selected right from the entropy)\n -Only requires 2 entropy bytes/word for word lists of up to 65536 words\n " ]
Please provide a description of the function:def bin_hash160(s, hex_format=False): if hex_format and is_hex(s): s = unhexlify(s) return hashlib.new('ripemd160', bin_sha256(s)).digest()
[ " s is in hex or binary format\n " ]
Please provide a description of the function:def hex_hash160(s, hex_format=False): if hex_format and is_hex(s): s = unhexlify(s) return hexlify(bin_hash160(s))
[ " s is in hex or binary format\n " ]
Please provide a description of the function:def reverse_hash(hash, hex_format=True): if not hex_format: hash = hexlify(hash) return "".join(reversed([hash[i:i+2] for i in range(0, len(hash), 2)]))
[ " hash is in hex or binary format\n " ]
Please provide a description of the function:def get_wordlist(language, word_source): try: wordlist_string = eval(language + '_words_' + word_source) except NameError: raise Exception("No wordlist could be found for the word source and language provided.") wordlist = wordlist_string.split(',') return wordlist
[ " Takes in a language and a word source and returns a matching wordlist,\n if it exists.\n Valid languages: ['english']\n Valid word sources: ['bip39', 'wiktionary', 'google']\n " ]
Please provide a description of the function:def get_num_words_with_entropy(bits_of_entropy, wordlist): entropy_per_word = math.log(len(wordlist))/math.log(2) num_words = int(math.ceil(bits_of_entropy/entropy_per_word)) return num_words
[ " Gets the number of words randomly selected from a given wordlist that\n would result in the number of bits of entropy specified.\n " ]
Please provide a description of the function:def create_passphrase(bits_of_entropy=None, num_words=None, language='english', word_source='wiktionary'): wordlist = get_wordlist(language, word_source) if not num_words: if not bits_of_entropy: bits_of_entropy = 80 num_words = get_num_words_with_entropy(bits_of_entropy, wordlist) return ' '.join(pick_random_words_from_wordlist(wordlist, num_words))
[ " Creates a passphrase that has a certain number of bits of entropy OR\n a certain number of words.\n " ]
Please provide a description of the function:def get_unspents(address, blockchain_client=BlockchainInfoClient()): if not isinstance(blockchain_client, BlockchainInfoClient): raise Exception('A BlockchainInfoClient object is required') url = BLOCKCHAIN_API_BASE_URL + "/unspent?format=json&active=" + address auth = blockchain_client.auth if auth and len(auth) == 2 and isinstance(auth[0], str): url = url + "&api_code=" + auth[0] r = requests.get(url, auth=auth) try: unspents = r.json()["unspent_outputs"] except ValueError, e: raise Exception('Invalid response from blockchain.info.') return format_unspents(unspents)
[ " Get the spendable transaction outputs, also known as UTXOs or\n unspent transaction outputs.\n " ]
Please provide a description of the function:def broadcast_transaction(hex_tx, blockchain_client=BlockchainInfoClient()): url = BLOCKCHAIN_API_BASE_URL + '/pushtx' payload = {'tx': hex_tx} r = requests.post(url, data=payload, auth=blockchain_client.auth) if 'submitted' in r.text.lower(): return {'success': True} else: raise Exception('Invalid response from blockchain.info.')
[ " Dispatch a raw transaction to the network.\n " ]
Please provide a description of the function:def serialize_input(input, signature_script_hex=''): if not (isinstance(input, dict) and 'transaction_hash' in input \ and 'output_index' in input): raise Exception('Required parameters: transaction_hash, output_index') if is_hex(str(input['transaction_hash'])) and len(str(input['transaction_hash'])) != 64: raise Exception("Transaction hash '%s' must be 32 bytes" % input['transaction_hash']) elif not is_hex(str(input['transaction_hash'])) and len(str(input['transaction_hash'])) != 32: raise Exception("Transaction hash '%s' must be 32 bytes" % hexlify(input['transaction_hash'])) if not 'sequence' in input: input['sequence'] = UINT_MAX return ''.join([ flip_endian(input['transaction_hash']), hexlify(struct.pack('<I', input['output_index'])), hexlify(variable_length_int(len(signature_script_hex)/2)), signature_script_hex, hexlify(struct.pack('<I', input['sequence'])) ])
[ " Serializes a transaction input.\n " ]
Please provide a description of the function:def serialize_output(output): if not ('value' in output and 'script_hex' in output): raise Exception('Invalid output') return ''.join([ hexlify(struct.pack('<Q', output['value'])), # pack into 8 bites hexlify(variable_length_int(len(output['script_hex'])/2)), output['script_hex'] ])
[ " Serializes a transaction output.\n " ]
Please provide a description of the function:def serialize_transaction(inputs, outputs, lock_time=0, version=1): # add in the inputs serialized_inputs = ''.join([serialize_input(input) for input in inputs]) # add in the outputs serialized_outputs = ''.join([serialize_output(output) for output in outputs]) return ''.join([ # add in the version number hexlify(struct.pack('<I', version)), # add in the number of inputs hexlify(variable_length_int(len(inputs))), # add in the inputs serialized_inputs, # add in the number of outputs hexlify(variable_length_int(len(outputs))), # add in the outputs serialized_outputs, # add in the lock time hexlify(struct.pack('<I', lock_time)), ])
[ " Serializes a transaction.\n " ]
Please provide a description of the function:def deserialize_transaction(tx_hex): tx = bitcoin.deserialize(str(tx_hex)) inputs = tx["ins"] outputs = tx["outs"] ret_inputs = [] ret_outputs = [] for inp in inputs: ret_inp = { "transaction_hash": inp["outpoint"]["hash"], "output_index": int(inp["outpoint"]["index"]), } if "sequence" in inp: ret_inp["sequence"] = int(inp["sequence"]) if "script" in inp: ret_inp["script_sig"] = inp["script"] ret_inputs.append(ret_inp) for out in outputs: ret_out = { "value": out["value"], "script_hex": out["script"] } ret_outputs.append(ret_out) return ret_inputs, ret_outputs, tx["locktime"], tx["version"]
[ "\n Given a serialized transaction, return its inputs, outputs,\n locktime, and version\n\n Each input will have:\n * transaction_hash: string\n * output_index: int\n * [optional] sequence: int\n * [optional] script_sig: string\n\n Each output will have:\n * value: int\n * script_hex: string\n " ]
Please provide a description of the function:def pending_transactions(server): namecoind = NamecoindClient(server, NAMECOIND_PORT, NAMECOIND_USER, NAMECOIND_PASSWD) reply = namecoind.listtransactions("", 10000) counter = 0 for i in reply: if i['confirmations'] == 0: counter += 1 return counter
[ " get the no. of pending transactions (0 confirmations) on a server\n " ]
Please provide a description of the function:def get_server(key, server=MAIN_SERVER, servers=LOAD_SERVERS): namecoind = NamecoindClient(NAMECOIND_SERVER, NAMECOIND_PORT, NAMECOIND_USER, NAMECOIND_PASSWD) info = namecoind.name_show(key) if 'address' in info: return check_address(info['address'], server, servers) response = {} response["registered"] = False response["server"] = None response["ismine"] = False return response
[ " given a key, get the IP address of the server that has the pvt key that\n owns the name/key\n " ]
Please provide a description of the function:def keypair(self, i, keypair_class): # Make sure keypair_class is a valid cryptocurrency keypair if not is_cryptocurrency_keypair_class(keypair_class): raise Exception(_messages["INVALID_KEYPAIR_CLASS"]) currency_name = keypair_class.__name__.lower().replace('keypair', '') k = keypair_class.from_passphrase( self._passphrase + " " + currency_name + str(i)) return k
[ " Return the keypair that corresponds to the provided sequence number\n and keypair class (BitcoinKeypair, etc.).\n " ]
Please provide a description of the function:def get_unspents(self, address): addresses = [] addresses.append(str(address)) min_confirmations = 0 max_confirmation = 2000000000 # just a very large number for max unspents = self.obj.listunspent(min_confirmations, max_confirmation, addresses) return self.format_unspents(unspents)
[ " Get the spendable transaction outputs, also known as UTXOs or\n unspent transaction outputs.\n\n NOTE: this will only return unspents if the address provided is\n present in the bitcoind server. Use the chain, blockchain,\n or blockcypher API to grab the unspents for arbitrary addresses.\n " ]
Please provide a description of the function:def broadcast_transaction(self, hex_tx): resp = self.obj.sendrawtransaction(hex_tx) if len(resp) > 0: return {'transaction_hash': resp, 'success': True} else: return error_reply('Invalid response from bitcoind.')
[ " Dispatch a raw transaction to the network.\n " ]
Please provide a description of the function:def from_passphrase(cls, passphrase=None): if not passphrase: # run a rejection sampling algorithm to ensure the private key is # less than the curve order while True: passphrase = create_passphrase(bits_of_entropy=160) hex_private_key = hashlib.sha256(passphrase).hexdigest() if int(hex_private_key, 16) < cls._curve.order: break else: hex_private_key = hashlib.sha256(passphrase).hexdigest() if not (int(hex_private_key, 16) < cls._curve.order): raise ValueError(_errors["PHRASE_YIELDS_INVALID_EXPONENT"]) keypair = cls(hex_private_key) keypair._passphrase = passphrase return keypair
[ " Create keypair from a passphrase input (a brain wallet keypair)." ]
Please provide a description of the function:def name_transfer(self, key, new_address, value=None): key_details = self.name_show(key) if 'code' in key_details and key_details.get('code') == -4: return error_reply("Key does not exist") # get new 'value' if given, otherwise use the old 'value' if value is None: value = json.dumps(key_details['value']) if not self.unlock_wallet(self.passphrase): error_reply("Error unlocking wallet", 403) # transfer the name (underlying call is still name_update) try: # update the 'value' reply = self.obj.name_update(key, value, new_address) except JSONRPCException as e: return e.error return reply
[ " Check if this name exists and if it does, find the value field\n note that update command needs an arg of <new value>.\n in case we're simply transferring, need to obtain old value first\n " ]
Please provide a description of the function:def variable_length_int(i): if not isinstance(i, (int,long)): raise Exception('i must be an integer') if i < (2**8-3): return chr(i) # pack the integer into one byte elif i < (2**16): return chr(253) + struct.pack('<H', i) # pack into 2 bytes elif i < (2**32): return chr(254) + struct.pack('<I', i) # pack into 4 bytes elif i < (2**64): return chr(255) + struct.pack('<Q', i) # pack into 8 bites else: raise Exception('Integer cannot exceed 8 bytes in length.')
[ " Encodes integers into variable length integers, which are used in\n Bitcoin in order to save space.\n " ]
Please provide a description of the function:def script_to_hex(script): hex_script = '' parts = script.split(' ') for part in parts: if part[0:3] == 'OP_': try: hex_script += '%0.2x' % eval(part) except: raise Exception('Invalid opcode: %s' % part) elif isinstance(part, (int)): hex_script += '%0.2x' % part elif is_hex(part): hex_script += '%0.2x' % count_bytes(part) + part else: raise Exception('Invalid script - only opcodes and hex characters allowed.') return hex_script
[ " Parse the string representation of a script and return the hex version.\n Example: \"OP_DUP OP_HASH160 c629...a6db OP_EQUALVERIFY OP_CHECKSIG\"\n " ]
Please provide a description of the function:def make_pay_to_address_script(address): hash160 = hexlify(b58check_decode(address)) script_string = 'OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG' % hash160 return script_to_hex(script_string)
[ " Takes in an address and returns the script \n " ]
Please provide a description of the function:def make_op_return_script(data, format='bin'): if format == 'hex': assert(is_hex(data)) hex_data = data elif format == 'bin': hex_data = hexlify(data) else: raise Exception("Format must be either 'hex' or 'bin'") num_bytes = count_bytes(hex_data) if num_bytes > MAX_BYTES_AFTER_OP_RETURN: raise Exception('Data is %i bytes - must not exceed 40.' % num_bytes) script_string = 'OP_RETURN %s' % hex_data return script_to_hex(script_string)
[ " Takes in raw ascii data to be embedded and returns a script.\n " ]
Please provide a description of the function:def create_bitcoind_service_proxy( rpc_username, rpc_password, server='127.0.0.1', port=8332, use_https=False): protocol = 'https' if use_https else 'http' uri = '%s://%s:%s@%s:%s' % (protocol, rpc_username, rpc_password, server, port) return AuthServiceProxy(uri)
[ " create a bitcoind service proxy\n " ]
Please provide a description of the function:def get_unspents(address, blockchain_client): if isinstance(blockchain_client, BitcoindClient): bitcoind = blockchain_client.bitcoind version_byte = blockchain_client.version_byte elif isinstance(blockchain_client, AuthServiceProxy): bitcoind = blockchain_client version_byte = 0 else: raise Exception('A BitcoindClient object is required') addresses = [] addresses.append(str(address)) min_confirmations = 0 max_confirmation = 2000000000 # just a very large number for max unspents = bitcoind.listunspent(min_confirmations, max_confirmation, addresses) return format_unspents(unspents)
[ " Get the spendable transaction outputs, also known as UTXOs or\n unspent transaction outputs.\n\n NOTE: this will only return unspents if the address provided is present\n in the bitcoind server. Use the chain, blockchain, or blockcypher API\n to grab the unspents for arbitrary addresses.\n " ]
Please provide a description of the function:def broadcast_transaction(hex_tx, blockchain_client): if isinstance(blockchain_client, BitcoindClient): bitcoind = blockchain_client.bitcoind elif isinstance(blockchain_client, AuthServiceProxy): bitcoind = blockchain_client else: raise Exception('A BitcoindClient object is required') try: resp = bitcoind.sendrawtransaction(hex_tx) except httplib.BadStatusLine: raise Exception('Invalid HTTP status code from bitcoind.') if len(resp) > 0: return {'tx_hash': resp, 'success': True} else: raise Exception('Invalid response from bitcoind.')
[ " Dispatch a raw transaction to the network.\n " ]
Please provide a description of the function:def get_unspents(address, blockchain_client=BlockchainInfoClient()): if isinstance(blockchain_client, BlockcypherClient): return blockcypher.get_unspents(address, blockchain_client) elif isinstance(blockchain_client, BlockchainInfoClient): return blockchain_info.get_unspents(address, blockchain_client) elif isinstance(blockchain_client, ChainComClient): return chain_com.get_unspents(address, blockchain_client) elif isinstance(blockchain_client, (BitcoindClient, AuthServiceProxy)): return bitcoind.get_unspents(address, blockchain_client) elif hasattr(blockchain_client, "get_unspents"): return blockchain_client.get_unspents( address ) elif isinstance(blockchain_client, BlockchainClient): raise Exception('That blockchain interface is not supported.') else: raise Exception('A BlockchainClient object is required')
[ " Gets the unspent outputs for a given address.\n " ]
Please provide a description of the function:def broadcast_transaction(hex_tx, blockchain_client): if isinstance(blockchain_client, BlockcypherClient): return blockcypher.broadcast_transaction(hex_tx, blockchain_client) elif isinstance(blockchain_client, BlockchainInfoClient): return blockchain_info.broadcast_transaction(hex_tx, blockchain_client) elif isinstance(blockchain_client, ChainComClient): return chain_com.broadcast_transaction(hex_tx, blockchain_client) elif isinstance(blockchain_client, (BitcoindClient, AuthServiceProxy)): return bitcoind.broadcast_transaction(hex_tx, blockchain_client) elif hasattr(blockchain_client, "broadcast_transaction"): return blockchain_client.broadcast_transaction( hex_tx ) elif isinstance(blockchain_client, BlockchainClient): raise Exception('That blockchain interface is not supported.') else: raise Exception('A BlockchainClient object is required')
[ " Dispatches a raw hex transaction to the network.\n " ]
Please provide a description of the function:def make_send_to_address_tx(recipient_address, amount, private_key, blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE, change_address=None): # get out the private key object, sending address, and inputs private_key_obj, from_address, inputs = analyze_private_key(private_key, blockchain_client) # get the change address if not change_address: change_address = from_address # create the outputs outputs = make_pay_to_address_outputs(recipient_address, amount, inputs, change_address, fee=fee) # serialize the transaction unsigned_tx = serialize_transaction(inputs, outputs) # generate a scriptSig for each input for i in xrange(0, len(inputs)): signed_tx = sign_transaction(unsigned_tx, i, private_key_obj.to_hex()) unsigned_tx = signed_tx # return the signed tx return signed_tx
[ " Builds and signs a \"send to address\" transaction.\n " ]
Please provide a description of the function:def make_op_return_tx(data, private_key, blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE, change_address=None, format='bin'): # get out the private key object, sending address, and inputs private_key_obj, from_address, inputs = analyze_private_key(private_key, blockchain_client) # get the change address if not change_address: change_address = from_address # create the outputs outputs = make_op_return_outputs(data, inputs, change_address, fee=fee, format=format) # serialize the transaction unsigned_tx = serialize_transaction(inputs, outputs) # generate a scriptSig for each input for i in xrange(0, len(inputs)): signed_tx = sign_transaction(unsigned_tx, i, private_key_obj.to_hex()) unsigned_tx = signed_tx # return the signed tx return signed_tx
[ " Builds and signs an OP_RETURN transaction.\n " ]
Please provide a description of the function:def send_to_address(recipient_address, amount, private_key, blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE, change_address=None): # build and sign the tx signed_tx = make_send_to_address_tx(recipient_address, amount, private_key, blockchain_client, fee=fee, change_address=change_address) # dispatch the signed transction to the network response = broadcast_transaction(signed_tx, blockchain_client) # return the response return response
[ " Builds, signs, and dispatches a \"send to address\" transaction.\n " ]
Please provide a description of the function:def embed_data_in_blockchain(data, private_key, blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE, change_address=None, format='bin'): # build and sign the tx signed_tx = make_op_return_tx(data, private_key, blockchain_client, fee=fee, change_address=change_address, format=format) # dispatch the signed transction to the network response = broadcast_transaction(signed_tx, blockchain_client) # return the response return response
[ " Builds, signs, and dispatches an OP_RETURN transaction.\n " ]
Please provide a description of the function:def sign_all_unsigned_inputs(hex_privkey, unsigned_tx_hex): inputs, outputs, locktime, version = deserialize_transaction(unsigned_tx_hex) tx_hex = unsigned_tx_hex for index in xrange(0, len(inputs)): if len(inputs[index]['script_sig']) == 0: # tx with index i signed with privkey tx_hex = sign_transaction(str(unsigned_tx_hex), index, hex_privkey) unsigned_tx_hex = tx_hex return tx_hex
[ "\n Sign a serialized transaction's unsigned inputs\n\n @hex_privkey: private key that should sign inputs\n @unsigned_tx_hex: hex transaction with unsigned inputs\n\n Returns: signed hex transaction\n " ]
Please provide a description of the function:def random_secret_exponent(curve_order): # run a rejection sampling algorithm to ensure the random int is less # than the curve order while True: # generate a random 256 bit hex string random_hex = hexlify(dev_random_entropy(32)) random_int = int(random_hex, 16) if random_int >= 1 and random_int < curve_order: break return random_int
[ " Generates a random secret exponent. " ]
Please provide a description of the function:def get_unspents(address, blockchain_client=ChainComClient()): if not isinstance(blockchain_client, ChainComClient): raise Exception('A ChainComClient object is required') url = CHAIN_API_BASE_URL + '/bitcoin/addresses/' + address + '/unspents' auth = blockchain_client.auth if auth: r = requests.get(url, auth=auth) else: r = requests.get(url + '?api-key-id=DEMO-4a5e1e4') try: unspents = r.json() except ValueError, e: raise Exception('Received non-JSON response from chain.com.') return format_unspents(unspents)
[ " Get the spendable transaction outputs, also known as UTXOs or\n unspent transaction outputs.\n " ]
Please provide a description of the function:def broadcast_transaction(hex_tx, blockchain_client): if not isinstance(blockchain_client, ChainComClient): raise Exception('A ChainComClient object is required') auth = blockchain_client.auth if not auth or len(auth) != 2: raise Exception('ChainComClient object must have auth credentials.') url = CHAIN_API_BASE_URL + '/bitcoin/transactions/send' payload = json.dumps({ 'signed_hex': hex_tx }) r = requests.post(url, data=payload, auth=auth) try: data = r.json() except ValueError, e: raise Exception('Received non-JSON from chain.com.') if 'transaction_hash' in data: reply = {} reply['tx_hash'] = data['transaction_hash'] reply['success'] = True return reply else: raise Exception('Tx hash missing from chain.com response: ' + str(data) + '\noriginal: ' + str(payload))
[ " Dispatch a raw hex transaction to the network.\n " ]
Please provide a description of the function:def get_unspents(address, blockchain_client=BlockcypherClient()): if not isinstance(blockchain_client, BlockcypherClient): raise Exception('A BlockcypherClient object is required') url = '%s/addrs/%s?unspentOnly=true&includeScript=true' % ( BLOCKCYPHER_BASE_URL, address) if blockchain_client.auth: r = requests.get(url + '&token=' + blockchain_client.auth[0]) else: r = requests.get(url) try: unspents = r.json() except ValueError: raise Exception('Received non-JSON response from blockcypher.com.') # sandwich unconfirmed and confirmed unspents return format_unspents(unspents)
[ " Get the spendable transaction outputs, also known as UTXOs or\n unspent transaction outputs.\n " ]
Please provide a description of the function:def broadcast_transaction(hex_tx, blockchain_client): if not isinstance(blockchain_client, BlockcypherClient): raise Exception('A BlockcypherClient object is required') url = '%s/txs/push' % (BLOCKCYPHER_BASE_URL) payload = json.dumps({'tx': hex_tx}) r = requests.post(url, data=payload) try: data = r.json() except ValueError: raise Exception('Received non-JSON from blockcypher.com.') if 'tx' in data: reply = {} reply['tx_hash'] = data['tx']['hash'] reply['success'] = True return reply else: err_str = 'Tx hash missing from blockcypher response: ' + str(data) raise Exception(err_str)
[ " Dispatch a raw hex transaction to the network.\n " ]
Please provide a description of the function:def calculate_merkle_root(hashes, hash_function=bin_double_sha256, hex_format=True): if hex_format: hashes = hex_to_bin_reversed_hashes(hashes) # keep moving up the merkle tree, constructing one row at a time while len(hashes) > 1: hashes = calculate_merkle_pairs(hashes, hash_function) # get the merkle root merkle_root = hashes[0] # if the user wants the merkle root in hex format, convert it if hex_format: return bin_to_hex_reversed(merkle_root) # return the binary merkle root return merkle_root
[ " takes in a list of binary hashes, returns a binary hash\n " ]
Please provide a description of the function:def b58check_encode(bin_s, version_byte=0): # append the version byte to the beginning bin_s = chr(int(version_byte)) + bin_s # calculate the number of leading zeros num_leading_zeros = len(re.match(r'^\x00*', bin_s).group(0)) # add in the checksum add the end bin_s = bin_s + bin_checksum(bin_s) # convert from b2 to b16 hex_s = hexlify(bin_s) # convert from b16 to b58 b58_s = change_charset(hex_s, HEX_KEYSPACE, B58_KEYSPACE) return B58_KEYSPACE[0] * num_leading_zeros + b58_s
[ " Takes in a binary string and converts it to a base 58 check string. " ]
Please provide a description of the function:def b58check_unpack(b58_s): num_leading_zeros = len(re.match(r'^1*', b58_s).group(0)) # convert from b58 to b16 hex_s = change_charset(b58_s, B58_KEYSPACE, HEX_KEYSPACE) # if an odd number of hex characters are present, add a zero to the front if len(hex_s) % 2 == 1: hex_s = "0" + hex_s # convert from b16 to b2 bin_s = unhexlify(hex_s) # add in the leading zeros bin_s = '\x00' * num_leading_zeros + bin_s # make sure the newly calculated checksum equals the embedded checksum newly_calculated_checksum = bin_checksum(bin_s[:-4]) embedded_checksum = bin_s[-4:] if not (newly_calculated_checksum == embedded_checksum): raise ValueError('b58check value has an invalid checksum') # return values version_byte = bin_s[:1] encoded_value = bin_s[1:-4] checksum = bin_s[-4:] return version_byte, encoded_value, checksum
[ " Takes in a base 58 check string and returns: the version byte, the\n original encoded binary string, and the checksum.\n " ]
Please provide a description of the function:def make_pay_to_address_outputs(to_address, send_amount, inputs, change_address, fee=STANDARD_FEE): return [ # main output { "script_hex": make_pay_to_address_script(to_address), "value": send_amount }, # change output { "script_hex": make_pay_to_address_script(change_address), "value": calculate_change_amount(inputs, send_amount, fee) } ]
[ " Builds the outputs for a \"pay to address\" transaction.\n " ]
Please provide a description of the function:def make_op_return_outputs(data, inputs, change_address, fee=OP_RETURN_FEE, send_amount=0, format='bin'): return [ # main output { "script_hex": make_op_return_script(data, format=format), "value": send_amount }, # change output { "script_hex": make_pay_to_address_script(change_address), "value": calculate_change_amount(inputs, send_amount, fee) } ]
[ " Builds the outputs for an OP_RETURN transaction.\n " ]
Please provide a description of the function:def add_timezone(value, tz=None): tz = tz or timezone.get_current_timezone() try: if timezone.is_naive(value): return timezone.make_aware(value, tz) except AttributeError: # 'datetime.date' object has no attribute 'tzinfo' dt = datetime.datetime.combine(value, datetime.time()) return timezone.make_aware(dt, tz) return value
[ "If the value is naive, then the timezone is added to it.\n\n If no timezone is given, timezone.get_current_timezone() is used.\n " ]
Please provide a description of the function:def get_active_entry(user, select_for_update=False): entries = apps.get_model('entries', 'Entry').no_join if select_for_update: entries = entries.select_for_update() entries = entries.filter(user=user, end_time__isnull=True) if not entries.exists(): return None if entries.count() > 1: raise ActiveEntryError('Only one active entry is allowed.') return entries[0]
[ "Returns the user's currently-active entry, or None." ]
Please provide a description of the function:def get_month_start(day=None): day = add_timezone(day or datetime.date.today()) return day.replace(day=1)
[ "Returns the first day of the given month." ]
Please provide a description of the function:def get_setting(name, **kwargs): if hasattr(settings, name): # Try user-defined settings first. return getattr(settings, name) if 'default' in kwargs: # Fall back to a specified default value. return kwargs['default'] if hasattr(defaults, name): # If that's not given, look in defaults file. return getattr(defaults, name) msg = '{0} must be specified in your project settings.'.format(name) raise AttributeError(msg)
[ "Returns the user-defined value for the setting, or a default value." ]
Please provide a description of the function:def get_week_start(day=None): day = add_timezone(day or datetime.date.today()) days_since_monday = day.weekday() if days_since_monday != 0: day = day - relativedelta(days=days_since_monday) return day
[ "Returns the Monday of the given week." ]
Please provide a description of the function:def get_year_start(day=None): day = add_timezone(day or datetime.date.today()) return day.replace(month=1).replace(day=1)
[ "Returns January 1 of the given year." ]
Please provide a description of the function:def to_datetime(date): return datetime.datetime(date.year, date.month, date.day)
[ "Transforms a date or datetime object into a date object." ]
Please provide a description of the function:def report_estimation_accuracy(request): contracts = ProjectContract.objects.filter( status=ProjectContract.STATUS_COMPLETE, type=ProjectContract.PROJECT_FIXED ) data = [('Target (hrs)', 'Actual (hrs)', 'Point Label')] for c in contracts: if c.contracted_hours() == 0: continue pt_label = "%s (%.2f%%)" % (c.name, c.hours_worked / c.contracted_hours() * 100) data.append((c.contracted_hours(), c.hours_worked, pt_label)) chart_max = max([max(x[0], x[1]) for x in data[1:]]) # max of all targets & actuals return render(request, 'timepiece/reports/estimation_accuracy.html', { 'data': json.dumps(data, cls=DecimalEncoder), 'chart_max': chart_max, })
[ "\n Idea from Software Estimation, Demystifying the Black Art, McConnel 2006 Fig 3-3.\n " ]
Please provide a description of the function:def get_context_data(self, **kwargs): context = super(ReportMixin, self).get_context_data(**kwargs) form = self.get_form() if form.is_valid(): data = form.cleaned_data start, end = form.save() entryQ = self.get_entry_query(start, end, data) trunc = data['trunc'] if entryQ: vals = ('pk', 'activity', 'project', 'project__name', 'project__status', 'project__type__label') entries = Entry.objects.date_trunc( trunc, extra_values=vals).filter(entryQ) else: entries = Entry.objects.none() end = end - relativedelta(days=1) date_headers = generate_dates(start, end, by=trunc) context.update({ 'from_date': start, 'to_date': end, 'date_headers': date_headers, 'entries': entries, 'filter_form': form, 'trunc': trunc, }) else: context.update({ 'from_date': None, 'to_date': None, 'date_headers': [], 'entries': Entry.objects.none(), 'filter_form': form, 'trunc': '', }) return context
[ "Processes form data to get relevant entries & date_headers." ]
Please provide a description of the function:def get_entry_query(self, start, end, data): # Entry types. incl_billable = data.get('billable', True) incl_nonbillable = data.get('non_billable', True) incl_leave = data.get('paid_leave', True) # If no types are selected, shortcut & return nothing. if not any((incl_billable, incl_nonbillable, incl_leave)): return None # All entries must meet time period requirements. basicQ = Q(end_time__gte=start, end_time__lt=end) # Filter by project for HourlyReport. projects = data.get('projects', None) basicQ &= Q(project__in=projects) if projects else Q() # Filter by user, activity, and project type for BillableReport. if 'users' in data: basicQ &= Q(user__in=data.get('users')) if 'activities' in data: basicQ &= Q(activity__in=data.get('activities')) if 'project_types' in data: basicQ &= Q(project__type__in=data.get('project_types')) # If all types are selected, no further filtering is required. if all((incl_billable, incl_nonbillable, incl_leave)): return basicQ # Filter by whether a project is billable or non-billable. billableQ = None if incl_billable and not incl_nonbillable: billableQ = Q(activity__billable=True, project__type__billable=True) if incl_nonbillable and not incl_billable: billableQ = Q(activity__billable=False) | Q(project__type__billable=False) # Filter by whether the entry is paid leave. leave_ids = utils.get_setting('TIMEPIECE_PAID_LEAVE_PROJECTS').values() leaveQ = Q(project__in=leave_ids) if incl_leave: extraQ = (leaveQ | billableQ) if billableQ else leaveQ else: extraQ = (~leaveQ & billableQ) if billableQ else ~leaveQ return basicQ & extraQ
[ "Builds Entry query from form data." ]
Please provide a description of the function:def get_headers(self, date_headers, from_date, to_date, trunc): date_headers = list(date_headers) # Earliest date should be no earlier than from_date. if date_headers and date_headers[0] < from_date: date_headers[0] = from_date # When organizing by week or month, create a list of the range for # each date header. if date_headers and trunc != 'day': count = len(date_headers) range_headers = [0] * count for i in range(count - 1): range_headers[i] = ( date_headers[i], date_headers[i + 1] - relativedelta(days=1)) range_headers[count - 1] = (date_headers[count - 1], to_date) else: range_headers = date_headers return date_headers, range_headers
[ "Adjust date headers & get range headers." ]
Please provide a description of the function:def get_previous_month(self): end = utils.get_month_start() - relativedelta(days=1) end = utils.to_datetime(end) start = utils.get_month_start(end) return start, end
[ "Returns date range for the previous full month." ]
Please provide a description of the function:def convert_context_to_csv(self, context): content = [] date_headers = context['date_headers'] headers = ['Name'] headers.extend([date.strftime('%m/%d/%Y') for date in date_headers]) headers.append('Total') content.append(headers) summaries = context['summaries'] summary = summaries.get(self.export, []) for rows, totals in summary: for name, user_id, hours in rows: data = [name] data.extend(hours) content.append(data) total = ['Totals'] total.extend(totals) content.append(total) return content
[ "Convert the context dictionary into a CSV file." ]
Please provide a description of the function:def defaults(self): # Set default date span to previous week. (start, end) = get_week_window(timezone.now() - relativedelta(days=7)) return { 'from_date': start, 'to_date': end, 'billable': True, 'non_billable': False, 'paid_leave': False, 'trunc': 'day', 'projects': [], }
[ "Default filter form data when no GET data is provided." ]
Please provide a description of the function:def get_hours_data(self, entries, date_headers): project_totals = get_project_totals( entries, date_headers, total_column=False) if entries else [] data_map = {} for rows, totals in project_totals: for user, user_id, periods in rows: for period in periods: day = period['day'] if day not in data_map: data_map[day] = {'billable': 0, 'nonbillable': 0} data_map[day]['billable'] += period['billable'] data_map[day]['nonbillable'] += period['nonbillable'] return data_map
[ "Sum billable and non-billable hours across all users." ]
Please provide a description of the function:def add_parameters(url, parameters): if parameters: sep = '&' if '?' in url else '?' return '{0}{1}{2}'.format(url, sep, urlencode(parameters)) return url
[ "\n Appends URL-encoded parameters to the base URL. It appends after '&' if\n '?' is found in the URL; otherwise it appends using '?'. Keep in mind that\n this tag does not take into account the value of existing params; it is\n therefore possible to add another value for a pre-existing parameter.\n\n For example::\n\n {% url 'this_view' as current_url %}\n {% with complete_url=current_url|add_parameters:request.GET %}\n The <a href=\"{% url 'other' %}?next={{ complete_url|urlencode }}\">\n other page</a> will redirect back to the current page (including\n any GET parameters).\n {% endwith %}\n " ]
Please provide a description of the function:def get_max_hours(context): progress = context['project_progress'] return max([0] + [max(p['worked'], p['assigned']) for p in progress])
[ "Return the largest number of hours worked or assigned on any project." ]
Please provide a description of the function:def get_uninvoiced_hours(entries, billable=None): statuses = ('invoiced', 'not-invoiced') if billable is not None: billable = (billable.lower() == u'billable') entries = [e for e in entries if e.activity.billable == billable] hours = sum([e.hours for e in entries if e.status not in statuses]) return '{0:.2f}'.format(hours)
[ "Given an iterable of entries, return the total hours that have\n not been invoiced. If billable is passed as 'billable' or 'nonbillable',\n limit to the corresponding entries.\n " ]
Please provide a description of the function:def humanize_hours(total_hours, frmt='{hours:02d}:{minutes:02d}:{seconds:02d}', negative_frmt=None): seconds = int(float(total_hours) * 3600) return humanize_seconds(seconds, frmt, negative_frmt)
[ "Given time in hours, return a string representing the time." ]
Please provide a description of the function:def humanize_seconds(total_seconds, frmt='{hours:02d}:{minutes:02d}:{seconds:02d}', negative_frmt=None): if negative_frmt is None: negative_frmt = '<span class="negative-time">-{0}</span>'.format(frmt) seconds = abs(int(total_seconds)) mapping = { 'hours': seconds // 3600, 'minutes': seconds % 3600 // 60, 'seconds': seconds % 3600 % 60, } if total_seconds < 0: result = negative_frmt.format(**mapping) else: result = frmt.format(**mapping) return mark_safe(result)
[ "Given time in int(seconds), return a string representing the time.\n\n If negative_frmt is not given, a negative sign is prepended to frmt\n and the result is wrapped in a <span> with the \"negative-time\" class.\n " ]
Please provide a description of the function:def project_hours_for_contract(contract, project, billable=None): hours = contract.entries.filter(project=project) if billable is not None: if billable in (u'billable', u'nonbillable'): billable = (billable.lower() == u'billable') hours = hours.filter(activity__billable=billable) else: msg = '`project_hours_for_contract` arg 4 must be "billable" ' \ 'or "nonbillable"' raise template.TemplateSyntaxError(msg) hours = hours.aggregate(s=Sum('hours'))['s'] or 0 return hours
[ "Total billable hours worked on project for contract.\n If billable is passed as 'billable' or 'nonbillable', limits to\n the corresponding hours. (Must pass a variable name first, of course.)\n " ]
Please provide a description of the function:def _timesheet_url(url_name, pk, date=None): url = reverse(url_name, args=(pk,)) if date: params = {'month': date.month, 'year': date.year} return '?'.join((url, urlencode(params))) return url
[ "Utility to create a time sheet URL with optional date parameters." ]
Please provide a description of the function:def reject_user_timesheet(request, user_id): form = YearMonthForm(request.GET or request.POST) user = User.objects.get(pk=user_id) if form.is_valid(): from_date, to_date = form.save() entries = Entry.no_join.filter( status=Entry.VERIFIED, user=user, start_time__gte=from_date, end_time__lte=to_date) if request.POST.get('yes'): if entries.exists(): count = entries.count() Entry.no_join.filter(pk__in=entries).update(status=Entry.UNVERIFIED) msg = 'You have rejected %d previously verified entries.' \ % count else: msg = 'There are no verified entries to reject.' messages.info(request, msg) else: return render(request, 'timepiece/user/timesheet/reject.html', { 'date': from_date, 'timesheet_user': user }) else: msg = 'You must provide a month and year for entries to be rejected.' messages.error(request, msg) url = reverse('view_user_timesheet', args=(user_id,)) return HttpResponseRedirect(url)
[ "\n This allows admins to reject all entries, instead of just one\n " ]
Please provide a description of the function:def _is_requirement(line): line = line.strip() return line and not (line.startswith("-r") or line.startswith("#"))
[ "Returns whether the line is a valid package requirement." ]
Please provide a description of the function:def render_to_response(self, context): if self.redirect_if_one_result: if self.object_list.count() == 1 and self.form.is_bound: return redirect(self.object_list.get().get_absolute_url()) return super(SearchMixin, self).render_to_response(context)
[ "\n When the user makes a search and there is only one result, redirect\n to the result's detail page rather than rendering the list.\n " ]
Please provide a description of the function:def clean_start_time(self): start = self.cleaned_data.get('start_time') if not start: return start active_entries = self.user.timepiece_entries.filter( start_time__gte=start, end_time__isnull=True) for entry in active_entries: output = ('The start time is on or before the current entry: ' '%s - %s starting at %s' % (entry.project, entry.activity, entry.start_time.strftime('%H:%M:%S'))) raise forms.ValidationError(output) return start
[ "\n Make sure that the start time doesn't come before the active entry\n " ]
Please provide a description of the function:def clean(self): active = utils.get_active_entry(self.user) start_time = self.cleaned_data.get('start_time', None) end_time = self.cleaned_data.get('end_time', None) if active and active.pk != self.instance.pk: if (start_time and start_time > active.start_time) or \ (end_time and end_time > active.start_time): raise forms.ValidationError( 'The start time or end time conflict with the active ' 'entry: {activity} on {project} starting at ' '{start_time}.'.format( project=active.project, activity=active.activity, start_time=active.start_time.strftime('%H:%M:%S'), )) month_start = utils.get_month_start(start_time) next_month = month_start + relativedelta(months=1) entries = self.instance.user.timepiece_entries.filter( Q(status=Entry.APPROVED) | Q(status=Entry.INVOICED), start_time__gte=month_start, end_time__lt=next_month ) entry = self.instance if not self.acting_user.is_superuser: if (entries.exists() and not entry.id or entry.id and entry.status == Entry.INVOICED): message = 'You cannot add/edit entries after a timesheet has been ' \ 'approved or invoiced. Please correct the start and end times.' raise forms.ValidationError(message) return self.cleaned_data
[ "\n If we're not editing the active entry, ensure that this entry doesn't\n conflict with or come after the active entry.\n " ]
Please provide a description of the function:def timespan(self, from_date, to_date=None, span=None, current=False): if span and not to_date: diff = None if span == 'month': diff = relativedelta(months=1) elif span == 'week': diff = relativedelta(days=7) elif span == 'day': diff = relativedelta(days=1) if diff is not None: to_date = from_date + diff datesQ = Q(end_time__gte=from_date) datesQ &= Q(end_time__lt=to_date) if to_date else Q() datesQ |= Q(end_time__isnull=True) if current else Q() return self.filter(datesQ)
[ "\n Takes a beginning date a filters entries. An optional to_date can be\n specified, or a span, which is one of ('month', 'week', 'day').\n N.B. - If given a to_date, it does not include that date, only before.\n " ]
Please provide a description of the function:def clock_in(request): user = request.user # Lock the active entry for the duration of this transaction, to prevent # creating multiple active entries. active_entry = utils.get_active_entry(user, select_for_update=True) initial = dict([(k, v) for k, v in request.GET.items()]) data = request.POST or None form = ClockInForm(data, initial=initial, user=user, active=active_entry) if form.is_valid(): entry = form.save() message = 'You have clocked into {0} on {1}.'.format( entry.activity.name, entry.project) messages.info(request, message) return HttpResponseRedirect(reverse('dashboard')) return render(request, 'timepiece/entry/clock_in.html', { 'form': form, 'active': active_entry, })
[ "For clocking the user into a project." ]
Please provide a description of the function:def toggle_pause(request): entry = utils.get_active_entry(request.user) if not entry: raise Http404 # toggle the paused state entry.toggle_paused() entry.save() # create a message that can be displayed to the user action = 'paused' if entry.is_paused else 'resumed' message = 'Your entry, {0} on {1}, has been {2}.'.format( entry.activity.name, entry.project, action) messages.info(request, message) # redirect to the log entry list return HttpResponseRedirect(reverse('dashboard'))
[ "Allow the user to pause and unpause the active entry." ]
Please provide a description of the function:def reject_entry(request, entry_id): return_url = request.GET.get('next', reverse('dashboard')) try: entry = Entry.no_join.get(pk=entry_id) except: message = 'No such log entry.' messages.error(request, message) return redirect(return_url) if entry.status == Entry.UNVERIFIED or entry.status == Entry.INVOICED: msg_text = 'This entry is unverified or is already invoiced.' messages.error(request, msg_text) return redirect(return_url) if request.POST.get('Yes'): entry.status = Entry.UNVERIFIED entry.save() msg_text = 'The entry\'s status was set to unverified.' messages.info(request, msg_text) return redirect(return_url) return render(request, 'timepiece/entry/reject.html', { 'entry': entry, 'next': request.GET.get('next'), })
[ "\n Admins can reject an entry that has been verified or approved but not\n invoiced to set its status to 'unverified' for the user to fix.\n " ]
Please provide a description of the function:def delete_entry(request, entry_id): try: entry = Entry.no_join.get(pk=entry_id, user=request.user) except Entry.DoesNotExist: message = 'No such entry found.' messages.info(request, message) url = request.GET.get('next', reverse('dashboard')) return HttpResponseRedirect(url) if request.method == 'POST': key = request.POST.get('key', None) if key and key == entry.delete_key: entry.delete() message = 'Deleted {0} for {1}.'.format(entry.activity.name, entry.project) messages.info(request, message) url = request.GET.get('next', reverse('dashboard')) return HttpResponseRedirect(url) else: message = 'You are not authorized to delete this entry!' messages.error(request, message) return render(request, 'timepiece/entry/delete.html', { 'entry': entry, })
[ "\n Give the user the ability to delete a log entry, with a confirmation\n beforehand. If this method is invoked via a GET request, a form asking\n for a confirmation of intent will be presented to the user. If this method\n is invoked via a POST request, the entry will be deleted.\n " ]
Please provide a description of the function:def get_hours_per_week(self, user=None): try: profile = UserProfile.objects.get(user=user or self.user) except UserProfile.DoesNotExist: profile = None return profile.hours_per_week if profile else Decimal('40.00')
[ "Retrieves the number of hours the user should work per week." ]
Please provide a description of the function:def process_progress(self, entries, assignments): # Determine all projects either worked or assigned. project_q = Q(id__in=assignments.values_list('project__id', flat=True)) project_q |= Q(id__in=entries.values_list('project__id', flat=True)) projects = Project.objects.filter(project_q).select_related('business') # Hours per project. project_data = {} for project in projects: try: assigned = assignments.get(project__id=project.pk).hours except ProjectHours.DoesNotExist: assigned = Decimal('0.00') project_data[project.pk] = { 'project': project, 'assigned': assigned, 'worked': Decimal('0.00'), } for entry in entries: pk = entry.project_id hours = Decimal('%.5f' % (entry.get_total_seconds() / 3600.0)) project_data[pk]['worked'] += hours # Sort by maximum of worked or assigned hours (highest first). key = lambda x: x['project'].name.lower() project_progress = sorted(project_data.values(), key=key) return project_progress
[ "\n Returns a list of progress summary data (pk, name, hours worked, and\n hours assigned) for each project either worked or assigned.\n The list is ordered by project name.\n " ]