Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def reverse_complement( self ):
rval = copy( self )
# Conveniently enough, reversing rows and columns is exactly what we
# want, since this results in A swapping with T and C swapping with G.
rval.values = self.values[::-1,::-1].copy(... | [
"\n Create the reverse complement of this matrix. The result probably\n only makese sense if the alphabet is that of DNA ('A','C','G','T').\n "
] |
Please provide a description of the function:def to_logodds_scoring_matrix( self, background=None, correction=DEFAULT_CORRECTION ):
alphabet_size = len( self.alphabet )
if background is None:
background = ones( alphabet_size, float32 ) / alphabet_size
# Row totals as a one c... | [
"\n Create a standard logodds scoring matrix.\n "
] |
Please provide a description of the function:def to_stormo_scoring_matrix( self, background=None ):
alphabet_size = len( self.alphabet )
if background is None:
background = ones( alphabet_size, float32 ) / alphabet_size
# Row totals as a one column array
totals = num... | [
"\n Create a scoring matrix from this count matrix using the method from:\n\n Hertz, G.Z. and G.D. Stormo (1999). Identifying DNA and protein patterns with statistically \n significant alignments of multiple sequences. Bioinformatics 15(7): 563-577.\n "
] |
Please provide a description of the function:def score_string( self, string ):
rval = zeros( len( string ), float32 )
rval[:] = nan
_pwm.score_string( self.values, self.char_to_index, string, rval )
return rval | [
"\n Score each valid position in `string` using this scoring matrix. \n Positions which were not scored are set to nan.\n "
] |
Please provide a description of the function:def _get_exchange_key_ntlm_v1(negotiate_flags, session_base_key,
server_challenge, lm_challenge_response,
lm_hash):
if negotiate_flags & \
NegotiateFlags.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURI... | [
"\n [MS-NLMP] v28.0 2016-07-14\n\n 3.4.5.1 KXKEY\n Calculates the Key Exchange Key for NTLMv1 authentication. Used for signing\n and sealing messages\n\n :param negotiate_flags: The negotiated NTLM flags\n :param session_base_key: A session key calculated from the user password\n challenge\... |
Please provide a description of the function:def _get_seal_key_ntlm1(negotiate_flags, exported_session_key):
if negotiate_flags & NegotiateFlags.NTLMSSP_NEGOTIATE_56:
seal_key = exported_session_key[:7] + b"\xa0"
else:
seal_key = exported_session_key[:5] + b"\xe5\x38\xb0"
return seal_k... | [
"\n 3.4.5.3 SEALKEY\n Calculates the seal_key used to seal (encrypt) messages. This for\n authentication where NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY has not\n been negotiated. Will weaken the keys if NTLMSSP_NEGOTIATE_56 is not\n negotiated it will default to the 40-bit key\n\n :param negotia... |
Please provide a description of the function:def get_nt_challenge_response(self, lm_challenge_response,
server_certificate_hash=None, cbt_data=None):
if self._negotiate_flags & \
NegotiateFlags.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY and \
... | [
"\n [MS-NLMP] v28.0 2016-07-14\n\n 3.3.1 - NTLM v1 Authentication\n 3.3.2 - NTLM v2 Authentication\n\n This method returns the NtChallengeResponse key based on the\n ntlm_compatibility chosen and the target_info supplied by the\n CHALLENGE_MESSAGE. It is quite different fro... |
Please provide a description of the function:def _get_LMv2_response(user_name, password, domain_name, server_challenge,
client_challenge):
nt_hash = comphash._ntowfv2(user_name, password, domain_name)
challenge = server_challenge + client_challenge
lm_hash = h... | [
"\n [MS-NLMP] v28.0 2016-07-14\n\n 2.2.2.4 LMv2_RESPONSE\n The LMv2_RESPONSE structure defines the NTLM v2 authentication\n LmChallengeResponse in the AUTHENTICATE_MESSAGE. This response is used\n only when NTLM v2 authentication is configured.\n\n :param user_name: The use... |
Please provide a description of the function:def _get_NTLM2_response(password, server_challenge, client_challenge):
ntlm_hash = comphash._ntowfv1(password)
challenge = server_challenge + client_challenge
nt_session_hash = hashlib.md5(challenge).digest()[:8]
response = ComputeRes... | [
"\n [MS-NLMP] v28.0 2016-07-14\n\n This name is really misleading as it isn't NTLM v2 authentication\n rather this authentication is only used when the ntlm_compatibility\n level is set to a value < 3 (No NTLMv2 auth) but the\n NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY flag is se... |
Please provide a description of the function:def _get_NTLMv2_response(user_name, password, domain_name,
server_challenge, client_challenge, timestamp,
target_info):
nt_hash = comphash._ntowfv2(user_name, password, domain_name)
temp = Co... | [
"\n [MS-NLMP] v28.0 2016-07-14\n\n 2.2.2.8 NTLM V2 Response: NTLMv2_RESPONSE\n The NTLMv2_RESPONSE strucutre defines the NTLMv2 authentication\n NtChallengeResponse in the AUTHENTICATE_MESSAGE. This response is used\n only when NTLMv2 authentication is configured.\n\n The g... |
Please provide a description of the function:def _get_NTLMv2_temp(timestamp, client_challenge, target_info):
resp_type = b'\x01'
hi_resp_type = b'\x01'
reserved1 = b'\x00' * 2
reserved2 = b'\x00' * 4
reserved3 = b'\x00' * 4
# This byte is not in the structure def... | [
"\n [MS-NLMP] v28.0 2016-07-14\n\n 2.2.2.7 NTLMv2_CLIENT_CHALLENGE - variable length\n The NTLMv2_CLIENT_CHALLENGE structure defines the client challenge in\n the AUTHENTICATE_MESSAGE. This structure is used only when NTLM v2\n authentication is configured and is transported in th... |
Please provide a description of the function:def _calc_resp(password_hash, server_challenge):
# padding with zeros to make the hash 21 bytes long
password_hash += b'\x00' * (21 - len(password_hash))
res = b''
dobj = DES(DES.key56_to_key64(password_hash[0:7]))
res = res ... | [
"\n Generate the LM response given a 16-byte password hash and the\n challenge from the CHALLENGE_MESSAGE\n\n :param password_hash: A 16-byte password hash\n :param server_challenge: A random 8-byte response generated by the\n server in the CHALLENGE_MESSAGE\n :return r... |
Please provide a description of the function:def encrypt(self, data, pad=True):
encrypted_data = b""
for i in range(0, len(data), 8):
block = data[i:i + 8]
block_length = len(block)
if block_length != 8 and pad:
block += b"\x00" * (8 - block_l... | [
"\n DES encrypts the data based on the key it was initialised with.\n\n :param data: The bytes string to encrypt\n :param pad: Whether to right pad data with \\x00 to a multiple of 8\n :return: The encrypted bytes string\n "
] |
Please provide a description of the function:def decrypt(self, data):
decrypted_data = b""
for i in range(0, len(data), 8):
block = data[i:i + 8]
block_length = len(block)
if block_length != 8:
raise ValueError("DES decryption must be a multip... | [
"\n DES decrypts the data based on the key it was initialised with.\n\n :param data: The encrypted bytes string to decrypt\n :return: The decrypted bytes string\n "
] |
Please provide a description of the function:def key56_to_key64(key):
if len(key) != 7:
raise ValueError("DES 7-byte key is not 7 bytes in length, "
"actual: %d" % len(key))
new_key = b""
for i in range(0, 8):
if i == 0:
... | [
"\n This takes in an a bytes string of 7 bytes and converts it to a bytes\n string of 8 bytes with the odd parity bit being set to every 8 bits,\n\n For example\n\n b\"\\x01\\x02\\x03\\x04\\x05\\x06\\x07\"\n 00000001 00000010 00000011 00000100 00000101 00000110 00000111\n\n ... |
Please provide a description of the function:def _lmowfv1(password):
# if the password is a hash, return the LM hash
if re.match(r'^[a-fA-F\d]{32}:[a-fA-F\d]{32}$', password):
lm_hash = binascii.unhexlify(password.split(':')[0])
return lm_hash
# fix the password to upper case and lengt... | [
"\n [MS-NLMP] v28.0 2016-07-14\n\n 3.3.1 NTLM v1 Authentication\n Same function as LMOWFv1 in document to create a one way hash of the\n password. Only used in NTLMv1 auth without session security\n\n :param password: The password or hash of the user we are trying to\n authenticate with\n :... |
Please provide a description of the function:def _ntowfv1(password):
# if the password is a hash, return the NT hash
if re.match(r'^[a-fA-F\d]{32}:[a-fA-F\d]{32}$', password):
nt_hash = binascii.unhexlify(password.split(':')[1])
return nt_hash
digest = hashlib.new('md4', password.enco... | [
"\n [MS-NLMP] v28.0 2016-07-14\n\n 3.3.1 NTLM v1 Authentication\n Same function as NTOWFv1 in document to create a one way hash of the\n password. Only used in NTLMv1 auth without session security\n\n :param password: The password or hash of the user we are trying to\n authenticate with\n :... |
Please provide a description of the function:def _ntowfv2(user_name, password, domain_name):
digest = _ntowfv1(password)
user = (user_name.upper() + domain_name).encode('utf-16-le')
digest = hmac.new(digest, user, digestmod=hashlib.md5).digest()
return digest | [
"\n [MS-NLMP] v28.0 2016-07-14\n\n 3.3.2 NTLM v2 Authentication\n Same function as NTOWFv2 (and LMOWFv2) in document to create a one way hash\n of the password. This combines some extra security features over the v1\n calculations used in NTLMv2 auth.\n\n :param user_name: The user name of the use... |
Please provide a description of the function:def visit_Method(self, method):
resolved_method = method.resolved.type
def get_params(method, extra_bindings):
# The Method should already be the resolved version.
result = []
for param in method.params:
... | [
"\n Ensure method has the same signature matching method on parent interface.\n\n :param method: L{quarkc.ast.Method} instance.\n "
] |
Please provide a description of the function:def urlparse(self, url, top=True, text=None, include=False, recurse=True):
if os.path.exists(url):
url = os.path.abspath(url)
urlc = compiled_quark(url)
if not include and url in self.CACHE:
self.log.debug("loading fr... | [
"\n Parse a quark file and, optionally, its recursive dependencies.\n\n A quark file (main.q) is loaded via urlparse() can have two kinds of\n dependencies, `use a.q` or `include b.q`. For the `use` case each file\n is added as a separate top-level root to self.roots. For the `include`\n... |
Please provide a description of the function:def get_doc(node):
res = " ".join(get_doc_annotations(node))
if not res:
res = "(%s)" % node.__class__.__name__.lower()
return res | [
"\n Return a node's documentation as a string, pulling from annotations\n or constructing a simple fake as needed.\n "
] |
Please provide a description of the function:def get_code(node, coder=Coder()):
return cgi.escape(str(coder.code(node)), quote=True) | [
"\n Return a node's code\n "
] |
Please provide a description of the function:def setup_environ(self):
SimpleHandler.setup_environ(self)
self.environ['ws4py.socket'] = get_connection(self.environ['wsgi.input'])
self.http_version = self.environ['SERVER_PROTOCOL'].rsplit('/')[-1] | [
"\n Setup the environ dictionary and add the\n `'ws4py.socket'` key. Its associated value\n is the real socket underlying socket.\n "
] |
Please provide a description of the function:def finish_response(self):
# force execution of the result iterator until first actual content
rest = iter(self.result)
first = list(itertools.islice(rest, 1))
self.result = itertools.chain(first, rest)
# now it's safe to look... | [
"\n Completes the response and performs the following tasks:\n\n - Remove the `'ws4py.socket'` and `'ws4py.websocket'`\n environ keys.\n - Attach the returned websocket, if any, to the WSGI server\n using its ``link_websocket_to_server`` method.\n "
] |
Please provide a description of the function:def handle(self):
self.raw_requestline = self.rfile.readline()
if not self.parse_request(): # An error code has been sent, just exit
return
# next line is where we'd have expect a configuration key somehow
handler = self.... | [
"\n Unfortunately the base class forces us\n to override the whole method to actually provide our wsgi handler.\n "
] |
Please provide a description of the function:def right_associative_infix_rule(operator, grammar_rule):
def semantic_action(self, node, (result, remaining)):
while remaining:
op, rhs = remaining.pop(0)
result = operator(Attr(result, Name(self.aliases[op])), [rhs], op)
ret... | [
"Semantic action for rules like 'A = B (C B)*'."
] |
Please provide a description of the function:def configure(self, voltage_range=RANGE_32V, gain=GAIN_AUTO,
bus_adc=ADC_12BIT, shunt_adc=ADC_12BIT):
self.__validate_voltage_range(voltage_range)
self._voltage_range = voltage_range
if self._max_expected_amps is not None:
... | [
" Configures and calibrates how the INA219 will take measurements.\n\n Arguments:\n voltage_range -- The full scale voltage range, this is either 16V\n or 32V represented by one of the following constants;\n RANGE_16V, RANGE_32V (default).\n gain -- The gain which controls... |
Please provide a description of the function:def wake(self):
configuration = self._read_configuration()
self._configuration_register(configuration | 0x0007)
# 40us delay to recover from powerdown (p14 of spec)
time.sleep(0.00004) | [
" Wake the INA219 from power down mode "
] |
Please provide a description of the function:def _return_response_and_status_code(response, json_results=True):
if response.status_code == requests.codes.ok:
return dict(results=response.json() if json_results else response.content, response_code=response.status_code)
elif response.status_code == 4... | [
" Output the requests response content or content as json and status code\n\n :rtype : dict\n :param response: requests response object\n :param json_results: Should return JSON or raw content\n :return: dict containing the response content and/or the status code with error string.\n "
] |
Please provide a description of the function:def rescan_file(self, this_hash, timeout=None):
params = {'apikey': self.api_key, 'resource': this_hash}
try:
response = requests.post(self.base + 'file/rescan', params=params, proxies=self.proxies, timeout=timeout)
except reques... | [
" Rescan a previously submitted filed or schedule an scan to be performed in the future.\n\n :param this_hash: a md5/sha1/sha256 hash. You can also specify a CSV list made up of a combination of any of\n the three allowed hashes (up to 25 items), this allows you to perform a batch re... |
Please provide a description of the function:def put_comments(self, resource, comment, timeout=None):
params = {'apikey': self.api_key, 'resource': resource, 'comment': comment}
try:
response = requests.post(self.base + 'comments/put', params=params, proxies=self.proxies, timeout=t... | [
" Post a comment on a file or URL.\n\n The initial idea of VirusTotal Community was that users should be able to make comments on files and URLs,\n the comments may be malware analyses, false positive flags, disinfection instructions, etc.\n\n Imagine you have some automatic setup that can prod... |
Please provide a description of the function:def get_ip_report(self, this_ip, timeout=None):
params = {'apikey': self.api_key, 'ip': this_ip}
try:
response = requests.get(self.base + 'ip-address/report',
params=params,
... | [
" Get IP address reports.\n\n :param this_ip: a valid IPv4 address in dotted quad notation, for the time being only IPv4 addresses are\n supported.\n :param timeout: The amount of time in seconds the request should wait before timing out.\n\n :return: JSON response\n ... |
Please provide a description of the function:def get_domain_report(self, this_domain, timeout=None):
params = {'apikey': self.api_key, 'domain': this_domain}
try:
response = requests.get(self.base + 'domain/report', params=params, proxies=self.proxies, timeout=timeout)
exce... | [
" Get information about a given domain.\n\n :param this_domain: a domain name.\n :param timeout: The amount of time in seconds the request should wait before timing out.\n\n :return: JSON response\n "
] |
Please provide a description of the function:def scan_file(self,
this_file,
notify_url=None,
notify_changes_only=None,
from_disk=True,
filename=None,
timeout=None):
params = {'apikey': self.api_k... | [
" Submit a file to be scanned by VirusTotal.\n\n Allows you to send a file for scanning with VirusTotal. Before performing your submissions we encourage you to\n retrieve the latest report on the files, if it is recent enough you might want to save time and bandwidth by\n making use of it. File... |
Please provide a description of the function:def get_upload_url(self, timeout=None):
params = {'apikey': self.api_key}
try:
response = requests.get(self.base + 'file/scan/upload_url',
params=params,
proxies=sel... | [
" Get a special URL for submitted files bigger than 32MB.\n\n In order to submit files bigger than 32MB you need to obtain a special upload URL to which you\n can POST files up to 200MB in size. This API generates such a URL.\n\n :param timeout: The amount of time in seconds the request should ... |
Please provide a description of the function:def get_file_report(self, resource, allinfo=1, timeout=None):
params = {'apikey': self.api_key, 'resource': resource, 'allinfo': allinfo}
try:
response = requests.get(self.base + 'file/report', params=params, proxies=self.proxies, timeou... | [
" Get the scan results for a file.\n\n Retrieves a concluded file scan report for a given file. Unlike the public API, this call allows you to also\n access all the information we have on a particular file (VirusTotal metadata, signature information, structural\n information, etc.) by using the... |
Please provide a description of the function:def file_search(self, query, offset=None, timeout=None):
params = dict(apikey=self.api_key, query=query, offset=offset)
try:
response = requests.get(self.base + 'file/search', params=params, proxies=self.proxies, timeout=timeout)
... | [
" Search for samples.\n\n In addition to retrieving all information on a particular file, VirusTotal allows you to perform what we\n call \"advanced reverse searches\". Reverse searches take you from a file property to a list of files that\n match that property. For example, this functionality ... |
Please provide a description of the function:def get_file_clusters(self, this_date, timeout=None):
params = {'apikey': self.api_key, 'date': this_date}
try:
response = requests.get(self.base + 'file/clusters', params=params, proxies=self.proxies, timeout=timeout)
except req... | [
" File similarity clusters for a given time frame.\n\n VirusTotal has built its own in-house file similarity clustering functionality. At present, this clustering\n works only on PE, PDF, DOC and RTF files and is based on a very simple structural feature hash. This hash\n can very often be conf... |
Please provide a description of the function:def get_url_distribution(self, after=None, reports='true', limit=1000, timeout=None):
params = {'apikey': self.api_key, 'after': after, 'reports': reports, 'limit': limit}
try:
response = requests.get(self.base + 'url/distribution',
... | [
" Get a live feed with the lastest URLs submitted to VirusTotal.\n\n Allows you to retrieve a live feed of URLs submitted to VirusTotal, along with their scan reports. This\n call enables you to stay synced with VirusTotal URL submissions and replicate our dataset.\n\n :param after: (optional) ... |
Please provide a description of the function:def get_url_feed(self, package=None, timeout=None):
if package is None:
now = datetime.utcnow()
five_minutes_ago = now - timedelta(
minutes=now.minute % 5 + 5, seconds=now.second, microseconds=now.microsecond)
... | [
" Get a live file feed with the latest files submitted to VirusTotal.\n\n Allows you to retrieve a live feed of reports on absolutely all URLs scanned by VirusTotal. This API requires\n you to stay relatively synced with the live submissions as only a backlog of 24 hours is provided at any given\n ... |
Please provide a description of the function:def get_hashes_from_search(self, query, page=None, timeout=None):
params = {'query': query, 'apikey': self.api_key, 'page': page}
try:
response = requests.get(self.base + 'search/programmatic/',
params... | [
" Get the scan results for a file.\n\n Even if you do not have a Private Mass API key that you can use, you can still automate VirusTotal Intelligence\n searches pretty much in the same way that the searching for files api call works.\n\n :param query: a VirusTotal Intelligence search string in... |
Please provide a description of the function:def get_file(self, file_hash, save_file_at, timeout=None):
params = {'hash': file_hash, 'apikey': self.api_key}
try:
response = requests.get(self.base + 'download/',
params=params,
... | [
" Get the scan results for a file.\n\n Even if you do not have a Private Mass API key that you can use, you can still download files from the\n VirusTotal storage making use of your VirusTotal Intelligence quota, i.e. programmatic downloads will\n also deduct quota.\n\n :param file_hash:... |
Please provide a description of the function:def get_all_file_report_pages(self, query):
responses = []
r = self.get_hashes_from_search(query)
responses.append(r)
if ('results' in r.keys()) and ('next_page' in r['results'].keys()):
next_page = r['results']['next_pag... | [
" Get File Report (All Pages).\n\n :param query: a VirusTotal Intelligence search string in accordance with the file search documentation.\n :return: All JSON responses appended together.\n "
] |
Please provide a description of the function:def get_intel_notifications_feed(self, page=None, timeout=None):
params = {'apikey': self.api_key, 'next': page}
try:
response = requests.get(self.base + 'hunting/notifications-feed/',
params=params,
... | [
" Get notification feed in JSON for further processing.\n\n :param page: the next_page property of the results of a previously issued query to this API. This parameter\n should not be provided if it is the very first query to the API, i.e. if we are retrieving the\n first page of result... |
Please provide a description of the function:def delete_intel_notifications(self, ids, timeout=None):
if not isinstance(ids, list):
raise TypeError("ids must be a list")
# VirusTotal needs ids as a stringified array
data = json.dumps(ids)
try:
response ... | [
" Programmatically delete notifications via the Intel API.\n\n :param ids: A list of IDs to delete from the notification feed.\n :returns: The post response.\n "
] |
Please provide a description of the function:def get_credentials(self):
return Credentials(access_key=self.aws_access_key_id,
secret_key=self.aws_secret_access_key,
token=self.aws_session_token) | [
"\n Returns botocore.credential.Credential object.\n "
] |
Please provide a description of the function:def check_membership(self, group):
user_groups = self.request.user.groups.values_list("name", flat=True)
if isinstance(group, (list, tuple)):
for req_group in group:
if req_group in user_groups:
return ... | [
" Check required group(s) "
] |
Please provide a description of the function:def form_valid(self, form):
ret = super(HookCreate, self).form_valid(form)
# Good to make note of that
messages.add_message(self.request, messages.SUCCESS, 'Hook %s created' % self.object.url)
return ret | [
"After the form is valid lets let people know"
] |
Please provide a description of the function:def form_valid(self, form):
form_valid_from_parent = super(HostCreate, self).form_valid(form)
messages.success(self.request, 'Host {} Successfully Created'.format(self.object))
return form_valid_from_parent | [
"First call the parent's form valid then let the user know it worked."
] |
Please provide a description of the function:def post(self, *args, **kwargs):
existing_ssh = models.SSHConfig.objects.all()
if existing_ssh.exists():
return self.get_view()
remote_user = self.request.POST.get('remote_user', 'root')
create_ssh_config(remote_user=r... | [
"Create the SSH file & then return the normal get method..."
] |
Please provide a description of the function:def update_sandbox_site(comment_text):
file_to_deliver = NamedTemporaryFile(delete=False)
file_text = "Deployed at: {} <br /> Comment: {}".format(datetime.datetime.now().strftime('%c'), cgi.escape(comment_text))
file_to_deliver.write(file_text)
file_t... | [
"put's a text file on the server"
] |
Please provide a description of the function:def web_hooks(self, include_global=True):
from fabric_bolt.web_hooks.models import Hook
ors = [Q(project=self)]
if include_global:
ors.append(Q(project=None))
hooks = Hook.objects.filter(reduce(operator.or_, ors))
... | [
"Get all web hooks for this project. Includes global hooks."
] |
Please provide a description of the function:def get_deployment_count(self):
ret = self.stage_set.annotate(num_deployments=Count('deployment')).aggregate(total_deployments=Sum('num_deployments'))
return ret['total_deployments'] | [
"Utility function to get the number of deployments a given project has"
] |
Please provide a description of the function:def get_queryset_configurations(self, **kwargs):
queryset_list = []
current_configs = []
# Create stage specific configurations dictionary
for stage in self.stage_configurations().filter(**kwargs):
queryset_list.append(st... | [
"\n Really we just want to do a simple SQL statement like this (but oh the ORM):\n\n SELECT Distinct(Coalesce(stage.key, project.key)) AS key,\n (CASE WHEN stage.key IS NOT null THEN stage.data_type ELSE project.data_type END) AS data_type,\n (CASE WHEN stage.key IS NOT null THEN stage.v... |
Please provide a description of the function:def get_configurations(self):
project_configurations_dictionary = {}
project_configurations = self.project.project_configurations()
# Create project specific configurations dictionary
for config in project_configurations:
... | [
"\n Generates a dictionary that's made up of the configurations on the project.\n Any configurations on a project that are duplicated on a stage, the stage configuration will take precedence.\n "
] |
Please provide a description of the function:def get_absolute_url(self):
# Determine if this configuration is on a stage
if self.stage:
# Stage specific configurations go back to the stage view
url = reverse('projects_stage_view', args=(self.project.pk, self.stage.pk))
... | [
"Determine where I am coming from and where I am going"
] |
Please provide a description of the function:def get_value(self):
if self.data_type == self.BOOLEAN_TYPE:
return self.value_boolean
elif self.data_type == self.NUMBER_TYPE:
return self.value_number
elif self.data_type == self.SSH_KEY_TYPE:
return sel... | [
"Determine the proper value based on the data_type"
] |
Please provide a description of the function:def set_value(self, value):
if self.data_type == self.BOOLEAN_TYPE:
self.value_boolean = bool(value)
elif self.data_type == self.NUMBER_TYPE:
self.value_number = float(value)
else:
self.value = value | [
"Determine the proper value based on the data_type"
] |
Please provide a description of the function:def add_output(self, line):
Deployment.objects.filter(pk=self.id).update(output=CF('output')+line) | [
"\n Appends {line} of output to the output instantly. (directly hits the database)\n :param line: the line of text to append\n :return: None\n "
] |
Please provide a description of the function:def add_input(self, line):
Deployment.objects.filter(pk=self.id).update(input=CF('input')+line) | [
"\n Appends {line} of input to the input instantly. (directly hits the database)\n :param line: the line of text to append\n :return: None\n "
] |
Please provide a description of the function:def get_next_input(self):
# TODO: could override input if we get input coming in at the same time
all_input = Deployment.objects.get(pk=self.id).input or ''
lines = all_input.splitlines()
first_line = lines[0] if len(lines) else None... | [
"\n Returns the next line of input\n :return: string of input\n "
] |
Please provide a description of the function:def gravatar(self, size=20):
default = "mm"
gravatar_url = "//www.gravatar.com/avatar/" + hashlib.md5(self.email.lower()).hexdigest() + "?"
gravatar_url += urllib.urlencode({'d': default, 's': str(size)})
return gravatar_url | [
"\n Construct a gravatar image address for the user\n "
] |
Please provide a description of the function:def save(self, commit=True):
instance = super(UserChangeForm, self).save(commit=commit)
if commit:
self.set_permissions(instance)
return instance | [
"\n Save the model instance with the correct Auth Group based on the user_level question\n "
] |
Please provide a description of the function:def save(self, commit=True):
instance = super(UserCreationForm, self).save(commit=commit)
random_password = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(32))
instance.set_password(random_password)
insta... | [
"\n Save the model instance with the correct Auth Group based on the user_level question\n "
] |
Please provide a description of the function:def hooks(self, project):
return self.get_queryset().filter(
Q(project=None) |
Q(project=project)
).distinct('url') | [
" Look up the urls we need to post to"
] |
Please provide a description of the function:def web_hook_receiver(sender, **kwargs):
deployment = Deployment.objects.get(pk=kwargs.get('deployment_id'))
hooks = deployment.web_hooks
if not hooks:
return
for hook in hooks:
data = payload_generator(deployment)
deliver_h... | [
"Generic receiver for the web hook firing piece."
] |
Please provide a description of the function:def full_domain_validator(hostname):
HOSTNAME_LABEL_PATTERN = re.compile("(?!-)[A-Z\d-]+(?<!-)$", re.IGNORECASE)
if not hostname:
return
if len(hostname) > 255:
raise ValidationError(_("The domain name cannot be composed of more than 255 cha... | [
"\n Fully validates a domain name as compilant with the standard rules:\n - Composed of series of labels concatenated with dots, as are all domain names.\n - Each label must be between 1 and 63 characters long.\n - The entire hostname (including the delimiting dots) has a maximum of 255 char... |
Please provide a description of the function:def serialize_hook(instance):
if getattr(instance, 'serialize_hook', None) and callable(instance.serialize_hook):
return instance.serialize_hook(hook=instance)
if getattr(settings, 'HOOK_SERIALIZER', None):
serializer = get_module(settings.HOOK_... | [
"\n Serialize the object down to Python primitives.\n\n By default it uses Django's built in serializer.\n "
] |
Please provide a description of the function:def deliver_hook(instance, target, payload_override=None):
payload = payload_override or serialize_hook(instance)
if hasattr(settings, 'HOOK_DELIVERER'):
deliverer = get_module(settings.HOOK_DELIVERER)
deliverer(target, payload, instance=instance... | [
"\n Deliver the payload to the target URL.\n\n By default it serializes to JSON and POSTs.\n "
] |
Please provide a description of the function:def paginate(self, klass=Paginator, per_page=None, page=1, *args, **kwargs):
self.per_page_options = [25, 50, 100, 200] # This should probably be a passed in option
self.per_page = per_page = per_page or self._meta.per_page
self.paginator... | [
"\n Paginates the table using a paginator and creates a ``page`` property\n containing information for the current page.\n\n :type klass: Paginator class\n :param klass: a paginator class to paginate the results\n :type per_page: `int`\n :param per_page: how many re... |
Please provide a description of the function:def get_fabric_tasks(self, project):
cache_key = 'project_{}_fabfile_tasks'.format(project.pk)
cached_result = cache.get(cache_key)
if cached_result:
return cached_result
try:
fabfile_path, activate_loc = se... | [
"\n Generate a list of fabric tasks that are available\n "
] |
Please provide a description of the function:def form_valid(self, form):
ret = super(ProjectCreate, self).form_valid(form)
# Good to make note of that
messages.add_message(self.request, messages.SUCCESS, 'Project %s created' % self.object.name)
return ret | [
"After the form is valid lets let people know"
] |
Please provide a description of the function:def get_initial(self):
initial = super(ProjectCopy, self).get_initial()
if self.copy_object:
initial.update({'name': '%s copy' % self.copy_object.name,
'description': self.copy_object.description,
... | [
"\n Returns the initial data to use for forms on this view.\n "
] |
Please provide a description of the function:def copy_configurations(self, stages=None):
if stages:
confs = stages[0].stage_configurations()
new_stage = stages[1]
else:
confs = self.copy_object.project_configurations()
new_stage = None
fo... | [
"\n Copy configuretions\n "
] |
Please provide a description of the function:def form_valid(self, form):
ret = super(ProjectCopy, self).form_valid(form)
self.copy_relations()
# Good to make note of that
messages.add_message(self.request, messages.SUCCESS, 'Project %s copied' % self.object.name)
retu... | [
"After the form is valid lets let people know"
] |
Please provide a description of the function:def form_valid(self, form):
self.object = form.save(commit=False)
self.object.project = self.project
if self.kwargs.get('stage_id', None):
current_stage = models.Stage.objects.get(pk=self.kwargs.get('stage_id'))
self... | [
"Set the project on this configuration after it's valid"
] |
Please provide a description of the function:def get_success_url(self):
if self.stage_id:
url = reverse('projects_stage_view', args=(self.project_id, self.stage_id))
else:
url = reverse('projects_project_view', args=(self.project_id,))
return url | [
"Get the url depending on what type of configuration I deleted."
] |
Please provide a description of the function:def form_valid(self, form):
self.object = form.save(commit=False)
self.object.project = self.project
self.object.save()
# Good to make note of that
messages.add_message(self.request, messages.SUCCESS, 'Stage %s created' % se... | [
"Set the project on this configuration after it's valid"
] |
Please provide a description of the function:def run(self, target, payload, instance=None, hook_id=None, **kwargs):
self.post_data(target, payload, hook_id) | [
"\n target: the url to receive the payload.\n payload: a python primitive data structure\n instance: a possibly null \"trigger\" instance\n hook: the defining Hook object (useful for removing)\n "
] |
Please provide a description of the function:def create_ssh_config(remote_user='root', name='Auto Generated SSH Key',
file_name='fabricbolt_private.key', email='deployments@fabricbolt.io', public_key_text=None,
private_key_text=None):
if not private_key_text and not... | [
"Create SSH Key"
] |
Please provide a description of the function:def convert(self, json="", table_attributes='border="1"', clubbing=True, encode=False, escape=True):
# table attributes such as class, id, data-attr-*, etc.
# eg: table_attributes = 'class = "table table-bordered sortable"'
self.table_init_ma... | [
"\n Convert JSON to HTML Table format\n "
] |
Please provide a description of the function:def column_headers_from_list_of_dicts(self, json_input):
if not json_input \
or not hasattr(json_input, '__getitem__') \
or not hasattr(json_input[0], 'keys'):
return None
column_headers = json_input[0].keys()
for ... | [
"\n This method is required to implement clubbing.\n It tries to come up with column headers for your input\n "
] |
Please provide a description of the function:def convert_json_node(self, json_input):
if type(json_input) in text_types:
if self.escape:
return cgi.escape(text(json_input))
else:
return text(json_input)
if hasattr(json_input, 'items'):
... | [
"\n Dispatch JSON input according to the outermost type and process it\n to generate the super awesome HTML format.\n We try to adhere to duck typing such that users can just pass all kinds\n of funky objects to json2html that *behave* like dicts and lists and other\n ... |
Please provide a description of the function:def convert_list(self, list_input):
if not list_input:
return ""
converted_output = ""
column_headers = None
if self.clubbing:
column_headers = self.column_headers_from_list_of_dicts(list_input)
if colu... | [
"\n Iterate over the JSON list and process it\n to generate either an HTML table or a HTML list, depending on what's inside.\n If suppose some key has array of objects and all the keys are same,\n instead of creating a new row for each such entry,\n club such v... |
Please provide a description of the function:def convert_object(self, json_input):
if not json_input:
return "" #avoid empty tables
converted_output = self.table_init_markup + "<tr>"
converted_output += "</tr><tr>".join([
"<th>%s</th><td>%s</td>" %(
... | [
"\n Iterate over the JSON object and process it\n to generate the super awesome HTML Table format\n "
] |
Please provide a description of the function:def cameraUrls(self, camera=None, home=None, cid=None):
local_url = None
vpn_url = None
if cid:
camera_data=self.cameraById(cid)
else:
camera_data=self.cameraByName(camera=camera, home=home)
if camera_d... | [
"\n Return the vpn_url and the local_url (if available) of a given camera\n in order to access to its live feed\n Can't use the is_local property which is mostly false in case of operator\n dynamic IP change after presence start sequence\n "
] |
Please provide a description of the function:def personsAtHome(self, home=None):
if not home: home = self.default_home
home_data = self.homeByName(home)
atHome = []
for p in home_data['persons']:
#Only check known persons
if 'pseudo' in p:
... | [
"\n Return the list of known persons who are currently at home\n "
] |
Please provide a description of the function:def getCameraPicture(self, image_id, key):
postParams = {
"access_token" : self.getAuthToken,
"image_id" : image_id,
"key" : key
}
resp = postRequest(_GETCAMERAPICTURE_REQ, postParams)
image_typ... | [
"\n Download a specific image (of an event or user face) from the camera\n "
] |
Please provide a description of the function:def getProfileImage(self, name):
for p in self.persons:
if 'pseudo' in self.persons[p]:
if name == self.persons[p]['pseudo']:
image_id = self.persons[p]['face']['id']
key = self.persons[p]['... | [
"\n Retrieve the face of a given person\n "
] |
Please provide a description of the function:def updateEvent(self, event=None, home=None):
if not home: home=self.default_home
if not event:
#If not event is provided we need to retrieve the oldest of the last event seen by each camera
listEvent = dict()
for ... | [
"\n Update the list of event with the latest ones\n "
] |
Please provide a description of the function:def personSeenByCamera(self, name, home=None, camera=None):
try:
cam_id = self.cameraByName(camera=camera, home=home)['id']
except TypeError:
logger.warning("personSeenByCamera: Camera name or home is unknown")
ret... | [
"\n Return True if a specific person has been seen by a camera\n "
] |
Please provide a description of the function:def someoneKnownSeen(self, home=None, camera=None):
try:
cam_id = self.cameraByName(camera=camera, home=home)['id']
except TypeError:
logger.warning("personSeenByCamera: Camera name or home is unknown")
return Fals... | [
"\n Return True if someone known has been seen\n "
] |
Please provide a description of the function:def motionDetected(self, home=None, camera=None):
try:
cam_id = self.cameraByName(camera=camera, home=home)['id']
except TypeError:
logger.warning("personSeenByCamera: Camera name or home is unknown")
return False
... | [
"\n Return True if movement has been detected\n "
] |
Please provide a description of the function:def batch(sequence, callback, size=100, **kwargs):
batch_len, rem = divmod(len(sequence), size)
if rem > 0:
batch_len += 1
for i in range(batch_len):
offset = i * size
yield callback(sequence[offset:offset + size], **kwargs) | [
"Helper to setup batch requests.\n\n There are endpoints which support updating multiple resources at once,\n but they are often limited to 100 updates per request.\n This function helps with splitting bigger requests into sequence of\n smaller ones.\n\n Example:\n def add_organization_tag(org... |
Please provide a description of the function:def call(self, path, query=None, method='GET', data=None,
files=None, get_all_pages=False, complete_response=False,
retry_on=None, max_retries=0, raw_query=None, retval=None,
**kwargs):
# Rather obscure way to support ... | [
"Make a REST call to the Zendesk web service.\n\n Parameters:\n path - Path portion of the Zendesk REST endpoint URL.\n query - Query parameters in dict form.\n method - HTTP method to use in making the request.\n data - POST data or multi-part form data to include.\n files... |
Please provide a description of the function:def _handle_retry(self, resp):
exc_t, exc_v, exc_tb = sys.exc_info()
if exc_t is None:
raise TypeError('Must be called in except block.')
retry_on_exc = tuple(
(x for x in self._retry_on if inspect.isclass(x)))
... | [
"Handle any exceptions during API request or\n parsing its response status code.\n\n Parameters:\n resp: requests.Response instance obtained during concerning request\n or None, when request failed\n\n Returns: True if should retry our request or raises original Exception\n ... |
Please provide a description of the function:def account_settings_update(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/account_settings#update-account-settings"
api_path = "/api/v2/account/settings.json"
return self.call(api_path, method="PUT", data=data, **kwargs) | [] |
Please provide a description of the function:def account_update(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/accounts#update-account"
api_path = "/api/v2/account"
return self.call(api_path, method="PUT", data=data, **kwargs) | [] |
Please provide a description of the function:def activities_list(self, since=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/activity_stream#list-activities"
api_path = "/api/v2/activities.json"
api_query = {}
if "query" in kwargs.keys():
api_query.update(k... | [] |
Please provide a description of the function:def activity_show(self, activity_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/activity_stream#show-activity"
api_path = "/api/v2/activities/{activity_id}.json"
api_path = api_path.format(activity_id=activity_id)
return self... | [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.