def OSCTimeTag(time):
"""Convert a time in floating seconds to its
OSC binary representation
"""
if time > 0:
fract, secs = math.modf(time)
secs = secs - NTP_epoch
binary = struct.pack('>LL', int(secs), int(fract * NTP_units_per_second))
else:
binary = struct.pack('>LL', 0, 1)
return binary
######
#
# OSCMessage decoding functions
#
######
python类modf()的实例源码
def OSCTimeTag(time):
"""Convert a time in floating seconds to its
OSC binary representation
"""
if time > 0:
fract, secs = math.modf(time)
secs = secs - NTP_epoch
binary = struct.pack('>LL', long(secs), long(fract * NTP_units_per_second))
else:
binary = struct.pack('>LL', 0L, 1L)
return binary
######
#
# OSCMessage decoding functions
#
######
def jd_to_date(jd):
jd = jd + 0.5
F, I = math.modf(jd)
I = int(I)
A = math.trunc((I - 1867216.25)/36524.25)
if I > 2299160:
B = I + 1 + A - math.trunc(A / 4.)
else:
B = I
C = B + 1524
D = math.trunc((C - 122.1) / 365.25)
E = math.trunc(365.25 * D)
G = math.trunc((C - E) / 30.6001)
day = C - E + F - math.trunc(30.6001 * G)
if G < 13.5:
month = G - 1
else:
month = G - 13
if month > 2.5:
year = D - 4716
else:
year = D - 4715
return year, month, day
# Find string between 2 strings
def _dict_to_tuple(d):
'''Convert a dictionary to a time tuple. Depends on key values in the
regexp pattern!
'''
# TODO: Adding a ms field to struct_time tuples is problematic
# since they don't have this field. Should use datetime
# which has a microseconds field, else no ms.. When mapping struct_time
# to gDateTime the last 3 fields are irrelevant, here using dummy values to make
# everything happy.
#
retval = _niltime[:]
for k,i in ( ('Y', 0), ('M', 1), ('D', 2), ('h', 3), ('m', 4), ):
v = d.get(k)
if v: retval[i] = int(v)
v = d.get('s')
if v:
msec,sec = _modf(float(v))
retval[6],retval[5] = int(round(msec*1000)), int(sec)
if d.get('neg', 0):
retval[0:5] = [(x is not None or x) and operator.__neg__(x) for x in retval[0:5]]
return tuple(retval)
def secondsInDayToTime(sssod):
# 3600 seconds per hour
(h, s) = divmod(sssod, 3600)
(m, s) = divmod(s, 60)
(fs, s) = math.modf( s )
return datetime.time(int(h), int(m), int(s), int(fs*1.0e6))
## Generalized version of 'quote_split' as found in command.py
## This one defaults to "'" for opening and "'" for closing quotes
## but these characters can be overridden
##
## quote_split do not extract _words_ but split the
## string at the indicated character,
## provided the character is not inside
## quotes
##
## "aap 'noot 1; mies 2'; foo bar"
## results in:
## ["aap 'noot 1;mies 2'", "foo bar"]
def rotateHue ( self, hue_inc ):
""" Rotates the hue value of Colz object """
if isinstance( hue_inc, int ):
hue_inc /= 360.0
newhue = self.h + hue_inc
if newhue > 1.0:
newhue, whole = math.modf(newhue) # Keep decimal part
if newhue < 0.0:
newhue, whole = math.modf(newhue) # Keep decimal part
newhue = 1.0 + newhue
self.h = newhue
self.hsl[0] = self.h
self.hsla[0] = self.h
self.updateFromHsl()
# Return array of integer values
def testModf(self):
self.assertRaises(TypeError, math.modf)
def testmodf(name, result, expected):
(v1, v2), (e1, e2) = result, expected
if abs(v1-e1) > eps or abs(v2-e2):
self.fail('%s returned %r, expected %r'%\
(name, result, expected))
testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
self.assertEqual(math.modf(INF), (0.0, INF))
self.assertEqual(math.modf(NINF), (-0.0, NINF))
modf_nan = math.modf(NAN)
self.assertTrue(math.isnan(modf_nan[0]))
self.assertTrue(math.isnan(modf_nan[1]))
def testModf(self):
self.assertRaises(TypeError, math.modf)
def testmodf(name, result, expected):
(v1, v2), (e1, e2) = result, expected
if abs(v1-e1) > eps or abs(v2-e2):
self.fail('%s returned %r, expected %r'%\
(name, (v1,v2), (e1,e2)))
testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
self.assertEqual(math.modf(INF), (0.0, INF))
self.assertEqual(math.modf(NINF), (-0.0, NINF))
modf_nan = math.modf(NAN)
self.assertTrue(math.isnan(modf_nan[0]))
self.assertTrue(math.isnan(modf_nan[1]))
def testModf(self):
self.assertRaises(TypeError, math.modf)
def testmodf(name, result, expected):
(v1, v2), (e1, e2) = result, expected
if abs(v1-e1) > eps or abs(v2-e2):
self.fail('%s returned %r, expected %r'%\
(name, (v1,v2), (e1,e2)))
testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
self.assertEqual(math.modf(INF), (0.0, INF))
self.assertEqual(math.modf(NINF), (-0.0, NINF))
modf_nan = math.modf(NAN)
self.assertTrue(math.isnan(modf_nan[0]))
self.assertTrue(math.isnan(modf_nan[1]))
convert_lecture_data_to_json.py 文件源码
项目:softuni-course-calendar-scraper
作者: Enether
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def get_utc_offset() -> str:
'''
function gets the difference between our timezones in hours and returns a string that will be put into the iso8601 format
if we're 3 hours ahead, we will return +03:00
if we're 3 hours behind, we will return -03:00
:return:
'''
now = datetime.datetime.now()
local_hour = now.hour
utc_hour = now.utcnow().hour
utc_offset = local_hour - utc_hour
str_preamble = '+' if utc_offset >= 0 else '-'
# convert the fraction and the whole to a string. Works for ints and floats
fraction, whole = math.modf(utc_offset)
fraction = str(fraction)[2:].zfill(2) # from 0.5 get 05 only
whole = str(int(whole)).zfill(2)
return '{preamble}{whole}:{fraction}'.format(preamble=str_preamble, whole=whole, fraction=fraction)
def testModf(self):
self.assertRaises(TypeError, math.modf)
def testmodf(name, result, expected):
(v1, v2), (e1, e2) = result, expected
if abs(v1-e1) > eps or abs(v2-e2):
self.fail('%s returned %r, expected %r'%\
(name, result, expected))
testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
self.assertEqual(math.modf(INF), (0.0, INF))
self.assertEqual(math.modf(NINF), (-0.0, NINF))
modf_nan = math.modf(NAN)
self.assertTrue(math.isnan(modf_nan[0]))
self.assertTrue(math.isnan(modf_nan[1]))
def gradientLine( ctx, points_list, hsl_palette_list, loop_palette = True ):
pal = hsl_palette_list[:]
if loop_palette:
pal.append( hsl_palette_list[0] ) # Duplicate first
rgb = Colz.hslToRgb( *pal[0] )
ctx.set_source_rgb( *rgb )
for i in range( 2, len(points_list), 2 ):
pal_pos = i * ( len(pal) - 1 ) / len(points_list)
col_current = math.floor( pal_pos )
col_next = math.ceil( pal_pos )
frac, whole = math.modf( pal_pos )
if col_current == col_next:
col_next = min( col_current + 1, len(pal) - 1 )
c_mix = Colz.interpolate( pal[col_current], pal[col_next], frac )
ctx.set_source_rgb( *c_mix.rgb )
ctx.move_to( points_list[i-2], points_list[i-1] )
ctx.line_to( points_list[i], points_list[i+1] )
ctx.stroke()
# Pass caito ctx, list of points, list of colors ( colz )
def rotateHue ( self, hue_inc ):
""" Rotates the hue value of Colz object """
if isinstance( hue_inc, int ):
hue_inc /= 360.0
newhue = self.h + hue_inc
if newhue > 1.0:
newhue, whole = math.modf(newhue) # Keep decimal part
if newhue < 0.0:
newhue, whole = math.modf(newhue) # Keep decimal part
newhue = 1.0 + newhue
self.h = newhue
self.hsl[0] = self.h
self.hsla[0] = self.h
self.updateFromHsl()
# Return array of integer values
def testModf(self):
self.assertRaises(TypeError, math.modf)
def testmodf(name, result, expected):
(v1, v2), (e1, e2) = result, expected
if abs(v1-e1) > eps or abs(v2-e2):
self.fail('%s returned %r, expected %r'%\
(name, (v1,v2), (e1,e2)))
testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
self.assertEqual(math.modf(INF), (0.0, INF))
self.assertEqual(math.modf(NINF), (-0.0, NINF))
modf_nan = math.modf(NAN)
self.assertTrue(math.isnan(modf_nan[0]))
self.assertTrue(math.isnan(modf_nan[1]))
def _fromtimestamp(cls, t, utc, tz):
"""Construct a datetime from a POSIX timestamp (like time.time()).
A timezone info object may be passed in as well.
"""
frac, t = _math.modf(t)
us = round(frac * 1e6)
if us >= 1000000:
t += 1
us -= 1000000
elif us < 0:
t -= 1
us += 1000000
converter = _time.gmtime if utc else _time.localtime
y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
ss = min(ss, 59) # clamp out leap seconds if the platform has them
return cls(y, m, d, hh, mm, ss, us, tz)
def testModf(self):
self.assertRaises(TypeError, math.modf)
def testmodf(name, result, expected):
(v1, v2), (e1, e2) = result, expected
if abs(v1-e1) > eps or abs(v2-e2):
self.fail('%s returned %r, expected %r'%\
(name, result, expected))
testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
self.assertEqual(math.modf(INF), (0.0, INF))
self.assertEqual(math.modf(NINF), (-0.0, NINF))
modf_nan = math.modf(NAN)
self.assertTrue(math.isnan(modf_nan[0]))
self.assertTrue(math.isnan(modf_nan[1]))
def testModf(self):
self.assertRaises(TypeError, math.modf)
def testmodf(name, result, expected):
(v1, v2), (e1, e2) = result, expected
if abs(v1-e1) > eps or abs(v2-e2):
self.fail('%s returned %r, expected %r'%\
(name, (v1,v2), (e1,e2)))
testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
self.assertEqual(math.modf(INF), (0.0, INF))
self.assertEqual(math.modf(NINF), (-0.0, NINF))
modf_nan = math.modf(NAN)
self.assertTrue(math.isnan(modf_nan[0]))
self.assertTrue(math.isnan(modf_nan[1]))
def OSCTimeTag(time):
"""Convert a time in floating seconds to its
OSC binary representation
"""
if time > 0:
fract, secs = math.modf(time)
secs = secs - NTP_epoch
binary = struct.pack('>LL', long(secs), long(fract * NTP_units_per_second))
else:
binary = struct.pack('>LL', 0L, 1L)
return binary
######
#
# OSCMessage decoding functions
#
######
def save_clip_img():
img=cv.LoadImage('static/InterceptedIMG/clip.jpg')
vertical_distance_decimal,vertical_distance_integer = math.modf(float(640)/19)
parallel_distance_decimal,parallel_distance_integer = math.modf(float(480)/19)
#print vertical_distance_decimal,vertical_distance_integer,parallel_distance_decimal,parallel_distance_integer
draw_img = cv2.imread('static/InterceptedIMG/clip.jpg')
for i in range(19):
for j in range(19):
cv2.rectangle(draw_img,(0+int(33.68*i),int(25.26*j)),(int(33.68*(i+1)),int(25.26*(j+1))),(0,255,0),1)
cv2.imshow('image',draw_img)
k = cv2.waitKey(0) & 0xFF
if k == 27:
cv2.destroyAllWindows()
for i in range(19):
for j in range(19):
wn_position =(int(vertical_distance_integer*i)+int(vertical_distance_decimal*i),int(parallel_distance_integer*j)+int(parallel_distance_decimal*j))
es_position =(int(vertical_distance_integer*(i+1)+int(vertical_distance_decimal*i)),int(parallel_distance_integer*(j+1))+int(parallel_distance_decimal*j))
img_backup=cv.CloneImage(img)
cv.SetImageROI(img_backup,(wn_position[0],wn_position[1],33,25))
cv.SaveImage('static/ClippedImg/%d_%d.jpg'%(j,i),img_backup)
def testModf(self):
self.assertRaises(TypeError, math.modf)
def testmodf(name, result, expected):
(v1, v2), (e1, e2) = result, expected
if abs(v1-e1) > eps or abs(v2-e2):
self.fail('%s returned %r, expected %r'%\
(name, result, expected))
testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
self.assertEqual(math.modf(INF), (0.0, INF))
self.assertEqual(math.modf(NINF), (-0.0, NINF))
modf_nan = math.modf(NAN)
self.assertTrue(math.isnan(modf_nan[0]))
self.assertTrue(math.isnan(modf_nan[1]))
def OSCTimeTag(time):
"""Convert a time in floating seconds to its
OSC binary representation
"""
if time > 0:
fract, secs = math.modf(time)
secs = secs - NTP_epoch
binary = struct.pack('>LL', int(secs), int(fract * NTP_units_per_second))
else:
binary = struct.pack('>LL', 0, 1)
return binary
######
#
# OSCMessage decoding functions
#
######
def update_index_t_info (starttime, samples, sps) :
global DAS_INFO
#tdoy = timedoy.TimeDOY ()
ph5file = EXREC.filename
ph5path = '/Experiment_g/Receivers_g/' + EXREC.ph5_g_receivers.current_g_das._v_name
das = ph5path[32:]
stoptime = starttime + (float (samples) / float (sps))
di = Index_t_Info (das, ph5file, ph5path, starttime, stoptime)
if not DAS_INFO.has_key (das) :
DAS_INFO[das] = []
DAS_INFO[das].append (di)
logging.info ("DAS: {0} File: {1} First Sample: {2} Last Sample: {3}".format (das, ph5file, time.ctime (starttime), time.ctime (stoptime)))
#startms, startsecs = math.modf (starttime)
#startms = int (startms * 1000.); startsecs = int (startsecs)
#stopms, stopsecs = math.modf (stoptime)
#stopms = int (stopms * 1000.); stopsecs = int (stopsecs)
#ptimestart = tdoy.epoch2PasscalTime (startsecs, startms)
#ptimestop = tdoy.epoch2PasscalTime (stopsecs, stopms)
#print ph5file, ph5path, ptimestart, ptimestop
def update_index_t_info (starttime, samples, sps) :
global DAS_INFO
ph5file = EXREC.filename
ph5path = '/Experiment_g/Receivers_g/' + EXREC.ph5_g_receivers.current_g_das._v_name
das = ph5path[32:]
stoptime = starttime + (float (samples) / float (sps))
di = Index_t_Info (das, ph5file, ph5path, starttime, stoptime)
if not DAS_INFO.has_key (das) :
DAS_INFO[das] = []
DAS_INFO[das].append (di)
logging.info ("DAS: {0} File: {1} First Sample: {2} Last Sample: {3}".format (das, ph5file, time.ctime (starttime), time.ctime (stoptime)))
#startms, startsecs = math.modf (starttime)
#startms = int (startms * 1000.); startsecs = int (startsecs)
#stopms, stopsecs = math.modf (stoptime)
#stopms = int (stopms * 1000.); stopsecs = int (stopsecs)
#ptimestart = tdoy.epoch2PasscalTime (startsecs, startms)
#ptimestop = tdoy.epoch2PasscalTime (stopsecs, stopms)
#print ph5file, ph5path, ptimestart, ptimestop
# YYY YYY
def json2generator(data, arrayKey=None):
"""
??????? ???????????? ?????????? json ? ?????????. ??? ????????? ???????? ?????? ?????? ?? ???????? ??????? ??????. ????? ?????? ????????? ?????? ??? ??????? (??????? ????? ??????????? ? ?????????). arrayKey ?????? ????????? ?? ??????, ????? ???? ???????? (key1.key2)
"""
from ijson import common
# from io import BytesIO
from cStringIO import StringIO
#! yajl2 ??????? ???????? ??????????? ???????, ?? ?? ?????? ?????? ??? ? ?? ??????? ??? ??????????, ????? "Yajl shared object cannot be found"
try: import ijson.backends.yajl2_cffi as ijson
except:
try: from ijson.backends import yajl2 as ijson
except:
try: from ijson.backends import yajl as ijson
except: from ijson.backends import python as ijson
try: f=StringIO(data)
except: f=StringIO(data.encode('utf-8'))
def _fixJSON(event):
# ??????? ?????????? "????" ?????????, ??????? ???????? ??? ???????? ???? ???????? ? decimal()
if event[1]=='number':
return (event[0], event[1], float(event[2]) if math.modf(event[2])[0] else int(event[2]))
else: return event
events=imap(_fixJSON, ijson.parse(f))
g=common.items(events, (arrayKey+'.item' if arrayKey else 'item'))
# g=ijson.items(f, (arrayKey+'.item' if arrayKey else 'item'))
return g
def getTimeTagStr(self):
"""Return the TimeTag as a human-readable string
"""
fract, secs = math.modf(self.timetag)
out = time.ctime(secs)[11:19]
out += ("%.3f" % fract)[1:]
return out
def getTimeTagStr(self):
"""Return the TimeTag as a human-readable string
"""
fract, secs = math.modf(self.timetag)
out = time.ctime(secs)[11:19]
out += ("%.3f" % fract)[1:]
return out
def iadd(t1, offset):
if not isinstance(t1, Time):
return t1
tmp=_copy.copy(t1)
# make into tics
pfrac,pwhole = math.modf(offset*Time.TicFreq)
tfrac = long(tmp.pf250_) + int(pfrac * Time.Two32)
tmp.ps250_ += long(pwhole) + (tfrac>>32)
tmp.pf250_ = int(tfrac)
return tmp
def setFromTime(self, time_sec=time.time() ):
"""
Create a sdds time object from the input parameter. If the time_sec is from the epoch
then we need to convert to the current year as per spec.
"""
if time_sec:
if time_sec >= self.startofyear:
# UTC.. need to convert to SDDS EPOCH
time_sec = time_sec - self.startofyear
pfrac, pwhole = math.modf(time_sec*Time.TicFreq)
self.ps250_ = long(pwhole)
self.pf250_ = int( pfrac*Time.Two32)
#print "td: %12Lu %12u %16.2Lf " % ( self.ps250_, self.pf250_, pfrac )
def setFromPartial( self, integral, fractional ):
pfrac, pwhole= math.modf(fractional*Time.TicFreq)
self.ps250_ = long(integral*Time.TicFreqLong) + long(pwhole)
self.pf250_ = int( pfrac * Time.Two32)
#print "td: %12Lu %12u %16.2Lf " % ( self.ps250_, self.pf250_, pfrac )
def normalize(tstamp):
# Get fractional adjustment from whole seconds
fadj, tstamp.twsec = math.modf(tstamp.twsec)
# Adjust fractional seconds and get whole seconds adjustment
tstamp.tfsec, wadj = math.modf(tstamp.tfsec + fadj)
# If fractional seconds are negative, borrow a second from the whole
# seconds to make it positive, normalizing to [0,1)
if (tstamp.tfsec < 0.0):
tstamp.tfsec += 1.0;
wadj -= 1.0;
tstamp.twsec += wadj;