repository_name
stringlengths 7
55
| func_path_in_repository
stringlengths 4
223
| func_name
stringlengths 1
134
| whole_func_string
stringlengths 75
104k
| language
stringclasses 1
value | func_code_string
stringlengths 75
104k
| func_code_tokens
sequencelengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
sequencelengths 1
1.97k
| split_name
stringclasses 1
value | func_code_url
stringlengths 87
315
|
---|---|---|---|---|---|---|---|---|---|---|
proycon/clam | clam/common/parameters.py | ChoiceParameter.valuefrompostdata | def valuefrompostdata(self, postdata):
"""This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set()"""
if self.multi: #multi parameters can be passed as parameterid=choiceid1,choiceid2 or by setting parameterid[choiceid]=1 (or whatever other non-zero value)
found = False
if self.id in postdata:
found = True
passedvalues = postdata[self.id].split(',')
values = []
for choicekey in [x[0] for x in self.choices]:
if choicekey in passedvalues:
found = True
values.append(choicekey)
else:
values = []
for choicekey in [x[0] for x in self.choices]:
if self.id+'['+choicekey+']' in postdata:
found = True
if postdata[self.id+'['+choicekey+']']:
values.append(choicekey)
if not found:
return None
else:
return values
else:
if self.id in postdata:
return postdata[self.id]
else:
return None | python | def valuefrompostdata(self, postdata):
"""This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set()"""
if self.multi: #multi parameters can be passed as parameterid=choiceid1,choiceid2 or by setting parameterid[choiceid]=1 (or whatever other non-zero value)
found = False
if self.id in postdata:
found = True
passedvalues = postdata[self.id].split(',')
values = []
for choicekey in [x[0] for x in self.choices]:
if choicekey in passedvalues:
found = True
values.append(choicekey)
else:
values = []
for choicekey in [x[0] for x in self.choices]:
if self.id+'['+choicekey+']' in postdata:
found = True
if postdata[self.id+'['+choicekey+']']:
values.append(choicekey)
if not found:
return None
else:
return values
else:
if self.id in postdata:
return postdata[self.id]
else:
return None | [
"def",
"valuefrompostdata",
"(",
"self",
",",
"postdata",
")",
":",
"if",
"self",
".",
"multi",
":",
"#multi parameters can be passed as parameterid=choiceid1,choiceid2 or by setting parameterid[choiceid]=1 (or whatever other non-zero value)",
"found",
"=",
"False",
"if",
"self",
".",
"id",
"in",
"postdata",
":",
"found",
"=",
"True",
"passedvalues",
"=",
"postdata",
"[",
"self",
".",
"id",
"]",
".",
"split",
"(",
"','",
")",
"values",
"=",
"[",
"]",
"for",
"choicekey",
"in",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"self",
".",
"choices",
"]",
":",
"if",
"choicekey",
"in",
"passedvalues",
":",
"found",
"=",
"True",
"values",
".",
"append",
"(",
"choicekey",
")",
"else",
":",
"values",
"=",
"[",
"]",
"for",
"choicekey",
"in",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"self",
".",
"choices",
"]",
":",
"if",
"self",
".",
"id",
"+",
"'['",
"+",
"choicekey",
"+",
"']'",
"in",
"postdata",
":",
"found",
"=",
"True",
"if",
"postdata",
"[",
"self",
".",
"id",
"+",
"'['",
"+",
"choicekey",
"+",
"']'",
"]",
":",
"values",
".",
"append",
"(",
"choicekey",
")",
"if",
"not",
"found",
":",
"return",
"None",
"else",
":",
"return",
"values",
"else",
":",
"if",
"self",
".",
"id",
"in",
"postdata",
":",
"return",
"postdata",
"[",
"self",
".",
"id",
"]",
"else",
":",
"return",
"None"
] | This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set() | [
"This",
"parameter",
"method",
"searches",
"the",
"POST",
"data",
"and",
"retrieves",
"the",
"values",
"it",
"needs",
".",
"It",
"does",
"not",
"set",
"the",
"value",
"yet",
"though",
"but",
"simply",
"returns",
"it",
".",
"Needs",
"to",
"be",
"explicitly",
"passed",
"to",
"parameter",
".",
"set",
"()"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/parameters.py#L489-L516 |
proycon/clam | clam/common/parameters.py | IntegerParameter.valuefrompostdata | def valuefrompostdata(self, postdata):
"""This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set()"""
if self.id in postdata and postdata[self.id] != '':
return int(postdata[self.id])
else:
return None | python | def valuefrompostdata(self, postdata):
"""This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set()"""
if self.id in postdata and postdata[self.id] != '':
return int(postdata[self.id])
else:
return None | [
"def",
"valuefrompostdata",
"(",
"self",
",",
"postdata",
")",
":",
"if",
"self",
".",
"id",
"in",
"postdata",
"and",
"postdata",
"[",
"self",
".",
"id",
"]",
"!=",
"''",
":",
"return",
"int",
"(",
"postdata",
"[",
"self",
".",
"id",
"]",
")",
"else",
":",
"return",
"None"
] | This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set() | [
"This",
"parameter",
"method",
"searches",
"the",
"POST",
"data",
"and",
"retrieves",
"the",
"values",
"it",
"needs",
".",
"It",
"does",
"not",
"set",
"the",
"value",
"yet",
"though",
"but",
"simply",
"returns",
"it",
".",
"Needs",
"to",
"be",
"explicitly",
"passed",
"to",
"parameter",
".",
"set",
"()"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/parameters.py#L575-L580 |
proycon/clam | clam/common/parameters.py | IntegerParameter.set | def set(self, value):
"""This parameter method attempts to set a specific value for this parameter. The value will be validated first, and if it can not be set. An error message will be set in the error property of this parameter"""
if self.validate(value):
#print "Parameter " + self.id + " successfully set to " + repr(value)
self.hasvalue = True
if isinstance(value, float):
self.value = round(value)
else:
self.value = int(value)
return True
else:
#print "Parameter " + self.id + " COULD NOT BE set to " + repr(value)
return False | python | def set(self, value):
"""This parameter method attempts to set a specific value for this parameter. The value will be validated first, and if it can not be set. An error message will be set in the error property of this parameter"""
if self.validate(value):
#print "Parameter " + self.id + " successfully set to " + repr(value)
self.hasvalue = True
if isinstance(value, float):
self.value = round(value)
else:
self.value = int(value)
return True
else:
#print "Parameter " + self.id + " COULD NOT BE set to " + repr(value)
return False | [
"def",
"set",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"validate",
"(",
"value",
")",
":",
"#print \"Parameter \" + self.id + \" successfully set to \" + repr(value)",
"self",
".",
"hasvalue",
"=",
"True",
"if",
"isinstance",
"(",
"value",
",",
"float",
")",
":",
"self",
".",
"value",
"=",
"round",
"(",
"value",
")",
"else",
":",
"self",
".",
"value",
"=",
"int",
"(",
"value",
")",
"return",
"True",
"else",
":",
"#print \"Parameter \" + self.id + \" COULD NOT BE set to \" + repr(value)",
"return",
"False"
] | This parameter method attempts to set a specific value for this parameter. The value will be validated first, and if it can not be set. An error message will be set in the error property of this parameter | [
"This",
"parameter",
"method",
"attempts",
"to",
"set",
"a",
"specific",
"value",
"for",
"this",
"parameter",
".",
"The",
"value",
"will",
"be",
"validated",
"first",
"and",
"if",
"it",
"can",
"not",
"be",
"set",
".",
"An",
"error",
"message",
"will",
"be",
"set",
"in",
"the",
"error",
"property",
"of",
"this",
"parameter"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/parameters.py#L582-L594 |
proycon/clam | clam/common/parameters.py | FloatParameter.valuefrompostdata | def valuefrompostdata(self, postdata):
"""This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set()"""
if self.id in postdata and postdata[self.id] != '':
return float(postdata[self.id])
else:
return None | python | def valuefrompostdata(self, postdata):
"""This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set()"""
if self.id in postdata and postdata[self.id] != '':
return float(postdata[self.id])
else:
return None | [
"def",
"valuefrompostdata",
"(",
"self",
",",
"postdata",
")",
":",
"if",
"self",
".",
"id",
"in",
"postdata",
"and",
"postdata",
"[",
"self",
".",
"id",
"]",
"!=",
"''",
":",
"return",
"float",
"(",
"postdata",
"[",
"self",
".",
"id",
"]",
")",
"else",
":",
"return",
"None"
] | This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set() | [
"This",
"parameter",
"method",
"searches",
"the",
"POST",
"data",
"and",
"retrieves",
"the",
"values",
"it",
"needs",
".",
"It",
"does",
"not",
"set",
"the",
"value",
"yet",
"though",
"but",
"simply",
"returns",
"it",
".",
"Needs",
"to",
"be",
"explicitly",
"passed",
"to",
"parameter",
".",
"set",
"()"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/parameters.py#L648-L653 |
proycon/clam | clam/clamservice.py | index | def index(credentials = None):
"""Get list of projects or shortcut to other functionality"""
#handle shortcut
shortcutresponse = entryshortcut(credentials)
if shortcutresponse is not None:
return shortcutresponse
projects = []
user, oauth_access_token = parsecredentials(credentials)
totalsize = 0.0
if settings.LISTPROJECTS:
projects, totalsize = getprojects(user)
errors = "no"
errormsg = ""
corpora = CLAMService.corpusindex()
#pylint: disable=bad-continuation
return withheaders(flask.make_response(flask.render_template('response.xml',
version=VERSION,
system_id=settings.SYSTEM_ID,
system_name=settings.SYSTEM_NAME,
system_description=settings.SYSTEM_DESCRIPTION,
system_author=settings.SYSTEM_AUTHOR,
system_version=settings.SYSTEM_VERSION,
system_email=settings.SYSTEM_EMAIL,
user=user,
project=None,
url=getrooturl(),
statuscode=-1,
statusmessage="",
statuslog=[],
completion=0,
errors=errors,
errormsg=errormsg,
parameterdata=settings.PARAMETERS,
inputsources=corpora,
outputpaths=None,
inputpaths=None,
profiles=settings.PROFILES,
datafile=None,
projects=projects,
totalsize=totalsize,
actions=settings.ACTIONS,
disableinterface=not settings.ENABLEWEBAPP,
info=False,
accesstoken=None,
interfaceoptions=settings.INTERFACEOPTIONS,
customhtml=settings.CUSTOMHTML_INDEX,
allow_origin=settings.ALLOW_ORIGIN,
oauth_access_token=oauth_encrypt(oauth_access_token),
auth_type=auth_type()
)), headers={'allow_origin':settings.ALLOW_ORIGIN}) | python | def index(credentials = None):
"""Get list of projects or shortcut to other functionality"""
#handle shortcut
shortcutresponse = entryshortcut(credentials)
if shortcutresponse is not None:
return shortcutresponse
projects = []
user, oauth_access_token = parsecredentials(credentials)
totalsize = 0.0
if settings.LISTPROJECTS:
projects, totalsize = getprojects(user)
errors = "no"
errormsg = ""
corpora = CLAMService.corpusindex()
#pylint: disable=bad-continuation
return withheaders(flask.make_response(flask.render_template('response.xml',
version=VERSION,
system_id=settings.SYSTEM_ID,
system_name=settings.SYSTEM_NAME,
system_description=settings.SYSTEM_DESCRIPTION,
system_author=settings.SYSTEM_AUTHOR,
system_version=settings.SYSTEM_VERSION,
system_email=settings.SYSTEM_EMAIL,
user=user,
project=None,
url=getrooturl(),
statuscode=-1,
statusmessage="",
statuslog=[],
completion=0,
errors=errors,
errormsg=errormsg,
parameterdata=settings.PARAMETERS,
inputsources=corpora,
outputpaths=None,
inputpaths=None,
profiles=settings.PROFILES,
datafile=None,
projects=projects,
totalsize=totalsize,
actions=settings.ACTIONS,
disableinterface=not settings.ENABLEWEBAPP,
info=False,
accesstoken=None,
interfaceoptions=settings.INTERFACEOPTIONS,
customhtml=settings.CUSTOMHTML_INDEX,
allow_origin=settings.ALLOW_ORIGIN,
oauth_access_token=oauth_encrypt(oauth_access_token),
auth_type=auth_type()
)), headers={'allow_origin':settings.ALLOW_ORIGIN}) | [
"def",
"index",
"(",
"credentials",
"=",
"None",
")",
":",
"#handle shortcut",
"shortcutresponse",
"=",
"entryshortcut",
"(",
"credentials",
")",
"if",
"shortcutresponse",
"is",
"not",
"None",
":",
"return",
"shortcutresponse",
"projects",
"=",
"[",
"]",
"user",
",",
"oauth_access_token",
"=",
"parsecredentials",
"(",
"credentials",
")",
"totalsize",
"=",
"0.0",
"if",
"settings",
".",
"LISTPROJECTS",
":",
"projects",
",",
"totalsize",
"=",
"getprojects",
"(",
"user",
")",
"errors",
"=",
"\"no\"",
"errormsg",
"=",
"\"\"",
"corpora",
"=",
"CLAMService",
".",
"corpusindex",
"(",
")",
"#pylint: disable=bad-continuation",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"flask",
".",
"render_template",
"(",
"'response.xml'",
",",
"version",
"=",
"VERSION",
",",
"system_id",
"=",
"settings",
".",
"SYSTEM_ID",
",",
"system_name",
"=",
"settings",
".",
"SYSTEM_NAME",
",",
"system_description",
"=",
"settings",
".",
"SYSTEM_DESCRIPTION",
",",
"system_author",
"=",
"settings",
".",
"SYSTEM_AUTHOR",
",",
"system_version",
"=",
"settings",
".",
"SYSTEM_VERSION",
",",
"system_email",
"=",
"settings",
".",
"SYSTEM_EMAIL",
",",
"user",
"=",
"user",
",",
"project",
"=",
"None",
",",
"url",
"=",
"getrooturl",
"(",
")",
",",
"statuscode",
"=",
"-",
"1",
",",
"statusmessage",
"=",
"\"\"",
",",
"statuslog",
"=",
"[",
"]",
",",
"completion",
"=",
"0",
",",
"errors",
"=",
"errors",
",",
"errormsg",
"=",
"errormsg",
",",
"parameterdata",
"=",
"settings",
".",
"PARAMETERS",
",",
"inputsources",
"=",
"corpora",
",",
"outputpaths",
"=",
"None",
",",
"inputpaths",
"=",
"None",
",",
"profiles",
"=",
"settings",
".",
"PROFILES",
",",
"datafile",
"=",
"None",
",",
"projects",
"=",
"projects",
",",
"totalsize",
"=",
"totalsize",
",",
"actions",
"=",
"settings",
".",
"ACTIONS",
",",
"disableinterface",
"=",
"not",
"settings",
".",
"ENABLEWEBAPP",
",",
"info",
"=",
"False",
",",
"accesstoken",
"=",
"None",
",",
"interfaceoptions",
"=",
"settings",
".",
"INTERFACEOPTIONS",
",",
"customhtml",
"=",
"settings",
".",
"CUSTOMHTML_INDEX",
",",
"allow_origin",
"=",
"settings",
".",
"ALLOW_ORIGIN",
",",
"oauth_access_token",
"=",
"oauth_encrypt",
"(",
"oauth_access_token",
")",
",",
"auth_type",
"=",
"auth_type",
"(",
")",
")",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")"
] | Get list of projects or shortcut to other functionality | [
"Get",
"list",
"of",
"projects",
"or",
"shortcut",
"to",
"other",
"functionality"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L364-L418 |
proycon/clam | clam/clamservice.py | addfile | def addfile(project, filename, user, postdata, inputsource=None,returntype='xml'): #pylint: disable=too-many-return-statements
"""Add a new input file, this invokes the actual uploader"""
def errorresponse(msg, code=403):
if returntype == 'json':
return withheaders(flask.make_response("{success: false, error: '" + msg + "'}"),'application/json',{'allow_origin': settings.ALLOW_ORIGIN})
else:
return withheaders(flask.make_response(msg,403),headers={'allow_origin': settings.ALLOW_ORIGIN}) #(it will have to be explicitly deleted by the client first)
inputtemplate_id = flask.request.headers.get('Inputtemplate','')
inputtemplate = None
metadata = None
printdebug('Handling addfile, postdata contains fields ' + ",".join(postdata.keys()) )
if 'inputtemplate' in postdata:
inputtemplate_id = postdata['inputtemplate']
if inputtemplate_id:
#An input template must always be provided
for profile in settings.PROFILES:
for t in profile.input:
if t.id == inputtemplate_id:
inputtemplate = t
if not inputtemplate:
#Inputtemplate not found, send 404
printlog("Specified inputtemplate (" + inputtemplate_id + ") not found!")
return withheaders(flask.make_response("Specified inputtemplate (" + inputtemplate_id + ") not found!",404),headers={'allow_origin': settings.ALLOW_ORIGIN})
printdebug('Inputtemplate explicitly provided: ' + inputtemplate.id )
if not inputtemplate:
#See if an inputtemplate is explicitly specified in the filename
printdebug('Attempting to determine input template from filename ' + filename )
if '/' in filename.strip('/'):
raw = filename.split('/')
inputtemplate = None
for profile in settings.PROFILES:
for it in profile.input:
if it.id == raw[0]:
inputtemplate = it
break
if inputtemplate:
filename = raw[1]
if not inputtemplate:
#Check if the specified filename can be uniquely associated with an inputtemplate
for profile in settings.PROFILES:
for t in profile.input:
if t.filename == filename:
if inputtemplate:
#we found another one, not unique!! reset and break
inputtemplate = None
break
else:
#good, we found one, don't break cause we want to make sure there is only one
inputtemplate = t
if not inputtemplate:
printlog("No inputtemplate specified and filename " + filename + " does not uniquely match with any inputtemplate!")
return errorresponse("No inputtemplate specified nor auto-detected for filename " + filename + "!",404)
#See if other previously uploaded input files use this inputtemplate
if inputtemplate.unique:
nextseq = 0 #unique
else:
nextseq = 1 #will hold the next sequence number for this inputtemplate (in multi-mode only)
for seq, inputfile in Project.inputindexbytemplate(project, user, inputtemplate): #pylint: disable=unused-variable
if inputtemplate.unique:
return errorresponse("You have already submitted a file of this type, you can only submit one. Delete it first. (Inputtemplate=" + inputtemplate.id + ", unique=True)")
else:
if seq >= nextseq:
nextseq = seq + 1 #next available sequence number
if not filename: #Actually, I don't think this can occur at this stage, but we'll leave it in to be sure (yes it can, when the entry shortcut is used!)
if inputtemplate.filename:
filename = inputtemplate.filename
elif inputtemplate.extension:
filename = str(nextseq) +'-' + str("%034x" % random.getrandbits(128)) + '.' + inputtemplate.extension
else:
filename = str(nextseq) +'-' + str("%034x" % random.getrandbits(128))
#Make sure filename matches (only if not an archive)
if inputtemplate.acceptarchive and (filename[-7:].lower() == '.tar.gz' or filename[-8:].lower() == '.tar.bz2' or filename[-4:].lower() == '.zip'):
pass
else:
if inputtemplate.filename:
if filename != inputtemplate.filename:
filename = inputtemplate.filename
#return flask.make_response("Specified filename must the filename dictated by the inputtemplate, which is " + inputtemplate.filename)
#TODO LATER: add support for calling this with an actual number instead of #
if inputtemplate.extension:
if filename[-len(inputtemplate.extension) - 1:].lower() == '.' + inputtemplate.extension.lower():
#good, extension matches (case independent). Let's just make sure the case is as defined exactly by the inputtemplate
filename = filename[:-len(inputtemplate.extension) - 1] + '.' + inputtemplate.extension
else:
filename = filename + '.' + inputtemplate.extension
#return flask.make_response("Specified filename does not have the extension dictated by the inputtemplate ("+inputtemplate.extension+")") #403
if inputtemplate.onlyinputsource and (not 'inputsource' in postdata or not postdata['inputsource']):
return errorresponse("Adding files for this inputtemplate must proceed through inputsource")
if 'converter' in postdata and postdata['converter'] and not postdata['converter'] in [ x.id for x in inputtemplate.converters]:
return errorresponse("Invalid converter specified: " + postdata['converter'])
#Make sure the filename is secure
validfilename = True
DISALLOWED = ('/','&','|','<','>',';','"',"'","`","{","}","\n","\r","\b","\t")
for c in filename:
if c in DISALLOWED:
validfilename = False
break
if not validfilename:
return errorresponse("Filename contains invalid symbols! Do not use /,&,|,<,>,',`,\",{,} or ;")
#Create the project (no effect if already exists)
response = Project.create(project, user)
if response is not None:
return response
printdebug("(Obtaining filename for uploaded file)")
head = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
head += "<clamupload>\n"
if 'file' in flask.request.files:
printlog("Adding client-side file " + flask.request.files['file'].filename + " to input files")
sourcefile = flask.request.files['file'].filename
elif 'url' in postdata and postdata['url']:
#Download from URL
printlog("Adding web-based URL " + postdata['url'] + " to input files")
sourcefile = os.path.basename(postdata['url'])
elif 'contents' in postdata and postdata['contents']:
#In message
printlog("Adding file " + filename + " with explicitly provided contents to input files")
sourcefile = "editor"
elif 'inputsource' in postdata and postdata['inputsource']:
printlog("Adding file " + filename + " from preinstalled data to input files")
if not inputsource:
inputsource = None
for s in inputtemplate.inputsources:
if s.id.lower() == postdata['inputsource'].lower():
inputsource = s
if not inputsource:
return errorresponse("Specified inputsource '" + postdata['inputsource'] + "' does not exist for inputtemplate '"+inputtemplate.id+"'")
sourcefile = os.path.basename(inputsource.path)
elif 'accesstoken' in postdata and 'filename' in postdata:
#XHR POST, data in body
printlog("Adding client-side file " + filename + " to input files. Uploaded using XHR POST")
sourcefile = postdata['filename']
else:
return errorresponse("No file, url or contents specified!")
#============================ Generate metadata ========================================
printdebug('(Generating and validating metadata)')
if 'metafile' in flask.request.files: #and (not isinstance(postdata['metafile'], dict) or len(postdata['metafile']) > 0)):
#an explicit metadata file was provided, upload it:
printlog("Metadata explicitly provided in file, uploading...")
#Upload file from client to server
metafile = Project.path(project, user) + 'input/.' + filename + '.METADATA'
flask.request.files['metafile'].save(metafile)
try:
with io.open(metafile,'r',encoding='utf-8') as f:
metadata = clam.common.data.CLAMMetaData.fromxml(f.read())
errors, parameters = inputtemplate.validate(metadata, user)
validmeta = True
except Exception as e: #pylint: disable=broad-except
printlog("Uploaded metadata is invalid! " + str(e))
metadata = None
errors = True
parameters = []
validmeta = False
elif 'metadata' in postdata and postdata['metadata']:
printlog("Metadata explicitly provided in message, uploading...")
try:
metadata = clam.common.data.CLAMMetaData.fromxml(postdata['metadata'])
errors, parameters = inputtemplate.validate(metadata, user)
validmeta = True
except: #pylint: disable=bare-except
printlog("Uploaded metadata is invalid!")
metadata = None
errors = True
parameters = []
validmeta = False
elif 'inputsource' in postdata and postdata['inputsource']:
printlog("Getting metadata from inputsource, uploading...")
if inputsource.metadata:
printlog("DEBUG: Validating metadata from inputsource")
metadata = inputsource.metadata
errors, parameters = inputtemplate.validate(metadata, user)
validmeta = True
else:
printlog("DEBUG: No metadata provided with inputsource, looking for metadata files..")
metafilename = os.path.dirname(inputsource.path)
if metafilename: metafilename += '/'
metafilename += '.' + os.path.basename(inputsource.path) + '.METADATA'
if os.path.exists(metafilename):
try:
metadata = clam.common.data.CLAMMetaData.fromxml(open(metafilename,'r').readlines())
errors, parameters = inputtemplate.validate(metadata, user)
validmeta = True
except: #pylint: disable=bare-except
printlog("Uploaded metadata is invalid!")
metadata = None
errors = True
parameters = []
validmeta = False
else:
return withheaders(flask.make_response("No metadata found nor specified for inputsource " + inputsource.id ,500),headers={'allow_origin': settings.ALLOW_ORIGIN})
else:
errors, parameters = inputtemplate.validate(postdata, user)
validmeta = True #will be checked later
# ----------- Check if archive are allowed -------------
archive = False
addedfiles = []
if not errors and inputtemplate.acceptarchive: #pylint: disable=too-many-nested-blocks
printdebug('(Archive test)')
# -------- Are we an archive? If so, determine what kind
archivetype = None
if 'file' in flask.request.files:
uploadname = sourcefile.lower()
archivetype = None
if uploadname[-4:] == '.zip':
archivetype = 'zip'
elif uploadname[-7:] == '.tar.gz':
archivetype = 'tar.gz'
elif uploadname[-4:] == '.tar':
archivetype = 'tar'
elif uploadname[-8:] == '.tar.bz2':
archivetype = 'tar.bz2'
xhrpost = False
elif 'accesstoken' in postdata and 'filename' in postdata:
xhrpost = True
if postdata['filename'][-7:].lower() == '.tar.gz':
uploadname = sourcefile.lower()
archivetype = 'tar.gz'
elif postdata['filename'][-8:].lower() == '.tar.bz2':
uploadname = sourcefile.lower()
archivetype = 'tar.bz2'
elif postdata['filename'][-4:].lower() == '.tar':
uploadname = sourcefile.lower()
archivetype = 'tar'
elif postdata['filename'][-4:].lower() == '.zip':
uploadname = sourcefile.lower()
archivetype = 'zip'
if archivetype:
# =============== upload archive ======================
#random name
archive = "%032x" % random.getrandbits(128) + '.' + archivetype
#Upload file from client to server
printdebug('(Archive transfer starting)')
if not xhrpost:
flask.request.files['file'].save(Project.path(project,user) + archive)
elif xhrpost:
with open(Project.path(project,user) + archive,'wb') as f:
while True:
chunk = flask.request.stream.read(16384)
if chunk:
f.write(chunk)
else:
break
printdebug('(Archive transfer completed)')
# =============== Extract archive ======================
#Determine extraction command
if archivetype == 'zip':
cmd = 'unzip -u'
elif archivetype == 'tar':
cmd = 'tar -xvf'
elif archivetype == 'tar.gz':
cmd = 'tar -xvzf'
elif archivetype == 'tar.bz2':
cmd = 'tar -xvjf'
else:
raise Exception("Invalid archive format: " + archivetype) #invalid archive, shouldn't happen
#invoke extractor
printlog("Extracting '" + archive + "'" )
try:
process = subprocess.Popen(cmd + " " + archive, cwd=Project.path(project,user), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
except: #pylint: disable=bare-except
return withheaders(flask.make_response("Unable to extract archive",500),headers={'allow_origin': settings.ALLOW_ORIGIN})
out, _ = process.communicate() #waits for process to end
if sys.version < '3':
if isinstance(out, str):
out = unicode(out,'utf-8') #pylint: disable=undefined-variable
else:
if isinstance(out, bytes):
out = str(out,'utf-8')
#Read filename results
firstline = True
for line in out.split("\n"):
line = line.strip()
if line:
printdebug('(Extraction output: ' + line+')')
subfile = None
if archivetype[0:3] == 'tar':
subfile = line
elif archivetype == 'zip' and not firstline: #firstline contains archive name itself, skip it
colon = line.find(":")
if colon:
subfile = line[colon + 1:].strip()
if subfile and os.path.isfile(Project.path(project, user) + subfile):
subfile_newname = clam.common.data.resolveinputfilename(os.path.basename(subfile), parameters, inputtemplate, nextseq+len(addedfiles), project)
printdebug('(Extracted file ' + subfile + ', moving to input/' + subfile_newname+')')
os.rename(Project.path(project, user) + subfile, Project.path(project, user) + 'input/' + subfile_newname)
addedfiles.append(subfile_newname)
firstline = False
#all done, remove archive
os.unlink(Project.path(project, user) + archive)
if not archive:
addedfiles = [clam.common.data.resolveinputfilename(filename, parameters, inputtemplate, nextseq, project)]
fatalerror = None
jsonoutput = {'success': False if errors else True, 'isarchive': archive}
output = head
for filename in addedfiles: #pylint: disable=too-many-nested-blocks
output += "<upload source=\""+sourcefile +"\" filename=\""+filename+"\" inputtemplate=\"" + inputtemplate.id + "\" templatelabel=\""+inputtemplate.label+"\" format=\""+inputtemplate.formatclass.__name__+"\">\n"
if not errors:
output += "<parameters errors=\"no\">"
else:
output += "<parameters errors=\"yes\">"
jsonoutput['error'] = 'There were parameter errors, file not uploaded: '
for parameter in parameters:
output += parameter.xml()
if parameter.error:
jsonoutput['error'] += parameter.error + ". "
output += "</parameters>"
if not errors:
if not archive:
#============================ Transfer file ========================================
printdebug('(Start file transfer: ' + Project.path(project, user) + 'input/' + filename+' )')
if 'file' in flask.request.files:
printdebug('(Receiving data by uploading file)')
#Upload file from client to server
flask.request.files['file'].save(Project.path(project, user) + 'input/' + filename)
elif 'url' in postdata and postdata['url']:
printdebug('(Receiving data via url)')
#Download file from 3rd party server to CLAM server
try:
r = requests.get(postdata['url'])
except:
raise flask.abort(404)
if not (r.status_code >= 200 and r.status_code < 300):
raise flask.abort(404)
CHUNK = 16 * 1024
f = open(Project.path(project, user) + 'input/' + filename,'wb')
for chunk in r.iter_content(chunk_size=CHUNK):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
f.close()
elif 'inputsource' in postdata and postdata['inputsource']:
#Copy (symlink!) from preinstalled data
printdebug('(Creating symlink to file ' + inputsource.path + ' <- ' + Project.path(project,user) + '/input/ ' + filename + ')')
os.symlink(inputsource.path, Project.path(project, user) + 'input/' + filename)
elif 'contents' in postdata and postdata['contents']:
printdebug('(Receiving data via from contents variable)')
#grab encoding
encoding = 'utf-8'
for p in parameters:
if p.id == 'encoding':
encoding = p.value
#Contents passed in POST message itself
try:
f = io.open(Project.path(project, user) + 'input/' + filename,'w',encoding=encoding)
f.write(postdata['contents'])
f.close()
except UnicodeError:
return errorresponse("Input file " + str(filename) + " is not in the expected encoding!")
elif 'accesstoken' in postdata and 'filename' in postdata:
printdebug('(Receiving data directly from post body)')
with open(Project.path(project,user) + 'input/' + filename,'wb') as f:
while True:
chunk = flask.request.stream.read(16384)
if chunk:
f.write(chunk)
else:
break
printdebug('(File transfer completed)')
#Create a file object
file = clam.common.data.CLAMInputFile(Project.path(project, user), filename, False) #get CLAMInputFile without metadata (chicken-egg problem, this does not read the actual file contents!
#============== Generate metadata ==============
metadataerror = None
if not metadata and not errors: #check if it has not already been set in another stage
printdebug('(Generating metadata)')
#for newly generated metadata
try:
#Now we generate the actual metadata object (unsaved yet though). We pass our earlier validation results to prevent computing it again
validmeta, metadata, parameters = inputtemplate.generate(file, (errors, parameters ))
if validmeta:
#And we tie it to the CLAMFile object
file.metadata = metadata
#Add inputtemplate ID to metadata
metadata.inputtemplate = inputtemplate.id
else:
metadataerror = "Undefined error"
except ValueError as msg:
validmeta = False
metadataerror = msg
except KeyError as msg:
validmeta = False
metadataerror = msg
elif validmeta:
#for explicitly uploaded metadata
metadata.file = file
file.metadata = metadata
metadata.inputtemplate = inputtemplate.id
if metadataerror:
printdebug('(Metadata could not be generated, ' + str(metadataerror) + ', this usually indicated an error in service configuration)')
#output += "<metadataerror />" #This usually indicates an error in service configuration!
fatalerror = "<error type=\"metadataerror\">Metadata could not be generated for " + filename + ": " + str(metadataerror) + " (this usually indicates an error in service configuration!)</error>"
jsonoutput['error'] = "Metadata could not be generated! " + str(metadataerror) + " (this usually indicates an error in service configuration!)"
elif validmeta:
#=========== Convert the uploaded file (if requested) ==============
conversionerror = False
if 'converter' in postdata and postdata['converter']:
for c in inputtemplate.converters:
if c.id == postdata['converter']:
converter = c
break
if converter: #(should always be found, error already provided earlier if not)
printdebug('(Invoking converter)')
try:
success = converter.convertforinput(Project.path(project, user) + 'input/' + filename, metadata)
except: #pylint: disable=bare-except
success = False
if not success:
conversionerror = True
fatalerror = "<error type=\"conversion\">The file " + xmlescape(filename) + " could not be converted</error>"
jsonoutput['error'] = "The file could not be converted"
jsonoutput['success'] = False
#====================== Validate the file itself ====================
if not conversionerror:
valid = file.validate()
if valid:
printdebug('(Validation ok)')
output += "<valid>yes</valid>"
#Great! Everything ok, save metadata
metadata.save(Project.path(project, user) + 'input/' + file.metafilename())
#And create symbolic link for inputtemplates
linkfilename = os.path.dirname(filename)
if linkfilename: linkfilename += '/'
linkfilename += '.' + os.path.basename(filename) + '.INPUTTEMPLATE' + '.' + inputtemplate.id + '.' + str(nextseq)
os.symlink(Project.path(project, user) + 'input/' + filename, Project.path(project, user) + 'input/' + linkfilename)
else:
printdebug('(Validation error)')
#Too bad, everything worked out but the file itself doesn't validate.
#output += "<valid>no</valid>"
fatalerror = "<error type=\"validation\">The file " + xmlescape(filename) + " did not validate, it is not in the proper expected format.</error>"
jsonoutput['error'] = "The file " + filename.replace("'","") + " did not validate, it is not in the proper expected format."
jsonoutput['success'] = False
#remove upload
os.unlink(Project.path(project, user) + 'input/' + filename)
output += "</upload>\n"
output += "</clamupload>"
if returntype == 'boolean':
return jsonoutput['success']
elif fatalerror:
#fatal error return error message with 403 code
printlog('Fatal Error during upload: ' + fatalerror)
return errorresponse(head + fatalerror,403)
elif errors:
#parameter errors, return XML output with 403 code
printdebug('There were parameter errors during upload!')
if returntype == 'json':
jsonoutput['xml'] = output #embed XML in JSON for complete client-side processing
return withheaders(flask.make_response(json.dumps(jsonoutput)), 'application/json', {'allow_origin': settings.ALLOW_ORIGIN})
else:
return withheaders(flask.make_response(output,403),headers={'allow_origin': settings.ALLOW_ORIGIN})
elif returntype == 'xml': #success
printdebug('Returning xml')
return withheaders(flask.make_response(output), 'text/xml', {'allow_origin': settings.ALLOW_ORIGIN})
elif returntype == 'json': #success
printdebug('Returning json')
#everything ok, return JSON output (caller decides)
jsonoutput['xml'] = output #embed XML in JSON for complete client-side processing
return withheaders(flask.make_response(json.dumps(jsonoutput)), 'application/json', {'allow_origin': settings.ALLOW_ORIGIN})
elif returntype == 'true_on_success':
return True
else:
printdebug('Invalid return type')
raise Exception("invalid return type") | python | def addfile(project, filename, user, postdata, inputsource=None,returntype='xml'): #pylint: disable=too-many-return-statements
"""Add a new input file, this invokes the actual uploader"""
def errorresponse(msg, code=403):
if returntype == 'json':
return withheaders(flask.make_response("{success: false, error: '" + msg + "'}"),'application/json',{'allow_origin': settings.ALLOW_ORIGIN})
else:
return withheaders(flask.make_response(msg,403),headers={'allow_origin': settings.ALLOW_ORIGIN}) #(it will have to be explicitly deleted by the client first)
inputtemplate_id = flask.request.headers.get('Inputtemplate','')
inputtemplate = None
metadata = None
printdebug('Handling addfile, postdata contains fields ' + ",".join(postdata.keys()) )
if 'inputtemplate' in postdata:
inputtemplate_id = postdata['inputtemplate']
if inputtemplate_id:
#An input template must always be provided
for profile in settings.PROFILES:
for t in profile.input:
if t.id == inputtemplate_id:
inputtemplate = t
if not inputtemplate:
#Inputtemplate not found, send 404
printlog("Specified inputtemplate (" + inputtemplate_id + ") not found!")
return withheaders(flask.make_response("Specified inputtemplate (" + inputtemplate_id + ") not found!",404),headers={'allow_origin': settings.ALLOW_ORIGIN})
printdebug('Inputtemplate explicitly provided: ' + inputtemplate.id )
if not inputtemplate:
#See if an inputtemplate is explicitly specified in the filename
printdebug('Attempting to determine input template from filename ' + filename )
if '/' in filename.strip('/'):
raw = filename.split('/')
inputtemplate = None
for profile in settings.PROFILES:
for it in profile.input:
if it.id == raw[0]:
inputtemplate = it
break
if inputtemplate:
filename = raw[1]
if not inputtemplate:
#Check if the specified filename can be uniquely associated with an inputtemplate
for profile in settings.PROFILES:
for t in profile.input:
if t.filename == filename:
if inputtemplate:
#we found another one, not unique!! reset and break
inputtemplate = None
break
else:
#good, we found one, don't break cause we want to make sure there is only one
inputtemplate = t
if not inputtemplate:
printlog("No inputtemplate specified and filename " + filename + " does not uniquely match with any inputtemplate!")
return errorresponse("No inputtemplate specified nor auto-detected for filename " + filename + "!",404)
#See if other previously uploaded input files use this inputtemplate
if inputtemplate.unique:
nextseq = 0 #unique
else:
nextseq = 1 #will hold the next sequence number for this inputtemplate (in multi-mode only)
for seq, inputfile in Project.inputindexbytemplate(project, user, inputtemplate): #pylint: disable=unused-variable
if inputtemplate.unique:
return errorresponse("You have already submitted a file of this type, you can only submit one. Delete it first. (Inputtemplate=" + inputtemplate.id + ", unique=True)")
else:
if seq >= nextseq:
nextseq = seq + 1 #next available sequence number
if not filename: #Actually, I don't think this can occur at this stage, but we'll leave it in to be sure (yes it can, when the entry shortcut is used!)
if inputtemplate.filename:
filename = inputtemplate.filename
elif inputtemplate.extension:
filename = str(nextseq) +'-' + str("%034x" % random.getrandbits(128)) + '.' + inputtemplate.extension
else:
filename = str(nextseq) +'-' + str("%034x" % random.getrandbits(128))
#Make sure filename matches (only if not an archive)
if inputtemplate.acceptarchive and (filename[-7:].lower() == '.tar.gz' or filename[-8:].lower() == '.tar.bz2' or filename[-4:].lower() == '.zip'):
pass
else:
if inputtemplate.filename:
if filename != inputtemplate.filename:
filename = inputtemplate.filename
#return flask.make_response("Specified filename must the filename dictated by the inputtemplate, which is " + inputtemplate.filename)
#TODO LATER: add support for calling this with an actual number instead of #
if inputtemplate.extension:
if filename[-len(inputtemplate.extension) - 1:].lower() == '.' + inputtemplate.extension.lower():
#good, extension matches (case independent). Let's just make sure the case is as defined exactly by the inputtemplate
filename = filename[:-len(inputtemplate.extension) - 1] + '.' + inputtemplate.extension
else:
filename = filename + '.' + inputtemplate.extension
#return flask.make_response("Specified filename does not have the extension dictated by the inputtemplate ("+inputtemplate.extension+")") #403
if inputtemplate.onlyinputsource and (not 'inputsource' in postdata or not postdata['inputsource']):
return errorresponse("Adding files for this inputtemplate must proceed through inputsource")
if 'converter' in postdata and postdata['converter'] and not postdata['converter'] in [ x.id for x in inputtemplate.converters]:
return errorresponse("Invalid converter specified: " + postdata['converter'])
#Make sure the filename is secure
validfilename = True
DISALLOWED = ('/','&','|','<','>',';','"',"'","`","{","}","\n","\r","\b","\t")
for c in filename:
if c in DISALLOWED:
validfilename = False
break
if not validfilename:
return errorresponse("Filename contains invalid symbols! Do not use /,&,|,<,>,',`,\",{,} or ;")
#Create the project (no effect if already exists)
response = Project.create(project, user)
if response is not None:
return response
printdebug("(Obtaining filename for uploaded file)")
head = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
head += "<clamupload>\n"
if 'file' in flask.request.files:
printlog("Adding client-side file " + flask.request.files['file'].filename + " to input files")
sourcefile = flask.request.files['file'].filename
elif 'url' in postdata and postdata['url']:
#Download from URL
printlog("Adding web-based URL " + postdata['url'] + " to input files")
sourcefile = os.path.basename(postdata['url'])
elif 'contents' in postdata and postdata['contents']:
#In message
printlog("Adding file " + filename + " with explicitly provided contents to input files")
sourcefile = "editor"
elif 'inputsource' in postdata and postdata['inputsource']:
printlog("Adding file " + filename + " from preinstalled data to input files")
if not inputsource:
inputsource = None
for s in inputtemplate.inputsources:
if s.id.lower() == postdata['inputsource'].lower():
inputsource = s
if not inputsource:
return errorresponse("Specified inputsource '" + postdata['inputsource'] + "' does not exist for inputtemplate '"+inputtemplate.id+"'")
sourcefile = os.path.basename(inputsource.path)
elif 'accesstoken' in postdata and 'filename' in postdata:
#XHR POST, data in body
printlog("Adding client-side file " + filename + " to input files. Uploaded using XHR POST")
sourcefile = postdata['filename']
else:
return errorresponse("No file, url or contents specified!")
#============================ Generate metadata ========================================
printdebug('(Generating and validating metadata)')
if 'metafile' in flask.request.files: #and (not isinstance(postdata['metafile'], dict) or len(postdata['metafile']) > 0)):
#an explicit metadata file was provided, upload it:
printlog("Metadata explicitly provided in file, uploading...")
#Upload file from client to server
metafile = Project.path(project, user) + 'input/.' + filename + '.METADATA'
flask.request.files['metafile'].save(metafile)
try:
with io.open(metafile,'r',encoding='utf-8') as f:
metadata = clam.common.data.CLAMMetaData.fromxml(f.read())
errors, parameters = inputtemplate.validate(metadata, user)
validmeta = True
except Exception as e: #pylint: disable=broad-except
printlog("Uploaded metadata is invalid! " + str(e))
metadata = None
errors = True
parameters = []
validmeta = False
elif 'metadata' in postdata and postdata['metadata']:
printlog("Metadata explicitly provided in message, uploading...")
try:
metadata = clam.common.data.CLAMMetaData.fromxml(postdata['metadata'])
errors, parameters = inputtemplate.validate(metadata, user)
validmeta = True
except: #pylint: disable=bare-except
printlog("Uploaded metadata is invalid!")
metadata = None
errors = True
parameters = []
validmeta = False
elif 'inputsource' in postdata and postdata['inputsource']:
printlog("Getting metadata from inputsource, uploading...")
if inputsource.metadata:
printlog("DEBUG: Validating metadata from inputsource")
metadata = inputsource.metadata
errors, parameters = inputtemplate.validate(metadata, user)
validmeta = True
else:
printlog("DEBUG: No metadata provided with inputsource, looking for metadata files..")
metafilename = os.path.dirname(inputsource.path)
if metafilename: metafilename += '/'
metafilename += '.' + os.path.basename(inputsource.path) + '.METADATA'
if os.path.exists(metafilename):
try:
metadata = clam.common.data.CLAMMetaData.fromxml(open(metafilename,'r').readlines())
errors, parameters = inputtemplate.validate(metadata, user)
validmeta = True
except: #pylint: disable=bare-except
printlog("Uploaded metadata is invalid!")
metadata = None
errors = True
parameters = []
validmeta = False
else:
return withheaders(flask.make_response("No metadata found nor specified for inputsource " + inputsource.id ,500),headers={'allow_origin': settings.ALLOW_ORIGIN})
else:
errors, parameters = inputtemplate.validate(postdata, user)
validmeta = True #will be checked later
# ----------- Check if archive are allowed -------------
archive = False
addedfiles = []
if not errors and inputtemplate.acceptarchive: #pylint: disable=too-many-nested-blocks
printdebug('(Archive test)')
# -------- Are we an archive? If so, determine what kind
archivetype = None
if 'file' in flask.request.files:
uploadname = sourcefile.lower()
archivetype = None
if uploadname[-4:] == '.zip':
archivetype = 'zip'
elif uploadname[-7:] == '.tar.gz':
archivetype = 'tar.gz'
elif uploadname[-4:] == '.tar':
archivetype = 'tar'
elif uploadname[-8:] == '.tar.bz2':
archivetype = 'tar.bz2'
xhrpost = False
elif 'accesstoken' in postdata and 'filename' in postdata:
xhrpost = True
if postdata['filename'][-7:].lower() == '.tar.gz':
uploadname = sourcefile.lower()
archivetype = 'tar.gz'
elif postdata['filename'][-8:].lower() == '.tar.bz2':
uploadname = sourcefile.lower()
archivetype = 'tar.bz2'
elif postdata['filename'][-4:].lower() == '.tar':
uploadname = sourcefile.lower()
archivetype = 'tar'
elif postdata['filename'][-4:].lower() == '.zip':
uploadname = sourcefile.lower()
archivetype = 'zip'
if archivetype:
# =============== upload archive ======================
#random name
archive = "%032x" % random.getrandbits(128) + '.' + archivetype
#Upload file from client to server
printdebug('(Archive transfer starting)')
if not xhrpost:
flask.request.files['file'].save(Project.path(project,user) + archive)
elif xhrpost:
with open(Project.path(project,user) + archive,'wb') as f:
while True:
chunk = flask.request.stream.read(16384)
if chunk:
f.write(chunk)
else:
break
printdebug('(Archive transfer completed)')
# =============== Extract archive ======================
#Determine extraction command
if archivetype == 'zip':
cmd = 'unzip -u'
elif archivetype == 'tar':
cmd = 'tar -xvf'
elif archivetype == 'tar.gz':
cmd = 'tar -xvzf'
elif archivetype == 'tar.bz2':
cmd = 'tar -xvjf'
else:
raise Exception("Invalid archive format: " + archivetype) #invalid archive, shouldn't happen
#invoke extractor
printlog("Extracting '" + archive + "'" )
try:
process = subprocess.Popen(cmd + " " + archive, cwd=Project.path(project,user), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
except: #pylint: disable=bare-except
return withheaders(flask.make_response("Unable to extract archive",500),headers={'allow_origin': settings.ALLOW_ORIGIN})
out, _ = process.communicate() #waits for process to end
if sys.version < '3':
if isinstance(out, str):
out = unicode(out,'utf-8') #pylint: disable=undefined-variable
else:
if isinstance(out, bytes):
out = str(out,'utf-8')
#Read filename results
firstline = True
for line in out.split("\n"):
line = line.strip()
if line:
printdebug('(Extraction output: ' + line+')')
subfile = None
if archivetype[0:3] == 'tar':
subfile = line
elif archivetype == 'zip' and not firstline: #firstline contains archive name itself, skip it
colon = line.find(":")
if colon:
subfile = line[colon + 1:].strip()
if subfile and os.path.isfile(Project.path(project, user) + subfile):
subfile_newname = clam.common.data.resolveinputfilename(os.path.basename(subfile), parameters, inputtemplate, nextseq+len(addedfiles), project)
printdebug('(Extracted file ' + subfile + ', moving to input/' + subfile_newname+')')
os.rename(Project.path(project, user) + subfile, Project.path(project, user) + 'input/' + subfile_newname)
addedfiles.append(subfile_newname)
firstline = False
#all done, remove archive
os.unlink(Project.path(project, user) + archive)
if not archive:
addedfiles = [clam.common.data.resolveinputfilename(filename, parameters, inputtemplate, nextseq, project)]
fatalerror = None
jsonoutput = {'success': False if errors else True, 'isarchive': archive}
output = head
for filename in addedfiles: #pylint: disable=too-many-nested-blocks
output += "<upload source=\""+sourcefile +"\" filename=\""+filename+"\" inputtemplate=\"" + inputtemplate.id + "\" templatelabel=\""+inputtemplate.label+"\" format=\""+inputtemplate.formatclass.__name__+"\">\n"
if not errors:
output += "<parameters errors=\"no\">"
else:
output += "<parameters errors=\"yes\">"
jsonoutput['error'] = 'There were parameter errors, file not uploaded: '
for parameter in parameters:
output += parameter.xml()
if parameter.error:
jsonoutput['error'] += parameter.error + ". "
output += "</parameters>"
if not errors:
if not archive:
#============================ Transfer file ========================================
printdebug('(Start file transfer: ' + Project.path(project, user) + 'input/' + filename+' )')
if 'file' in flask.request.files:
printdebug('(Receiving data by uploading file)')
#Upload file from client to server
flask.request.files['file'].save(Project.path(project, user) + 'input/' + filename)
elif 'url' in postdata and postdata['url']:
printdebug('(Receiving data via url)')
#Download file from 3rd party server to CLAM server
try:
r = requests.get(postdata['url'])
except:
raise flask.abort(404)
if not (r.status_code >= 200 and r.status_code < 300):
raise flask.abort(404)
CHUNK = 16 * 1024
f = open(Project.path(project, user) + 'input/' + filename,'wb')
for chunk in r.iter_content(chunk_size=CHUNK):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
f.close()
elif 'inputsource' in postdata and postdata['inputsource']:
#Copy (symlink!) from preinstalled data
printdebug('(Creating symlink to file ' + inputsource.path + ' <- ' + Project.path(project,user) + '/input/ ' + filename + ')')
os.symlink(inputsource.path, Project.path(project, user) + 'input/' + filename)
elif 'contents' in postdata and postdata['contents']:
printdebug('(Receiving data via from contents variable)')
#grab encoding
encoding = 'utf-8'
for p in parameters:
if p.id == 'encoding':
encoding = p.value
#Contents passed in POST message itself
try:
f = io.open(Project.path(project, user) + 'input/' + filename,'w',encoding=encoding)
f.write(postdata['contents'])
f.close()
except UnicodeError:
return errorresponse("Input file " + str(filename) + " is not in the expected encoding!")
elif 'accesstoken' in postdata and 'filename' in postdata:
printdebug('(Receiving data directly from post body)')
with open(Project.path(project,user) + 'input/' + filename,'wb') as f:
while True:
chunk = flask.request.stream.read(16384)
if chunk:
f.write(chunk)
else:
break
printdebug('(File transfer completed)')
#Create a file object
file = clam.common.data.CLAMInputFile(Project.path(project, user), filename, False) #get CLAMInputFile without metadata (chicken-egg problem, this does not read the actual file contents!
#============== Generate metadata ==============
metadataerror = None
if not metadata and not errors: #check if it has not already been set in another stage
printdebug('(Generating metadata)')
#for newly generated metadata
try:
#Now we generate the actual metadata object (unsaved yet though). We pass our earlier validation results to prevent computing it again
validmeta, metadata, parameters = inputtemplate.generate(file, (errors, parameters ))
if validmeta:
#And we tie it to the CLAMFile object
file.metadata = metadata
#Add inputtemplate ID to metadata
metadata.inputtemplate = inputtemplate.id
else:
metadataerror = "Undefined error"
except ValueError as msg:
validmeta = False
metadataerror = msg
except KeyError as msg:
validmeta = False
metadataerror = msg
elif validmeta:
#for explicitly uploaded metadata
metadata.file = file
file.metadata = metadata
metadata.inputtemplate = inputtemplate.id
if metadataerror:
printdebug('(Metadata could not be generated, ' + str(metadataerror) + ', this usually indicated an error in service configuration)')
#output += "<metadataerror />" #This usually indicates an error in service configuration!
fatalerror = "<error type=\"metadataerror\">Metadata could not be generated for " + filename + ": " + str(metadataerror) + " (this usually indicates an error in service configuration!)</error>"
jsonoutput['error'] = "Metadata could not be generated! " + str(metadataerror) + " (this usually indicates an error in service configuration!)"
elif validmeta:
#=========== Convert the uploaded file (if requested) ==============
conversionerror = False
if 'converter' in postdata and postdata['converter']:
for c in inputtemplate.converters:
if c.id == postdata['converter']:
converter = c
break
if converter: #(should always be found, error already provided earlier if not)
printdebug('(Invoking converter)')
try:
success = converter.convertforinput(Project.path(project, user) + 'input/' + filename, metadata)
except: #pylint: disable=bare-except
success = False
if not success:
conversionerror = True
fatalerror = "<error type=\"conversion\">The file " + xmlescape(filename) + " could not be converted</error>"
jsonoutput['error'] = "The file could not be converted"
jsonoutput['success'] = False
#====================== Validate the file itself ====================
if not conversionerror:
valid = file.validate()
if valid:
printdebug('(Validation ok)')
output += "<valid>yes</valid>"
#Great! Everything ok, save metadata
metadata.save(Project.path(project, user) + 'input/' + file.metafilename())
#And create symbolic link for inputtemplates
linkfilename = os.path.dirname(filename)
if linkfilename: linkfilename += '/'
linkfilename += '.' + os.path.basename(filename) + '.INPUTTEMPLATE' + '.' + inputtemplate.id + '.' + str(nextseq)
os.symlink(Project.path(project, user) + 'input/' + filename, Project.path(project, user) + 'input/' + linkfilename)
else:
printdebug('(Validation error)')
#Too bad, everything worked out but the file itself doesn't validate.
#output += "<valid>no</valid>"
fatalerror = "<error type=\"validation\">The file " + xmlescape(filename) + " did not validate, it is not in the proper expected format.</error>"
jsonoutput['error'] = "The file " + filename.replace("'","") + " did not validate, it is not in the proper expected format."
jsonoutput['success'] = False
#remove upload
os.unlink(Project.path(project, user) + 'input/' + filename)
output += "</upload>\n"
output += "</clamupload>"
if returntype == 'boolean':
return jsonoutput['success']
elif fatalerror:
#fatal error return error message with 403 code
printlog('Fatal Error during upload: ' + fatalerror)
return errorresponse(head + fatalerror,403)
elif errors:
#parameter errors, return XML output with 403 code
printdebug('There were parameter errors during upload!')
if returntype == 'json':
jsonoutput['xml'] = output #embed XML in JSON for complete client-side processing
return withheaders(flask.make_response(json.dumps(jsonoutput)), 'application/json', {'allow_origin': settings.ALLOW_ORIGIN})
else:
return withheaders(flask.make_response(output,403),headers={'allow_origin': settings.ALLOW_ORIGIN})
elif returntype == 'xml': #success
printdebug('Returning xml')
return withheaders(flask.make_response(output), 'text/xml', {'allow_origin': settings.ALLOW_ORIGIN})
elif returntype == 'json': #success
printdebug('Returning json')
#everything ok, return JSON output (caller decides)
jsonoutput['xml'] = output #embed XML in JSON for complete client-side processing
return withheaders(flask.make_response(json.dumps(jsonoutput)), 'application/json', {'allow_origin': settings.ALLOW_ORIGIN})
elif returntype == 'true_on_success':
return True
else:
printdebug('Invalid return type')
raise Exception("invalid return type") | [
"def",
"addfile",
"(",
"project",
",",
"filename",
",",
"user",
",",
"postdata",
",",
"inputsource",
"=",
"None",
",",
"returntype",
"=",
"'xml'",
")",
":",
"#pylint: disable=too-many-return-statements",
"def",
"errorresponse",
"(",
"msg",
",",
"code",
"=",
"403",
")",
":",
"if",
"returntype",
"==",
"'json'",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"{success: false, error: '\"",
"+",
"msg",
"+",
"\"'}\"",
")",
",",
"'application/json'",
",",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"else",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"msg",
",",
"403",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"#(it will have to be explicitly deleted by the client first)",
"inputtemplate_id",
"=",
"flask",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'Inputtemplate'",
",",
"''",
")",
"inputtemplate",
"=",
"None",
"metadata",
"=",
"None",
"printdebug",
"(",
"'Handling addfile, postdata contains fields '",
"+",
"\",\"",
".",
"join",
"(",
"postdata",
".",
"keys",
"(",
")",
")",
")",
"if",
"'inputtemplate'",
"in",
"postdata",
":",
"inputtemplate_id",
"=",
"postdata",
"[",
"'inputtemplate'",
"]",
"if",
"inputtemplate_id",
":",
"#An input template must always be provided",
"for",
"profile",
"in",
"settings",
".",
"PROFILES",
":",
"for",
"t",
"in",
"profile",
".",
"input",
":",
"if",
"t",
".",
"id",
"==",
"inputtemplate_id",
":",
"inputtemplate",
"=",
"t",
"if",
"not",
"inputtemplate",
":",
"#Inputtemplate not found, send 404",
"printlog",
"(",
"\"Specified inputtemplate (\"",
"+",
"inputtemplate_id",
"+",
"\") not found!\"",
")",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"Specified inputtemplate (\"",
"+",
"inputtemplate_id",
"+",
"\") not found!\"",
",",
"404",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"printdebug",
"(",
"'Inputtemplate explicitly provided: '",
"+",
"inputtemplate",
".",
"id",
")",
"if",
"not",
"inputtemplate",
":",
"#See if an inputtemplate is explicitly specified in the filename",
"printdebug",
"(",
"'Attempting to determine input template from filename '",
"+",
"filename",
")",
"if",
"'/'",
"in",
"filename",
".",
"strip",
"(",
"'/'",
")",
":",
"raw",
"=",
"filename",
".",
"split",
"(",
"'/'",
")",
"inputtemplate",
"=",
"None",
"for",
"profile",
"in",
"settings",
".",
"PROFILES",
":",
"for",
"it",
"in",
"profile",
".",
"input",
":",
"if",
"it",
".",
"id",
"==",
"raw",
"[",
"0",
"]",
":",
"inputtemplate",
"=",
"it",
"break",
"if",
"inputtemplate",
":",
"filename",
"=",
"raw",
"[",
"1",
"]",
"if",
"not",
"inputtemplate",
":",
"#Check if the specified filename can be uniquely associated with an inputtemplate",
"for",
"profile",
"in",
"settings",
".",
"PROFILES",
":",
"for",
"t",
"in",
"profile",
".",
"input",
":",
"if",
"t",
".",
"filename",
"==",
"filename",
":",
"if",
"inputtemplate",
":",
"#we found another one, not unique!! reset and break",
"inputtemplate",
"=",
"None",
"break",
"else",
":",
"#good, we found one, don't break cause we want to make sure there is only one",
"inputtemplate",
"=",
"t",
"if",
"not",
"inputtemplate",
":",
"printlog",
"(",
"\"No inputtemplate specified and filename \"",
"+",
"filename",
"+",
"\" does not uniquely match with any inputtemplate!\"",
")",
"return",
"errorresponse",
"(",
"\"No inputtemplate specified nor auto-detected for filename \"",
"+",
"filename",
"+",
"\"!\"",
",",
"404",
")",
"#See if other previously uploaded input files use this inputtemplate",
"if",
"inputtemplate",
".",
"unique",
":",
"nextseq",
"=",
"0",
"#unique",
"else",
":",
"nextseq",
"=",
"1",
"#will hold the next sequence number for this inputtemplate (in multi-mode only)",
"for",
"seq",
",",
"inputfile",
"in",
"Project",
".",
"inputindexbytemplate",
"(",
"project",
",",
"user",
",",
"inputtemplate",
")",
":",
"#pylint: disable=unused-variable",
"if",
"inputtemplate",
".",
"unique",
":",
"return",
"errorresponse",
"(",
"\"You have already submitted a file of this type, you can only submit one. Delete it first. (Inputtemplate=\"",
"+",
"inputtemplate",
".",
"id",
"+",
"\", unique=True)\"",
")",
"else",
":",
"if",
"seq",
">=",
"nextseq",
":",
"nextseq",
"=",
"seq",
"+",
"1",
"#next available sequence number",
"if",
"not",
"filename",
":",
"#Actually, I don't think this can occur at this stage, but we'll leave it in to be sure (yes it can, when the entry shortcut is used!)",
"if",
"inputtemplate",
".",
"filename",
":",
"filename",
"=",
"inputtemplate",
".",
"filename",
"elif",
"inputtemplate",
".",
"extension",
":",
"filename",
"=",
"str",
"(",
"nextseq",
")",
"+",
"'-'",
"+",
"str",
"(",
"\"%034x\"",
"%",
"random",
".",
"getrandbits",
"(",
"128",
")",
")",
"+",
"'.'",
"+",
"inputtemplate",
".",
"extension",
"else",
":",
"filename",
"=",
"str",
"(",
"nextseq",
")",
"+",
"'-'",
"+",
"str",
"(",
"\"%034x\"",
"%",
"random",
".",
"getrandbits",
"(",
"128",
")",
")",
"#Make sure filename matches (only if not an archive)",
"if",
"inputtemplate",
".",
"acceptarchive",
"and",
"(",
"filename",
"[",
"-",
"7",
":",
"]",
".",
"lower",
"(",
")",
"==",
"'.tar.gz'",
"or",
"filename",
"[",
"-",
"8",
":",
"]",
".",
"lower",
"(",
")",
"==",
"'.tar.bz2'",
"or",
"filename",
"[",
"-",
"4",
":",
"]",
".",
"lower",
"(",
")",
"==",
"'.zip'",
")",
":",
"pass",
"else",
":",
"if",
"inputtemplate",
".",
"filename",
":",
"if",
"filename",
"!=",
"inputtemplate",
".",
"filename",
":",
"filename",
"=",
"inputtemplate",
".",
"filename",
"#return flask.make_response(\"Specified filename must the filename dictated by the inputtemplate, which is \" + inputtemplate.filename)",
"#TODO LATER: add support for calling this with an actual number instead of #",
"if",
"inputtemplate",
".",
"extension",
":",
"if",
"filename",
"[",
"-",
"len",
"(",
"inputtemplate",
".",
"extension",
")",
"-",
"1",
":",
"]",
".",
"lower",
"(",
")",
"==",
"'.'",
"+",
"inputtemplate",
".",
"extension",
".",
"lower",
"(",
")",
":",
"#good, extension matches (case independent). Let's just make sure the case is as defined exactly by the inputtemplate",
"filename",
"=",
"filename",
"[",
":",
"-",
"len",
"(",
"inputtemplate",
".",
"extension",
")",
"-",
"1",
"]",
"+",
"'.'",
"+",
"inputtemplate",
".",
"extension",
"else",
":",
"filename",
"=",
"filename",
"+",
"'.'",
"+",
"inputtemplate",
".",
"extension",
"#return flask.make_response(\"Specified filename does not have the extension dictated by the inputtemplate (\"+inputtemplate.extension+\")\") #403",
"if",
"inputtemplate",
".",
"onlyinputsource",
"and",
"(",
"not",
"'inputsource'",
"in",
"postdata",
"or",
"not",
"postdata",
"[",
"'inputsource'",
"]",
")",
":",
"return",
"errorresponse",
"(",
"\"Adding files for this inputtemplate must proceed through inputsource\"",
")",
"if",
"'converter'",
"in",
"postdata",
"and",
"postdata",
"[",
"'converter'",
"]",
"and",
"not",
"postdata",
"[",
"'converter'",
"]",
"in",
"[",
"x",
".",
"id",
"for",
"x",
"in",
"inputtemplate",
".",
"converters",
"]",
":",
"return",
"errorresponse",
"(",
"\"Invalid converter specified: \"",
"+",
"postdata",
"[",
"'converter'",
"]",
")",
"#Make sure the filename is secure",
"validfilename",
"=",
"True",
"DISALLOWED",
"=",
"(",
"'/'",
",",
"'&'",
",",
"'|'",
",",
"'<'",
",",
"'>'",
",",
"';'",
",",
"'\"'",
",",
"\"'\"",
",",
"\"`\"",
",",
"\"{\"",
",",
"\"}\"",
",",
"\"\\n\"",
",",
"\"\\r\"",
",",
"\"\\b\"",
",",
"\"\\t\"",
")",
"for",
"c",
"in",
"filename",
":",
"if",
"c",
"in",
"DISALLOWED",
":",
"validfilename",
"=",
"False",
"break",
"if",
"not",
"validfilename",
":",
"return",
"errorresponse",
"(",
"\"Filename contains invalid symbols! Do not use /,&,|,<,>,',`,\\\",{,} or ;\"",
")",
"#Create the project (no effect if already exists)",
"response",
"=",
"Project",
".",
"create",
"(",
"project",
",",
"user",
")",
"if",
"response",
"is",
"not",
"None",
":",
"return",
"response",
"printdebug",
"(",
"\"(Obtaining filename for uploaded file)\"",
")",
"head",
"=",
"\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"",
"head",
"+=",
"\"<clamupload>\\n\"",
"if",
"'file'",
"in",
"flask",
".",
"request",
".",
"files",
":",
"printlog",
"(",
"\"Adding client-side file \"",
"+",
"flask",
".",
"request",
".",
"files",
"[",
"'file'",
"]",
".",
"filename",
"+",
"\" to input files\"",
")",
"sourcefile",
"=",
"flask",
".",
"request",
".",
"files",
"[",
"'file'",
"]",
".",
"filename",
"elif",
"'url'",
"in",
"postdata",
"and",
"postdata",
"[",
"'url'",
"]",
":",
"#Download from URL",
"printlog",
"(",
"\"Adding web-based URL \"",
"+",
"postdata",
"[",
"'url'",
"]",
"+",
"\" to input files\"",
")",
"sourcefile",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"postdata",
"[",
"'url'",
"]",
")",
"elif",
"'contents'",
"in",
"postdata",
"and",
"postdata",
"[",
"'contents'",
"]",
":",
"#In message",
"printlog",
"(",
"\"Adding file \"",
"+",
"filename",
"+",
"\" with explicitly provided contents to input files\"",
")",
"sourcefile",
"=",
"\"editor\"",
"elif",
"'inputsource'",
"in",
"postdata",
"and",
"postdata",
"[",
"'inputsource'",
"]",
":",
"printlog",
"(",
"\"Adding file \"",
"+",
"filename",
"+",
"\" from preinstalled data to input files\"",
")",
"if",
"not",
"inputsource",
":",
"inputsource",
"=",
"None",
"for",
"s",
"in",
"inputtemplate",
".",
"inputsources",
":",
"if",
"s",
".",
"id",
".",
"lower",
"(",
")",
"==",
"postdata",
"[",
"'inputsource'",
"]",
".",
"lower",
"(",
")",
":",
"inputsource",
"=",
"s",
"if",
"not",
"inputsource",
":",
"return",
"errorresponse",
"(",
"\"Specified inputsource '\"",
"+",
"postdata",
"[",
"'inputsource'",
"]",
"+",
"\"' does not exist for inputtemplate '\"",
"+",
"inputtemplate",
".",
"id",
"+",
"\"'\"",
")",
"sourcefile",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"inputsource",
".",
"path",
")",
"elif",
"'accesstoken'",
"in",
"postdata",
"and",
"'filename'",
"in",
"postdata",
":",
"#XHR POST, data in body",
"printlog",
"(",
"\"Adding client-side file \"",
"+",
"filename",
"+",
"\" to input files. Uploaded using XHR POST\"",
")",
"sourcefile",
"=",
"postdata",
"[",
"'filename'",
"]",
"else",
":",
"return",
"errorresponse",
"(",
"\"No file, url or contents specified!\"",
")",
"#============================ Generate metadata ========================================",
"printdebug",
"(",
"'(Generating and validating metadata)'",
")",
"if",
"'metafile'",
"in",
"flask",
".",
"request",
".",
"files",
":",
"#and (not isinstance(postdata['metafile'], dict) or len(postdata['metafile']) > 0)):",
"#an explicit metadata file was provided, upload it:",
"printlog",
"(",
"\"Metadata explicitly provided in file, uploading...\"",
")",
"#Upload file from client to server",
"metafile",
"=",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'input/.'",
"+",
"filename",
"+",
"'.METADATA'",
"flask",
".",
"request",
".",
"files",
"[",
"'metafile'",
"]",
".",
"save",
"(",
"metafile",
")",
"try",
":",
"with",
"io",
".",
"open",
"(",
"metafile",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"metadata",
"=",
"clam",
".",
"common",
".",
"data",
".",
"CLAMMetaData",
".",
"fromxml",
"(",
"f",
".",
"read",
"(",
")",
")",
"errors",
",",
"parameters",
"=",
"inputtemplate",
".",
"validate",
"(",
"metadata",
",",
"user",
")",
"validmeta",
"=",
"True",
"except",
"Exception",
"as",
"e",
":",
"#pylint: disable=broad-except",
"printlog",
"(",
"\"Uploaded metadata is invalid! \"",
"+",
"str",
"(",
"e",
")",
")",
"metadata",
"=",
"None",
"errors",
"=",
"True",
"parameters",
"=",
"[",
"]",
"validmeta",
"=",
"False",
"elif",
"'metadata'",
"in",
"postdata",
"and",
"postdata",
"[",
"'metadata'",
"]",
":",
"printlog",
"(",
"\"Metadata explicitly provided in message, uploading...\"",
")",
"try",
":",
"metadata",
"=",
"clam",
".",
"common",
".",
"data",
".",
"CLAMMetaData",
".",
"fromxml",
"(",
"postdata",
"[",
"'metadata'",
"]",
")",
"errors",
",",
"parameters",
"=",
"inputtemplate",
".",
"validate",
"(",
"metadata",
",",
"user",
")",
"validmeta",
"=",
"True",
"except",
":",
"#pylint: disable=bare-except",
"printlog",
"(",
"\"Uploaded metadata is invalid!\"",
")",
"metadata",
"=",
"None",
"errors",
"=",
"True",
"parameters",
"=",
"[",
"]",
"validmeta",
"=",
"False",
"elif",
"'inputsource'",
"in",
"postdata",
"and",
"postdata",
"[",
"'inputsource'",
"]",
":",
"printlog",
"(",
"\"Getting metadata from inputsource, uploading...\"",
")",
"if",
"inputsource",
".",
"metadata",
":",
"printlog",
"(",
"\"DEBUG: Validating metadata from inputsource\"",
")",
"metadata",
"=",
"inputsource",
".",
"metadata",
"errors",
",",
"parameters",
"=",
"inputtemplate",
".",
"validate",
"(",
"metadata",
",",
"user",
")",
"validmeta",
"=",
"True",
"else",
":",
"printlog",
"(",
"\"DEBUG: No metadata provided with inputsource, looking for metadata files..\"",
")",
"metafilename",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"inputsource",
".",
"path",
")",
"if",
"metafilename",
":",
"metafilename",
"+=",
"'/'",
"metafilename",
"+=",
"'.'",
"+",
"os",
".",
"path",
".",
"basename",
"(",
"inputsource",
".",
"path",
")",
"+",
"'.METADATA'",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"metafilename",
")",
":",
"try",
":",
"metadata",
"=",
"clam",
".",
"common",
".",
"data",
".",
"CLAMMetaData",
".",
"fromxml",
"(",
"open",
"(",
"metafilename",
",",
"'r'",
")",
".",
"readlines",
"(",
")",
")",
"errors",
",",
"parameters",
"=",
"inputtemplate",
".",
"validate",
"(",
"metadata",
",",
"user",
")",
"validmeta",
"=",
"True",
"except",
":",
"#pylint: disable=bare-except",
"printlog",
"(",
"\"Uploaded metadata is invalid!\"",
")",
"metadata",
"=",
"None",
"errors",
"=",
"True",
"parameters",
"=",
"[",
"]",
"validmeta",
"=",
"False",
"else",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"No metadata found nor specified for inputsource \"",
"+",
"inputsource",
".",
"id",
",",
"500",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"else",
":",
"errors",
",",
"parameters",
"=",
"inputtemplate",
".",
"validate",
"(",
"postdata",
",",
"user",
")",
"validmeta",
"=",
"True",
"#will be checked later",
"# ----------- Check if archive are allowed -------------",
"archive",
"=",
"False",
"addedfiles",
"=",
"[",
"]",
"if",
"not",
"errors",
"and",
"inputtemplate",
".",
"acceptarchive",
":",
"#pylint: disable=too-many-nested-blocks",
"printdebug",
"(",
"'(Archive test)'",
")",
"# -------- Are we an archive? If so, determine what kind",
"archivetype",
"=",
"None",
"if",
"'file'",
"in",
"flask",
".",
"request",
".",
"files",
":",
"uploadname",
"=",
"sourcefile",
".",
"lower",
"(",
")",
"archivetype",
"=",
"None",
"if",
"uploadname",
"[",
"-",
"4",
":",
"]",
"==",
"'.zip'",
":",
"archivetype",
"=",
"'zip'",
"elif",
"uploadname",
"[",
"-",
"7",
":",
"]",
"==",
"'.tar.gz'",
":",
"archivetype",
"=",
"'tar.gz'",
"elif",
"uploadname",
"[",
"-",
"4",
":",
"]",
"==",
"'.tar'",
":",
"archivetype",
"=",
"'tar'",
"elif",
"uploadname",
"[",
"-",
"8",
":",
"]",
"==",
"'.tar.bz2'",
":",
"archivetype",
"=",
"'tar.bz2'",
"xhrpost",
"=",
"False",
"elif",
"'accesstoken'",
"in",
"postdata",
"and",
"'filename'",
"in",
"postdata",
":",
"xhrpost",
"=",
"True",
"if",
"postdata",
"[",
"'filename'",
"]",
"[",
"-",
"7",
":",
"]",
".",
"lower",
"(",
")",
"==",
"'.tar.gz'",
":",
"uploadname",
"=",
"sourcefile",
".",
"lower",
"(",
")",
"archivetype",
"=",
"'tar.gz'",
"elif",
"postdata",
"[",
"'filename'",
"]",
"[",
"-",
"8",
":",
"]",
".",
"lower",
"(",
")",
"==",
"'.tar.bz2'",
":",
"uploadname",
"=",
"sourcefile",
".",
"lower",
"(",
")",
"archivetype",
"=",
"'tar.bz2'",
"elif",
"postdata",
"[",
"'filename'",
"]",
"[",
"-",
"4",
":",
"]",
".",
"lower",
"(",
")",
"==",
"'.tar'",
":",
"uploadname",
"=",
"sourcefile",
".",
"lower",
"(",
")",
"archivetype",
"=",
"'tar'",
"elif",
"postdata",
"[",
"'filename'",
"]",
"[",
"-",
"4",
":",
"]",
".",
"lower",
"(",
")",
"==",
"'.zip'",
":",
"uploadname",
"=",
"sourcefile",
".",
"lower",
"(",
")",
"archivetype",
"=",
"'zip'",
"if",
"archivetype",
":",
"# =============== upload archive ======================",
"#random name",
"archive",
"=",
"\"%032x\"",
"%",
"random",
".",
"getrandbits",
"(",
"128",
")",
"+",
"'.'",
"+",
"archivetype",
"#Upload file from client to server",
"printdebug",
"(",
"'(Archive transfer starting)'",
")",
"if",
"not",
"xhrpost",
":",
"flask",
".",
"request",
".",
"files",
"[",
"'file'",
"]",
".",
"save",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"archive",
")",
"elif",
"xhrpost",
":",
"with",
"open",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"archive",
",",
"'wb'",
")",
"as",
"f",
":",
"while",
"True",
":",
"chunk",
"=",
"flask",
".",
"request",
".",
"stream",
".",
"read",
"(",
"16384",
")",
"if",
"chunk",
":",
"f",
".",
"write",
"(",
"chunk",
")",
"else",
":",
"break",
"printdebug",
"(",
"'(Archive transfer completed)'",
")",
"# =============== Extract archive ======================",
"#Determine extraction command",
"if",
"archivetype",
"==",
"'zip'",
":",
"cmd",
"=",
"'unzip -u'",
"elif",
"archivetype",
"==",
"'tar'",
":",
"cmd",
"=",
"'tar -xvf'",
"elif",
"archivetype",
"==",
"'tar.gz'",
":",
"cmd",
"=",
"'tar -xvzf'",
"elif",
"archivetype",
"==",
"'tar.bz2'",
":",
"cmd",
"=",
"'tar -xvjf'",
"else",
":",
"raise",
"Exception",
"(",
"\"Invalid archive format: \"",
"+",
"archivetype",
")",
"#invalid archive, shouldn't happen",
"#invoke extractor",
"printlog",
"(",
"\"Extracting '\"",
"+",
"archive",
"+",
"\"'\"",
")",
"try",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
"+",
"\" \"",
"+",
"archive",
",",
"cwd",
"=",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"shell",
"=",
"True",
")",
"except",
":",
"#pylint: disable=bare-except",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"Unable to extract archive\"",
",",
"500",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"out",
",",
"_",
"=",
"process",
".",
"communicate",
"(",
")",
"#waits for process to end",
"if",
"sys",
".",
"version",
"<",
"'3'",
":",
"if",
"isinstance",
"(",
"out",
",",
"str",
")",
":",
"out",
"=",
"unicode",
"(",
"out",
",",
"'utf-8'",
")",
"#pylint: disable=undefined-variable",
"else",
":",
"if",
"isinstance",
"(",
"out",
",",
"bytes",
")",
":",
"out",
"=",
"str",
"(",
"out",
",",
"'utf-8'",
")",
"#Read filename results",
"firstline",
"=",
"True",
"for",
"line",
"in",
"out",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
":",
"printdebug",
"(",
"'(Extraction output: '",
"+",
"line",
"+",
"')'",
")",
"subfile",
"=",
"None",
"if",
"archivetype",
"[",
"0",
":",
"3",
"]",
"==",
"'tar'",
":",
"subfile",
"=",
"line",
"elif",
"archivetype",
"==",
"'zip'",
"and",
"not",
"firstline",
":",
"#firstline contains archive name itself, skip it",
"colon",
"=",
"line",
".",
"find",
"(",
"\":\"",
")",
"if",
"colon",
":",
"subfile",
"=",
"line",
"[",
"colon",
"+",
"1",
":",
"]",
".",
"strip",
"(",
")",
"if",
"subfile",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"subfile",
")",
":",
"subfile_newname",
"=",
"clam",
".",
"common",
".",
"data",
".",
"resolveinputfilename",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"subfile",
")",
",",
"parameters",
",",
"inputtemplate",
",",
"nextseq",
"+",
"len",
"(",
"addedfiles",
")",
",",
"project",
")",
"printdebug",
"(",
"'(Extracted file '",
"+",
"subfile",
"+",
"', moving to input/'",
"+",
"subfile_newname",
"+",
"')'",
")",
"os",
".",
"rename",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"subfile",
",",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'input/'",
"+",
"subfile_newname",
")",
"addedfiles",
".",
"append",
"(",
"subfile_newname",
")",
"firstline",
"=",
"False",
"#all done, remove archive",
"os",
".",
"unlink",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"archive",
")",
"if",
"not",
"archive",
":",
"addedfiles",
"=",
"[",
"clam",
".",
"common",
".",
"data",
".",
"resolveinputfilename",
"(",
"filename",
",",
"parameters",
",",
"inputtemplate",
",",
"nextseq",
",",
"project",
")",
"]",
"fatalerror",
"=",
"None",
"jsonoutput",
"=",
"{",
"'success'",
":",
"False",
"if",
"errors",
"else",
"True",
",",
"'isarchive'",
":",
"archive",
"}",
"output",
"=",
"head",
"for",
"filename",
"in",
"addedfiles",
":",
"#pylint: disable=too-many-nested-blocks",
"output",
"+=",
"\"<upload source=\\\"\"",
"+",
"sourcefile",
"+",
"\"\\\" filename=\\\"\"",
"+",
"filename",
"+",
"\"\\\" inputtemplate=\\\"\"",
"+",
"inputtemplate",
".",
"id",
"+",
"\"\\\" templatelabel=\\\"\"",
"+",
"inputtemplate",
".",
"label",
"+",
"\"\\\" format=\\\"\"",
"+",
"inputtemplate",
".",
"formatclass",
".",
"__name__",
"+",
"\"\\\">\\n\"",
"if",
"not",
"errors",
":",
"output",
"+=",
"\"<parameters errors=\\\"no\\\">\"",
"else",
":",
"output",
"+=",
"\"<parameters errors=\\\"yes\\\">\"",
"jsonoutput",
"[",
"'error'",
"]",
"=",
"'There were parameter errors, file not uploaded: '",
"for",
"parameter",
"in",
"parameters",
":",
"output",
"+=",
"parameter",
".",
"xml",
"(",
")",
"if",
"parameter",
".",
"error",
":",
"jsonoutput",
"[",
"'error'",
"]",
"+=",
"parameter",
".",
"error",
"+",
"\". \"",
"output",
"+=",
"\"</parameters>\"",
"if",
"not",
"errors",
":",
"if",
"not",
"archive",
":",
"#============================ Transfer file ========================================",
"printdebug",
"(",
"'(Start file transfer: '",
"+",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'input/'",
"+",
"filename",
"+",
"' )'",
")",
"if",
"'file'",
"in",
"flask",
".",
"request",
".",
"files",
":",
"printdebug",
"(",
"'(Receiving data by uploading file)'",
")",
"#Upload file from client to server",
"flask",
".",
"request",
".",
"files",
"[",
"'file'",
"]",
".",
"save",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'input/'",
"+",
"filename",
")",
"elif",
"'url'",
"in",
"postdata",
"and",
"postdata",
"[",
"'url'",
"]",
":",
"printdebug",
"(",
"'(Receiving data via url)'",
")",
"#Download file from 3rd party server to CLAM server",
"try",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"postdata",
"[",
"'url'",
"]",
")",
"except",
":",
"raise",
"flask",
".",
"abort",
"(",
"404",
")",
"if",
"not",
"(",
"r",
".",
"status_code",
">=",
"200",
"and",
"r",
".",
"status_code",
"<",
"300",
")",
":",
"raise",
"flask",
".",
"abort",
"(",
"404",
")",
"CHUNK",
"=",
"16",
"*",
"1024",
"f",
"=",
"open",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'input/'",
"+",
"filename",
",",
"'wb'",
")",
"for",
"chunk",
"in",
"r",
".",
"iter_content",
"(",
"chunk_size",
"=",
"CHUNK",
")",
":",
"if",
"chunk",
":",
"# filter out keep-alive new chunks",
"f",
".",
"write",
"(",
"chunk",
")",
"f",
".",
"flush",
"(",
")",
"f",
".",
"close",
"(",
")",
"elif",
"'inputsource'",
"in",
"postdata",
"and",
"postdata",
"[",
"'inputsource'",
"]",
":",
"#Copy (symlink!) from preinstalled data",
"printdebug",
"(",
"'(Creating symlink to file '",
"+",
"inputsource",
".",
"path",
"+",
"' <- '",
"+",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'/input/ '",
"+",
"filename",
"+",
"')'",
")",
"os",
".",
"symlink",
"(",
"inputsource",
".",
"path",
",",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'input/'",
"+",
"filename",
")",
"elif",
"'contents'",
"in",
"postdata",
"and",
"postdata",
"[",
"'contents'",
"]",
":",
"printdebug",
"(",
"'(Receiving data via from contents variable)'",
")",
"#grab encoding",
"encoding",
"=",
"'utf-8'",
"for",
"p",
"in",
"parameters",
":",
"if",
"p",
".",
"id",
"==",
"'encoding'",
":",
"encoding",
"=",
"p",
".",
"value",
"#Contents passed in POST message itself",
"try",
":",
"f",
"=",
"io",
".",
"open",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'input/'",
"+",
"filename",
",",
"'w'",
",",
"encoding",
"=",
"encoding",
")",
"f",
".",
"write",
"(",
"postdata",
"[",
"'contents'",
"]",
")",
"f",
".",
"close",
"(",
")",
"except",
"UnicodeError",
":",
"return",
"errorresponse",
"(",
"\"Input file \"",
"+",
"str",
"(",
"filename",
")",
"+",
"\" is not in the expected encoding!\"",
")",
"elif",
"'accesstoken'",
"in",
"postdata",
"and",
"'filename'",
"in",
"postdata",
":",
"printdebug",
"(",
"'(Receiving data directly from post body)'",
")",
"with",
"open",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'input/'",
"+",
"filename",
",",
"'wb'",
")",
"as",
"f",
":",
"while",
"True",
":",
"chunk",
"=",
"flask",
".",
"request",
".",
"stream",
".",
"read",
"(",
"16384",
")",
"if",
"chunk",
":",
"f",
".",
"write",
"(",
"chunk",
")",
"else",
":",
"break",
"printdebug",
"(",
"'(File transfer completed)'",
")",
"#Create a file object",
"file",
"=",
"clam",
".",
"common",
".",
"data",
".",
"CLAMInputFile",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
",",
"filename",
",",
"False",
")",
"#get CLAMInputFile without metadata (chicken-egg problem, this does not read the actual file contents!",
"#============== Generate metadata ==============",
"metadataerror",
"=",
"None",
"if",
"not",
"metadata",
"and",
"not",
"errors",
":",
"#check if it has not already been set in another stage",
"printdebug",
"(",
"'(Generating metadata)'",
")",
"#for newly generated metadata",
"try",
":",
"#Now we generate the actual metadata object (unsaved yet though). We pass our earlier validation results to prevent computing it again",
"validmeta",
",",
"metadata",
",",
"parameters",
"=",
"inputtemplate",
".",
"generate",
"(",
"file",
",",
"(",
"errors",
",",
"parameters",
")",
")",
"if",
"validmeta",
":",
"#And we tie it to the CLAMFile object",
"file",
".",
"metadata",
"=",
"metadata",
"#Add inputtemplate ID to metadata",
"metadata",
".",
"inputtemplate",
"=",
"inputtemplate",
".",
"id",
"else",
":",
"metadataerror",
"=",
"\"Undefined error\"",
"except",
"ValueError",
"as",
"msg",
":",
"validmeta",
"=",
"False",
"metadataerror",
"=",
"msg",
"except",
"KeyError",
"as",
"msg",
":",
"validmeta",
"=",
"False",
"metadataerror",
"=",
"msg",
"elif",
"validmeta",
":",
"#for explicitly uploaded metadata",
"metadata",
".",
"file",
"=",
"file",
"file",
".",
"metadata",
"=",
"metadata",
"metadata",
".",
"inputtemplate",
"=",
"inputtemplate",
".",
"id",
"if",
"metadataerror",
":",
"printdebug",
"(",
"'(Metadata could not be generated, '",
"+",
"str",
"(",
"metadataerror",
")",
"+",
"', this usually indicated an error in service configuration)'",
")",
"#output += \"<metadataerror />\" #This usually indicates an error in service configuration!",
"fatalerror",
"=",
"\"<error type=\\\"metadataerror\\\">Metadata could not be generated for \"",
"+",
"filename",
"+",
"\": \"",
"+",
"str",
"(",
"metadataerror",
")",
"+",
"\" (this usually indicates an error in service configuration!)</error>\"",
"jsonoutput",
"[",
"'error'",
"]",
"=",
"\"Metadata could not be generated! \"",
"+",
"str",
"(",
"metadataerror",
")",
"+",
"\" (this usually indicates an error in service configuration!)\"",
"elif",
"validmeta",
":",
"#=========== Convert the uploaded file (if requested) ==============",
"conversionerror",
"=",
"False",
"if",
"'converter'",
"in",
"postdata",
"and",
"postdata",
"[",
"'converter'",
"]",
":",
"for",
"c",
"in",
"inputtemplate",
".",
"converters",
":",
"if",
"c",
".",
"id",
"==",
"postdata",
"[",
"'converter'",
"]",
":",
"converter",
"=",
"c",
"break",
"if",
"converter",
":",
"#(should always be found, error already provided earlier if not)",
"printdebug",
"(",
"'(Invoking converter)'",
")",
"try",
":",
"success",
"=",
"converter",
".",
"convertforinput",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'input/'",
"+",
"filename",
",",
"metadata",
")",
"except",
":",
"#pylint: disable=bare-except",
"success",
"=",
"False",
"if",
"not",
"success",
":",
"conversionerror",
"=",
"True",
"fatalerror",
"=",
"\"<error type=\\\"conversion\\\">The file \"",
"+",
"xmlescape",
"(",
"filename",
")",
"+",
"\" could not be converted</error>\"",
"jsonoutput",
"[",
"'error'",
"]",
"=",
"\"The file could not be converted\"",
"jsonoutput",
"[",
"'success'",
"]",
"=",
"False",
"#====================== Validate the file itself ====================",
"if",
"not",
"conversionerror",
":",
"valid",
"=",
"file",
".",
"validate",
"(",
")",
"if",
"valid",
":",
"printdebug",
"(",
"'(Validation ok)'",
")",
"output",
"+=",
"\"<valid>yes</valid>\"",
"#Great! Everything ok, save metadata",
"metadata",
".",
"save",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'input/'",
"+",
"file",
".",
"metafilename",
"(",
")",
")",
"#And create symbolic link for inputtemplates",
"linkfilename",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"if",
"linkfilename",
":",
"linkfilename",
"+=",
"'/'",
"linkfilename",
"+=",
"'.'",
"+",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"+",
"'.INPUTTEMPLATE'",
"+",
"'.'",
"+",
"inputtemplate",
".",
"id",
"+",
"'.'",
"+",
"str",
"(",
"nextseq",
")",
"os",
".",
"symlink",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'input/'",
"+",
"filename",
",",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'input/'",
"+",
"linkfilename",
")",
"else",
":",
"printdebug",
"(",
"'(Validation error)'",
")",
"#Too bad, everything worked out but the file itself doesn't validate.",
"#output += \"<valid>no</valid>\"",
"fatalerror",
"=",
"\"<error type=\\\"validation\\\">The file \"",
"+",
"xmlescape",
"(",
"filename",
")",
"+",
"\" did not validate, it is not in the proper expected format.</error>\"",
"jsonoutput",
"[",
"'error'",
"]",
"=",
"\"The file \"",
"+",
"filename",
".",
"replace",
"(",
"\"'\"",
",",
"\"\"",
")",
"+",
"\" did not validate, it is not in the proper expected format.\"",
"jsonoutput",
"[",
"'success'",
"]",
"=",
"False",
"#remove upload",
"os",
".",
"unlink",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'input/'",
"+",
"filename",
")",
"output",
"+=",
"\"</upload>\\n\"",
"output",
"+=",
"\"</clamupload>\"",
"if",
"returntype",
"==",
"'boolean'",
":",
"return",
"jsonoutput",
"[",
"'success'",
"]",
"elif",
"fatalerror",
":",
"#fatal error return error message with 403 code",
"printlog",
"(",
"'Fatal Error during upload: '",
"+",
"fatalerror",
")",
"return",
"errorresponse",
"(",
"head",
"+",
"fatalerror",
",",
"403",
")",
"elif",
"errors",
":",
"#parameter errors, return XML output with 403 code",
"printdebug",
"(",
"'There were parameter errors during upload!'",
")",
"if",
"returntype",
"==",
"'json'",
":",
"jsonoutput",
"[",
"'xml'",
"]",
"=",
"output",
"#embed XML in JSON for complete client-side processing",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"json",
".",
"dumps",
"(",
"jsonoutput",
")",
")",
",",
"'application/json'",
",",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"else",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"output",
",",
"403",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"elif",
"returntype",
"==",
"'xml'",
":",
"#success",
"printdebug",
"(",
"'Returning xml'",
")",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"output",
")",
",",
"'text/xml'",
",",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"elif",
"returntype",
"==",
"'json'",
":",
"#success",
"printdebug",
"(",
"'Returning json'",
")",
"#everything ok, return JSON output (caller decides)",
"jsonoutput",
"[",
"'xml'",
"]",
"=",
"output",
"#embed XML in JSON for complete client-side processing",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"json",
".",
"dumps",
"(",
"jsonoutput",
")",
")",
",",
"'application/json'",
",",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"elif",
"returntype",
"==",
"'true_on_success'",
":",
"return",
"True",
"else",
":",
"printdebug",
"(",
"'Invalid return type'",
")",
"raise",
"Exception",
"(",
"\"invalid return type\"",
")"
] | Add a new input file, this invokes the actual uploader | [
"Add",
"a",
"new",
"input",
"file",
"this",
"invokes",
"the",
"actual",
"uploader"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L1547-L2069 |
proycon/clam | clam/clamservice.py | uploader | def uploader(project, credentials=None):
"""The Uploader is intended for the Fine Uploader used in the web application (or similar frontend), it is not intended for proper RESTful communication. Will return JSON compatible with Fine Uploader rather than CLAM Upload XML. Unfortunately, normal digest authentication does not work well with the uploader, so we implement a simple key check based on hashed username, projectname and a secret key that is communicated as a JS variable in the interface ."""
postdata = flask.request.values
if 'user' in postdata:
user = postdata['user']
else:
user = 'anonymous'
if 'filename' in postdata:
filename = postdata['filename']
else:
printdebug('No filename passed')
return "{success: false, error: 'No filename passed'}"
if 'accesstoken' in postdata:
accesstoken = postdata['accesstoken']
else:
return withheaders(flask.make_response("{success: false, error: 'No accesstoken given'}"),'application/json', {'allow_origin': settings.ALLOW_ORIGIN})
if accesstoken != Project.getaccesstoken(user,project):
return withheaders(flask.make_response("{success: false, error: 'Invalid accesstoken given'}"),'application/json', {'allow_origin': settings.ALLOW_ORIGIN})
if not os.path.exists(Project.path(project, user)):
return withheaders(flask.make_response("{success: false, error: 'Destination does not exist'}"),'application/json', {'allow_origin': settings.ALLOW_ORIGIN})
else:
return addfile(project,filename,user, postdata,None, 'json' ) | python | def uploader(project, credentials=None):
"""The Uploader is intended for the Fine Uploader used in the web application (or similar frontend), it is not intended for proper RESTful communication. Will return JSON compatible with Fine Uploader rather than CLAM Upload XML. Unfortunately, normal digest authentication does not work well with the uploader, so we implement a simple key check based on hashed username, projectname and a secret key that is communicated as a JS variable in the interface ."""
postdata = flask.request.values
if 'user' in postdata:
user = postdata['user']
else:
user = 'anonymous'
if 'filename' in postdata:
filename = postdata['filename']
else:
printdebug('No filename passed')
return "{success: false, error: 'No filename passed'}"
if 'accesstoken' in postdata:
accesstoken = postdata['accesstoken']
else:
return withheaders(flask.make_response("{success: false, error: 'No accesstoken given'}"),'application/json', {'allow_origin': settings.ALLOW_ORIGIN})
if accesstoken != Project.getaccesstoken(user,project):
return withheaders(flask.make_response("{success: false, error: 'Invalid accesstoken given'}"),'application/json', {'allow_origin': settings.ALLOW_ORIGIN})
if not os.path.exists(Project.path(project, user)):
return withheaders(flask.make_response("{success: false, error: 'Destination does not exist'}"),'application/json', {'allow_origin': settings.ALLOW_ORIGIN})
else:
return addfile(project,filename,user, postdata,None, 'json' ) | [
"def",
"uploader",
"(",
"project",
",",
"credentials",
"=",
"None",
")",
":",
"postdata",
"=",
"flask",
".",
"request",
".",
"values",
"if",
"'user'",
"in",
"postdata",
":",
"user",
"=",
"postdata",
"[",
"'user'",
"]",
"else",
":",
"user",
"=",
"'anonymous'",
"if",
"'filename'",
"in",
"postdata",
":",
"filename",
"=",
"postdata",
"[",
"'filename'",
"]",
"else",
":",
"printdebug",
"(",
"'No filename passed'",
")",
"return",
"\"{success: false, error: 'No filename passed'}\"",
"if",
"'accesstoken'",
"in",
"postdata",
":",
"accesstoken",
"=",
"postdata",
"[",
"'accesstoken'",
"]",
"else",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"{success: false, error: 'No accesstoken given'}\"",
")",
",",
"'application/json'",
",",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"if",
"accesstoken",
"!=",
"Project",
".",
"getaccesstoken",
"(",
"user",
",",
"project",
")",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"{success: false, error: 'Invalid accesstoken given'}\"",
")",
",",
"'application/json'",
",",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
")",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"{success: false, error: 'Destination does not exist'}\"",
")",
",",
"'application/json'",
",",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"else",
":",
"return",
"addfile",
"(",
"project",
",",
"filename",
",",
"user",
",",
"postdata",
",",
"None",
",",
"'json'",
")"
] | The Uploader is intended for the Fine Uploader used in the web application (or similar frontend), it is not intended for proper RESTful communication. Will return JSON compatible with Fine Uploader rather than CLAM Upload XML. Unfortunately, normal digest authentication does not work well with the uploader, so we implement a simple key check based on hashed username, projectname and a secret key that is communicated as a JS variable in the interface . | [
"The",
"Uploader",
"is",
"intended",
"for",
"the",
"Fine",
"Uploader",
"used",
"in",
"the",
"web",
"application",
"(",
"or",
"similar",
"frontend",
")",
"it",
"is",
"not",
"intended",
"for",
"proper",
"RESTful",
"communication",
".",
"Will",
"return",
"JSON",
"compatible",
"with",
"Fine",
"Uploader",
"rather",
"than",
"CLAM",
"Upload",
"XML",
".",
"Unfortunately",
"normal",
"digest",
"authentication",
"does",
"not",
"work",
"well",
"with",
"the",
"uploader",
"so",
"we",
"implement",
"a",
"simple",
"key",
"check",
"based",
"on",
"hashed",
"username",
"projectname",
"and",
"a",
"secret",
"key",
"that",
"is",
"communicated",
"as",
"a",
"JS",
"variable",
"in",
"the",
"interface",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L2099-L2120 |
proycon/clam | clam/clamservice.py | run_wsgi | def run_wsgi(settings_module):
"""Run CLAM in WSGI mode"""
global settingsmodule, DEBUG #pylint: disable=global-statement
printdebug("Initialising WSGI service")
globals()['settings'] = settings_module
settingsmodule = settings_module.__name__
try:
if settings.DEBUG:
DEBUG = True
setdebug(True)
except:
pass
test_version()
if DEBUG:
setlog(sys.stderr)
else:
setlog(None)
try:
if settings.LOGFILE:
setlogfile(settings.LOGFILE)
except:
pass
set_defaults() #host, port
test_dirs()
if DEBUG:
from werkzeug.debug import DebuggedApplication
return DebuggedApplication(CLAMService('wsgi').service.wsgi_app, True)
else:
return CLAMService('wsgi').service.wsgi_app | python | def run_wsgi(settings_module):
"""Run CLAM in WSGI mode"""
global settingsmodule, DEBUG #pylint: disable=global-statement
printdebug("Initialising WSGI service")
globals()['settings'] = settings_module
settingsmodule = settings_module.__name__
try:
if settings.DEBUG:
DEBUG = True
setdebug(True)
except:
pass
test_version()
if DEBUG:
setlog(sys.stderr)
else:
setlog(None)
try:
if settings.LOGFILE:
setlogfile(settings.LOGFILE)
except:
pass
set_defaults() #host, port
test_dirs()
if DEBUG:
from werkzeug.debug import DebuggedApplication
return DebuggedApplication(CLAMService('wsgi').service.wsgi_app, True)
else:
return CLAMService('wsgi').service.wsgi_app | [
"def",
"run_wsgi",
"(",
"settings_module",
")",
":",
"global",
"settingsmodule",
",",
"DEBUG",
"#pylint: disable=global-statement",
"printdebug",
"(",
"\"Initialising WSGI service\"",
")",
"globals",
"(",
")",
"[",
"'settings'",
"]",
"=",
"settings_module",
"settingsmodule",
"=",
"settings_module",
".",
"__name__",
"try",
":",
"if",
"settings",
".",
"DEBUG",
":",
"DEBUG",
"=",
"True",
"setdebug",
"(",
"True",
")",
"except",
":",
"pass",
"test_version",
"(",
")",
"if",
"DEBUG",
":",
"setlog",
"(",
"sys",
".",
"stderr",
")",
"else",
":",
"setlog",
"(",
"None",
")",
"try",
":",
"if",
"settings",
".",
"LOGFILE",
":",
"setlogfile",
"(",
"settings",
".",
"LOGFILE",
")",
"except",
":",
"pass",
"set_defaults",
"(",
")",
"#host, port",
"test_dirs",
"(",
")",
"if",
"DEBUG",
":",
"from",
"werkzeug",
".",
"debug",
"import",
"DebuggedApplication",
"return",
"DebuggedApplication",
"(",
"CLAMService",
"(",
"'wsgi'",
")",
".",
"service",
".",
"wsgi_app",
",",
"True",
")",
"else",
":",
"return",
"CLAMService",
"(",
"'wsgi'",
")",
".",
"service",
".",
"wsgi_app"
] | Run CLAM in WSGI mode | [
"Run",
"CLAM",
"in",
"WSGI",
"mode"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L2895-L2927 |
proycon/clam | clam/clamservice.py | Admin.index | def index(credentials=None):
"""Get list of projects"""
user, oauth_access_token = parsecredentials(credentials)
if not settings.ADMINS or user not in settings.ADMINS:
return flask.make_response('You shall not pass!!! You are not an administrator!',403)
usersprojects = {}
totalsize = {}
for f in glob.glob(settings.ROOT + "projects/*"):
if os.path.isdir(f):
u = os.path.basename(f)
usersprojects[u], totalsize[u] = getprojects(u)
usersprojects[u].sort()
return withheaders(flask.make_response(flask.render_template('admin.html',
version=VERSION,
system_id=settings.SYSTEM_ID,
system_name=settings.SYSTEM_NAME,
system_description=settings.SYSTEM_DESCRIPTION,
system_author=settings.SYSTEM_AUTHOR,
system_version=settings.SYSTEM_VERSION,
system_email=settings.SYSTEM_EMAIL,
user=user,
url=getrooturl(),
usersprojects = sorted(usersprojects.items()),
totalsize=totalsize,
allow_origin=settings.ALLOW_ORIGIN,
oauth_access_token=oauth_encrypt(oauth_access_token)
)), "text/html; charset=UTF-8", {'allow_origin':settings.ALLOW_ORIGIN}) | python | def index(credentials=None):
"""Get list of projects"""
user, oauth_access_token = parsecredentials(credentials)
if not settings.ADMINS or user not in settings.ADMINS:
return flask.make_response('You shall not pass!!! You are not an administrator!',403)
usersprojects = {}
totalsize = {}
for f in glob.glob(settings.ROOT + "projects/*"):
if os.path.isdir(f):
u = os.path.basename(f)
usersprojects[u], totalsize[u] = getprojects(u)
usersprojects[u].sort()
return withheaders(flask.make_response(flask.render_template('admin.html',
version=VERSION,
system_id=settings.SYSTEM_ID,
system_name=settings.SYSTEM_NAME,
system_description=settings.SYSTEM_DESCRIPTION,
system_author=settings.SYSTEM_AUTHOR,
system_version=settings.SYSTEM_VERSION,
system_email=settings.SYSTEM_EMAIL,
user=user,
url=getrooturl(),
usersprojects = sorted(usersprojects.items()),
totalsize=totalsize,
allow_origin=settings.ALLOW_ORIGIN,
oauth_access_token=oauth_encrypt(oauth_access_token)
)), "text/html; charset=UTF-8", {'allow_origin':settings.ALLOW_ORIGIN}) | [
"def",
"index",
"(",
"credentials",
"=",
"None",
")",
":",
"user",
",",
"oauth_access_token",
"=",
"parsecredentials",
"(",
"credentials",
")",
"if",
"not",
"settings",
".",
"ADMINS",
"or",
"user",
"not",
"in",
"settings",
".",
"ADMINS",
":",
"return",
"flask",
".",
"make_response",
"(",
"'You shall not pass!!! You are not an administrator!'",
",",
"403",
")",
"usersprojects",
"=",
"{",
"}",
"totalsize",
"=",
"{",
"}",
"for",
"f",
"in",
"glob",
".",
"glob",
"(",
"settings",
".",
"ROOT",
"+",
"\"projects/*\"",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"f",
")",
":",
"u",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
"usersprojects",
"[",
"u",
"]",
",",
"totalsize",
"[",
"u",
"]",
"=",
"getprojects",
"(",
"u",
")",
"usersprojects",
"[",
"u",
"]",
".",
"sort",
"(",
")",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"flask",
".",
"render_template",
"(",
"'admin.html'",
",",
"version",
"=",
"VERSION",
",",
"system_id",
"=",
"settings",
".",
"SYSTEM_ID",
",",
"system_name",
"=",
"settings",
".",
"SYSTEM_NAME",
",",
"system_description",
"=",
"settings",
".",
"SYSTEM_DESCRIPTION",
",",
"system_author",
"=",
"settings",
".",
"SYSTEM_AUTHOR",
",",
"system_version",
"=",
"settings",
".",
"SYSTEM_VERSION",
",",
"system_email",
"=",
"settings",
".",
"SYSTEM_EMAIL",
",",
"user",
"=",
"user",
",",
"url",
"=",
"getrooturl",
"(",
")",
",",
"usersprojects",
"=",
"sorted",
"(",
"usersprojects",
".",
"items",
"(",
")",
")",
",",
"totalsize",
"=",
"totalsize",
",",
"allow_origin",
"=",
"settings",
".",
"ALLOW_ORIGIN",
",",
"oauth_access_token",
"=",
"oauth_encrypt",
"(",
"oauth_access_token",
")",
")",
")",
",",
"\"text/html; charset=UTF-8\"",
",",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")"
] | Get list of projects | [
"Get",
"list",
"of",
"projects"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L473-L501 |
proycon/clam | clam/clamservice.py | Project.path | def path(project, credentials):
"""Get the path to the project (static method)"""
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
return settings.ROOT + "projects/" + user + '/' + project + "/" | python | def path(project, credentials):
"""Get the path to the project (static method)"""
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
return settings.ROOT + "projects/" + user + '/' + project + "/" | [
"def",
"path",
"(",
"project",
",",
"credentials",
")",
":",
"user",
",",
"oauth_access_token",
"=",
"parsecredentials",
"(",
"credentials",
")",
"#pylint: disable=unused-variable",
"return",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
"+",
"'/'",
"+",
"project",
"+",
"\"/\""
] | Get the path to the project (static method) | [
"Get",
"the",
"path",
"to",
"the",
"project",
"(",
"static",
"method",
")"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L620-L623 |
proycon/clam | clam/clamservice.py | Project.create | def create(project, credentials): #pylint: disable=too-many-return-statements
"""Create project skeleton if it does not already exist (static method)"""
if not settings.COMMAND:
return flask.make_response("Projects disabled, no command configured",404)
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
if not Project.validate(project):
return withheaders(flask.make_response('Invalid project ID. Note that only alphanumerical characters are allowed.',403),headers={'allow_origin': settings.ALLOW_ORIGIN})
printdebug("Checking if " + settings.ROOT + "projects/" + user + '/' + project + " exists")
if not project:
return withheaders(flask.make_response('No project name',403),headers={'allow_origin': settings.ALLOW_ORIGIN})
if not os.path.isdir(settings.ROOT + "projects/" + user):
printlog("Creating user directory '" + user + "'")
os.makedirs(settings.ROOT + "projects/" + user)
if not os.path.isdir(settings.ROOT + "projects/" + user): #verify:
return withheaders(flask.make_response("Directory " + settings.ROOT + "projects/" + user + " could not be created succesfully",403),headers={'allow_origin': settings.ALLOW_ORIGIN})
#checking user quota
if settings.USERQUOTA > 0:
_, totalsize = getprojects(user)
if totalsize > settings.USERQUOTA:
printlog("User " + user + " exceeded quota, refusing to create new project...")
return withheaders(flask.make_response("Unable to create new project because you are exceeding your disk quota (max " + str(settings.USERQUOTA) + " MB, you now use " + str(totalsize) + " MB). Please delete some projects and try again.",403),headers={'allow_origin': settings.ALLOW_ORIGIN})
if not os.path.isdir(settings.ROOT + "projects/" + user + '/' + project):
printlog("Creating project '" + project + "'")
os.makedirs(settings.ROOT + "projects/" + user + '/' + project)
#project index will need to be regenerated, remove cache
if os.path.exists(os.path.join(settings.ROOT + "projects/" + user,'.index')):
os.unlink(os.path.join(settings.ROOT + "projects/" + user,'.index'))
if not os.path.isdir(settings.ROOT + "projects/" + user + '/' + project + '/input/'):
os.makedirs(settings.ROOT + "projects/" + user + '/' + project + "/input")
if not os.path.isdir(settings.ROOT + "projects/" + user + '/' + project + '/input'):
return withheaders(flask.make_response("Input directory " + settings.ROOT + "projects/" + user + '/' + project + "/input/ could not be created succesfully",403),headers={'allow_origin': settings.ALLOW_ORIGIN})
if not os.path.isdir(settings.ROOT + "projects/" + user + '/' + project + '/output/'):
os.makedirs(settings.ROOT + "projects/" + user + '/' + project + "/output")
if not os.path.isdir(settings.ROOT + "projects/" + user + '/' + project + '/output'):
return withheaders(flask.make_response("Output directory " + settings.ROOT + "projects/" + user + '/' + project + "/output/ could not be created succesfully",403),headers={'allow_origin': settings.ALLOW_ORIGIN})
if not os.path.isdir(settings.ROOT + "projects/" + user + '/' + project + '/tmp/'):
os.makedirs(settings.ROOT + "projects/" + user + '/' + project + "/tmp")
if not os.path.isdir(settings.ROOT + "projects/" + user + '/' + project + '/tmp'):
return withheaders(flask.make_response("tmp directory " + settings.ROOT + "projects/" + user + '/' + project + "/tmp/ could not be created succesfully",403),headers={'allow_origin': settings.ALLOW_ORIGIN})
return None | python | def create(project, credentials): #pylint: disable=too-many-return-statements
"""Create project skeleton if it does not already exist (static method)"""
if not settings.COMMAND:
return flask.make_response("Projects disabled, no command configured",404)
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
if not Project.validate(project):
return withheaders(flask.make_response('Invalid project ID. Note that only alphanumerical characters are allowed.',403),headers={'allow_origin': settings.ALLOW_ORIGIN})
printdebug("Checking if " + settings.ROOT + "projects/" + user + '/' + project + " exists")
if not project:
return withheaders(flask.make_response('No project name',403),headers={'allow_origin': settings.ALLOW_ORIGIN})
if not os.path.isdir(settings.ROOT + "projects/" + user):
printlog("Creating user directory '" + user + "'")
os.makedirs(settings.ROOT + "projects/" + user)
if not os.path.isdir(settings.ROOT + "projects/" + user): #verify:
return withheaders(flask.make_response("Directory " + settings.ROOT + "projects/" + user + " could not be created succesfully",403),headers={'allow_origin': settings.ALLOW_ORIGIN})
#checking user quota
if settings.USERQUOTA > 0:
_, totalsize = getprojects(user)
if totalsize > settings.USERQUOTA:
printlog("User " + user + " exceeded quota, refusing to create new project...")
return withheaders(flask.make_response("Unable to create new project because you are exceeding your disk quota (max " + str(settings.USERQUOTA) + " MB, you now use " + str(totalsize) + " MB). Please delete some projects and try again.",403),headers={'allow_origin': settings.ALLOW_ORIGIN})
if not os.path.isdir(settings.ROOT + "projects/" + user + '/' + project):
printlog("Creating project '" + project + "'")
os.makedirs(settings.ROOT + "projects/" + user + '/' + project)
#project index will need to be regenerated, remove cache
if os.path.exists(os.path.join(settings.ROOT + "projects/" + user,'.index')):
os.unlink(os.path.join(settings.ROOT + "projects/" + user,'.index'))
if not os.path.isdir(settings.ROOT + "projects/" + user + '/' + project + '/input/'):
os.makedirs(settings.ROOT + "projects/" + user + '/' + project + "/input")
if not os.path.isdir(settings.ROOT + "projects/" + user + '/' + project + '/input'):
return withheaders(flask.make_response("Input directory " + settings.ROOT + "projects/" + user + '/' + project + "/input/ could not be created succesfully",403),headers={'allow_origin': settings.ALLOW_ORIGIN})
if not os.path.isdir(settings.ROOT + "projects/" + user + '/' + project + '/output/'):
os.makedirs(settings.ROOT + "projects/" + user + '/' + project + "/output")
if not os.path.isdir(settings.ROOT + "projects/" + user + '/' + project + '/output'):
return withheaders(flask.make_response("Output directory " + settings.ROOT + "projects/" + user + '/' + project + "/output/ could not be created succesfully",403),headers={'allow_origin': settings.ALLOW_ORIGIN})
if not os.path.isdir(settings.ROOT + "projects/" + user + '/' + project + '/tmp/'):
os.makedirs(settings.ROOT + "projects/" + user + '/' + project + "/tmp")
if not os.path.isdir(settings.ROOT + "projects/" + user + '/' + project + '/tmp'):
return withheaders(flask.make_response("tmp directory " + settings.ROOT + "projects/" + user + '/' + project + "/tmp/ could not be created succesfully",403),headers={'allow_origin': settings.ALLOW_ORIGIN})
return None | [
"def",
"create",
"(",
"project",
",",
"credentials",
")",
":",
"#pylint: disable=too-many-return-statements",
"if",
"not",
"settings",
".",
"COMMAND",
":",
"return",
"flask",
".",
"make_response",
"(",
"\"Projects disabled, no command configured\"",
",",
"404",
")",
"user",
",",
"oauth_access_token",
"=",
"parsecredentials",
"(",
"credentials",
")",
"#pylint: disable=unused-variable",
"if",
"not",
"Project",
".",
"validate",
"(",
"project",
")",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"'Invalid project ID. Note that only alphanumerical characters are allowed.'",
",",
"403",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"printdebug",
"(",
"\"Checking if \"",
"+",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
"+",
"'/'",
"+",
"project",
"+",
"\" exists\"",
")",
"if",
"not",
"project",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"'No project name'",
",",
"403",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
")",
":",
"printlog",
"(",
"\"Creating user directory '\"",
"+",
"user",
"+",
"\"'\"",
")",
"os",
".",
"makedirs",
"(",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
")",
":",
"#verify:",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"Directory \"",
"+",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
"+",
"\" could not be created succesfully\"",
",",
"403",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"#checking user quota",
"if",
"settings",
".",
"USERQUOTA",
">",
"0",
":",
"_",
",",
"totalsize",
"=",
"getprojects",
"(",
"user",
")",
"if",
"totalsize",
">",
"settings",
".",
"USERQUOTA",
":",
"printlog",
"(",
"\"User \"",
"+",
"user",
"+",
"\" exceeded quota, refusing to create new project...\"",
")",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"Unable to create new project because you are exceeding your disk quota (max \"",
"+",
"str",
"(",
"settings",
".",
"USERQUOTA",
")",
"+",
"\" MB, you now use \"",
"+",
"str",
"(",
"totalsize",
")",
"+",
"\" MB). Please delete some projects and try again.\"",
",",
"403",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
"+",
"'/'",
"+",
"project",
")",
":",
"printlog",
"(",
"\"Creating project '\"",
"+",
"project",
"+",
"\"'\"",
")",
"os",
".",
"makedirs",
"(",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
"+",
"'/'",
"+",
"project",
")",
"#project index will need to be regenerated, remove cache",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
",",
"'.index'",
")",
")",
":",
"os",
".",
"unlink",
"(",
"os",
".",
"path",
".",
"join",
"(",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
",",
"'.index'",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
"+",
"'/'",
"+",
"project",
"+",
"'/input/'",
")",
":",
"os",
".",
"makedirs",
"(",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
"+",
"'/'",
"+",
"project",
"+",
"\"/input\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
"+",
"'/'",
"+",
"project",
"+",
"'/input'",
")",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"Input directory \"",
"+",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
"+",
"'/'",
"+",
"project",
"+",
"\"/input/ could not be created succesfully\"",
",",
"403",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
"+",
"'/'",
"+",
"project",
"+",
"'/output/'",
")",
":",
"os",
".",
"makedirs",
"(",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
"+",
"'/'",
"+",
"project",
"+",
"\"/output\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
"+",
"'/'",
"+",
"project",
"+",
"'/output'",
")",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"Output directory \"",
"+",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
"+",
"'/'",
"+",
"project",
"+",
"\"/output/ could not be created succesfully\"",
",",
"403",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
"+",
"'/'",
"+",
"project",
"+",
"'/tmp/'",
")",
":",
"os",
".",
"makedirs",
"(",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
"+",
"'/'",
"+",
"project",
"+",
"\"/tmp\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
"+",
"'/'",
"+",
"project",
"+",
"'/tmp'",
")",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"tmp directory \"",
"+",
"settings",
".",
"ROOT",
"+",
"\"projects/\"",
"+",
"user",
"+",
"'/'",
"+",
"project",
"+",
"\"/tmp/ could not be created succesfully\"",
",",
"403",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"return",
"None"
] | Create project skeleton if it does not already exist (static method) | [
"Create",
"project",
"skeleton",
"if",
"it",
"does",
"not",
"already",
"exist",
"(",
"static",
"method",
")"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L638-L685 |
proycon/clam | clam/clamservice.py | Project.exists | def exists(project, credentials):
"""Check if the project exists"""
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
printdebug("Checking if project " + project + " exists for " + user)
return os.path.isdir(Project.path(project, user)) | python | def exists(project, credentials):
"""Check if the project exists"""
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
printdebug("Checking if project " + project + " exists for " + user)
return os.path.isdir(Project.path(project, user)) | [
"def",
"exists",
"(",
"project",
",",
"credentials",
")",
":",
"user",
",",
"oauth_access_token",
"=",
"parsecredentials",
"(",
"credentials",
")",
"#pylint: disable=unused-variable",
"printdebug",
"(",
"\"Checking if project \"",
"+",
"project",
"+",
"\" exists for \"",
"+",
"user",
")",
"return",
"os",
".",
"path",
".",
"isdir",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
")"
] | Check if the project exists | [
"Check",
"if",
"the",
"project",
"exists"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L748-L752 |
proycon/clam | clam/clamservice.py | Project.inputindexbytemplate | def inputindexbytemplate(project, user, inputtemplate):
"""Retrieve sorted index for the specified input template"""
index = [] #pylint: disable=redefined-outer-name
prefix = Project.path(project, user) + 'input/'
for linkf, f in globsymlinks(prefix + '.*.INPUTTEMPLATE.' + inputtemplate.id + '.*'):
seq = int(linkf.split('.')[-1])
index.append( (seq,f) )
#yield CLAMFile objects in proper sequence
for seq, f in sorted(index):
yield seq, clam.common.data.CLAMInputFile(Project.path(project, user), f[len(prefix):]) | python | def inputindexbytemplate(project, user, inputtemplate):
"""Retrieve sorted index for the specified input template"""
index = [] #pylint: disable=redefined-outer-name
prefix = Project.path(project, user) + 'input/'
for linkf, f in globsymlinks(prefix + '.*.INPUTTEMPLATE.' + inputtemplate.id + '.*'):
seq = int(linkf.split('.')[-1])
index.append( (seq,f) )
#yield CLAMFile objects in proper sequence
for seq, f in sorted(index):
yield seq, clam.common.data.CLAMInputFile(Project.path(project, user), f[len(prefix):]) | [
"def",
"inputindexbytemplate",
"(",
"project",
",",
"user",
",",
"inputtemplate",
")",
":",
"index",
"=",
"[",
"]",
"#pylint: disable=redefined-outer-name",
"prefix",
"=",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'input/'",
"for",
"linkf",
",",
"f",
"in",
"globsymlinks",
"(",
"prefix",
"+",
"'.*.INPUTTEMPLATE.'",
"+",
"inputtemplate",
".",
"id",
"+",
"'.*'",
")",
":",
"seq",
"=",
"int",
"(",
"linkf",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
")",
"index",
".",
"append",
"(",
"(",
"seq",
",",
"f",
")",
")",
"#yield CLAMFile objects in proper sequence",
"for",
"seq",
",",
"f",
"in",
"sorted",
"(",
"index",
")",
":",
"yield",
"seq",
",",
"clam",
".",
"common",
".",
"data",
".",
"CLAMInputFile",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
",",
"f",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
")"
] | Retrieve sorted index for the specified input template | [
"Retrieve",
"sorted",
"index",
"for",
"the",
"specified",
"input",
"template"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L869-L879 |
proycon/clam | clam/clamservice.py | Project.outputindexbytemplate | def outputindexbytemplate(project, user, outputtemplate):
"""Retrieve sorted index for the specified input template"""
index = [] #pylint: disable=redefined-outer-name
prefix = Project.path(project, user) + 'output/'
for linkf, f in globsymlinks(prefix + '.*.OUTPUTTEMPLATE.' + outputtemplate.id + '.*'):
seq = int(linkf.split('.')[-1])
index.append( (seq,f) )
#yield CLAMFile objects in proper sequence
for seq, f in sorted(index):
yield seq, clam.common.data.CLAMOutputFile(Project.path(project, user), f[len(prefix):]) | python | def outputindexbytemplate(project, user, outputtemplate):
"""Retrieve sorted index for the specified input template"""
index = [] #pylint: disable=redefined-outer-name
prefix = Project.path(project, user) + 'output/'
for linkf, f in globsymlinks(prefix + '.*.OUTPUTTEMPLATE.' + outputtemplate.id + '.*'):
seq = int(linkf.split('.')[-1])
index.append( (seq,f) )
#yield CLAMFile objects in proper sequence
for seq, f in sorted(index):
yield seq, clam.common.data.CLAMOutputFile(Project.path(project, user), f[len(prefix):]) | [
"def",
"outputindexbytemplate",
"(",
"project",
",",
"user",
",",
"outputtemplate",
")",
":",
"index",
"=",
"[",
"]",
"#pylint: disable=redefined-outer-name",
"prefix",
"=",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'output/'",
"for",
"linkf",
",",
"f",
"in",
"globsymlinks",
"(",
"prefix",
"+",
"'.*.OUTPUTTEMPLATE.'",
"+",
"outputtemplate",
".",
"id",
"+",
"'.*'",
")",
":",
"seq",
"=",
"int",
"(",
"linkf",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
")",
"index",
".",
"append",
"(",
"(",
"seq",
",",
"f",
")",
")",
"#yield CLAMFile objects in proper sequence",
"for",
"seq",
",",
"f",
"in",
"sorted",
"(",
"index",
")",
":",
"yield",
"seq",
",",
"clam",
".",
"common",
".",
"data",
".",
"CLAMOutputFile",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
",",
"f",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
")"
] | Retrieve sorted index for the specified input template | [
"Retrieve",
"sorted",
"index",
"for",
"the",
"specified",
"input",
"template"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L883-L893 |
proycon/clam | clam/clamservice.py | Project.get | def get(project, credentials=None):
"""Main Get method: Get project state, parameters, outputindex"""
user, oauth_access_token = parsecredentials(credentials)
if not Project.exists(project, user):
return withheaders(flask.make_response("Project " + project + " was not found for user " + user,404) ,headers={'allow_origin': settings.ALLOW_ORIGIN})#404
else:
#if user and not Project.access(project, user) and not user in settings.ADMINS:
# return flask.make_response("Access denied to project " + project + " for user " + user, 401) #401
datafile = os.path.join(Project.path(project,credentials),'clam.xml')
statuscode, statusmsg, statuslog, completion = Project.status(project, user) #pylint: disable=unused-variable
if statuscode == clam.common.status.DONE and os.path.exists(datafile):
f = io.open(datafile,'r',encoding='utf-8')
xmldata = f.read(os.path.getsize(datafile))
f.close()
data = clam.common.data.CLAMData(xmldata, None,False, Project.path(project,credentials), loadmetadata=False)
return Project.response(user, project, settings.PARAMETERS,"",False,oauth_access_token,','.join([str(x) for x in data.program.matchedprofiles]) if data.program else "", data.program) #200
else:
#HTTP request parameters may be used to pre-set global parameters when starting a project (issue #66)
for parametergroup, parameterlist in settings.PARAMETERS: #pylint: disable=unused-variable
for parameter in parameterlist:
value = parameter.valuefrompostdata(flask.request.values)
if value is not None:
parameter.set(value)
return Project.response(user, project, settings.PARAMETERS,"",False,oauth_access_token) | python | def get(project, credentials=None):
"""Main Get method: Get project state, parameters, outputindex"""
user, oauth_access_token = parsecredentials(credentials)
if not Project.exists(project, user):
return withheaders(flask.make_response("Project " + project + " was not found for user " + user,404) ,headers={'allow_origin': settings.ALLOW_ORIGIN})#404
else:
#if user and not Project.access(project, user) and not user in settings.ADMINS:
# return flask.make_response("Access denied to project " + project + " for user " + user, 401) #401
datafile = os.path.join(Project.path(project,credentials),'clam.xml')
statuscode, statusmsg, statuslog, completion = Project.status(project, user) #pylint: disable=unused-variable
if statuscode == clam.common.status.DONE and os.path.exists(datafile):
f = io.open(datafile,'r',encoding='utf-8')
xmldata = f.read(os.path.getsize(datafile))
f.close()
data = clam.common.data.CLAMData(xmldata, None,False, Project.path(project,credentials), loadmetadata=False)
return Project.response(user, project, settings.PARAMETERS,"",False,oauth_access_token,','.join([str(x) for x in data.program.matchedprofiles]) if data.program else "", data.program) #200
else:
#HTTP request parameters may be used to pre-set global parameters when starting a project (issue #66)
for parametergroup, parameterlist in settings.PARAMETERS: #pylint: disable=unused-variable
for parameter in parameterlist:
value = parameter.valuefrompostdata(flask.request.values)
if value is not None:
parameter.set(value)
return Project.response(user, project, settings.PARAMETERS,"",False,oauth_access_token) | [
"def",
"get",
"(",
"project",
",",
"credentials",
"=",
"None",
")",
":",
"user",
",",
"oauth_access_token",
"=",
"parsecredentials",
"(",
"credentials",
")",
"if",
"not",
"Project",
".",
"exists",
"(",
"project",
",",
"user",
")",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"Project \"",
"+",
"project",
"+",
"\" was not found for user \"",
"+",
"user",
",",
"404",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"#404",
"else",
":",
"#if user and not Project.access(project, user) and not user in settings.ADMINS:",
"# return flask.make_response(\"Access denied to project \" + project + \" for user \" + user, 401) #401",
"datafile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"credentials",
")",
",",
"'clam.xml'",
")",
"statuscode",
",",
"statusmsg",
",",
"statuslog",
",",
"completion",
"=",
"Project",
".",
"status",
"(",
"project",
",",
"user",
")",
"#pylint: disable=unused-variable",
"if",
"statuscode",
"==",
"clam",
".",
"common",
".",
"status",
".",
"DONE",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"datafile",
")",
":",
"f",
"=",
"io",
".",
"open",
"(",
"datafile",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"xmldata",
"=",
"f",
".",
"read",
"(",
"os",
".",
"path",
".",
"getsize",
"(",
"datafile",
")",
")",
"f",
".",
"close",
"(",
")",
"data",
"=",
"clam",
".",
"common",
".",
"data",
".",
"CLAMData",
"(",
"xmldata",
",",
"None",
",",
"False",
",",
"Project",
".",
"path",
"(",
"project",
",",
"credentials",
")",
",",
"loadmetadata",
"=",
"False",
")",
"return",
"Project",
".",
"response",
"(",
"user",
",",
"project",
",",
"settings",
".",
"PARAMETERS",
",",
"\"\"",
",",
"False",
",",
"oauth_access_token",
",",
"','",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"data",
".",
"program",
".",
"matchedprofiles",
"]",
")",
"if",
"data",
".",
"program",
"else",
"\"\"",
",",
"data",
".",
"program",
")",
"#200",
"else",
":",
"#HTTP request parameters may be used to pre-set global parameters when starting a project (issue #66)",
"for",
"parametergroup",
",",
"parameterlist",
"in",
"settings",
".",
"PARAMETERS",
":",
"#pylint: disable=unused-variable",
"for",
"parameter",
"in",
"parameterlist",
":",
"value",
"=",
"parameter",
".",
"valuefrompostdata",
"(",
"flask",
".",
"request",
".",
"values",
")",
"if",
"value",
"is",
"not",
"None",
":",
"parameter",
".",
"set",
"(",
"value",
")",
"return",
"Project",
".",
"response",
"(",
"user",
",",
"project",
",",
"settings",
".",
"PARAMETERS",
",",
"\"\"",
",",
"False",
",",
"oauth_access_token",
")"
] | Main Get method: Get project state, parameters, outputindex | [
"Main",
"Get",
"method",
":",
"Get",
"project",
"state",
"parameters",
"outputindex"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L994-L1017 |
proycon/clam | clam/clamservice.py | Project.new | def new(project, credentials=None):
"""Create an empty project"""
user, oauth_access_token = parsecredentials(credentials)
response = Project.create(project, user)
if response is not None:
return response
msg = "Project " + project + " has been created for user " + user
if oauth_access_token:
extraloc = '?oauth_access_token=' + oauth_access_token
else:
extraloc = ''
return flask.make_response(msg, 201, {'Location': getrooturl() + '/' + project + '/' + extraloc, 'Content-Type':'text/plain','Content-Length': len(msg),'Access-Control-Allow-Origin': settings.ALLOW_ORIGIN, 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE', 'Access-Control-Allow-Headers': 'Authorization'}) | python | def new(project, credentials=None):
"""Create an empty project"""
user, oauth_access_token = parsecredentials(credentials)
response = Project.create(project, user)
if response is not None:
return response
msg = "Project " + project + " has been created for user " + user
if oauth_access_token:
extraloc = '?oauth_access_token=' + oauth_access_token
else:
extraloc = ''
return flask.make_response(msg, 201, {'Location': getrooturl() + '/' + project + '/' + extraloc, 'Content-Type':'text/plain','Content-Length': len(msg),'Access-Control-Allow-Origin': settings.ALLOW_ORIGIN, 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE', 'Access-Control-Allow-Headers': 'Authorization'}) | [
"def",
"new",
"(",
"project",
",",
"credentials",
"=",
"None",
")",
":",
"user",
",",
"oauth_access_token",
"=",
"parsecredentials",
"(",
"credentials",
")",
"response",
"=",
"Project",
".",
"create",
"(",
"project",
",",
"user",
")",
"if",
"response",
"is",
"not",
"None",
":",
"return",
"response",
"msg",
"=",
"\"Project \"",
"+",
"project",
"+",
"\" has been created for user \"",
"+",
"user",
"if",
"oauth_access_token",
":",
"extraloc",
"=",
"'?oauth_access_token='",
"+",
"oauth_access_token",
"else",
":",
"extraloc",
"=",
"''",
"return",
"flask",
".",
"make_response",
"(",
"msg",
",",
"201",
",",
"{",
"'Location'",
":",
"getrooturl",
"(",
")",
"+",
"'/'",
"+",
"project",
"+",
"'/'",
"+",
"extraloc",
",",
"'Content-Type'",
":",
"'text/plain'",
",",
"'Content-Length'",
":",
"len",
"(",
"msg",
")",
",",
"'Access-Control-Allow-Origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
",",
"'Access-Control-Allow-Methods'",
":",
"'GET, POST, PUT, DELETE'",
",",
"'Access-Control-Allow-Headers'",
":",
"'Authorization'",
"}",
")"
] | Create an empty project | [
"Create",
"an",
"empty",
"project"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L1021-L1032 |
proycon/clam | clam/clamservice.py | Project.start | def start(project, credentials=None): #pylint: disable=too-many-return-statements
"""Start execution"""
#handle shortcut
shortcutresponse = entryshortcut(credentials, True) #protected against endless recursion, will return None when no shortcut is found, True when one is found and starting should continue
if shortcutresponse is not None and shortcutresponse is not True:
return shortcutresponse
user, oauth_access_token = parsecredentials(credentials)
response = Project.create(project, user)
if response is not None:
return response
#if user and not Project.access(project, user):
# return flask.make_response("Access denied to project " + project + " for user " + user,401) #401
statuscode, _, _, _ = Project.status(project, user)
if statuscode != clam.common.status.READY:
if oauth_access_token:
return withheaders(flask.redirect(getrooturl() + '/' + project + '/?oauth_access_token=' + oauth_access_token),headers={'allow_origin': settings.ALLOW_ORIGIN})
else:
return withheaders(flask.redirect(getrooturl() + '/' + project),headers={'allow_origin': settings.ALLOW_ORIGIN})
#Generate arguments based on POSTed parameters
commandlineparams = []
postdata = flask.request.values
errors, parameters, commandlineparams = clam.common.data.processparameters(postdata, settings.PARAMETERS)
sufresources, resmsg = sufficientresources()
if not sufresources:
printlog("*** NOT ENOUGH SYSTEM RESOURCES AVAILABLE: " + resmsg + " ***")
return withheaders(flask.make_response("There are not enough system resources available to accommodate your request. " + resmsg + " .Please try again later.",503),headers={'allow_origin': settings.ALLOW_ORIGIN})
if not errors: #We don't even bother running the profiler if there are errors
matchedprofiles, program = clam.common.data.profiler(settings.PROFILES, Project.path(project, user), parameters, settings.SYSTEM_ID, settings.SYSTEM_NAME, getrooturl(), printdebug)
#converted matched profiles to a list of indices
matchedprofiles_byindex = []
for i, profile in enumerate(settings.PROFILES):
if profile in matchedprofiles:
matchedprofiles_byindex.append(i)
if errors:
#There are parameter errors, return 403 response with errors marked
printlog("There are parameter errors, not starting.")
return Project.response(user, project, parameters,"",False,oauth_access_token, http_code=403)
elif not matchedprofiles:
printlog("No profiles matching, not starting.")
return Project.response(user, project, parameters, "No profiles matching input and parameters, unable to start. Are you sure you added all necessary input files and set all necessary parameters?", False, oauth_access_token,http_code=403)
else:
#everything good, write clam.xml output file and start
with io.open(Project.path(project, user) + "clam.xml",'wb') as f:
f.write(Project.response(user, project, parameters, "",True, oauth_access_token, ",".join([str(x) for x in matchedprofiles_byindex]), program).data)
#Start project with specified parameters
cmd = settings.COMMAND
cmd = cmd.replace('$PARAMETERS', " ".join(commandlineparams)) #commandlineparams is shell-safe
#if 'usecorpus' in postdata and postdata['usecorpus']:
# corpus = postdata['usecorpus'].replace('..','') #security
# #use a preinstalled corpus:
# if os.path.exists(settings.ROOT + "corpora/" + corpus):
# cmd = cmd.replace('$INPUTDIRECTORY', settings.ROOT + "corpora/" + corpus + "/")
# else:
# raise web.webapi.NotFound("Corpus " + corpus + " not found")
#else:
cmd = cmd.replace('$INPUTDIRECTORY', Project.path(project, user) + 'input/')
cmd = cmd.replace('$OUTPUTDIRECTORY',Project.path(project, user) + 'output/')
cmd = cmd.replace('$TMPDIRECTORY',Project.path(project, user) + 'tmp/')
cmd = cmd.replace('$STATUSFILE',Project.path(project, user) + '.status')
cmd = cmd.replace('$DATAFILE',Project.path(project, user) + 'clam.xml')
cmd = cmd.replace('$USERNAME',user if user else "anonymous")
cmd = cmd.replace('$PROJECT',project) #alphanumberic only, shell-safe
cmd = cmd.replace('$OAUTH_ACCESS_TOKEN',oauth_access_token)
cmd = clam.common.data.escapeshelloperators(cmd)
#everything should be shell-safe now
cmd += " 2> " + Project.path(project, user) + "output/error.log" #add error output
pythonpath = ''
try:
pythonpath = ':'.join(settings.DISPATCHER_PYTHONPATH)
except AttributeError:
pass
if pythonpath:
pythonpath = os.path.dirname(settings.__file__) + ':' + pythonpath
else:
pythonpath = os.path.dirname(settings.__file__)
#if settings.DISPATCHER == 'clamdispatcher' and os.path.exists(settings.CLAMDIR + '/' + settings.DISPATCHER + '.py') and stat.S_IXUSR & os.stat(settings.CLAMDIR + '/' + settings.DISPATCHER+'.py')[stat.ST_MODE]:
# #backward compatibility for old configurations without setuptools
# cmd = settings.CLAMDIR + '/' + settings.DISPATCHER + '.py'
#else:
cmd = settings.DISPATCHER + ' ' + pythonpath + ' ' + settingsmodule + ' ' + Project.path(project, user) + ' ' + cmd
if settings.REMOTEHOST:
if settings.REMOTEUSER:
cmd = "ssh -o NumberOfPasswordPrompts=0 " + settings.REMOTEUSER + "@" + settings.REMOTEHOST + " " + cmd
else:
cmd = "ssh -o NumberOfPasswordPrompts=0 " + settings.REMOTEHOST + " " + cmd
printlog("Starting dispatcher " + settings.DISPATCHER + " with " + settings.COMMAND + ": " + repr(cmd) + " ..." )
#process = subprocess.Popen(cmd,cwd=Project.path(project), shell=True)
process = subprocess.Popen(cmd,cwd=settings.CLAMDIR, shell=True)
if process:
pid = process.pid
printlog("Started dispatcher with pid " + str(pid) )
with open(Project.path(project, user) + '.pid','w') as f: #will be handled by dispatcher!
f.write(str(pid))
if shortcutresponse is True:
#redirect to project page to lose parameters in URL
if oauth_access_token:
return withheaders(flask.redirect(getrooturl() + '/' + project + '/?oauth_access_token=' + oauth_access_token),headers={'allow_origin': settings.ALLOW_ORIGIN})
else:
return withheaders(flask.redirect(getrooturl() + '/' + project),headers={'allow_origin': settings.ALLOW_ORIGIN})
else:
#normal response (202)
return Project.response(user, project, parameters,"",False,oauth_access_token,",".join([str(x) for x in matchedprofiles_byindex]), program,http_code=202) #returns 202 - Accepted
else:
return withheaders(flask.make_response("Unable to launch process",500),headers={'allow_origin': settings.ALLOW_ORIGIN}) | python | def start(project, credentials=None): #pylint: disable=too-many-return-statements
"""Start execution"""
#handle shortcut
shortcutresponse = entryshortcut(credentials, True) #protected against endless recursion, will return None when no shortcut is found, True when one is found and starting should continue
if shortcutresponse is not None and shortcutresponse is not True:
return shortcutresponse
user, oauth_access_token = parsecredentials(credentials)
response = Project.create(project, user)
if response is not None:
return response
#if user and not Project.access(project, user):
# return flask.make_response("Access denied to project " + project + " for user " + user,401) #401
statuscode, _, _, _ = Project.status(project, user)
if statuscode != clam.common.status.READY:
if oauth_access_token:
return withheaders(flask.redirect(getrooturl() + '/' + project + '/?oauth_access_token=' + oauth_access_token),headers={'allow_origin': settings.ALLOW_ORIGIN})
else:
return withheaders(flask.redirect(getrooturl() + '/' + project),headers={'allow_origin': settings.ALLOW_ORIGIN})
#Generate arguments based on POSTed parameters
commandlineparams = []
postdata = flask.request.values
errors, parameters, commandlineparams = clam.common.data.processparameters(postdata, settings.PARAMETERS)
sufresources, resmsg = sufficientresources()
if not sufresources:
printlog("*** NOT ENOUGH SYSTEM RESOURCES AVAILABLE: " + resmsg + " ***")
return withheaders(flask.make_response("There are not enough system resources available to accommodate your request. " + resmsg + " .Please try again later.",503),headers={'allow_origin': settings.ALLOW_ORIGIN})
if not errors: #We don't even bother running the profiler if there are errors
matchedprofiles, program = clam.common.data.profiler(settings.PROFILES, Project.path(project, user), parameters, settings.SYSTEM_ID, settings.SYSTEM_NAME, getrooturl(), printdebug)
#converted matched profiles to a list of indices
matchedprofiles_byindex = []
for i, profile in enumerate(settings.PROFILES):
if profile in matchedprofiles:
matchedprofiles_byindex.append(i)
if errors:
#There are parameter errors, return 403 response with errors marked
printlog("There are parameter errors, not starting.")
return Project.response(user, project, parameters,"",False,oauth_access_token, http_code=403)
elif not matchedprofiles:
printlog("No profiles matching, not starting.")
return Project.response(user, project, parameters, "No profiles matching input and parameters, unable to start. Are you sure you added all necessary input files and set all necessary parameters?", False, oauth_access_token,http_code=403)
else:
#everything good, write clam.xml output file and start
with io.open(Project.path(project, user) + "clam.xml",'wb') as f:
f.write(Project.response(user, project, parameters, "",True, oauth_access_token, ",".join([str(x) for x in matchedprofiles_byindex]), program).data)
#Start project with specified parameters
cmd = settings.COMMAND
cmd = cmd.replace('$PARAMETERS', " ".join(commandlineparams)) #commandlineparams is shell-safe
#if 'usecorpus' in postdata and postdata['usecorpus']:
# corpus = postdata['usecorpus'].replace('..','') #security
# #use a preinstalled corpus:
# if os.path.exists(settings.ROOT + "corpora/" + corpus):
# cmd = cmd.replace('$INPUTDIRECTORY', settings.ROOT + "corpora/" + corpus + "/")
# else:
# raise web.webapi.NotFound("Corpus " + corpus + " not found")
#else:
cmd = cmd.replace('$INPUTDIRECTORY', Project.path(project, user) + 'input/')
cmd = cmd.replace('$OUTPUTDIRECTORY',Project.path(project, user) + 'output/')
cmd = cmd.replace('$TMPDIRECTORY',Project.path(project, user) + 'tmp/')
cmd = cmd.replace('$STATUSFILE',Project.path(project, user) + '.status')
cmd = cmd.replace('$DATAFILE',Project.path(project, user) + 'clam.xml')
cmd = cmd.replace('$USERNAME',user if user else "anonymous")
cmd = cmd.replace('$PROJECT',project) #alphanumberic only, shell-safe
cmd = cmd.replace('$OAUTH_ACCESS_TOKEN',oauth_access_token)
cmd = clam.common.data.escapeshelloperators(cmd)
#everything should be shell-safe now
cmd += " 2> " + Project.path(project, user) + "output/error.log" #add error output
pythonpath = ''
try:
pythonpath = ':'.join(settings.DISPATCHER_PYTHONPATH)
except AttributeError:
pass
if pythonpath:
pythonpath = os.path.dirname(settings.__file__) + ':' + pythonpath
else:
pythonpath = os.path.dirname(settings.__file__)
#if settings.DISPATCHER == 'clamdispatcher' and os.path.exists(settings.CLAMDIR + '/' + settings.DISPATCHER + '.py') and stat.S_IXUSR & os.stat(settings.CLAMDIR + '/' + settings.DISPATCHER+'.py')[stat.ST_MODE]:
# #backward compatibility for old configurations without setuptools
# cmd = settings.CLAMDIR + '/' + settings.DISPATCHER + '.py'
#else:
cmd = settings.DISPATCHER + ' ' + pythonpath + ' ' + settingsmodule + ' ' + Project.path(project, user) + ' ' + cmd
if settings.REMOTEHOST:
if settings.REMOTEUSER:
cmd = "ssh -o NumberOfPasswordPrompts=0 " + settings.REMOTEUSER + "@" + settings.REMOTEHOST + " " + cmd
else:
cmd = "ssh -o NumberOfPasswordPrompts=0 " + settings.REMOTEHOST + " " + cmd
printlog("Starting dispatcher " + settings.DISPATCHER + " with " + settings.COMMAND + ": " + repr(cmd) + " ..." )
#process = subprocess.Popen(cmd,cwd=Project.path(project), shell=True)
process = subprocess.Popen(cmd,cwd=settings.CLAMDIR, shell=True)
if process:
pid = process.pid
printlog("Started dispatcher with pid " + str(pid) )
with open(Project.path(project, user) + '.pid','w') as f: #will be handled by dispatcher!
f.write(str(pid))
if shortcutresponse is True:
#redirect to project page to lose parameters in URL
if oauth_access_token:
return withheaders(flask.redirect(getrooturl() + '/' + project + '/?oauth_access_token=' + oauth_access_token),headers={'allow_origin': settings.ALLOW_ORIGIN})
else:
return withheaders(flask.redirect(getrooturl() + '/' + project),headers={'allow_origin': settings.ALLOW_ORIGIN})
else:
#normal response (202)
return Project.response(user, project, parameters,"",False,oauth_access_token,",".join([str(x) for x in matchedprofiles_byindex]), program,http_code=202) #returns 202 - Accepted
else:
return withheaders(flask.make_response("Unable to launch process",500),headers={'allow_origin': settings.ALLOW_ORIGIN}) | [
"def",
"start",
"(",
"project",
",",
"credentials",
"=",
"None",
")",
":",
"#pylint: disable=too-many-return-statements",
"#handle shortcut",
"shortcutresponse",
"=",
"entryshortcut",
"(",
"credentials",
",",
"True",
")",
"#protected against endless recursion, will return None when no shortcut is found, True when one is found and starting should continue",
"if",
"shortcutresponse",
"is",
"not",
"None",
"and",
"shortcutresponse",
"is",
"not",
"True",
":",
"return",
"shortcutresponse",
"user",
",",
"oauth_access_token",
"=",
"parsecredentials",
"(",
"credentials",
")",
"response",
"=",
"Project",
".",
"create",
"(",
"project",
",",
"user",
")",
"if",
"response",
"is",
"not",
"None",
":",
"return",
"response",
"#if user and not Project.access(project, user):",
"# return flask.make_response(\"Access denied to project \" + project + \" for user \" + user,401) #401",
"statuscode",
",",
"_",
",",
"_",
",",
"_",
"=",
"Project",
".",
"status",
"(",
"project",
",",
"user",
")",
"if",
"statuscode",
"!=",
"clam",
".",
"common",
".",
"status",
".",
"READY",
":",
"if",
"oauth_access_token",
":",
"return",
"withheaders",
"(",
"flask",
".",
"redirect",
"(",
"getrooturl",
"(",
")",
"+",
"'/'",
"+",
"project",
"+",
"'/?oauth_access_token='",
"+",
"oauth_access_token",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"else",
":",
"return",
"withheaders",
"(",
"flask",
".",
"redirect",
"(",
"getrooturl",
"(",
")",
"+",
"'/'",
"+",
"project",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"#Generate arguments based on POSTed parameters",
"commandlineparams",
"=",
"[",
"]",
"postdata",
"=",
"flask",
".",
"request",
".",
"values",
"errors",
",",
"parameters",
",",
"commandlineparams",
"=",
"clam",
".",
"common",
".",
"data",
".",
"processparameters",
"(",
"postdata",
",",
"settings",
".",
"PARAMETERS",
")",
"sufresources",
",",
"resmsg",
"=",
"sufficientresources",
"(",
")",
"if",
"not",
"sufresources",
":",
"printlog",
"(",
"\"*** NOT ENOUGH SYSTEM RESOURCES AVAILABLE: \"",
"+",
"resmsg",
"+",
"\" ***\"",
")",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"There are not enough system resources available to accommodate your request. \"",
"+",
"resmsg",
"+",
"\" .Please try again later.\"",
",",
"503",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"if",
"not",
"errors",
":",
"#We don't even bother running the profiler if there are errors",
"matchedprofiles",
",",
"program",
"=",
"clam",
".",
"common",
".",
"data",
".",
"profiler",
"(",
"settings",
".",
"PROFILES",
",",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
",",
"parameters",
",",
"settings",
".",
"SYSTEM_ID",
",",
"settings",
".",
"SYSTEM_NAME",
",",
"getrooturl",
"(",
")",
",",
"printdebug",
")",
"#converted matched profiles to a list of indices",
"matchedprofiles_byindex",
"=",
"[",
"]",
"for",
"i",
",",
"profile",
"in",
"enumerate",
"(",
"settings",
".",
"PROFILES",
")",
":",
"if",
"profile",
"in",
"matchedprofiles",
":",
"matchedprofiles_byindex",
".",
"append",
"(",
"i",
")",
"if",
"errors",
":",
"#There are parameter errors, return 403 response with errors marked",
"printlog",
"(",
"\"There are parameter errors, not starting.\"",
")",
"return",
"Project",
".",
"response",
"(",
"user",
",",
"project",
",",
"parameters",
",",
"\"\"",
",",
"False",
",",
"oauth_access_token",
",",
"http_code",
"=",
"403",
")",
"elif",
"not",
"matchedprofiles",
":",
"printlog",
"(",
"\"No profiles matching, not starting.\"",
")",
"return",
"Project",
".",
"response",
"(",
"user",
",",
"project",
",",
"parameters",
",",
"\"No profiles matching input and parameters, unable to start. Are you sure you added all necessary input files and set all necessary parameters?\"",
",",
"False",
",",
"oauth_access_token",
",",
"http_code",
"=",
"403",
")",
"else",
":",
"#everything good, write clam.xml output file and start",
"with",
"io",
".",
"open",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\"clam.xml\"",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"Project",
".",
"response",
"(",
"user",
",",
"project",
",",
"parameters",
",",
"\"\"",
",",
"True",
",",
"oauth_access_token",
",",
"\",\"",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"matchedprofiles_byindex",
"]",
")",
",",
"program",
")",
".",
"data",
")",
"#Start project with specified parameters",
"cmd",
"=",
"settings",
".",
"COMMAND",
"cmd",
"=",
"cmd",
".",
"replace",
"(",
"'$PARAMETERS'",
",",
"\" \"",
".",
"join",
"(",
"commandlineparams",
")",
")",
"#commandlineparams is shell-safe",
"#if 'usecorpus' in postdata and postdata['usecorpus']:",
"# corpus = postdata['usecorpus'].replace('..','') #security",
"# #use a preinstalled corpus:",
"# if os.path.exists(settings.ROOT + \"corpora/\" + corpus):",
"# cmd = cmd.replace('$INPUTDIRECTORY', settings.ROOT + \"corpora/\" + corpus + \"/\")",
"# else:",
"# raise web.webapi.NotFound(\"Corpus \" + corpus + \" not found\")",
"#else:",
"cmd",
"=",
"cmd",
".",
"replace",
"(",
"'$INPUTDIRECTORY'",
",",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'input/'",
")",
"cmd",
"=",
"cmd",
".",
"replace",
"(",
"'$OUTPUTDIRECTORY'",
",",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'output/'",
")",
"cmd",
"=",
"cmd",
".",
"replace",
"(",
"'$TMPDIRECTORY'",
",",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'tmp/'",
")",
"cmd",
"=",
"cmd",
".",
"replace",
"(",
"'$STATUSFILE'",
",",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'.status'",
")",
"cmd",
"=",
"cmd",
".",
"replace",
"(",
"'$DATAFILE'",
",",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'clam.xml'",
")",
"cmd",
"=",
"cmd",
".",
"replace",
"(",
"'$USERNAME'",
",",
"user",
"if",
"user",
"else",
"\"anonymous\"",
")",
"cmd",
"=",
"cmd",
".",
"replace",
"(",
"'$PROJECT'",
",",
"project",
")",
"#alphanumberic only, shell-safe",
"cmd",
"=",
"cmd",
".",
"replace",
"(",
"'$OAUTH_ACCESS_TOKEN'",
",",
"oauth_access_token",
")",
"cmd",
"=",
"clam",
".",
"common",
".",
"data",
".",
"escapeshelloperators",
"(",
"cmd",
")",
"#everything should be shell-safe now",
"cmd",
"+=",
"\" 2> \"",
"+",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\"output/error.log\"",
"#add error output",
"pythonpath",
"=",
"''",
"try",
":",
"pythonpath",
"=",
"':'",
".",
"join",
"(",
"settings",
".",
"DISPATCHER_PYTHONPATH",
")",
"except",
"AttributeError",
":",
"pass",
"if",
"pythonpath",
":",
"pythonpath",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"settings",
".",
"__file__",
")",
"+",
"':'",
"+",
"pythonpath",
"else",
":",
"pythonpath",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"settings",
".",
"__file__",
")",
"#if settings.DISPATCHER == 'clamdispatcher' and os.path.exists(settings.CLAMDIR + '/' + settings.DISPATCHER + '.py') and stat.S_IXUSR & os.stat(settings.CLAMDIR + '/' + settings.DISPATCHER+'.py')[stat.ST_MODE]:",
"# #backward compatibility for old configurations without setuptools",
"# cmd = settings.CLAMDIR + '/' + settings.DISPATCHER + '.py'",
"#else:",
"cmd",
"=",
"settings",
".",
"DISPATCHER",
"+",
"' '",
"+",
"pythonpath",
"+",
"' '",
"+",
"settingsmodule",
"+",
"' '",
"+",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"' '",
"+",
"cmd",
"if",
"settings",
".",
"REMOTEHOST",
":",
"if",
"settings",
".",
"REMOTEUSER",
":",
"cmd",
"=",
"\"ssh -o NumberOfPasswordPrompts=0 \"",
"+",
"settings",
".",
"REMOTEUSER",
"+",
"\"@\"",
"+",
"settings",
".",
"REMOTEHOST",
"+",
"\" \"",
"+",
"cmd",
"else",
":",
"cmd",
"=",
"\"ssh -o NumberOfPasswordPrompts=0 \"",
"+",
"settings",
".",
"REMOTEHOST",
"+",
"\" \"",
"+",
"cmd",
"printlog",
"(",
"\"Starting dispatcher \"",
"+",
"settings",
".",
"DISPATCHER",
"+",
"\" with \"",
"+",
"settings",
".",
"COMMAND",
"+",
"\": \"",
"+",
"repr",
"(",
"cmd",
")",
"+",
"\" ...\"",
")",
"#process = subprocess.Popen(cmd,cwd=Project.path(project), shell=True)",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"cwd",
"=",
"settings",
".",
"CLAMDIR",
",",
"shell",
"=",
"True",
")",
"if",
"process",
":",
"pid",
"=",
"process",
".",
"pid",
"printlog",
"(",
"\"Started dispatcher with pid \"",
"+",
"str",
"(",
"pid",
")",
")",
"with",
"open",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'.pid'",
",",
"'w'",
")",
"as",
"f",
":",
"#will be handled by dispatcher!",
"f",
".",
"write",
"(",
"str",
"(",
"pid",
")",
")",
"if",
"shortcutresponse",
"is",
"True",
":",
"#redirect to project page to lose parameters in URL",
"if",
"oauth_access_token",
":",
"return",
"withheaders",
"(",
"flask",
".",
"redirect",
"(",
"getrooturl",
"(",
")",
"+",
"'/'",
"+",
"project",
"+",
"'/?oauth_access_token='",
"+",
"oauth_access_token",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"else",
":",
"return",
"withheaders",
"(",
"flask",
".",
"redirect",
"(",
"getrooturl",
"(",
")",
"+",
"'/'",
"+",
"project",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"else",
":",
"#normal response (202)",
"return",
"Project",
".",
"response",
"(",
"user",
",",
"project",
",",
"parameters",
",",
"\"\"",
",",
"False",
",",
"oauth_access_token",
",",
"\",\"",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"matchedprofiles_byindex",
"]",
")",
",",
"program",
",",
"http_code",
"=",
"202",
")",
"#returns 202 - Accepted",
"else",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"Unable to launch process\"",
",",
"500",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")"
] | Start execution | [
"Start",
"execution"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L1035-L1150 |
proycon/clam | clam/clamservice.py | Project.deleteoutputfile | def deleteoutputfile(project, filename, credentials=None):
"""Delete an output file"""
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
if filename: filename = filename.replace("..","") #Simple security
if not filename or len(filename) == 0:
#Deleting all output files and resetting
Project.reset(project, user)
msg = "Deleted"
return withheaders(flask.make_response(msg), 'text/plain',{'Content-Length':len(msg), 'allow_origin': settings.ALLOW_ORIGIN}) #200
elif os.path.isdir(Project.path(project, user) + filename):
#Deleting specified directory
shutil.rmtree(Project.path(project, user) + filename)
msg = "Deleted"
return withheaders(flask.make_response(msg), 'text/plain',{'Content-Length':len(msg), 'allow_origin': settings.ALLOW_ORIGIN}) #200
else:
try:
file = clam.common.data.CLAMOutputFile(Project.path(project, user), filename)
except:
raise flask.abort(404)
success = file.delete()
if not success:
raise flask.abort(404)
else:
msg = "Deleted"
return withheaders(flask.make_response(msg), 'text/plain',{'Content-Length':len(msg), 'allow_origin': settings.ALLOW_ORIGIN}) | python | def deleteoutputfile(project, filename, credentials=None):
"""Delete an output file"""
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
if filename: filename = filename.replace("..","") #Simple security
if not filename or len(filename) == 0:
#Deleting all output files and resetting
Project.reset(project, user)
msg = "Deleted"
return withheaders(flask.make_response(msg), 'text/plain',{'Content-Length':len(msg), 'allow_origin': settings.ALLOW_ORIGIN}) #200
elif os.path.isdir(Project.path(project, user) + filename):
#Deleting specified directory
shutil.rmtree(Project.path(project, user) + filename)
msg = "Deleted"
return withheaders(flask.make_response(msg), 'text/plain',{'Content-Length':len(msg), 'allow_origin': settings.ALLOW_ORIGIN}) #200
else:
try:
file = clam.common.data.CLAMOutputFile(Project.path(project, user), filename)
except:
raise flask.abort(404)
success = file.delete()
if not success:
raise flask.abort(404)
else:
msg = "Deleted"
return withheaders(flask.make_response(msg), 'text/plain',{'Content-Length':len(msg), 'allow_origin': settings.ALLOW_ORIGIN}) | [
"def",
"deleteoutputfile",
"(",
"project",
",",
"filename",
",",
"credentials",
"=",
"None",
")",
":",
"user",
",",
"oauth_access_token",
"=",
"parsecredentials",
"(",
"credentials",
")",
"#pylint: disable=unused-variable",
"if",
"filename",
":",
"filename",
"=",
"filename",
".",
"replace",
"(",
"\"..\"",
",",
"\"\"",
")",
"#Simple security",
"if",
"not",
"filename",
"or",
"len",
"(",
"filename",
")",
"==",
"0",
":",
"#Deleting all output files and resetting",
"Project",
".",
"reset",
"(",
"project",
",",
"user",
")",
"msg",
"=",
"\"Deleted\"",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"msg",
")",
",",
"'text/plain'",
",",
"{",
"'Content-Length'",
":",
"len",
"(",
"msg",
")",
",",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"#200",
"elif",
"os",
".",
"path",
".",
"isdir",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"filename",
")",
":",
"#Deleting specified directory",
"shutil",
".",
"rmtree",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"filename",
")",
"msg",
"=",
"\"Deleted\"",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"msg",
")",
",",
"'text/plain'",
",",
"{",
"'Content-Length'",
":",
"len",
"(",
"msg",
")",
",",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"#200",
"else",
":",
"try",
":",
"file",
"=",
"clam",
".",
"common",
".",
"data",
".",
"CLAMOutputFile",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
",",
"filename",
")",
"except",
":",
"raise",
"flask",
".",
"abort",
"(",
"404",
")",
"success",
"=",
"file",
".",
"delete",
"(",
")",
"if",
"not",
"success",
":",
"raise",
"flask",
".",
"abort",
"(",
"404",
")",
"else",
":",
"msg",
"=",
"\"Deleted\"",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"msg",
")",
",",
"'text/plain'",
",",
"{",
"'Content-Length'",
":",
"len",
"(",
"msg",
")",
",",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")"
] | Delete an output file | [
"Delete",
"an",
"output",
"file"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L1280-L1307 |
proycon/clam | clam/clamservice.py | Project.reset | def reset(project, user):
"""Reset system, delete all output files and prepare for a new run"""
d = Project.path(project, user) + "output"
if os.path.isdir(d):
shutil.rmtree(d)
os.makedirs(d)
else:
raise flask.abort(404)
if os.path.exists(Project.path(project, user) + ".done"):
os.unlink(Project.path(project, user) + ".done")
if os.path.exists(Project.path(project, user) + ".status"):
os.unlink(Project.path(project, user) + ".status") | python | def reset(project, user):
"""Reset system, delete all output files and prepare for a new run"""
d = Project.path(project, user) + "output"
if os.path.isdir(d):
shutil.rmtree(d)
os.makedirs(d)
else:
raise flask.abort(404)
if os.path.exists(Project.path(project, user) + ".done"):
os.unlink(Project.path(project, user) + ".done")
if os.path.exists(Project.path(project, user) + ".status"):
os.unlink(Project.path(project, user) + ".status") | [
"def",
"reset",
"(",
"project",
",",
"user",
")",
":",
"d",
"=",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\"output\"",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"d",
")",
":",
"shutil",
".",
"rmtree",
"(",
"d",
")",
"os",
".",
"makedirs",
"(",
"d",
")",
"else",
":",
"raise",
"flask",
".",
"abort",
"(",
"404",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\".done\"",
")",
":",
"os",
".",
"unlink",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\".done\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\".status\"",
")",
":",
"os",
".",
"unlink",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\".status\"",
")"
] | Reset system, delete all output files and prepare for a new run | [
"Reset",
"system",
"delete",
"all",
"output",
"files",
"and",
"prepare",
"for",
"a",
"new",
"run"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L1311-L1322 |
proycon/clam | clam/clamservice.py | Project.getarchive | def getarchive(project, user, format=None):
"""Generates and returns a download package (or 403 if one is already in the process of being prepared)"""
if os.path.isfile(Project.path(project, user) + '.download'):
#make sure we don't start two compression processes at the same time
return withheaders(flask.make_response('Another compression is already running',403),headers={'allow_origin': settings.ALLOW_ORIGIN})
else:
if not format:
data = flask.request.values
if 'format' in data:
format = data['format']
else:
format = 'zip' #default
#validation, security
contentencoding = None
if format == 'zip':
contenttype = 'application/zip'
command = "/usr/bin/zip -r" #TODO: do not hard-code path!
if os.path.isfile(Project.path(project, user) + "output/" + project + ".tar.gz"):
os.unlink(Project.path(project, user) + "output/" + project + ".tar.gz")
if os.path.isfile(Project.path(project, user) + "output/" + project + ".tar.bz2"):
os.unlink(Project.path(project, user) + "output/" + project + ".tar.bz2")
elif format == 'tar.gz':
contenttype = 'application/x-tar'
contentencoding = 'gzip'
command = "/bin/tar -czf"
if os.path.isfile(Project.path(project, user) + "output/" + project + ".zip"):
os.unlink(Project.path(project, user) + "output/" + project + ".zip")
if os.path.isfile(Project.path(project, user) + "output/" + project + ".tar.bz2"):
os.unlink(Project.path(project, user) + "output/" + project + ".tar.bz2")
elif format == 'tar.bz2':
contenttype = 'application/x-bzip2'
command = "/bin/tar -cjf"
if os.path.isfile(Project.path(project, user) + "output/" + project + ".tar.gz"):
os.unlink(Project.path(project, user) + "output/" + project + ".tar.gz")
if os.path.isfile(Project.path(project, user) + "output/" + project + ".zip"):
os.unlink(Project.path(project, user) + "output/" + project + ".zip")
else:
return withheaders(flask.make_response('Invalid archive format',403) ,headers={'allow_origin': settings.ALLOW_ORIGIN})#TODO: message won't show
path = Project.path(project, user) + "output/" + project + "." + format
if not os.path.isfile(path):
printlog("Building download archive in " + format + " format")
cmd = command + ' ' + project + '.' + format + ' *'
printdebug(cmd)
printdebug(Project.path(project, user)+'output/')
process = subprocess.Popen(cmd, cwd=Project.path(project, user)+'output/', shell=True)
if not process:
return withheaders(flask.make_response("Unable to make download package",500),headers={'allow_origin': settings.ALLOW_ORIGIN})
else:
pid = process.pid
f = open(Project.path(project, user) + '.download','w')
f.write(str(pid))
f.close()
os.waitpid(pid, 0) #wait for process to finish
os.unlink(Project.path(project, user) + '.download')
extraheaders = {'allow_origin': settings.ALLOW_ORIGIN }
if contentencoding:
extraheaders['Content-Encoding'] = contentencoding
return withheaders(flask.Response( getbinarydata(path) ), contenttype, extraheaders ) | python | def getarchive(project, user, format=None):
"""Generates and returns a download package (or 403 if one is already in the process of being prepared)"""
if os.path.isfile(Project.path(project, user) + '.download'):
#make sure we don't start two compression processes at the same time
return withheaders(flask.make_response('Another compression is already running',403),headers={'allow_origin': settings.ALLOW_ORIGIN})
else:
if not format:
data = flask.request.values
if 'format' in data:
format = data['format']
else:
format = 'zip' #default
#validation, security
contentencoding = None
if format == 'zip':
contenttype = 'application/zip'
command = "/usr/bin/zip -r" #TODO: do not hard-code path!
if os.path.isfile(Project.path(project, user) + "output/" + project + ".tar.gz"):
os.unlink(Project.path(project, user) + "output/" + project + ".tar.gz")
if os.path.isfile(Project.path(project, user) + "output/" + project + ".tar.bz2"):
os.unlink(Project.path(project, user) + "output/" + project + ".tar.bz2")
elif format == 'tar.gz':
contenttype = 'application/x-tar'
contentencoding = 'gzip'
command = "/bin/tar -czf"
if os.path.isfile(Project.path(project, user) + "output/" + project + ".zip"):
os.unlink(Project.path(project, user) + "output/" + project + ".zip")
if os.path.isfile(Project.path(project, user) + "output/" + project + ".tar.bz2"):
os.unlink(Project.path(project, user) + "output/" + project + ".tar.bz2")
elif format == 'tar.bz2':
contenttype = 'application/x-bzip2'
command = "/bin/tar -cjf"
if os.path.isfile(Project.path(project, user) + "output/" + project + ".tar.gz"):
os.unlink(Project.path(project, user) + "output/" + project + ".tar.gz")
if os.path.isfile(Project.path(project, user) + "output/" + project + ".zip"):
os.unlink(Project.path(project, user) + "output/" + project + ".zip")
else:
return withheaders(flask.make_response('Invalid archive format',403) ,headers={'allow_origin': settings.ALLOW_ORIGIN})#TODO: message won't show
path = Project.path(project, user) + "output/" + project + "." + format
if not os.path.isfile(path):
printlog("Building download archive in " + format + " format")
cmd = command + ' ' + project + '.' + format + ' *'
printdebug(cmd)
printdebug(Project.path(project, user)+'output/')
process = subprocess.Popen(cmd, cwd=Project.path(project, user)+'output/', shell=True)
if not process:
return withheaders(flask.make_response("Unable to make download package",500),headers={'allow_origin': settings.ALLOW_ORIGIN})
else:
pid = process.pid
f = open(Project.path(project, user) + '.download','w')
f.write(str(pid))
f.close()
os.waitpid(pid, 0) #wait for process to finish
os.unlink(Project.path(project, user) + '.download')
extraheaders = {'allow_origin': settings.ALLOW_ORIGIN }
if contentencoding:
extraheaders['Content-Encoding'] = contentencoding
return withheaders(flask.Response( getbinarydata(path) ), contenttype, extraheaders ) | [
"def",
"getarchive",
"(",
"project",
",",
"user",
",",
"format",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'.download'",
")",
":",
"#make sure we don't start two compression processes at the same time",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"'Another compression is already running'",
",",
"403",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"else",
":",
"if",
"not",
"format",
":",
"data",
"=",
"flask",
".",
"request",
".",
"values",
"if",
"'format'",
"in",
"data",
":",
"format",
"=",
"data",
"[",
"'format'",
"]",
"else",
":",
"format",
"=",
"'zip'",
"#default",
"#validation, security",
"contentencoding",
"=",
"None",
"if",
"format",
"==",
"'zip'",
":",
"contenttype",
"=",
"'application/zip'",
"command",
"=",
"\"/usr/bin/zip -r\"",
"#TODO: do not hard-code path!",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\"output/\"",
"+",
"project",
"+",
"\".tar.gz\"",
")",
":",
"os",
".",
"unlink",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\"output/\"",
"+",
"project",
"+",
"\".tar.gz\"",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\"output/\"",
"+",
"project",
"+",
"\".tar.bz2\"",
")",
":",
"os",
".",
"unlink",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\"output/\"",
"+",
"project",
"+",
"\".tar.bz2\"",
")",
"elif",
"format",
"==",
"'tar.gz'",
":",
"contenttype",
"=",
"'application/x-tar'",
"contentencoding",
"=",
"'gzip'",
"command",
"=",
"\"/bin/tar -czf\"",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\"output/\"",
"+",
"project",
"+",
"\".zip\"",
")",
":",
"os",
".",
"unlink",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\"output/\"",
"+",
"project",
"+",
"\".zip\"",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\"output/\"",
"+",
"project",
"+",
"\".tar.bz2\"",
")",
":",
"os",
".",
"unlink",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\"output/\"",
"+",
"project",
"+",
"\".tar.bz2\"",
")",
"elif",
"format",
"==",
"'tar.bz2'",
":",
"contenttype",
"=",
"'application/x-bzip2'",
"command",
"=",
"\"/bin/tar -cjf\"",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\"output/\"",
"+",
"project",
"+",
"\".tar.gz\"",
")",
":",
"os",
".",
"unlink",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\"output/\"",
"+",
"project",
"+",
"\".tar.gz\"",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\"output/\"",
"+",
"project",
"+",
"\".zip\"",
")",
":",
"os",
".",
"unlink",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\"output/\"",
"+",
"project",
"+",
"\".zip\"",
")",
"else",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"'Invalid archive format'",
",",
"403",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"#TODO: message won't show",
"path",
"=",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"\"output/\"",
"+",
"project",
"+",
"\".\"",
"+",
"format",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"printlog",
"(",
"\"Building download archive in \"",
"+",
"format",
"+",
"\" format\"",
")",
"cmd",
"=",
"command",
"+",
"' '",
"+",
"project",
"+",
"'.'",
"+",
"format",
"+",
"' *'",
"printdebug",
"(",
"cmd",
")",
"printdebug",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'output/'",
")",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"cwd",
"=",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'output/'",
",",
"shell",
"=",
"True",
")",
"if",
"not",
"process",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"Unable to make download package\"",
",",
"500",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"else",
":",
"pid",
"=",
"process",
".",
"pid",
"f",
"=",
"open",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'.download'",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"str",
"(",
"pid",
")",
")",
"f",
".",
"close",
"(",
")",
"os",
".",
"waitpid",
"(",
"pid",
",",
"0",
")",
"#wait for process to finish",
"os",
".",
"unlink",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'.download'",
")",
"extraheaders",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
"if",
"contentencoding",
":",
"extraheaders",
"[",
"'Content-Encoding'",
"]",
"=",
"contentencoding",
"return",
"withheaders",
"(",
"flask",
".",
"Response",
"(",
"getbinarydata",
"(",
"path",
")",
")",
",",
"contenttype",
",",
"extraheaders",
")"
] | Generates and returns a download package (or 403 if one is already in the process of being prepared) | [
"Generates",
"and",
"returns",
"a",
"download",
"package",
"(",
"or",
"403",
"if",
"one",
"is",
"already",
"in",
"the",
"process",
"of",
"being",
"prepared",
")"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L1325-L1386 |
proycon/clam | clam/clamservice.py | Project.deleteinputfile | def deleteinputfile(project, filename, credentials=None):
"""Delete an input file"""
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
filename = filename.replace("..","") #Simple security
if len(filename) == 0:
#Deleting all input files
shutil.rmtree(Project.path(project, user) + 'input')
os.makedirs(Project.path(project, user) + 'input') #re-add new input directory
return "Deleted" #200
elif os.path.isdir(Project.path(project, user) + filename):
#Deleting specified directory
shutil.rmtree(Project.path(project, user) + filename)
return "Deleted" #200
else:
try:
file = clam.common.data.CLAMInputFile(Project.path(project, user), filename)
except:
raise flask.abort(404)
success = file.delete()
if not success:
raise flask.abort(404)
else:
msg = "Deleted"
return withheaders(flask.make_response(msg),'text/plain', {'Content-Length': len(msg), 'allow_origin': settings.ALLOW_ORIGIN}) | python | def deleteinputfile(project, filename, credentials=None):
"""Delete an input file"""
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
filename = filename.replace("..","") #Simple security
if len(filename) == 0:
#Deleting all input files
shutil.rmtree(Project.path(project, user) + 'input')
os.makedirs(Project.path(project, user) + 'input') #re-add new input directory
return "Deleted" #200
elif os.path.isdir(Project.path(project, user) + filename):
#Deleting specified directory
shutil.rmtree(Project.path(project, user) + filename)
return "Deleted" #200
else:
try:
file = clam.common.data.CLAMInputFile(Project.path(project, user), filename)
except:
raise flask.abort(404)
success = file.delete()
if not success:
raise flask.abort(404)
else:
msg = "Deleted"
return withheaders(flask.make_response(msg),'text/plain', {'Content-Length': len(msg), 'allow_origin': settings.ALLOW_ORIGIN}) | [
"def",
"deleteinputfile",
"(",
"project",
",",
"filename",
",",
"credentials",
"=",
"None",
")",
":",
"user",
",",
"oauth_access_token",
"=",
"parsecredentials",
"(",
"credentials",
")",
"#pylint: disable=unused-variable",
"filename",
"=",
"filename",
".",
"replace",
"(",
"\"..\"",
",",
"\"\"",
")",
"#Simple security",
"if",
"len",
"(",
"filename",
")",
"==",
"0",
":",
"#Deleting all input files",
"shutil",
".",
"rmtree",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'input'",
")",
"os",
".",
"makedirs",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"'input'",
")",
"#re-add new input directory",
"return",
"\"Deleted\"",
"#200",
"elif",
"os",
".",
"path",
".",
"isdir",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"filename",
")",
":",
"#Deleting specified directory",
"shutil",
".",
"rmtree",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
"+",
"filename",
")",
"return",
"\"Deleted\"",
"#200",
"else",
":",
"try",
":",
"file",
"=",
"clam",
".",
"common",
".",
"data",
".",
"CLAMInputFile",
"(",
"Project",
".",
"path",
"(",
"project",
",",
"user",
")",
",",
"filename",
")",
"except",
":",
"raise",
"flask",
".",
"abort",
"(",
"404",
")",
"success",
"=",
"file",
".",
"delete",
"(",
")",
"if",
"not",
"success",
":",
"raise",
"flask",
".",
"abort",
"(",
"404",
")",
"else",
":",
"msg",
"=",
"\"Deleted\"",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"msg",
")",
",",
"'text/plain'",
",",
"{",
"'Content-Length'",
":",
"len",
"(",
"msg",
")",
",",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")"
] | Delete an input file | [
"Delete",
"an",
"input",
"file"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L1447-L1473 |
proycon/clam | clam/clamservice.py | Project.addinputfile | def addinputfile(project, filename, credentials=None): #pylint: disable=too-many-return-statements
"""Add a new input file, this invokes the actual uploader"""
printdebug('Addinputfile: Initialising' )
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
response = Project.create(project, user)
if response is not None:
return response
postdata = flask.request.values
if filename == '': #pylint: disable=too-many-nested-blocks
#Handle inputsource
printdebug('Addinputfile: checking for input source' )
if 'inputsource' in postdata and postdata['inputsource']:
inputsource = None
inputtemplate = None
for profile in settings.PROFILES:
for t in profile.input:
for s in t.inputsources:
if s.id == postdata['inputsource']:
inputsource = s
inputsource.inputtemplate = t.id
inputtemplate = t
break
if not inputsource:
for s in settings.INPUTSOURCES:
if s.id == postdata['inputsource']:
inputsource = s
if not inputsource:
return withheaders(flask.make_response("No such inputsource exists",403),headers={'allow_origin': settings.ALLOW_ORIGIN})
if not inputtemplate:
for profile in settings.PROFILES:
for t in profile.input:
if inputsource.inputtemplate == t.id:
inputtemplate = t
if inputtemplate is None:
return withheaders(flask.make_response("No input template found for inputsource",500),headers={'allow_origin': settings.ALLOW_ORIGIN})
if inputsource.isfile():
if inputtemplate.filename:
filename = inputtemplate.filename
else:
filename = os.path.basename(inputsource.path)
xml = addfile(project, filename, user, {'inputsource': postdata['inputsource'], 'inputtemplate': inputtemplate.id}, inputsource)
return xml
elif inputsource.isdir():
if inputtemplate.filename:
filename = inputtemplate.filename
for f in glob.glob(inputsource.path + "/*"):
if not inputtemplate.filename:
filename = os.path.basename(f)
if f[0] != '.':
tmpinputsource = clam.common.data.InputSource(id='tmp',label='tmp',path=f, metadata=inputsource.metadata)
addfile(project, filename, user, {'inputsource':'tmp', 'inputtemplate': inputtemplate.id}, tmpinputsource)
#WARNING: Output is dropped silently here!
return "" #200
else:
assert False
else:
return withheaders(flask.make_response("No filename or inputsource specified",403),headers={'allow_origin': settings.ALLOW_ORIGIN})
else:
#Simply forward to addfile
return addfile(project,filename,user, postdata) | python | def addinputfile(project, filename, credentials=None): #pylint: disable=too-many-return-statements
"""Add a new input file, this invokes the actual uploader"""
printdebug('Addinputfile: Initialising' )
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
response = Project.create(project, user)
if response is not None:
return response
postdata = flask.request.values
if filename == '': #pylint: disable=too-many-nested-blocks
#Handle inputsource
printdebug('Addinputfile: checking for input source' )
if 'inputsource' in postdata and postdata['inputsource']:
inputsource = None
inputtemplate = None
for profile in settings.PROFILES:
for t in profile.input:
for s in t.inputsources:
if s.id == postdata['inputsource']:
inputsource = s
inputsource.inputtemplate = t.id
inputtemplate = t
break
if not inputsource:
for s in settings.INPUTSOURCES:
if s.id == postdata['inputsource']:
inputsource = s
if not inputsource:
return withheaders(flask.make_response("No such inputsource exists",403),headers={'allow_origin': settings.ALLOW_ORIGIN})
if not inputtemplate:
for profile in settings.PROFILES:
for t in profile.input:
if inputsource.inputtemplate == t.id:
inputtemplate = t
if inputtemplate is None:
return withheaders(flask.make_response("No input template found for inputsource",500),headers={'allow_origin': settings.ALLOW_ORIGIN})
if inputsource.isfile():
if inputtemplate.filename:
filename = inputtemplate.filename
else:
filename = os.path.basename(inputsource.path)
xml = addfile(project, filename, user, {'inputsource': postdata['inputsource'], 'inputtemplate': inputtemplate.id}, inputsource)
return xml
elif inputsource.isdir():
if inputtemplate.filename:
filename = inputtemplate.filename
for f in glob.glob(inputsource.path + "/*"):
if not inputtemplate.filename:
filename = os.path.basename(f)
if f[0] != '.':
tmpinputsource = clam.common.data.InputSource(id='tmp',label='tmp',path=f, metadata=inputsource.metadata)
addfile(project, filename, user, {'inputsource':'tmp', 'inputtemplate': inputtemplate.id}, tmpinputsource)
#WARNING: Output is dropped silently here!
return "" #200
else:
assert False
else:
return withheaders(flask.make_response("No filename or inputsource specified",403),headers={'allow_origin': settings.ALLOW_ORIGIN})
else:
#Simply forward to addfile
return addfile(project,filename,user, postdata) | [
"def",
"addinputfile",
"(",
"project",
",",
"filename",
",",
"credentials",
"=",
"None",
")",
":",
"#pylint: disable=too-many-return-statements",
"printdebug",
"(",
"'Addinputfile: Initialising'",
")",
"user",
",",
"oauth_access_token",
"=",
"parsecredentials",
"(",
"credentials",
")",
"#pylint: disable=unused-variable",
"response",
"=",
"Project",
".",
"create",
"(",
"project",
",",
"user",
")",
"if",
"response",
"is",
"not",
"None",
":",
"return",
"response",
"postdata",
"=",
"flask",
".",
"request",
".",
"values",
"if",
"filename",
"==",
"''",
":",
"#pylint: disable=too-many-nested-blocks",
"#Handle inputsource",
"printdebug",
"(",
"'Addinputfile: checking for input source'",
")",
"if",
"'inputsource'",
"in",
"postdata",
"and",
"postdata",
"[",
"'inputsource'",
"]",
":",
"inputsource",
"=",
"None",
"inputtemplate",
"=",
"None",
"for",
"profile",
"in",
"settings",
".",
"PROFILES",
":",
"for",
"t",
"in",
"profile",
".",
"input",
":",
"for",
"s",
"in",
"t",
".",
"inputsources",
":",
"if",
"s",
".",
"id",
"==",
"postdata",
"[",
"'inputsource'",
"]",
":",
"inputsource",
"=",
"s",
"inputsource",
".",
"inputtemplate",
"=",
"t",
".",
"id",
"inputtemplate",
"=",
"t",
"break",
"if",
"not",
"inputsource",
":",
"for",
"s",
"in",
"settings",
".",
"INPUTSOURCES",
":",
"if",
"s",
".",
"id",
"==",
"postdata",
"[",
"'inputsource'",
"]",
":",
"inputsource",
"=",
"s",
"if",
"not",
"inputsource",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"No such inputsource exists\"",
",",
"403",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"if",
"not",
"inputtemplate",
":",
"for",
"profile",
"in",
"settings",
".",
"PROFILES",
":",
"for",
"t",
"in",
"profile",
".",
"input",
":",
"if",
"inputsource",
".",
"inputtemplate",
"==",
"t",
".",
"id",
":",
"inputtemplate",
"=",
"t",
"if",
"inputtemplate",
"is",
"None",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"No input template found for inputsource\"",
",",
"500",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"if",
"inputsource",
".",
"isfile",
"(",
")",
":",
"if",
"inputtemplate",
".",
"filename",
":",
"filename",
"=",
"inputtemplate",
".",
"filename",
"else",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"inputsource",
".",
"path",
")",
"xml",
"=",
"addfile",
"(",
"project",
",",
"filename",
",",
"user",
",",
"{",
"'inputsource'",
":",
"postdata",
"[",
"'inputsource'",
"]",
",",
"'inputtemplate'",
":",
"inputtemplate",
".",
"id",
"}",
",",
"inputsource",
")",
"return",
"xml",
"elif",
"inputsource",
".",
"isdir",
"(",
")",
":",
"if",
"inputtemplate",
".",
"filename",
":",
"filename",
"=",
"inputtemplate",
".",
"filename",
"for",
"f",
"in",
"glob",
".",
"glob",
"(",
"inputsource",
".",
"path",
"+",
"\"/*\"",
")",
":",
"if",
"not",
"inputtemplate",
".",
"filename",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
"if",
"f",
"[",
"0",
"]",
"!=",
"'.'",
":",
"tmpinputsource",
"=",
"clam",
".",
"common",
".",
"data",
".",
"InputSource",
"(",
"id",
"=",
"'tmp'",
",",
"label",
"=",
"'tmp'",
",",
"path",
"=",
"f",
",",
"metadata",
"=",
"inputsource",
".",
"metadata",
")",
"addfile",
"(",
"project",
",",
"filename",
",",
"user",
",",
"{",
"'inputsource'",
":",
"'tmp'",
",",
"'inputtemplate'",
":",
"inputtemplate",
".",
"id",
"}",
",",
"tmpinputsource",
")",
"#WARNING: Output is dropped silently here!",
"return",
"\"\"",
"#200",
"else",
":",
"assert",
"False",
"else",
":",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"\"No filename or inputsource specified\"",
",",
"403",
")",
",",
"headers",
"=",
"{",
"'allow_origin'",
":",
"settings",
".",
"ALLOW_ORIGIN",
"}",
")",
"else",
":",
"#Simply forward to addfile",
"return",
"addfile",
"(",
"project",
",",
"filename",
",",
"user",
",",
"postdata",
")"
] | Add a new input file, this invokes the actual uploader | [
"Add",
"a",
"new",
"input",
"file",
"this",
"invokes",
"the",
"actual",
"uploader"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L1481-L1543 |
proycon/clam | clam/clamservice.py | CLAMService.corpusindex | def corpusindex():
"""Get list of pre-installed corpora"""
corpora = []
for f in glob.glob(settings.ROOT + "corpora/*"):
if os.path.isdir(f):
corpora.append(os.path.basename(f))
return corpora | python | def corpusindex():
"""Get list of pre-installed corpora"""
corpora = []
for f in glob.glob(settings.ROOT + "corpora/*"):
if os.path.isdir(f):
corpora.append(os.path.basename(f))
return corpora | [
"def",
"corpusindex",
"(",
")",
":",
"corpora",
"=",
"[",
"]",
"for",
"f",
"in",
"glob",
".",
"glob",
"(",
"settings",
".",
"ROOT",
"+",
"\"corpora/*\"",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"f",
")",
":",
"corpora",
".",
"append",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
")",
"return",
"corpora"
] | Get list of pre-installed corpora | [
"Get",
"list",
"of",
"pre",
"-",
"installed",
"corpora"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L2552-L2558 |
proycon/clam | clam/common/auth.py | NonceMemory.validate | def validate(self, nonce):
"""Does the nonce exist and is it valid for the request?"""
if self.debug: print("Checking nonce " + str(nonce),file=sys.stderr)
try:
opaque, ip, expiretime = self.get(nonce) #pylint: disable=unused-variable
if expiretime < time.time():
if self.debug: print("Nonce expired",file=sys.stderr)
self.remove(nonce)
return False
elif ip != flask.request.remote_addr:
if self.debug: print("Nonce IP mismatch",file=sys.stderr)
self.remove(nonce)
return False
else:
return True
except KeyError:
if self.debug: print("Nonce " + nonce + " does not exist",file=sys.stderr)
return False | python | def validate(self, nonce):
"""Does the nonce exist and is it valid for the request?"""
if self.debug: print("Checking nonce " + str(nonce),file=sys.stderr)
try:
opaque, ip, expiretime = self.get(nonce) #pylint: disable=unused-variable
if expiretime < time.time():
if self.debug: print("Nonce expired",file=sys.stderr)
self.remove(nonce)
return False
elif ip != flask.request.remote_addr:
if self.debug: print("Nonce IP mismatch",file=sys.stderr)
self.remove(nonce)
return False
else:
return True
except KeyError:
if self.debug: print("Nonce " + nonce + " does not exist",file=sys.stderr)
return False | [
"def",
"validate",
"(",
"self",
",",
"nonce",
")",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"Checking nonce \"",
"+",
"str",
"(",
"nonce",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"try",
":",
"opaque",
",",
"ip",
",",
"expiretime",
"=",
"self",
".",
"get",
"(",
"nonce",
")",
"#pylint: disable=unused-variable",
"if",
"expiretime",
"<",
"time",
".",
"time",
"(",
")",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"Nonce expired\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"self",
".",
"remove",
"(",
"nonce",
")",
"return",
"False",
"elif",
"ip",
"!=",
"flask",
".",
"request",
".",
"remote_addr",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"Nonce IP mismatch\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"self",
".",
"remove",
"(",
"nonce",
")",
"return",
"False",
"else",
":",
"return",
"True",
"except",
"KeyError",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"Nonce \"",
"+",
"nonce",
"+",
"\" does not exist\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"return",
"False"
] | Does the nonce exist and is it valid for the request? | [
"Does",
"the",
"nonce",
"exist",
"and",
"is",
"it",
"valid",
"for",
"the",
"request?"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/auth.py#L463-L480 |
proycon/clam | clam/common/auth.py | NonceMemory.cleanup | def cleanup(self):
"""Delete expired nonces"""
t = time.time()
for noncefile in glob(self.path + '/*.nonce'):
if os.path.getmtime(noncefile) + self.expiration > t:
os.unlink(noncefile) | python | def cleanup(self):
"""Delete expired nonces"""
t = time.time()
for noncefile in glob(self.path + '/*.nonce'):
if os.path.getmtime(noncefile) + self.expiration > t:
os.unlink(noncefile) | [
"def",
"cleanup",
"(",
"self",
")",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"for",
"noncefile",
"in",
"glob",
"(",
"self",
".",
"path",
"+",
"'/*.nonce'",
")",
":",
"if",
"os",
".",
"path",
".",
"getmtime",
"(",
"noncefile",
")",
"+",
"self",
".",
"expiration",
">",
"t",
":",
"os",
".",
"unlink",
"(",
"noncefile",
")"
] | Delete expired nonces | [
"Delete",
"expired",
"nonces"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/auth.py#L503-L508 |
guillermo-carrasco/bcbio-nextgen-monitor | bcbio_monitor/analysis/__init__.py | RunData.json | def json(self):
"""Retrun JSON representation for this run"""
return {
"id": self.ID,
"steps": self.steps,
"graph_source": self.source,
"errored": self.errored
} | python | def json(self):
"""Retrun JSON representation for this run"""
return {
"id": self.ID,
"steps": self.steps,
"graph_source": self.source,
"errored": self.errored
} | [
"def",
"json",
"(",
"self",
")",
":",
"return",
"{",
"\"id\"",
":",
"self",
".",
"ID",
",",
"\"steps\"",
":",
"self",
".",
"steps",
",",
"\"graph_source\"",
":",
"self",
".",
"source",
",",
"\"errored\"",
":",
"self",
".",
"errored",
"}"
] | Retrun JSON representation for this run | [
"Retrun",
"JSON",
"representation",
"for",
"this",
"run"
] | train | https://github.com/guillermo-carrasco/bcbio-nextgen-monitor/blob/6d059154d774140e1fd03a0e3625f607cef06f5a/bcbio_monitor/analysis/__init__.py#L31-L38 |
guillermo-carrasco/bcbio-nextgen-monitor | bcbio_monitor/analysis/__init__.py | AnalysisData.new_run | def new_run(self):
"""Creates a new RunData object and increments pointers"""
self.current_run += 1
self.runs.append(RunData(self.current_run + 1)) | python | def new_run(self):
"""Creates a new RunData object and increments pointers"""
self.current_run += 1
self.runs.append(RunData(self.current_run + 1)) | [
"def",
"new_run",
"(",
"self",
")",
":",
"self",
".",
"current_run",
"+=",
"1",
"self",
".",
"runs",
".",
"append",
"(",
"RunData",
"(",
"self",
".",
"current_run",
"+",
"1",
")",
")"
] | Creates a new RunData object and increments pointers | [
"Creates",
"a",
"new",
"RunData",
"object",
"and",
"increments",
"pointers"
] | train | https://github.com/guillermo-carrasco/bcbio-nextgen-monitor/blob/6d059154d774140e1fd03a0e3625f607cef06f5a/bcbio_monitor/analysis/__init__.py#L69-L72 |
guillermo-carrasco/bcbio-nextgen-monitor | bcbio_monitor/analysis/__init__.py | AnalysisData.follow_log | def follow_log(self):
"""Reads a logfile continuously and updates internal graph if new step is found"""
# Server needs to be up and running before starting sending POST requests
time.sleep(5)
try:
if self.remote:
logger.debug('Logfile in remote host!')
cl = client.SSHClient()
# Try to load system keys
cl.load_system_host_keys()
cl.connect(self.remote['host'], port=self.remote.get('port', 22), username=self.remote.get('username', None), \
password=self.remote.get('password', None))
sftp = cl.open_sftp()
f = sftp.open(self.logfile, 'r')
f.settimeout(5) # Set 5 seconds timeout for read operations
else:
f = open(self.logfile, 'r')
except IOError:
raise RuntimeError("Provided logfile does not exist or its not readable")
self.analysis_finished = False
last_line_read = False
while not self.analysis_finished:
try:
line = f.readline()
except timeout:
logger.error("Connection with the server lost, trying to reconnect and continue reading")
current_pos = f.tell()
try:
cl.connect(self.remote['host'], port=self.remote.get('port', 22), username=self.remote.get('username', None), \
password=self.remote.get('password', None), timeout=300, banner_timeout=300)
except error:
logger.error("Couldn't connect to the server after 5 minutes, aborting.")
os._exit(0)
else:
logger.info("Connection restablished!! Will continue reading the logfile")
sftp = cl.open_sftp()
f = sftp.open(self.logfile, 'r')
f.seek(current_pos)
else:
if not line:
self.finished_reading = True
if not last_line_read:
self.update_frontend({'finished_reading': True})
if self.update:
self.update_frontend(self._last_message)
last_line_read = True
time.sleep(1)
continue
parsed_line = ps.parse_log_line(line)
self._last_message = parsed_line
self.analysis_finished = parsed_line['step'] == 'finished'
# If this is a new step, update internal data
parsed_line['new_run'] = False
if parsed_line['step'] and not parsed_line['step'] == 'error':
if self.FIRST_STEP is None:
self.FIRST_STEP = parsed_line['step']
elif parsed_line['step'] == self.FIRST_STEP:
parsed_line['new_run'] = True
self.new_run()
node_id = 'run-{}_'.format(self.current_run + 1) + '_'.join(parsed_line['step'].lower().split())
parsed_line['step_id'] = node_id
self.runs[self.current_run].steps.append(parsed_line)
self.runs[self.current_run].node(node_id, parsed_line['step'])
self.runs[self.current_run]._nodes.append(node_id)
n_nodes = len(self.runs[self.current_run]._nodes)
if n_nodes > 1:
self.runs[self.current_run].edge(self.runs[self.current_run]._nodes[n_nodes - 2], self.runs[self.current_run]._nodes[n_nodes -1])
parsed_line['graph_source'] = self.runs[self.current_run].source
elif parsed_line['step'] == 'error':
self.runs[self.current_run].errored = True
# Update frontend only if its a new step _or_ the update flag is set to true and we are
# not loading the log for the first time
if (last_line_read and self.update) or parsed_line['step']:
self.update_frontend(parsed_line)
f.close() | python | def follow_log(self):
"""Reads a logfile continuously and updates internal graph if new step is found"""
# Server needs to be up and running before starting sending POST requests
time.sleep(5)
try:
if self.remote:
logger.debug('Logfile in remote host!')
cl = client.SSHClient()
# Try to load system keys
cl.load_system_host_keys()
cl.connect(self.remote['host'], port=self.remote.get('port', 22), username=self.remote.get('username', None), \
password=self.remote.get('password', None))
sftp = cl.open_sftp()
f = sftp.open(self.logfile, 'r')
f.settimeout(5) # Set 5 seconds timeout for read operations
else:
f = open(self.logfile, 'r')
except IOError:
raise RuntimeError("Provided logfile does not exist or its not readable")
self.analysis_finished = False
last_line_read = False
while not self.analysis_finished:
try:
line = f.readline()
except timeout:
logger.error("Connection with the server lost, trying to reconnect and continue reading")
current_pos = f.tell()
try:
cl.connect(self.remote['host'], port=self.remote.get('port', 22), username=self.remote.get('username', None), \
password=self.remote.get('password', None), timeout=300, banner_timeout=300)
except error:
logger.error("Couldn't connect to the server after 5 minutes, aborting.")
os._exit(0)
else:
logger.info("Connection restablished!! Will continue reading the logfile")
sftp = cl.open_sftp()
f = sftp.open(self.logfile, 'r')
f.seek(current_pos)
else:
if not line:
self.finished_reading = True
if not last_line_read:
self.update_frontend({'finished_reading': True})
if self.update:
self.update_frontend(self._last_message)
last_line_read = True
time.sleep(1)
continue
parsed_line = ps.parse_log_line(line)
self._last_message = parsed_line
self.analysis_finished = parsed_line['step'] == 'finished'
# If this is a new step, update internal data
parsed_line['new_run'] = False
if parsed_line['step'] and not parsed_line['step'] == 'error':
if self.FIRST_STEP is None:
self.FIRST_STEP = parsed_line['step']
elif parsed_line['step'] == self.FIRST_STEP:
parsed_line['new_run'] = True
self.new_run()
node_id = 'run-{}_'.format(self.current_run + 1) + '_'.join(parsed_line['step'].lower().split())
parsed_line['step_id'] = node_id
self.runs[self.current_run].steps.append(parsed_line)
self.runs[self.current_run].node(node_id, parsed_line['step'])
self.runs[self.current_run]._nodes.append(node_id)
n_nodes = len(self.runs[self.current_run]._nodes)
if n_nodes > 1:
self.runs[self.current_run].edge(self.runs[self.current_run]._nodes[n_nodes - 2], self.runs[self.current_run]._nodes[n_nodes -1])
parsed_line['graph_source'] = self.runs[self.current_run].source
elif parsed_line['step'] == 'error':
self.runs[self.current_run].errored = True
# Update frontend only if its a new step _or_ the update flag is set to true and we are
# not loading the log for the first time
if (last_line_read and self.update) or parsed_line['step']:
self.update_frontend(parsed_line)
f.close() | [
"def",
"follow_log",
"(",
"self",
")",
":",
"# Server needs to be up and running before starting sending POST requests",
"time",
".",
"sleep",
"(",
"5",
")",
"try",
":",
"if",
"self",
".",
"remote",
":",
"logger",
".",
"debug",
"(",
"'Logfile in remote host!'",
")",
"cl",
"=",
"client",
".",
"SSHClient",
"(",
")",
"# Try to load system keys",
"cl",
".",
"load_system_host_keys",
"(",
")",
"cl",
".",
"connect",
"(",
"self",
".",
"remote",
"[",
"'host'",
"]",
",",
"port",
"=",
"self",
".",
"remote",
".",
"get",
"(",
"'port'",
",",
"22",
")",
",",
"username",
"=",
"self",
".",
"remote",
".",
"get",
"(",
"'username'",
",",
"None",
")",
",",
"password",
"=",
"self",
".",
"remote",
".",
"get",
"(",
"'password'",
",",
"None",
")",
")",
"sftp",
"=",
"cl",
".",
"open_sftp",
"(",
")",
"f",
"=",
"sftp",
".",
"open",
"(",
"self",
".",
"logfile",
",",
"'r'",
")",
"f",
".",
"settimeout",
"(",
"5",
")",
"# Set 5 seconds timeout for read operations",
"else",
":",
"f",
"=",
"open",
"(",
"self",
".",
"logfile",
",",
"'r'",
")",
"except",
"IOError",
":",
"raise",
"RuntimeError",
"(",
"\"Provided logfile does not exist or its not readable\"",
")",
"self",
".",
"analysis_finished",
"=",
"False",
"last_line_read",
"=",
"False",
"while",
"not",
"self",
".",
"analysis_finished",
":",
"try",
":",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"except",
"timeout",
":",
"logger",
".",
"error",
"(",
"\"Connection with the server lost, trying to reconnect and continue reading\"",
")",
"current_pos",
"=",
"f",
".",
"tell",
"(",
")",
"try",
":",
"cl",
".",
"connect",
"(",
"self",
".",
"remote",
"[",
"'host'",
"]",
",",
"port",
"=",
"self",
".",
"remote",
".",
"get",
"(",
"'port'",
",",
"22",
")",
",",
"username",
"=",
"self",
".",
"remote",
".",
"get",
"(",
"'username'",
",",
"None",
")",
",",
"password",
"=",
"self",
".",
"remote",
".",
"get",
"(",
"'password'",
",",
"None",
")",
",",
"timeout",
"=",
"300",
",",
"banner_timeout",
"=",
"300",
")",
"except",
"error",
":",
"logger",
".",
"error",
"(",
"\"Couldn't connect to the server after 5 minutes, aborting.\"",
")",
"os",
".",
"_exit",
"(",
"0",
")",
"else",
":",
"logger",
".",
"info",
"(",
"\"Connection restablished!! Will continue reading the logfile\"",
")",
"sftp",
"=",
"cl",
".",
"open_sftp",
"(",
")",
"f",
"=",
"sftp",
".",
"open",
"(",
"self",
".",
"logfile",
",",
"'r'",
")",
"f",
".",
"seek",
"(",
"current_pos",
")",
"else",
":",
"if",
"not",
"line",
":",
"self",
".",
"finished_reading",
"=",
"True",
"if",
"not",
"last_line_read",
":",
"self",
".",
"update_frontend",
"(",
"{",
"'finished_reading'",
":",
"True",
"}",
")",
"if",
"self",
".",
"update",
":",
"self",
".",
"update_frontend",
"(",
"self",
".",
"_last_message",
")",
"last_line_read",
"=",
"True",
"time",
".",
"sleep",
"(",
"1",
")",
"continue",
"parsed_line",
"=",
"ps",
".",
"parse_log_line",
"(",
"line",
")",
"self",
".",
"_last_message",
"=",
"parsed_line",
"self",
".",
"analysis_finished",
"=",
"parsed_line",
"[",
"'step'",
"]",
"==",
"'finished'",
"# If this is a new step, update internal data",
"parsed_line",
"[",
"'new_run'",
"]",
"=",
"False",
"if",
"parsed_line",
"[",
"'step'",
"]",
"and",
"not",
"parsed_line",
"[",
"'step'",
"]",
"==",
"'error'",
":",
"if",
"self",
".",
"FIRST_STEP",
"is",
"None",
":",
"self",
".",
"FIRST_STEP",
"=",
"parsed_line",
"[",
"'step'",
"]",
"elif",
"parsed_line",
"[",
"'step'",
"]",
"==",
"self",
".",
"FIRST_STEP",
":",
"parsed_line",
"[",
"'new_run'",
"]",
"=",
"True",
"self",
".",
"new_run",
"(",
")",
"node_id",
"=",
"'run-{}_'",
".",
"format",
"(",
"self",
".",
"current_run",
"+",
"1",
")",
"+",
"'_'",
".",
"join",
"(",
"parsed_line",
"[",
"'step'",
"]",
".",
"lower",
"(",
")",
".",
"split",
"(",
")",
")",
"parsed_line",
"[",
"'step_id'",
"]",
"=",
"node_id",
"self",
".",
"runs",
"[",
"self",
".",
"current_run",
"]",
".",
"steps",
".",
"append",
"(",
"parsed_line",
")",
"self",
".",
"runs",
"[",
"self",
".",
"current_run",
"]",
".",
"node",
"(",
"node_id",
",",
"parsed_line",
"[",
"'step'",
"]",
")",
"self",
".",
"runs",
"[",
"self",
".",
"current_run",
"]",
".",
"_nodes",
".",
"append",
"(",
"node_id",
")",
"n_nodes",
"=",
"len",
"(",
"self",
".",
"runs",
"[",
"self",
".",
"current_run",
"]",
".",
"_nodes",
")",
"if",
"n_nodes",
">",
"1",
":",
"self",
".",
"runs",
"[",
"self",
".",
"current_run",
"]",
".",
"edge",
"(",
"self",
".",
"runs",
"[",
"self",
".",
"current_run",
"]",
".",
"_nodes",
"[",
"n_nodes",
"-",
"2",
"]",
",",
"self",
".",
"runs",
"[",
"self",
".",
"current_run",
"]",
".",
"_nodes",
"[",
"n_nodes",
"-",
"1",
"]",
")",
"parsed_line",
"[",
"'graph_source'",
"]",
"=",
"self",
".",
"runs",
"[",
"self",
".",
"current_run",
"]",
".",
"source",
"elif",
"parsed_line",
"[",
"'step'",
"]",
"==",
"'error'",
":",
"self",
".",
"runs",
"[",
"self",
".",
"current_run",
"]",
".",
"errored",
"=",
"True",
"# Update frontend only if its a new step _or_ the update flag is set to true and we are",
"# not loading the log for the first time",
"if",
"(",
"last_line_read",
"and",
"self",
".",
"update",
")",
"or",
"parsed_line",
"[",
"'step'",
"]",
":",
"self",
".",
"update_frontend",
"(",
"parsed_line",
")",
"f",
".",
"close",
"(",
")"
] | Reads a logfile continuously and updates internal graph if new step is found | [
"Reads",
"a",
"logfile",
"continuously",
"and",
"updates",
"internal",
"graph",
"if",
"new",
"step",
"is",
"found"
] | train | https://github.com/guillermo-carrasco/bcbio-nextgen-monitor/blob/6d059154d774140e1fd03a0e3625f607cef06f5a/bcbio_monitor/analysis/__init__.py#L75-L152 |
guillermo-carrasco/bcbio-nextgen-monitor | bcbio_monitor/analysis/__init__.py | AnalysisData.update_frontend | def update_frontend(self, info):
"""Updates frontend with info from the log
:param info: dict - Information from a line in the log. i.e regular line, new step.
"""
headers = {'Content-Type': 'text/event-stream'}
if info.get('when'):
info['when'] = info['when'].isoformat()
requests.post(self.base_url + '/publish', data=json.dumps(info), headers=headers) | python | def update_frontend(self, info):
"""Updates frontend with info from the log
:param info: dict - Information from a line in the log. i.e regular line, new step.
"""
headers = {'Content-Type': 'text/event-stream'}
if info.get('when'):
info['when'] = info['when'].isoformat()
requests.post(self.base_url + '/publish', data=json.dumps(info), headers=headers) | [
"def",
"update_frontend",
"(",
"self",
",",
"info",
")",
":",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'text/event-stream'",
"}",
"if",
"info",
".",
"get",
"(",
"'when'",
")",
":",
"info",
"[",
"'when'",
"]",
"=",
"info",
"[",
"'when'",
"]",
".",
"isoformat",
"(",
")",
"requests",
".",
"post",
"(",
"self",
".",
"base_url",
"+",
"'/publish'",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"info",
")",
",",
"headers",
"=",
"headers",
")"
] | Updates frontend with info from the log
:param info: dict - Information from a line in the log. i.e regular line, new step. | [
"Updates",
"frontend",
"with",
"info",
"from",
"the",
"log"
] | train | https://github.com/guillermo-carrasco/bcbio-nextgen-monitor/blob/6d059154d774140e1fd03a0e3625f607cef06f5a/bcbio_monitor/analysis/__init__.py#L155-L163 |
guillermo-carrasco/bcbio-nextgen-monitor | bcbio_monitor/analysis/__init__.py | AnalysisData.get_summary | def get_summary(self):
"""Returns some summary data for a finished analysis"""
if not self.analysis_finished:
return []
summary = {'times_summary': []}
for i in range(len(self.runs[self.current_run].steps) - 1):
step = self.runs[self.current_run].steps[i]
begin = parse(step['when'])
end = parse(self.runs[self.current_run].steps[i + 1]['when'])
duration = end - begin
summary['times_summary'].append((step['step'], duration.seconds))
return summary | python | def get_summary(self):
"""Returns some summary data for a finished analysis"""
if not self.analysis_finished:
return []
summary = {'times_summary': []}
for i in range(len(self.runs[self.current_run].steps) - 1):
step = self.runs[self.current_run].steps[i]
begin = parse(step['when'])
end = parse(self.runs[self.current_run].steps[i + 1]['when'])
duration = end - begin
summary['times_summary'].append((step['step'], duration.seconds))
return summary | [
"def",
"get_summary",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"analysis_finished",
":",
"return",
"[",
"]",
"summary",
"=",
"{",
"'times_summary'",
":",
"[",
"]",
"}",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"runs",
"[",
"self",
".",
"current_run",
"]",
".",
"steps",
")",
"-",
"1",
")",
":",
"step",
"=",
"self",
".",
"runs",
"[",
"self",
".",
"current_run",
"]",
".",
"steps",
"[",
"i",
"]",
"begin",
"=",
"parse",
"(",
"step",
"[",
"'when'",
"]",
")",
"end",
"=",
"parse",
"(",
"self",
".",
"runs",
"[",
"self",
".",
"current_run",
"]",
".",
"steps",
"[",
"i",
"+",
"1",
"]",
"[",
"'when'",
"]",
")",
"duration",
"=",
"end",
"-",
"begin",
"summary",
"[",
"'times_summary'",
"]",
".",
"append",
"(",
"(",
"step",
"[",
"'step'",
"]",
",",
"duration",
".",
"seconds",
")",
")",
"return",
"summary"
] | Returns some summary data for a finished analysis | [
"Returns",
"some",
"summary",
"data",
"for",
"a",
"finished",
"analysis"
] | train | https://github.com/guillermo-carrasco/bcbio-nextgen-monitor/blob/6d059154d774140e1fd03a0e3625f607cef06f5a/bcbio_monitor/analysis/__init__.py#L176-L187 |
i3visio/deepify | deepify/zeronet.py | Zeronet._grabContentFromUrl | def _grabContentFromUrl(self, url):
"""
Function that abstracts capturing a URL. This method rewrites the one from Wrapper.
:param url: The URL to be processed.
:return: The response in a Json format.
"""
# Defining an empty object for the response
info = {}
# This part has to be modified...
try:
# Configuring the socket
queryURL = "http://" + self.info["host"] + ":" + self.info["port"] + "/" + url
response = urllib2.urlopen(queryURL)
# Rebuilding data to be processed
data = str(response.headers) + "\n"
data += response.read()
# Processing data as expected
info = self._createDataStructure(data)
# Try to make the errors clear for other users
except Exception, e:
errMsg = "ERROR Exception. Something seems to be wrong with the Zeronet Bundler."
raise Exception( errMsg + " " + str(e))
return info | python | def _grabContentFromUrl(self, url):
"""
Function that abstracts capturing a URL. This method rewrites the one from Wrapper.
:param url: The URL to be processed.
:return: The response in a Json format.
"""
# Defining an empty object for the response
info = {}
# This part has to be modified...
try:
# Configuring the socket
queryURL = "http://" + self.info["host"] + ":" + self.info["port"] + "/" + url
response = urllib2.urlopen(queryURL)
# Rebuilding data to be processed
data = str(response.headers) + "\n"
data += response.read()
# Processing data as expected
info = self._createDataStructure(data)
# Try to make the errors clear for other users
except Exception, e:
errMsg = "ERROR Exception. Something seems to be wrong with the Zeronet Bundler."
raise Exception( errMsg + " " + str(e))
return info | [
"def",
"_grabContentFromUrl",
"(",
"self",
",",
"url",
")",
":",
"# Defining an empty object for the response",
"info",
"=",
"{",
"}",
"# This part has to be modified... ",
"try",
":",
"# Configuring the socket",
"queryURL",
"=",
"\"http://\"",
"+",
"self",
".",
"info",
"[",
"\"host\"",
"]",
"+",
"\":\"",
"+",
"self",
".",
"info",
"[",
"\"port\"",
"]",
"+",
"\"/\"",
"+",
"url",
"response",
"=",
"urllib2",
".",
"urlopen",
"(",
"queryURL",
")",
"# Rebuilding data to be processed",
"data",
"=",
"str",
"(",
"response",
".",
"headers",
")",
"+",
"\"\\n\"",
"data",
"+=",
"response",
".",
"read",
"(",
")",
"# Processing data as expected",
"info",
"=",
"self",
".",
"_createDataStructure",
"(",
"data",
")",
"# Try to make the errors clear for other users",
"except",
"Exception",
",",
"e",
":",
"errMsg",
"=",
"\"ERROR Exception. Something seems to be wrong with the Zeronet Bundler.\"",
"raise",
"Exception",
"(",
"errMsg",
"+",
"\" \"",
"+",
"str",
"(",
"e",
")",
")",
"return",
"info"
] | Function that abstracts capturing a URL. This method rewrites the one from Wrapper.
:param url: The URL to be processed.
:return: The response in a Json format. | [
"Function",
"that",
"abstracts",
"capturing",
"a",
"URL",
".",
"This",
"method",
"rewrites",
"the",
"one",
"from",
"Wrapper",
".",
":",
"param",
"url",
":",
"The",
"URL",
"to",
"be",
"processed",
".",
":",
"return",
":",
"The",
"response",
"in",
"a",
"Json",
"format",
"."
] | train | https://github.com/i3visio/deepify/blob/2af04e0bea3eaabe96b0565e10f7eeb29b042a2b/deepify/zeronet.py#L52-L81 |
harcokuppens/thonny-ev3dev | thonnycontrib/ev3dev/__init__.py | _handle_rundebug_from_shell | def _handle_rundebug_from_shell(cmd_line):
"""
Handles all commands that take a filename and 0 or more extra arguments.
Passes the command to backend.
(Debugger plugin may also use this method)
"""
command, args = parse_shell_command(cmd_line)
if len(args) >= 1:
get_workbench().get_editor_notebook().save_all_named_editors()
origcommand=command
if command == "Ev3RemoteRun":
command="Run"
if command == "Ev3RemoteDebug":
command="Debug"
cmd = ToplevelCommand(command=command,
filename=args[0],
args=args[1:])
if origcommand == "Ev3RemoteRun" or origcommand == "Ev3RemoteDebug":
cmd.environment={ "EV3MODE" : "remote", "EV3IP": get_workbench().get_option("ev3.ip") }
if os.path.isabs(cmd.filename):
cmd.full_filename = cmd.filename
else:
runner=get_runner()
cmd.full_filename = os.path.join(runner.get_cwd(), cmd.filename)
if command in ["Run", "run", "Debug", "debug"]:
with tokenize.open(cmd.full_filename) as fp:
cmd.source = fp.read()
get_runner().send_command(cmd)
else:
print_error_in_backend("Command '{}' takes at least one argument".format(command)) | python | def _handle_rundebug_from_shell(cmd_line):
"""
Handles all commands that take a filename and 0 or more extra arguments.
Passes the command to backend.
(Debugger plugin may also use this method)
"""
command, args = parse_shell_command(cmd_line)
if len(args) >= 1:
get_workbench().get_editor_notebook().save_all_named_editors()
origcommand=command
if command == "Ev3RemoteRun":
command="Run"
if command == "Ev3RemoteDebug":
command="Debug"
cmd = ToplevelCommand(command=command,
filename=args[0],
args=args[1:])
if origcommand == "Ev3RemoteRun" or origcommand == "Ev3RemoteDebug":
cmd.environment={ "EV3MODE" : "remote", "EV3IP": get_workbench().get_option("ev3.ip") }
if os.path.isabs(cmd.filename):
cmd.full_filename = cmd.filename
else:
runner=get_runner()
cmd.full_filename = os.path.join(runner.get_cwd(), cmd.filename)
if command in ["Run", "run", "Debug", "debug"]:
with tokenize.open(cmd.full_filename) as fp:
cmd.source = fp.read()
get_runner().send_command(cmd)
else:
print_error_in_backend("Command '{}' takes at least one argument".format(command)) | [
"def",
"_handle_rundebug_from_shell",
"(",
"cmd_line",
")",
":",
"command",
",",
"args",
"=",
"parse_shell_command",
"(",
"cmd_line",
")",
"if",
"len",
"(",
"args",
")",
">=",
"1",
":",
"get_workbench",
"(",
")",
".",
"get_editor_notebook",
"(",
")",
".",
"save_all_named_editors",
"(",
")",
"origcommand",
"=",
"command",
"if",
"command",
"==",
"\"Ev3RemoteRun\"",
":",
"command",
"=",
"\"Run\"",
"if",
"command",
"==",
"\"Ev3RemoteDebug\"",
":",
"command",
"=",
"\"Debug\"",
"cmd",
"=",
"ToplevelCommand",
"(",
"command",
"=",
"command",
",",
"filename",
"=",
"args",
"[",
"0",
"]",
",",
"args",
"=",
"args",
"[",
"1",
":",
"]",
")",
"if",
"origcommand",
"==",
"\"Ev3RemoteRun\"",
"or",
"origcommand",
"==",
"\"Ev3RemoteDebug\"",
":",
"cmd",
".",
"environment",
"=",
"{",
"\"EV3MODE\"",
":",
"\"remote\"",
",",
"\"EV3IP\"",
":",
"get_workbench",
"(",
")",
".",
"get_option",
"(",
"\"ev3.ip\"",
")",
"}",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"cmd",
".",
"filename",
")",
":",
"cmd",
".",
"full_filename",
"=",
"cmd",
".",
"filename",
"else",
":",
"runner",
"=",
"get_runner",
"(",
")",
"cmd",
".",
"full_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"runner",
".",
"get_cwd",
"(",
")",
",",
"cmd",
".",
"filename",
")",
"if",
"command",
"in",
"[",
"\"Run\"",
",",
"\"run\"",
",",
"\"Debug\"",
",",
"\"debug\"",
"]",
":",
"with",
"tokenize",
".",
"open",
"(",
"cmd",
".",
"full_filename",
")",
"as",
"fp",
":",
"cmd",
".",
"source",
"=",
"fp",
".",
"read",
"(",
")",
"get_runner",
"(",
")",
".",
"send_command",
"(",
"cmd",
")",
"else",
":",
"print_error_in_backend",
"(",
"\"Command '{}' takes at least one argument\"",
".",
"format",
"(",
"command",
")",
")"
] | Handles all commands that take a filename and 0 or more extra arguments.
Passes the command to backend.
(Debugger plugin may also use this method) | [
"Handles",
"all",
"commands",
"that",
"take",
"a",
"filename",
"and",
"0",
"or",
"more",
"extra",
"arguments",
".",
"Passes",
"the",
"command",
"to",
"backend",
"."
] | train | https://github.com/harcokuppens/thonny-ev3dev/blob/e3437d7716068976faf2146c6bb0332ed56a1760/thonnycontrib/ev3dev/__init__.py#L326-L364 |
harcokuppens/thonny-ev3dev | thonnycontrib/ev3dev/__init__.py | upload_current_script | def upload_current_script():
"""upload current python script to EV3"""
current_editor = get_workbench().get_editor_notebook().get_current_editor()
code = current_editor.get_text_widget().get("1.0", "end")
try:
filename= current_editor.get_filename()
if (not filename) or (not filename.endswith(".py")):
return
ast.parse(code)
if not code.startswith('#!'):
if tkMessageBox.askokcancel("Shebang", "To make a python file on the EV3 executable Thonny prepends the shebang line:\n\n !#/usr/bin/env python3\n"):
current_editor.get_text_widget().direct_insert("1.0", "#!/usr/bin/env python3\n")
else:
return
# automatically save file (without confirm dialog, nor dialog for asking filename )
# save_file does return None, if script is not saved and user closed file saving window, otherwise return file name.
py_file = current_editor.save_file(False)
if py_file is None:
return
upload(py_file)
except Exception:
error_msg = traceback.format_exc(0)+'\n'
showerror("Error", error_msg) | python | def upload_current_script():
"""upload current python script to EV3"""
current_editor = get_workbench().get_editor_notebook().get_current_editor()
code = current_editor.get_text_widget().get("1.0", "end")
try:
filename= current_editor.get_filename()
if (not filename) or (not filename.endswith(".py")):
return
ast.parse(code)
if not code.startswith('#!'):
if tkMessageBox.askokcancel("Shebang", "To make a python file on the EV3 executable Thonny prepends the shebang line:\n\n !#/usr/bin/env python3\n"):
current_editor.get_text_widget().direct_insert("1.0", "#!/usr/bin/env python3\n")
else:
return
# automatically save file (without confirm dialog, nor dialog for asking filename )
# save_file does return None, if script is not saved and user closed file saving window, otherwise return file name.
py_file = current_editor.save_file(False)
if py_file is None:
return
upload(py_file)
except Exception:
error_msg = traceback.format_exc(0)+'\n'
showerror("Error", error_msg) | [
"def",
"upload_current_script",
"(",
")",
":",
"current_editor",
"=",
"get_workbench",
"(",
")",
".",
"get_editor_notebook",
"(",
")",
".",
"get_current_editor",
"(",
")",
"code",
"=",
"current_editor",
".",
"get_text_widget",
"(",
")",
".",
"get",
"(",
"\"1.0\"",
",",
"\"end\"",
")",
"try",
":",
"filename",
"=",
"current_editor",
".",
"get_filename",
"(",
")",
"if",
"(",
"not",
"filename",
")",
"or",
"(",
"not",
"filename",
".",
"endswith",
"(",
"\".py\"",
")",
")",
":",
"return",
"ast",
".",
"parse",
"(",
"code",
")",
"if",
"not",
"code",
".",
"startswith",
"(",
"'#!'",
")",
":",
"if",
"tkMessageBox",
".",
"askokcancel",
"(",
"\"Shebang\"",
",",
"\"To make a python file on the EV3 executable Thonny prepends the shebang line:\\n\\n !#/usr/bin/env python3\\n\"",
")",
":",
"current_editor",
".",
"get_text_widget",
"(",
")",
".",
"direct_insert",
"(",
"\"1.0\"",
",",
"\"#!/usr/bin/env python3\\n\"",
")",
"else",
":",
"return",
"# automatically save file (without confirm dialog, nor dialog for asking filename )",
"# save_file does return None, if script is not saved and user closed file saving window, otherwise return file name.",
"py_file",
"=",
"current_editor",
".",
"save_file",
"(",
"False",
")",
"if",
"py_file",
"is",
"None",
":",
"return",
"upload",
"(",
"py_file",
")",
"except",
"Exception",
":",
"error_msg",
"=",
"traceback",
".",
"format_exc",
"(",
"0",
")",
"+",
"'\\n'",
"showerror",
"(",
"\"Error\"",
",",
"error_msg",
")"
] | upload current python script to EV3 | [
"upload",
"current",
"python",
"script",
"to",
"EV3"
] | train | https://github.com/harcokuppens/thonny-ev3dev/blob/e3437d7716068976faf2146c6bb0332ed56a1760/thonnycontrib/ev3dev/__init__.py#L407-L433 |
harcokuppens/thonny-ev3dev | thonnycontrib/ev3dev/__init__.py | start_current_script | def start_current_script():
"""upload current python script to EV3"""
current_editor = get_workbench().get_editor_notebook().get_current_editor()
code = current_editor.get_text_widget().get("1.0", "end")
try:
ast.parse(code)
#Return None, if script is not saved and user closed file saving window, otherwise return file name.
py_file = get_workbench().get_current_editor().save_file(False)
if py_file is None:
return
start(py_file)
except Exception:
error_msg = traceback.format_exc(0)+'\n'
showerror("Error", error_msg) | python | def start_current_script():
"""upload current python script to EV3"""
current_editor = get_workbench().get_editor_notebook().get_current_editor()
code = current_editor.get_text_widget().get("1.0", "end")
try:
ast.parse(code)
#Return None, if script is not saved and user closed file saving window, otherwise return file name.
py_file = get_workbench().get_current_editor().save_file(False)
if py_file is None:
return
start(py_file)
except Exception:
error_msg = traceback.format_exc(0)+'\n'
showerror("Error", error_msg) | [
"def",
"start_current_script",
"(",
")",
":",
"current_editor",
"=",
"get_workbench",
"(",
")",
".",
"get_editor_notebook",
"(",
")",
".",
"get_current_editor",
"(",
")",
"code",
"=",
"current_editor",
".",
"get_text_widget",
"(",
")",
".",
"get",
"(",
"\"1.0\"",
",",
"\"end\"",
")",
"try",
":",
"ast",
".",
"parse",
"(",
"code",
")",
"#Return None, if script is not saved and user closed file saving window, otherwise return file name.",
"py_file",
"=",
"get_workbench",
"(",
")",
".",
"get_current_editor",
"(",
")",
".",
"save_file",
"(",
"False",
")",
"if",
"py_file",
"is",
"None",
":",
"return",
"start",
"(",
"py_file",
")",
"except",
"Exception",
":",
"error_msg",
"=",
"traceback",
".",
"format_exc",
"(",
"0",
")",
"+",
"'\\n'",
"showerror",
"(",
"\"Error\"",
",",
"error_msg",
")"
] | upload current python script to EV3 | [
"upload",
"current",
"python",
"script",
"to",
"EV3"
] | train | https://github.com/harcokuppens/thonny-ev3dev/blob/e3437d7716068976faf2146c6bb0332ed56a1760/thonnycontrib/ev3dev/__init__.py#L457-L470 |
harcokuppens/thonny-ev3dev | thonnycontrib/ev3dev/__init__.py | download_log | def download_log(currentfile=None):
"""downloads log of given .py file from EV3."""
if currentfile == None:
return
# add ".err.log" if file doesn't end with it!
if not currentfile.endswith(".err.log"):
currentfile=currentfile + ".err.log"
list = get_base_ev3dev_cmd() + ['download','--force']
list.append(currentfile)
env = os.environ.copy()
env["PYTHONUSERBASE"] = THONNY_USER_BASE
proc = subprocess.Popen(list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True, env=env)
dlg = MySubprocessDialog(get_workbench(), proc, "Downloading log of program from EV3", autoclose=True)
dlg.wait_window()
if dlg.returncode == 0:
from pathlib import Path
home = str(Path.home())
open_file(currentfile,home,True) | python | def download_log(currentfile=None):
"""downloads log of given .py file from EV3."""
if currentfile == None:
return
# add ".err.log" if file doesn't end with it!
if not currentfile.endswith(".err.log"):
currentfile=currentfile + ".err.log"
list = get_base_ev3dev_cmd() + ['download','--force']
list.append(currentfile)
env = os.environ.copy()
env["PYTHONUSERBASE"] = THONNY_USER_BASE
proc = subprocess.Popen(list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True, env=env)
dlg = MySubprocessDialog(get_workbench(), proc, "Downloading log of program from EV3", autoclose=True)
dlg.wait_window()
if dlg.returncode == 0:
from pathlib import Path
home = str(Path.home())
open_file(currentfile,home,True) | [
"def",
"download_log",
"(",
"currentfile",
"=",
"None",
")",
":",
"if",
"currentfile",
"==",
"None",
":",
"return",
"# add \".err.log\" if file doesn't end with it!",
"if",
"not",
"currentfile",
".",
"endswith",
"(",
"\".err.log\"",
")",
":",
"currentfile",
"=",
"currentfile",
"+",
"\".err.log\"",
"list",
"=",
"get_base_ev3dev_cmd",
"(",
")",
"+",
"[",
"'download'",
",",
"'--force'",
"]",
"list",
".",
"append",
"(",
"currentfile",
")",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"env",
"[",
"\"PYTHONUSERBASE\"",
"]",
"=",
"THONNY_USER_BASE",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"list",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
"universal_newlines",
"=",
"True",
",",
"env",
"=",
"env",
")",
"dlg",
"=",
"MySubprocessDialog",
"(",
"get_workbench",
"(",
")",
",",
"proc",
",",
"\"Downloading log of program from EV3\"",
",",
"autoclose",
"=",
"True",
")",
"dlg",
".",
"wait_window",
"(",
")",
"if",
"dlg",
".",
"returncode",
"==",
"0",
":",
"from",
"pathlib",
"import",
"Path",
"home",
"=",
"str",
"(",
"Path",
".",
"home",
"(",
")",
")",
"open_file",
"(",
"currentfile",
",",
"home",
",",
"True",
")"
] | downloads log of given .py file from EV3. | [
"downloads",
"log",
"of",
"given",
".",
"py",
"file",
"from",
"EV3",
"."
] | train | https://github.com/harcokuppens/thonny-ev3dev/blob/e3437d7716068976faf2146c6bb0332ed56a1760/thonnycontrib/ev3dev/__init__.py#L473-L495 |
harcokuppens/thonny-ev3dev | thonnycontrib/ev3dev/__init__.py | download_log_of_current_script | def download_log_of_current_script():
"""download log of current python script from EV3"""
try:
#Return None, if script is not saved and user closed file saving window, otherwise return file name.
src_file = get_workbench().get_current_editor().get_filename(False)
if src_file is None:
return
download_log(src_file)
except Exception:
error_msg = traceback.format_exc(0)+'\n'
showerror("Error", error_msg) | python | def download_log_of_current_script():
"""download log of current python script from EV3"""
try:
#Return None, if script is not saved and user closed file saving window, otherwise return file name.
src_file = get_workbench().get_current_editor().get_filename(False)
if src_file is None:
return
download_log(src_file)
except Exception:
error_msg = traceback.format_exc(0)+'\n'
showerror("Error", error_msg) | [
"def",
"download_log_of_current_script",
"(",
")",
":",
"try",
":",
"#Return None, if script is not saved and user closed file saving window, otherwise return file name.",
"src_file",
"=",
"get_workbench",
"(",
")",
".",
"get_current_editor",
"(",
")",
".",
"get_filename",
"(",
"False",
")",
"if",
"src_file",
"is",
"None",
":",
"return",
"download_log",
"(",
"src_file",
")",
"except",
"Exception",
":",
"error_msg",
"=",
"traceback",
".",
"format_exc",
"(",
"0",
")",
"+",
"'\\n'",
"showerror",
"(",
"\"Error\"",
",",
"error_msg",
")"
] | download log of current python script from EV3 | [
"download",
"log",
"of",
"current",
"python",
"script",
"from",
"EV3"
] | train | https://github.com/harcokuppens/thonny-ev3dev/blob/e3437d7716068976faf2146c6bb0332ed56a1760/thonnycontrib/ev3dev/__init__.py#L528-L539 |
harcokuppens/thonny-ev3dev | thonnycontrib/ev3dev/__init__.py | cleanup_files_on_ev3 | def cleanup_files_on_ev3():
"""cleanup files in homedir on EV3."""
list = get_base_ev3dev_cmd() + ['cleanup']
env = os.environ.copy()
env["PYTHONUSERBASE"] = THONNY_USER_BASE
proc = subprocess.Popen(list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True, env=env)
dlg = MySubprocessDialog(get_workbench(), proc, "Delete files in homedir on EV3", autoclose=False)
dlg.wait_window() | python | def cleanup_files_on_ev3():
"""cleanup files in homedir on EV3."""
list = get_base_ev3dev_cmd() + ['cleanup']
env = os.environ.copy()
env["PYTHONUSERBASE"] = THONNY_USER_BASE
proc = subprocess.Popen(list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True, env=env)
dlg = MySubprocessDialog(get_workbench(), proc, "Delete files in homedir on EV3", autoclose=False)
dlg.wait_window() | [
"def",
"cleanup_files_on_ev3",
"(",
")",
":",
"list",
"=",
"get_base_ev3dev_cmd",
"(",
")",
"+",
"[",
"'cleanup'",
"]",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"env",
"[",
"\"PYTHONUSERBASE\"",
"]",
"=",
"THONNY_USER_BASE",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"list",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
"universal_newlines",
"=",
"True",
",",
"env",
"=",
"env",
")",
"dlg",
"=",
"MySubprocessDialog",
"(",
"get_workbench",
"(",
")",
",",
"proc",
",",
"\"Delete files in homedir on EV3\"",
",",
"autoclose",
"=",
"False",
")",
"dlg",
".",
"wait_window",
"(",
")"
] | cleanup files in homedir on EV3. | [
"cleanup",
"files",
"in",
"homedir",
"on",
"EV3",
"."
] | train | https://github.com/harcokuppens/thonny-ev3dev/blob/e3437d7716068976faf2146c6bb0332ed56a1760/thonnycontrib/ev3dev/__init__.py#L541-L551 |
harcokuppens/thonny-ev3dev | thonnycontrib/ev3dev/__init__.py | load_plugin | def load_plugin():
"""Adds EV3 buttons on toolbar and commands under Run and Tools menu. Add EV3 configuration window."""
# Add EV3 configuration window
workbench=get_workbench()
workbench.set_default("ev3.ip", "192.168.0.1")
workbench.set_default("ev3.username", "robot")
workbench.set_default("ev3.password", "maker")
workbench.add_configuration_page("EV3", Ev3ConfigurationPage)
# icons
image_path_remoterun = os.path.join(os.path.dirname(__file__), "res", "remoterun.gif")
image_path_remotedebug = os.path.join(os.path.dirname(__file__), "res", "remotedebug.gif")
image_path_upload = os.path.join(os.path.dirname(__file__), "res", "up.gif")
image_path_run = os.path.join(os.path.dirname(__file__), "res", "flash.gif")
image_path_log = os.path.join(os.path.dirname(__file__), "res", "log.gif")
image_path_clean = os.path.join(os.path.dirname(__file__), "res", "clean.gif")
# menu buttons
get_workbench().add_command("ev3remoterun", "run", "Run current script using the EV3 API in remote control mode" ,
get_button_handler_for_magiccmd_on_current_file("Ev3RemoteRun"),
currentscript_and_command_enabled,
default_sequence="<F9>",
group=20,
image_filename=image_path_remoterun,
include_in_toolbar=True)
get_workbench().add_command("ev3remotedebug", "run", "Debug current script using the EV3 API in remote control mode" ,
get_button_handler_for_magiccmd_on_current_file("Ev3RemoteDebug"),
currentscript_and_command_enabled,
default_sequence="<Control-F9>",
group=20,
image_filename=image_path_remotedebug,
include_in_toolbar=True)
get_workbench().add_command("ev3patch", "tools", "Install ev3dev additions to the ev3dev sdcard on the EV3",
patch_ev3,
command_enabled,
default_sequence=None,
group=270,
#image_filename=image_path_upload,
include_in_toolbar=False)
get_workbench().add_command("ev3softreset", "tools", "Soft reset the EV3 (stop programs,rpyc started sound/motors,restart brickman and rpycd service)",
soft_reset_ev3,
command_enabled,
default_sequence=None,
group=275,
#image_filename=image_path_clean,
include_in_toolbar=False)
get_workbench().add_command("ev3upload", "tools", "Upload current script to EV3",
upload_current_script,
currentscript_and_command_enabled,
default_sequence="<F10>",
group=280,
image_filename=image_path_upload,
include_in_toolbar=True)
get_workbench().add_command("ev3run", "tools", "Start current script on the EV3",
start_current_script,
currentscript_and_command_enabled,
default_sequence="<Control-F10>",
group=280,
image_filename=image_path_run,
include_in_toolbar=True)
get_workbench().add_command("ev3log", "tools", "Download log of current script from EV3",
download_log_of_current_script,
currentscript_and_command_enabled,
default_sequence=None,
group=280,
image_filename=image_path_log,
include_in_toolbar=True)
get_workbench().add_command("ev3clean", "tools", "Cleanup EV3 by deleting all files stored in homedir on EV3",
cleanup_files_on_ev3,
command_enabled,
default_sequence=None,
group=290,
image_filename=image_path_clean,
include_in_toolbar=True)
orig_interrupt_backend=get_runner().interrupt_backend
def wrapped_interrupt_backend():
# kill program on pc
orig_interrupt_backend()
# stop programmings running on ev3 and stop sound/motors via rpyc
stop_ev3_programs__and__rpyc_motors_sound()
get_runner().interrupt_backend = wrapped_interrupt_backend
# magic commands
shell = get_workbench().get_view("ShellView")
shell.add_command("Ev3RemoteRun", _handle_rundebug_from_shell)
shell.add_command("Ev3RemoteDebug", _handle_rundebug_from_shell)
shell.add_command("Reset", _handle_reset_from_shell)
shell.add_command("pwd", _handle_pwd_from_shell)
shell.add_command("cd", _handle_cd_from_shell)
shell.add_command("ls", _handle_ls_from_shell)
shell.add_command("help", _handle_help_from_shell)
shell.add_command("open", _handle_open_from_shell)
shell.add_command("reload", _handle_reload_from_shell) | python | def load_plugin():
"""Adds EV3 buttons on toolbar and commands under Run and Tools menu. Add EV3 configuration window."""
# Add EV3 configuration window
workbench=get_workbench()
workbench.set_default("ev3.ip", "192.168.0.1")
workbench.set_default("ev3.username", "robot")
workbench.set_default("ev3.password", "maker")
workbench.add_configuration_page("EV3", Ev3ConfigurationPage)
# icons
image_path_remoterun = os.path.join(os.path.dirname(__file__), "res", "remoterun.gif")
image_path_remotedebug = os.path.join(os.path.dirname(__file__), "res", "remotedebug.gif")
image_path_upload = os.path.join(os.path.dirname(__file__), "res", "up.gif")
image_path_run = os.path.join(os.path.dirname(__file__), "res", "flash.gif")
image_path_log = os.path.join(os.path.dirname(__file__), "res", "log.gif")
image_path_clean = os.path.join(os.path.dirname(__file__), "res", "clean.gif")
# menu buttons
get_workbench().add_command("ev3remoterun", "run", "Run current script using the EV3 API in remote control mode" ,
get_button_handler_for_magiccmd_on_current_file("Ev3RemoteRun"),
currentscript_and_command_enabled,
default_sequence="<F9>",
group=20,
image_filename=image_path_remoterun,
include_in_toolbar=True)
get_workbench().add_command("ev3remotedebug", "run", "Debug current script using the EV3 API in remote control mode" ,
get_button_handler_for_magiccmd_on_current_file("Ev3RemoteDebug"),
currentscript_and_command_enabled,
default_sequence="<Control-F9>",
group=20,
image_filename=image_path_remotedebug,
include_in_toolbar=True)
get_workbench().add_command("ev3patch", "tools", "Install ev3dev additions to the ev3dev sdcard on the EV3",
patch_ev3,
command_enabled,
default_sequence=None,
group=270,
#image_filename=image_path_upload,
include_in_toolbar=False)
get_workbench().add_command("ev3softreset", "tools", "Soft reset the EV3 (stop programs,rpyc started sound/motors,restart brickman and rpycd service)",
soft_reset_ev3,
command_enabled,
default_sequence=None,
group=275,
#image_filename=image_path_clean,
include_in_toolbar=False)
get_workbench().add_command("ev3upload", "tools", "Upload current script to EV3",
upload_current_script,
currentscript_and_command_enabled,
default_sequence="<F10>",
group=280,
image_filename=image_path_upload,
include_in_toolbar=True)
get_workbench().add_command("ev3run", "tools", "Start current script on the EV3",
start_current_script,
currentscript_and_command_enabled,
default_sequence="<Control-F10>",
group=280,
image_filename=image_path_run,
include_in_toolbar=True)
get_workbench().add_command("ev3log", "tools", "Download log of current script from EV3",
download_log_of_current_script,
currentscript_and_command_enabled,
default_sequence=None,
group=280,
image_filename=image_path_log,
include_in_toolbar=True)
get_workbench().add_command("ev3clean", "tools", "Cleanup EV3 by deleting all files stored in homedir on EV3",
cleanup_files_on_ev3,
command_enabled,
default_sequence=None,
group=290,
image_filename=image_path_clean,
include_in_toolbar=True)
orig_interrupt_backend=get_runner().interrupt_backend
def wrapped_interrupt_backend():
# kill program on pc
orig_interrupt_backend()
# stop programmings running on ev3 and stop sound/motors via rpyc
stop_ev3_programs__and__rpyc_motors_sound()
get_runner().interrupt_backend = wrapped_interrupt_backend
# magic commands
shell = get_workbench().get_view("ShellView")
shell.add_command("Ev3RemoteRun", _handle_rundebug_from_shell)
shell.add_command("Ev3RemoteDebug", _handle_rundebug_from_shell)
shell.add_command("Reset", _handle_reset_from_shell)
shell.add_command("pwd", _handle_pwd_from_shell)
shell.add_command("cd", _handle_cd_from_shell)
shell.add_command("ls", _handle_ls_from_shell)
shell.add_command("help", _handle_help_from_shell)
shell.add_command("open", _handle_open_from_shell)
shell.add_command("reload", _handle_reload_from_shell) | [
"def",
"load_plugin",
"(",
")",
":",
"# Add EV3 configuration window",
"workbench",
"=",
"get_workbench",
"(",
")",
"workbench",
".",
"set_default",
"(",
"\"ev3.ip\"",
",",
"\"192.168.0.1\"",
")",
"workbench",
".",
"set_default",
"(",
"\"ev3.username\"",
",",
"\"robot\"",
")",
"workbench",
".",
"set_default",
"(",
"\"ev3.password\"",
",",
"\"maker\"",
")",
"workbench",
".",
"add_configuration_page",
"(",
"\"EV3\"",
",",
"Ev3ConfigurationPage",
")",
"# icons",
"image_path_remoterun",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"res\"",
",",
"\"remoterun.gif\"",
")",
"image_path_remotedebug",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"res\"",
",",
"\"remotedebug.gif\"",
")",
"image_path_upload",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"res\"",
",",
"\"up.gif\"",
")",
"image_path_run",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"res\"",
",",
"\"flash.gif\"",
")",
"image_path_log",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"res\"",
",",
"\"log.gif\"",
")",
"image_path_clean",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"res\"",
",",
"\"clean.gif\"",
")",
"# menu buttons",
"get_workbench",
"(",
")",
".",
"add_command",
"(",
"\"ev3remoterun\"",
",",
"\"run\"",
",",
"\"Run current script using the EV3 API in remote control mode\"",
",",
"get_button_handler_for_magiccmd_on_current_file",
"(",
"\"Ev3RemoteRun\"",
")",
",",
"currentscript_and_command_enabled",
",",
"default_sequence",
"=",
"\"<F9>\"",
",",
"group",
"=",
"20",
",",
"image_filename",
"=",
"image_path_remoterun",
",",
"include_in_toolbar",
"=",
"True",
")",
"get_workbench",
"(",
")",
".",
"add_command",
"(",
"\"ev3remotedebug\"",
",",
"\"run\"",
",",
"\"Debug current script using the EV3 API in remote control mode\"",
",",
"get_button_handler_for_magiccmd_on_current_file",
"(",
"\"Ev3RemoteDebug\"",
")",
",",
"currentscript_and_command_enabled",
",",
"default_sequence",
"=",
"\"<Control-F9>\"",
",",
"group",
"=",
"20",
",",
"image_filename",
"=",
"image_path_remotedebug",
",",
"include_in_toolbar",
"=",
"True",
")",
"get_workbench",
"(",
")",
".",
"add_command",
"(",
"\"ev3patch\"",
",",
"\"tools\"",
",",
"\"Install ev3dev additions to the ev3dev sdcard on the EV3\"",
",",
"patch_ev3",
",",
"command_enabled",
",",
"default_sequence",
"=",
"None",
",",
"group",
"=",
"270",
",",
"#image_filename=image_path_upload,",
"include_in_toolbar",
"=",
"False",
")",
"get_workbench",
"(",
")",
".",
"add_command",
"(",
"\"ev3softreset\"",
",",
"\"tools\"",
",",
"\"Soft reset the EV3 (stop programs,rpyc started sound/motors,restart brickman and rpycd service)\"",
",",
"soft_reset_ev3",
",",
"command_enabled",
",",
"default_sequence",
"=",
"None",
",",
"group",
"=",
"275",
",",
"#image_filename=image_path_clean,",
"include_in_toolbar",
"=",
"False",
")",
"get_workbench",
"(",
")",
".",
"add_command",
"(",
"\"ev3upload\"",
",",
"\"tools\"",
",",
"\"Upload current script to EV3\"",
",",
"upload_current_script",
",",
"currentscript_and_command_enabled",
",",
"default_sequence",
"=",
"\"<F10>\"",
",",
"group",
"=",
"280",
",",
"image_filename",
"=",
"image_path_upload",
",",
"include_in_toolbar",
"=",
"True",
")",
"get_workbench",
"(",
")",
".",
"add_command",
"(",
"\"ev3run\"",
",",
"\"tools\"",
",",
"\"Start current script on the EV3\"",
",",
"start_current_script",
",",
"currentscript_and_command_enabled",
",",
"default_sequence",
"=",
"\"<Control-F10>\"",
",",
"group",
"=",
"280",
",",
"image_filename",
"=",
"image_path_run",
",",
"include_in_toolbar",
"=",
"True",
")",
"get_workbench",
"(",
")",
".",
"add_command",
"(",
"\"ev3log\"",
",",
"\"tools\"",
",",
"\"Download log of current script from EV3\"",
",",
"download_log_of_current_script",
",",
"currentscript_and_command_enabled",
",",
"default_sequence",
"=",
"None",
",",
"group",
"=",
"280",
",",
"image_filename",
"=",
"image_path_log",
",",
"include_in_toolbar",
"=",
"True",
")",
"get_workbench",
"(",
")",
".",
"add_command",
"(",
"\"ev3clean\"",
",",
"\"tools\"",
",",
"\"Cleanup EV3 by deleting all files stored in homedir on EV3\"",
",",
"cleanup_files_on_ev3",
",",
"command_enabled",
",",
"default_sequence",
"=",
"None",
",",
"group",
"=",
"290",
",",
"image_filename",
"=",
"image_path_clean",
",",
"include_in_toolbar",
"=",
"True",
")",
"orig_interrupt_backend",
"=",
"get_runner",
"(",
")",
".",
"interrupt_backend",
"def",
"wrapped_interrupt_backend",
"(",
")",
":",
"# kill program on pc",
"orig_interrupt_backend",
"(",
")",
"# stop programmings running on ev3 and stop sound/motors via rpyc",
"stop_ev3_programs__and__rpyc_motors_sound",
"(",
")",
"get_runner",
"(",
")",
".",
"interrupt_backend",
"=",
"wrapped_interrupt_backend",
"# magic commands",
"shell",
"=",
"get_workbench",
"(",
")",
".",
"get_view",
"(",
"\"ShellView\"",
")",
"shell",
".",
"add_command",
"(",
"\"Ev3RemoteRun\"",
",",
"_handle_rundebug_from_shell",
")",
"shell",
".",
"add_command",
"(",
"\"Ev3RemoteDebug\"",
",",
"_handle_rundebug_from_shell",
")",
"shell",
".",
"add_command",
"(",
"\"Reset\"",
",",
"_handle_reset_from_shell",
")",
"shell",
".",
"add_command",
"(",
"\"pwd\"",
",",
"_handle_pwd_from_shell",
")",
"shell",
".",
"add_command",
"(",
"\"cd\"",
",",
"_handle_cd_from_shell",
")",
"shell",
".",
"add_command",
"(",
"\"ls\"",
",",
"_handle_ls_from_shell",
")",
"shell",
".",
"add_command",
"(",
"\"help\"",
",",
"_handle_help_from_shell",
")",
"shell",
".",
"add_command",
"(",
"\"open\"",
",",
"_handle_open_from_shell",
")",
"shell",
".",
"add_command",
"(",
"\"reload\"",
",",
"_handle_reload_from_shell",
")"
] | Adds EV3 buttons on toolbar and commands under Run and Tools menu. Add EV3 configuration window. | [
"Adds",
"EV3",
"buttons",
"on",
"toolbar",
"and",
"commands",
"under",
"Run",
"and",
"Tools",
"menu",
".",
"Add",
"EV3",
"configuration",
"window",
"."
] | train | https://github.com/harcokuppens/thonny-ev3dev/blob/e3437d7716068976faf2146c6bb0332ed56a1760/thonnycontrib/ev3dev/__init__.py#L686-L808 |
jasonkeene/python-ubersmith | ubersmith/__init__.py | init | def init(base_url, username=None, password=None, verify=True):
"""Initialize ubersmith API module with HTTP request handler."""
handler = RequestHandler(base_url, username, password, verify)
set_default_request_handler(handler)
return handler | python | def init(base_url, username=None, password=None, verify=True):
"""Initialize ubersmith API module with HTTP request handler."""
handler = RequestHandler(base_url, username, password, verify)
set_default_request_handler(handler)
return handler | [
"def",
"init",
"(",
"base_url",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"verify",
"=",
"True",
")",
":",
"handler",
"=",
"RequestHandler",
"(",
"base_url",
",",
"username",
",",
"password",
",",
"verify",
")",
"set_default_request_handler",
"(",
"handler",
")",
"return",
"handler"
] | Initialize ubersmith API module with HTTP request handler. | [
"Initialize",
"ubersmith",
"API",
"module",
"with",
"HTTP",
"request",
"handler",
"."
] | train | https://github.com/jasonkeene/python-ubersmith/blob/0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a/ubersmith/__init__.py#L34-L38 |
i3visio/deepify | deepify/utils/configuration.py | getConfigPath | def getConfigPath(configFileName = None):
"""
Auxiliar function to get the configuration path depending on the system.
"""
if configFileName != None:
# Returning the path of the configuration file
if sys.platform == 'win32':
return os.path.expanduser(os.path.join('~\\', 'Deepify', configFileName))
else:
return os.path.expanduser(os.path.join('~/', '.config', 'Deepify', configFileName))
else:
# Returning the path of the configuration folder
if sys.platform == 'win32':
return os.path.expanduser(os.path.join('~\\', 'Deepify'))
else:
return os.path.expanduser(os.path.join('~/', '.config', 'Deepify')) | python | def getConfigPath(configFileName = None):
"""
Auxiliar function to get the configuration path depending on the system.
"""
if configFileName != None:
# Returning the path of the configuration file
if sys.platform == 'win32':
return os.path.expanduser(os.path.join('~\\', 'Deepify', configFileName))
else:
return os.path.expanduser(os.path.join('~/', '.config', 'Deepify', configFileName))
else:
# Returning the path of the configuration folder
if sys.platform == 'win32':
return os.path.expanduser(os.path.join('~\\', 'Deepify'))
else:
return os.path.expanduser(os.path.join('~/', '.config', 'Deepify')) | [
"def",
"getConfigPath",
"(",
"configFileName",
"=",
"None",
")",
":",
"if",
"configFileName",
"!=",
"None",
":",
"# Returning the path of the configuration file",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"return",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'~\\\\'",
",",
"'Deepify'",
",",
"configFileName",
")",
")",
"else",
":",
"return",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'~/'",
",",
"'.config'",
",",
"'Deepify'",
",",
"configFileName",
")",
")",
"else",
":",
"# Returning the path of the configuration folder",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"return",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'~\\\\'",
",",
"'Deepify'",
")",
")",
"else",
":",
"return",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'~/'",
",",
"'.config'",
",",
"'Deepify'",
")",
")"
] | Auxiliar function to get the configuration path depending on the system. | [
"Auxiliar",
"function",
"to",
"get",
"the",
"configuration",
"path",
"depending",
"on",
"the",
"system",
"."
] | train | https://github.com/i3visio/deepify/blob/2af04e0bea3eaabe96b0565e10f7eeb29b042a2b/deepify/utils/configuration.py#L59-L74 |
i3visio/deepify | deepify/utils/configuration.py | getConfiguration | def getConfiguration(configPath = None):
"""
Reading the configuration file to look for where the different gates are running.
:return: A json containing the information stored in the .cfg file.
"""
if configPath == None:
# If a current.cfg has not been found, creating it by copying from default
configPath = getConfigPath("browser.cfg")
# Checking if the configuration file exists
if not os.path.exists(configPath):
try:
# Copy the data from the default folder
defaultConfigPath = getConfigPath(os.path.join("default", "browser.cfg"))
with open(configPath, "w") as oF:
with open(defaultConfigPath) as iF:
cont = iF.read()
oF.write(cont)
except Exception, e:
errMsg = "ERROR. No configuration file could be found and the default file was not found either. You might need to reset it manually."
raise Exception( errMsg + " " + str(e))
try:
# Reading the configuration file
config = ConfigParser.ConfigParser()
config.read(configPath)
info = {}
# Iterating through all the sections, which contain the platforms
for section in config.sections():
current = {}
# Iterating through parametgers
for (param, value) in config.items(section):
current[param] = value
# Loading the configuration in the info dictionary
info[section] = current
except Exception, e:
errMsg = "ERROR. Something happened when processing the Configuration file (some kind of malform?). Check it before running it again."
raise Exception( errMsg + " " + str(e))
return info | python | def getConfiguration(configPath = None):
"""
Reading the configuration file to look for where the different gates are running.
:return: A json containing the information stored in the .cfg file.
"""
if configPath == None:
# If a current.cfg has not been found, creating it by copying from default
configPath = getConfigPath("browser.cfg")
# Checking if the configuration file exists
if not os.path.exists(configPath):
try:
# Copy the data from the default folder
defaultConfigPath = getConfigPath(os.path.join("default", "browser.cfg"))
with open(configPath, "w") as oF:
with open(defaultConfigPath) as iF:
cont = iF.read()
oF.write(cont)
except Exception, e:
errMsg = "ERROR. No configuration file could be found and the default file was not found either. You might need to reset it manually."
raise Exception( errMsg + " " + str(e))
try:
# Reading the configuration file
config = ConfigParser.ConfigParser()
config.read(configPath)
info = {}
# Iterating through all the sections, which contain the platforms
for section in config.sections():
current = {}
# Iterating through parametgers
for (param, value) in config.items(section):
current[param] = value
# Loading the configuration in the info dictionary
info[section] = current
except Exception, e:
errMsg = "ERROR. Something happened when processing the Configuration file (some kind of malform?). Check it before running it again."
raise Exception( errMsg + " " + str(e))
return info | [
"def",
"getConfiguration",
"(",
"configPath",
"=",
"None",
")",
":",
"if",
"configPath",
"==",
"None",
":",
"# If a current.cfg has not been found, creating it by copying from default",
"configPath",
"=",
"getConfigPath",
"(",
"\"browser.cfg\"",
")",
"# Checking if the configuration file exists",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"configPath",
")",
":",
"try",
":",
"# Copy the data from the default folder",
"defaultConfigPath",
"=",
"getConfigPath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"\"default\"",
",",
"\"browser.cfg\"",
")",
")",
"with",
"open",
"(",
"configPath",
",",
"\"w\"",
")",
"as",
"oF",
":",
"with",
"open",
"(",
"defaultConfigPath",
")",
"as",
"iF",
":",
"cont",
"=",
"iF",
".",
"read",
"(",
")",
"oF",
".",
"write",
"(",
"cont",
")",
"except",
"Exception",
",",
"e",
":",
"errMsg",
"=",
"\"ERROR. No configuration file could be found and the default file was not found either. You might need to reset it manually.\"",
"raise",
"Exception",
"(",
"errMsg",
"+",
"\" \"",
"+",
"str",
"(",
"e",
")",
")",
"try",
":",
"# Reading the configuration file",
"config",
"=",
"ConfigParser",
".",
"ConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"configPath",
")",
"info",
"=",
"{",
"}",
"# Iterating through all the sections, which contain the platforms",
"for",
"section",
"in",
"config",
".",
"sections",
"(",
")",
":",
"current",
"=",
"{",
"}",
"# Iterating through parametgers",
"for",
"(",
"param",
",",
"value",
")",
"in",
"config",
".",
"items",
"(",
"section",
")",
":",
"current",
"[",
"param",
"]",
"=",
"value",
"# Loading the configuration in the info dictionary",
"info",
"[",
"section",
"]",
"=",
"current",
"except",
"Exception",
",",
"e",
":",
"errMsg",
"=",
"\"ERROR. Something happened when processing the Configuration file (some kind of malform?). Check it before running it again.\"",
"raise",
"Exception",
"(",
"errMsg",
"+",
"\" \"",
"+",
"str",
"(",
"e",
")",
")",
"return",
"info"
] | Reading the configuration file to look for where the different gates are running.
:return: A json containing the information stored in the .cfg file. | [
"Reading",
"the",
"configuration",
"file",
"to",
"look",
"for",
"where",
"the",
"different",
"gates",
"are",
"running",
".",
":",
"return",
":",
"A",
"json",
"containing",
"the",
"information",
"stored",
"in",
"the",
".",
"cfg",
"file",
"."
] | train | https://github.com/i3visio/deepify/blob/2af04e0bea3eaabe96b0565e10f7eeb29b042a2b/deepify/utils/configuration.py#L76-L122 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_utils.py | new_log_file | def new_log_file(logger, suffix, file_type='tcl'):
""" Create new logger and log file from existing logger.
The new logger will be create in the same directory as the existing logger file and will be named
as the existing log file with the requested suffix.
:param logger: existing logger
:param suffix: string to add to the existing log file name to create the new log file name.
:param file_type: logger file type (tcl. txt. etc.)
:return: the newly created logger
"""
file_handler = None
for handler in logger.handlers:
if isinstance(handler, logging.FileHandler):
file_handler = handler
new_logger = logging.getLogger(file_type + suffix)
if file_handler:
logger_file_name = path.splitext(file_handler.baseFilename)[0]
tcl_logger_file_name = logger_file_name + '-' + suffix + '.' + file_type
new_logger.addHandler(logging.FileHandler(tcl_logger_file_name, 'w'))
new_logger.setLevel(logger.getEffectiveLevel())
return new_logger | python | def new_log_file(logger, suffix, file_type='tcl'):
""" Create new logger and log file from existing logger.
The new logger will be create in the same directory as the existing logger file and will be named
as the existing log file with the requested suffix.
:param logger: existing logger
:param suffix: string to add to the existing log file name to create the new log file name.
:param file_type: logger file type (tcl. txt. etc.)
:return: the newly created logger
"""
file_handler = None
for handler in logger.handlers:
if isinstance(handler, logging.FileHandler):
file_handler = handler
new_logger = logging.getLogger(file_type + suffix)
if file_handler:
logger_file_name = path.splitext(file_handler.baseFilename)[0]
tcl_logger_file_name = logger_file_name + '-' + suffix + '.' + file_type
new_logger.addHandler(logging.FileHandler(tcl_logger_file_name, 'w'))
new_logger.setLevel(logger.getEffectiveLevel())
return new_logger | [
"def",
"new_log_file",
"(",
"logger",
",",
"suffix",
",",
"file_type",
"=",
"'tcl'",
")",
":",
"file_handler",
"=",
"None",
"for",
"handler",
"in",
"logger",
".",
"handlers",
":",
"if",
"isinstance",
"(",
"handler",
",",
"logging",
".",
"FileHandler",
")",
":",
"file_handler",
"=",
"handler",
"new_logger",
"=",
"logging",
".",
"getLogger",
"(",
"file_type",
"+",
"suffix",
")",
"if",
"file_handler",
":",
"logger_file_name",
"=",
"path",
".",
"splitext",
"(",
"file_handler",
".",
"baseFilename",
")",
"[",
"0",
"]",
"tcl_logger_file_name",
"=",
"logger_file_name",
"+",
"'-'",
"+",
"suffix",
"+",
"'.'",
"+",
"file_type",
"new_logger",
".",
"addHandler",
"(",
"logging",
".",
"FileHandler",
"(",
"tcl_logger_file_name",
",",
"'w'",
")",
")",
"new_logger",
".",
"setLevel",
"(",
"logger",
".",
"getEffectiveLevel",
"(",
")",
")",
"return",
"new_logger"
] | Create new logger and log file from existing logger.
The new logger will be create in the same directory as the existing logger file and will be named
as the existing log file with the requested suffix.
:param logger: existing logger
:param suffix: string to add to the existing log file name to create the new log file name.
:param file_type: logger file type (tcl. txt. etc.)
:return: the newly created logger | [
"Create",
"new",
"logger",
"and",
"log",
"file",
"from",
"existing",
"logger",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_utils.py#L81-L104 |
jasonkeene/python-ubersmith | ubersmith/api.py | RequestHandler.process_request | def process_request(self, method, data=None):
"""Process request over HTTP to ubersmith instance.
method: Ubersmith API method string
data: dict of method arguments
"""
# make sure requested method is valid
self._validate_request_method(method)
# attempt the request multiple times
attempts = 3
for i in range(attempts):
response = self._send_request(method, data)
# handle case where ubersmith is 'updating token'
# see: https://github.com/jasonkeene/python-ubersmith/issues/1
if self._is_token_response(response):
if i < attempts - 1:
# wait 2 secs before retrying request
time.sleep(2)
continue
else:
raise UpdatingTokenResponse
break
resp = BaseResponse(response)
# test for error in json response
if response.headers.get('content-type') == 'application/json':
if not resp.json.get('status'):
if all([
resp.json.get('error_code') == 1,
resp.json.get('error_message') == u"We are currently "
"undergoing maintenance, please check back shortly.",
]):
raise MaintenanceResponse(response=resp.json)
else:
raise ResponseError(response=resp.json)
return resp | python | def process_request(self, method, data=None):
"""Process request over HTTP to ubersmith instance.
method: Ubersmith API method string
data: dict of method arguments
"""
# make sure requested method is valid
self._validate_request_method(method)
# attempt the request multiple times
attempts = 3
for i in range(attempts):
response = self._send_request(method, data)
# handle case where ubersmith is 'updating token'
# see: https://github.com/jasonkeene/python-ubersmith/issues/1
if self._is_token_response(response):
if i < attempts - 1:
# wait 2 secs before retrying request
time.sleep(2)
continue
else:
raise UpdatingTokenResponse
break
resp = BaseResponse(response)
# test for error in json response
if response.headers.get('content-type') == 'application/json':
if not resp.json.get('status'):
if all([
resp.json.get('error_code') == 1,
resp.json.get('error_message') == u"We are currently "
"undergoing maintenance, please check back shortly.",
]):
raise MaintenanceResponse(response=resp.json)
else:
raise ResponseError(response=resp.json)
return resp | [
"def",
"process_request",
"(",
"self",
",",
"method",
",",
"data",
"=",
"None",
")",
":",
"# make sure requested method is valid",
"self",
".",
"_validate_request_method",
"(",
"method",
")",
"# attempt the request multiple times",
"attempts",
"=",
"3",
"for",
"i",
"in",
"range",
"(",
"attempts",
")",
":",
"response",
"=",
"self",
".",
"_send_request",
"(",
"method",
",",
"data",
")",
"# handle case where ubersmith is 'updating token'",
"# see: https://github.com/jasonkeene/python-ubersmith/issues/1",
"if",
"self",
".",
"_is_token_response",
"(",
"response",
")",
":",
"if",
"i",
"<",
"attempts",
"-",
"1",
":",
"# wait 2 secs before retrying request",
"time",
".",
"sleep",
"(",
"2",
")",
"continue",
"else",
":",
"raise",
"UpdatingTokenResponse",
"break",
"resp",
"=",
"BaseResponse",
"(",
"response",
")",
"# test for error in json response",
"if",
"response",
".",
"headers",
".",
"get",
"(",
"'content-type'",
")",
"==",
"'application/json'",
":",
"if",
"not",
"resp",
".",
"json",
".",
"get",
"(",
"'status'",
")",
":",
"if",
"all",
"(",
"[",
"resp",
".",
"json",
".",
"get",
"(",
"'error_code'",
")",
"==",
"1",
",",
"resp",
".",
"json",
".",
"get",
"(",
"'error_message'",
")",
"==",
"u\"We are currently \"",
"\"undergoing maintenance, please check back shortly.\"",
",",
"]",
")",
":",
"raise",
"MaintenanceResponse",
"(",
"response",
"=",
"resp",
".",
"json",
")",
"else",
":",
"raise",
"ResponseError",
"(",
"response",
"=",
"resp",
".",
"json",
")",
"return",
"resp"
] | Process request over HTTP to ubersmith instance.
method: Ubersmith API method string
data: dict of method arguments | [
"Process",
"request",
"over",
"HTTP",
"to",
"ubersmith",
"instance",
"."
] | train | https://github.com/jasonkeene/python-ubersmith/blob/0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a/ubersmith/api.py#L253-L292 |
jasonkeene/python-ubersmith | ubersmith/api.py | RequestHandler._encode_data | def _encode_data(data):
"""URL encode data."""
data = data if data is not None else {}
data = to_nested_php_args(data)
files = dict([
(key, value) for key, value in
data.items() if isinstance(value, file_type)])
for fname in files:
del data[fname]
return data, files or None, None | python | def _encode_data(data):
"""URL encode data."""
data = data if data is not None else {}
data = to_nested_php_args(data)
files = dict([
(key, value) for key, value in
data.items() if isinstance(value, file_type)])
for fname in files:
del data[fname]
return data, files or None, None | [
"def",
"_encode_data",
"(",
"data",
")",
":",
"data",
"=",
"data",
"if",
"data",
"is",
"not",
"None",
"else",
"{",
"}",
"data",
"=",
"to_nested_php_args",
"(",
"data",
")",
"files",
"=",
"dict",
"(",
"[",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
"if",
"isinstance",
"(",
"value",
",",
"file_type",
")",
"]",
")",
"for",
"fname",
"in",
"files",
":",
"del",
"data",
"[",
"fname",
"]",
"return",
"data",
",",
"files",
"or",
"None",
",",
"None"
] | URL encode data. | [
"URL",
"encode",
"data",
"."
] | train | https://github.com/jasonkeene/python-ubersmith/blob/0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a/ubersmith/api.py#L313-L322 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObjectsDict.dumps | def dumps(self, indent=1):
""" Returns nested string representation of the dictionary (like json.dumps).
:param indent: indentation level.
"""
str_keys_dict = OrderedDict({str(k): v for k, v in self.items()})
for k, v in str_keys_dict.items():
if isinstance(v, dict):
str_keys_dict[k] = OrderedDict({str(k1): v1 for k1, v1 in v.items()})
for k1, v1 in str_keys_dict[k].items():
if isinstance(v1, dict):
str_keys_dict[k][k1] = OrderedDict({str(k2): v2 for k2, v2 in v1.items()})
return json.dumps(str_keys_dict, indent=indent) | python | def dumps(self, indent=1):
""" Returns nested string representation of the dictionary (like json.dumps).
:param indent: indentation level.
"""
str_keys_dict = OrderedDict({str(k): v for k, v in self.items()})
for k, v in str_keys_dict.items():
if isinstance(v, dict):
str_keys_dict[k] = OrderedDict({str(k1): v1 for k1, v1 in v.items()})
for k1, v1 in str_keys_dict[k].items():
if isinstance(v1, dict):
str_keys_dict[k][k1] = OrderedDict({str(k2): v2 for k2, v2 in v1.items()})
return json.dumps(str_keys_dict, indent=indent) | [
"def",
"dumps",
"(",
"self",
",",
"indent",
"=",
"1",
")",
":",
"str_keys_dict",
"=",
"OrderedDict",
"(",
"{",
"str",
"(",
"k",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
"}",
")",
"for",
"k",
",",
"v",
"in",
"str_keys_dict",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"str_keys_dict",
"[",
"k",
"]",
"=",
"OrderedDict",
"(",
"{",
"str",
"(",
"k1",
")",
":",
"v1",
"for",
"k1",
",",
"v1",
"in",
"v",
".",
"items",
"(",
")",
"}",
")",
"for",
"k1",
",",
"v1",
"in",
"str_keys_dict",
"[",
"k",
"]",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v1",
",",
"dict",
")",
":",
"str_keys_dict",
"[",
"k",
"]",
"[",
"k1",
"]",
"=",
"OrderedDict",
"(",
"{",
"str",
"(",
"k2",
")",
":",
"v2",
"for",
"k2",
",",
"v2",
"in",
"v1",
".",
"items",
"(",
")",
"}",
")",
"return",
"json",
".",
"dumps",
"(",
"str_keys_dict",
",",
"indent",
"=",
"indent",
")"
] | Returns nested string representation of the dictionary (like json.dumps).
:param indent: indentation level. | [
"Returns",
"nested",
"string",
"representation",
"of",
"the",
"dictionary",
"(",
"like",
"json",
".",
"dumps",
")",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L44-L57 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_child | def get_child(self, *types):
"""
:param types: list of requested types.
:return: the first (and in most useful cases only) child of specific type(s).
"""
children = list(self.get_children(*types))
return children[0] if any(children) else None | python | def get_child(self, *types):
"""
:param types: list of requested types.
:return: the first (and in most useful cases only) child of specific type(s).
"""
children = list(self.get_children(*types))
return children[0] if any(children) else None | [
"def",
"get_child",
"(",
"self",
",",
"*",
"types",
")",
":",
"children",
"=",
"list",
"(",
"self",
".",
"get_children",
"(",
"*",
"types",
")",
")",
"return",
"children",
"[",
"0",
"]",
"if",
"any",
"(",
"children",
")",
"else",
"None"
] | :param types: list of requested types.
:return: the first (and in most useful cases only) child of specific type(s). | [
":",
"param",
"types",
":",
"list",
"of",
"requested",
"types",
".",
":",
"return",
":",
"the",
"first",
"(",
"and",
"in",
"most",
"useful",
"cases",
"only",
")",
"child",
"of",
"specific",
"type",
"(",
"s",
")",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L109-L115 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_objects_by_type | def get_objects_by_type(self, *types):
""" Returned objects stored in memory (without re-reading them from the TGN).
Use this method for fast access to objects in case of static configurations.
:param types: requested object types.
:return: all children of the specified types.
"""
if not types:
return self.objects.values()
types_l = [o.lower() for o in types]
return [o for o in self.objects.values() if o.obj_type().lower() in types_l] | python | def get_objects_by_type(self, *types):
""" Returned objects stored in memory (without re-reading them from the TGN).
Use this method for fast access to objects in case of static configurations.
:param types: requested object types.
:return: all children of the specified types.
"""
if not types:
return self.objects.values()
types_l = [o.lower() for o in types]
return [o for o in self.objects.values() if o.obj_type().lower() in types_l] | [
"def",
"get_objects_by_type",
"(",
"self",
",",
"*",
"types",
")",
":",
"if",
"not",
"types",
":",
"return",
"self",
".",
"objects",
".",
"values",
"(",
")",
"types_l",
"=",
"[",
"o",
".",
"lower",
"(",
")",
"for",
"o",
"in",
"types",
"]",
"return",
"[",
"o",
"for",
"o",
"in",
"self",
".",
"objects",
".",
"values",
"(",
")",
"if",
"o",
".",
"obj_type",
"(",
")",
".",
"lower",
"(",
")",
"in",
"types_l",
"]"
] | Returned objects stored in memory (without re-reading them from the TGN).
Use this method for fast access to objects in case of static configurations.
:param types: requested object types.
:return: all children of the specified types. | [
"Returned",
"objects",
"stored",
"in",
"memory",
"(",
"without",
"re",
"-",
"reading",
"them",
"from",
"the",
"TGN",
")",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L144-L156 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_object_by_type | def get_object_by_type(self, *types):
"""
:param types: requested object types.
:return: the child of the specified types.
"""
children = self.get_objects_by_type(*types)
return children[0] if any(children) else None | python | def get_object_by_type(self, *types):
"""
:param types: requested object types.
:return: the child of the specified types.
"""
children = self.get_objects_by_type(*types)
return children[0] if any(children) else None | [
"def",
"get_object_by_type",
"(",
"self",
",",
"*",
"types",
")",
":",
"children",
"=",
"self",
".",
"get_objects_by_type",
"(",
"*",
"types",
")",
"return",
"children",
"[",
"0",
"]",
"if",
"any",
"(",
"children",
")",
"else",
"None"
] | :param types: requested object types.
:return: the child of the specified types. | [
":",
"param",
"types",
":",
"requested",
"object",
"types",
".",
":",
"return",
":",
"the",
"child",
"of",
"the",
"specified",
"types",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L158-L164 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_objects_by_type_in_subtree | def get_objects_by_type_in_subtree(self, *types):
"""
:param types: requested object types.
:return: all children of the specified types.
"""
typed_objects = self.get_objects_by_type(*types)
for child in self.objects.values():
typed_objects += child.get_objects_by_type_in_subtree(*types)
return typed_objects | python | def get_objects_by_type_in_subtree(self, *types):
"""
:param types: requested object types.
:return: all children of the specified types.
"""
typed_objects = self.get_objects_by_type(*types)
for child in self.objects.values():
typed_objects += child.get_objects_by_type_in_subtree(*types)
return typed_objects | [
"def",
"get_objects_by_type_in_subtree",
"(",
"self",
",",
"*",
"types",
")",
":",
"typed_objects",
"=",
"self",
".",
"get_objects_by_type",
"(",
"*",
"types",
")",
"for",
"child",
"in",
"self",
".",
"objects",
".",
"values",
"(",
")",
":",
"typed_objects",
"+=",
"child",
".",
"get_objects_by_type_in_subtree",
"(",
"*",
"types",
")",
"return",
"typed_objects"
] | :param types: requested object types.
:return: all children of the specified types. | [
":",
"param",
"types",
":",
"requested",
"object",
"types",
".",
":",
"return",
":",
"all",
"children",
"of",
"the",
"specified",
"types",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L166-L175 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_objects_or_children_by_type | def get_objects_or_children_by_type(self, *types):
""" Get objects if children already been read or get children.
Use this method for fast access to objects in case of static configurations.
:param types: requested object types.
:return: all children of the specified types.
"""
objects = self.get_objects_by_type(*types)
return objects if objects else self.get_children(*types) | python | def get_objects_or_children_by_type(self, *types):
""" Get objects if children already been read or get children.
Use this method for fast access to objects in case of static configurations.
:param types: requested object types.
:return: all children of the specified types.
"""
objects = self.get_objects_by_type(*types)
return objects if objects else self.get_children(*types) | [
"def",
"get_objects_or_children_by_type",
"(",
"self",
",",
"*",
"types",
")",
":",
"objects",
"=",
"self",
".",
"get_objects_by_type",
"(",
"*",
"types",
")",
"return",
"objects",
"if",
"objects",
"else",
"self",
".",
"get_children",
"(",
"*",
"types",
")"
] | Get objects if children already been read or get children.
Use this method for fast access to objects in case of static configurations.
:param types: requested object types.
:return: all children of the specified types. | [
"Get",
"objects",
"if",
"children",
"already",
"been",
"read",
"or",
"get",
"children",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L177-L187 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_object_or_child_by_type | def get_object_or_child_by_type(self, *types):
""" Get object if child already been read or get child.
Use this method for fast access to objects in case of static configurations.
:param types: requested object types.
:return: all children of the specified types.
"""
objects = self.get_objects_or_children_by_type(*types)
return objects[0] if any(objects) else None | python | def get_object_or_child_by_type(self, *types):
""" Get object if child already been read or get child.
Use this method for fast access to objects in case of static configurations.
:param types: requested object types.
:return: all children of the specified types.
"""
objects = self.get_objects_or_children_by_type(*types)
return objects[0] if any(objects) else None | [
"def",
"get_object_or_child_by_type",
"(",
"self",
",",
"*",
"types",
")",
":",
"objects",
"=",
"self",
".",
"get_objects_or_children_by_type",
"(",
"*",
"types",
")",
"return",
"objects",
"[",
"0",
"]",
"if",
"any",
"(",
"objects",
")",
"else",
"None"
] | Get object if child already been read or get child.
Use this method for fast access to objects in case of static configurations.
:param types: requested object types.
:return: all children of the specified types. | [
"Get",
"object",
"if",
"child",
"already",
"been",
"read",
"or",
"get",
"child",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L189-L199 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_objects_with_object | def get_objects_with_object(self, obj_type, *child_types):
"""
:param obj_type: requested object type.
:param child_type: requested child types.
:return: all children of the requested type that have the requested child types.
"""
return [o for o in self.get_objects_by_type(obj_type) if
o.get_objects_by_type(*child_types)] | python | def get_objects_with_object(self, obj_type, *child_types):
"""
:param obj_type: requested object type.
:param child_type: requested child types.
:return: all children of the requested type that have the requested child types.
"""
return [o for o in self.get_objects_by_type(obj_type) if
o.get_objects_by_type(*child_types)] | [
"def",
"get_objects_with_object",
"(",
"self",
",",
"obj_type",
",",
"*",
"child_types",
")",
":",
"return",
"[",
"o",
"for",
"o",
"in",
"self",
".",
"get_objects_by_type",
"(",
"obj_type",
")",
"if",
"o",
".",
"get_objects_by_type",
"(",
"*",
"child_types",
")",
"]"
] | :param obj_type: requested object type.
:param child_type: requested child types.
:return: all children of the requested type that have the requested child types. | [
":",
"param",
"obj_type",
":",
"requested",
"object",
"type",
".",
":",
"param",
"child_type",
":",
"requested",
"child",
"types",
".",
":",
"return",
":",
"all",
"children",
"of",
"the",
"requested",
"type",
"that",
"have",
"the",
"requested",
"child",
"types",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L201-L209 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_objects_without_object | def get_objects_without_object(self, obj_type, *child_types):
"""
:param obj_type: requested object type.
:param child_type: unrequested child types.
:return: all children of the requested type that do not have the unrequested child types.
"""
return [o for o in self.get_objects_by_type(obj_type) if
not o.get_objects_by_type(*child_types)] | python | def get_objects_without_object(self, obj_type, *child_types):
"""
:param obj_type: requested object type.
:param child_type: unrequested child types.
:return: all children of the requested type that do not have the unrequested child types.
"""
return [o for o in self.get_objects_by_type(obj_type) if
not o.get_objects_by_type(*child_types)] | [
"def",
"get_objects_without_object",
"(",
"self",
",",
"obj_type",
",",
"*",
"child_types",
")",
":",
"return",
"[",
"o",
"for",
"o",
"in",
"self",
".",
"get_objects_by_type",
"(",
"obj_type",
")",
"if",
"not",
"o",
".",
"get_objects_by_type",
"(",
"*",
"child_types",
")",
"]"
] | :param obj_type: requested object type.
:param child_type: unrequested child types.
:return: all children of the requested type that do not have the unrequested child types. | [
":",
"param",
"obj_type",
":",
"requested",
"object",
"type",
".",
":",
"param",
"child_type",
":",
"unrequested",
"child",
"types",
".",
":",
"return",
":",
"all",
"children",
"of",
"the",
"requested",
"type",
"that",
"do",
"not",
"have",
"the",
"unrequested",
"child",
"types",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L211-L218 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_objects_with_attribute | def get_objects_with_attribute(self, obj_type, attribute, value):
"""
:param obj_type: requested object type.
:param attribute: requested attribute.
:param value: requested attribute value.
:return: all children of the requested type that have the requested attribute == requested value.
"""
return [o for o in self.get_objects_by_type(obj_type) if o.get_attribute(attribute) == value] | python | def get_objects_with_attribute(self, obj_type, attribute, value):
"""
:param obj_type: requested object type.
:param attribute: requested attribute.
:param value: requested attribute value.
:return: all children of the requested type that have the requested attribute == requested value.
"""
return [o for o in self.get_objects_by_type(obj_type) if o.get_attribute(attribute) == value] | [
"def",
"get_objects_with_attribute",
"(",
"self",
",",
"obj_type",
",",
"attribute",
",",
"value",
")",
":",
"return",
"[",
"o",
"for",
"o",
"in",
"self",
".",
"get_objects_by_type",
"(",
"obj_type",
")",
"if",
"o",
".",
"get_attribute",
"(",
"attribute",
")",
"==",
"value",
"]"
] | :param obj_type: requested object type.
:param attribute: requested attribute.
:param value: requested attribute value.
:return: all children of the requested type that have the requested attribute == requested value. | [
":",
"param",
"obj_type",
":",
"requested",
"object",
"type",
".",
":",
"param",
"attribute",
":",
"requested",
"attribute",
".",
":",
"param",
"value",
":",
"requested",
"attribute",
"value",
".",
":",
"return",
":",
"all",
"children",
"of",
"the",
"requested",
"type",
"that",
"have",
"the",
"requested",
"attribute",
"==",
"requested",
"value",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L220-L227 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_ancestor_object_by_type | def get_ancestor_object_by_type(self, obj_type):
"""
:param obj_type: requested ancestor type.
:return: the ancestor of the object who's type is obj_type if exists else None.
"""
if self.type.lower() == obj_type.lower():
return self
else:
if not self.parent:
return None
return self.parent.get_ancestor_object_by_type(obj_type) | python | def get_ancestor_object_by_type(self, obj_type):
"""
:param obj_type: requested ancestor type.
:return: the ancestor of the object who's type is obj_type if exists else None.
"""
if self.type.lower() == obj_type.lower():
return self
else:
if not self.parent:
return None
return self.parent.get_ancestor_object_by_type(obj_type) | [
"def",
"get_ancestor_object_by_type",
"(",
"self",
",",
"obj_type",
")",
":",
"if",
"self",
".",
"type",
".",
"lower",
"(",
")",
"==",
"obj_type",
".",
"lower",
"(",
")",
":",
"return",
"self",
"else",
":",
"if",
"not",
"self",
".",
"parent",
":",
"return",
"None",
"return",
"self",
".",
"parent",
".",
"get_ancestor_object_by_type",
"(",
"obj_type",
")"
] | :param obj_type: requested ancestor type.
:return: the ancestor of the object who's type is obj_type if exists else None. | [
":",
"param",
"obj_type",
":",
"requested",
"ancestor",
"type",
".",
":",
"return",
":",
"the",
"ancestor",
"of",
"the",
"object",
"who",
"s",
"type",
"is",
"obj_type",
"if",
"exists",
"else",
"None",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L229-L240 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.del_object_from_parent | def del_object_from_parent(self):
""" Delete object from parent object. """
if self.parent:
self.parent.objects.pop(self.ref) | python | def del_object_from_parent(self):
""" Delete object from parent object. """
if self.parent:
self.parent.objects.pop(self.ref) | [
"def",
"del_object_from_parent",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
":",
"self",
".",
"parent",
".",
"objects",
".",
"pop",
"(",
"self",
".",
"ref",
")"
] | Delete object from parent object. | [
"Delete",
"object",
"from",
"parent",
"object",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L249-L252 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_objects_of_class | def get_objects_of_class(cls):
"""
:return: all instances of the requested class.
"""
return list(o for o in gc.get_objects() if isinstance(o, cls)) | python | def get_objects_of_class(cls):
"""
:return: all instances of the requested class.
"""
return list(o for o in gc.get_objects() if isinstance(o, cls)) | [
"def",
"get_objects_of_class",
"(",
"cls",
")",
":",
"return",
"list",
"(",
"o",
"for",
"o",
"in",
"gc",
".",
"get_objects",
"(",
")",
"if",
"isinstance",
"(",
"o",
",",
"cls",
")",
")"
] | :return: all instances of the requested class. | [
":",
"return",
":",
"all",
"instances",
"of",
"the",
"requested",
"class",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L262-L266 |
harcokuppens/thonny-ev3dev | ev3devcmd_package/ev3devcmd_res/legacy/rpyc_classic__threaded_hup_reset.py | _handle_sighup | def _handle_sighup(myrpcserver, signum, unused):
"""Closes (terminates) all of its clients. Though keeps server running."""
print("SIGHUP: stopping all clients",sys.stderr)
if myrpcserver._closed:
return
for c in set(myrpcserver.clients):
try:
c.shutdown(socket.SHUT_RDWR)
except Exception:
pass
c.close()
myrpcserver.clients.clear() | python | def _handle_sighup(myrpcserver, signum, unused):
"""Closes (terminates) all of its clients. Though keeps server running."""
print("SIGHUP: stopping all clients",sys.stderr)
if myrpcserver._closed:
return
for c in set(myrpcserver.clients):
try:
c.shutdown(socket.SHUT_RDWR)
except Exception:
pass
c.close()
myrpcserver.clients.clear() | [
"def",
"_handle_sighup",
"(",
"myrpcserver",
",",
"signum",
",",
"unused",
")",
":",
"print",
"(",
"\"SIGHUP: stopping all clients\"",
",",
"sys",
".",
"stderr",
")",
"if",
"myrpcserver",
".",
"_closed",
":",
"return",
"for",
"c",
"in",
"set",
"(",
"myrpcserver",
".",
"clients",
")",
":",
"try",
":",
"c",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_RDWR",
")",
"except",
"Exception",
":",
"pass",
"c",
".",
"close",
"(",
")",
"myrpcserver",
".",
"clients",
".",
"clear",
"(",
")"
] | Closes (terminates) all of its clients. Though keeps server running. | [
"Closes",
"(",
"terminates",
")",
"all",
"of",
"its",
"clients",
".",
"Though",
"keeps",
"server",
"running",
"."
] | train | https://github.com/harcokuppens/thonny-ev3dev/blob/e3437d7716068976faf2146c6bb0332ed56a1760/ev3devcmd_package/ev3devcmd_res/legacy/rpyc_classic__threaded_hup_reset.py#L15-L26 |
moonso/extract_vcf | extract_vcf/get_annotations.py | split_strings | def split_strings(string, separators):
"""
Split a string with arbitrary number of separators.
Return a list with the splitted values
Arguments:
string (str): ex. "a:1|2,b:2"
separators (list): ex. [',',':','|']
Returns:
results (list) : ex. ['a','1','2','b','2']
"""
logger = logging.getLogger('extract_vcf.split_strings')
logger.debug("splitting string '{0}' with separators {1}".format(
string, separators
))
results = []
def recursion(recursive_string, separators, i=1):
"""
Split a string with arbitrary number of separators.
Add the elements of the string to global list result.
Arguments:
string : ex. "a:1|2,b:2"
separators (list): ex. [',',':','|']
Returns:
Adds splitted string to results. ex. ['a','1','2','b','2']
"""
if i == len(separators):
for value in recursive_string.split(separators[i-1]):
logger.debug("Adding {0} to results".format(value))
results.append(value)
else:
for value in recursive_string.split(separators[i-1]):
recursion(value, separators, i+1)
if len(separators) > 0:
recursion(string, separators)
else:
results = [string]
return results | python | def split_strings(string, separators):
"""
Split a string with arbitrary number of separators.
Return a list with the splitted values
Arguments:
string (str): ex. "a:1|2,b:2"
separators (list): ex. [',',':','|']
Returns:
results (list) : ex. ['a','1','2','b','2']
"""
logger = logging.getLogger('extract_vcf.split_strings')
logger.debug("splitting string '{0}' with separators {1}".format(
string, separators
))
results = []
def recursion(recursive_string, separators, i=1):
"""
Split a string with arbitrary number of separators.
Add the elements of the string to global list result.
Arguments:
string : ex. "a:1|2,b:2"
separators (list): ex. [',',':','|']
Returns:
Adds splitted string to results. ex. ['a','1','2','b','2']
"""
if i == len(separators):
for value in recursive_string.split(separators[i-1]):
logger.debug("Adding {0} to results".format(value))
results.append(value)
else:
for value in recursive_string.split(separators[i-1]):
recursion(value, separators, i+1)
if len(separators) > 0:
recursion(string, separators)
else:
results = [string]
return results | [
"def",
"split_strings",
"(",
"string",
",",
"separators",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'extract_vcf.split_strings'",
")",
"logger",
".",
"debug",
"(",
"\"splitting string '{0}' with separators {1}\"",
".",
"format",
"(",
"string",
",",
"separators",
")",
")",
"results",
"=",
"[",
"]",
"def",
"recursion",
"(",
"recursive_string",
",",
"separators",
",",
"i",
"=",
"1",
")",
":",
"\"\"\"\n Split a string with arbitrary number of separators.\n Add the elements of the string to global list result.\n \n Arguments:\n string : ex. \"a:1|2,b:2\"\n separators (list): ex. [',',':','|']\n \n Returns:\n Adds splitted string to results. ex. ['a','1','2','b','2']\n \"\"\"",
"if",
"i",
"==",
"len",
"(",
"separators",
")",
":",
"for",
"value",
"in",
"recursive_string",
".",
"split",
"(",
"separators",
"[",
"i",
"-",
"1",
"]",
")",
":",
"logger",
".",
"debug",
"(",
"\"Adding {0} to results\"",
".",
"format",
"(",
"value",
")",
")",
"results",
".",
"append",
"(",
"value",
")",
"else",
":",
"for",
"value",
"in",
"recursive_string",
".",
"split",
"(",
"separators",
"[",
"i",
"-",
"1",
"]",
")",
":",
"recursion",
"(",
"value",
",",
"separators",
",",
"i",
"+",
"1",
")",
"if",
"len",
"(",
"separators",
")",
">",
"0",
":",
"recursion",
"(",
"string",
",",
"separators",
")",
"else",
":",
"results",
"=",
"[",
"string",
"]",
"return",
"results"
] | Split a string with arbitrary number of separators.
Return a list with the splitted values
Arguments:
string (str): ex. "a:1|2,b:2"
separators (list): ex. [',',':','|']
Returns:
results (list) : ex. ['a','1','2','b','2'] | [
"Split",
"a",
"string",
"with",
"arbitrary",
"number",
"of",
"separators",
".",
"Return",
"a",
"list",
"with",
"the",
"splitted",
"values",
"Arguments",
":",
"string",
"(",
"str",
")",
":",
"ex",
".",
"a",
":",
"1|2",
"b",
":",
"2",
"separators",
"(",
"list",
")",
":",
"ex",
".",
"[",
":",
"|",
"]",
"Returns",
":",
"results",
"(",
"list",
")",
":",
"ex",
".",
"[",
"a",
"1",
"2",
"b",
"2",
"]"
] | train | https://github.com/moonso/extract_vcf/blob/c8381b362fa6734cd2ee65ef260738868d981aaf/extract_vcf/get_annotations.py#L6-L48 |
Nic30/pyDigitalWaveTools | pyDigitalWaveTools/vcd/writer.py | VcdVarIdScope._idToStr | def _idToStr(self, x):
"""
Convert VCD id in int to string
"""
if x < 0:
sign = -1
elif x == 0:
return self._idChars[0]
else:
sign = 1
x *= sign
digits = []
while x:
digits.append(self._idChars[x % self._idCharsCnt])
x //= self._idCharsCnt
if sign < 0:
digits.append('-')
digits.reverse()
return ''.join(digits) | python | def _idToStr(self, x):
"""
Convert VCD id in int to string
"""
if x < 0:
sign = -1
elif x == 0:
return self._idChars[0]
else:
sign = 1
x *= sign
digits = []
while x:
digits.append(self._idChars[x % self._idCharsCnt])
x //= self._idCharsCnt
if sign < 0:
digits.append('-')
digits.reverse()
return ''.join(digits) | [
"def",
"_idToStr",
"(",
"self",
",",
"x",
")",
":",
"if",
"x",
"<",
"0",
":",
"sign",
"=",
"-",
"1",
"elif",
"x",
"==",
"0",
":",
"return",
"self",
".",
"_idChars",
"[",
"0",
"]",
"else",
":",
"sign",
"=",
"1",
"x",
"*=",
"sign",
"digits",
"=",
"[",
"]",
"while",
"x",
":",
"digits",
".",
"append",
"(",
"self",
".",
"_idChars",
"[",
"x",
"%",
"self",
".",
"_idCharsCnt",
"]",
")",
"x",
"//=",
"self",
".",
"_idCharsCnt",
"if",
"sign",
"<",
"0",
":",
"digits",
".",
"append",
"(",
"'-'",
")",
"digits",
".",
"reverse",
"(",
")",
"return",
"''",
".",
"join",
"(",
"digits",
")"
] | Convert VCD id in int to string | [
"Convert",
"VCD",
"id",
"in",
"int",
"to",
"string"
] | train | https://github.com/Nic30/pyDigitalWaveTools/blob/95b96fa5f52ffd7ca916db51a4f22ee1bd9e46fc/pyDigitalWaveTools/vcd/writer.py#L31-L50 |
Nic30/pyDigitalWaveTools | pyDigitalWaveTools/vcd/writer.py | VcdVarWritingScope.addVar | def addVar(self, sig: object, name: str, sigType: VCD_SIG_TYPE, width: int,
valueFormatter: Callable[["Value"], str]):
"""
Add variable to scope
:ivar sig: user specified object to keep track of VcdVarInfo in change()
:ivar sigType: vcd type name
:ivar valueFormatter: value which converts new value in change() to vcd string
"""
vInf = self._writer._idScope.registerVariable(sig, name, self, width,
sigType, valueFormatter)
self.children[vInf.name] = vInf
self._writer._oFile.write("$var %s %d %s %s $end\n" % (
sigType, vInf.width, vInf.vcdId, vInf.name)) | python | def addVar(self, sig: object, name: str, sigType: VCD_SIG_TYPE, width: int,
valueFormatter: Callable[["Value"], str]):
"""
Add variable to scope
:ivar sig: user specified object to keep track of VcdVarInfo in change()
:ivar sigType: vcd type name
:ivar valueFormatter: value which converts new value in change() to vcd string
"""
vInf = self._writer._idScope.registerVariable(sig, name, self, width,
sigType, valueFormatter)
self.children[vInf.name] = vInf
self._writer._oFile.write("$var %s %d %s %s $end\n" % (
sigType, vInf.width, vInf.vcdId, vInf.name)) | [
"def",
"addVar",
"(",
"self",
",",
"sig",
":",
"object",
",",
"name",
":",
"str",
",",
"sigType",
":",
"VCD_SIG_TYPE",
",",
"width",
":",
"int",
",",
"valueFormatter",
":",
"Callable",
"[",
"[",
"\"Value\"",
"]",
",",
"str",
"]",
")",
":",
"vInf",
"=",
"self",
".",
"_writer",
".",
"_idScope",
".",
"registerVariable",
"(",
"sig",
",",
"name",
",",
"self",
",",
"width",
",",
"sigType",
",",
"valueFormatter",
")",
"self",
".",
"children",
"[",
"vInf",
".",
"name",
"]",
"=",
"vInf",
"self",
".",
"_writer",
".",
"_oFile",
".",
"write",
"(",
"\"$var %s %d %s %s $end\\n\"",
"%",
"(",
"sigType",
",",
"vInf",
".",
"width",
",",
"vInf",
".",
"vcdId",
",",
"vInf",
".",
"name",
")",
")"
] | Add variable to scope
:ivar sig: user specified object to keep track of VcdVarInfo in change()
:ivar sigType: vcd type name
:ivar valueFormatter: value which converts new value in change() to vcd string | [
"Add",
"variable",
"to",
"scope"
] | train | https://github.com/Nic30/pyDigitalWaveTools/blob/95b96fa5f52ffd7ca916db51a4f22ee1bd9e46fc/pyDigitalWaveTools/vcd/writer.py#L78-L91 |
Nic30/pyDigitalWaveTools | pyDigitalWaveTools/vcd/writer.py | VcdVarWritingScope.varScope | def varScope(self, name):
"""
Create sub variable scope with defined name
"""
ch = VcdVarWritingScope(name, self._writer, parent=self)
assert name not in self.children, name
self.children[name] = ch
return ch | python | def varScope(self, name):
"""
Create sub variable scope with defined name
"""
ch = VcdVarWritingScope(name, self._writer, parent=self)
assert name not in self.children, name
self.children[name] = ch
return ch | [
"def",
"varScope",
"(",
"self",
",",
"name",
")",
":",
"ch",
"=",
"VcdVarWritingScope",
"(",
"name",
",",
"self",
".",
"_writer",
",",
"parent",
"=",
"self",
")",
"assert",
"name",
"not",
"in",
"self",
".",
"children",
",",
"name",
"self",
".",
"children",
"[",
"name",
"]",
"=",
"ch",
"return",
"ch"
] | Create sub variable scope with defined name | [
"Create",
"sub",
"variable",
"scope",
"with",
"defined",
"name"
] | train | https://github.com/Nic30/pyDigitalWaveTools/blob/95b96fa5f52ffd7ca916db51a4f22ee1bd9e46fc/pyDigitalWaveTools/vcd/writer.py#L93-L100 |
i3visio/deepify | scripts/zeronetsFromFile.py | multi_run_wrapper | def multi_run_wrapper(params):
'''
Wrapper for being able to launch all the threads.
:param params: We receive the parameters as a tuple.
'''
zeronet, index, total, output_folder, overwrite = params
print "[" + str(index) + "/" + str(total) + "] ", dt.datetime.now(), ":\tRecovering information from ", onion
try:
# Reading content
zeronetWrapper = Zeronet()
domain = zeronetWrapper.getDomainFromUrl(zeronet)
# Only doing something if the Json files does NOT exist
if overwrite or not os.path.exists (os.path.join( output_folder, domain +".json")):
response = zeronetWrapper.getResponse(zeronet)
if response["status"]["code"] != 200:
print dt.datetime.now(), ":\tSomething happened when launching the query for <" + zeronet +">.\nError message: " + response["status"]["desc"]
print "[" + str(index) + "/" + str(total) + "] ", dt.datetime.now(), ":\tStoring information from", zeronet
# Storing the full processed response
with open(os.path.join( output_folder, response["domain"] +".json"), "w") as oF:
try:
oF.write(json.dumps(response, indent = 2))
except Exception, e:
# Grabbing possible exceptions that may occur when using json library...
oF.write(response)
except:
print "ERROR. SOMETHING HAPPENED WITH THE FOLLOWING DOMAIN: " + zeronet
with open("./errors.log", "a") as errorFile:
errorFile.write(zeronet+"\n") | python | def multi_run_wrapper(params):
'''
Wrapper for being able to launch all the threads.
:param params: We receive the parameters as a tuple.
'''
zeronet, index, total, output_folder, overwrite = params
print "[" + str(index) + "/" + str(total) + "] ", dt.datetime.now(), ":\tRecovering information from ", onion
try:
# Reading content
zeronetWrapper = Zeronet()
domain = zeronetWrapper.getDomainFromUrl(zeronet)
# Only doing something if the Json files does NOT exist
if overwrite or not os.path.exists (os.path.join( output_folder, domain +".json")):
response = zeronetWrapper.getResponse(zeronet)
if response["status"]["code"] != 200:
print dt.datetime.now(), ":\tSomething happened when launching the query for <" + zeronet +">.\nError message: " + response["status"]["desc"]
print "[" + str(index) + "/" + str(total) + "] ", dt.datetime.now(), ":\tStoring information from", zeronet
# Storing the full processed response
with open(os.path.join( output_folder, response["domain"] +".json"), "w") as oF:
try:
oF.write(json.dumps(response, indent = 2))
except Exception, e:
# Grabbing possible exceptions that may occur when using json library...
oF.write(response)
except:
print "ERROR. SOMETHING HAPPENED WITH THE FOLLOWING DOMAIN: " + zeronet
with open("./errors.log", "a") as errorFile:
errorFile.write(zeronet+"\n") | [
"def",
"multi_run_wrapper",
"(",
"params",
")",
":",
"zeronet",
",",
"index",
",",
"total",
",",
"output_folder",
",",
"overwrite",
"=",
"params",
"print",
"\"[\"",
"+",
"str",
"(",
"index",
")",
"+",
"\"/\"",
"+",
"str",
"(",
"total",
")",
"+",
"\"] \"",
",",
"dt",
".",
"datetime",
".",
"now",
"(",
")",
",",
"\":\\tRecovering information from \"",
",",
"onion",
"try",
":",
"# Reading content",
"zeronetWrapper",
"=",
"Zeronet",
"(",
")",
"domain",
"=",
"zeronetWrapper",
".",
"getDomainFromUrl",
"(",
"zeronet",
")",
"# Only doing something if the Json files does NOT exist ",
"if",
"overwrite",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"output_folder",
",",
"domain",
"+",
"\".json\"",
")",
")",
":",
"response",
"=",
"zeronetWrapper",
".",
"getResponse",
"(",
"zeronet",
")",
"if",
"response",
"[",
"\"status\"",
"]",
"[",
"\"code\"",
"]",
"!=",
"200",
":",
"print",
"dt",
".",
"datetime",
".",
"now",
"(",
")",
",",
"\":\\tSomething happened when launching the query for <\"",
"+",
"zeronet",
"+",
"\">.\\nError message: \"",
"+",
"response",
"[",
"\"status\"",
"]",
"[",
"\"desc\"",
"]",
"print",
"\"[\"",
"+",
"str",
"(",
"index",
")",
"+",
"\"/\"",
"+",
"str",
"(",
"total",
")",
"+",
"\"] \"",
",",
"dt",
".",
"datetime",
".",
"now",
"(",
")",
",",
"\":\\tStoring information from\"",
",",
"zeronet",
"# Storing the full processed response",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"output_folder",
",",
"response",
"[",
"\"domain\"",
"]",
"+",
"\".json\"",
")",
",",
"\"w\"",
")",
"as",
"oF",
":",
"try",
":",
"oF",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"response",
",",
"indent",
"=",
"2",
")",
")",
"except",
"Exception",
",",
"e",
":",
"# Grabbing possible exceptions that may occur when using json library...",
"oF",
".",
"write",
"(",
"response",
")",
"except",
":",
"print",
"\"ERROR. SOMETHING HAPPENED WITH THE FOLLOWING DOMAIN: \"",
"+",
"zeronet",
"with",
"open",
"(",
"\"./errors.log\"",
",",
"\"a\"",
")",
"as",
"errorFile",
":",
"errorFile",
".",
"write",
"(",
"zeronet",
"+",
"\"\\n\"",
")"
] | Wrapper for being able to launch all the threads.
:param params: We receive the parameters as a tuple. | [
"Wrapper",
"for",
"being",
"able",
"to",
"launch",
"all",
"the",
"threads",
".",
":",
"param",
"params",
":",
"We",
"receive",
"the",
"parameters",
"as",
"a",
"tuple",
"."
] | train | https://github.com/i3visio/deepify/blob/2af04e0bea3eaabe96b0565e10f7eeb29b042a2b/scripts/zeronetsFromFile.py#L47-L79 |
i3visio/deepify | scripts/zeronetsFromFile.py | main | def main(args):
"""
Main function.
"""
urls = []
# Grabbing all possible URL
with open(args.file) as iF:
urls = iF.read().splitlines()
# Creating the output folder if it does not exist.
if not os.path.exists(args.output_folder):
os.makedirs(args.output_folder)
# Using threads in a pool if we are not running the program in main
zeronets = []
for i, url in enumerate(urls):
zeronets.append((url, i+1, len(urls), args.output_folder, args.overwrite))
# If the process is executed by the current app, we use the Processes. It is faster than pools.
if args.threads <= 0 or args.threads > len(zeronets):
nThreads = len(zeronets)
else:
nThreads = args.threads
# Launching the Pool
# ------------------
#logger.info("Launching " + str(nThreads) + " different threads...")
# We define the pool
pool = Pool(nThreads)
# We call the wrapping function with all the args previously generated
poolResults = pool.map(multi_run_wrapper,zeronets)
pool.close() | python | def main(args):
"""
Main function.
"""
urls = []
# Grabbing all possible URL
with open(args.file) as iF:
urls = iF.read().splitlines()
# Creating the output folder if it does not exist.
if not os.path.exists(args.output_folder):
os.makedirs(args.output_folder)
# Using threads in a pool if we are not running the program in main
zeronets = []
for i, url in enumerate(urls):
zeronets.append((url, i+1, len(urls), args.output_folder, args.overwrite))
# If the process is executed by the current app, we use the Processes. It is faster than pools.
if args.threads <= 0 or args.threads > len(zeronets):
nThreads = len(zeronets)
else:
nThreads = args.threads
# Launching the Pool
# ------------------
#logger.info("Launching " + str(nThreads) + " different threads...")
# We define the pool
pool = Pool(nThreads)
# We call the wrapping function with all the args previously generated
poolResults = pool.map(multi_run_wrapper,zeronets)
pool.close() | [
"def",
"main",
"(",
"args",
")",
":",
"urls",
"=",
"[",
"]",
"# Grabbing all possible URL",
"with",
"open",
"(",
"args",
".",
"file",
")",
"as",
"iF",
":",
"urls",
"=",
"iF",
".",
"read",
"(",
")",
".",
"splitlines",
"(",
")",
"# Creating the output folder if it does not exist.",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"args",
".",
"output_folder",
")",
":",
"os",
".",
"makedirs",
"(",
"args",
".",
"output_folder",
")",
"# Using threads in a pool if we are not running the program in main",
"zeronets",
"=",
"[",
"]",
"for",
"i",
",",
"url",
"in",
"enumerate",
"(",
"urls",
")",
":",
"zeronets",
".",
"append",
"(",
"(",
"url",
",",
"i",
"+",
"1",
",",
"len",
"(",
"urls",
")",
",",
"args",
".",
"output_folder",
",",
"args",
".",
"overwrite",
")",
")",
"# If the process is executed by the current app, we use the Processes. It is faster than pools.",
"if",
"args",
".",
"threads",
"<=",
"0",
"or",
"args",
".",
"threads",
">",
"len",
"(",
"zeronets",
")",
":",
"nThreads",
"=",
"len",
"(",
"zeronets",
")",
"else",
":",
"nThreads",
"=",
"args",
".",
"threads",
"# Launching the Pool",
"# ------------------",
"#logger.info(\"Launching \" + str(nThreads) + \" different threads...\")",
"# We define the pool",
"pool",
"=",
"Pool",
"(",
"nThreads",
")",
"# We call the wrapping function with all the args previously generated",
"poolResults",
"=",
"pool",
".",
"map",
"(",
"multi_run_wrapper",
",",
"zeronets",
")",
"pool",
".",
"close",
"(",
")"
] | Main function. | [
"Main",
"function",
"."
] | train | https://github.com/i3visio/deepify/blob/2af04e0bea3eaabe96b0565e10f7eeb29b042a2b/scripts/zeronetsFromFile.py#L81-L116 |
i3visio/deepify | deepify/utils/wrapper.py | Wrapper._getConfiguration | def _getConfiguration(self):
"""
Method that abstracts the extraction of grabbing the configuration.
:return: the applicable configuration settings.
"""
info =configuration.getConfiguration()
try:
# This returns only the parameters needed by each wrapper. E. g., for Tor:
# {
# "host" : "127.0.0.1"
# "port" : "9150"
# }
return info[self.name]
except KeyError, e:
errMsg = "ERROR. WTF! There was not found any configuration for " + self.name + " in the configuration file!"
raise Exception( errMsg ) | python | def _getConfiguration(self):
"""
Method that abstracts the extraction of grabbing the configuration.
:return: the applicable configuration settings.
"""
info =configuration.getConfiguration()
try:
# This returns only the parameters needed by each wrapper. E. g., for Tor:
# {
# "host" : "127.0.0.1"
# "port" : "9150"
# }
return info[self.name]
except KeyError, e:
errMsg = "ERROR. WTF! There was not found any configuration for " + self.name + " in the configuration file!"
raise Exception( errMsg ) | [
"def",
"_getConfiguration",
"(",
"self",
")",
":",
"info",
"=",
"configuration",
".",
"getConfiguration",
"(",
")",
"try",
":",
"# This returns only the parameters needed by each wrapper. E. g., for Tor:",
"# {",
"# \"host\" : \"127.0.0.1\"",
"# \"port\" : \"9150\"",
"# } ",
"return",
"info",
"[",
"self",
".",
"name",
"]",
"except",
"KeyError",
",",
"e",
":",
"errMsg",
"=",
"\"ERROR. WTF! There was not found any configuration for \"",
"+",
"self",
".",
"name",
"+",
"\" in the configuration file!\"",
"raise",
"Exception",
"(",
"errMsg",
")"
] | Method that abstracts the extraction of grabbing the configuration.
:return: the applicable configuration settings. | [
"Method",
"that",
"abstracts",
"the",
"extraction",
"of",
"grabbing",
"the",
"configuration",
".",
":",
"return",
":",
"the",
"applicable",
"configuration",
"settings",
"."
] | train | https://github.com/i3visio/deepify/blob/2af04e0bea3eaabe96b0565e10f7eeb29b042a2b/deepify/utils/wrapper.py#L42-L60 |
i3visio/deepify | deepify/utils/wrapper.py | Wrapper.getDomainFromUrl | def getDomainFromUrl(self, url):
"""
Extracting the domain from the URL.
:return: domain as a string.
"""
try:
domain = re.findall( self.domainRegexp, url )[0]
except Exception, e:
errMsg = "ERROR. Something happened when trying to find the domain from <" + url + ">. Are you sure that the following regular expression matches a domain in the url provided?\n\t" + self.domainRegexp
raise Exception( errMsg + "\n" + str(e) )
return domain | python | def getDomainFromUrl(self, url):
"""
Extracting the domain from the URL.
:return: domain as a string.
"""
try:
domain = re.findall( self.domainRegexp, url )[0]
except Exception, e:
errMsg = "ERROR. Something happened when trying to find the domain from <" + url + ">. Are you sure that the following regular expression matches a domain in the url provided?\n\t" + self.domainRegexp
raise Exception( errMsg + "\n" + str(e) )
return domain | [
"def",
"getDomainFromUrl",
"(",
"self",
",",
"url",
")",
":",
"try",
":",
"domain",
"=",
"re",
".",
"findall",
"(",
"self",
".",
"domainRegexp",
",",
"url",
")",
"[",
"0",
"]",
"except",
"Exception",
",",
"e",
":",
"errMsg",
"=",
"\"ERROR. Something happened when trying to find the domain from <\"",
"+",
"url",
"+",
"\">. Are you sure that the following regular expression matches a domain in the url provided?\\n\\t\"",
"+",
"self",
".",
"domainRegexp",
"raise",
"Exception",
"(",
"errMsg",
"+",
"\"\\n\"",
"+",
"str",
"(",
"e",
")",
")",
"return",
"domain"
] | Extracting the domain from the URL.
:return: domain as a string. | [
"Extracting",
"the",
"domain",
"from",
"the",
"URL",
".",
":",
"return",
":",
"domain",
"as",
"a",
"string",
"."
] | train | https://github.com/i3visio/deepify/blob/2af04e0bea3eaabe96b0565e10f7eeb29b042a2b/deepify/utils/wrapper.py#L62-L74 |
i3visio/deepify | deepify/utils/wrapper.py | Wrapper._createDataStructure | def _createDataStructure(self, content):
"""
This method receives a response, including headers, and creates the appropriate structure.
:param url: The URL to be recovered.
:param content: The content of the response.
:return: A json.
"""
aux = {}
aux["headers"] = {}
aux["content"] = ""
for i, line in enumerate(content.splitlines()):
if i == 0:
aux["procotol"] = line.split()[0]
aux["code"] = line.split()[1]
elif line != "":
header = line.split(": ")[0]
aux["headers"][header] = line[line.find(": ")+2:]
else:
aux["content"] += self._rebuildHTMLContent(content.splitlines()[i+1:])
# TO-DO: Perform additional processing of the HTML
break
return aux | python | def _createDataStructure(self, content):
"""
This method receives a response, including headers, and creates the appropriate structure.
:param url: The URL to be recovered.
:param content: The content of the response.
:return: A json.
"""
aux = {}
aux["headers"] = {}
aux["content"] = ""
for i, line in enumerate(content.splitlines()):
if i == 0:
aux["procotol"] = line.split()[0]
aux["code"] = line.split()[1]
elif line != "":
header = line.split(": ")[0]
aux["headers"][header] = line[line.find(": ")+2:]
else:
aux["content"] += self._rebuildHTMLContent(content.splitlines()[i+1:])
# TO-DO: Perform additional processing of the HTML
break
return aux | [
"def",
"_createDataStructure",
"(",
"self",
",",
"content",
")",
":",
"aux",
"=",
"{",
"}",
"aux",
"[",
"\"headers\"",
"]",
"=",
"{",
"}",
"aux",
"[",
"\"content\"",
"]",
"=",
"\"\"",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"content",
".",
"splitlines",
"(",
")",
")",
":",
"if",
"i",
"==",
"0",
":",
"aux",
"[",
"\"procotol\"",
"]",
"=",
"line",
".",
"split",
"(",
")",
"[",
"0",
"]",
"aux",
"[",
"\"code\"",
"]",
"=",
"line",
".",
"split",
"(",
")",
"[",
"1",
"]",
"elif",
"line",
"!=",
"\"\"",
":",
"header",
"=",
"line",
".",
"split",
"(",
"\": \"",
")",
"[",
"0",
"]",
"aux",
"[",
"\"headers\"",
"]",
"[",
"header",
"]",
"=",
"line",
"[",
"line",
".",
"find",
"(",
"\": \"",
")",
"+",
"2",
":",
"]",
"else",
":",
"aux",
"[",
"\"content\"",
"]",
"+=",
"self",
".",
"_rebuildHTMLContent",
"(",
"content",
".",
"splitlines",
"(",
")",
"[",
"i",
"+",
"1",
":",
"]",
")",
"# TO-DO: Perform additional processing of the HTML",
"break",
"return",
"aux"
] | This method receives a response, including headers, and creates the appropriate structure.
:param url: The URL to be recovered.
:param content: The content of the response.
:return: A json. | [
"This",
"method",
"receives",
"a",
"response",
"including",
"headers",
"and",
"creates",
"the",
"appropriate",
"structure",
".",
":",
"param",
"url",
":",
"The",
"URL",
"to",
"be",
"recovered",
".",
":",
"param",
"content",
":",
"The",
"content",
"of",
"the",
"response",
".",
":",
"return",
":",
"A",
"json",
"."
] | train | https://github.com/i3visio/deepify/blob/2af04e0bea3eaabe96b0565e10f7eeb29b042a2b/deepify/utils/wrapper.py#L87-L111 |
i3visio/deepify | deepify/utils/wrapper.py | Wrapper._grabContentFromUrl | def _grabContentFromUrl(self, url):
"""
Function that abstracts capturing a URL. This method will be rewritten in child classes.
:param url: The URL to be processed.
:return: The response in a Json format.
"""
# Defining an empty object for the response
response = {}
# This part has to be modified...
try:
import urllib2
# Grabbing the data
data = urllib2.urlopen(url).read()
# Processing the data as expectesd
response = self._createDataStructure(data)
# Try to make the errors clear for other users
except Exception, e:
errMsg = "ERROR. Something happened."
raise Exception( errMsg + " " + str(e))
return response | python | def _grabContentFromUrl(self, url):
"""
Function that abstracts capturing a URL. This method will be rewritten in child classes.
:param url: The URL to be processed.
:return: The response in a Json format.
"""
# Defining an empty object for the response
response = {}
# This part has to be modified...
try:
import urllib2
# Grabbing the data
data = urllib2.urlopen(url).read()
# Processing the data as expectesd
response = self._createDataStructure(data)
# Try to make the errors clear for other users
except Exception, e:
errMsg = "ERROR. Something happened."
raise Exception( errMsg + " " + str(e))
return response | [
"def",
"_grabContentFromUrl",
"(",
"self",
",",
"url",
")",
":",
"# Defining an empty object for the response",
"response",
"=",
"{",
"}",
"# This part has to be modified... ",
"try",
":",
"import",
"urllib2",
"# Grabbing the data ",
"data",
"=",
"urllib2",
".",
"urlopen",
"(",
"url",
")",
".",
"read",
"(",
")",
"# Processing the data as expectesd",
"response",
"=",
"self",
".",
"_createDataStructure",
"(",
"data",
")",
"# Try to make the errors clear for other users",
"except",
"Exception",
",",
"e",
":",
"errMsg",
"=",
"\"ERROR. Something happened.\"",
"raise",
"Exception",
"(",
"errMsg",
"+",
"\" \"",
"+",
"str",
"(",
"e",
")",
")",
"return",
"response"
] | Function that abstracts capturing a URL. This method will be rewritten in child classes.
:param url: The URL to be processed.
:return: The response in a Json format. | [
"Function",
"that",
"abstracts",
"capturing",
"a",
"URL",
".",
"This",
"method",
"will",
"be",
"rewritten",
"in",
"child",
"classes",
".",
":",
"param",
"url",
":",
"The",
"URL",
"to",
"be",
"processed",
".",
":",
"return",
":",
"The",
"response",
"in",
"a",
"Json",
"format",
"."
] | train | https://github.com/i3visio/deepify/blob/2af04e0bea3eaabe96b0565e10f7eeb29b042a2b/deepify/utils/wrapper.py#L113-L138 |
i3visio/deepify | deepify/utils/wrapper.py | Wrapper.getResponse | def getResponse(self, url):
"""
Public method that wraps the extraction of the content.
:param url: The resource to be processed.
:return: The response in a Json format.
"""
# Defining an empty object for the response
response = {}
try:
# This receives only the parameters needed by this Tor Wrapper:
# {
# "host" : "127.0.0.1"
# "port" : "9150"
# }
self.info = self._getConfiguration()
response = self._grabContentFromUrl(url)
except Exception, e:
response["status"] = { "code" : 400, "desc" : str(e) }
# Adding other known data
response["time_processed"] = str(dt.datetime.now())
response["domain"] = self.getDomainFromUrl(url)
response["url"] = url
try:
# We'll check if something happened...
response["status"]
except Exception, e:
# If nothing happened till now, we'll set the code as 200
response["status"] = { "code" : 200, "desc" : "OK." }
return response | python | def getResponse(self, url):
"""
Public method that wraps the extraction of the content.
:param url: The resource to be processed.
:return: The response in a Json format.
"""
# Defining an empty object for the response
response = {}
try:
# This receives only the parameters needed by this Tor Wrapper:
# {
# "host" : "127.0.0.1"
# "port" : "9150"
# }
self.info = self._getConfiguration()
response = self._grabContentFromUrl(url)
except Exception, e:
response["status"] = { "code" : 400, "desc" : str(e) }
# Adding other known data
response["time_processed"] = str(dt.datetime.now())
response["domain"] = self.getDomainFromUrl(url)
response["url"] = url
try:
# We'll check if something happened...
response["status"]
except Exception, e:
# If nothing happened till now, we'll set the code as 200
response["status"] = { "code" : 200, "desc" : "OK." }
return response | [
"def",
"getResponse",
"(",
"self",
",",
"url",
")",
":",
"# Defining an empty object for the response",
"response",
"=",
"{",
"}",
"try",
":",
"# This receives only the parameters needed by this Tor Wrapper:",
"# {",
"# \"host\" : \"127.0.0.1\"",
"# \"port\" : \"9150\"",
"# } ",
"self",
".",
"info",
"=",
"self",
".",
"_getConfiguration",
"(",
")",
"response",
"=",
"self",
".",
"_grabContentFromUrl",
"(",
"url",
")",
"except",
"Exception",
",",
"e",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"{",
"\"code\"",
":",
"400",
",",
"\"desc\"",
":",
"str",
"(",
"e",
")",
"}",
"# Adding other known data ",
"response",
"[",
"\"time_processed\"",
"]",
"=",
"str",
"(",
"dt",
".",
"datetime",
".",
"now",
"(",
")",
")",
"response",
"[",
"\"domain\"",
"]",
"=",
"self",
".",
"getDomainFromUrl",
"(",
"url",
")",
"response",
"[",
"\"url\"",
"]",
"=",
"url",
"try",
":",
"# We'll check if something happened... ",
"response",
"[",
"\"status\"",
"]",
"except",
"Exception",
",",
"e",
":",
"# If nothing happened till now, we'll set the code as 200 ",
"response",
"[",
"\"status\"",
"]",
"=",
"{",
"\"code\"",
":",
"200",
",",
"\"desc\"",
":",
"\"OK.\"",
"}",
"return",
"response"
] | Public method that wraps the extraction of the content.
:param url: The resource to be processed.
:return: The response in a Json format. | [
"Public",
"method",
"that",
"wraps",
"the",
"extraction",
"of",
"the",
"content",
".",
":",
"param",
"url",
":",
"The",
"resource",
"to",
"be",
"processed",
".",
":",
"return",
":",
"The",
"response",
"in",
"a",
"Json",
"format",
"."
] | train | https://github.com/i3visio/deepify/blob/2af04e0bea3eaabe96b0565e10f7eeb29b042a2b/deepify/utils/wrapper.py#L140-L174 |
jasonkeene/python-ubersmith | ubersmith/utils.py | append_qs | def append_qs(url, query_string):
"""Append query_string values to an existing URL and return it as a string.
query_string can be:
* an encoded string: 'test3=val1&test3=val2'
* a dict of strings: {'test3': 'val'}
* a dict of lists of strings: {'test3': ['val1', 'val2']}
* a list of tuples: [('test3', 'val1'), ('test3', 'val2')]
"""
parsed_url = urlsplit(url)
parsed_qs = parse_qsl(parsed_url.query, True)
if isstr(query_string):
parsed_qs += parse_qsl(query_string)
elif isdict(query_string):
for item in list(query_string.items()):
if islist(item[1]):
for val in item[1]:
parsed_qs.append((item[0], val))
else:
parsed_qs.append(item)
elif islist(query_string):
parsed_qs += query_string
else:
raise TypeError('Unexpected query_string type')
return urlunsplit((
parsed_url.scheme,
parsed_url.netloc,
parsed_url.path,
urlencode_unicode(parsed_qs),
parsed_url.fragment,
)) | python | def append_qs(url, query_string):
"""Append query_string values to an existing URL and return it as a string.
query_string can be:
* an encoded string: 'test3=val1&test3=val2'
* a dict of strings: {'test3': 'val'}
* a dict of lists of strings: {'test3': ['val1', 'val2']}
* a list of tuples: [('test3', 'val1'), ('test3', 'val2')]
"""
parsed_url = urlsplit(url)
parsed_qs = parse_qsl(parsed_url.query, True)
if isstr(query_string):
parsed_qs += parse_qsl(query_string)
elif isdict(query_string):
for item in list(query_string.items()):
if islist(item[1]):
for val in item[1]:
parsed_qs.append((item[0], val))
else:
parsed_qs.append(item)
elif islist(query_string):
parsed_qs += query_string
else:
raise TypeError('Unexpected query_string type')
return urlunsplit((
parsed_url.scheme,
parsed_url.netloc,
parsed_url.path,
urlencode_unicode(parsed_qs),
parsed_url.fragment,
)) | [
"def",
"append_qs",
"(",
"url",
",",
"query_string",
")",
":",
"parsed_url",
"=",
"urlsplit",
"(",
"url",
")",
"parsed_qs",
"=",
"parse_qsl",
"(",
"parsed_url",
".",
"query",
",",
"True",
")",
"if",
"isstr",
"(",
"query_string",
")",
":",
"parsed_qs",
"+=",
"parse_qsl",
"(",
"query_string",
")",
"elif",
"isdict",
"(",
"query_string",
")",
":",
"for",
"item",
"in",
"list",
"(",
"query_string",
".",
"items",
"(",
")",
")",
":",
"if",
"islist",
"(",
"item",
"[",
"1",
"]",
")",
":",
"for",
"val",
"in",
"item",
"[",
"1",
"]",
":",
"parsed_qs",
".",
"append",
"(",
"(",
"item",
"[",
"0",
"]",
",",
"val",
")",
")",
"else",
":",
"parsed_qs",
".",
"append",
"(",
"item",
")",
"elif",
"islist",
"(",
"query_string",
")",
":",
"parsed_qs",
"+=",
"query_string",
"else",
":",
"raise",
"TypeError",
"(",
"'Unexpected query_string type'",
")",
"return",
"urlunsplit",
"(",
"(",
"parsed_url",
".",
"scheme",
",",
"parsed_url",
".",
"netloc",
",",
"parsed_url",
".",
"path",
",",
"urlencode_unicode",
"(",
"parsed_qs",
")",
",",
"parsed_url",
".",
"fragment",
",",
")",
")"
] | Append query_string values to an existing URL and return it as a string.
query_string can be:
* an encoded string: 'test3=val1&test3=val2'
* a dict of strings: {'test3': 'val'}
* a dict of lists of strings: {'test3': ['val1', 'val2']}
* a list of tuples: [('test3', 'val1'), ('test3', 'val2')] | [
"Append",
"query_string",
"values",
"to",
"an",
"existing",
"URL",
"and",
"return",
"it",
"as",
"a",
"string",
"."
] | train | https://github.com/jasonkeene/python-ubersmith/blob/0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a/ubersmith/utils.py#L33-L66 |
jasonkeene/python-ubersmith | ubersmith/utils.py | urlencode_unicode | def urlencode_unicode(data, doseq=0):
"""urllib.urlencode can't handle unicode, this is a hack to fix it."""
data_iter = None
if isdict(data):
data_iter = list(data.items())
elif islist(data):
data_iter = data
if data_iter:
for i, (key, value) in enumerate(data_iter):
if isinstance(value, text_type):
# try to convert to str
try:
safe_val = str(value)
except UnicodeEncodeError:
# try to encode as utf-8
# if an exception is raised here then idk what to do
safe_val = value.encode('utf-8')
finally:
if isdict(data):
data[key] = safe_val
else:
data[i] = (key, safe_val)
return urlencode(data, doseq=doseq) | python | def urlencode_unicode(data, doseq=0):
"""urllib.urlencode can't handle unicode, this is a hack to fix it."""
data_iter = None
if isdict(data):
data_iter = list(data.items())
elif islist(data):
data_iter = data
if data_iter:
for i, (key, value) in enumerate(data_iter):
if isinstance(value, text_type):
# try to convert to str
try:
safe_val = str(value)
except UnicodeEncodeError:
# try to encode as utf-8
# if an exception is raised here then idk what to do
safe_val = value.encode('utf-8')
finally:
if isdict(data):
data[key] = safe_val
else:
data[i] = (key, safe_val)
return urlencode(data, doseq=doseq) | [
"def",
"urlencode_unicode",
"(",
"data",
",",
"doseq",
"=",
"0",
")",
":",
"data_iter",
"=",
"None",
"if",
"isdict",
"(",
"data",
")",
":",
"data_iter",
"=",
"list",
"(",
"data",
".",
"items",
"(",
")",
")",
"elif",
"islist",
"(",
"data",
")",
":",
"data_iter",
"=",
"data",
"if",
"data_iter",
":",
"for",
"i",
",",
"(",
"key",
",",
"value",
")",
"in",
"enumerate",
"(",
"data_iter",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"text_type",
")",
":",
"# try to convert to str",
"try",
":",
"safe_val",
"=",
"str",
"(",
"value",
")",
"except",
"UnicodeEncodeError",
":",
"# try to encode as utf-8",
"# if an exception is raised here then idk what to do",
"safe_val",
"=",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
"finally",
":",
"if",
"isdict",
"(",
"data",
")",
":",
"data",
"[",
"key",
"]",
"=",
"safe_val",
"else",
":",
"data",
"[",
"i",
"]",
"=",
"(",
"key",
",",
"safe_val",
")",
"return",
"urlencode",
"(",
"data",
",",
"doseq",
"=",
"doseq",
")"
] | urllib.urlencode can't handle unicode, this is a hack to fix it. | [
"urllib",
".",
"urlencode",
"can",
"t",
"handle",
"unicode",
"this",
"is",
"a",
"hack",
"to",
"fix",
"it",
"."
] | train | https://github.com/jasonkeene/python-ubersmith/blob/0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a/ubersmith/utils.py#L69-L93 |
jasonkeene/python-ubersmith | ubersmith/utils.py | to_nested_php_args | def to_nested_php_args(data, prefix_key=None):
"""
This function will take either a dict or list and will recursively loop
through the values converting it into a format similar to a PHP array which
Ubersmith requires for the info portion of the API's order.create method.
"""
is_root = prefix_key is None
prefix_key = prefix_key if prefix_key else ''
if islist(data):
data_iter = data if is_root else enumerate(data)
new_data = [] if is_root else {}
elif isdict(data):
data_iter = list(data.items())
new_data = {}
else:
raise TypeError('expected dict or list, got {0}'.format(type(data)))
if islist(new_data):
def data_set(k, v):
new_data.append((k, v))
def data_update(d):
for k, v in list(d.items()):
new_data.append((k, v))
else:
def data_set(k, v):
new_data[k] = v
data_update = new_data.update
for key, value in data_iter:
end_key = prefix_key + (str(key) if is_root else '[{0}]'.format(key))
if _is_leaf(value):
data_set(end_key, value)
else:
nested_args = to_nested_php_args(value, end_key)
data_update(nested_args)
return new_data | python | def to_nested_php_args(data, prefix_key=None):
"""
This function will take either a dict or list and will recursively loop
through the values converting it into a format similar to a PHP array which
Ubersmith requires for the info portion of the API's order.create method.
"""
is_root = prefix_key is None
prefix_key = prefix_key if prefix_key else ''
if islist(data):
data_iter = data if is_root else enumerate(data)
new_data = [] if is_root else {}
elif isdict(data):
data_iter = list(data.items())
new_data = {}
else:
raise TypeError('expected dict or list, got {0}'.format(type(data)))
if islist(new_data):
def data_set(k, v):
new_data.append((k, v))
def data_update(d):
for k, v in list(d.items()):
new_data.append((k, v))
else:
def data_set(k, v):
new_data[k] = v
data_update = new_data.update
for key, value in data_iter:
end_key = prefix_key + (str(key) if is_root else '[{0}]'.format(key))
if _is_leaf(value):
data_set(end_key, value)
else:
nested_args = to_nested_php_args(value, end_key)
data_update(nested_args)
return new_data | [
"def",
"to_nested_php_args",
"(",
"data",
",",
"prefix_key",
"=",
"None",
")",
":",
"is_root",
"=",
"prefix_key",
"is",
"None",
"prefix_key",
"=",
"prefix_key",
"if",
"prefix_key",
"else",
"''",
"if",
"islist",
"(",
"data",
")",
":",
"data_iter",
"=",
"data",
"if",
"is_root",
"else",
"enumerate",
"(",
"data",
")",
"new_data",
"=",
"[",
"]",
"if",
"is_root",
"else",
"{",
"}",
"elif",
"isdict",
"(",
"data",
")",
":",
"data_iter",
"=",
"list",
"(",
"data",
".",
"items",
"(",
")",
")",
"new_data",
"=",
"{",
"}",
"else",
":",
"raise",
"TypeError",
"(",
"'expected dict or list, got {0}'",
".",
"format",
"(",
"type",
"(",
"data",
")",
")",
")",
"if",
"islist",
"(",
"new_data",
")",
":",
"def",
"data_set",
"(",
"k",
",",
"v",
")",
":",
"new_data",
".",
"append",
"(",
"(",
"k",
",",
"v",
")",
")",
"def",
"data_update",
"(",
"d",
")",
":",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"d",
".",
"items",
"(",
")",
")",
":",
"new_data",
".",
"append",
"(",
"(",
"k",
",",
"v",
")",
")",
"else",
":",
"def",
"data_set",
"(",
"k",
",",
"v",
")",
":",
"new_data",
"[",
"k",
"]",
"=",
"v",
"data_update",
"=",
"new_data",
".",
"update",
"for",
"key",
",",
"value",
"in",
"data_iter",
":",
"end_key",
"=",
"prefix_key",
"+",
"(",
"str",
"(",
"key",
")",
"if",
"is_root",
"else",
"'[{0}]'",
".",
"format",
"(",
"key",
")",
")",
"if",
"_is_leaf",
"(",
"value",
")",
":",
"data_set",
"(",
"end_key",
",",
"value",
")",
"else",
":",
"nested_args",
"=",
"to_nested_php_args",
"(",
"value",
",",
"end_key",
")",
"data_update",
"(",
"nested_args",
")",
"return",
"new_data"
] | This function will take either a dict or list and will recursively loop
through the values converting it into a format similar to a PHP array which
Ubersmith requires for the info portion of the API's order.create method. | [
"This",
"function",
"will",
"take",
"either",
"a",
"dict",
"or",
"list",
"and",
"will",
"recursively",
"loop",
"through",
"the",
"values",
"converting",
"it",
"into",
"a",
"format",
"similar",
"to",
"a",
"PHP",
"array",
"which",
"Ubersmith",
"requires",
"for",
"the",
"info",
"portion",
"of",
"the",
"API",
"s",
"order",
".",
"create",
"method",
"."
] | train | https://github.com/jasonkeene/python-ubersmith/blob/0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a/ubersmith/utils.py#L101-L138 |
jasonkeene/python-ubersmith | ubersmith/utils.py | get_filename | def get_filename(disposition):
"""Parse Content-Disposition header to pull out the filename bit.
See: http://tools.ietf.org/html/rfc2616#section-19.5.1
"""
if disposition:
params = [param.strip() for param in disposition.split(';')[1:]]
for param in params:
if '=' in param:
name, value = param.split('=', 1)
if name == 'filename':
return value.strip('"') | python | def get_filename(disposition):
"""Parse Content-Disposition header to pull out the filename bit.
See: http://tools.ietf.org/html/rfc2616#section-19.5.1
"""
if disposition:
params = [param.strip() for param in disposition.split(';')[1:]]
for param in params:
if '=' in param:
name, value = param.split('=', 1)
if name == 'filename':
return value.strip('"') | [
"def",
"get_filename",
"(",
"disposition",
")",
":",
"if",
"disposition",
":",
"params",
"=",
"[",
"param",
".",
"strip",
"(",
")",
"for",
"param",
"in",
"disposition",
".",
"split",
"(",
"';'",
")",
"[",
"1",
":",
"]",
"]",
"for",
"param",
"in",
"params",
":",
"if",
"'='",
"in",
"param",
":",
"name",
",",
"value",
"=",
"param",
".",
"split",
"(",
"'='",
",",
"1",
")",
"if",
"name",
"==",
"'filename'",
":",
"return",
"value",
".",
"strip",
"(",
"'\"'",
")"
] | Parse Content-Disposition header to pull out the filename bit.
See: http://tools.ietf.org/html/rfc2616#section-19.5.1 | [
"Parse",
"Content",
"-",
"Disposition",
"header",
"to",
"pull",
"out",
"the",
"filename",
"bit",
"."
] | train | https://github.com/jasonkeene/python-ubersmith/blob/0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a/ubersmith/utils.py#L161-L173 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_tcl.py | get_args_pairs | def get_args_pairs(arguments):
"""
:param arguments: Python dictionary of TGN API command arguments <key, value>.
:returns: Tcl list of argument pairs <-key, value> to be used in TGN API commands.
"""
return ' '.join(' '.join(['-' + k, tcl_str(str(v))]) for k, v in arguments.items()) | python | def get_args_pairs(arguments):
"""
:param arguments: Python dictionary of TGN API command arguments <key, value>.
:returns: Tcl list of argument pairs <-key, value> to be used in TGN API commands.
"""
return ' '.join(' '.join(['-' + k, tcl_str(str(v))]) for k, v in arguments.items()) | [
"def",
"get_args_pairs",
"(",
"arguments",
")",
":",
"return",
"' '",
".",
"join",
"(",
"' '",
".",
"join",
"(",
"[",
"'-'",
"+",
"k",
",",
"tcl_str",
"(",
"str",
"(",
"v",
")",
")",
"]",
")",
"for",
"k",
",",
"v",
"in",
"arguments",
".",
"items",
"(",
")",
")"
] | :param arguments: Python dictionary of TGN API command arguments <key, value>.
:returns: Tcl list of argument pairs <-key, value> to be used in TGN API commands. | [
":",
"param",
"arguments",
":",
"Python",
"dictionary",
"of",
"TGN",
"API",
"command",
"arguments",
"<key",
"value",
">",
".",
":",
"returns",
":",
"Tcl",
"list",
"of",
"argument",
"pairs",
"<",
"-",
"key",
"value",
">",
"to",
"be",
"used",
"in",
"TGN",
"API",
"commands",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_tcl.py#L46-L52 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_tcl.py | tcl_list_2_py_list | def tcl_list_2_py_list(tcl_list, within_tcl_str=False):
""" Convert Tcl list to Python list using Tcl interpreter.
:param tcl_list: string representing the Tcl string.
:param within_tcl_str: True - Tcl list is embedded within Tcl str. False - native Tcl string.
:return: Python list equivalent to the Tcl ist.
:rtye: list
"""
if not within_tcl_str:
tcl_list = tcl_str(tcl_list)
return tcl_interp_g.eval('join ' + tcl_list + ' LiStSeP').split('LiStSeP') if tcl_list else [] | python | def tcl_list_2_py_list(tcl_list, within_tcl_str=False):
""" Convert Tcl list to Python list using Tcl interpreter.
:param tcl_list: string representing the Tcl string.
:param within_tcl_str: True - Tcl list is embedded within Tcl str. False - native Tcl string.
:return: Python list equivalent to the Tcl ist.
:rtye: list
"""
if not within_tcl_str:
tcl_list = tcl_str(tcl_list)
return tcl_interp_g.eval('join ' + tcl_list + ' LiStSeP').split('LiStSeP') if tcl_list else [] | [
"def",
"tcl_list_2_py_list",
"(",
"tcl_list",
",",
"within_tcl_str",
"=",
"False",
")",
":",
"if",
"not",
"within_tcl_str",
":",
"tcl_list",
"=",
"tcl_str",
"(",
"tcl_list",
")",
"return",
"tcl_interp_g",
".",
"eval",
"(",
"'join '",
"+",
"tcl_list",
"+",
"' LiStSeP'",
")",
".",
"split",
"(",
"'LiStSeP'",
")",
"if",
"tcl_list",
"else",
"[",
"]"
] | Convert Tcl list to Python list using Tcl interpreter.
:param tcl_list: string representing the Tcl string.
:param within_tcl_str: True - Tcl list is embedded within Tcl str. False - native Tcl string.
:return: Python list equivalent to the Tcl ist.
:rtye: list | [
"Convert",
"Tcl",
"list",
"to",
"Python",
"list",
"using",
"Tcl",
"interpreter",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_tcl.py#L68-L79 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_tcl.py | py_list_to_tcl_list | def py_list_to_tcl_list(py_list):
""" Convert Python list to Tcl list using Tcl interpreter.
:param py_list: Python list.
:type py_list: list
:return: string representing the Tcl string equivalent to the Python list.
"""
py_list_str = [str(s) for s in py_list]
return tcl_str(tcl_interp_g.eval('split' + tcl_str('\t'.join(py_list_str)) + '\\t')) | python | def py_list_to_tcl_list(py_list):
""" Convert Python list to Tcl list using Tcl interpreter.
:param py_list: Python list.
:type py_list: list
:return: string representing the Tcl string equivalent to the Python list.
"""
py_list_str = [str(s) for s in py_list]
return tcl_str(tcl_interp_g.eval('split' + tcl_str('\t'.join(py_list_str)) + '\\t')) | [
"def",
"py_list_to_tcl_list",
"(",
"py_list",
")",
":",
"py_list_str",
"=",
"[",
"str",
"(",
"s",
")",
"for",
"s",
"in",
"py_list",
"]",
"return",
"tcl_str",
"(",
"tcl_interp_g",
".",
"eval",
"(",
"'split'",
"+",
"tcl_str",
"(",
"'\\t'",
".",
"join",
"(",
"py_list_str",
")",
")",
"+",
"'\\\\t'",
")",
")"
] | Convert Python list to Tcl list using Tcl interpreter.
:param py_list: Python list.
:type py_list: list
:return: string representing the Tcl string equivalent to the Python list. | [
"Convert",
"Python",
"list",
"to",
"Tcl",
"list",
"using",
"Tcl",
"interpreter",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_tcl.py#L82-L91 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_tcl.py | TgnTclConsole.eval | def eval(self, command):
"""
@summary: Evaluate Tcl command.
@param command: command to evaluate.
@return: command output.
"""
# Some operations (like take ownership) may take long time.
con_command_out = self._con.send_cmd(command, timeout=256)
if 'ERROR_SEND_CMD_EXIT_DUE_TO_TIMEOUT' in con_command_out:
raise Exception('{} - command timeout'.format(command))
command = command.replace('\\', '/')
con_command_out = con_command_out.replace('\\', '/')
command = command.replace('(', '\(').replace(')', '\)')
command = command.replace('{', '\{').replace('}', '\}')
m = re.search(command + '(.*)' + '%', con_command_out, re.DOTALL)
command_out = m.group(1).strip()
if 'couldn\'t read file' in command_out or 'RuntimeError' in command_out:
raise Exception(command_out)
return command_out | python | def eval(self, command):
"""
@summary: Evaluate Tcl command.
@param command: command to evaluate.
@return: command output.
"""
# Some operations (like take ownership) may take long time.
con_command_out = self._con.send_cmd(command, timeout=256)
if 'ERROR_SEND_CMD_EXIT_DUE_TO_TIMEOUT' in con_command_out:
raise Exception('{} - command timeout'.format(command))
command = command.replace('\\', '/')
con_command_out = con_command_out.replace('\\', '/')
command = command.replace('(', '\(').replace(')', '\)')
command = command.replace('{', '\{').replace('}', '\}')
m = re.search(command + '(.*)' + '%', con_command_out, re.DOTALL)
command_out = m.group(1).strip()
if 'couldn\'t read file' in command_out or 'RuntimeError' in command_out:
raise Exception(command_out)
return command_out | [
"def",
"eval",
"(",
"self",
",",
"command",
")",
":",
"# Some operations (like take ownership) may take long time.",
"con_command_out",
"=",
"self",
".",
"_con",
".",
"send_cmd",
"(",
"command",
",",
"timeout",
"=",
"256",
")",
"if",
"'ERROR_SEND_CMD_EXIT_DUE_TO_TIMEOUT'",
"in",
"con_command_out",
":",
"raise",
"Exception",
"(",
"'{} - command timeout'",
".",
"format",
"(",
"command",
")",
")",
"command",
"=",
"command",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"con_command_out",
"=",
"con_command_out",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"command",
"=",
"command",
".",
"replace",
"(",
"'('",
",",
"'\\('",
")",
".",
"replace",
"(",
"')'",
",",
"'\\)'",
")",
"command",
"=",
"command",
".",
"replace",
"(",
"'{'",
",",
"'\\{'",
")",
".",
"replace",
"(",
"'}'",
",",
"'\\}'",
")",
"m",
"=",
"re",
".",
"search",
"(",
"command",
"+",
"'(.*)'",
"+",
"'%'",
",",
"con_command_out",
",",
"re",
".",
"DOTALL",
")",
"command_out",
"=",
"m",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
"if",
"'couldn\\'t read file'",
"in",
"command_out",
"or",
"'RuntimeError'",
"in",
"command_out",
":",
"raise",
"Exception",
"(",
"command_out",
")",
"return",
"command_out"
] | @summary: Evaluate Tcl command.
@param command: command to evaluate.
@return: command output. | [
"@summary",
":",
"Evaluate",
"Tcl",
"command",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_tcl.py#L158-L177 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_tcl.py | TgnTclWrapper.eval | def eval(self, command):
""" Execute Tcl command.
Write the command to tcl script (.tcl) log file.
Execute the command.
Write the command and the output to general (.txt) log file.
:param command: Command to execute.
:returns: command raw output.
"""
if self.logger.handlers:
self.logger.debug(command.decode('utf-8'))
if self.tcl_script:
self.tcl_script.info(command)
self.rc = self.tcl_interp.eval(command)
if self.logger.handlers:
self.logger.debug('\t' + self.rc.decode('utf-8'))
return self.rc | python | def eval(self, command):
""" Execute Tcl command.
Write the command to tcl script (.tcl) log file.
Execute the command.
Write the command and the output to general (.txt) log file.
:param command: Command to execute.
:returns: command raw output.
"""
if self.logger.handlers:
self.logger.debug(command.decode('utf-8'))
if self.tcl_script:
self.tcl_script.info(command)
self.rc = self.tcl_interp.eval(command)
if self.logger.handlers:
self.logger.debug('\t' + self.rc.decode('utf-8'))
return self.rc | [
"def",
"eval",
"(",
"self",
",",
"command",
")",
":",
"if",
"self",
".",
"logger",
".",
"handlers",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"command",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"if",
"self",
".",
"tcl_script",
":",
"self",
".",
"tcl_script",
".",
"info",
"(",
"command",
")",
"self",
".",
"rc",
"=",
"self",
".",
"tcl_interp",
".",
"eval",
"(",
"command",
")",
"if",
"self",
".",
"logger",
".",
"handlers",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'\\t'",
"+",
"self",
".",
"rc",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"return",
"self",
".",
"rc"
] | Execute Tcl command.
Write the command to tcl script (.tcl) log file.
Execute the command.
Write the command and the output to general (.txt) log file.
:param command: Command to execute.
:returns: command raw output. | [
"Execute",
"Tcl",
"command",
"."
] | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_tcl.py#L208-L226 |
i3visio/deepify | deepify/tor.py | Tor._grabContentFromUrl | def _grabContentFromUrl(self, url):
"""
Function that abstracts capturing a URL. This method rewrites the one from Wrapper.
:param url: The URL to be processed.
:return: The response in a Json format.
"""
# Defining an empty object for the response
response = {}
# This part has to be modified...
try:
# Configuring the socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, self.info["host"], int(self.info["port"]), True)
s = socks.socksocket()
# Extracting the domain from the URL
domain = self.getDomainFromUrl(url)
s.connect((domain, 80))
message = 'GET ' + url + ' HTTP/1.0\r\n\r\n'
s.sendall(message)
data = ""
while True:
reply = s.recv(4096)
if not reply:
break
else:
data += reply
# Processing data as expected
response = self._createDataStructure(data)
# Try to make the errors clear for other users
except socks.ProxyConnectionError, sPCE:
errMsg = "ERROR socks.ProxyConnectionError. Something seems to be wrong with the Tor Bundler."
raise Exception( errMsg + " " + str(sPCE))
return response | python | def _grabContentFromUrl(self, url):
"""
Function that abstracts capturing a URL. This method rewrites the one from Wrapper.
:param url: The URL to be processed.
:return: The response in a Json format.
"""
# Defining an empty object for the response
response = {}
# This part has to be modified...
try:
# Configuring the socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, self.info["host"], int(self.info["port"]), True)
s = socks.socksocket()
# Extracting the domain from the URL
domain = self.getDomainFromUrl(url)
s.connect((domain, 80))
message = 'GET ' + url + ' HTTP/1.0\r\n\r\n'
s.sendall(message)
data = ""
while True:
reply = s.recv(4096)
if not reply:
break
else:
data += reply
# Processing data as expected
response = self._createDataStructure(data)
# Try to make the errors clear for other users
except socks.ProxyConnectionError, sPCE:
errMsg = "ERROR socks.ProxyConnectionError. Something seems to be wrong with the Tor Bundler."
raise Exception( errMsg + " " + str(sPCE))
return response | [
"def",
"_grabContentFromUrl",
"(",
"self",
",",
"url",
")",
":",
"# Defining an empty object for the response",
"response",
"=",
"{",
"}",
"# This part has to be modified... ",
"try",
":",
"# Configuring the socket",
"socks",
".",
"setdefaultproxy",
"(",
"socks",
".",
"PROXY_TYPE_SOCKS5",
",",
"self",
".",
"info",
"[",
"\"host\"",
"]",
",",
"int",
"(",
"self",
".",
"info",
"[",
"\"port\"",
"]",
")",
",",
"True",
")",
"s",
"=",
"socks",
".",
"socksocket",
"(",
")",
"# Extracting the domain from the URL",
"domain",
"=",
"self",
".",
"getDomainFromUrl",
"(",
"url",
")",
"s",
".",
"connect",
"(",
"(",
"domain",
",",
"80",
")",
")",
"message",
"=",
"'GET '",
"+",
"url",
"+",
"' HTTP/1.0\\r\\n\\r\\n'",
"s",
".",
"sendall",
"(",
"message",
")",
"data",
"=",
"\"\"",
"while",
"True",
":",
"reply",
"=",
"s",
".",
"recv",
"(",
"4096",
")",
"if",
"not",
"reply",
":",
"break",
"else",
":",
"data",
"+=",
"reply",
"# Processing data as expected",
"response",
"=",
"self",
".",
"_createDataStructure",
"(",
"data",
")",
"# Try to make the errors clear for other users",
"except",
"socks",
".",
"ProxyConnectionError",
",",
"sPCE",
":",
"errMsg",
"=",
"\"ERROR socks.ProxyConnectionError. Something seems to be wrong with the Tor Bundler.\"",
"raise",
"Exception",
"(",
"errMsg",
"+",
"\" \"",
"+",
"str",
"(",
"sPCE",
")",
")",
"return",
"response"
] | Function that abstracts capturing a URL. This method rewrites the one from Wrapper.
:param url: The URL to be processed.
:return: The response in a Json format. | [
"Function",
"that",
"abstracts",
"capturing",
"a",
"URL",
".",
"This",
"method",
"rewrites",
"the",
"one",
"from",
"Wrapper",
".",
":",
"param",
"url",
":",
"The",
"URL",
"to",
"be",
"processed",
".",
":",
"return",
":",
"The",
"response",
"in",
"a",
"Json",
"format",
"."
] | train | https://github.com/i3visio/deepify/blob/2af04e0bea3eaabe96b0565e10f7eeb29b042a2b/deepify/tor.py#L53-L93 |
Nic30/pyDigitalWaveTools | pyDigitalWaveTools/vcd/parser.py | VcdParser.value_change | def value_change(self, vcdId, value):
'''append change from VCD file signal data series'''
self.idcode2series[vcdId].append((self.now, value)) | python | def value_change(self, vcdId, value):
'''append change from VCD file signal data series'''
self.idcode2series[vcdId].append((self.now, value)) | [
"def",
"value_change",
"(",
"self",
",",
"vcdId",
",",
"value",
")",
":",
"self",
".",
"idcode2series",
"[",
"vcdId",
"]",
".",
"append",
"(",
"(",
"self",
".",
"now",
",",
"value",
")",
")"
] | append change from VCD file signal data series | [
"append",
"change",
"from",
"VCD",
"file",
"signal",
"data",
"series"
] | train | https://github.com/Nic30/pyDigitalWaveTools/blob/95b96fa5f52ffd7ca916db51a4f22ee1bd9e46fc/pyDigitalWaveTools/vcd/parser.py#L82-L84 |
Nic30/pyDigitalWaveTools | pyDigitalWaveTools/vcd/parser.py | VcdParser.parse | def parse(self, file_handle):
'''
Tokenize and parse the VCD file
:ivar file_handle: opened file with vcd string
'''
# open the VCD file and create a token generator
lineIterator = iter(enumerate(file_handle))
tokeniser = ((lineNo, word) for lineNo, line in lineIterator
for word in line.split() if word)
while True:
token = next(tokeniser)
# parse VCD until the end of definitions
self.keyword_dispatch[token[1]](tokeniser, token[1])
if self.end_of_definitions:
break
while True:
try:
lineNo, token = next(lineIterator)
except StopIteration:
break
# parse changes
c = token[0]
if c == '$':
# skip $dump* tokens and $end tokens in sim section
continue
elif c == '#':
# [TODO] may be a float
self.now = int(token[1:])
else:
sp = token.split()
sp_len = len(sp)
if sp_len == 1:
# 1 bit value
value = c
vcdId = token[1:]
elif sp_len == 2:
# vectors and strings
value, vcdId = sp
else:
raise VcdSyntaxError(
"Line %d: Don't understand: %s " % (lineNo, token))
self.value_change(vcdId.strip(), value.strip()) | python | def parse(self, file_handle):
'''
Tokenize and parse the VCD file
:ivar file_handle: opened file with vcd string
'''
# open the VCD file and create a token generator
lineIterator = iter(enumerate(file_handle))
tokeniser = ((lineNo, word) for lineNo, line in lineIterator
for word in line.split() if word)
while True:
token = next(tokeniser)
# parse VCD until the end of definitions
self.keyword_dispatch[token[1]](tokeniser, token[1])
if self.end_of_definitions:
break
while True:
try:
lineNo, token = next(lineIterator)
except StopIteration:
break
# parse changes
c = token[0]
if c == '$':
# skip $dump* tokens and $end tokens in sim section
continue
elif c == '#':
# [TODO] may be a float
self.now = int(token[1:])
else:
sp = token.split()
sp_len = len(sp)
if sp_len == 1:
# 1 bit value
value = c
vcdId = token[1:]
elif sp_len == 2:
# vectors and strings
value, vcdId = sp
else:
raise VcdSyntaxError(
"Line %d: Don't understand: %s " % (lineNo, token))
self.value_change(vcdId.strip(), value.strip()) | [
"def",
"parse",
"(",
"self",
",",
"file_handle",
")",
":",
"# open the VCD file and create a token generator",
"lineIterator",
"=",
"iter",
"(",
"enumerate",
"(",
"file_handle",
")",
")",
"tokeniser",
"=",
"(",
"(",
"lineNo",
",",
"word",
")",
"for",
"lineNo",
",",
"line",
"in",
"lineIterator",
"for",
"word",
"in",
"line",
".",
"split",
"(",
")",
"if",
"word",
")",
"while",
"True",
":",
"token",
"=",
"next",
"(",
"tokeniser",
")",
"# parse VCD until the end of definitions",
"self",
".",
"keyword_dispatch",
"[",
"token",
"[",
"1",
"]",
"]",
"(",
"tokeniser",
",",
"token",
"[",
"1",
"]",
")",
"if",
"self",
".",
"end_of_definitions",
":",
"break",
"while",
"True",
":",
"try",
":",
"lineNo",
",",
"token",
"=",
"next",
"(",
"lineIterator",
")",
"except",
"StopIteration",
":",
"break",
"# parse changes",
"c",
"=",
"token",
"[",
"0",
"]",
"if",
"c",
"==",
"'$'",
":",
"# skip $dump* tokens and $end tokens in sim section",
"continue",
"elif",
"c",
"==",
"'#'",
":",
"# [TODO] may be a float",
"self",
".",
"now",
"=",
"int",
"(",
"token",
"[",
"1",
":",
"]",
")",
"else",
":",
"sp",
"=",
"token",
".",
"split",
"(",
")",
"sp_len",
"=",
"len",
"(",
"sp",
")",
"if",
"sp_len",
"==",
"1",
":",
"# 1 bit value",
"value",
"=",
"c",
"vcdId",
"=",
"token",
"[",
"1",
":",
"]",
"elif",
"sp_len",
"==",
"2",
":",
"# vectors and strings",
"value",
",",
"vcdId",
"=",
"sp",
"else",
":",
"raise",
"VcdSyntaxError",
"(",
"\"Line %d: Don't understand: %s \"",
"%",
"(",
"lineNo",
",",
"token",
")",
")",
"self",
".",
"value_change",
"(",
"vcdId",
".",
"strip",
"(",
")",
",",
"value",
".",
"strip",
"(",
")",
")"
] | Tokenize and parse the VCD file
:ivar file_handle: opened file with vcd string | [
"Tokenize",
"and",
"parse",
"the",
"VCD",
"file"
] | train | https://github.com/Nic30/pyDigitalWaveTools/blob/95b96fa5f52ffd7ca916db51a4f22ee1bd9e46fc/pyDigitalWaveTools/vcd/parser.py#L86-L132 |
artefactual-labs/agentarchives | agentarchives/archivists_toolkit/client.py | ArchivistsToolkitClient.edit_record | def edit_record(self, new_record):
"""
Update a record in Archivist's Toolkit using the provided new_record.
The format of new_record is identical to the format returned by get_resource_component_and_children and related methods.
This means it's possible, for example, to request a record, modify the returned dict, and pass that dict to this method to update the server.
Currently supported fields are:
* title
* targetfield
:raises ValueError: if the 'id' field isn't specified, or no fields to edit were specified.
"""
try:
record_id = new_record["id"]
except KeyError:
raise ValueError("No record ID provided!")
record_type = self.resource_type(record_id)
if record_type is None:
raise ArchivistsToolkitError(
"Could not determine type for record with ID {}; not in database?".format(
record_id
)
)
clause = []
values = []
if "title" in new_record:
clause.append("title=%s")
values.append(new_record["title"])
if "levelOfDescription" in new_record:
clause.append("resourceLevel=%s")
values.append(new_record["levelOfDescription"])
# nothing to update
if not clause:
raise ValueError("No fields to update specified!")
clause = ", ".join(clause)
if record_type == ArchivistsToolkitClient.RESOURCE:
db_type = "Resources"
db_id_field = "resourceId"
else:
db_type = "ResourcesComponents"
db_id_field = "resourceComponentId"
sql = "UPDATE {} SET {} WHERE {}=%s".format(db_type, clause, db_id_field)
cursor = self.db.cursor()
cursor.execute(sql, tuple(values)) | python | def edit_record(self, new_record):
"""
Update a record in Archivist's Toolkit using the provided new_record.
The format of new_record is identical to the format returned by get_resource_component_and_children and related methods.
This means it's possible, for example, to request a record, modify the returned dict, and pass that dict to this method to update the server.
Currently supported fields are:
* title
* targetfield
:raises ValueError: if the 'id' field isn't specified, or no fields to edit were specified.
"""
try:
record_id = new_record["id"]
except KeyError:
raise ValueError("No record ID provided!")
record_type = self.resource_type(record_id)
if record_type is None:
raise ArchivistsToolkitError(
"Could not determine type for record with ID {}; not in database?".format(
record_id
)
)
clause = []
values = []
if "title" in new_record:
clause.append("title=%s")
values.append(new_record["title"])
if "levelOfDescription" in new_record:
clause.append("resourceLevel=%s")
values.append(new_record["levelOfDescription"])
# nothing to update
if not clause:
raise ValueError("No fields to update specified!")
clause = ", ".join(clause)
if record_type == ArchivistsToolkitClient.RESOURCE:
db_type = "Resources"
db_id_field = "resourceId"
else:
db_type = "ResourcesComponents"
db_id_field = "resourceComponentId"
sql = "UPDATE {} SET {} WHERE {}=%s".format(db_type, clause, db_id_field)
cursor = self.db.cursor()
cursor.execute(sql, tuple(values)) | [
"def",
"edit_record",
"(",
"self",
",",
"new_record",
")",
":",
"try",
":",
"record_id",
"=",
"new_record",
"[",
"\"id\"",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"No record ID provided!\"",
")",
"record_type",
"=",
"self",
".",
"resource_type",
"(",
"record_id",
")",
"if",
"record_type",
"is",
"None",
":",
"raise",
"ArchivistsToolkitError",
"(",
"\"Could not determine type for record with ID {}; not in database?\"",
".",
"format",
"(",
"record_id",
")",
")",
"clause",
"=",
"[",
"]",
"values",
"=",
"[",
"]",
"if",
"\"title\"",
"in",
"new_record",
":",
"clause",
".",
"append",
"(",
"\"title=%s\"",
")",
"values",
".",
"append",
"(",
"new_record",
"[",
"\"title\"",
"]",
")",
"if",
"\"levelOfDescription\"",
"in",
"new_record",
":",
"clause",
".",
"append",
"(",
"\"resourceLevel=%s\"",
")",
"values",
".",
"append",
"(",
"new_record",
"[",
"\"levelOfDescription\"",
"]",
")",
"# nothing to update",
"if",
"not",
"clause",
":",
"raise",
"ValueError",
"(",
"\"No fields to update specified!\"",
")",
"clause",
"=",
"\", \"",
".",
"join",
"(",
"clause",
")",
"if",
"record_type",
"==",
"ArchivistsToolkitClient",
".",
"RESOURCE",
":",
"db_type",
"=",
"\"Resources\"",
"db_id_field",
"=",
"\"resourceId\"",
"else",
":",
"db_type",
"=",
"\"ResourcesComponents\"",
"db_id_field",
"=",
"\"resourceComponentId\"",
"sql",
"=",
"\"UPDATE {} SET {} WHERE {}=%s\"",
".",
"format",
"(",
"db_type",
",",
"clause",
",",
"db_id_field",
")",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"sql",
",",
"tuple",
"(",
"values",
")",
")"
] | Update a record in Archivist's Toolkit using the provided new_record.
The format of new_record is identical to the format returned by get_resource_component_and_children and related methods.
This means it's possible, for example, to request a record, modify the returned dict, and pass that dict to this method to update the server.
Currently supported fields are:
* title
* targetfield
:raises ValueError: if the 'id' field isn't specified, or no fields to edit were specified. | [
"Update",
"a",
"record",
"in",
"Archivist",
"s",
"Toolkit",
"using",
"the",
"provided",
"new_record",
"."
] | train | https://github.com/artefactual-labs/agentarchives/blob/af19ade56a90c64069cf46b50972fe72b6f10a45/agentarchives/archivists_toolkit/client.py#L47-L95 |
artefactual-labs/agentarchives | agentarchives/archivists_toolkit/client.py | ArchivistsToolkitClient.get_levels_of_description | def get_levels_of_description(self):
"""
Returns an array of all levels of description defined in this Archivist's Toolkit instance.
"""
if not hasattr(self, "levels_of_description"):
cursor = self.db.cursor()
levels = set()
cursor.execute("SELECT distinct(resourceLevel) FROM Resources")
for row in cursor:
levels.add(row)
cursor.execute("SELECT distinct(resourceLevel) FROM ResourcesComponents")
for row in cursor:
levels.add(row)
self.levels_of_description = list(levels)
return self.levels_of_description | python | def get_levels_of_description(self):
"""
Returns an array of all levels of description defined in this Archivist's Toolkit instance.
"""
if not hasattr(self, "levels_of_description"):
cursor = self.db.cursor()
levels = set()
cursor.execute("SELECT distinct(resourceLevel) FROM Resources")
for row in cursor:
levels.add(row)
cursor.execute("SELECT distinct(resourceLevel) FROM ResourcesComponents")
for row in cursor:
levels.add(row)
self.levels_of_description = list(levels)
return self.levels_of_description | [
"def",
"get_levels_of_description",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"levels_of_description\"",
")",
":",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"levels",
"=",
"set",
"(",
")",
"cursor",
".",
"execute",
"(",
"\"SELECT distinct(resourceLevel) FROM Resources\"",
")",
"for",
"row",
"in",
"cursor",
":",
"levels",
".",
"add",
"(",
"row",
")",
"cursor",
".",
"execute",
"(",
"\"SELECT distinct(resourceLevel) FROM ResourcesComponents\"",
")",
"for",
"row",
"in",
"cursor",
":",
"levels",
".",
"add",
"(",
"row",
")",
"self",
".",
"levels_of_description",
"=",
"list",
"(",
"levels",
")",
"return",
"self",
".",
"levels_of_description"
] | Returns an array of all levels of description defined in this Archivist's Toolkit instance. | [
"Returns",
"an",
"array",
"of",
"all",
"levels",
"of",
"description",
"defined",
"in",
"this",
"Archivist",
"s",
"Toolkit",
"instance",
"."
] | train | https://github.com/artefactual-labs/agentarchives/blob/af19ade56a90c64069cf46b50972fe72b6f10a45/agentarchives/archivists_toolkit/client.py#L97-L112 |
artefactual-labs/agentarchives | agentarchives/archivists_toolkit/client.py | ArchivistsToolkitClient.collection_list | def collection_list(self, resource_id, resource_type="collection"):
"""
Fetches a list of all resource and component IDs within the specified resource.
:param long resource_id: The ID of the resource to fetch children from.
:param string resource_type: Specifies whether the resource to fetch is a collection or a child element.
Defaults to 'collection'.
:return: A list of longs representing the database resource IDs for all children of the requested record.
:rtype list:
"""
ret = []
cursor = self.db.cursor()
if resource_type == "collection":
cursor.execute(
"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId IS NULL AND resourceId=%s",
(resource_id),
)
else:
ret.append(resource_id)
cursor.execute(
"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId=%s",
(resource_id),
)
rows = cursor.fetchall()
if len(rows):
for row in rows:
ret.extend(self.collection_list(row[0], "description"))
return ret | python | def collection_list(self, resource_id, resource_type="collection"):
"""
Fetches a list of all resource and component IDs within the specified resource.
:param long resource_id: The ID of the resource to fetch children from.
:param string resource_type: Specifies whether the resource to fetch is a collection or a child element.
Defaults to 'collection'.
:return: A list of longs representing the database resource IDs for all children of the requested record.
:rtype list:
"""
ret = []
cursor = self.db.cursor()
if resource_type == "collection":
cursor.execute(
"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId IS NULL AND resourceId=%s",
(resource_id),
)
else:
ret.append(resource_id)
cursor.execute(
"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId=%s",
(resource_id),
)
rows = cursor.fetchall()
if len(rows):
for row in rows:
ret.extend(self.collection_list(row[0], "description"))
return ret | [
"def",
"collection_list",
"(",
"self",
",",
"resource_id",
",",
"resource_type",
"=",
"\"collection\"",
")",
":",
"ret",
"=",
"[",
"]",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"if",
"resource_type",
"==",
"\"collection\"",
":",
"cursor",
".",
"execute",
"(",
"\"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId IS NULL AND resourceId=%s\"",
",",
"(",
"resource_id",
")",
",",
")",
"else",
":",
"ret",
".",
"append",
"(",
"resource_id",
")",
"cursor",
".",
"execute",
"(",
"\"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId=%s\"",
",",
"(",
"resource_id",
")",
",",
")",
"rows",
"=",
"cursor",
".",
"fetchall",
"(",
")",
"if",
"len",
"(",
"rows",
")",
":",
"for",
"row",
"in",
"rows",
":",
"ret",
".",
"extend",
"(",
"self",
".",
"collection_list",
"(",
"row",
"[",
"0",
"]",
",",
"\"description\"",
")",
")",
"return",
"ret"
] | Fetches a list of all resource and component IDs within the specified resource.
:param long resource_id: The ID of the resource to fetch children from.
:param string resource_type: Specifies whether the resource to fetch is a collection or a child element.
Defaults to 'collection'.
:return: A list of longs representing the database resource IDs for all children of the requested record.
:rtype list: | [
"Fetches",
"a",
"list",
"of",
"all",
"resource",
"and",
"component",
"IDs",
"within",
"the",
"specified",
"resource",
"."
] | train | https://github.com/artefactual-labs/agentarchives/blob/af19ade56a90c64069cf46b50972fe72b6f10a45/agentarchives/archivists_toolkit/client.py#L114-L145 |
artefactual-labs/agentarchives | agentarchives/archivists_toolkit/client.py | ArchivistsToolkitClient.get_resource_component_and_children | def get_resource_component_and_children(
self, resource_id, resource_type="collection", level=1, sort_data={}, **kwargs
):
"""
Fetch detailed metadata for the specified resource_id and all of its children.
:param long resource_id: The resource for which to fetch metadata.
:param string resource_type: The level of description of the record.
:param int recurse_max_level: The maximum depth level to fetch when fetching children.
Default is to fetch all of the resource's children, descending as deeply as necessary.
Pass 1 to fetch no children.
:param string search_pattern: If specified, limits fetched children to those whose titles or IDs match the provided query.
See ArchivistsToolkitClient.find_collection_ids for documentation of the query format.
:return: A dict containing detailed metadata about both the requested resource and its children.
The dict follows this format:
{
'id': '31',
'type': 'resource',
'sortPosition': '1',
'identifier': 'PR01',
'title': 'Parent',
'levelOfDescription': 'collection',
'dates': '1880-1889',
'date_expression': '1880 to 1889',
'notes': [
'type': 'odd',
'content': 'This is a note',
],
'children': [{
'id': '23',
'type': 'resource_component',
'sortPosition': '2',
'identifier': 'CH01',
'title': 'Child A',
'levelOfDescription': 'Sousfonds',
'dates': '1880-1888',
'date_expression': '1880 to 1888',
'notes': [],
'children': [{
'id': '24',
'type': 'resource_component',
'sortPosition': '3',
'identifier': 'GR01',
'title': 'Grandchild A',
'levelOfDescription': 'Item',
'dates': '1880-1888',
'date_expression': '1880 to 1888',
'notes': [],
'children': False
},
{
'id': '25',
'type': 'resource_component',
'sortPosition': '4',
'identifier': 'GR02',
'title': 'Grandchild B',
'levelOfDescription': 'Item',
'notes': [],
'children': False
}]
},
{
'id': '26',
'type': 'resource_component',
'sortPosition': '5',
'identifier': 'CH02',
'title': 'Child B',
'levelOfDescription': 'Sousfonds',
'dates': '1889',
'date_expression': '1889',
'notes': [],
'children': False
}]
}
:rtype list:
"""
# we pass the sort position as a dict so it passes by reference and we
# can use it to share state during recursion
recurse_max_level = kwargs.get("recurse_max_level", False)
query = kwargs.get("search_pattern", "")
# intialize sort position if this is the beginning of recursion
if level == 1:
sort_data["position"] = 0
sort_data["position"] = sort_data["position"] + 1
resource_data = {}
cursor = self.db.cursor()
if resource_type == "collection":
cursor.execute(
"SELECT title, dateExpression, resourceIdentifier1, resourceLevel FROM Resources WHERE resourceid=%s",
(resource_id),
)
for row in cursor.fetchall():
resource_data["id"] = resource_id
resource_data["type"] = "resource"
resource_data["sortPosition"] = sort_data["position"]
resource_data["title"] = row[0]
# TODO reformat dates from the separate date fields, like ArchivesSpaceClient?
resource_data["dates"] = row[1]
resource_data["date_expression"] = row[1]
resource_data["identifier"] = row[2]
resource_data["levelOfDescription"] = row[3]
else:
cursor.execute(
"SELECT title, dateExpression, persistentID, resourceLevel FROM ResourcesComponents WHERE resourceComponentId=%s",
(resource_id),
)
for row in cursor.fetchall():
resource_data["id"] = resource_id
resource_data["type"] = "resource_component"
resource_data["sortPosition"] = sort_data["position"]
resource_data["title"] = row[0]
resource_data["dates"] = row[1]
resource_data["date_expression"] = row[1]
resource_data["identifier"] = row[2]
resource_data["levelOfDescription"] = row[3]
# fetch children if we haven't reached the maximum recursion level
if resource_type == "collection":
if query == "":
cursor.execute(
"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId IS NULL AND resourceId=%s ORDER BY FIND_IN_SET(resourceLevel, 'subseries,file'), title ASC",
(resource_id),
)
else:
cursor.execute(
"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId IS NULL AND resourceId=%s AND (title LIKE %s OR persistentID LIKE %s) ORDER BY FIND_IN_SET(resourceLevel, 'subseries,file'), title ASC",
(resource_id, "%" + query + "%", "%" + query + "%"),
)
else:
if query == "":
cursor.execute(
"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId=%s ORDER BY FIND_IN_SET(resourceLevel, 'subseries,file'), title ASC",
(resource_id),
)
else:
cursor.execute(
"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId=%s AND (title LIKE %s OR persistentID LIKE %s) ORDER BY FIND_IN_SET(resourceLevel, 'subseries,file'), title ASC",
(resource_id, "%" + query + "%", "%" + query + "%"),
)
rows = cursor.fetchall()
if (not recurse_max_level) or level < recurse_max_level:
if len(rows):
resource_data["children"] = []
resource_data["has_children"] = True
for row in rows:
resource_data["children"].append(
self.get_resource_component_and_children(
row[0], "description", level + 1, sort_data
)
)
else:
if len(rows):
resource_data["children"] = []
resource_data["has_children"] = True
else:
resource_data["children"] = False
resource_data["has_children"] = False
# TODO: implement fetching notes
resource_data["notes"] = []
return resource_data | python | def get_resource_component_and_children(
self, resource_id, resource_type="collection", level=1, sort_data={}, **kwargs
):
"""
Fetch detailed metadata for the specified resource_id and all of its children.
:param long resource_id: The resource for which to fetch metadata.
:param string resource_type: The level of description of the record.
:param int recurse_max_level: The maximum depth level to fetch when fetching children.
Default is to fetch all of the resource's children, descending as deeply as necessary.
Pass 1 to fetch no children.
:param string search_pattern: If specified, limits fetched children to those whose titles or IDs match the provided query.
See ArchivistsToolkitClient.find_collection_ids for documentation of the query format.
:return: A dict containing detailed metadata about both the requested resource and its children.
The dict follows this format:
{
'id': '31',
'type': 'resource',
'sortPosition': '1',
'identifier': 'PR01',
'title': 'Parent',
'levelOfDescription': 'collection',
'dates': '1880-1889',
'date_expression': '1880 to 1889',
'notes': [
'type': 'odd',
'content': 'This is a note',
],
'children': [{
'id': '23',
'type': 'resource_component',
'sortPosition': '2',
'identifier': 'CH01',
'title': 'Child A',
'levelOfDescription': 'Sousfonds',
'dates': '1880-1888',
'date_expression': '1880 to 1888',
'notes': [],
'children': [{
'id': '24',
'type': 'resource_component',
'sortPosition': '3',
'identifier': 'GR01',
'title': 'Grandchild A',
'levelOfDescription': 'Item',
'dates': '1880-1888',
'date_expression': '1880 to 1888',
'notes': [],
'children': False
},
{
'id': '25',
'type': 'resource_component',
'sortPosition': '4',
'identifier': 'GR02',
'title': 'Grandchild B',
'levelOfDescription': 'Item',
'notes': [],
'children': False
}]
},
{
'id': '26',
'type': 'resource_component',
'sortPosition': '5',
'identifier': 'CH02',
'title': 'Child B',
'levelOfDescription': 'Sousfonds',
'dates': '1889',
'date_expression': '1889',
'notes': [],
'children': False
}]
}
:rtype list:
"""
# we pass the sort position as a dict so it passes by reference and we
# can use it to share state during recursion
recurse_max_level = kwargs.get("recurse_max_level", False)
query = kwargs.get("search_pattern", "")
# intialize sort position if this is the beginning of recursion
if level == 1:
sort_data["position"] = 0
sort_data["position"] = sort_data["position"] + 1
resource_data = {}
cursor = self.db.cursor()
if resource_type == "collection":
cursor.execute(
"SELECT title, dateExpression, resourceIdentifier1, resourceLevel FROM Resources WHERE resourceid=%s",
(resource_id),
)
for row in cursor.fetchall():
resource_data["id"] = resource_id
resource_data["type"] = "resource"
resource_data["sortPosition"] = sort_data["position"]
resource_data["title"] = row[0]
# TODO reformat dates from the separate date fields, like ArchivesSpaceClient?
resource_data["dates"] = row[1]
resource_data["date_expression"] = row[1]
resource_data["identifier"] = row[2]
resource_data["levelOfDescription"] = row[3]
else:
cursor.execute(
"SELECT title, dateExpression, persistentID, resourceLevel FROM ResourcesComponents WHERE resourceComponentId=%s",
(resource_id),
)
for row in cursor.fetchall():
resource_data["id"] = resource_id
resource_data["type"] = "resource_component"
resource_data["sortPosition"] = sort_data["position"]
resource_data["title"] = row[0]
resource_data["dates"] = row[1]
resource_data["date_expression"] = row[1]
resource_data["identifier"] = row[2]
resource_data["levelOfDescription"] = row[3]
# fetch children if we haven't reached the maximum recursion level
if resource_type == "collection":
if query == "":
cursor.execute(
"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId IS NULL AND resourceId=%s ORDER BY FIND_IN_SET(resourceLevel, 'subseries,file'), title ASC",
(resource_id),
)
else:
cursor.execute(
"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId IS NULL AND resourceId=%s AND (title LIKE %s OR persistentID LIKE %s) ORDER BY FIND_IN_SET(resourceLevel, 'subseries,file'), title ASC",
(resource_id, "%" + query + "%", "%" + query + "%"),
)
else:
if query == "":
cursor.execute(
"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId=%s ORDER BY FIND_IN_SET(resourceLevel, 'subseries,file'), title ASC",
(resource_id),
)
else:
cursor.execute(
"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId=%s AND (title LIKE %s OR persistentID LIKE %s) ORDER BY FIND_IN_SET(resourceLevel, 'subseries,file'), title ASC",
(resource_id, "%" + query + "%", "%" + query + "%"),
)
rows = cursor.fetchall()
if (not recurse_max_level) or level < recurse_max_level:
if len(rows):
resource_data["children"] = []
resource_data["has_children"] = True
for row in rows:
resource_data["children"].append(
self.get_resource_component_and_children(
row[0], "description", level + 1, sort_data
)
)
else:
if len(rows):
resource_data["children"] = []
resource_data["has_children"] = True
else:
resource_data["children"] = False
resource_data["has_children"] = False
# TODO: implement fetching notes
resource_data["notes"] = []
return resource_data | [
"def",
"get_resource_component_and_children",
"(",
"self",
",",
"resource_id",
",",
"resource_type",
"=",
"\"collection\"",
",",
"level",
"=",
"1",
",",
"sort_data",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"# we pass the sort position as a dict so it passes by reference and we",
"# can use it to share state during recursion",
"recurse_max_level",
"=",
"kwargs",
".",
"get",
"(",
"\"recurse_max_level\"",
",",
"False",
")",
"query",
"=",
"kwargs",
".",
"get",
"(",
"\"search_pattern\"",
",",
"\"\"",
")",
"# intialize sort position if this is the beginning of recursion",
"if",
"level",
"==",
"1",
":",
"sort_data",
"[",
"\"position\"",
"]",
"=",
"0",
"sort_data",
"[",
"\"position\"",
"]",
"=",
"sort_data",
"[",
"\"position\"",
"]",
"+",
"1",
"resource_data",
"=",
"{",
"}",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"if",
"resource_type",
"==",
"\"collection\"",
":",
"cursor",
".",
"execute",
"(",
"\"SELECT title, dateExpression, resourceIdentifier1, resourceLevel FROM Resources WHERE resourceid=%s\"",
",",
"(",
"resource_id",
")",
",",
")",
"for",
"row",
"in",
"cursor",
".",
"fetchall",
"(",
")",
":",
"resource_data",
"[",
"\"id\"",
"]",
"=",
"resource_id",
"resource_data",
"[",
"\"type\"",
"]",
"=",
"\"resource\"",
"resource_data",
"[",
"\"sortPosition\"",
"]",
"=",
"sort_data",
"[",
"\"position\"",
"]",
"resource_data",
"[",
"\"title\"",
"]",
"=",
"row",
"[",
"0",
"]",
"# TODO reformat dates from the separate date fields, like ArchivesSpaceClient?",
"resource_data",
"[",
"\"dates\"",
"]",
"=",
"row",
"[",
"1",
"]",
"resource_data",
"[",
"\"date_expression\"",
"]",
"=",
"row",
"[",
"1",
"]",
"resource_data",
"[",
"\"identifier\"",
"]",
"=",
"row",
"[",
"2",
"]",
"resource_data",
"[",
"\"levelOfDescription\"",
"]",
"=",
"row",
"[",
"3",
"]",
"else",
":",
"cursor",
".",
"execute",
"(",
"\"SELECT title, dateExpression, persistentID, resourceLevel FROM ResourcesComponents WHERE resourceComponentId=%s\"",
",",
"(",
"resource_id",
")",
",",
")",
"for",
"row",
"in",
"cursor",
".",
"fetchall",
"(",
")",
":",
"resource_data",
"[",
"\"id\"",
"]",
"=",
"resource_id",
"resource_data",
"[",
"\"type\"",
"]",
"=",
"\"resource_component\"",
"resource_data",
"[",
"\"sortPosition\"",
"]",
"=",
"sort_data",
"[",
"\"position\"",
"]",
"resource_data",
"[",
"\"title\"",
"]",
"=",
"row",
"[",
"0",
"]",
"resource_data",
"[",
"\"dates\"",
"]",
"=",
"row",
"[",
"1",
"]",
"resource_data",
"[",
"\"date_expression\"",
"]",
"=",
"row",
"[",
"1",
"]",
"resource_data",
"[",
"\"identifier\"",
"]",
"=",
"row",
"[",
"2",
"]",
"resource_data",
"[",
"\"levelOfDescription\"",
"]",
"=",
"row",
"[",
"3",
"]",
"# fetch children if we haven't reached the maximum recursion level",
"if",
"resource_type",
"==",
"\"collection\"",
":",
"if",
"query",
"==",
"\"\"",
":",
"cursor",
".",
"execute",
"(",
"\"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId IS NULL AND resourceId=%s ORDER BY FIND_IN_SET(resourceLevel, 'subseries,file'), title ASC\"",
",",
"(",
"resource_id",
")",
",",
")",
"else",
":",
"cursor",
".",
"execute",
"(",
"\"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId IS NULL AND resourceId=%s AND (title LIKE %s OR persistentID LIKE %s) ORDER BY FIND_IN_SET(resourceLevel, 'subseries,file'), title ASC\"",
",",
"(",
"resource_id",
",",
"\"%\"",
"+",
"query",
"+",
"\"%\"",
",",
"\"%\"",
"+",
"query",
"+",
"\"%\"",
")",
",",
")",
"else",
":",
"if",
"query",
"==",
"\"\"",
":",
"cursor",
".",
"execute",
"(",
"\"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId=%s ORDER BY FIND_IN_SET(resourceLevel, 'subseries,file'), title ASC\"",
",",
"(",
"resource_id",
")",
",",
")",
"else",
":",
"cursor",
".",
"execute",
"(",
"\"SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId=%s AND (title LIKE %s OR persistentID LIKE %s) ORDER BY FIND_IN_SET(resourceLevel, 'subseries,file'), title ASC\"",
",",
"(",
"resource_id",
",",
"\"%\"",
"+",
"query",
"+",
"\"%\"",
",",
"\"%\"",
"+",
"query",
"+",
"\"%\"",
")",
",",
")",
"rows",
"=",
"cursor",
".",
"fetchall",
"(",
")",
"if",
"(",
"not",
"recurse_max_level",
")",
"or",
"level",
"<",
"recurse_max_level",
":",
"if",
"len",
"(",
"rows",
")",
":",
"resource_data",
"[",
"\"children\"",
"]",
"=",
"[",
"]",
"resource_data",
"[",
"\"has_children\"",
"]",
"=",
"True",
"for",
"row",
"in",
"rows",
":",
"resource_data",
"[",
"\"children\"",
"]",
".",
"append",
"(",
"self",
".",
"get_resource_component_and_children",
"(",
"row",
"[",
"0",
"]",
",",
"\"description\"",
",",
"level",
"+",
"1",
",",
"sort_data",
")",
")",
"else",
":",
"if",
"len",
"(",
"rows",
")",
":",
"resource_data",
"[",
"\"children\"",
"]",
"=",
"[",
"]",
"resource_data",
"[",
"\"has_children\"",
"]",
"=",
"True",
"else",
":",
"resource_data",
"[",
"\"children\"",
"]",
"=",
"False",
"resource_data",
"[",
"\"has_children\"",
"]",
"=",
"False",
"# TODO: implement fetching notes",
"resource_data",
"[",
"\"notes\"",
"]",
"=",
"[",
"]",
"return",
"resource_data"
] | Fetch detailed metadata for the specified resource_id and all of its children.
:param long resource_id: The resource for which to fetch metadata.
:param string resource_type: The level of description of the record.
:param int recurse_max_level: The maximum depth level to fetch when fetching children.
Default is to fetch all of the resource's children, descending as deeply as necessary.
Pass 1 to fetch no children.
:param string search_pattern: If specified, limits fetched children to those whose titles or IDs match the provided query.
See ArchivistsToolkitClient.find_collection_ids for documentation of the query format.
:return: A dict containing detailed metadata about both the requested resource and its children.
The dict follows this format:
{
'id': '31',
'type': 'resource',
'sortPosition': '1',
'identifier': 'PR01',
'title': 'Parent',
'levelOfDescription': 'collection',
'dates': '1880-1889',
'date_expression': '1880 to 1889',
'notes': [
'type': 'odd',
'content': 'This is a note',
],
'children': [{
'id': '23',
'type': 'resource_component',
'sortPosition': '2',
'identifier': 'CH01',
'title': 'Child A',
'levelOfDescription': 'Sousfonds',
'dates': '1880-1888',
'date_expression': '1880 to 1888',
'notes': [],
'children': [{
'id': '24',
'type': 'resource_component',
'sortPosition': '3',
'identifier': 'GR01',
'title': 'Grandchild A',
'levelOfDescription': 'Item',
'dates': '1880-1888',
'date_expression': '1880 to 1888',
'notes': [],
'children': False
},
{
'id': '25',
'type': 'resource_component',
'sortPosition': '4',
'identifier': 'GR02',
'title': 'Grandchild B',
'levelOfDescription': 'Item',
'notes': [],
'children': False
}]
},
{
'id': '26',
'type': 'resource_component',
'sortPosition': '5',
'identifier': 'CH02',
'title': 'Child B',
'levelOfDescription': 'Sousfonds',
'dates': '1889',
'date_expression': '1889',
'notes': [],
'children': False
}]
}
:rtype list: | [
"Fetch",
"detailed",
"metadata",
"for",
"the",
"specified",
"resource_id",
"and",
"all",
"of",
"its",
"children",
"."
] | train | https://github.com/artefactual-labs/agentarchives/blob/af19ade56a90c64069cf46b50972fe72b6f10a45/agentarchives/archivists_toolkit/client.py#L159-L332 |
artefactual-labs/agentarchives | agentarchives/archivists_toolkit/client.py | ArchivistsToolkitClient.find_resource_id_for_component | def find_resource_id_for_component(self, component_id):
"""
Given the ID of a component, returns the parent resource ID.
If the immediate parent of the component is itself a component, this method will progress up the tree until a resource is found.
:param long component_id: The ID of the ResourceComponent.
:return: The ID of the component's parent resource.
:rtype: long
"""
cursor = self.db.cursor()
sql = "SELECT resourceId, parentResourceComponentId FROM ResourcesComponents WHERE resourceComponentId=%s"
cursor.execute(sql, (component_id,))
resource_id, parent_id = cursor.fetchone()
if resource_id is None:
return self.find_resource_id_for_component(parent_id)
else:
return resource_id | python | def find_resource_id_for_component(self, component_id):
"""
Given the ID of a component, returns the parent resource ID.
If the immediate parent of the component is itself a component, this method will progress up the tree until a resource is found.
:param long component_id: The ID of the ResourceComponent.
:return: The ID of the component's parent resource.
:rtype: long
"""
cursor = self.db.cursor()
sql = "SELECT resourceId, parentResourceComponentId FROM ResourcesComponents WHERE resourceComponentId=%s"
cursor.execute(sql, (component_id,))
resource_id, parent_id = cursor.fetchone()
if resource_id is None:
return self.find_resource_id_for_component(parent_id)
else:
return resource_id | [
"def",
"find_resource_id_for_component",
"(",
"self",
",",
"component_id",
")",
":",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"sql",
"=",
"\"SELECT resourceId, parentResourceComponentId FROM ResourcesComponents WHERE resourceComponentId=%s\"",
"cursor",
".",
"execute",
"(",
"sql",
",",
"(",
"component_id",
",",
")",
")",
"resource_id",
",",
"parent_id",
"=",
"cursor",
".",
"fetchone",
"(",
")",
"if",
"resource_id",
"is",
"None",
":",
"return",
"self",
".",
"find_resource_id_for_component",
"(",
"parent_id",
")",
"else",
":",
"return",
"resource_id"
] | Given the ID of a component, returns the parent resource ID.
If the immediate parent of the component is itself a component, this method will progress up the tree until a resource is found.
:param long component_id: The ID of the ResourceComponent.
:return: The ID of the component's parent resource.
:rtype: long | [
"Given",
"the",
"ID",
"of",
"a",
"component",
"returns",
"the",
"parent",
"resource",
"ID",
"."
] | train | https://github.com/artefactual-labs/agentarchives/blob/af19ade56a90c64069cf46b50972fe72b6f10a45/agentarchives/archivists_toolkit/client.py#L334-L353 |
artefactual-labs/agentarchives | agentarchives/archivists_toolkit/client.py | ArchivistsToolkitClient.find_parent_id_for_component | def find_parent_id_for_component(self, component_id):
"""
Given the ID of a component, returns the parent component's ID.
:param string component_id: The ID of the component.
:return: A tuple containing:
* The type of the parent record; valid values are ArchivesSpaceClient.RESOURCE and ArchivesSpaceClient.RESOURCE_COMPONENT.
* The ID of the parent record.
:rtype tuple:
"""
cursor = self.db.cursor()
sql = "SELECT parentResourceComponentId FROM ResourcesComponents WHERE resourceComponentId=%s"
count = cursor.execute(sql, (component_id,))
if count > 0:
return (ArchivistsToolkitClient.RESOURCE_COMPONENT, cursor.fetchone())
return (
ArchivistsToolkitClient.RESOURCE,
self.find_resource_id_for_component(component_id),
) | python | def find_parent_id_for_component(self, component_id):
"""
Given the ID of a component, returns the parent component's ID.
:param string component_id: The ID of the component.
:return: A tuple containing:
* The type of the parent record; valid values are ArchivesSpaceClient.RESOURCE and ArchivesSpaceClient.RESOURCE_COMPONENT.
* The ID of the parent record.
:rtype tuple:
"""
cursor = self.db.cursor()
sql = "SELECT parentResourceComponentId FROM ResourcesComponents WHERE resourceComponentId=%s"
count = cursor.execute(sql, (component_id,))
if count > 0:
return (ArchivistsToolkitClient.RESOURCE_COMPONENT, cursor.fetchone())
return (
ArchivistsToolkitClient.RESOURCE,
self.find_resource_id_for_component(component_id),
) | [
"def",
"find_parent_id_for_component",
"(",
"self",
",",
"component_id",
")",
":",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"sql",
"=",
"\"SELECT parentResourceComponentId FROM ResourcesComponents WHERE resourceComponentId=%s\"",
"count",
"=",
"cursor",
".",
"execute",
"(",
"sql",
",",
"(",
"component_id",
",",
")",
")",
"if",
"count",
">",
"0",
":",
"return",
"(",
"ArchivistsToolkitClient",
".",
"RESOURCE_COMPONENT",
",",
"cursor",
".",
"fetchone",
"(",
")",
")",
"return",
"(",
"ArchivistsToolkitClient",
".",
"RESOURCE",
",",
"self",
".",
"find_resource_id_for_component",
"(",
"component_id",
")",
",",
")"
] | Given the ID of a component, returns the parent component's ID.
:param string component_id: The ID of the component.
:return: A tuple containing:
* The type of the parent record; valid values are ArchivesSpaceClient.RESOURCE and ArchivesSpaceClient.RESOURCE_COMPONENT.
* The ID of the parent record.
:rtype tuple: | [
"Given",
"the",
"ID",
"of",
"a",
"component",
"returns",
"the",
"parent",
"component",
"s",
"ID",
"."
] | train | https://github.com/artefactual-labs/agentarchives/blob/af19ade56a90c64069cf46b50972fe72b6f10a45/agentarchives/archivists_toolkit/client.py#L355-L375 |
artefactual-labs/agentarchives | agentarchives/archivists_toolkit/client.py | ArchivistsToolkitClient.find_collection_ids | def find_collection_ids(
self, search_pattern="", identifier="", page=None, page_size=30
):
"""
Fetches a list of all resource IDs for every resource in the database.
:param string search_pattern: A search pattern to use in looking up resources by title or resourceid.
The search will match any title or resourceid containing this string;
for example, "text" will match "this title has this text in it".
If omitted, then all resources will be fetched.
:param string identifier: Restrict records to only those with this identifier.
This refers to the human-assigned record identifier, not the automatically generated internal ID.
Unlike the ArchivesSpaceClient version of this method, wildcards are not supported; however, identifiers which begin or end with this string will be returned.
For example, if the passed identifier is "A1", then records with an identifier of "A1", "SAA1", "A10", and "SAA10" will all be returned.
:return: A list containing every matched resource's ID.
:rtype: list
"""
cursor = self.db.cursor()
if search_pattern == "" and identifier == "":
sql = "SELECT resourceId FROM Resources ORDER BY title"
params = ()
else:
clause = "resourceid LIKE %s"
params = ["%" + search_pattern + "%"]
if search_pattern != "":
clause = "title LIKE %s OR" + clause
params.insert(0, "%" + search_pattern + "%")
if identifier != "":
clause = "resourceIdentifier1 LIKE %s OR " + clause
params.insert(0, "%" + identifier + "%")
params = tuple(params)
sql = "SELECT resourceId FROM Resources WHERE ({}) AND resourceLevel in ('recordgrp', 'collection') ORDER BY title".format(
clause
)
if page is not None:
start = (page - 1) * page_size
sql = sql + " LIMIT {},{}".format(start, page_size)
cursor.execute(sql, params)
return [r[0] for r in cursor] | python | def find_collection_ids(
self, search_pattern="", identifier="", page=None, page_size=30
):
"""
Fetches a list of all resource IDs for every resource in the database.
:param string search_pattern: A search pattern to use in looking up resources by title or resourceid.
The search will match any title or resourceid containing this string;
for example, "text" will match "this title has this text in it".
If omitted, then all resources will be fetched.
:param string identifier: Restrict records to only those with this identifier.
This refers to the human-assigned record identifier, not the automatically generated internal ID.
Unlike the ArchivesSpaceClient version of this method, wildcards are not supported; however, identifiers which begin or end with this string will be returned.
For example, if the passed identifier is "A1", then records with an identifier of "A1", "SAA1", "A10", and "SAA10" will all be returned.
:return: A list containing every matched resource's ID.
:rtype: list
"""
cursor = self.db.cursor()
if search_pattern == "" and identifier == "":
sql = "SELECT resourceId FROM Resources ORDER BY title"
params = ()
else:
clause = "resourceid LIKE %s"
params = ["%" + search_pattern + "%"]
if search_pattern != "":
clause = "title LIKE %s OR" + clause
params.insert(0, "%" + search_pattern + "%")
if identifier != "":
clause = "resourceIdentifier1 LIKE %s OR " + clause
params.insert(0, "%" + identifier + "%")
params = tuple(params)
sql = "SELECT resourceId FROM Resources WHERE ({}) AND resourceLevel in ('recordgrp', 'collection') ORDER BY title".format(
clause
)
if page is not None:
start = (page - 1) * page_size
sql = sql + " LIMIT {},{}".format(start, page_size)
cursor.execute(sql, params)
return [r[0] for r in cursor] | [
"def",
"find_collection_ids",
"(",
"self",
",",
"search_pattern",
"=",
"\"\"",
",",
"identifier",
"=",
"\"\"",
",",
"page",
"=",
"None",
",",
"page_size",
"=",
"30",
")",
":",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"if",
"search_pattern",
"==",
"\"\"",
"and",
"identifier",
"==",
"\"\"",
":",
"sql",
"=",
"\"SELECT resourceId FROM Resources ORDER BY title\"",
"params",
"=",
"(",
")",
"else",
":",
"clause",
"=",
"\"resourceid LIKE %s\"",
"params",
"=",
"[",
"\"%\"",
"+",
"search_pattern",
"+",
"\"%\"",
"]",
"if",
"search_pattern",
"!=",
"\"\"",
":",
"clause",
"=",
"\"title LIKE %s OR\"",
"+",
"clause",
"params",
".",
"insert",
"(",
"0",
",",
"\"%\"",
"+",
"search_pattern",
"+",
"\"%\"",
")",
"if",
"identifier",
"!=",
"\"\"",
":",
"clause",
"=",
"\"resourceIdentifier1 LIKE %s OR \"",
"+",
"clause",
"params",
".",
"insert",
"(",
"0",
",",
"\"%\"",
"+",
"identifier",
"+",
"\"%\"",
")",
"params",
"=",
"tuple",
"(",
"params",
")",
"sql",
"=",
"\"SELECT resourceId FROM Resources WHERE ({}) AND resourceLevel in ('recordgrp', 'collection') ORDER BY title\"",
".",
"format",
"(",
"clause",
")",
"if",
"page",
"is",
"not",
"None",
":",
"start",
"=",
"(",
"page",
"-",
"1",
")",
"*",
"page_size",
"sql",
"=",
"sql",
"+",
"\" LIMIT {},{}\"",
".",
"format",
"(",
"start",
",",
"page_size",
")",
"cursor",
".",
"execute",
"(",
"sql",
",",
"params",
")",
"return",
"[",
"r",
"[",
"0",
"]",
"for",
"r",
"in",
"cursor",
"]"
] | Fetches a list of all resource IDs for every resource in the database.
:param string search_pattern: A search pattern to use in looking up resources by title or resourceid.
The search will match any title or resourceid containing this string;
for example, "text" will match "this title has this text in it".
If omitted, then all resources will be fetched.
:param string identifier: Restrict records to only those with this identifier.
This refers to the human-assigned record identifier, not the automatically generated internal ID.
Unlike the ArchivesSpaceClient version of this method, wildcards are not supported; however, identifiers which begin or end with this string will be returned.
For example, if the passed identifier is "A1", then records with an identifier of "A1", "SAA1", "A10", and "SAA10" will all be returned.
:return: A list containing every matched resource's ID.
:rtype: list | [
"Fetches",
"a",
"list",
"of",
"all",
"resource",
"IDs",
"for",
"every",
"resource",
"in",
"the",
"database",
"."
] | train | https://github.com/artefactual-labs/agentarchives/blob/af19ade56a90c64069cf46b50972fe72b6f10a45/agentarchives/archivists_toolkit/client.py#L377-L424 |
mirca/vaneska | vaneska/models.py | Gaussian.evaluate | def evaluate(self, flux, xo, yo, a, b, c):
"""
Evaluate the Gaussian model
Parameters
----------
flux : tf.Variable
xo, yo : tf.Variable, tf.Variable
Center coordiantes of the Gaussian.
a, b, c : tf.Variable, tf.Variable
Parameters that control the rotation angle
and the stretch along the major axis of the Gaussian,
such that the matrix M = [a b ; b c] is positive-definite.
References
----------
https://en.wikipedia.org/wiki/Gaussian_function#Two-dimensional_Gaussian_function
"""
dx = self.x - xo
dy = self.y - yo
psf = tf.exp(-(a * dx ** 2 + 2 * b * dx * dy + c * dy ** 2))
psf_sum = tf.reduce_sum(psf)
return flux * psf / psf_sum | python | def evaluate(self, flux, xo, yo, a, b, c):
"""
Evaluate the Gaussian model
Parameters
----------
flux : tf.Variable
xo, yo : tf.Variable, tf.Variable
Center coordiantes of the Gaussian.
a, b, c : tf.Variable, tf.Variable
Parameters that control the rotation angle
and the stretch along the major axis of the Gaussian,
such that the matrix M = [a b ; b c] is positive-definite.
References
----------
https://en.wikipedia.org/wiki/Gaussian_function#Two-dimensional_Gaussian_function
"""
dx = self.x - xo
dy = self.y - yo
psf = tf.exp(-(a * dx ** 2 + 2 * b * dx * dy + c * dy ** 2))
psf_sum = tf.reduce_sum(psf)
return flux * psf / psf_sum | [
"def",
"evaluate",
"(",
"self",
",",
"flux",
",",
"xo",
",",
"yo",
",",
"a",
",",
"b",
",",
"c",
")",
":",
"dx",
"=",
"self",
".",
"x",
"-",
"xo",
"dy",
"=",
"self",
".",
"y",
"-",
"yo",
"psf",
"=",
"tf",
".",
"exp",
"(",
"-",
"(",
"a",
"*",
"dx",
"**",
"2",
"+",
"2",
"*",
"b",
"*",
"dx",
"*",
"dy",
"+",
"c",
"*",
"dy",
"**",
"2",
")",
")",
"psf_sum",
"=",
"tf",
".",
"reduce_sum",
"(",
"psf",
")",
"return",
"flux",
"*",
"psf",
"/",
"psf_sum"
] | Evaluate the Gaussian model
Parameters
----------
flux : tf.Variable
xo, yo : tf.Variable, tf.Variable
Center coordiantes of the Gaussian.
a, b, c : tf.Variable, tf.Variable
Parameters that control the rotation angle
and the stretch along the major axis of the Gaussian,
such that the matrix M = [a b ; b c] is positive-definite.
References
----------
https://en.wikipedia.org/wiki/Gaussian_function#Two-dimensional_Gaussian_function | [
"Evaluate",
"the",
"Gaussian",
"model"
] | train | https://github.com/mirca/vaneska/blob/9bbf0b16957ec765e5f30872c8d22470c66bfd83/vaneska/models.py#L49-L71 |
guillermo-carrasco/bcbio-nextgen-monitor | bcbio_monitor/parser/__init__.py | parse_log_line | def parse_log_line(line):
"""Parses a log line and returns it with more information
:param line: str - A line from a bcbio-nextgen log
:returns dict: A dictionary containing the line, if its a new step if its a Traceback or if the
analysis is finished
"""
matches = re.search(r'^\[([^\]]+)\] ([^:]+: .*)', line)
error = re.search(r'Traceback', line)
if error:
return {'line': line, 'step': 'error'}
if not matches:
return {'line': line, 'step': None}
tstamp = matches.group(1)
msg = matches.group(2)
if not msg.find('Timing: ') >= 0:
return {'line': line, 'step': None}
when = datetime.strptime(tstamp, '%Y-%m-%dT%H:%MZ').replace(
tzinfo=pytz.timezone('UTC'))
step = msg.split(":")[-1].strip()
return {'line': line, 'step': step, 'when': when} | python | def parse_log_line(line):
"""Parses a log line and returns it with more information
:param line: str - A line from a bcbio-nextgen log
:returns dict: A dictionary containing the line, if its a new step if its a Traceback or if the
analysis is finished
"""
matches = re.search(r'^\[([^\]]+)\] ([^:]+: .*)', line)
error = re.search(r'Traceback', line)
if error:
return {'line': line, 'step': 'error'}
if not matches:
return {'line': line, 'step': None}
tstamp = matches.group(1)
msg = matches.group(2)
if not msg.find('Timing: ') >= 0:
return {'line': line, 'step': None}
when = datetime.strptime(tstamp, '%Y-%m-%dT%H:%MZ').replace(
tzinfo=pytz.timezone('UTC'))
step = msg.split(":")[-1].strip()
return {'line': line, 'step': step, 'when': when} | [
"def",
"parse_log_line",
"(",
"line",
")",
":",
"matches",
"=",
"re",
".",
"search",
"(",
"r'^\\[([^\\]]+)\\] ([^:]+: .*)'",
",",
"line",
")",
"error",
"=",
"re",
".",
"search",
"(",
"r'Traceback'",
",",
"line",
")",
"if",
"error",
":",
"return",
"{",
"'line'",
":",
"line",
",",
"'step'",
":",
"'error'",
"}",
"if",
"not",
"matches",
":",
"return",
"{",
"'line'",
":",
"line",
",",
"'step'",
":",
"None",
"}",
"tstamp",
"=",
"matches",
".",
"group",
"(",
"1",
")",
"msg",
"=",
"matches",
".",
"group",
"(",
"2",
")",
"if",
"not",
"msg",
".",
"find",
"(",
"'Timing: '",
")",
">=",
"0",
":",
"return",
"{",
"'line'",
":",
"line",
",",
"'step'",
":",
"None",
"}",
"when",
"=",
"datetime",
".",
"strptime",
"(",
"tstamp",
",",
"'%Y-%m-%dT%H:%MZ'",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"timezone",
"(",
"'UTC'",
")",
")",
"step",
"=",
"msg",
".",
"split",
"(",
"\":\"",
")",
"[",
"-",
"1",
"]",
".",
"strip",
"(",
")",
"return",
"{",
"'line'",
":",
"line",
",",
"'step'",
":",
"step",
",",
"'when'",
":",
"when",
"}"
] | Parses a log line and returns it with more information
:param line: str - A line from a bcbio-nextgen log
:returns dict: A dictionary containing the line, if its a new step if its a Traceback or if the
analysis is finished | [
"Parses",
"a",
"log",
"line",
"and",
"returns",
"it",
"with",
"more",
"information"
] | train | https://github.com/guillermo-carrasco/bcbio-nextgen-monitor/blob/6d059154d774140e1fd03a0e3625f607cef06f5a/bcbio_monitor/parser/__init__.py#L12-L35 |
Leeps-Lab/otree-redwood | otree_redwood/models.py | Event.message | def message(self):
"""Dictionary representation of the Event appropriate for JSON-encoding."""
return {
'timestamp': time.mktime(self.timestamp.timetuple())*1e3 + self.timestamp.microsecond/1e3,
'group': self.group_pk,
'participant': None if not self.participant else self.participant.code,
'channel': self.channel,
'value': self.value
} | python | def message(self):
"""Dictionary representation of the Event appropriate for JSON-encoding."""
return {
'timestamp': time.mktime(self.timestamp.timetuple())*1e3 + self.timestamp.microsecond/1e3,
'group': self.group_pk,
'participant': None if not self.participant else self.participant.code,
'channel': self.channel,
'value': self.value
} | [
"def",
"message",
"(",
"self",
")",
":",
"return",
"{",
"'timestamp'",
":",
"time",
".",
"mktime",
"(",
"self",
".",
"timestamp",
".",
"timetuple",
"(",
")",
")",
"*",
"1e3",
"+",
"self",
".",
"timestamp",
".",
"microsecond",
"/",
"1e3",
",",
"'group'",
":",
"self",
".",
"group_pk",
",",
"'participant'",
":",
"None",
"if",
"not",
"self",
".",
"participant",
"else",
"self",
".",
"participant",
".",
"code",
",",
"'channel'",
":",
"self",
".",
"channel",
",",
"'value'",
":",
"self",
".",
"value",
"}"
] | Dictionary representation of the Event appropriate for JSON-encoding. | [
"Dictionary",
"representation",
"of",
"the",
"Event",
"appropriate",
"for",
"JSON",
"-",
"encoding",
"."
] | train | https://github.com/Leeps-Lab/otree-redwood/blob/59212f61a256ef77e0a9ed392ff497ea83ee6245/otree_redwood/models.py#L50-L58 |
Leeps-Lab/otree-redwood | otree_redwood/models.py | Event.save | def save(self, *args, **kwargs):
"""Saving an Event automatically sets the timestamp if not already set."""
if self.timestamp is None:
self.timestamp = timezone.now()
super().save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""Saving an Event automatically sets the timestamp if not already set."""
if self.timestamp is None:
self.timestamp = timezone.now()
super().save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"timestamp",
"is",
"None",
":",
"self",
".",
"timestamp",
"=",
"timezone",
".",
"now",
"(",
")",
"super",
"(",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Saving an Event automatically sets the timestamp if not already set. | [
"Saving",
"an",
"Event",
"automatically",
"sets",
"the",
"timestamp",
"if",
"not",
"already",
"set",
"."
] | train | https://github.com/Leeps-Lab/otree-redwood/blob/59212f61a256ef77e0a9ed392ff497ea83ee6245/otree_redwood/models.py#L60-L65 |
Leeps-Lab/otree-redwood | otree_redwood/models.py | Group._on_connect | def _on_connect(self, participant):
"""Called from the WebSocket consumer. Checks if all players in the group
have connected; runs :meth:`when_all_players_ready` once all connections
are established.
"""
lock = get_redis_lock()
if not lock:
lock = fake_lock()
with lock:
self.refresh_from_db()
if self.ran_ready_function:
return
for player in self.get_players():
if Connection.objects.filter(participant__code=player.participant.code).count() == 0:
return
self.when_all_players_ready()
self.ran_ready_function = timezone.now()
self.save()
self.send('state', 'period_start')
if self.period_length():
# TODO: Should replace this with something like Huey/Celery so it'll survive a server restart.
self._timer = threading.Timer(
self.period_length(),
lambda: self.send('state', 'period_end'))
self._timer.start() | python | def _on_connect(self, participant):
"""Called from the WebSocket consumer. Checks if all players in the group
have connected; runs :meth:`when_all_players_ready` once all connections
are established.
"""
lock = get_redis_lock()
if not lock:
lock = fake_lock()
with lock:
self.refresh_from_db()
if self.ran_ready_function:
return
for player in self.get_players():
if Connection.objects.filter(participant__code=player.participant.code).count() == 0:
return
self.when_all_players_ready()
self.ran_ready_function = timezone.now()
self.save()
self.send('state', 'period_start')
if self.period_length():
# TODO: Should replace this with something like Huey/Celery so it'll survive a server restart.
self._timer = threading.Timer(
self.period_length(),
lambda: self.send('state', 'period_end'))
self._timer.start() | [
"def",
"_on_connect",
"(",
"self",
",",
"participant",
")",
":",
"lock",
"=",
"get_redis_lock",
"(",
")",
"if",
"not",
"lock",
":",
"lock",
"=",
"fake_lock",
"(",
")",
"with",
"lock",
":",
"self",
".",
"refresh_from_db",
"(",
")",
"if",
"self",
".",
"ran_ready_function",
":",
"return",
"for",
"player",
"in",
"self",
".",
"get_players",
"(",
")",
":",
"if",
"Connection",
".",
"objects",
".",
"filter",
"(",
"participant__code",
"=",
"player",
".",
"participant",
".",
"code",
")",
".",
"count",
"(",
")",
"==",
"0",
":",
"return",
"self",
".",
"when_all_players_ready",
"(",
")",
"self",
".",
"ran_ready_function",
"=",
"timezone",
".",
"now",
"(",
")",
"self",
".",
"save",
"(",
")",
"self",
".",
"send",
"(",
"'state'",
",",
"'period_start'",
")",
"if",
"self",
".",
"period_length",
"(",
")",
":",
"# TODO: Should replace this with something like Huey/Celery so it'll survive a server restart.",
"self",
".",
"_timer",
"=",
"threading",
".",
"Timer",
"(",
"self",
".",
"period_length",
"(",
")",
",",
"lambda",
":",
"self",
".",
"send",
"(",
"'state'",
",",
"'period_end'",
")",
")",
"self",
".",
"_timer",
".",
"start",
"(",
")"
] | Called from the WebSocket consumer. Checks if all players in the group
have connected; runs :meth:`when_all_players_ready` once all connections
are established. | [
"Called",
"from",
"the",
"WebSocket",
"consumer",
".",
"Checks",
"if",
"all",
"players",
"in",
"the",
"group",
"have",
"connected",
";",
"runs",
":",
"meth",
":",
"when_all_players_ready",
"once",
"all",
"connections",
"are",
"established",
"."
] | train | https://github.com/Leeps-Lab/otree-redwood/blob/59212f61a256ef77e0a9ed392ff497ea83ee6245/otree_redwood/models.py#L105-L133 |
Leeps-Lab/otree-redwood | otree_redwood/models.py | Group._on_disconnect | def _on_disconnect(self, participant):
"""Trigger the :meth:`when_player_disconnects` callback."""
player = None
for p in self.get_players():
if p.participant == participant:
player = p
break
self.when_player_disconnects(player) | python | def _on_disconnect(self, participant):
"""Trigger the :meth:`when_player_disconnects` callback."""
player = None
for p in self.get_players():
if p.participant == participant:
player = p
break
self.when_player_disconnects(player) | [
"def",
"_on_disconnect",
"(",
"self",
",",
"participant",
")",
":",
"player",
"=",
"None",
"for",
"p",
"in",
"self",
".",
"get_players",
"(",
")",
":",
"if",
"p",
".",
"participant",
"==",
"participant",
":",
"player",
"=",
"p",
"break",
"self",
".",
"when_player_disconnects",
"(",
"player",
")"
] | Trigger the :meth:`when_player_disconnects` callback. | [
"Trigger",
"the",
":",
"meth",
":",
"when_player_disconnects",
"callback",
"."
] | train | https://github.com/Leeps-Lab/otree-redwood/blob/59212f61a256ef77e0a9ed392ff497ea83ee6245/otree_redwood/models.py#L135-L142 |
Leeps-Lab/otree-redwood | otree_redwood/models.py | Group.send | def send(self, channel, payload):
"""Send a message with the given payload on the given channel.
Messages are broadcast to all players in the group.
"""
with track('send_channel=' + channel):
with track('create event'):
Event.objects.create(
group=self,
channel=channel,
value=payload)
ChannelGroup(str(self.pk)).send(
{'text': json.dumps({
'channel': channel,
'payload': payload
})}) | python | def send(self, channel, payload):
"""Send a message with the given payload on the given channel.
Messages are broadcast to all players in the group.
"""
with track('send_channel=' + channel):
with track('create event'):
Event.objects.create(
group=self,
channel=channel,
value=payload)
ChannelGroup(str(self.pk)).send(
{'text': json.dumps({
'channel': channel,
'payload': payload
})}) | [
"def",
"send",
"(",
"self",
",",
"channel",
",",
"payload",
")",
":",
"with",
"track",
"(",
"'send_channel='",
"+",
"channel",
")",
":",
"with",
"track",
"(",
"'create event'",
")",
":",
"Event",
".",
"objects",
".",
"create",
"(",
"group",
"=",
"self",
",",
"channel",
"=",
"channel",
",",
"value",
"=",
"payload",
")",
"ChannelGroup",
"(",
"str",
"(",
"self",
".",
"pk",
")",
")",
".",
"send",
"(",
"{",
"'text'",
":",
"json",
".",
"dumps",
"(",
"{",
"'channel'",
":",
"channel",
",",
"'payload'",
":",
"payload",
"}",
")",
"}",
")"
] | Send a message with the given payload on the given channel.
Messages are broadcast to all players in the group. | [
"Send",
"a",
"message",
"with",
"the",
"given",
"payload",
"on",
"the",
"given",
"channel",
".",
"Messages",
"are",
"broadcast",
"to",
"all",
"players",
"in",
"the",
"group",
"."
] | train | https://github.com/Leeps-Lab/otree-redwood/blob/59212f61a256ef77e0a9ed392ff497ea83ee6245/otree_redwood/models.py#L144-L158 |
Leeps-Lab/otree-redwood | otree_redwood/models.py | Group.save | def save(self, *args, **kwargs):
"""
BUG: Django save-the-change, which all oTree models inherit from,
doesn't recognize changes to JSONField properties. So saving the model
won't trigger a database save. This is a hack, but fixes it so any
JSONFields get updated every save. oTree uses a forked version of
save-the-change so a good alternative might be to fix that to recognize
JSONFields (diff them at save time, maybe?).
"""
super().save(*args, **kwargs)
if self.pk is not None:
update_fields = kwargs.get('update_fields')
json_fields = {}
for field in self._meta.get_fields():
if isinstance(field, JSONField) and (update_fields is None or field.attname in update_fields):
json_fields[field.attname] = getattr(self, field.attname)
self.__class__._default_manager.filter(pk=self.pk).update(**json_fields) | python | def save(self, *args, **kwargs):
"""
BUG: Django save-the-change, which all oTree models inherit from,
doesn't recognize changes to JSONField properties. So saving the model
won't trigger a database save. This is a hack, but fixes it so any
JSONFields get updated every save. oTree uses a forked version of
save-the-change so a good alternative might be to fix that to recognize
JSONFields (diff them at save time, maybe?).
"""
super().save(*args, **kwargs)
if self.pk is not None:
update_fields = kwargs.get('update_fields')
json_fields = {}
for field in self._meta.get_fields():
if isinstance(field, JSONField) and (update_fields is None or field.attname in update_fields):
json_fields[field.attname] = getattr(self, field.attname)
self.__class__._default_manager.filter(pk=self.pk).update(**json_fields) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"pk",
"is",
"not",
"None",
":",
"update_fields",
"=",
"kwargs",
".",
"get",
"(",
"'update_fields'",
")",
"json_fields",
"=",
"{",
"}",
"for",
"field",
"in",
"self",
".",
"_meta",
".",
"get_fields",
"(",
")",
":",
"if",
"isinstance",
"(",
"field",
",",
"JSONField",
")",
"and",
"(",
"update_fields",
"is",
"None",
"or",
"field",
".",
"attname",
"in",
"update_fields",
")",
":",
"json_fields",
"[",
"field",
".",
"attname",
"]",
"=",
"getattr",
"(",
"self",
",",
"field",
".",
"attname",
")",
"self",
".",
"__class__",
".",
"_default_manager",
".",
"filter",
"(",
"pk",
"=",
"self",
".",
"pk",
")",
".",
"update",
"(",
"*",
"*",
"json_fields",
")"
] | BUG: Django save-the-change, which all oTree models inherit from,
doesn't recognize changes to JSONField properties. So saving the model
won't trigger a database save. This is a hack, but fixes it so any
JSONFields get updated every save. oTree uses a forked version of
save-the-change so a good alternative might be to fix that to recognize
JSONFields (diff them at save time, maybe?). | [
"BUG",
":",
"Django",
"save",
"-",
"the",
"-",
"change",
"which",
"all",
"oTree",
"models",
"inherit",
"from",
"doesn",
"t",
"recognize",
"changes",
"to",
"JSONField",
"properties",
".",
"So",
"saving",
"the",
"model",
"won",
"t",
"trigger",
"a",
"database",
"save",
".",
"This",
"is",
"a",
"hack",
"but",
"fixes",
"it",
"so",
"any",
"JSONFields",
"get",
"updated",
"every",
"save",
".",
"oTree",
"uses",
"a",
"forked",
"version",
"of",
"save",
"-",
"the",
"-",
"change",
"so",
"a",
"good",
"alternative",
"might",
"be",
"to",
"fix",
"that",
"to",
"recognize",
"JSONFields",
"(",
"diff",
"them",
"at",
"save",
"time",
"maybe?",
")",
"."
] | train | https://github.com/Leeps-Lab/otree-redwood/blob/59212f61a256ef77e0a9ed392ff497ea83ee6245/otree_redwood/models.py#L160-L176 |
Leeps-Lab/otree-redwood | otree_redwood/models.py | DecisionGroup.when_all_players_ready | def when_all_players_ready(self):
"""Initializes decisions based on ``player.initial_decision()``.
If :attr:`num_subperiods` is set, starts a timed task to run the
sub-periods.
"""
self.group_decisions = {}
self.subperiod_group_decisions = {}
for player in self.get_players():
self.group_decisions[player.participant.code] = player.initial_decision()
self.subperiod_group_decisions[player.participant.code] = player.initial_decision()
if self.num_subperiods():
emitter = DiscreteEventEmitter(
self.period_length() / self.num_subperiods(),
self.period_length(),
self,
self._subperiod_tick)
emitter.start()
elif self.rate_limit():
def _tick(current_interval, intervals):
self.refresh_from_db()
if self._group_decisions_updated:
self.send('group_decisions', self.group_decisions)
self._group_decisions_updated = False
self.save(update_fields=['_group_decisions_updated'])
update_period = self.rate_limit()
emitter = DiscreteEventEmitter(
update_period,
self.period_length(),
self,
_tick)
emitter.start()
self.save() | python | def when_all_players_ready(self):
"""Initializes decisions based on ``player.initial_decision()``.
If :attr:`num_subperiods` is set, starts a timed task to run the
sub-periods.
"""
self.group_decisions = {}
self.subperiod_group_decisions = {}
for player in self.get_players():
self.group_decisions[player.participant.code] = player.initial_decision()
self.subperiod_group_decisions[player.participant.code] = player.initial_decision()
if self.num_subperiods():
emitter = DiscreteEventEmitter(
self.period_length() / self.num_subperiods(),
self.period_length(),
self,
self._subperiod_tick)
emitter.start()
elif self.rate_limit():
def _tick(current_interval, intervals):
self.refresh_from_db()
if self._group_decisions_updated:
self.send('group_decisions', self.group_decisions)
self._group_decisions_updated = False
self.save(update_fields=['_group_decisions_updated'])
update_period = self.rate_limit()
emitter = DiscreteEventEmitter(
update_period,
self.period_length(),
self,
_tick)
emitter.start()
self.save() | [
"def",
"when_all_players_ready",
"(",
"self",
")",
":",
"self",
".",
"group_decisions",
"=",
"{",
"}",
"self",
".",
"subperiod_group_decisions",
"=",
"{",
"}",
"for",
"player",
"in",
"self",
".",
"get_players",
"(",
")",
":",
"self",
".",
"group_decisions",
"[",
"player",
".",
"participant",
".",
"code",
"]",
"=",
"player",
".",
"initial_decision",
"(",
")",
"self",
".",
"subperiod_group_decisions",
"[",
"player",
".",
"participant",
".",
"code",
"]",
"=",
"player",
".",
"initial_decision",
"(",
")",
"if",
"self",
".",
"num_subperiods",
"(",
")",
":",
"emitter",
"=",
"DiscreteEventEmitter",
"(",
"self",
".",
"period_length",
"(",
")",
"/",
"self",
".",
"num_subperiods",
"(",
")",
",",
"self",
".",
"period_length",
"(",
")",
",",
"self",
",",
"self",
".",
"_subperiod_tick",
")",
"emitter",
".",
"start",
"(",
")",
"elif",
"self",
".",
"rate_limit",
"(",
")",
":",
"def",
"_tick",
"(",
"current_interval",
",",
"intervals",
")",
":",
"self",
".",
"refresh_from_db",
"(",
")",
"if",
"self",
".",
"_group_decisions_updated",
":",
"self",
".",
"send",
"(",
"'group_decisions'",
",",
"self",
".",
"group_decisions",
")",
"self",
".",
"_group_decisions_updated",
"=",
"False",
"self",
".",
"save",
"(",
"update_fields",
"=",
"[",
"'_group_decisions_updated'",
"]",
")",
"update_period",
"=",
"self",
".",
"rate_limit",
"(",
")",
"emitter",
"=",
"DiscreteEventEmitter",
"(",
"update_period",
",",
"self",
".",
"period_length",
"(",
")",
",",
"self",
",",
"_tick",
")",
"emitter",
".",
"start",
"(",
")",
"self",
".",
"save",
"(",
")"
] | Initializes decisions based on ``player.initial_decision()``.
If :attr:`num_subperiods` is set, starts a timed task to run the
sub-periods. | [
"Initializes",
"decisions",
"based",
"on",
"player",
".",
"initial_decision",
"()",
".",
"If",
":",
"attr",
":",
"num_subperiods",
"is",
"set",
"starts",
"a",
"timed",
"task",
"to",
"run",
"the",
"sub",
"-",
"periods",
"."
] | train | https://github.com/Leeps-Lab/otree-redwood/blob/59212f61a256ef77e0a9ed392ff497ea83ee6245/otree_redwood/models.py#L213-L245 |
Leeps-Lab/otree-redwood | otree_redwood/models.py | DecisionGroup._subperiod_tick | def _subperiod_tick(self, current_interval, intervals):
"""Tick each sub-period, copying group_decisions to subperiod_group_decisions."""
self.refresh_from_db()
for key, value in self.group_decisions.items():
self.subperiod_group_decisions[key] = value
self.send('group_decisions', self.subperiod_group_decisions)
self.save(update_fields=['subperiod_group_decisions']) | python | def _subperiod_tick(self, current_interval, intervals):
"""Tick each sub-period, copying group_decisions to subperiod_group_decisions."""
self.refresh_from_db()
for key, value in self.group_decisions.items():
self.subperiod_group_decisions[key] = value
self.send('group_decisions', self.subperiod_group_decisions)
self.save(update_fields=['subperiod_group_decisions']) | [
"def",
"_subperiod_tick",
"(",
"self",
",",
"current_interval",
",",
"intervals",
")",
":",
"self",
".",
"refresh_from_db",
"(",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"group_decisions",
".",
"items",
"(",
")",
":",
"self",
".",
"subperiod_group_decisions",
"[",
"key",
"]",
"=",
"value",
"self",
".",
"send",
"(",
"'group_decisions'",
",",
"self",
".",
"subperiod_group_decisions",
")",
"self",
".",
"save",
"(",
"update_fields",
"=",
"[",
"'subperiod_group_decisions'",
"]",
")"
] | Tick each sub-period, copying group_decisions to subperiod_group_decisions. | [
"Tick",
"each",
"sub",
"-",
"period",
"copying",
"group_decisions",
"to",
"subperiod_group_decisions",
"."
] | train | https://github.com/Leeps-Lab/otree-redwood/blob/59212f61a256ef77e0a9ed392ff497ea83ee6245/otree_redwood/models.py#L247-L253 |
Leeps-Lab/otree-redwood | otree_redwood/models.py | DecisionGroup._on_decisions_event | def _on_decisions_event(self, event=None, **kwargs):
"""Called when an Event is received on the decisions channel. Saves
the value in group_decisions. If num_subperiods is None, immediately
broadcasts the event back out on the group_decisions channel.
"""
if not self.ran_ready_function:
logger.warning('ignoring decision from {} before when_all_players_ready: {}'.format(event.participant.code, event.value))
return
with track('_on_decisions_event'):
self.group_decisions[event.participant.code] = event.value
self._group_decisions_updated = True
self.save(update_fields=['group_decisions', '_group_decisions_updated'])
if not self.num_subperiods() and not self.rate_limit():
self.send('group_decisions', self.group_decisions) | python | def _on_decisions_event(self, event=None, **kwargs):
"""Called when an Event is received on the decisions channel. Saves
the value in group_decisions. If num_subperiods is None, immediately
broadcasts the event back out on the group_decisions channel.
"""
if not self.ran_ready_function:
logger.warning('ignoring decision from {} before when_all_players_ready: {}'.format(event.participant.code, event.value))
return
with track('_on_decisions_event'):
self.group_decisions[event.participant.code] = event.value
self._group_decisions_updated = True
self.save(update_fields=['group_decisions', '_group_decisions_updated'])
if not self.num_subperiods() and not self.rate_limit():
self.send('group_decisions', self.group_decisions) | [
"def",
"_on_decisions_event",
"(",
"self",
",",
"event",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"ran_ready_function",
":",
"logger",
".",
"warning",
"(",
"'ignoring decision from {} before when_all_players_ready: {}'",
".",
"format",
"(",
"event",
".",
"participant",
".",
"code",
",",
"event",
".",
"value",
")",
")",
"return",
"with",
"track",
"(",
"'_on_decisions_event'",
")",
":",
"self",
".",
"group_decisions",
"[",
"event",
".",
"participant",
".",
"code",
"]",
"=",
"event",
".",
"value",
"self",
".",
"_group_decisions_updated",
"=",
"True",
"self",
".",
"save",
"(",
"update_fields",
"=",
"[",
"'group_decisions'",
",",
"'_group_decisions_updated'",
"]",
")",
"if",
"not",
"self",
".",
"num_subperiods",
"(",
")",
"and",
"not",
"self",
".",
"rate_limit",
"(",
")",
":",
"self",
".",
"send",
"(",
"'group_decisions'",
",",
"self",
".",
"group_decisions",
")"
] | Called when an Event is received on the decisions channel. Saves
the value in group_decisions. If num_subperiods is None, immediately
broadcasts the event back out on the group_decisions channel. | [
"Called",
"when",
"an",
"Event",
"is",
"received",
"on",
"the",
"decisions",
"channel",
".",
"Saves",
"the",
"value",
"in",
"group_decisions",
".",
"If",
"num_subperiods",
"is",
"None",
"immediately",
"broadcasts",
"the",
"event",
"back",
"out",
"on",
"the",
"group_decisions",
"channel",
"."
] | train | https://github.com/Leeps-Lab/otree-redwood/blob/59212f61a256ef77e0a9ed392ff497ea83ee6245/otree_redwood/models.py#L255-L268 |
Aluriak/tergraw | tergraw/view.py | clean | def clean(matrix):
"""Return a copy of given matrix where keys associated
to space values are discarded"""
return defaultdict(lambda: ' ', {
k: v for k, v in matrix.items() if v != ' '
}) | python | def clean(matrix):
"""Return a copy of given matrix where keys associated
to space values are discarded"""
return defaultdict(lambda: ' ', {
k: v for k, v in matrix.items() if v != ' '
}) | [
"def",
"clean",
"(",
"matrix",
")",
":",
"return",
"defaultdict",
"(",
"lambda",
":",
"' '",
",",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"matrix",
".",
"items",
"(",
")",
"if",
"v",
"!=",
"' '",
"}",
")"
] | Return a copy of given matrix where keys associated
to space values are discarded | [
"Return",
"a",
"copy",
"of",
"given",
"matrix",
"where",
"keys",
"associated",
"to",
"space",
"values",
"are",
"discarded"
] | train | https://github.com/Aluriak/tergraw/blob/7f73cd286a77611e9c73f50b1e43be4f6643ac9f/tergraw/view.py#L11-L16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.