Example #1
0
def parse_areaspec(tokens,i):
  """
   Parse Area Value specification
   areaspec ::="area" literal ":" number "," number "," number "," number "=" number "." areaspec | []. 
  """
  if env.verbose:
    print stack()[0][3]+" with token n."+str(i)+" '"+str(tokens[i])+"'"
  if env.aborted:
    return i
  elif i>=len(tokens):
    return len(tokens)
  elif i<len(tokens)-12 and tokens[i]==AREAKEYWORD and \
      is_literal(tokens[i+1]) and tokens[i+2]==STEPSEPARATOR and \
      is_number(tokens[i+3]) and tokens[i+4]==AREASEPARATOR and \
      is_number(tokens[i+5]) and tokens[i+6]==AREASEPARATOR and \
      is_number(tokens[i+7]) and tokens[i+8]==AREASEPARATOR and \
      is_number(tokens[i+9]) and tokens[i+10]==EQUALS and \
      is_number(tokens[i+11]) and tokens[i+12]==END_LINE:
    if env.chem_dict.has_key( tokens[i+1] ):
      env.add_rectarea(tokens[i+1],float(tokens[i+11]),
            float(tokens[i+3]),float(tokens[i+5]),
            float(tokens[i+7]),float(tokens[i+9]))
    else:
      env.abort(stack()[0][3]+": Cant initialize an unknown Molecule. @line:"+str(env.tok_lines[i]))
      print env.errormsg
      return i+1
    i+=13
    i=parse_areaspec(tokens,i)
  else:
    # Unknown token
    pass
  return i
Example #2
0
    def option_handler(self, param_args=None):
        if self.CMD_LINE_HINT:
            usage = '%prog [options] ' + self.CMD_LINE_HINT
        else:
            usage = None
        self.parser = OptionParser(usage,
                                   description=self.DESCRIPTION,
                                   version=self.VERSION,
                                   )

        self.parser.add_option("-v", default=0, action="count", dest="verbose",
                               help='Verbosity level, you can add up to three -v \t\t0=no output, 1, 2, 3=all output')
        self.parser.add_option('-q', '--quiet', dest='verbose', action='store_false')
        self.parser.add_option('--nsca', dest='nsca', default='',
                               help='show result in nsca format, expected param host,srvcname '
                                    '(host where the check is logged), '
                                    'nsca will find destination where to send the data in its own config file)')

        self.custom_options(self.parser)
        if not param_args:
            # if we have param_args this is irrelevant
            if sys.argv[0].find('py.test') > -1:
                sys.argv = [inspect.stack()[4][1]] # during pytest insert progname here
            elif sys.argv[0].find('utrunner.py') > -1:
                sys.argv = [inspect.stack()[4][1]] # during pytest insert progname here
        try:
            self.options, self.args = self.parser.parse_args(param_args)
        except SystemExit as exit_code:
            if self.HELP:
                self.log(self.HELP)
            raise #SystemExit(0) # exiting program after displaying help
Example #3
0
	def debug(*arguments):

		if 0:
			f = inspect.stack()
			f = f[2]
			f = f[0]
			f = inspect.getargvalues(f)
			# f = inspect.getframeinfo(f)
			# f = f.locals.get('self')
			out.println(util.timestamp(), ' [debug] <', str(f), '> ', *arguments)
			return
		if 0:
			out.println(util.timestamp(), ' [debug] ', *arguments)
			return
		if 0:
			# 呼び出しフレーム
			frame_object = inspect.stack()[1]
			# スタックトレース
			trace = traceback.extract_stack(frame_object[0])
			out.println(trace)
			out.println(inspect.getmodule(trace[1][2]))
			info = trace[1][2]
			# info = repr(info)
			out.println(util.timestamp(), ' [debug] <', info, '> ', *arguments)
			return
		if 1:
			f = inspect.currentframe()
			f = inspect.getframeinfo(f)
# print(f.module + '.' + f.function)
			print(repr(f))
Example #4
0
def parse_interval(tokens,i):
  """
   Parse Interval Specification
   interval ::= "intrerval" number "-->" number ":" number "."
  """
  if env.verbose:
    print stack()[0][3]+" with token n."+str(i)+" '"+str(tokens[i])+"'"
  if env.aborted:
    return i
  elif i>=len(tokens):
    return len(tokens)
  elif i<len(tokens)-6 and tokens[i]==INTERVAL_KEYWORD and \
      is_number(tokens[i+1]) and tokens[i+2]==ARROWEND and \
      is_number(tokens[i+3]) and tokens[i+4]==STEPSEPARATOR and \
      is_number(tokens[i+5]) and tokens[i+6]==END_LINE:
    env.set_tbegin(float(tokens[i+1]))
    env.set_tend(float(tokens[i+3]))
    if env.tbegin>= env.tend :
      env.abort(stack()[0][3]+": tbegin >= tend !!! @line:"+str(env.tok_lines[i+1]))
      print >> sys.stderr,  env.errormsg
      return i+1
    env.set_step(float(tokens[i+5]))
    if env.step > (env.tend - env.tbegin):
      env.abort(stack()[0][3]+": Step is bigger than interval! @line:"+str(env.tok_lines[i+5]))
      print env.errormsg
      return i+5
    i+=7
  else:
    #env.abort(stack()[0][3]+": missing interval specification. @line:"+str(env.tok_lines[tokens[i-1]]))
    if env.verbose:
      print "Info: default interval: %f --> %f : %f " % (env.tbegin,env.tend,env.step)
  return i
Example #5
0
 def getTCStepByID(self):
     try:
         tc_obj=testCase(self.rally,self.data)
         tc=tc_obj.getTCByID()
         #query_criteria_tc = 'FormattedID = "%s"' % str(self.data['tc']['FormattedID'])
         #tc_response = self.rally.get('TestCase', fetch=True, query=query_criteria_tc)
         lst=[]
         #for tc in tc_response:  
         query_criteria_ts = 'TestCase = "%s"' % str(tc.ref)
         ts_response=self.rally.get('TestCaseStep', fetch=True, query=query_criteria_ts)                          
         for ts in ts_response:
             dic={}
             for key in dir(ts):                            
                 if not key.endswith("__"):
                     dic[key]=getattr(ts,key)   
             lst.append(dic)
         #pprint(lst)                    
         #print "Test case step obtained, FormattedID: %s, Content: %s" % (str(self.data['tc']['FormattedID']))
         self.logger.debug("Test case step obtained, FormattedID: %s, Content: %s" % (str(self.data['tc']['FormattedID']),lst))
         return ts
     except Exception, details:
         #sys.stderr.write('ERROR: %s \n' % details)
         #x=inspect.stack()
         if 'test_' in inspect.stack()[1][3] or 'test_' in inspect.stack()[2][3]:
             raise
         else:
             #print Exception,details
             self.logger.error('ERROR: %s \n' % details,exc_info=True)
             sys.exit(1)
Example #6
0
def log(s0, s1):
	# s0 = "E" 			<- Log error and EXIT
	# s0 = "I"			<- Log and print message
	# s0 = ""			<- Log method
	# s1 = "Hej hej"	<- Message
	if s0 == "E":
		output = "ERROR: " + strftime("%d %b %Y %H:%M:%S", gmtime()) + " " + inspect.stack()[1][3] + "() " + s1 + "\n"
		file = open("log", "a")
		file.write(output)
		print output # Print message in terminal
		i = 1
		s = ""
		# trace back
		while inspect.stack()[i][3] != "main":
			s = s + "\n" + inspect.stack()[i][3] + "() "
			i = i + 1
			
		s = s + "\n" + inspect.stack()[i][3] + "() "	
		print s
		file = open("log", "a")
		file.write(s)
		quit()	# And quit
	elif s0 == "I":	
		msg = strftime("%d %b %Y %H:%M:%S", gmtime()) + " INFO: "+ s1 + "\n"
		file = open("log", "a")
		file.write(msg)
		print s1
	else:
		output = strftime("%d %b %Y %H:%M:%S", gmtime()) + " " + inspect.stack()[1][3] + "() " + s1 + "\n"
		file = open("log", "a")
		file.write(output)
Example #7
0
def raiseNotDefined():
    fileName = inspect.stack()[1][1]
    line = inspect.stack()[1][2]
    method = inspect.stack()[1][3]

    print("*** Method not implemented: %s at line %s of %s" % (method, line, fileName))
    sys.exit(1)
def createFormatString(status, fmt, level):
    """  Create and return a standard format string, with input format string
         appended
    Parameters
    ----------
    status : str
       'OK', 'ERROR', 'WARNING', 'CRITICAL'
    fmt : str
       Format string
    level : int
       1 if calling function is 1 deep compared to what you want to get line/function/file,
       2 if calling function is 2 deep
    Returns
    -------
    str : The format string
    """

    # Get location of caller ([level+1]'th thing on stack)
    lineno = inspect.stack()[level+1][2]
    funcname = inspect.stack()[level+1][3]
    filename = os.path.basename(inspect.stack()[level+1][1])
    # a standard output format:
    linestr = '%d' % (lineno)
    fStatus = status;
    fStatus = fStatus.ljust(8)
    formatStr = fStatus + WhfConfigType + WhfAction + WhfData + " [" + filename + ":" + linestr + "," + funcname + "] " + fmt
    return formatStr
    def GetFamily(self, testParam=200):
        if testParam == 200:
            headers = {'x-csv-token': str(self.testThis.loginToCSVas()["text"]["access-token"])}
            response = requests.get(url=self.testThis.url, headers=headers)

        if testParam == 405:
            headers = {'x-csv-token': 'DoesntMatter'}
            response = requests.delete(url=self.testThis.url, headers=headers)    

        if response.status_code == 200:
            familyList = json.loads(response.text)["families"]
            for family in familyList:
                self.familyID = family["id"]

        if response.status_code != 200:
            print self.testThis.url
            print response.text
            print headers

        if response.status_code == 200:
            self.testThis.updateTestuff(inspect.stack()[0][3], 'passed')
        else:
            self.testThis.updateTestuff(inspect.stack()[0][3], 'failed')

        return {'text': json.loads(response.text), 'status': response.status_code}
Example #10
0
File: my.py Project: glensk/scripts
def exit(error=None):
    import sys
    import inspect
    from termcolor import colored
    if inspect.stack()[1][3] == '<module>':
        print "Check file ", inspect.stack()[1][1], "for checkpath in the main code, not in some definition"
    else:
        text = ""
        path_full = inspect.stack()[1][1]
        path_name = inspect.getmoduleinfo(path_full).name
        ERROR_GENERAL = "ERROR in Module: " + inspect.stack(
        )[1][3] + "  Skript: " + path_name
        if error is None:
            ERROR = ERROR_GENERAL
        else:
            ERROR = error + " (" + ERROR_GENERAL + ")"
#            print "KA:",ERROR.split()[0][0:5]
            if ERROR.split()[0][0:5] == "ERROR":
                #text = colored(ERROR, 'red', attrs=['bold'])
                text = printred("ERROR")
            else:
                #text = colored(ERROR, 'blue', attrs=['bold'])
                text = printred("ERROR")
        sys.exit(text)
    sys.exit()
Example #11
0
    def status_output(self, level, text, color=white):
        
        function_name = str(inspect.stack()[2][3])
        #print "function_name: %s" % function_name
        if function_name == "<module>":
            function_name = str(inspect.stack()[2][1]).rpartition("./")[2] + ":main"

        class_name = None

        #print "\t%s" % str(dir(inspect.stack()[2][0].f_code))
        #print "\t%s" % str(inspect.stack()[2][0].f_code.co_name)
        #print "\t%s" % str(inspect.stack()[2][0].f_trace)
        #print "\t%s" % str(inspect.stack()[2][0].f_globals["__name__"])
        #print "\t%s" % str(inspect.stack()[2][0].f_globals.viewitems())
        #print "\t%s" % str(inspect.stack()[2][0].f_locals["__class__"])
        if "self" in inspect.stack()[2][0].f_locals.keys():
            #print "\t%s" % str(inspect.stack()[2][0].f_locals["self"])
            #print "\t%s" % str(dir(inspect.stack()[2][0].f_locals["self"]))
            
            class_name = str(inspect.stack()[2][0].f_locals["self"])
            while class_name.find(".") != -1:
                class_name = class_name.partition(".")[2]
            class_name = class_name.partition(" ")[0]

            class_name = class_name.strip("(")
            class_name = class_name.strip(")")

        if class_name is not None and (len(class_name) > 0) and (class_name.strip() != "<module>"):
            d = "%s:%s: " % (class_name, function_name)
        else:
            d = "%s: " % (function_name)

        text = d + text
        print "%s%s: %s%s" % (color, level, text, white)
Example #12
0
    def chisquaredDemo2(self):
        """
        Demonstrate how to use curve_fit.  Generate data points with an
        exponential function, deviating with random gausian numbers.

        Use curve_fit to fit to these data points.

        Plot the data points and the fit curve to a png file
        """
            
        def func(x, a, b, c):
            return a*np.exp(-b*x) + c

        x = np.linspace(0, 4, 50)
        y = func(x, 2.5, 1.3, 0.5)
        yn = y + 0.2*np.random.normal(size=len(x))
            
        popt, pcov = curve_fit(func, x, yn)
        print 'optimal parameters: ', popt
        print 'uncertainties of parameters: ', pcov

        # plot the data points
        plt.plot(x,yn,'ro')

        # plot the fit line
        xFit = np.linspace(0,4,100)
        yFit = func(xFit, *popt)
        plt.plot(xFit,yFit)
        plt.title(inspect.stack()[0][3])
        plt.savefig(inspect.stack()[0][3]+".png")
 def new_func(*args, **kwargs):
     try:
         try:  # python 2 + python 3
             f_name = func.__name__
             f_file = func.__code__.co_filename
             f_line = func.__code__.co_firstlineno + 1
         except AttributeError:  # maybe some old python 2?
             f_name = func.func_code.co_name
             f_file = func.func_code.co_filename
             f_line = func.func_code.co_firstlineno + 1
         # end try
         try:
             logger.warning(
                 "Call to deprecated function {f_name} at file {f_file}:{f_line}\n"
                 "{msg}Called from function {c_name} at file {c_file}:{c_line}\nLine: {c_code}".format(
                     f_name=f_name, f_file=f_file,
                     f_line=f_line,
                     msg="Warning: " + message.strip() + "\n" if message else "",
                     c_name=inspect.stack()[1][3], c_file=inspect.stack()[1][1],
                     c_line=inspect.stack()[1][2], c_code=inspect.stack()[1][4][0],
                 ))
         except TypeError:
             logger.warning(
                 "Call to deprecated function {f_name} at file {f_file}:{f_line}{msg}".format(
                     f_name=f_name, f_file=f_file,
                     f_line=f_line, msg="\nWarning: " + message.strip() if message else ""
                 ))
     except (AttributeError, TypeError):
         logger.warning(
             "Call to deprecated function.{msg}".format(msg="\nWarning: " + message.strip() if message else ""),
             exc_info=True
         )
     return func(*args, **kwargs)
Example #14
0
 def checkDeptokens(cls,corpus):
     reWs = re.compile(r'^\s*$')
     valid = True
     # each non-whitespace subtoken must be assigned
     # exactly one reltoken
     for sentence in corpus.sentences:
         seen = {}
         for deptoken in sentence.deptokens.values():
             for x in deptoken.getNested():
                 if reWs.search(x.text):
                     printWarning(cls,inspect.stack()[0][3],
                                  "Whitespace subtoken %s in token %s"%
                                  (x.id,deptoken.id))
                 if x.id in seen.keys():
                     printError(cls,inspect.stack()[0][3],
                                "Double-assigned subtoken %s (tokens %s and %s)"%
                                (x.id,seen[x],deptoken.id))
                     valid = False
                 else:
                     seen[x.id] = deptoken.id
         for subtoken in sentence.subtokens.values():
             if not subtoken.id in seen and not reWs.search(subtoken.text):
                 printError(cls,inspect.stack()[0][3],
                            "Non-assigned subtoken %s"%(subtoken.id))
                 valid = False
     return(valid)
Example #15
0
 async def _get_channel(self, guild):
     if not inspect.stack()[2][3] in ["_warn"]:
         events = await self.config.guild(guild).events()
         return discord.utils.get(
             self.bot.get_all_channels(), id=events[inspect.stack()[2][3]]["channel"]
         )
     return False
Example #16
0
    def fast_stack_buster(self, root_word, not_candidates):
        """Returns longest last letter-first letter sequence starting with root_word formed from curr_candidates dictionary.

        curr_candidates: Dictionary containing all candidates, except those that are already in the sequence.

        A recursive function that will probably kill your stack if you try to catch'em all.
        Builds longest sequence "backwards".
        """
        self.total_calls += 1
        if not self.total_calls % 1000:
            print("Made {0} calls so far.".format(self.total_calls))
        # Keep track of number of open stack frames, just for fun
        if len(inspect.stack()) > self.lib_max_stack_frames:
            self.lib_max_stack_frames = len(inspect.stack())

        self.stack_frames += 1
        if self.stack_frames > self.max_stack_frames:
            self.max_stack_frames = self.stack_frames

        sequences = []
        for candidate in self.all_candidates:
            if candidate not in not_candidates and hacky_is_llfl_match(root_word, candidate):
                next_not_candidates = not_candidates.copy()
                next_not_candidates[candidate] = None
                sequences.append(self.fast_stack_buster(candidate, next_not_candidates))
        
        self.stack_frames -= 1

        if len(sequences) < 1:
            return [root_word]
        else:
            return [root_word] + max(sequences, key=len)
Example #17
0
    def validateSemantic(cls,corpus,target):
        """
        Performs semantic validation on the data.

        @param corpus: the corpus
        @type corpus: Corpus instance
        @param target: target format
        @type target: string

        @return: validity of the corpus
        @rtype: boolean
        """
        printMessage(cls,inspect.stack()[0][3],
                     "Validating against '%s' semantics.."%(target))

        if target=="new":
            testfunction = Validator.isValidNew
        elif target=="relaxed":
            testfunction = Validator.isValidRelaxed
        elif target=="compatible":
            testfunction = Validator.isValidCompatible
        else:
            printError(cls,inspect.stack()[0][3],"Cannot validate '%s' format"%target)
            return(False)
        
        valid = testfunction(corpus)
        if valid:
            printMessage(cls,inspect.stack()[0][3],"Valid semantics")
        else:
            printError(cls,inspect.stack()[0][3],"Invalid semantics")
        return(valid)
Example #18
0
def determine_main(name):
    ''' Find the calling main module
    
    :Parameters:

    name : str
           Name of the calling module
    
    :Returns:
    
    module : Module
             Calling main module
    '''
    
    if name == '__main__':
        import inspect
        main_module = inspect.getmodule(inspect.stack()[1][0])
        #main_module = inspect.getmodule(inspect.stack()[2][0])
        if main_module is None:
            name = os.path.splitext(inspect.stack()[1][1])[0]
            name = name.replace(os.sep, '.')
            main_module = __import__(name, fromlist="*")
        elif main_module.__name__ == '__main__':
            name = os.path.splitext(inspect.stack()[1][1])[0]
            name = name.replace(os.sep, '.')
            while name.find('.') != -1:
                try:
                    main_module = __import__(name, fromlist="*")
                except:
                    name = name.split('.', 1)[1]
                else:
                    if main_module.__name__ != '__main__': break
    else:
        main_module = sys.modules[name]
    return main_module
Example #19
0
File: cb.py Project: eunchong/infra
  def _expect_dir(self):
    """Locate the directory containing this test's expectations.

    First we look for whether this was called via a test_*() method.  If
    we find such a method in the stack, we set the expectations directory
    to be based on that location.

    If we can't find a test_*() method on the stack, then we set the
    expectations directory to just be similar to the test filename.
    """
    # Search for a *_test.py filename on the stack.  We should find this, so
    # we raise an Exception if we can't find it.
    test_filename = None
    for stack in inspect.stack():
      if stack[1].endswith('_test.py'):
        md = re.match(r'.*/([^/]*_test).py$', stack[1])
        if md and md.group(1):
          test_filename = md.group(1)
          break
    if test_filename is None:
      raise Exception('can not determine test_filename')

    # Search for a test_* method on the stack.  If we find it, we'll include
    # it in the pathname to the expectations directory.
    test_method = None
    for stack in inspect.stack():
      if stack[3].startswith('test_'):
        test_method = stack[3]
        break
    expect_dir = os.path.join(self.TEST_DIR, test_filename + '.files')
    if test_method is not None:
        expect_dir = os.path.join(expect_dir, test_method)
    return expect_dir
Example #20
0
def delegate(func):
    print inspect.stack()[1]
    def inner(self, *args, **kwargs):
        print self, inspect.stack()[0][3]
        for worker in self.workers:
            func(worker, *args, **kwargs)
    return inner
Example #21
0
 def get_code_line(self):
     # first frame is this line, then check_line_changed(), then 2 callbacks,
     # then actual code.
     try:
         return inspect.stack()[4][1:]
     except:
         return inspect.stack()[0][1:]
Example #22
0
 def __getErrFilePath(self):
     '''
     得到发生error的文件的路径
     '''
     n = len(inspect.stack())
     current_file = inspect.stack()[n-1][1]
     return os.path.abspath(current_file)
Example #23
0
def facebook_login(request):
    try:
        if request.is_ajax():
            if request.method == "POST":
                email = request.POST['email']
                username = request.POST['username']
                fb_id = request.POST['fb_id']
                try:
                    user = User.objects.get(id=Fb_user.objects.get(fb_email=email).user_id)
                except Fb_user.DoesNotExist:
                    return register_user_with_fb(request, email, username, fb_id)
                if user is not None:
                    user.backend = 'django.contrib.auth.backends.ModelBackend'
                    login(request, user)
                    return HttpResponse("fblogin_complete", content_type="text/html; charset=utf-8")
                else:
                    send_error_email(inspect.stack()[0][3])
                    return HttpResponse("Cant authenticate", content_type="text/html; charset=utf-8")
            else:
                send_error_email(inspect.stack()[0][3])
                return HttpResponse("request method is not POST", content_type="text/html; charset=utf-8")
        else:
            send_error_email(inspect.stack()[0][3])
            return HttpResponse("not_ajax", content_type="text/html; charset=utf-8")
    except:
        send_error_email(inspect.stack()[0][3])
        return HttpResponse("Error", content_type="text/html; charset=utf-8")
Example #24
0
    def create_master(**params):
        logger.info("Created news_fetcher master")
        logger.info((inspect.stack()[1],inspect.getmodule(inspect.stack()[1][0])))
        if len(params) != 1:
            raise Exception("Wrong param list")

        return NewsFetcher(**params)
Example #25
0
def save_comment(request):
    try:
        if request.method == 'POST':
            if request.user.is_authenticated():
                try:
                    #assessment = request.POST["assessment"]
                    comment = request.POST["comment"]
                    user_fb_id = request.POST["user_fb_id"]
                    from_user = Fb_user.objects.get(user=request.user.id)
                    from_fb_id = from_user.fb_id
                    from_fb_name = from_user.fb_name
                    #update_rating(user_fb_id, assessment)
                    
                    new_comment = Comment.objects.create(fb_id=user_fb_id, comment=comment, from_fb_id=from_fb_id, from_fb_name=from_fb_name)
                    new_comment.save()              
                    return HttpResponse("comment_saved", content_type="text/html; charset=utf-8")
                except:
                    send_error_email(inspect.stack()[0][3])
                    return HttpResponse("Error", content_type="text/html; charset=utf-8")
            else:
                send_error_email(inspect.stack()[0][3])
                return HttpResponse("user_not_authenticated", content_type="text/html; charset=utf-8")
        else:
            send_error_email(inspect.stack()[0][3])
            return HttpResponse("request_not_post", content_type="text/html; charset=utf-8")
    except:
        send_error_email(inspect.stack()[0][3])
        return HttpResponse("Error", content_type="text/html; charset=utf-8")
Example #26
0
def q2print(message, err=0):
    """Prefixes a message with the calling module and function name

    err = 0 is an INFO message
    err = 1 is an ERROR message
    """

    if err == 0 and Messages.info == 0:
        return None
    if err == 1 and Messages.error == 0:
        return None

    maxc = 70
    if err == 0:
        err_strg = 'INFO'
    else:
        err_strg = 'ERROR'
    x = inspect.stack()[1]
    mname = inspect.getmodule(x[0]).__name__
    fname = inspect.stack()[1][3]
    msg = '['+mname+'.'+fname+': '+err_strg+'] '+message
    lmsg = len(msg)
    if lmsg <= maxc:
        print msg
    else:
        msga =  msg.split(' ')
        words = ''
        for word in msga:
            words += word+' '
            if len(words) >= maxc:
                print words
                words = '    '
        if words.replace(' ', '') != '':
            print words
def getClusterHistogram(pointsInCluster, trueLabelHash, histSize=101):
    """
    Given all the points in a cluster, extract a histogram which plots the 
    amount of those points allocated to a true label of the data. This function
    is used as a degree of approximation to cluster accuracy.
    
    @param pointsInCluster: 2D ndarray which holds all the D-dimensional points assigned to the cluster.
    @param trueLabelHash: a hash table which maps the index of a point to its true label in the data.
    @param histSize: The size of the histogram to build (by default 101, corresponding to Caltech 101's labels).
    @return a histogram as described above
    @return the maximal true label in the cluster
    @raise LogicalError when the first or second parameter is None, or when histSize <= 0.      
    """

    if pointsInCluster is None or trueLabelHash is None:
        raise LogicalError, "Method %s: None arguments were provided." % (stack()[0][3])
    if histSize is None or histSize <= 0:
        raise LogicalError, "Method %s: histSize parameter should be a positive integer (provided: %s)" % (
            stack()[0][3],
            str(histSize),
        )

    trueLabels = [trueLabelHash[point] for point in pointsInCluster]
    histogram, _binEdges = np.histogram(trueLabels, range(0, histSize + 1))
    return histogram, Counter(trueLabels).most_common(1)[0][0]
Example #28
0
def get_caller(message=None):
    module = inspect.getmodule(inspect.stack()[2][0])

    # En boxee en ocasiones no detecta el modulo, de este modo lo hacemos manual
    if module is None:
        module = ".".join(os.path.splitext(inspect.stack()[2][1].split("pelisalacarta")[1])[0].split(os.path.sep))[1:]
    else:
        module = module.__name__

    function = inspect.stack()[2][3]

    if module == "__main__":
        module = "pelisalacarta"
    else:
        module = "pelisalacarta." + module
    if message:
        if module not in message:
            if function == "<module>":
                return module + " " + message
            else:
                return module + " [" + function + "] " + message
        else:
            return message
    else:
        if function == "<module>":
            return module
        else:
            return module + "." + function
def PrintLog(loglevel, fixd, *data):
    '''
    打印日志
    '''
    iscontrol = int(memdata.getvalue().split('+++')[0])
    isstdebug = int(memdata.getvalue().split('+++')[1])       #是否发布
    if loglevel == 'exception':
        getattr(loggerfile, loglevel)(fixd)
        if iscontrol != 0:
            getattr(loggercontrol, loglevel)(fixd)
    else:
        systype = platform.system()
        if systype == 'Windows' and isstdebug == 0:
            enty = 'gbk'
        else:
            enty = 'utf-8'

        #获取调用函数的文件名和行号
        filepath = inspect.stack()[1][1]
        filename = os.path.basename(filepath)
        linen = inspect.stack()[1][2]
        fixdd = u'%s[%d] - '

        fixdf = (fixdd + ch2unicode(fixd)).encode('utf-8')
        fixdc = (fixdd + ch2unicode(fixd)).encode(enty)
        valuesf = [filename,linen]
        valuesc = [filename,linen]
        for d in data:
            df = ch2unicode(d).encode('utf-8')
            dc = ch2unicode(d).encode(enty)
            valuesf.append(df)
            valuesc.append(dc)
        getattr(loggerfile, loglevel)(fixdf % tuple(valuesf))
        if iscontrol != 0:
            getattr(loggercontrol, loglevel)(fixdc % tuple(valuesc))
Example #30
0
def _register_completer(args, stdin=None):
    err = None
    if len(args) not in {2, 3}:
        err = ("completer add takes either 2 or 3 arguments.\n"
               "For help, run:  completer help add")
    else:
        name = args[0]
        func_name = args[1]
        if name in builtins.__xonsh_completers__:
            err = ("The name %s is already a registered "
                   "completer function.") % name
        else:
            if func_name in builtins.__xonsh_ctx__:
                func = builtins.__xonsh_ctx__[func_name]
                if not callable(func):
                    err = "%s is not callable" % func_name
            else:
                print(inspect.stack(context=0))
                for frame_info in inspect.stack(context=0):
                    frame = frame_info[0]
                    if func_name in frame.f_locals:
                        func = frame.f_locals[func_name]
                        break
                    elif func_name in frame.f_globals:
                        func = frame.f_globals[func_name]
                        break
                else:
                    err = "No such function: %s" % func_name
    if err is None:
        position = "start" if len(args) == 2 else args[2]
        _add_one_completer(name, func, position)
    else:
        return None, err + '\n', 1
Example #31
0
 def get_transaction_result(
         self,
         transaction: SignedTransactionAPI,
         at_header: BlockHeaderAPI) -> bytes:
     raise NotImplementedError("Chain classes must implement " + inspect.stack()[0][3])
Example #32
0
 def validate_uncles(self, block: BlockAPI) -> None:
     raise NotImplementedError("Chain classes must implement " + inspect.stack()[0][3])
Example #33
0
 def validate_seal(self, header: BlockHeaderAPI) -> None:
     raise NotImplementedError("Chain classes must implement " + inspect.stack()[0][3])
Example #34
0
 async def coro_validate_receipt(self, receipt: ReceiptAPI, at_header: BlockHeaderAPI) -> None:
     raise NotImplementedError("Chain classes must implement " + inspect.stack()[0][3])
Example #35
0
 def mine_block(self, *args: Any, **kwargs: Any) -> BlockAPI:
     raise NotImplementedError("Chain classes must implement " + inspect.stack()[0][3])
Example #36
0
 async def coro_import_block(self, block: BlockAPI, perform_validation: bool=True) -> BlockAPI:
     raise NotImplementedError("Chain classes must implement " + inspect.stack()[0][3])
Example #37
0
 def estimate_gas(
         self,
         transaction: SignedTransactionAPI,
         at_header: BlockHeaderAPI=None) -> int:
     raise NotImplementedError("Chain classes must implement " + inspect.stack()[0][3])
Example #38
0
 def get_transaction_receipt(self, transaction_hash: Hash32) -> ReceiptAPI:
     raise NotImplementedError("Chain classes must implement " + inspect.stack()[0][3])
Example #39
0
 def create_transaction(self, *args: Any, **kwargs: Any) -> SignedTransactionAPI:
     raise NotImplementedError("Chain classes must implement " + inspect.stack()[0][3])
Example #40
0
 def apply_transaction(
         self,
         transaction: SignedTransactionAPI) -> Tuple[BlockAPI, ReceiptAPI, ComputationAPI]:
     raise NotImplementedError("Chain classes must implement " + inspect.stack()[0][3])
Example #41
0
 def get_block(self) -> BlockAPI:
     raise NotImplementedError("Chain classes must implement " + inspect.stack()[0][3])
Example #42
0
 def get_canonical_transaction(self, transaction_hash: Hash32) -> SignedTransactionAPI:
     raise NotImplementedError("Chain classes must implement " + inspect.stack()[0][3])
Example #43
0
 def create_header_from_parent(self,
                               parent_header: BlockHeaderAPI,
                               **header_params: HeaderParams) -> BlockHeaderAPI:
     raise NotImplementedError("Chain classes must implement " + inspect.stack()[0][3])
Example #44
0
 def build_block_with_transactions(self,
                                   transactions: Sequence[SignedTransactionAPI],
                                   parent_header: BlockHeaderAPI=None) -> Tuple[BlockAPI, Tuple[ReceiptAPI, ...], Tuple[ComputationAPI, ...]]:        # noqa: E501
     raise NotImplementedError("Chain classes must implement " + inspect.stack()[0][3])
Example #45
0
def who_is_calling():
    """return the name of the calling function"""
    stack = inspect.stack()[2]
    return "{0}.{1}".format(
        os.path.splitext(os.path.basename(stack[1]))[0], stack[3])
Example #46
0
 async def coro_get_ancestors(self, limit: int, header: BlockHeaderAPI) -> Tuple[BlockAPI, ...]:
     raise NotImplementedError("Chain classes must implement " + inspect.stack()[0][3])
Example #47
0
     if args.loglevel is not None:
         args_log_level = re.sub('\s+', '', args.loglevel.strip().upper())
         try:
             log_level = getattr(logging, args_log_level)
         except AttributeError:
             logging.error(
                 "command line option to set log_level failed "
                 "because '%s' is not a valid level name; using %s" %
                 (args_log_level, log_level_name))
     if args.veryverbose:
         log_level = logging.DEBUG
     elif args.verbose:
         log_level = logging.INFO
     log_level_name = logging.getLevelName(log_level)
     logging.getLogger().setLevel(log_level)
     fn_this = inspect.stack()[0][1].strip()
     title_this = __doc__.strip()
     logging.info(': '.join((fn_this, title_this)))
     if log_level != DEFAULT_LOG_LEVEL:
         logging.warning(
             "logging level changed to %s via command line option" %
             log_level_name)
     else:
         logging.info("using default logging level: %s" % log_level_name)
     logging.debug("command line: '%s'" % ' '.join(sys.argv))
     main(args)
     sys.exit(0)
 except KeyboardInterrupt as e:  # Ctrl-C
     raise e
 except SystemExit as e:  # sys.exit()
     raise e
Example #48
0
def whoami():
    """ return name of calling function """
    return inspect.stack()[1][3]
Example #49
0
 async def _validate_event(self, server):
     try:
         return self.settings[server.id]['events'][inspect.stack(
         )[1][3]] if await self._validate_server(server) else False
     except KeyError:
         return False
Example #50
0
 def get_asset_path(asset_file):
     """Returns a fully-resolved local file path to the test asset."""
     test_path = inspect.stack()[1][1]
     module_path = os.path.split(test_path)[0]
     module_name = os.path.split(test_path)[1].split(".py")[0]
     return os.path.join(module_path, "assets", module_name, asset_file)
def command(**args):
    args["func"] = lambda e: e.via_bot_id is None
    
    stack = inspect.stack()
    previous_stack_frame = stack[1]
    file_test = Path(previous_stack_frame.filename)
    file_test = file_test.stem.replace(".py", "")
    if 1 == 0:
        return print("stupidity at its best")
    else:
        pattern = args.get("pattern", None)
        allow_sudo = args.get("allow_sudo", False)
        allow_edited_updates = args.get('allow_edited_updates', False)
        args["incoming"] = args.get("incoming", False)
        args["outgoing"] = True
        if bool(args["incoming"]):
            args["outgoing"] = False

        try:
            if pattern is not None and not pattern.startswith('(?i)'):
                args['pattern'] = '(?i)' + pattern
        except:
            pass

        reg = re.compile('(.*)')
        if not pattern == None:
            try:
                cmd = re.search(reg, pattern)
                try:
                    cmd = cmd.group(1).replace("$", "").replace("\\", "").replace("^", "")
                except:
                    pass

                try:
                    CMD_LIST[file_test].append(cmd)
                except:
                    CMD_LIST.update({file_test: [cmd]})
            except:
                pass

        if allow_sudo:
            args["from_users"] = list(Config.SUDO_USERS)
            # Mutually exclusive with outgoing (can only set one of either).
            args["incoming"] = True
        del allow_sudo
        try:
            del args["allow_sudo"]
        except:
            pass

        if "allow_edited_updates" in args:
            del args['allow_edited_updates']

        def decorator(func):
            if allow_edited_updates:
                bot.add_event_handler(func, events.MessageEdited(**args))
            bot.add_event_handler(func, events.NewMessage(**args))
            try:
                LOAD_PLUG[file_test].append(func)
            except:
                LOAD_PLUG.update({file_test: [func]})
            return func

        return decorator
Example #52
0
 async def _get_channel(self, server):
     return discord.utils.get(self.bot.get_all_channels(),
                              id=self.settings[server.id]['channels'][
                                  self.event_types[inspect.stack()[2][3]]])
Example #53
0
def get_func_name() -> str:
    """
    get name of the *calling* function
    :return: name of the calling function
    """
    return inspect.stack()[1].frame.f_code.co_name
Example #54
0
File: utils.py Project: imace/miasm
def whoami():
    return inspect.stack()[2][3]
Example #55
0
def getLogger (name=None, moreFrames=0):
  """
  In general, you don't need to call this directly, and will use
  core.getLogger() instead.
  """
  if name is None:
    s = inspect.stack()[1+moreFrames]
    name = s[1]
    if name.endswith('.py'):
      name = name[0:-3]
    elif name.endswith('.pyc'):
      name = name[0:-4]
    if name.startswith(_path):
      name = name[len(_path):]
    elif name.startswith(_ext_path):
      name = name[len(_ext_path):]
    name = name.replace('/', '.').replace('\\', '.') #FIXME: use os.path or whatever

    # Remove double names ("topology.topology" -> "topology")
    if name.find('.') != -1:
      n = name.split('.')
      if len(n) >= 2:
        if n[-1] == n[-2]:
          del n[-1]
          name = '.'.join(n)

    if name.startswith("ext."):
      name = name.split("ext.",1)[1]

    if name.endswith(".__init__"):
      name = name.rsplit(".__init__",1)[0]

  l = logging.getLogger(name)
  g=globals()
  if not hasattr(l, "print"):
    def printmsg (*args, **kw):
      #squelch = kw.get('squelch', True)
      msg = ' '.join((str(s) for s in args))
      s = inspect.stack()[1]
      o = '['
      if 'self' in s[0].f_locals:
        o += s[0].f_locals['self'].__class__.__name__ + '.'
      o += s[3] + ':' + str(s[2]) + '] '
      o += msg
      if o == _squelch:
        if time.time() >= _squelchTime:
          l.debug("[Previous message repeated %i more times]" % (g['_squelchCount']+1,))
          g['_squelchCount'] = 0
          g['_squelchTime'] = time.time() + SQUELCH_TIME
        else:
          g['_squelchCount'] += 1
      else:
        g['_squelch'] = o
        if g['_squelchCount'] > 0:
          l.debug("[Previous message repeated %i more times]" % (g['_squelchCount'],))
        g['_squelchCount'] = 0
        g['_squelchTime'] = time.time() + SQUELCH_TIME
        l.debug(o)

    setattr(l, "print", printmsg)
    setattr(l, "msg", printmsg)

  return l
Example #56
0
def get_current_dir():
    return os.path.dirname(os.path.abspath(inspect.stack()[1][1]))
Example #57
0
    def test_update(self):
        cache = Cache()
        record_type = 'schema:test'
        record_id = 'test_post_02'

        path = 'schema:test/test_post_02'
        
        record_original = {
                '@type': 'schema:test',
                '@id': 'test_post_02',
                'schema:name': 'test post 02',
                'schema:url': 'https://www.test.com',
                'schema:email': '*****@*****.**'
            }
        metadata_original= {
            'schema:name': {
                'kraken:credibility': 50,
                'kraken:id': 'test id'
                }
            }

        record_delta = {
                '@type': 'schema:test',
                '@id': 'test_post_02',
                'schema:name': 'test post TEST',
                'schema:test': 'test'
            }
        
        metadata_delta= {
            'schema:name': {
                'kraken:credibility': 60,
                'kraken:id': 'test id'
                }
            }
        

        record_reference = {
                '@type': 'schema:test',
                '@id': 'test_post_02',
                'schema:name': 'test post TEST',
                'schema:test': 'test',
                'schema:url': 'https://www.test.com',
                'schema:email': '*****@*****.**'
            }

        metadata_reference= {
            'schema:name': {
                'kraken:credibility': 60,
                'kraken:id': 'test id'
            }
        }


        cache.post(record_type, record_id, record_original, metadata_original)
        cache.update(record_type, record_id, record_delta, metadata_delta)

        new_record, new_metadata = cache.get(record_type, record_id)
        
        fn_name = inspect.stack()[0][3]

        if record_reference == new_record and metadata_reference == new_metadata:
            print(fn_name, 'pass')
        else: 
            fn_name = inspect.stack()[0][3]
            print('---')
            print(fn_name, 'fail')
            print(new_metadata)
            print(metadata_reference)
            print('---')
Example #58
0
def get_line_number() -> str:
    """
    get name of the *calling* function
    :return: name of the calling function
    """
    return inspect.stack()[1].frame.f_lineno
Example #59
0
 def get_pipeline_name():
   for _, _, _, method_name, _, _ in inspect.stack():
     if method_name.find('test') != -1:
       return method_name
   return 'unknown_test'
Example #60
0
This includes things like component rendezvous, logging, system status
(up and down events), etc.
"""

from __future__ import print_function

# Set up initial log state
import logging

import inspect
import time
import os
import signal

_path = inspect.stack()[0][1]
_ext_path = _path[0:_path.rindex(os.sep)]
_ext_path = os.path.dirname(_ext_path) + os.sep
_path = os.path.dirname(_path) + os.sep

SQUELCH_TIME = 5

_squelch = ''
_squelchTime = 0
_squelchCount = 0

def getLogger (name=None, moreFrames=0):
  """
  In general, you don't need to call this directly, and will use
  core.getLogger() instead.
  """