_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q19400
|
ItModule.bruteVersionStr
|
train
|
def bruteVersionStr(self, valu):
'''
Brute force the version out of a string.
Args:
valu (str): String to attempt to get version information for.
Notes:
This first attempts to parse strings using the it:semver normalization
before attempting to extract version parts out of the string.
Returns:
int, dict: The system normalized version integer and a subs dictionary.
'''
try:
valu, info = self.core.model.type('it:semver').norm(valu)
subs = info.get('subs')
return valu, subs
except s_exc.BadTypeValu:
# Try doing version part extraction by noming through the string
subs = s_version.parseVersionParts(valu)
if subs is None:
raise s_exc.BadTypeValu(valu=valu, name='bruteVersionStr',
mesg='Unable to brute force version parts out of the string')
if subs:
valu = s_version.packVersion(subs.get('major'),
subs.get('minor', 0),
subs.get('patch', 0))
return valu, subs
|
python
|
{
"resource": ""
}
|
q19401
|
chopurl
|
train
|
def chopurl(url):
'''
A sane "stand alone" url parser.
Example:
info = chopurl(url)
'''
ret = {}
if url.find('://') == -1:
raise s_exc.BadUrl(':// not found in [{}]!'.format(url))
scheme, remain = url.split('://', 1)
ret['scheme'] = scheme.lower()
# carve query params from the end
if remain.find('?') != -1:
query = {}
remain, queryrem = remain.split('?', 1)
for qkey in queryrem.split('&'):
qval = None
if qkey.find('=') != -1:
qkey, qval = qkey.split('=', 1)
query[qkey] = qval
ret['query'] = query
pathrem = ''
slashoff = remain.find('/')
if slashoff != -1:
pathrem = remain[slashoff:]
remain = remain[:slashoff]
# detect user[:passwd]@netloc syntax
if remain.find('@') != -1:
user, remain = remain.rsplit('@', 1)
if user.find(':') != -1:
user, passwd = user.split(':', 1)
ret['passwd'] = passwd
ret['user'] = user
# remain should be down to host[:port]
# detect ipv6 [addr]:port syntax
if remain.startswith('['):
hostrem, portstr = remain.rsplit(':', 1)
ret['port'] = int(portstr)
ret['host'] = hostrem[1:-1]
# detect ipv6 without port syntax
elif remain.count(':') > 1:
ret['host'] = remain
# regular old host or host:port syntax
else:
if remain.find(':') != -1:
remain, portstr = remain.split(':', 1)
ret['port'] = int(portstr)
ret['host'] = remain
ret['path'] = pathrem
return ret
|
python
|
{
"resource": ""
}
|
q19402
|
HashSet.eatfd
|
train
|
def eatfd(self, fd):
'''
Consume all the bytes from a file like object.
Example:
hset = HashSet()
hset.eatfd(fd)
'''
fd.seek(0)
byts = fd.read(10000000)
while byts:
self.update(byts)
byts = fd.read(10000000)
return self.guid()
|
python
|
{
"resource": ""
}
|
q19403
|
HashSet.update
|
train
|
def update(self, byts):
'''
Update all the hashes in the set with the given bytes.
'''
self.size += len(byts)
[h[1].update(byts) for h in self.hashes]
|
python
|
{
"resource": ""
}
|
q19404
|
claim
|
train
|
def claim(typ, **info):
'''
Add an entry to the provenance stack for the duration of the context
'''
stack = s_task.varget('provstack')
if len(stack) > 256: # pragma: no cover
raise s_exc.RecursionLimitHit(mesg='Hit global recursion limit')
stack.push(typ, **info)
try:
yield
finally:
stack.pop()
|
python
|
{
"resource": ""
}
|
q19405
|
dupstack
|
train
|
def dupstack(newtask):
'''
Duplicate the current provenance stack onto another task
'''
stack = s_task.varget('provstack')
s_task.varset('provstack', stack.copy(), newtask)
|
python
|
{
"resource": ""
}
|
q19406
|
ProvStor.getProvStack
|
train
|
def getProvStack(self, iden: bytes):
'''
Returns the provenance stack given the iden to it
'''
retn = self.slab.get(iden, db=self.db)
if retn is None:
return None
return s_msgpack.un(retn)
|
python
|
{
"resource": ""
}
|
q19407
|
ProvStor.provStacks
|
train
|
def provStacks(self, offs, size):
'''
Returns a stream of provenance stacks at the given offset
'''
for _, iden in self.provseq.slice(offs, size):
stack = self.getProvStack(iden)
if stack is None:
continue
yield (iden, stack)
|
python
|
{
"resource": ""
}
|
q19408
|
ProvStor.getProvIden
|
train
|
def getProvIden(self, provstack):
'''
Returns the iden corresponding to a provenance stack and stores if it hasn't seen it before
'''
iden = _providen(provstack)
misc, frames = provstack
# Convert each frame back from (k, v) tuples to a dict
dictframes = [(typ, {k: v for (k, v) in info}) for (typ, info) in frames]
bytz = s_msgpack.en((misc, dictframes))
didwrite = self.slab.put(iden, bytz, overwrite=False, db=self.db)
if didwrite:
self.provseq.save([iden])
return iden
|
python
|
{
"resource": ""
}
|
q19409
|
ProvStor.commit
|
train
|
def commit(self):
'''
Writes the current provenance stack to storage if it wasn't already there and returns it
Returns (Tuple[bool, str, List[]]):
Whether the stack was not cached, the iden of the prov stack, and the provstack
'''
providen, provstack = get()
wasnew = (providen is None)
if wasnew:
providen = self.getProvIden(provstack)
setiden(providen)
return wasnew, s_common.ehex(providen), provstack
|
python
|
{
"resource": ""
}
|
q19410
|
SlabSeqn.save
|
train
|
def save(self, items):
'''
Save a series of items to a sequence.
Args:
items (tuple): The series of items to save into the sequence.
Returns:
The index of the first item
'''
rows = []
indx = self.indx
size = 0
tick = s_common.now()
for item in items:
byts = s_msgpack.en(item)
size += len(byts)
lkey = s_common.int64en(indx)
indx += 1
rows.append((lkey, byts))
self.slab.putmulti(rows, append=True, db=self.db)
took = s_common.now() - tick
origindx = self.indx
self.indx = indx
return {'indx': indx, 'size': size, 'count': len(items), 'time': tick, 'took': took}
return origindx
|
python
|
{
"resource": ""
}
|
q19411
|
SlabSeqn.nextindx
|
train
|
def nextindx(self):
'''
Determine the next insert offset according to storage.
Returns:
int: The next insert offset.
'''
indx = 0
with s_lmdbslab.Scan(self.slab, self.db) as curs:
last_key = curs.last_key()
if last_key is not None:
indx = s_common.int64un(last_key) + 1
return indx
|
python
|
{
"resource": ""
}
|
q19412
|
SlabSeqn.iter
|
train
|
def iter(self, offs):
'''
Iterate over items in a sequence from a given offset.
Args:
offs (int): The offset to begin iterating from.
Yields:
(indx, valu): The index and valu of the item.
'''
startkey = s_common.int64en(offs)
for lkey, lval in self.slab.scanByRange(startkey, db=self.db):
indx = s_common.int64un(lkey)
valu = s_msgpack.un(lval)
yield indx, valu
|
python
|
{
"resource": ""
}
|
q19413
|
SlabSeqn.rows
|
train
|
def rows(self, offs):
'''
Iterate over raw indx, bytes tuples from a given offset.
'''
lkey = s_common.int64en(offs)
for lkey, byts in self.slab.scanByRange(lkey, db=self.db):
indx = s_common.int64un(lkey)
yield indx, byts
|
python
|
{
"resource": ""
}
|
q19414
|
near
|
train
|
def near(point, dist, points):
'''
Determine if the given point is within dist of any of points.
Args:
point ((float,float)): A latitude, longitude float tuple.
dist (int): A distance in mm ( base units )
points (list): A list of latitude, longitude float tuples to compare against.
'''
for cmpt in points:
if haversine(point, cmpt) <= dist:
return True
return False
|
python
|
{
"resource": ""
}
|
q19415
|
SumoLogic.search_metrics
|
train
|
def search_metrics(self, query, fromTime=None, toTime=None, requestedDataPoints=600, maxDataPoints=800):
'''Perform a single Sumo metrics query'''
def millisectimestamp(ts):
'''Convert UNIX timestamp to milliseconds'''
if ts > 10**12:
ts = ts/(10**(len(str(ts))-13))
else:
ts = ts*10**(12-len(str(ts)))
return int(ts)
params = {'query': [{"query":query, "rowId":"A"}],
'startTime': millisectimestamp(fromTime),
'endTime': millisectimestamp(toTime),
'requestedDataPoints': requestedDataPoints,
'maxDataPoints': maxDataPoints}
r = self.post('/metrics/results', params)
return json.loads(r.text)
|
python
|
{
"resource": ""
}
|
q19416
|
CardConnectionDecorator.connect
|
train
|
def connect(self, protocol=None, mode=None, disposition=None):
"""call inner component connect"""
self.component.connect(protocol, mode, disposition)
|
python
|
{
"resource": ""
}
|
q19417
|
translateprotocolmask
|
train
|
def translateprotocolmask(protocol):
"""Translate CardConnection protocol mask into PCSC protocol mask."""
pcscprotocol = 0
if None != protocol:
if CardConnection.T0_protocol & protocol:
pcscprotocol |= SCARD_PROTOCOL_T0
if CardConnection.T1_protocol & protocol:
pcscprotocol |= SCARD_PROTOCOL_T1
if CardConnection.RAW_protocol & protocol:
pcscprotocol |= SCARD_PROTOCOL_RAW
if CardConnection.T15_protocol & protocol:
pcscprotocol |= SCARD_PROTOCOL_T15
return pcscprotocol
|
python
|
{
"resource": ""
}
|
q19418
|
translateprotocolheader
|
train
|
def translateprotocolheader(protocol):
"""Translate protocol into PCSC protocol header."""
pcscprotocol = 0
if None != protocol:
if CardConnection.T0_protocol == protocol:
pcscprotocol = SCARD_PCI_T0
if CardConnection.T1_protocol == protocol:
pcscprotocol = SCARD_PCI_T1
if CardConnection.RAW_protocol == protocol:
pcscprotocol = SCARD_PCI_RAW
return pcscprotocol
|
python
|
{
"resource": ""
}
|
q19419
|
PCSCCardConnection.connect
|
train
|
def connect(self, protocol=None, mode=None, disposition=None):
"""Connect to the card.
If protocol is not specified, connect with the default
connection protocol.
If mode is not specified, connect with SCARD_SHARE_SHARED."""
CardConnection.connect(self, protocol)
pcscprotocol = translateprotocolmask(protocol)
if 0 == pcscprotocol:
pcscprotocol = self.getProtocol()
if mode == None:
mode = SCARD_SHARE_SHARED
# store the way to dispose the card
if disposition == None:
disposition = SCARD_UNPOWER_CARD
self.disposition = disposition
hresult, self.hcard, dwActiveProtocol = SCardConnect(
self.hcontext, str(self.reader), mode, pcscprotocol)
if hresult != 0:
self.hcard = None
if hresult in (SCARD_W_REMOVED_CARD, SCARD_E_NO_SMARTCARD):
raise NoCardException('Unable to connect', hresult=hresult)
else:
raise CardConnectionException(
'Unable to connect with protocol: ' + \
dictProtocol[pcscprotocol] + '. ' + \
SCardGetErrorMessage(hresult))
protocol = 0
if dwActiveProtocol == SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1:
# special case for T0 | T1
# this happen when mode=SCARD_SHARE_DIRECT and no protocol is
# then negociated with the card
protocol = CardConnection.T0_protocol | CardConnection.T1_protocol
else:
for p in dictProtocol:
if p == dwActiveProtocol:
protocol = eval("CardConnection.%s_protocol" % dictProtocol[p])
PCSCCardConnection.setProtocol(self, protocol)
|
python
|
{
"resource": ""
}
|
q19420
|
PCSCCardConnection.disconnect
|
train
|
def disconnect(self):
"""Disconnect from the card."""
# when __del__() is invoked in response to a module being deleted,
# e.g., when execution of the program is done, other globals referenced
# by the __del__() method may already have been deleted.
# this causes CardConnection.disconnect to except with a TypeError
try:
CardConnection.disconnect(self)
except TypeError:
pass
if None != self.hcard:
hresult = SCardDisconnect(self.hcard, self.disposition)
if hresult != 0:
raise CardConnectionException(
'Failed to disconnect: ' + \
SCardGetErrorMessage(hresult))
self.hcard = None
|
python
|
{
"resource": ""
}
|
q19421
|
PCSCCardConnection.getATR
|
train
|
def getATR(self):
"""Return card ATR"""
CardConnection.getATR(self)
if None == self.hcard:
raise CardConnectionException('Card not connected')
hresult, reader, state, protocol, atr = SCardStatus(self.hcard)
if hresult != 0:
raise CardConnectionException(
'Failed to get status: ' + \
SCardGetErrorMessage(hresult))
return atr
|
python
|
{
"resource": ""
}
|
q19422
|
PCSCCardConnection.doTransmit
|
train
|
def doTransmit(self, bytes, protocol=None):
"""Transmit an apdu to the card and return response apdu.
@param bytes: command apdu to transmit (list of bytes)
@param protocol: the transmission protocol, from
CardConnection.T0_protocol, CardConnection.T1_protocol, or
CardConnection.RAW_protocol
@return: a tuple (response, sw1, sw2) where
sw1 is status word 1, e.g. 0x90
sw2 is status word 2, e.g. 0x1A
response are the response bytes excluding status words
"""
if None == protocol:
protocol = self.getProtocol()
CardConnection.doTransmit(self, bytes, protocol)
pcscprotocolheader = translateprotocolheader(protocol)
if 0 == pcscprotocolheader:
raise CardConnectionException(
'Invalid protocol in transmit: must be ' + \
'CardConnection.T0_protocol, ' + \
'CardConnection.T1_protocol, or ' + \
'CardConnection.RAW_protocol')
if None == self.hcard:
raise CardConnectionException('Card not connected')
hresult, response = SCardTransmit(
self.hcard, pcscprotocolheader, bytes)
if hresult != 0:
raise CardConnectionException(
'Failed to transmit with protocol ' + \
dictProtocolHeader[pcscprotocolheader] + '. ' + \
SCardGetErrorMessage(hresult))
sw1 = (response[-2] + 256) % 256
sw2 = (response[-1] + 256) % 256
data = [(x + 256) % 256 for x in response[:-2]]
return list(data), sw1, sw2
|
python
|
{
"resource": ""
}
|
q19423
|
PCSCCardConnection.doControl
|
train
|
def doControl(self, controlCode, bytes=[]):
"""Transmit a control command to the reader and return response.
controlCode: control command
bytes: command data to transmit (list of bytes)
return: response are the response bytes (if any)
"""
CardConnection.doControl(self, controlCode, bytes)
hresult, response = SCardControl(self.hcard, controlCode, bytes)
if hresult != 0:
raise SmartcardException(
'Failed to control ' + SCardGetErrorMessage(hresult))
data = [(x + 256) % 256 for x in response]
return list(data)
|
python
|
{
"resource": ""
}
|
q19424
|
PCSCCardConnection.doGetAttrib
|
train
|
def doGetAttrib(self, attribId):
"""get an attribute
attribId: Identifier for the attribute to get
return: response are the attribute byte array
"""
CardConnection.doGetAttrib(self, attribId)
hresult, response = SCardGetAttrib(self.hcard, attribId)
if hresult != 0:
raise SmartcardException(
'Failed to getAttrib ' + SCardGetErrorMessage(hresult))
return response
|
python
|
{
"resource": ""
}
|
q19425
|
pcscdiag.OnExpandAll
|
train
|
def OnExpandAll(self):
""" expand all nodes """
root = self.tree.GetRootItem()
fn = self.tree.Expand
self.traverse(root, fn)
self.tree.Expand(root)
|
python
|
{
"resource": ""
}
|
q19426
|
pcscdiag.traverse
|
train
|
def traverse(self, traverseroot, function, cookie=0):
""" recursivly walk tree control """
if self.tree.ItemHasChildren(traverseroot):
firstchild, cookie = self.tree.GetFirstChild(traverseroot)
function(firstchild)
self.traverse(firstchild, function, cookie)
child = self.tree.GetNextSibling(traverseroot)
if child:
function(child)
self.traverse(child, function, cookie)
|
python
|
{
"resource": ""
}
|
q19427
|
module_path
|
train
|
def module_path():
""" This will get us the program's directory,
even if we are frozen using py2exe. From WhereAmI page on py2exe wiki."""
if we_are_frozen():
return os.path.dirname(
unicode(sys.executable, sys.getfilesystemencoding()))
return os.path.dirname(unicode(__file__, sys.getfilesystemencoding()))
|
python
|
{
"resource": ""
}
|
q19428
|
CardConnection.getAttrib
|
train
|
def getAttrib(self, attribId):
"""return the requested attribute
@param attribId: attribute id like SCARD_ATTR_VENDOR_NAME
"""
Observable.setChanged(self)
Observable.notifyObservers(self,
CardConnectionEvent(
'attrib',
[attribId]))
data = self.doGetAttrib(attribId)
if self.errorcheckingchain is not None:
self.errorcheckingchain[0](data)
return data
|
python
|
{
"resource": ""
}
|
q19429
|
PyroReader.createConnection
|
train
|
def createConnection(self):
"""Return a card connection thru a remote reader."""
uri = self.reader.createConnection()
return Pyro.core.getAttrProxyForURI(uri)
|
python
|
{
"resource": ""
}
|
q19430
|
SampleAPDUManagerPanel.OnActivateCard
|
train
|
def OnActivateCard(self, card):
"""Called when a card is activated by double-clicking
on the card or reader tree control or toolbar.
In this sample, we just connect to the card on the first activation."""
SimpleSCardAppEventObserver.OnActivateCard(self, card)
self.feedbacktext.SetLabel('Activated card: ' + repr(card))
self.transmitbutton.Enable()
|
python
|
{
"resource": ""
}
|
q19431
|
SimpleSCardApp.OnInit
|
train
|
def OnInit(self):
"""Create and display application frame."""
self.frame = SimpleSCardAppFrame(
self.appname,
self.apppanel,
self.appstyle,
self.appicon,
self.pos,
self.size)
self.frame.Show(True)
self.SetTopWindow(self.frame)
return True
|
python
|
{
"resource": ""
}
|
q19432
|
PyroNameServer.getShutdownArgs
|
train
|
def getShutdownArgs(self):
"""return command line arguments for shutting down the
server; this command line is built from the name server
startup arguments."""
shutdownArgs = []
if self.host:
shutdownArgs += ['-h', self.host]
if self.bcport:
shutdownArgs += ['-p', self.bcport]
if self.bcaddr:
shutdownArgs += ['-c', self.bcaddr]
if self.identification:
shutdownArgs += ['-i', self.identification]
return shutdownArgs
|
python
|
{
"resource": ""
}
|
q19433
|
PyroNameServer.stop
|
train
|
def stop(self):
"""Shutdown pyro naming server."""
args = self.getShutdownArgs() + ['shutdown']
Pyro.nsc.main(args)
self.join()
|
python
|
{
"resource": ""
}
|
q19434
|
Card.createConnection
|
train
|
def createConnection(self):
"""Return a CardConnection to the Card object."""
readerobj = None
if isinstance(self.reader, Reader):
readerobj = self.reader
elif type(self.reader) == str:
for reader in readers():
if self.reader == str(reader):
readerobj = reader
if readerobj:
return readerobj.createConnection()
else:
# raise CardConnectionException(
# 'not a valid reader: ' + str(self.reader))
return None
|
python
|
{
"resource": ""
}
|
q19435
|
pcscinnerreadergroups.getreadergroups
|
train
|
def getreadergroups(self):
""" Returns the list of smartcard reader groups."""
innerreadergroups.getreadergroups(self)
hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER)
if hresult != 0:
raise EstablishContextException(hresult)
hresult, readers = SCardListReaderGroups(hcontext)
if hresult != 0:
raise ListReadersException(hresult)
hresult = SCardReleaseContext(hcontext)
if hresult != 0:
raise ReleaseContextException(hresult)
return readers
|
python
|
{
"resource": ""
}
|
q19436
|
pcscinnerreadergroups.addreadergroup
|
train
|
def addreadergroup(self, newgroup):
"""Add a reader group"""
hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER)
if 0 != hresult:
raise error(
'Failed to establish context: ' + \
SCardGetErrorMessage(hresult))
try:
hresult = SCardIntroduceReaderGroup(hcontext, newgroup)
if 0 != hresult:
raise error(
'Unable to introduce reader group: ' + \
SCardGetErrorMessage(hresult))
else:
innerreadergroups.addreadergroup(self, newgroup)
finally:
hresult = SCardReleaseContext(hcontext)
if 0 != hresult:
raise error(
'Failed to release context: ' + \
SCardGetErrorMessage(hresult))
|
python
|
{
"resource": ""
}
|
q19437
|
parseFeatureRequest
|
train
|
def parseFeatureRequest(response):
""" Get the list of Part10 features supported by the reader.
@param response: result of CM_IOCTL_GET_FEATURE_REQUEST commmand
@rtype: list
@return: a list of list [[tag1, value1], [tag2, value2]]
"""
features = []
while (len(response) > 0):
tag = response[0]
control = ((((((response[2] << 8) +
response[3]) << 8) +
response[4]) << 8) +
response[5])
try:
features.append([Features[tag], control])
except KeyError:
pass
del response[:6]
return features
|
python
|
{
"resource": ""
}
|
q19438
|
hasFeature
|
train
|
def hasFeature(featureList, feature):
""" return the controlCode for a feature or None
@param feature: feature to look for
@param featureList: feature list as returned by L{getFeatureRequest()}
@return: feature value or None
"""
for f in featureList:
if f[0] == feature or Features[f[0]] == feature:
return f[1]
|
python
|
{
"resource": ""
}
|
q19439
|
getPinProperties
|
train
|
def getPinProperties(cardConnection, featureList=None, controlCode=None):
""" return the PIN_PROPERTIES structure
@param cardConnection: L{CardConnection} object
@param featureList: feature list as returned by L{getFeatureRequest()}
@param controlCode: control code for L{FEATURE_IFD_PIN_PROPERTIES}
@rtype: dict
@return: a dict """
if controlCode is None:
if featureList is None:
featureList = getFeatureRequest(cardConnection)
controlCode = hasFeature(featureList, FEATURE_IFD_PIN_PROPERTIES)
if controlCode is None:
return {'raw': []}
response = cardConnection.control(controlCode, [])
d = {
'raw': response,
'LcdLayoutX': response[0],
'LcdLayoutY': response[1],
'EntryValidationCondition': response[2],
'TimeOut2': response[3]}
return d
|
python
|
{
"resource": ""
}
|
q19440
|
RemoteReader.createConnection
|
train
|
def createConnection(self):
"""Return a card connection thru the reader."""
connection = RemoteCardConnection(self.readerobj.createConnection())
daemon = PyroDaemon.PyroDaemon()
uri = daemon.connect(connection)
return uri
|
python
|
{
"resource": ""
}
|
q19441
|
RemoteReaderServer.update
|
train
|
def update(self, observable, actions):
"""Called when a local reader is added or removed.
Create remote pyro reader objects for added readers.
Delete remote pyro reader objects for removed readers."""
(addedreaders, removedreaders) = actions
for reader in addedreaders:
remotereader = RemoteReader(reader)
self.remotereaders[reader.name] = remotereader
name = "".join(reader.name.split(' '))
name = ":pyscard.smartcard.readers." + "".join(name.split('.'))
uri = self.daemon.connect(remotereader, name)
for reader in removedreaders:
remotereader = self.remotereaders[reader.name]
self.daemon.disconnect(remotereader)
del self.remotereaders[reader.name]
self.pn.listall()
|
python
|
{
"resource": ""
}
|
q19442
|
ReaderMonitor.addObserver
|
train
|
def addObserver(self, observer):
"""Add an observer."""
Observable.addObserver(self, observer)
# If self.startOnDemand is True, the reader monitoring
# thread only runs when there are observers.
if self.startOnDemand:
if 0 < self.countObservers():
if not self.rmthread:
self.rmthread = ReaderMonitoringThread(
self,
self.readerProc, self.period)
# start reader monitoring thread in another thread to
# avoid a deadlock; addObserver and notifyObservers called
# in the ReaderMonitoringThread run() method are
# synchronized
try:
# Python 3.x
import _thread
_thread.start_new_thread(self.rmthread.start, ())
except:
# Python 2.x
import thread
thread.start_new_thread(self.rmthread.start, ())
else:
observer.update(self, (self.rmthread.readers, []))
|
python
|
{
"resource": ""
}
|
q19443
|
ReaderMonitor.deleteObserver
|
train
|
def deleteObserver(self, observer):
"""Remove an observer."""
Observable.deleteObserver(self, observer)
# If self.startOnDemand is True, the reader monitoring
# thread is stopped when there are no more observers.
if self.startOnDemand:
if 0 == self.countObservers():
self.rmthread.stop()
del self.rmthread
self.rmthread = None
|
python
|
{
"resource": ""
}
|
q19444
|
ulist.__remove_duplicates
|
train
|
def __remove_duplicates(self, _other):
"""Remove from other items already in list."""
if not isinstance(_other, type(self)) \
and not isinstance(_other, type(list)) \
and not isinstance(_other, type([])):
other = [_other]
else:
other = list(_other)
# remove items already in self
newother = []
for i in range(0, len(other)):
item = other.pop(0)
if not list.__contains__(self, item):
newother.append(item)
# remove duplicate items in other
other = []
if newother != []:
other.append(newother[0])
for i in range(1, len(newother)):
item = newother.pop()
if not other.__contains__(item):
other.append(item)
return other
|
python
|
{
"resource": ""
}
|
q19445
|
APDUTracerPanel.update
|
train
|
def update(self, cardconnection, ccevent):
'''CardConnectionObserver callback.'''
apduline = ""
if 'connect' == ccevent.type:
apduline += 'connecting to ' + cardconnection.getReader()
elif 'disconnect' == ccevent.type:
apduline += 'disconnecting from ' + cardconnection.getReader()
elif 'command' == ccevent.type:
apduline += '> ' + toHexString(ccevent.args[0])
elif 'response' == ccevent.type:
if [] == ccevent.args[0]:
apduline += "< %-2X %-2X" % tuple(ccevent.args[-2:])
else:
apduline += "< " + toHexString(ccevent.args[0]) + \
"%-2X %-2X" % tuple(ccevent.args[-2:])
self.apdutextctrl.AppendText(apduline + "\n")
|
python
|
{
"resource": ""
}
|
q19446
|
synchronize
|
train
|
def synchronize(klass, names=None):
"""Synchronize methods in the given class.
Only synchronize the methods whose names are
given, or all methods if names=None."""
# basestring does not exist on Python 3
try:
basestring
except NameError:
basestring = (str, bytes)
if isinstance(names, basestring):
names = names.split()
for (name, val) in list(klass.__dict__.items()):
if callable(val) and name != '__init__' and \
(names is None or name in names):
# print("synchronizing", name)
setattr(klass, name, synchronized(val))
|
python
|
{
"resource": ""
}
|
q19447
|
ExclusiveTransmitCardConnection.lock
|
train
|
def lock(self):
'''Lock card with SCardBeginTransaction.'''
component = self.component
while True:
if isinstance(
component,
smartcard.pcsc.PCSCCardConnection.PCSCCardConnection):
hresult = SCardBeginTransaction(component.hcard)
if 0 != hresult:
raise CardConnectionException(
'Failed to lock with SCardBeginTransaction: ' +
SCardGetErrorMessage(hresult))
else:
# print('locked')
pass
break
if hasattr(component, 'component'):
component = component.component
else:
break
|
python
|
{
"resource": ""
}
|
q19448
|
ExclusiveTransmitCardConnection.unlock
|
train
|
def unlock(self):
'''Unlock card with SCardEndTransaction.'''
component = self.component
while True:
if isinstance(
component,
smartcard.pcsc.PCSCCardConnection.PCSCCardConnection):
hresult = SCardEndTransaction(component.hcard,
SCARD_LEAVE_CARD)
if 0 != hresult:
raise CardConnectionException(
'Failed to unlock with SCardEndTransaction: ' +
SCardGetErrorMessage(hresult))
else:
# print('unlocked')
pass
break
if hasattr(component, 'component'):
component = component.component
else:
break
|
python
|
{
"resource": ""
}
|
q19449
|
ExclusiveTransmitCardConnection.transmit
|
train
|
def transmit(self, bytes, protocol=None):
'''Gain exclusive access to card during APDU transmission for if this
decorator decorates a PCSCCardConnection.'''
data, sw1, sw2 = CardConnectionDecorator.transmit(
self, bytes, protocol)
return data, sw1, sw2
|
python
|
{
"resource": ""
}
|
q19450
|
ReaderFactory.createReader
|
train
|
def createReader(clazz, readername):
"""Static method to create a reader from a reader clazz.
@param clazz: the reader class name
@param readername: the reader name
"""
if not clazz in ReaderFactory.factories:
ReaderFactory.factories[clazz] = get_class(clazz).Factory()
return ReaderFactory.factories[clazz].create(readername)
|
python
|
{
"resource": ""
}
|
q19451
|
ReaderComboBox.update
|
train
|
def update(self, observable, handlers):
"""Toolbar ReaderObserver callback that is notified when
readers are added or removed."""
addedreaders, removedreaders = handlers
for reader in addedreaders:
item = self.Append(str(reader))
self.SetClientData(item, reader)
for reader in removedreaders:
item = self.FindString(str(reader))
if wx.NOT_FOUND != item:
self.Delete(item)
selection = self.GetSelection()
|
python
|
{
"resource": ""
}
|
q19452
|
Session.sendCommandAPDU
|
train
|
def sendCommandAPDU(self, command):
"""Send an APDU command to the connected smartcard.
@param command: list of APDU bytes, e.g. [0xA0, 0xA4, 0x00, 0x00, 0x02]
@return: a tuple (response, sw1, sw2) where
response is the APDU response
sw1, sw2 are the two status words
"""
response, sw1, sw2 = self.cs.connection.transmit(command)
if len(response) > 2:
response.append(sw1)
response.append(sw2)
return response, sw1, sw2
|
python
|
{
"resource": ""
}
|
q19453
|
ErrorCheckingChain.next
|
train
|
def next(self):
"""Returns next error checking strategy."""
# Where this link is in the chain:
location = self.chain.index(self)
if not self.end():
return self.chain[location + 1]
|
python
|
{
"resource": ""
}
|
q19454
|
ErrorCheckingChain.addFilterException
|
train
|
def addFilterException(self, exClass):
"""Add an exception filter to the error checking chain.
@param exClass: the exception to exclude, e.g.
L{smartcard.sw.SWExceptions.WarningProcessingException} A filtered
exception will not be raised when the sw1,sw2 conditions that
would raise the excption are met.
"""
self.excludes.append(exClass)
if self.end():
return
self.next().addFilterException(exClass)
|
python
|
{
"resource": ""
}
|
q19455
|
PCSCReader.addtoreadergroup
|
train
|
def addtoreadergroup(self, groupname):
"""Add reader to a reader group."""
hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER)
if 0 != hresult:
raise EstablishContextException(hresult)
try:
hresult = SCardIntroduceReader(hcontext, self.name, self.name)
if 0 != hresult and SCARD_E_DUPLICATE_READER != hresult:
raise IntroduceReaderException(hresult, self.name)
hresult = SCardAddReaderToGroup(hcontext, self.name, groupname)
if 0 != hresult:
raise AddReaderToGroupException(hresult, self.name, groupname)
finally:
hresult = SCardReleaseContext(hcontext)
if 0 != hresult:
raise ReleaseContextException(hresult)
|
python
|
{
"resource": ""
}
|
q19456
|
PCSCReader.removefromreadergroup
|
train
|
def removefromreadergroup(self, groupname):
"""Remove a reader from a reader group"""
hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER)
if 0 != hresult:
raise EstablishContextException(hresult)
try:
hresult = SCardRemoveReaderFromGroup(hcontext, self.name,
groupname)
if 0 != hresult:
raise RemoveReaderFromGroupException(hresult, self.name,
groupname)
finally:
hresult = SCardReleaseContext(hcontext)
if 0 != hresult:
raise ReleaseContextException(hresult)
|
python
|
{
"resource": ""
}
|
q19457
|
TreeAndUserPanelPanel.ActivateCard
|
train
|
def ActivateCard(self, card):
"""Activate a card."""
if not hasattr(card, 'connection'):
card.connection = card.createConnection()
if None != self.parent.apdutracerpanel:
card.connection.addObserver(self.parent.apdutracerpanel)
card.connection.connect()
self.dialogpanel.OnActivateCard(card)
|
python
|
{
"resource": ""
}
|
q19458
|
TreeAndUserPanelPanel.DeactivateCard
|
train
|
def DeactivateCard(self, card):
"""Deactivate a card."""
if hasattr(card, 'connection'):
card.connection.disconnect()
if None != self.parent.apdutracerpanel:
card.connection.deleteObserver(self.parent.apdutracerpanel)
delattr(card, 'connection')
self.dialogpanel.OnDeactivateCard(card)
|
python
|
{
"resource": ""
}
|
q19459
|
TreeAndUserPanelPanel.OnActivateReader
|
train
|
def OnActivateReader(self, event):
"""Called when the user activates a reader in the tree."""
item = event.GetItem()
if item:
itemdata = self.readertreepanel.readertreectrl.GetItemPyData(item)
if isinstance(itemdata, smartcard.Card.Card):
self.ActivateCard(itemdata)
elif isinstance(itemdata, smartcard.reader.Reader.Reader):
self.dialogpanel.OnActivateReader(itemdata)
event.Skip()
|
python
|
{
"resource": ""
}
|
q19460
|
TreeAndUserPanelPanel.OnCardRightClick
|
train
|
def OnCardRightClick(self, event):
"""Called when user right-clicks a node in the card tree control."""
item = event.GetItem()
if item:
itemdata = self.readertreepanel.cardtreectrl.GetItemPyData(item)
if isinstance(itemdata, smartcard.Card.Card):
self.selectedcard = itemdata
if not hasattr(self, "connectID"):
self.connectID = wx.NewId()
self.disconnectID = wx.NewId()
self.Bind(wx.EVT_MENU, self.OnConnect, id=self.connectID)
self.Bind(
wx.EVT_MENU, self.OnDisconnect, id=self.disconnectID)
menu = wx.Menu()
if not hasattr(self.selectedcard, 'connection'):
menu.Append(self.connectID, "Connect")
else:
menu.Append(self.disconnectID, "Disconnect")
self.PopupMenu(menu)
menu.Destroy()
|
python
|
{
"resource": ""
}
|
q19461
|
TreeAndUserPanelPanel.OnSelectCard
|
train
|
def OnSelectCard(self, event):
"""Called when the user selects a card in the tree."""
item = event.GetItem()
if item:
itemdata = self.readertreepanel.cardtreectrl.GetItemPyData(item)
if isinstance(itemdata, smartcard.Card.Card):
self.dialogpanel.OnSelectCard(itemdata)
else:
self.dialogpanel.OnDeselectCard(itemdata)
|
python
|
{
"resource": ""
}
|
q19462
|
TreeAndUserPanelPanel.OnSelectReader
|
train
|
def OnSelectReader(self, event):
"""Called when the user selects a reader in the tree."""
item = event.GetItem()
if item:
itemdata = self.readertreepanel.readertreectrl.GetItemPyData(item)
if isinstance(itemdata, smartcard.Card.Card):
self.dialogpanel.OnSelectCard(itemdata)
elif isinstance(itemdata, smartcard.reader.Reader.Reader):
self.dialogpanel.OnSelectReader(itemdata)
else:
self.dialogpanel.OnDeselectCard(itemdata)
|
python
|
{
"resource": ""
}
|
q19463
|
SimpleSCardAppFrame.OnReaderComboBox
|
train
|
def OnReaderComboBox(self, event):
"""Called when the user activates a reader in the toolbar combo box."""
cb = event.GetEventObject()
reader = cb.GetClientData(cb.GetSelection())
if isinstance(reader, smartcard.reader.Reader.Reader):
self.treeuserpanel.dialogpanel.OnActivateReader(reader)
|
python
|
{
"resource": ""
}
|
q19464
|
get_func
|
train
|
def get_func(fullFuncName):
"""Retrieve a function object from a full dotted-package name."""
# Parse out the path, module, and function
lastDot = fullFuncName.rfind(u".")
funcName = fullFuncName[lastDot + 1:]
modPath = fullFuncName[:lastDot]
aMod = get_mod(modPath)
aFunc = getattr(aMod, funcName)
# Assert that the function is a *callable* attribute.
assert callable(aFunc), u"%s is not callable." % fullFuncName
# Return a reference to the function itself,
# not the results of the function.
return aFunc
|
python
|
{
"resource": ""
}
|
q19465
|
PCSCCardRequest.getReaderNames
|
train
|
def getReaderNames(self):
"""Returns the list or PCSC readers on which to wait for cards."""
# get inserted readers
hresult, pcscreaders = SCardListReaders(self.hcontext, [])
if 0 != hresult and SCARD_E_NO_READERS_AVAILABLE != hresult:
raise ListReadersException(hresult)
readers = []
# if no readers asked, use all inserted readers
if None == self.readersAsked:
readers = pcscreaders
# otherwise use only the asked readers that are inserted
else:
for reader in self.readersAsked:
if not isinstance(reader, type("")):
reader = str(reader)
if reader in pcscreaders:
readers = readers + [reader]
return readers
|
python
|
{
"resource": ""
}
|
q19466
|
PCSCCardRequest.waitforcardevent
|
train
|
def waitforcardevent(self):
"""Wait for card insertion or removal."""
AbstractCardRequest.waitforcardevent(self)
presentcards = []
evt = threading.Event()
# for non infinite timeout, a timer will signal the end of the time-out
if INFINITE == self.timeout:
timertimeout = 1
else:
timertimeout = self.timeout
timer = threading.Timer(
timertimeout, signalEvent, [evt, INFINITE == self.timeout])
# get status change until time-out, e.g. evt is set
readerstates = {}
timerstarted = False
while not evt.isSet():
if not timerstarted:
timerstarted = True
timer.start()
time.sleep(self.pollinginterval)
# reinitialize at each iteration just in case a new reader appeared
readernames = self.getReaderNames()
for reader in readernames:
# create a dictionary entry for new readers
if not reader in readerstates:
readerstates[reader] = (reader, SCARD_STATE_UNAWARE)
# remove dictionary entry for readers that disappeared
for oldreader in list(readerstates.keys()):
if oldreader not in readernames:
del readerstates[oldreader]
# get status change
if {} != readerstates:
hresult, newstates = SCardGetStatusChange(
self.hcontext, 0, list(readerstates.values()))
else:
hresult = 0
newstates = []
# time-out
if SCARD_E_TIMEOUT == hresult:
if evt.isSet():
raise CardRequestTimeoutException()
# the reader was unplugged during the loop
elif SCARD_E_UNKNOWN_READER == hresult:
pass
# some error happened
elif 0 != hresult:
timer.cancel()
raise CardRequestException(
'Failed to get status change ' + \
SCardGetErrorMessage(hresult))
# something changed!
else:
timer.cancel()
for state in newstates:
readername, eventstate, atr = state
r, oldstate = readerstates[readername]
# the status can change on a card already inserted, e.g.
# unpowered, in use, ... Clear the state changed bit if
# the card was already inserted and is still inserted
if oldstate & SCARD_STATE_PRESENT and \
eventstate & \
(SCARD_STATE_CHANGED | SCARD_STATE_PRESENT):
eventstate = eventstate & \
(0xFFFFFFFF ^ SCARD_STATE_CHANGED)
if eventstate & SCARD_STATE_PRESENT and \
eventstate & SCARD_STATE_CHANGED:
presentcards.append(Card.Card(readername, atr))
return presentcards
if evt.isSet():
raise CardRequestTimeoutException()
|
python
|
{
"resource": ""
}
|
q19467
|
strToGUID
|
train
|
def strToGUID(s):
"""Converts a GUID string into a list of bytes.
>>> strToGUID('{AD4F1667-EA75-4124-84D4-641B3B197C65}')
[103, 22, 79, 173, 117, 234, 36, 65, 132, 212, 100, 27, 59, 25, 124, 101]
"""
dat = uuid.UUID(hex=s)
if isinstance(dat.bytes_le, str):
# Python 2
dat = [ord(e) for e in dat.bytes_le]
else:
# Python 3
dat = list(dat.bytes_le)
return dat
|
python
|
{
"resource": ""
}
|
q19468
|
GUIDToStr
|
train
|
def GUIDToStr(g):
"""Converts a GUID sequence of bytes into a string.
>>> GUIDToStr([103,22,79,173, 117,234, 36,65,
... 132, 212, 100, 27, 59, 25, 124, 101])
'{AD4F1667-EA75-4124-84D4-641B3B197C65}'
"""
try:
dat = uuid.UUID(bytes_le=bytes(g))
except:
dat = uuid.UUID(bytes_le=''.join(map(chr, g)))
return '{' + str(dat).upper() + '}'
|
python
|
{
"resource": ""
}
|
q19469
|
ATRCardType.matches
|
train
|
def matches(self, atr, reader=None):
"""Returns true if the atr matches the masked CardType atr.
@param atr: the atr to chek for matching
@param reader: the reader (optional); default is None
When atr is compared to the CardType ATR, matches returns true if
and only if CardType.atr & CardType.mask = atr & CardType.mask,
where & is the bitwise logical AND."""
if len(atr) != len(self.atr):
return not True
if self.mask is not None:
maskedatr = list(map(lambda x, y: x & y, list(atr), self.mask))
else:
maskedatr = atr
return self.maskedatr == maskedatr
|
python
|
{
"resource": ""
}
|
q19470
|
SamplePanel.OnActivateReader
|
train
|
def OnActivateReader(self, reader):
"""Called when a reader is activated by double-clicking on the
reader tree control or toolbar."""
SimpleSCardAppEventObserver.OnActivateReader(self, reader)
self.feedbacktext.SetLabel('Activated reader: ' + repr(reader))
|
python
|
{
"resource": ""
}
|
q19471
|
SamplePanel.OnDeactivateCard
|
train
|
def OnDeactivateCard(self, card):
"""Called when a card is deactivated in the reader tree control
or toolbar."""
SimpleSCardAppEventObserver.OnActivateCard(self, card)
self.feedbacktext.SetLabel('Deactivated card: ' + repr(card))
|
python
|
{
"resource": ""
}
|
q19472
|
ATR.getSupportedProtocols
|
train
|
def getSupportedProtocols(self):
"""Returns a dictionnary of supported protocols."""
protocols = {}
for td in self.TD:
if td is not None:
strprotocol = "T=%d" % (td & 0x0F)
protocols[strprotocol] = True
if not self.hasTD[0]:
protocols['T=0'] = True
return protocols
|
python
|
{
"resource": ""
}
|
q19473
|
ATR.dump
|
train
|
def dump(self):
"""Dump the details of an ATR."""
for i in range(0, len(self.TA)):
if self.TA[i] is not None:
print("TA%d: %x" % (i + 1, self.TA[i]))
if self.TB[i] is not None:
print("TB%d: %x" % (i + 1, self.TB[i]))
if self.TC[i] is not None:
print("TC%d: %x" % (i + 1, self.TC[i]))
if self.TD[i] is not None:
print("TD%d: %x" % (i + 1, self.TD[i]))
print('supported protocols ' + ','.join(self.getSupportedProtocols()))
print('T=0 supported: ' + str(self.isT0Supported()))
print('T=1 supported: ' + str(self.isT1Supported()))
if self.getChecksum():
print('checksum: %d' % self.getChecksum())
print('\tclock rate conversion factor: ' +
str(self.getClockRateConversion()))
print('\tbit rate adjustment factor: ' + str(self.getBitRateFactor()))
print('\tmaximum programming current: ' +
str(self.getProgrammingCurrent()))
print('\tprogramming voltage: ' + str(self.getProgrammingVoltage()))
print('\tguard time: ' + str(self.getGuardTime()))
print('nb of interface bytes: %d' % self.getInterfaceBytesCount())
print('nb of historical bytes: %d' % self.getHistoricalBytesCount())
|
python
|
{
"resource": ""
}
|
q19474
|
CardTreeCtrl.OnAddCards
|
train
|
def OnAddCards(self, addedcards):
"""Called when a card is inserted.
Adds a smart card to the smartcards tree."""
parentnode = self.root
for cardtoadd in addedcards:
childCard = self.AppendItem(parentnode, toHexString(cardtoadd.atr))
self.SetItemText(childCard, toHexString(cardtoadd.atr))
self.SetPyData(childCard, cardtoadd)
self.SetItemImage(
childCard, self.cardimageindex, wx.TreeItemIcon_Normal)
self.SetItemImage(
childCard, self.cardimageindex, wx.TreeItemIcon_Expanded)
self.Expand(childCard)
self.Expand(self.root)
self.EnsureVisible(self.root)
self.Repaint()
|
python
|
{
"resource": ""
}
|
q19475
|
CardTreeCtrl.OnRemoveCards
|
train
|
def OnRemoveCards(self, removedcards):
"""Called when a card is removed.
Removes a card from the tree."""
parentnode = self.root
for cardtoremove in removedcards:
(childCard, cookie) = self.GetFirstChild(parentnode)
while childCard.IsOk():
if self.GetItemText(childCard) == \
toHexString(cardtoremove.atr):
self.Delete(childCard)
(childCard, cookie) = self.GetNextChild(parentnode, cookie)
self.Expand(self.root)
self.EnsureVisible(self.root)
self.Repaint()
|
python
|
{
"resource": ""
}
|
q19476
|
ReaderTreeCtrl.AddATR
|
train
|
def AddATR(self, readernode, atr):
"""Add an ATR to a reader node."""
capchild = self.AppendItem(readernode, atr)
self.SetPyData(capchild, None)
self.SetItemImage(
capchild, self.cardimageindex, wx.TreeItemIcon_Normal)
self.SetItemImage(
capchild, self.cardimageindex, wx.TreeItemIcon_Expanded)
self.Expand(capchild)
return capchild
|
python
|
{
"resource": ""
}
|
q19477
|
ReaderTreeCtrl.OnAddCards
|
train
|
def OnAddCards(self, addedcards):
"""Called when a card is inserted.
Adds the smart card child to the reader node."""
self.mutex.acquire()
try:
parentnode = self.root
for cardtoadd in addedcards:
(childReader, cookie) = self.GetFirstChild(parentnode)
found = False
while childReader.IsOk() and not found:
if self.GetItemText(childReader) == str(cardtoadd.reader):
(childCard, cookie2) = self.GetFirstChild(childReader)
self.SetItemText(childCard, toHexString(cardtoadd.atr))
self.SetPyData(childCard, cardtoadd)
found = True
else:
(childReader, cookie) = self.GetNextChild(
parentnode, cookie)
# reader was not found, add reader node
# this happens when card monitoring thread signals
# added cards before reader monitoring thread signals
# added readers
if not found:
childReader = self.AppendItem(
parentnode, str(cardtoadd.reader))
self.SetPyData(childReader, cardtoadd.reader)
self.SetItemImage(
childReader,
self.readerimageindex,
wx.TreeItemIcon_Normal)
self.SetItemImage(
childReader,
self.readerimageindex,
wx.TreeItemIcon_Expanded)
childCard = self.AddATR(
childReader, toHexString(cardtoadd.atr))
self.SetPyData(childCard, cardtoadd)
self.Expand(childReader)
self.Expand(self.root)
finally:
self.mutex.release()
self.EnsureVisible(self.root)
self.Repaint()
|
python
|
{
"resource": ""
}
|
q19478
|
ReaderTreeCtrl.OnAddReaders
|
train
|
def OnAddReaders(self, addedreaders):
"""Called when a reader is inserted.
Adds the smart card reader to the smartcard readers tree."""
self.mutex.acquire()
try:
parentnode = self.root
for readertoadd in addedreaders:
# is the reader already here?
found = False
(childReader, cookie) = self.GetFirstChild(parentnode)
while childReader.IsOk() and not found:
if self.GetItemText(childReader) == str(readertoadd):
found = True
else:
(childReader, cookie) = self.GetNextChild(
parentnode, cookie)
if not found:
childReader = self.AppendItem(parentnode, str(readertoadd))
self.SetPyData(childReader, readertoadd)
self.SetItemImage(
childReader,
self.readerimageindex,
wx.TreeItemIcon_Normal)
self.SetItemImage(
childReader,
self.readerimageindex,
wx.TreeItemIcon_Expanded)
self.AddATR(
childReader,
self.GetATR(readertoadd))
self.Expand(childReader)
self.Expand(self.root)
finally:
self.mutex.release()
self.EnsureVisible(self.root)
self.Repaint()
|
python
|
{
"resource": ""
}
|
q19479
|
ReaderTreeCtrl.OnRemoveCards
|
train
|
def OnRemoveCards(self, removedcards):
"""Called when a card is removed.
Removes the card from the tree."""
self.mutex.acquire()
try:
parentnode = self.root
for cardtoremove in removedcards:
(childReader, cookie) = self.GetFirstChild(parentnode)
found = False
while childReader.IsOk() and not found:
if self.GetItemText(childReader) == \
str(cardtoremove.reader):
(childCard, cookie2) = self.GetFirstChild(childReader)
self.SetItemText(childCard, 'no card inserted')
found = True
else:
(childReader, cookie) = \
self.GetNextChild(parentnode, cookie)
self.Expand(self.root)
finally:
self.mutex.release()
self.EnsureVisible(self.root)
self.Repaint()
|
python
|
{
"resource": ""
}
|
q19480
|
ReaderTreeCtrl.OnRemoveReaders
|
train
|
def OnRemoveReaders(self, removedreaders):
"""Called when a reader is removed.
Removes the reader from the smartcard readers tree."""
self.mutex.acquire()
try:
parentnode = self.root
for readertoremove in removedreaders:
(childReader, cookie) = self.GetFirstChild(parentnode)
while childReader.IsOk():
if self.GetItemText(childReader) == str(readertoremove):
self.Delete(childReader)
else:
(childReader, cookie) = \
self.GetNextChild(parentnode, cookie)
self.Expand(self.root)
finally:
self.mutex.release()
self.EnsureVisible(self.root)
self.Repaint()
|
python
|
{
"resource": ""
}
|
q19481
|
CardAndReaderTreePanel.OnDestroy
|
train
|
def OnDestroy(self, event):
"""Called on panel destruction."""
# deregister observers
if hasattr(self, 'cardmonitor'):
self.cardmonitor.deleteObserver(self.cardtreecardobserver)
if hasattr(self, 'readermonitor'):
self.readermonitor.deleteObserver(self.readertreereaderobserver)
self.cardmonitor.deleteObserver(self.readertreecardobserver)
event.Skip()
|
python
|
{
"resource": ""
}
|
q19482
|
ExclusiveConnectCardConnection.connect
|
train
|
def connect(self, protocol=None, mode=None, disposition=None):
'''Disconnect and reconnect in exclusive mode PCSCCardconnections.'''
CardConnectionDecorator.connect(self, protocol, mode, disposition)
component = self.component
while True:
if isinstance(component,
smartcard.pcsc.PCSCCardConnection.PCSCCardConnection):
pcscprotocol = PCSCCardConnection.translateprotocolmask(
protocol)
if 0 == pcscprotocol:
pcscprotocol = component.getProtocol()
if component.hcard is not None:
hresult = SCardDisconnect(component.hcard,
SCARD_LEAVE_CARD)
if hresult != 0:
raise CardConnectionException(
'Failed to disconnect: ' +
SCardGetErrorMessage(hresult))
hresult, component.hcard, dwActiveProtocol = SCardConnect(
component.hcontext, str(component.reader),
SCARD_SHARE_EXCLUSIVE, pcscprotocol)
if hresult != 0:
raise CardConnectionException(
'Failed to connect with SCARD_SHARE_EXCLUSIVE' +
SCardGetErrorMessage(hresult))
# print('reconnected exclusive')
break
if hasattr(component, 'component'):
component = component.component
else:
break
|
python
|
{
"resource": ""
}
|
q19483
|
build_module
|
train
|
def build_module(name, objs, doc='', source=None, mode='ignore'):
"""Create a module from imported objects.
Parameters
----------
name : str
New module name.
objs : dict
Dictionary of the objects (or their name) to import into the module,
keyed by the name they will take in the created module.
doc : str
Docstring of the new module.
source : Module object
Module where objects are defined if not explicitly given.
mode : {'raise', 'warn', 'ignore'}
How to deal with missing objects.
Returns
-------
ModuleType
A module built from a list of objects' name.
"""
import types
import warnings
import logging
logging.captureWarnings(capture=True)
try:
out = types.ModuleType(name, doc)
except TypeError:
msg = "Module '{}' is not properly formatted".format(name)
raise TypeError(msg)
for key, obj in objs.items():
if isinstance(obj, str) and source is not None:
module_mappings = getattr(source, obj, None)
else:
module_mappings = obj
if module_mappings is None:
msg = "{} has not been implemented.".format(obj)
if mode == 'raise':
raise NotImplementedError(msg)
elif mode == 'warn':
warnings.warn(msg)
else:
logging.info(msg)
else:
out.__dict__[key] = module_mappings
try:
module_mappings.__module__ = name
except AttributeError:
msg = "{} is not a function".format(module_mappings)
raise AttributeError(msg)
sys.modules[name] = out
return out
|
python
|
{
"resource": ""
}
|
q19484
|
base_flow_index
|
train
|
def base_flow_index(q, freq='YS'):
r"""Base flow index
Return the base flow index, defined as the minimum 7-day average flow divided by the mean flow.
Parameters
----------
q : xarray.DataArray
Rate of river discharge [m³/s]
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArrray
Base flow index.
Notes
-----
Let :math:`\mathbf{q}=q_0, q_1, \ldots, q_n` be the sequence of daily discharge and :math:`\overline{\mathbf{q}}`
the mean flow over the period. The base flow index is given by:
.. math::
\frac{\min(\mathrm{CMA}_7(\mathbf{q}))}{\overline{\mathbf{q}}}
where :math:`\mathrm{CMA}_7` is the seven days moving average of the daily flow:
.. math::
\mathrm{CMA}_7(q_i) = \frac{\sum_{j=i-3}^{i+3} q_j}{7}
"""
m7 = q.rolling(time=7, center=True).mean().resample(time=freq)
mq = q.resample(time=freq)
m7m = m7.min(dim='time')
return m7m / mq.mean(dim='time')
|
python
|
{
"resource": ""
}
|
q19485
|
cold_spell_duration_index
|
train
|
def cold_spell_duration_index(tasmin, tn10, window=6, freq='YS'):
r"""Cold spell duration index
Number of days with at least six consecutive days where the daily minimum temperature is below the 10th
percentile.
Parameters
----------
tasmin : xarray.DataArray
Minimum daily temperature.
tn10 : float
10th percentile of daily minimum temperature.
window : int
Minimum number of days with temperature below threshold to qualify as a cold spell. Default: 6.
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArray
Count of days with at least six consecutive days where the daily minimum temperature is below the 10th
percentile [days].
Notes
-----
Let :math:`TN_i` be the minimum daily temperature for the day of the year :math:`i` and :math:`TN10_i` the 10th
percentile of the minimum daily temperature over the 1961-1990 period for day of the year :math:`i`, the cold spell
duration index over period :math:`\phi` is defined as:
.. math::
\sum_{i \in \phi} \prod_{j=i}^{i+6} \left[ TN_j < TN10_j \right]
where :math:`[P]` is 1 if :math:`P` is true, and 0 if false.
References
----------
From the Expert Team on Climate Change Detection, Monitoring and Indices (ETCCDMI).
Example
-------
>>> tn10 = percentile_doy(historical_tasmin, per=.1)
>>> cold_spell_duration_index(reference_tasmin, tn10)
"""
if 'dayofyear' not in tn10.coords.keys():
raise AttributeError("tn10 should have dayofyear coordinates.")
# The day of year value of the tasmin series.
doy = tasmin.indexes['time'].dayofyear
tn10 = utils.convert_units_to(tn10, tasmin)
# If calendar of `tn10` is different from `tasmin`, interpolate.
tn10 = utils.adjust_doy_calendar(tn10, tasmin)
# Create an array with the shape and coords of tasmin, but with values set to tx90 according to the doy index.
thresh = xr.full_like(tasmin, np.nan)
thresh.data = tn10.sel(dayofyear=doy)
below = (tasmin < thresh)
return below.resample(time=freq).apply(rl.windowed_run_count, window=window, dim='time')
|
python
|
{
"resource": ""
}
|
q19486
|
cold_spell_days
|
train
|
def cold_spell_days(tas, thresh='-10 degC', window=5, freq='AS-JUL'):
r"""Cold spell days
The number of days that are part of a cold spell, defined as five or more consecutive days with mean daily
temperature below a threshold in °C.
Parameters
----------
tas : xarrray.DataArray
Mean daily temperature [℃] or [K]
thresh : str
Threshold temperature below which a cold spell begins [℃] or [K]. Default : '-10 degC'
window : int
Minimum number of days with temperature below threshold to qualify as a cold spell.
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArray
Cold spell days.
Notes
-----
Let :math:`T_i` be the mean daily temperature on day :math:`i`, the number of cold spell days during
period :math:`\phi` is given by
.. math::
\sum_{i \in \phi} \prod_{j=i}^{i+5} [T_j < thresh]
where :math:`[P]` is 1 if :math:`P` is true, and 0 if false.
"""
t = utils.convert_units_to(thresh, tas)
over = tas < t
group = over.resample(time=freq)
return group.apply(rl.windowed_run_count, window=window, dim='time')
|
python
|
{
"resource": ""
}
|
q19487
|
daily_pr_intensity
|
train
|
def daily_pr_intensity(pr, thresh='1 mm/day', freq='YS'):
r"""Average daily precipitation intensity
Return the average precipitation over wet days.
Parameters
----------
pr : xarray.DataArray
Daily precipitation [mm/d or kg/m²/s]
thresh : str
precipitation value over which a day is considered wet. Default : '1 mm/day'
freq : str, optional
Resampling frequency defining the periods
defined in http://pandas.pydata.org/pandas-docs/stable/timeseries.html#resampling. Default : '1 mm/day'
Returns
-------
xarray.DataArray
The average precipitation over wet days for each period
Notes
-----
Let :math:`\mathbf{p} = p_0, p_1, \ldots, p_n` be the daily precipitation and :math:`thresh` be the precipitation
threshold defining wet days. Then the daily precipitation intensity is defined as
.. math::
\frac{\sum_{i=0}^n p_i [p_i \leq thresh]}{\sum_{i=0}^n [p_i \leq thresh]}
where :math:`[P]` is 1 if :math:`P` is true, and 0 if false.
Examples
--------
The following would compute for each grid cell of file `pr.day.nc` the average
precipitation fallen over days with precipitation >= 5 mm at seasonal
frequency, ie DJF, MAM, JJA, SON, DJF, etc.:
>>> pr = xr.open_dataset('pr.day.nc')
>>> daily_int = daily_pr_intensity(pr, thresh='5 mm/day', freq="QS-DEC")
"""
t = utils.convert_units_to(thresh, pr, 'hydro')
# put pr=0 for non wet-days
pr_wd = xr.where(pr >= t, pr, 0)
pr_wd.attrs['units'] = pr.units
# sum over wanted period
s = pr_wd.resample(time=freq).sum(dim='time', keep_attrs=True)
sd = utils.pint_multiply(s, 1 * units.day, 'mm')
# get number of wetdays over period
wd = wetdays(pr, thresh=thresh, freq=freq)
return sd / wd
|
python
|
{
"resource": ""
}
|
q19488
|
maximum_consecutive_dry_days
|
train
|
def maximum_consecutive_dry_days(pr, thresh='1 mm/day', freq='YS'):
r"""Maximum number of consecutive dry days
Return the maximum number of consecutive days within the period where precipitation
is below a certain threshold.
Parameters
----------
pr : xarray.DataArray
Mean daily precipitation flux [mm]
thresh : str
Threshold precipitation on which to base evaluation [mm]. Default : '1 mm/day'
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArray
The maximum number of consecutive dry days.
Notes
-----
Let :math:`\mathbf{p}=p_0, p_1, \ldots, p_n` be a daily precipitation series and :math:`thresh` the threshold
under which a day is considered dry. Then let :math:`\mathbf{s}` be the sorted vector of indices :math:`i` where
:math:`[p_i < thresh] \neq [p_{i+1} < thresh]`, that is, the days when the temperature crosses the threshold.
Then the maximum number of consecutive dry days is given by
.. math::
\max(\mathbf{d}) \quad \mathrm{where} \quad d_j = (s_j - s_{j-1}) [p_{s_j} > thresh]
where :math:`[P]` is 1 if :math:`P` is true, and 0 if false. Note that this formula does not handle sequences at
the start and end of the series, but the numerical algorithm does.
"""
t = utils.convert_units_to(thresh, pr, 'hydro')
group = (pr < t).resample(time=freq)
return group.apply(rl.longest_run, dim='time')
|
python
|
{
"resource": ""
}
|
q19489
|
daily_freezethaw_cycles
|
train
|
def daily_freezethaw_cycles(tasmax, tasmin, freq='YS'):
r"""Number of days with a diurnal freeze-thaw cycle
The number of days where Tmax > 0℃ and Tmin < 0℃.
Parameters
----------
tasmax : xarray.DataArray
Maximum daily temperature [℃] or [K]
tasmin : xarray.DataArray
Minimum daily temperature values [℃] or [K]
freq : str
Resampling frequency
Returns
-------
xarray.DataArray
Number of days with a diurnal freeze-thaw cycle
Notes
-----
Let :math:`TX_{i}` be the maximum temperature at day :math:`i` and :math:`TN_{i}` be
the daily minimum temperature at day :math:`i`. Then the number of freeze thaw cycles
during period :math:`\phi` is given by :
.. math::
\sum_{i \in \phi} [ TX_{i} > 0℃ ] [ TN_{i} < 0℃ ]
where :math:`[P]` is 1 if :math:`P` is true, and 0 if false.
"""
frz = utils.convert_units_to('0 degC', tasmax)
ft = (tasmin < frz) * (tasmax > frz) * 1
out = ft.resample(time=freq).sum(dim='time')
return out
|
python
|
{
"resource": ""
}
|
q19490
|
daily_temperature_range
|
train
|
def daily_temperature_range(tasmax, tasmin, freq='YS'):
r"""Mean of daily temperature range.
The mean difference between the daily maximum temperature and the daily minimum temperature.
Parameters
----------
tasmax : xarray.DataArray
Maximum daily temperature values [℃] or [K]
tasmin : xarray.DataArray
Minimum daily temperature values [℃] or [K]
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArray
The average variation in daily temperature range for the given time period.
Notes
-----
Let :math:`TX_{ij}` and :math:`TN_{ij}` be the daily maximum and minimum temperature at day :math:`i`
of period :math:`j`. Then the mean diurnal temperature range in period :math:`j` is:
.. math::
DTR_j = \frac{ \sum_{i=1}^I (TX_{ij} - TN_{ij}) }{I}
"""
dtr = tasmax - tasmin
out = dtr.resample(time=freq).mean(dim='time', keep_attrs=True)
out.attrs['units'] = tasmax.units
return out
|
python
|
{
"resource": ""
}
|
q19491
|
daily_temperature_range_variability
|
train
|
def daily_temperature_range_variability(tasmax, tasmin, freq="YS"):
r"""Mean absolute day-to-day variation in daily temperature range.
Mean absolute day-to-day variation in daily temperature range.
Parameters
----------
tasmax : xarray.DataArray
Maximum daily temperature values [℃] or [K]
tasmin : xarray.DataArray
Minimum daily temperature values [℃] or [K]
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArray
The average day-to-day variation in daily temperature range for the given time period.
Notes
-----
Let :math:`TX_{ij}` and :math:`TN_{ij}` be the daily maximum and minimum temperature at
day :math:`i` of period :math:`j`. Then calculated is the absolute day-to-day differences in
period :math:`j` is:
.. math::
vDTR_j = \frac{ \sum_{i=2}^{I} |(TX_{ij}-TN_{ij})-(TX_{i-1,j}-TN_{i-1,j})| }{I}
"""
vdtr = abs((tasmax - tasmin).diff(dim='time'))
out = vdtr.resample(time=freq).mean(dim='time')
out.attrs['units'] = tasmax.units
return out
|
python
|
{
"resource": ""
}
|
q19492
|
extreme_temperature_range
|
train
|
def extreme_temperature_range(tasmax, tasmin, freq='YS'):
r"""Extreme intra-period temperature range.
The maximum of max temperature (TXx) minus the minimum of min temperature (TNn) for the given time period.
Parameters
----------
tasmax : xarray.DataArray
Maximum daily temperature values [℃] or [K]
tasmin : xarray.DataArray
Minimum daily temperature values [℃] or [K]
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArray
Extreme intra-period temperature range for the given time period.
Notes
-----
Let :math:`TX_{ij}` and :math:`TN_{ij}` be the daily maximum and minimum temperature at day :math:`i`
of period :math:`j`. Then the extreme temperature range in period :math:`j` is:
.. math::
ETR_j = max(TX_{ij}) - min(TN_{ij})
"""
tx_max = tasmax.resample(time=freq).max(dim='time')
tn_min = tasmin.resample(time=freq).min(dim='time')
out = tx_max - tn_min
out.attrs['units'] = tasmax.units
return out
|
python
|
{
"resource": ""
}
|
q19493
|
freshet_start
|
train
|
def freshet_start(tas, thresh='0 degC', window=5, freq='YS'):
r"""First day consistently exceeding threshold temperature.
Returns first day of period where a temperature threshold is exceeded
over a given number of days.
Parameters
----------
tas : xarray.DataArray
Mean daily temperature [℃] or [K]
thresh : str
Threshold temperature on which to base evaluation [℃] or [K]. Default '0 degC'
window : int
Minimum number of days with temperature above threshold needed for evaluation
freq : str, optional
Resampling frequency
Returns
-------
float
Day of the year when temperature exceeds threshold over a given number of days for the first time. If there are
no such day, return np.nan.
Notes
-----
Let :math:`x_i` be the daily mean temperature at day of the year :math:`i` for values of :math:`i` going from 1
to 365 or 366. The start date of the freshet is given by the smallest index :math:`i` for which
.. math::
\prod_{j=i}^{i+w} [x_j > thresh]
is true, where :math:`w` is the number of days the temperature threshold should be exceeded, and :math:`[P]` is
1 if :math:`P` is true, and 0 if false.
"""
thresh = utils.convert_units_to(thresh, tas)
over = (tas > thresh)
group = over.resample(time=freq)
return group.apply(rl.first_run_ufunc, window=window, index='dayofyear')
|
python
|
{
"resource": ""
}
|
q19494
|
frost_days
|
train
|
def frost_days(tasmin, freq='YS'):
r"""Frost days index
Number of days where daily minimum temperatures are below 0℃.
Parameters
----------
tasmin : xarray.DataArray
Minimum daily temperature [℃] or [K]
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArray
Frost days index.
Notes
-----
Let :math:`TN_{ij}` be the daily minimum temperature at day :math:`i` of period :math:`j`. Then
counted is the number of days where:
.. math::
TN_{ij} < 0℃
"""
tu = units.parse_units(tasmin.attrs['units'].replace('-', '**-'))
fu = 'degC'
frz = 0
if fu != tu:
frz = units.convert(frz, fu, tu)
f = (tasmin < frz) * 1
return f.resample(time=freq).sum(dim='time')
|
python
|
{
"resource": ""
}
|
q19495
|
growing_season_length
|
train
|
def growing_season_length(tas, thresh='5.0 degC', window=6, freq='YS'):
r"""Growing season length.
The number of days between the first occurrence of at least
six consecutive days with mean daily temperature over 5℃ and
the first occurrence of at least six consecutive days with
mean daily temperature below 5℃ after July 1st in the northern
hemisphere and January 1st in the southern hemisphere.
Parameters
---------
tas : xarray.DataArray
Mean daily temperature [℃] or [K]
thresh : str
Threshold temperature on which to base evaluation [℃] or [K]. Default: '5.0 degC'.
window : int
Minimum number of days with temperature above threshold to mark the beginning and end of growing season.
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArray
Growing season length.
Notes
-----
Let :math:`TG_{ij}` be the mean temperature at day :math:`i` of period :math:`j`. Then counted is
the number of days between the first occurrence of at least 6 consecutive days with:
.. math::
TG_{ij} > 5 ℃
and the first occurrence after 1 July of at least 6 consecutive days with:
.. math::
TG_{ij} < 5 ℃
"""
# i = xr.DataArray(np.arange(tas.time.size), dims='time')
# ind = xr.broadcast(i, tas)[0]
#
# c = ((tas > thresh) * 1).rolling(time=window).sum()
# i1 = ind.where(c == window).resample(time=freq).min(dim='time')
#
# # Resample sets the time to T00:00.
# i11 = i1.reindex_like(c, method='ffill')
#
# # TODO: Adjust for southern hemisphere
#
# #i2 = ind.where(c == 0).where(tas.time.dt.month >= 7)
# # add check to make sure indice of end of growing season is after growing season start
# i2 = ind.where((c==0) & (ind > i11)).where(tas.time.dt.month >= 7)
#
# d = i2 - i11
#
# # take min value (first occurence after july)
# gsl = d.resample(time=freq).min(dim='time')
#
# # turn nan into 0
# gsl = xr.where(np.isnan(gsl), 0, gsl)
# compute growth season length on resampled data
thresh = utils.convert_units_to(thresh, tas)
c = ((tas > thresh) * 1).rolling(time=window).sum().chunk(tas.chunks)
def compute_gsl(c):
nt = c.time.size
i = xr.DataArray(np.arange(nt), dims='time').chunk({'time': 1})
ind = xr.broadcast(i, c)[0].chunk(c.chunks)
i1 = ind.where(c == window).min(dim='time')
i1 = xr.where(np.isnan(i1), nt, i1)
i11 = i1.reindex_like(c, method='ffill')
i2 = ind.where((c == 0) & (ind > i11)).where(c.time.dt.month >= 7)
i2 = xr.where(np.isnan(i2), nt, i2)
d = (i2 - i1).min(dim='time')
return d
gsl = c.resample(time=freq).apply(compute_gsl)
return gsl
|
python
|
{
"resource": ""
}
|
q19496
|
heat_wave_frequency
|
train
|
def heat_wave_frequency(tasmin, tasmax, thresh_tasmin='22.0 degC', thresh_tasmax='30 degC',
window=3, freq='YS'):
# Dev note : we should decide if it is deg K or C
r"""Heat wave frequency
Number of heat waves over a given period. A heat wave is defined as an event
where the minimum and maximum daily temperature both exceeds specific thresholds
over a minimum number of days.
Parameters
----------
tasmin : xarrray.DataArray
Minimum daily temperature [℃] or [K]
tasmax : xarrray.DataArray
Maximum daily temperature [℃] or [K]
thresh_tasmin : str
The minimum temperature threshold needed to trigger a heatwave event [℃] or [K]. Default : '22 degC'
thresh_tasmax : str
The maximum temperature threshold needed to trigger a heatwave event [℃] or [K]. Default : '30 degC'
window : int
Minimum number of days with temperatures above thresholds to qualify as a heatwave.
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArray
Number of heatwave at the wanted frequency
Notes
-----
The thresholds of 22° and 25°C for night temperatures and 30° and 35°C for day temperatures were selected by
Health Canada professionals, following a temperature–mortality analysis. These absolute temperature thresholds
characterize the occurrence of hot weather events that can result in adverse health outcomes for Canadian
communities (Casati et al., 2013).
In Robinson (2001), the parameters would be `thresh_tasmin=27.22, thresh_tasmax=39.44, window=2` (81F, 103F).
References
----------
Casati, B., A. Yagouti, and D. Chaumont, 2013: Regional Climate Projections of Extreme Heat Events in Nine Pilot
Canadian Communities for Public Health Planning. J. Appl. Meteor. Climatol., 52, 2669–2698,
https://doi.org/10.1175/JAMC-D-12-0341.1
Robinson, P.J., 2001: On the Definition of a Heat Wave. J. Appl. Meteor., 40, 762–775,
https://doi.org/10.1175/1520-0450(2001)040<0762:OTDOAH>2.0.CO;2
"""
thresh_tasmax = utils.convert_units_to(thresh_tasmax, tasmax)
thresh_tasmin = utils.convert_units_to(thresh_tasmin, tasmin)
cond = (tasmin > thresh_tasmin) & (tasmax > thresh_tasmax)
group = cond.resample(time=freq)
return group.apply(rl.windowed_run_events, window=window, dim='time')
|
python
|
{
"resource": ""
}
|
q19497
|
heat_wave_index
|
train
|
def heat_wave_index(tasmax, thresh='25.0 degC', window=5, freq='YS'):
r"""Heat wave index.
Number of days that are part of a heatwave, defined as five or more consecutive days over 25℃.
Parameters
----------
tasmax : xarrray.DataArray
Maximum daily temperature [℃] or [K]
thresh : str
Threshold temperature on which to designate a heatwave [℃] or [K]. Default: '25.0 degC'.
window : int
Minimum number of days with temperature above threshold to qualify as a heatwave.
freq : str, optional
Resampling frequency
Returns
-------
DataArray
Heat wave index.
"""
thresh = utils.convert_units_to(thresh, tasmax)
over = tasmax > thresh
group = over.resample(time=freq)
return group.apply(rl.windowed_run_count, window=window, dim='time')
|
python
|
{
"resource": ""
}
|
q19498
|
heat_wave_max_length
|
train
|
def heat_wave_max_length(tasmin, tasmax, thresh_tasmin='22.0 degC', thresh_tasmax='30 degC',
window=3, freq='YS'):
# Dev note : we should decide if it is deg K or C
r"""Heat wave max length
Maximum length of heat waves over a given period. A heat wave is defined as an event
where the minimum and maximum daily temperature both exceeds specific thresholds
over a minimum number of days.
By definition heat_wave_max_length must be >= window.
Parameters
----------
tasmin : xarrray.DataArray
Minimum daily temperature [℃] or [K]
tasmax : xarrray.DataArray
Maximum daily temperature [℃] or [K]
thresh_tasmin : str
The minimum temperature threshold needed to trigger a heatwave event [℃] or [K]. Default : '22 degC'
thresh_tasmax : str
The maximum temperature threshold needed to trigger a heatwave event [℃] or [K]. Default : '30 degC'
window : int
Minimum number of days with temperatures above thresholds to qualify as a heatwave.
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArray
Maximum length of heatwave at the wanted frequency
Notes
-----
The thresholds of 22° and 25°C for night temperatures and 30° and 35°C for day temperatures were selected by
Health Canada professionals, following a temperature–mortality analysis. These absolute temperature thresholds
characterize the occurrence of hot weather events that can result in adverse health outcomes for Canadian
communities (Casati et al., 2013).
In Robinson (2001), the parameters would be `thresh_tasmin=27.22, thresh_tasmax=39.44, window=2` (81F, 103F).
References
----------
Casati, B., A. Yagouti, and D. Chaumont, 2013: Regional Climate Projections of Extreme Heat Events in Nine Pilot
Canadian Communities for Public Health Planning. J. Appl. Meteor. Climatol., 52, 2669–2698,
https://doi.org/10.1175/JAMC-D-12-0341.1
Robinson, P.J., 2001: On the Definition of a Heat Wave. J. Appl. Meteor., 40, 762–775,
https://doi.org/10.1175/1520-0450(2001)040<0762:OTDOAH>2.0.CO;2
"""
thresh_tasmax = utils.convert_units_to(thresh_tasmax, tasmax)
thresh_tasmin = utils.convert_units_to(thresh_tasmin, tasmin)
cond = (tasmin > thresh_tasmin) & (tasmax > thresh_tasmax)
group = cond.resample(time=freq)
max_l = group.apply(rl.longest_run, dim='time')
return max_l.where(max_l >= window, 0)
|
python
|
{
"resource": ""
}
|
q19499
|
heating_degree_days
|
train
|
def heating_degree_days(tas, thresh='17.0 degC', freq='YS'):
r"""Heating degree days
Sum of degree days below the temperature threshold at which spaces are heated.
Parameters
----------
tas : xarray.DataArray
Mean daily temperature [℃] or [K]
thresh : str
Threshold temperature on which to base evaluation [℃] or [K]. Default: '17.0 degC'.
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArray
Heating degree days index.
Notes
-----
Let :math:`TG_{ij}` be the daily mean temperature at day :math:`i` of period :math:`j`. Then the
heating degree days are:
.. math::
HD17_j = \sum_{i=1}^{I} (17℃ - TG_{ij})
"""
thresh = utils.convert_units_to(thresh, tas)
return tas.pipe(lambda x: thresh - x) \
.clip(0) \
.resample(time=freq) \
.sum(dim='time')
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.