예제 #1
0
def fitX(func, target, *funcArgs, **funcKwargs):
    """
	e.g. fitX(func=kt2e0, target=77.338912, ax=ax, bx=bx) == 5.  
	"""
    def curryFuncWithTarget(func, target, *funcArgs, **funcKwargs):
        argsP = funcArgs
        kwargsP = funcKwargs

        def f(x):
            return (func(x, *argsP, **kwargsP) - target)**2

        return f

    cf = curryFuncWithTarget(func, target, *funcArgs, **funcKwargs)
    (out, infodict, ier, mesg) = [None] * 4
    try:
        (out, infodict, ier,
         mesg) = scipy.optimize.fsolve(func=cf,
                                       x0=((2 * S.rand()) - 0.5),
                                       full_output=1,
                                       xtol=1.0e-04)
        if ier == 1:
            lcfitlogger.debug("Successful fsolve\n")
        else:
            lcfitlogger.warning("Problem with fsolve. ier = %s, mesg = \"%s.\"\n %s\n" % \
                 (ier, mesg.replace('\n', ' '), infodict))
    except Exception, e:
        lcfitlogger.error(
            "Exception with fsolve: \"%s\".  Catching and ignoring..." % e)
예제 #2
0
    def __call__(self, session=None, form=None):
        """ Deal with registration data"""
        data = f2d(form)

        # Log
        lcfitlogger.debug('LcRegistrationProcess:  __call__')

        ## Clean and check data, display error and return if necessary.
        for k in [
                'USERNAME', 'PASSWORD', 'EMAIL', 'FULLNAME', 'REASONS',
                'HOWFIND', 'AFFILIATION'
        ]:
            if (not data.has_key(k)) or LCFIT_EMPTY_ALL_RE.match(
                    data[k]):  # Error
                err_mess = 'Empty strings or other bad data in form: "%s".<br>Please use the back button and correct.' % (
                    k)
                sl = [{
                    'TITLE': 'Registration Error',
                    'LC_ERROR_MESSAGE': err_mess
                }]
                formTemplate = Template.Template(
                    file=self.errorTemplate,
                    searchList=sl,
                    compilerSettings={'prioritizeSearchListOverSelf': True})
                sys.stdout.write("Content-type: text/html")
                sys.stdout.write(str(formTemplate))
                sys.stdout.flush()
                return (0)
            if k in ('USERNAME', 'PASSWORD'):
                data[k] = re.sub('\s*', '', data[k])
            data[k] = data[k].strip()
            data[k] = data[k].replace("'", "")

        ## Insert info into db (email will be sent by daily sweeper)
        try:
            self.lcdb.insertRegRequest(data)
        except LcException, e:
            lcfitlogger.error('Bad Registration request: %s.' %
                              pprint.pformat(e))
            if re.match('.*pending.*', str(e)):
                sys.stdout.write("Status: 303\nLocation: %s\n\n" %
                                 LCFIT_PREV_PEND_ERROR_PAGE)
                sys.stdout.flush()
            elif re.match('.*in-use.*', str(e)):
                sys.stdout.write("Status: 303\nLocation: %s\n\n" %
                                 LCFIT_PREV_REG_ERROR_PAGE)
                sys.stdout.flush()
            else:
                raise
예제 #3
0
def try_execute(dbcon, sql, data=None, fetch_N='all', tries_N=3):
	""" Do the execute, trying to reconnect a few times.  Pass a db
	connection back, either the old one or a new reconnected ref."""

	## TODO incorporate lists of SQL statements and data in order to
	## transactionalize them. ... hm ... But what if you want
	## intermediate data ... hmm.  Maybe a reconnecting cursor is what
	## I want? So then I don't have a bunch of duplicated connection
	## lines.  But what happens if we disconnect or have to roll
	## back.... Hmm...  I am leaving this as-is, because it should be
	## fine for the little application that is LCFIT, but the
	## interface of multiple SQL statements to the DB, handling
	## commits and rollbacks, seems to be a thing I haven't completely
	## figured out.  Perhaps the best approach is to have complex
	## updates/ inserts/ deletions as a server side function, with
	## pure non-transactionally complex selects left explicit.
	tries_comp = 0
	while tries_N >= 0:
		try:
			curs = dbcon.cursor()
			#raise Exception(sql + ' xxx ' + repr(data))
			curs.execute(sql, data)
			if fetch_N == 'all':
				res = curs.fetchall()
			elif fetch_N == 'one':
				res = curs.fetchone()
			elif fetch_N == 'none':
				res = None
			else:
				raise Exception, "Bad value for fetch_N: %s" % fetch_N
			curs.close()
			dbcon.commit()
			return (res,dbcon)
		except (psycopg2.OperationalError, psycopg2.InterfaceError, psycopg2.InternalError), e:
			lcfitlogger.error( "Error trying to execute query, reconnecting: \"%s\", \"%s\"." % (sql, e))
			tries_N -= 1
			time.sleep(2**tries_comp)
			tries_comp += 1
			try:
				dbcon = psycopg2.connect(dbcon.dsn)
			except Exception, e:
				raise LcException, "Exception trying to connect: \"%s\"." % str(e)
			lcfitlogger.warning( "Successfully reconnected, re-executed cursor.")
예제 #4
0
파일: LcUtil.py 프로젝트: forkandwait/LCFIT
def fitX(func, target, *funcArgs, **funcKwargs):
	"""
	e.g. fitX(func=kt2e0, target=77.338912, ax=ax, bx=bx) == 5.  
	"""

	def curryFuncWithTarget(func, target, *funcArgs, **funcKwargs):
		argsP = funcArgs
		kwargsP = funcKwargs
		def f(x):
			return (func(x, *argsP, **kwargsP) - target)**2
		return f 
	cf = curryFuncWithTarget(func, target, *funcArgs, **funcKwargs)
	(out, infodict, ier, mesg) = [None]*4
	try:
		(out, infodict, ier, mesg) = scipy.optimize.fsolve(
			func=cf, x0=((2*S.rand())-0.5), full_output=1, xtol=1.0e-04)
		if ier == 1:
			lcfitlogger.debug( "Successful fsolve\n")
		else:
			lcfitlogger.warning("Problem with fsolve. ier = %s, mesg = \"%s.\"\n %s\n" % \
						  (ier, mesg.replace('\n', ' '), infodict))
	except Exception, e:
		lcfitlogger.error( "Exception with fsolve: \"%s\".  Catching and ignoring..." % e)
예제 #5
0
 def __call__(self, session=None, form=None):
     """ Deal with registration data"""
     data = f2d(form)    
     
     # Log
     lcfitlogger.debug( 'LcRegistrationProcess:  __call__')
     
     ## Clean and check data, display error and return if necessary.
     for k in ['USERNAME', 'PASSWORD', 'EMAIL', 'FULLNAME', 'REASONS', 'HOWFIND', 'AFFILIATION']:
         if (not data.has_key(k)) or LCFIT_EMPTY_ALL_RE.match(data[k]): # Error
             err_mess = 'Empty strings or other bad data in form: "%s".<br>Please use the back button and correct.' % (k)
             sl = [{'TITLE':'Registration Error','LC_ERROR_MESSAGE':err_mess}]
             formTemplate = Template.Template(file=self.errorTemplate, searchList = sl,
                                              compilerSettings={'prioritizeSearchListOverSelf' : True}) 
             sys.stdout.write("Content-type: text/html")
             sys.stdout.write(str(formTemplate))
             sys.stdout.flush()
             return(0)
         if k in ('USERNAME', 'PASSWORD'):
             data[k] = re.sub('\s*', '', data[k]) 
         data[k] = data[k].strip()
         data[k] = data[k].replace("'", "")
         
     ## Insert info into db (email will be sent by daily sweeper)
     try:
         self.lcdb.insertRegRequest(data)
     except LcException, e:
         lcfitlogger.error( 'Bad Registration request: %s.' % pprint.pformat(e))
         if re.match('.*pending.*', str(e)):
             sys.stdout.write("Status: 303\nLocation: %s\n\n" %  LCFIT_PREV_PEND_ERROR_PAGE)
             sys.stdout.flush()
         elif re.match('.*in-use.*', str(e)):
             sys.stdout.write("Status: 303\nLocation: %s\n\n" %  LCFIT_PREV_REG_ERROR_PAGE)
             sys.stdout.flush()
         else:
             raise