id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
147,548 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/Observer.py
|
smartcard.Observer.Observable
|
class Observable(Synchronization):
def __init__(self) -> None:
super().__init__()
self.obs: list[Observer] = []
self.changed = 0
def addObserver(self, observer: Observer) -> None:
if observer not in self.obs:
self.obs.append(observer)
def deleteObserver(self, observer: Observer) -> None:
self.obs.remove(observer)
def notifyObservers(self, arg: typing.Any = None) -> None:
"""If 'changed' indicates that this object
has changed, notify all its observers, then
call clearChanged(). Each observer has its
update() called with two arguments: this
observable object and the generic 'arg'."""
with self.mutex:
if not self.changed:
return
# Make a copy of the observer list.
observers = self.obs.copy()
self.changed = 0
# Update observers
for observer in observers:
observer.update(self, arg)
def deleteObservers(self) -> None:
self.obs = []
def setChanged(self) -> None:
self.changed = 1
def clearChanged(self) -> None:
self.changed = 0
def hasChanged(self) -> int:
return self.changed
def countObservers(self) -> int:
return len(self.obs)
|
class Observable(Synchronization):
def __init__(self) -> None:
pass
def addObserver(self, observer: Observer) -> None:
pass
def deleteObserver(self, observer: Observer) -> None:
pass
def notifyObservers(self, arg: typing.Any = None) -> None:
'''If 'changed' indicates that this object
has changed, notify all its observers, then
call clearChanged(). Each observer has its
update() called with two arguments: this
observable object and the generic 'arg'.'''
pass
def deleteObservers(self) -> None:
pass
def setChanged(self) -> None:
pass
def clearChanged(self) -> None:
pass
def hasChanged(self) -> int:
pass
def countObservers(self) -> int:
pass
| 10 | 1 | 4 | 0 | 3 | 1 | 1 | 0.25 | 1 | 5 | 1 | 3 | 9 | 2 | 9 | 34 | 45 | 10 | 28 | 14 | 18 | 7 | 28 | 14 | 18 | 3 | 7 | 2 | 12 |
147,549 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/Observer.py
|
smartcard.Observer.Observer
|
class Observer:
def update(self, observable: Observable, arg: typing.Any) -> None:
"""Called when the observed object is
modified. You call an Observable object's
notifyObservers method to notify all the
object's observers of the change."""
pass
|
class Observer:
def update(self, observable: Observable, arg: typing.Any) -> None:
'''Called when the observed object is
modified. You call an Observable object's
notifyObservers method to notify all the
object's observers of the change.'''
pass
| 2 | 1 | 6 | 0 | 2 | 4 | 1 | 1.33 | 0 | 2 | 1 | 5 | 1 | 0 | 1 | 1 | 7 | 0 | 3 | 2 | 1 | 4 | 3 | 2 | 1 | 1 | 0 | 0 | 1 |
147,550 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/PassThruCardService.py
|
smartcard.PassThruCardService.PassThruCardService
|
class PassThruCardService(CardService.CardService):
"""Pass-thru card service class."""
def __init__(self, connection, cardname=None):
"""Construct a pass-thru card service.
@param connection: the CardConnection used to access the smart card
"""
CardService.CardService.__init__(self, connection, cardname)
@staticmethod
def supports(cardname):
"""Returns True if the cardname is supported by the card service.
The PassThruCardService supports all cardnames and always
returns True."""
return True
|
class PassThruCardService(CardService.CardService):
'''Pass-thru card service class.'''
def __init__(self, connection, cardname=None):
'''Construct a pass-thru card service.
@param connection: the CardConnection used to access the smart card
'''
pass
@staticmethod
def supports(cardname):
'''Returns True if the cardname is supported by the card service.
The PassThruCardService supports all cardnames and always
returns True.'''
pass
| 4 | 3 | 6 | 1 | 2 | 3 | 1 | 1.17 | 1 | 0 | 0 | 0 | 1 | 0 | 2 | 5 | 16 | 3 | 6 | 4 | 2 | 7 | 5 | 3 | 2 | 1 | 1 | 0 | 2 |
147,551 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/ReaderMonitoring.py
|
smartcard.ReaderMonitoring.ReaderMonitoringThread
|
class ReaderMonitoringThread(Thread):
"""Reader insertion thread.
This thread polls for pcsc reader insertion, since no
reader insertion event is available in pcsc.
"""
__shared_state = {}
def __init__(self, observable, readerProc, period):
self.__dict__ = self.__shared_state
Thread.__init__(self)
self.observable = observable
self.stopEvent = Event()
self.stopEvent.clear()
self.readers = []
self.daemon = True
self.name = "smartcard.ReaderMonitoringThread"
self.readerProc = readerProc
self.period = period
def run(self):
"""Runs until stopEvent is notified, and notify
observers of all reader insertion/removal.
"""
while not self.stopEvent.is_set():
try:
# no need to monitor if no observers
if 0 < self.observable.countObservers():
currentReaders = self.readerProc()
addedReaders = []
removedReaders = []
if currentReaders != self.readers:
for reader in currentReaders:
if reader not in self.readers:
addedReaders.append(reader)
for reader in self.readers:
if reader not in currentReaders:
removedReaders.append(reader)
if addedReaders or removedReaders:
# Notify observers
self.readers = []
for r in currentReaders:
self.readers.append(r)
self.observable.setChanged()
self.observable.notifyObservers(
(addedReaders, removedReaders)
)
# wait every second on stopEvent
self.stopEvent.wait(self.period)
except Exception:
# FIXME Tighten the exceptions caught by this block
traceback.print_exc()
# Most likely raised during interpreter shutdown due
# to unclean exit which failed to remove all observers.
# To solve this, we set the stop event and pass the
# exception to let the thread finish gracefully.
self.stopEvent.set()
def stop(self):
self.stopEvent.set()
self.join()
|
class ReaderMonitoringThread(Thread):
'''Reader insertion thread.
This thread polls for pcsc reader insertion, since no
reader insertion event is available in pcsc.
'''
def __init__(self, observable, readerProc, period):
pass
def run(self):
'''Runs until stopEvent is notified, and notify
observers of all reader insertion/removal.
'''
pass
def stop(self):
pass
| 4 | 2 | 18 | 1 | 13 | 4 | 4 | 0.36 | 1 | 2 | 0 | 0 | 3 | 8 | 3 | 28 | 65 | 8 | 42 | 18 | 38 | 15 | 40 | 18 | 36 | 11 | 1 | 6 | 13 |
147,552 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/ReaderMonitoring.py
|
smartcard.ReaderMonitoring.ReaderObserver
|
class ReaderObserver(Observer):
"""
ReaderObserver is a base abstract class for objects that are to be notified
upon smartcard reader insertion/removal.
"""
def __init__(self):
pass
def update(self, observable, handlers):
"""Called upon reader insertion/removal.
@param observable:
@param handlers:
- addedreaders: list of added readers causing notification
- removedreaders: list of removed readers causing notification
"""
pass
|
class ReaderObserver(Observer):
'''
ReaderObserver is a base abstract class for objects that are to be notified
upon smartcard reader insertion/removal.
'''
def __init__(self):
pass
def update(self, observable, handlers):
'''Called upon reader insertion/removal.
@param observable:
@param handlers:
- addedreaders: list of added readers causing notification
- removedreaders: list of removed readers causing notification
'''
pass
| 3 | 2 | 6 | 1 | 2 | 3 | 1 | 2 | 1 | 0 | 0 | 6 | 2 | 0 | 2 | 3 | 18 | 3 | 5 | 3 | 2 | 10 | 5 | 3 | 2 | 1 | 1 | 0 | 2 |
147,553 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/Session.py
|
smartcard.Session.Session
|
class Session:
"""The Session object enables programmers to transmit APDU to smartcards.
This is an example of use of the Session object:
>>> import smartcard
>>> reader=smartcard.listReaders()
>>> s = smartcard.Session(reader[0])
>>> SELECT = [0xA0, 0xA4, 0x00, 0x00, 0x02]
>>> DF_TELECOM = [0x7F, 0x10]
>>> data, sw1, sw2 = s.sendCommandAPDU(SELECT+DF_TELECOM)
>>> print(data, sw1, sw2)
>>> s.close()
>>> print(`s`)
"""
def __init__(self, readerName=None, cardServiceClass=None):
"""Session constructor. Initializes a smart card session and
connect to the card.
@param readerName: reader to connect to; default is first PCSC reader
@param cardServiceClass: card service to bind the session to; default
is None
"""
# if reader name not given, select first reader
if readerName is None:
if len(readers()) > 0:
self.reader = readers()[0]
self.readerName = repr(self.reader)
else:
raise NoReadersException()
# otherwise select reader from name
else:
self.readerName = readerName
for reader in readers():
if readerName == str(reader):
self.reader = reader
self.readerName = repr(self.reader)
try:
self.reader
except AttributeError:
raise InvalidReaderException(self.readerName)
# open card connection and bind PassThruCardService
cc = self.reader.createConnection()
self.cs = PassThruCardService(cc)
self.cs.connection.connect()
def close(self):
"""Close the smartcard session.
Closing a session will disconnect from the card."""
self.cs.connection.disconnect()
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
def getATR(self):
"""Returns the ATR of the connected card."""
return self.cs.connection.getATR()
def __repr__(self):
"""Returns a string representation of the session."""
return "<Session instance: readerName=%s>" % self.readerName
|
class Session:
'''The Session object enables programmers to transmit APDU to smartcards.
This is an example of use of the Session object:
>>> import smartcard
>>> reader=smartcard.listReaders()
>>> s = smartcard.Session(reader[0])
>>> SELECT = [0xA0, 0xA4, 0x00, 0x00, 0x02]
>>> DF_TELECOM = [0x7F, 0x10]
>>> data, sw1, sw2 = s.sendCommandAPDU(SELECT+DF_TELECOM)
>>> print(data, sw1, sw2)
>>> s.close()
>>> print(`s`)
'''
def __init__(self, readerName=None, cardServiceClass=None):
'''Session constructor. Initializes a smart card session and
connect to the card.
@param readerName: reader to connect to; default is first PCSC reader
@param cardServiceClass: card service to bind the session to; default
is None
'''
pass
def close(self):
'''Close the smartcard session.
Closing a session will disconnect from the card.'''
pass
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
'''
pass
def getATR(self):
'''Returns the ATR of the connected card.'''
pass
def __repr__(self):
'''Returns a string representation of the session.'''
pass
| 6 | 6 | 12 | 2 | 6 | 4 | 2 | 0.94 | 0 | 5 | 3 | 0 | 5 | 3 | 5 | 5 | 81 | 17 | 33 | 12 | 27 | 31 | 31 | 12 | 25 | 6 | 0 | 3 | 11 |
147,554 |
LukeB42/Window
|
LukeB42_Window/examples/world_clock.py
|
world_clock.WorldClock
|
class WorldClock(window.Pane):
geometry = [window.EXPAND, window.EXPAND]
def update(self):
self.change_content(0, "")
for i, timezone in enumerate(times.split('\n')):
if not timezone: continue
# We can append the text to the zeroth content frame using the
# additive assignment operator. Specifying which frame to append to
# is done with an int as the first element of a tuple or list:
# self += (1, "This is concatenated onto the second content frame.")
tz = pytz.timezone(timezone)
self += datetime.now(tz).strftime(timezone + "\t%H:%M")
if not i % 2:
self += '\n'
else:
self += ' '
|
class WorldClock(window.Pane):
def update(self):
pass
| 2 | 0 | 14 | 0 | 10 | 4 | 4 | 0.33 | 1 | 2 | 0 | 0 | 1 | 0 | 1 | 7 | 16 | 0 | 12 | 5 | 10 | 4 | 12 | 5 | 10 | 4 | 2 | 2 | 4 |
147,555 |
LukeB42/Window
|
LukeB42_Window/examples/advent.py
|
advent.Weapon
|
class Weapon(object):
name = ""
description = ""
power = 0
def __init__(self, name):
self.name = name
|
class Weapon(object):
def __init__(self, name):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 6 | 0 | 6 | 5 | 4 | 0 | 6 | 5 | 4 | 1 | 1 | 0 | 1 |
147,556 |
LukeB42/Window
|
LukeB42_Window/examples/window.py
|
window.PaneError
|
class PaneError(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return(repr(self.message))
|
class PaneError(Exception):
def __init__(self, message):
pass
def __str__(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 12 | 6 | 1 | 5 | 4 | 2 | 0 | 5 | 4 | 2 | 1 | 3 | 0 | 2 |
147,557 |
LukeB42/Window
|
LukeB42_Window/examples/window.py
|
window.PaneError
|
class PaneError(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return(repr(self.message))
|
class PaneError(Exception):
def __init__(self, message):
pass
def __str__(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 12 | 6 | 1 | 5 | 4 | 2 | 0 | 5 | 4 | 2 | 1 | 3 | 0 | 2 |
147,558 |
LukeB42/Window
|
LukeB42_Window/examples/corner_test.py
|
corner_test.CornerPane
|
class CornerPane(window.Pane):
geometry = [10, 10]
self_coordinating = True
def update(self):
updatestr = ""
for _ in range(50):
updatestr += random.choice(string.ascii_letters)
updatestr += '\n' * random.randint(0, 5)
self.change_content(0, updatestr)
self.coords[0] = ((random.randint(0,10), random.randint(0,10)), (random.randint(0,10), random.randint(0,10)))
self.coords[1] = ((random.randint(0,10), random.randint(0,10)), (random.randint(0,10), random.randint(0,10)))
|
class CornerPane(window.Pane):
def update(self):
pass
| 2 | 0 | 8 | 0 | 8 | 0 | 2 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 7 | 11 | 0 | 11 | 6 | 9 | 0 | 11 | 6 | 9 | 2 | 2 | 1 | 2 |
147,559 |
LukeB42/Window
|
LukeB42_Window/examples/window.py
|
window.WindowError
|
class WindowError(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return(repr(self.message))
|
class WindowError(Exception):
def __init__(self, message):
pass
def __str__(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 12 | 6 | 1 | 5 | 4 | 2 | 0 | 5 | 4 | 2 | 1 | 3 | 0 | 2 |
147,560 |
LukeB42/Window
|
LukeB42_Window/examples/window.py
|
window.WindowError
|
class WindowError(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return(repr(self.message))
|
class WindowError(Exception):
def __init__(self, message):
pass
def __str__(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 12 | 6 | 1 | 5 | 4 | 2 | 0 | 5 | 4 | 2 | 1 | 3 | 0 | 2 |
147,561 |
LukeB42/Window
|
LukeB42_Window/examples/kilo.py
|
kilo.Editor
|
class Editor(Pane):
"""
Defines a text editor/input pane.
"""
geometry = [EXPAND, EXPAND]
buffer = ""
buffers = {}
clipboard = ""
def update(self):
header = " Psybernetics kilo 0.0.1 (Python %i.%i.%i)" %\
(sys.version_info.major, sys.version_info.minor, sys.version_info.micro)
header += ' ' * (self.width - len(header))
header += "\n"
self.change_content(0,header, ALIGN_LEFT, palette("black", "white"))
pass
# if len(self.content) >= 1:
# self.change_content(1, "%i\n" % len(self.buffer))
def process_input(self, character):
self.window.window.clear()
self.status.change_content(0,
str(character),
ALIGN_LEFT,
palette(-1, -1))
if character == 23 and self.buffer: # Delete word on ^W
self.buffer = self.buffer.split("\n")
line = self.buffer[-1].split()
if line:
line = ' '.join(line[:-1])
self.buffer[-1] = line
self.buffer = '\n'.join(self.buffer)
elif character == 11 and self.buffer: # Yank line on ^K
self.buffer = self.buffer.split("\n")
self.clipboard = self.buffer[-1]
self.buffer = '\n'.join(self.buffer[:-1])
elif character == 15 and self.buffer: # Write file to disk on ^O
self.active = False
self.status.saving = True
elif character == 263 and self.buffer: # Handle backspace
self.buffer = self.buffer[:-1]
elif character == 10 or character == 13: # Handle the return key
self.buffer += "\n"
elif character == 1: # Execute as cmd on ^A
line = self.buffer.split('\n')[-1]
line = line.split()
if not line: return
output = subprocess.Popen(line, stdout=subprocess.PIPE).communicate()[0]
self.buffer = self.buffer.split('\n')
self.buffer[-1] = output
f = lambda x: x.decode("ascii", "ignore") if hasattr(x, "decode") else x
self.buffer = '\n'.join([f(_) for _ in self.buffer])
else:
try: self.buffer += chr(character) # Append input to buffer
except: pass
self.change_content(1, self.buffer, ALIGN_LEFT)
self.change_content(2, ' ', ALIGN_LEFT, palette(-1, "yellow"))
|
class Editor(Pane):
'''
Defines a text editor/input pane.
'''
def update(self):
pass
def process_input(self, character):
pass
| 3 | 1 | 24 | 2 | 23 | 4 | 6 | 0.24 | 1 | 2 | 0 | 0 | 2 | 1 | 2 | 8 | 60 | 5 | 50 | 12 | 47 | 12 | 43 | 12 | 40 | 10 | 2 | 2 | 11 |
147,562 |
LukeB42/Window
|
LukeB42_Window/examples/advent.py
|
advent.Person
|
class Person(object):
"""
"""
def __init__(self):
self.level = 1
self.health = [100, 100] # [actual, maximum]
self.mana = [100, 100]
self.money = 100
self.weapons = None
self.weapons = []
|
class Person(object):
'''
'''
def __init__(self):
pass
| 2 | 1 | 7 | 0 | 7 | 1 | 1 | 0.38 | 1 | 0 | 0 | 2 | 1 | 5 | 1 | 1 | 10 | 0 | 8 | 7 | 6 | 3 | 8 | 7 | 6 | 1 | 1 | 0 | 1 |
147,563 |
LukeB42/Window
|
LukeB42_Window/examples/advent.py
|
advent.PClass
|
class PClass(object):
def __init__(self, name):
self.class_type = name
|
class PClass(object):
def __init__(self, name):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 3 | 0 | 3 | 3 | 1 | 0 | 3 | 3 | 1 | 1 | 1 | 0 | 1 |
147,564 |
LukeB42/Window
|
LukeB42_Window/examples/window.py
|
window.Pager
|
class Pager(Pane):
"""
Defines a scrolling pager for long multi-line strings.
"""
geometry = [EXPAND, EXPAND]
data = ""
outbuffer = ""
position = 0
def update(self):
self.outbuffer = self.data.split('\n')[self.position:]
self.change_content(1, '\n'.join(self.outbuffer))
def process_input(self, character):
self.window.window.clear()
if character == 259: # Up arrow
if self.position != 0:
self.position -= 1
elif character == 258: # Down arrow
self.position += 1
elif character == 339: # Page up
if self.position - self.height < 0:
self.position = 0
else:
self.position -= self.height
elif character == 338: # Page down
if not self.position + self.height > len(self.data.split('\n')):
self.position += self.height
|
class Pager(Pane):
'''
Defines a scrolling pager for long multi-line strings.
'''
def update(self):
pass
def process_input(self, character):
pass
| 3 | 1 | 9 | 0 | 9 | 2 | 5 | 0.3 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 8 | 28 | 2 | 23 | 7 | 20 | 7 | 19 | 7 | 16 | 8 | 2 | 2 | 9 |
147,565 |
LukeB42/Window
|
LukeB42_Window/examples/window.py
|
window.Pager
|
class Pager(Pane):
"""
Defines a scrolling pager for long multi-line strings.
"""
geometry = [EXPAND, EXPAND]
data = ""
outbuffer = ""
position = 0
def update(self):
self.outbuffer = self.data.split('\n')[self.position:]
self.change_content(1, '\n'.join(self.outbuffer))
def process_input(self, character):
self.window.window.clear()
if character == 259: # Up arrow
if self.position != 0:
self.position -= 1
elif character == 258: # Down arrow
self.position += 1
elif character == 339: # Page up
if self.position - self.height < 0:
self.position = 0
else:
self.position -= self.height
elif character == 338: # Page down
if not self.position + self.height > len(self.data.split('\n')):
self.position += self.height
|
class Pager(Pane):
'''
Defines a scrolling pager for long multi-line strings.
'''
def update(self):
pass
def process_input(self, character):
pass
| 3 | 1 | 9 | 0 | 9 | 2 | 5 | 0.3 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 8 | 28 | 2 | 23 | 7 | 20 | 7 | 19 | 7 | 16 | 8 | 2 | 2 | 9 |
147,566 |
LukeB42/Window
|
LukeB42_Window/window.py
|
window.Menu
|
class Menu(Pane):
"""
Defines a menu where items call local methods.
"""
geometry = [EXPAND, EXPAND]
# Default and selection colours.
col = [-1, -1] # fg, bg
sel = [-1, "blue"]
items = []
def update(self):
for i, item in enumerate(self.items):
if item[0]:
colours = palette(self.sel[0], self.sel[1])
else:
colours = palette(self.col[0], self.col[1])
text = ' ' + item[1]
spaces = ' ' * (self.width - len(text))
text += spaces
self.change_content(i, text + '\n', ALIGN_LEFT, colours)
def process_input(self, character):
# Handle the return key
if character == 10 or character == 13:
for i, item in enumerate(self.items):
if item[0]:
func = getattr(self, item[2].lower(), None)
if func:
func()
# Handle navigating the menu
elif character in [259, 258, 339, 338]:
for i, item in enumerate(self.items):
if item[0]:
if character == 259: # up arrow
if i == 0: break
item[0] = 0
self.items[i-1][0] = 1
break
if character == 258: # down arrow
if i+1 >= len(self.items): break
item[0] = 0
self.items[i+1][0] = 1
break
if character == 339: # page up
item[0] = 0
self.items[0][0] = 1
break
if character == 338: # page down
item[0] = 0
self.items[-1][0] = 1
break
|
class Menu(Pane):
'''
Defines a menu where items call local methods.
'''
def update(self):
pass
def process_input(self, character):
pass
| 3 | 1 | 21 | 1 | 19 | 3 | 9 | 0.26 | 1 | 1 | 0 | 3 | 2 | 0 | 2 | 8 | 52 | 3 | 43 | 13 | 40 | 11 | 43 | 13 | 40 | 14 | 2 | 5 | 17 |
147,567 |
LukeB42/Window
|
LukeB42_Window/window.py
|
window.Menu
|
class Menu(Pane):
"""
Defines a menu where items call local methods.
"""
geometry = [EXPAND, EXPAND]
# Default and selection colours.
col = [-1, -1] # fg, bg
sel = [-1, "blue"]
items = []
def update(self):
for i, item in enumerate(self.items):
if item[0]:
colours = palette(self.sel[0], self.sel[1])
else:
colours = palette(self.col[0], self.col[1])
text = ' ' + item[1]
spaces = ' ' * (self.width - len(text))
text += spaces
self.change_content(i, text + '\n', ALIGN_LEFT, colours)
def process_input(self, character):
# Handle the return key
if character == 10 or character == 13:
for i, item in enumerate(self.items):
if item[0]:
func = getattr(self, item[2].lower(), None)
if func:
func()
# Handle navigating the menu
elif character in [259, 258, 339, 338]:
for i, item in enumerate(self.items):
if item[0]:
if character == 259: # up arrow
if i == 0: break
item[0] = 0
self.items[i-1][0] = 1
break
if character == 258: # down arrow
if i+1 >= len(self.items): break
item[0] = 0
self.items[i+1][0] = 1
break
if character == 339: # page up
item[0] = 0
self.items[0][0] = 1
break
if character == 338: # page down
item[0] = 0
self.items[-1][0] = 1
break
|
class Menu(Pane):
'''
Defines a menu where items call local methods.
'''
def update(self):
pass
def process_input(self, character):
pass
| 3 | 1 | 21 | 1 | 19 | 3 | 9 | 0.26 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 8 | 52 | 3 | 43 | 13 | 40 | 11 | 43 | 13 | 40 | 14 | 2 | 5 | 17 |
147,568 |
LukeB42/Window
|
LukeB42_Window/window.py
|
window.Pane
|
class Pane(object):
"""
Subclassable data and logic for window panes.
Panes can not be placed inside one another.
The format for content is [text, alignment, attributes].
text can contain newlines and will be printed as-is, overflowing by default.
Multiple content elements can inhabit the same line and have different alignments.
The wrap attribute can be set to 1 to wrap on words or 2 to wrap by character.
Panes can be marked as floating, instructing Window to draw any EXPANDing panes around them.
"""
name = ''
window = None
active = None # Whether this pane is accepting user input
geometry = [] # x,y (desired width, height)
# Having a height of 1 makes your top and bottom coordinates identical.
coords = [] # [((top-left-from-top, top-left-from-left), (top-right-from-top, top-right-from-left)),
# ((bottom-left-from-top, bottom-left-from-left), (bottom-right-from-top, bottom-right-from-left))]
content = [] # [[text, align, attrs]] to render. Frames may hold multiple elements, displayed contiguously.
height = None # Updated every cycle to hold the actual height
width = None # Updated every cycle to hold the actual width
attr = None # Default attributes to draw the pane with
floating = None # Whether to float on top of adjacent EXPANDing panes
self_coordinating = None # Whether this pane defines its own coordinates
wrap = None # Flow offscreen by default
hidden = None # The default is to include panes in the draw() steps
def __init__(self, name):
"""
We define self.content here so it's unique across instances.
"""
self.name = name
self.content = []
def process_input(self, character):
"""
A subclassable method for dealing with input characters.
"""
func = None
try:
func = getattr(self, "handle_%s" % chr(character), None)
except:
pass
if func:
func()
def update(self):
"""
A subclassable method for updating content.
Called on active panes in every cycle of the event loop.
"""
pass
def __iadd__(self, data):
"""
This overrides the += assignment operator to make it possible to append
new text to a pane either by assuming the 0th element in self.content
or by using a tuple and specifying the index as the first element.
"""
if isinstance(data, (unicode, str)):
if len(self.content):
self.content[0][0] += data
else:
self.change_content(0, data, align=ALIGN_LEFT, attrs=1)
elif isinstance(data, (tuple, list)):
if len(data) < 2:
return self
if not isinstance(data[0], int):
return self
if len(self.content) < data[0]+1:
self.change_content(data[0], data[1], align=ALIGN_LEFT, attrs=1)
return self
self.content[data[0]][0] += data[1]
return self
def change_content(self, index, text, align=ALIGN_LEFT, attrs=1):
self.whoami = str(self)
if index > len(self.content) and len(self.content): return
if not self.content or index == len(self.content):
self.content.append([text, align, attrs])
else:
self.content[index] = [text, align, attrs]
def __repr__(self):
if self.name:
return "<Pane %s at %s>" % (self.name, hex(id(self)))
return "<Pane at %s>" % hex(id(self))
|
class Pane(object):
'''
Subclassable data and logic for window panes.
Panes can not be placed inside one another.
The format for content is [text, alignment, attributes].
text can contain newlines and will be printed as-is, overflowing by default.
Multiple content elements can inhabit the same line and have different alignments.
The wrap attribute can be set to 1 to wrap on words or 2 to wrap by character.
Panes can be marked as floating, instructing Window to draw any EXPANDing panes around them.
'''
def __init__(self, name):
'''
We define self.content here so it's unique across instances.
'''
pass
def process_input(self, character):
'''
A subclassable method for dealing with input characters.
'''
pass
def update(self):
'''
A subclassable method for updating content.
Called on active panes in every cycle of the event loop.
'''
pass
def __iadd__(self, data):
'''
This overrides the += assignment operator to make it possible to append
new text to a pane either by assuming the 0th element in self.content
or by using a tuple and specifying the index as the first element.
'''
pass
def change_content(self, index, text, align=ALIGN_LEFT, attrs=1):
pass
def __repr__(self):
pass
| 7 | 5 | 9 | 0 | 7 | 3 | 3 | 0.69 | 1 | 4 | 0 | 14 | 6 | 1 | 6 | 6 | 91 | 11 | 54 | 22 | 47 | 37 | 52 | 22 | 45 | 7 | 1 | 2 | 17 |
147,569 |
LukeB42/Window
|
LukeB42_Window/window.py
|
window.Pane
|
class Pane(object):
"""
Subclassable data and logic for window panes.
Panes can not be placed inside one another.
The format for content is [text, alignment, attributes].
text can contain newlines and will be printed as-is, overflowing by default.
Multiple content elements can inhabit the same line and have different alignments.
The wrap attribute can be set to 1 to wrap on words or 2 to wrap by character.
Panes can be marked as floating, instructing Window to draw any EXPANDing panes around them.
"""
name = ''
window = None
active = None # Whether this pane is accepting user input
geometry = [] # x,y (desired width, height)
# Having a height of 1 makes your top and bottom coordinates identical.
coords = [] # [((top-left-from-top, top-left-from-left), (top-right-from-top, top-right-from-left)),
# ((bottom-left-from-top, bottom-left-from-left), (bottom-right-from-top, bottom-right-from-left))]
content = [] # [[text, align, attrs]] to render. Frames may hold multiple elements, displayed contiguously.
height = None # Updated every cycle to hold the actual height
width = None # Updated every cycle to hold the actual width
attr = None # Default attributes to draw the pane with
floating = None # Whether to float on top of adjacent EXPANDing panes
self_coordinating = None # Whether this pane defines its own coordinates
wrap = None # Flow offscreen by default
hidden = None # The default is to include panes in the draw() steps
def __init__(self, name):
"""
We define self.content here so it's unique across instances.
"""
self.name = name
self.content = []
def process_input(self, character):
"""
A subclassable method for dealing with input characters.
"""
func = None
try:
func = getattr(self, "handle_%s" % chr(character), None)
except:
pass
if func:
func()
def update(self):
"""
A subclassable method for updating content.
Called on active panes in every cycle of the event loop.
"""
pass
def __iadd__(self, data):
"""
This overrides the += assignment operator to make it possible to append
new text to a pane either by assuming the 0th element in self.content
or by using a tuple and specifying the index as the first element.
"""
if isinstance(data, (unicode, str)):
if len(self.content):
self.content[0][0] += data
else:
self.change_content(0, data, align=ALIGN_LEFT, attrs=1)
elif isinstance(data, (tuple, list)):
if len(data) < 2:
return self
if not isinstance(data[0], int):
return self
if len(self.content) < data[0]+1:
self.change_content(data[0], data[1], align=ALIGN_LEFT, attrs=1)
return self
self.content[data[0]][0] += data[1]
return self
def change_content(self, index, text, align=ALIGN_LEFT, attrs=1):
self.whoami = str(self)
if index > len(self.content) and len(self.content): return
if not self.content or index == len(self.content):
self.content.append([text, align, attrs])
else:
self.content[index] = [text, align, attrs]
def __repr__(self):
if self.name:
return "<Pane %s at %s>" % (self.name, hex(id(self)))
return "<Pane at %s>" % hex(id(self))
|
class Pane(object):
'''
Subclassable data and logic for window panes.
Panes can not be placed inside one another.
The format for content is [text, alignment, attributes].
text can contain newlines and will be printed as-is, overflowing by default.
Multiple content elements can inhabit the same line and have different alignments.
The wrap attribute can be set to 1 to wrap on words or 2 to wrap by character.
Panes can be marked as floating, instructing Window to draw any EXPANDing panes around them.
'''
def __init__(self, name):
'''
We define self.content here so it's unique across instances.
'''
pass
def process_input(self, character):
'''
A subclassable method for dealing with input characters.
'''
pass
def update(self):
'''
A subclassable method for updating content.
Called on active panes in every cycle of the event loop.
'''
pass
def __iadd__(self, data):
'''
This overrides the += assignment operator to make it possible to append
new text to a pane either by assuming the 0th element in self.content
or by using a tuple and specifying the index as the first element.
'''
pass
def change_content(self, index, text, align=ALIGN_LEFT, attrs=1):
pass
def __repr__(self):
pass
| 7 | 5 | 9 | 0 | 7 | 3 | 3 | 0.69 | 1 | 4 | 0 | 3 | 6 | 1 | 6 | 6 | 91 | 11 | 54 | 22 | 47 | 37 | 52 | 22 | 45 | 7 | 1 | 2 | 17 |
147,570 |
LukeB42/Window
|
LukeB42_Window/examples/menu_test.py
|
menu_test.Menu
|
class Menu(Pane):
"""
Defines a menu where items call local methods.
"""
geometry = [EXPAND, EXPAND]
# Default and selection colours.
col = [-1, -1] # fg, bg, default.
sel = [-1, "blue"] # Selected
pin = [-1, "yellow"] # Pinned
sap = [-1, "green"] # Selected and pinned
items = [
[1, 'Hello','handle_hello'], # [selected, text, function]
[0, 'world','handle_world'],
[0, 'fight','handle_fight'],
[0, 'items','handle_items'],
[0, 'magic','handle_magic'],
[0, 'flee','handle_flee'],
]
def update(self):
for i, item in enumerate(self.items):
if item[0] == 3:
colours = palette(self.sap[0], self.sap[1])
elif item[0] == 2:
colours = palette(self.pin[0], self.pin[1])
elif item[0] == 1:
colours = palette(self.sel[0], self.sel[1])
else:
colours = palette(self.col[0], self.col[1])
if i == self.height:
text = ' ' * (self.width / 2)
text += 'V'
else:
text = ' ' + item[1]
spaces = ' ' * (self.width - len(text))
text += spaces
self.change_content(i, text + '\n', ALIGN_LEFT, colours)
def process_input(self, character):
# Return key to invoke.
if character == 10 or character == 13:
for i, item in enumerate(self.items):
if item[0]:
func = getattr(self, item[2].lower(), None)
if func:
func()
# Spacebar to pin.
elif character == 32:
for i, item in enumerate(self.items):
if item[0]:
if item[0] == 1:
self.items[i][0] = 3
elif item[0] == 3:
self.items[i][0] = 1
# Iterate if subsequent items are selected.
if any(filter(lambda x: x[0] in [1, 3], self.items[i:])):
continue
break
# Handle menu navigation.
elif character in [259, 258, 339, 338]:
for i, item in enumerate(self.items):
if item[0]:
if character == 259: # up arrow
if i == 0: break
# Deselect the current item.
if item[0] in [1, 3]:
item[0] -= 1
# Iterate if subsequent items are selected.
if any(filter(lambda x: x[0] in [1, 3], self.items[i:])):
continue
# Select the previous item if it's unselected.
if self.items[i-1][0] in [0, 2]:
self.items[i-1][0] += 1
break
if character == 258: # down arrow
if i+1 >= len(self.items): break
if item[0] in [1, 3]:
item[0] -= 1
if any(filter(lambda x: x[0] in [1, 3], self.items[i:])):
continue
if self.items[i+1][0] in [0, 2]:
self.items[i+1][0] += 1
break
if character == 339: # page up
if item[0] != 2:
item[0] = 0
if self.items[0][0] != 2:
self.items[0][0] = 1
break
if character == 338: # page down
if item[0] != 2:
item[0] = 0
if self.items[-1][0] != 2:
self.items[-1][0] = 1
break
|
class Menu(Pane):
'''
Defines a menu where items call local methods.
'''
def update(self):
pass
def process_input(self, character):
pass
| 3 | 1 | 44 | 7 | 34 | 6 | 18 | 0.24 | 1 | 2 | 0 | 0 | 2 | 0 | 2 | 8 | 108 | 15 | 82 | 15 | 79 | 20 | 70 | 15 | 67 | 30 | 2 | 5 | 36 |
147,571 |
LukeB42/Window
|
LukeB42_Window/window.py
|
window.Window
|
class Window(object):
"""
A window can have multiple panes responsible for different things.
This object filters input characters through the .process_input() method on all
panes marked as active.
The list of panes orders panes vertically from highest to lowest.
Elements in the list of panes can also be lists of panes ordered from left to right.
Set blocking to True to wait for input before redrawing the screen.
Set debug to True to draw any exception messages and to print character codes on the last line.
In non-blocking mode a default delay of 0.030 seconds (as the interpreter can clock them..) is
used so as not hog CPU time. Higher values can be used for implementing things like wall clocks.
"""
def __init__(self, blocking=True):
"""
Create a Window instance.
You may want to wait for user input if the connection is over SSH.
This can be done by checking for 'SSH_CONNECTION' in os.environ.
"""
self.blocking = blocking
self.running = None
self.blocking = None
self.debug = None
self.window = None
self.height = None
self.width = None
self.panes = []
self.pane_cache = []
self.exit_keys = []
self.friendly = True
self.delay = 0.030
def start(self):
"""
Window event loop
"""
self.window = _curses.initscr()
_curses.savetty()
_curses.start_color()
_curses.use_default_colors()
self.window.leaveok(1)
_curses.raw()
self.window.keypad(1)
_curses.noecho()
_curses.cbreak()
_curses.nonl()
_curses.curs_set(0)
if self.blocking:
self.window.nodelay(0)
else:
self.window.nodelay(1)
self.running = True
while self.running:
self.cycle()
if self.friendly and not self.blocking:
time.sleep(self.delay)
self.stop()
def cycle(self):
"""
Permits composition with asyncio/your own event loop.
while True:
sockets.poll()
update_with_network_data(window)
window.cycle()
"""
self.draw()
self.process_input()
def stop(self):
"""
Restore the TTY to its original state.
"""
_curses.nocbreak()
self.window.keypad(0)
_curses.echo()
_curses.resetty()
_curses.endwin()
self.running = False
def draw(self):
# Check for a resize
self.update_window_size()
# Compute the coordinates of all currently attached panes
self.calculate_pane_heights_and_widths()
self.coordinate()
# update all pane content
[pane.update() for pane in self if not pane.hidden]
# Draw panes within their areas based on pane.coords
# Draw pane frames, accounting for alignment, to window coordinates.
# If, for example, a pane is self-coordinating and its bottom right value
# is higher than its top right, then we can deduce that the square left with
# top-right as its lower-left is to be omitted from being drawn with this pane.
# Coordinates are of the form:
# [
# ((top-left-from-top, top-left-from-left),
# (top-right-from-top, top-right-from-left)),
# ((bottom-left-from-top, bottom-left-from-left),
# (bottom-right-from-top, bottom-right-from-left))
# ]
for pane in self:
if pane.hidden: continue
# Set y,x to top left of pane.coords
top_left_top = pane.coords[0][0][0]
top_left_left = pane.coords[0][0][1]
top_right_top = pane.coords[0][1][0]
top_right_left = pane.coords[0][1][1]
bottom_left_top = pane.coords[1][0][0]
bottom_left_left = pane.coords[1][0][1]
bottom_right_top = pane.coords[1][1][0]
bottom_right_left = pane.coords[1][1][1]
y = 0 # from top
x = 0 # from left
l = 0 # line length
# You will see some conversions to int within slices in the following section.
# This is to ensure Python 3 compatibility.
for frame in pane.content:
(text, align, attrs) = frame
for i, line in enumerate(text.split("\n")):
# Don't attempt to draw below the window
if (i+y) > (bottom_left_top - top_left_top): break
# if i+y > pane.height: break
# if i+y > bottom_left_top or i+y > bottom_right_top: break
l = len(line)
# Truncate non-wrapping panes
if not pane.wrap:
# self.truncate_to_fit(line, pane.coords)
# Honour inverted upper right corners
if top_right_top > top_left_top or top_right_left < bottom_right_left:
# if the current cursor is above or level with
# where the top-right corner inverts
if y >= top_right_top:
# and the bottom left inverts
if bottom_left_top < bottom_right_top and y >= bottom_left_top:
# then perform lower left to top right corner inversion
line = line[:int(top_right_left - bottom_left_left)]
else:
# otherwise our line length is from the top left to the top-right
line = line[:int(top_right_left - top_left_left)]
# Honour inverted lower right corners
if bottom_right_top < bottom_left_top or top_right_left > bottom_right_left:
# if the current cursor is below or level with
# where the lower-right corner inverts
if y >= bottom_right_top:
# and the top left inverts
if top_left_top > top_right_top and y >= top_left_top:
# then perform upper left to lower right inversion
line = line[:int(bottom_right_left - top_left_left)]
# otherwise our line length is from bottom left to bottom right
else:
line = line[:int(bottom_right_left - bottom_left_left)]
# Honour inverted upper left corners
if top_left_left > bottom_left_left or top_left_top > top_right_top:
# if the current cursor is above or level with
# where the top-left corner inverts
if y >= top_left_top:
# and the lower right inverts
if bottom_right_top < bottom_left_top and y >= bottom_right_top:
# perform upper left to lower right inversion
line = line[:bottom_right_left - top_left_left]
# otherwise we're just fitting to the coordinates
else:
line = line[:int(top_right_left - top_left_left)]
# Honour inverted lower left corners
if bottom_left_left > top_left_left:
# if the current cursor is below or level with
# where the lower left corner inverts
if y >= bottom_left_top:
# and the upper right inverts
if top_right_top > top_left_top and y <= top_right_top:
# perform lower left to top right inversion
line = line[:int(top_right_left - bottom_left_left)]
# otherwise we're just fitting to the coordinates
else:
line = line[:int(bottom_right_left - bottom_left_left)]
# All non-wrapping panes
if l > pane.width:
line = line[:pane.width]
if top_left_left+x+l > self.width:
line = line[:int(self.width - top_left_left)]
# Purposefully wrap panes by incrementing y and resetting x
# pane.wrap = 1 for wordwrapping
# pane.wrap = 2 for character wrapping
else:
# The important thing to remember is that the "first line"
# of a wrapping line is coming through this path
# TODO: Wrap text based on the coordinate system
if top_left_left+x+l > top_right_left - top_left_left:
hilight_attrs = attrs
if self.debug:
hilight_attrs = palette("black", "yellow")
else:
hilight_attrs = attrs
if pane.wrap == 1 or pane.wrap == True:
line = line.split()
for c,j in enumerate(line):
if y > bottom_left_top - top_left_top: break
# Place a space between words after the first if word-wrapping
if c and isinstance(line, list):
j = ' ' + j
# Move to the next line if the cursor + j would draw past the top right
if top_left_left+x+len(j) > top_right_left:
y += 1
x = 0
if len(j) > 1 and j[0] == ' ':
j = j[1:]
# Draw ... if j doesnt fit in the line
if len(j) > top_right_left - top_left_left+x:
if not c:
y -= 1
t = '...'[:(top_right_left - top_left_left+x)]
self.addstr(top_left_top+i+y, top_left_left+x, t, hilight_attrs)
continue
self.addstr(top_left_top+i+y, top_left_left+x, j, hilight_attrs)
x += len(j)
l = x # The length of the line is the
# current position on the horizontal.
# Process next line in current frame
# the value for i will increment, presuming there's a newline..
if self.debug:
self.addstr(self.height-8,0, str(i))
self.addstr(self.height-7,0, str(c))
self.addstr(self.height-6,0, str(x))
x = 0
continue
# TODO: Text alignment
# Account for an inverted top left corner
if top_left_top > top_right_top and y >= top_left_top:
self.addstr(top_left_top+i+y, bottom_left_left+x, line, attrs)
# Account for an inverted bottom left corner
elif bottom_left_top < bottom_right_top and y >= bottom_left_top:
self.addstr(top_left_top+i+y, bottom_left_left+x, line, attrs)
else:
self.addstr(top_left_top+i+y, top_left_left+x, line, attrs)
x=0
# leave cursor at the end of the last line after processing the line.
x = l
y += i
def process_input(self):
"""
Send input to panes marked as active after checking for
a request to redraw the screen (^L), a request to exit,
and optionally display character codes as they're received.
"""
try:
character = self.window.getch()
except Exception as e:
character = -1
if self.debug:
self.addstr(self.height-1, self.width - len(e.message) + 1, e.message)
# Check for any keys we've been told to exit on
if character in self.exit_keys:
self.stop()
# Force redraw the screen on ^L
if character == 12:
self.window.clear()
return
# Send input to active panes (hidden panes can still receive input)
if character != -1:
[pane.process_input(character) for pane in self if pane.active ]
# Print character codes to the bottom center if debugging.
if self.debug:
self.addstr(self.height-1, self.width/2, " "*4)
self.addstr(self.height-1, self.width/2 - len(str(character)) / 2, str(character))
def calculate_pane_heights_and_widths(self):
"""
Update pane heights and widths based on the current window and their desired geometry.
What to bear in mind:
Panes may have a fixed desired size.
Panes may be set to expand maximally on either axis.
Panes may be set to fit to the sum of their content buffers (accounting for alignment).
Panes may be set to float.
Two panes set to float and expand on the same axis will not overlap.
EXPANDing panes may be adjacent to non-floating self-coordinating panes...
Two panes wanting a height of ten each on a five line window will overflow offscreen.
Using FIT for an axis on an undersized Window will also overflow offscreen.
"""
# Do a pass for heights
# Every pane must be represented in order to map properly later
growing_panes = []
claimed_columns = 0
for v_index, element in enumerate(self.panes):
# Get maximal height from panes in sublists
if type(element) == list:
expanding_in_sublist = [] # A list we'll append to growing_panes
claimed_from_sublist = [] # The heights gleaned from this pass
for h_index, pane in enumerate(element):
if pane.hidden: continue
# Let height be max L/R distance from top if self-coordinating
if pane.coords and pane.self_coordinating:
pane.height = max([pane.coords[1][0][0],pane.coords[1][1][0]])
claimed_from_sublist.append(pane.height)
continue
if len(pane.geometry) < 2:
pane.height = 0
continue
desired_height = pane.geometry[1]
if isinstance(desired_height, int):
pane.height = desired_height
claimed_from_sublist.append(pane.height)
continue
elif isinstance(desired_height, str):
# Calculate the width of panes set to FIT
if desired_height == FIT:
buffer = ""
for frame in pane.content:
buffer += frame[0]
pane.height = len(buffer.split('\n'))
claimed_from_sublist.append(pane.height)
continue
elif desired_height == EXPAND:
expanding_in_sublist.append(pane)
continue
pane.height = desired_height
# Append any expanding panes to growing_panes as a list
if expanding_in_sublist:
growing_panes.append(expanding_in_sublist)
# The total claimed columns for this sublist:
if claimed_from_sublist:
claimed_columns += max(claimed_from_sublist)
else:
if element.hidden: continue
if element.coords and element.self_coordinating:
element.height = max([element.coords[1][0][0], element.coords[1][1][0]])
claimed_columns += element.height
continue
if len(element.geometry) < 2:
element.height = 0
continue
desired_height = element.geometry[1]
if isinstance(desired_height, int):
element.height = desired_height
claimed_columns += element.height
continue
elif isinstance(desired_height, str):
# Calculate the width of panes set to FIT
if desired_height == FIT:
buffer = ""
for frame in element.content:
buffer += frame[0]
element.height = len(buffer.split('\n'))
claimed_columns += element.height
continue
elif desired_height == EXPAND:
growing_panes.append(element)
continue
# Calculate how many rows are left by panes with fixed heights
if growing_panes:
g = len(growing_panes)
remaining_space = self.height - claimed_columns
typical_expanse = remaining_space / g
tracking = 0
rmg = remaining_space % g
# Calculate adjustments if the height isn't evenly shared
for i, pane in enumerate(growing_panes):
if isinstance(pane, list):
for k,p in enumerate(pane):
p.height = typical_expanse
if not i:
# Account for claimed space
for x in range(len(growing_panes)):
if rmg == x:
p.height -= len(growing_panes) - (x+1)
# Adjust for an extra column that can't be evenly shared
if self.height % 2:
if not claimed_columns:
p.height += 1
else:
p.height -= claimed_columns
else:
p.height -= claimed_columns
if not k:
tracking += p.height
else:
pane.height = typical_expanse
if not i:
for x in range(len(growing_panes)):
if rmg == x:
pane.height -= len(growing_panes) - (x+1)
if self.height % 2:
if not claimed_columns:
pane.height += 1
else:
pane.height -= claimed_columns
else:
pane.height -= claimed_columns
tracking += pane.height
#s = "Growing rows: %i, %s number of rows: %s, claimed: %i, remaining: %i, remaining/growing: %i,rmodg: %i" % \
# (g, "odd" if self.height % 2 else "even", self.height, claimed_columns,remaining_space, typical_expanse, remaining_space%g)
# self.addstr(self.height-1, self.width-len(s),s)
# Then a pass for widths.
for v_index, element in enumerate(self.panes):
claimed_rows = 0
growing_panes = []
# Get panes who will be sharing the x axis
if type(element) == list:
for h_index, pane in enumerate(element):
if pane.hidden: continue
# Calculate the widest part of a self-coordinating pane
if pane.coords and pane.self_coordinating:
rightmost = [pane.coords[0][1][1],pane.coords[1][1][1]]
pane.width = max(rightmost)
continue
if not pane.geometry:
pane.width = 0
continue
desired_width = pane.geometry[0]
if isinstance(desired_width, int):
claimed_rows += desired_width
pane.width = desired_width
continue
elif isinstance(desired_width, str):
# Calculate the width of panes set to FIT
if desired_width == FIT:
buffer = ""
for frame in pane.content:
buffer += frame[0]
pane.width = max(map(len, buffer.split('\n')))
claimed_rows += pane.width
continue
elif desired_width == EXPAND:
growing_panes.append(pane)
continue
else:
if element.hidden: continue
if not element.geometry:
element.width = 0
continue
desired_geometry = element.geometry[0]
if element.coords and element.self_coordinating:
rightmost = [element.coords[0][1][1],element.coords[1][1][1]]
element.width = max(rightmost)
continue
if isinstance(desired_geometry, int):
element.width = desired_geometry
continue
if isinstance(desired_geometry, str):
if desired_geometry == FIT:
buffer = ""
for frame in element.content:
buffer += frame[0]
element.width = max(map(len, buffer.split('\n')))
elif desired_geometry == EXPAND:
element.width = self.width
# Calculate the space to be shared between panes set to EXPAND
remaining_space = self.width - claimed_rows
for pane in growing_panes:
pane.width = remaining_space / len(growing_panes)
# Grant the rightmost panes an extra row if self.width is uneven:
if self.width % 2:
for pane in self.panes:
if isinstance(pane, list):
for i, p in enumerate(reversed(pane)):
if i == 0 and not p.self_coordinating and p.geometry \
and p.geometry[0] == EXPAND and not p.hidden:
p.width += 1
else:
if not pane.self_coordinating and pane.geometry \
and pane.geometry[0] == EXPAND and not pane.hidden:
pane.width += 1
continue
if self.debug:
self.addstr(self.height-5, 0, "Window height: " + str(self.height))
self.addstr(self.height-4, 0, "Window width: " + str(self.width))
self.addstr(self.height-2, 0, "Heights: " + str([p.height for p in self]))
self.addstr(self.height-1, 0, "Widths: " + str([p.width for p in self]))
def coordinate(self, panes=[], index=0):
"""
Update pane coordinate tuples based on their height and width relative to other panes
within the dimensions of the current window.
We account for panes with a height of 1 where the bottom coordinates are the same as the top.
Account for floating panes and self-coordinating panes adjacent to panes set to EXPAND.
Coordinates are of the form:
[
((top-left-from-top, top-left-from-left),
(top-right-from-top, top-right-from-left)),
((bottom-left-from-top, bottom-left-from-left),
(bottom-right-from-top, bottom-right-from-left))
]
We can then use these to determine things such as whether corners are inverted and how
many characters may be drawn
"""
y = 0 # height
for i, element in enumerate(self.panes):
x = 0 # width
if isinstance(element, list):
current_height = 0
for j, pane in enumerate(element):
if pane.hidden: continue
current_width = pane.width
current_height = pane.height
upper = ((y, x), (y, x+current_width))
lower = ((y+(current_height if current_height > 1 else 0), x),
(y+(current_height if current_height > 1 else 0), x+current_width))
pane.coords = [upper, lower]
x += current_width
y += (current_height+1 if current_height > 1 else 1)
else:
if element.hidden: continue
current_width = element.width
current_height = element.height
upper = ((y, x), (y, x+current_width))
lower = ((y+(current_height if current_height > 1 else 0), x),
(y+(current_height if current_height > 1 else 0), x+current_width))
element.coords = [upper, lower]
y += (current_height+1 if current_height > 1 else 1)
if self.debug:
coordinates = "Coordinates: " + str([p.coords for p in self])
if len(coordinates) > self.width:
coordinates = coordinates[:self.width - 3]
coordinates += '...'
self.addstr(self.height-3, 0, coordinates)
def addstr(self, h, w, text, attrs=0):
"""
A safe addstr wrapper
"""
self.update_window_size()
if h > self.height or w > self.width:
return
try:
# Python curses addstr doesn't deal with non-ascii characters
#self.window.addstr(h, w, text.encode("ascii", "ignore"), attrs)
self.window.addstr(h, w, text, attrs)
except Exception as e:
pass
def update_window_size(self):
"""
Update the current window object with its current
height and width and clear the screen if they've changed.
"""
height, width = self.window.getmaxyx()
if self.height != height or self.width != width:
self.height, self.width = height, width
self.window.clear()
def add(self, pane):
"""
Adds new panes to the window
"""
if isinstance(pane, list):
initialised_panes = []
for p in pane:
initialised_panes.append(self.init_pane(p))
self.panes.append(initialised_panes)
else:
pane = self.init_pane(pane)
self.panes.append(pane)
def init_pane(self, pane):
if not pane.name:
raise PaneError("Unnamed pane. How're you gonna move this thing around?")
pane.active = True
pane.window = self
for existing_pane in self:
if existing_pane.name == pane.name:
raise WindowError("A pane is already attached with the name %s" % pane.name)
return pane
def block(self):
self.window.blocking = True
self.window.window.nodelay(0)
def unblock(self):
self.window.blocking = False
self.window.window.nodelay(1)
def get(self, name, default=None, cache=False):
"""
Get a pane by name, possibly from the cache. Return None if not found.
"""
if cache == True:
for pane in self.cache:
if pane.name == name:
return pane
return default
for pane in self:
if pane.name == name:
return pane
return default
def __setitem__(self, name, new_pane):
for i, pane in enumerate(self):
if not isinstance(pane, list):
if pane.name == name:
self.panes[i] = new_pane
else:
for x, horiz_pane in enumerate(pane):
if horiz_pane.name == name:
self.panes[i][x] = new_pane
raise KeyError("Unknown pane %s" % name)
def __getitem__(self, name):
for pane in self:
if pane.name == name:
return name
raise KeyError("Unknown pane %s" % name)
def __len__(self):
return len([p for p in self])
def __iter__(self):
"""
Iterate over self.panes by automatically flattening lists.
"""
panes = []
for pane in self.panes:
if type(pane) == list:
panes.extend(pane)
else:
panes.append(pane)
return iter(panes)
|
class Window(object):
'''
A window can have multiple panes responsible for different things.
This object filters input characters through the .process_input() method on all
panes marked as active.
The list of panes orders panes vertically from highest to lowest.
Elements in the list of panes can also be lists of panes ordered from left to right.
Set blocking to True to wait for input before redrawing the screen.
Set debug to True to draw any exception messages and to print character codes on the last line.
In non-blocking mode a default delay of 0.030 seconds (as the interpreter can clock them..) is
used so as not hog CPU time. Higher values can be used for implementing things like wall clocks.
'''
def __init__(self, blocking=True):
'''
Create a Window instance.
You may want to wait for user input if the connection is over SSH.
This can be done by checking for 'SSH_CONNECTION' in os.environ.
'''
pass
def start(self):
'''
Window event loop
'''
pass
def cycle(self):
'''
Permits composition with asyncio/your own event loop.
while True:
sockets.poll()
update_with_network_data(window)
window.cycle()
'''
pass
def stop(self):
'''
Restore the TTY to its original state.
'''
pass
def draw(self):
pass
def process_input(self):
'''
Send input to panes marked as active after checking for
a request to redraw the screen (^L), a request to exit,
and optionally display character codes as they're received.
'''
pass
def calculate_pane_heights_and_widths(self):
'''
Update pane heights and widths based on the current window and their desired geometry.
What to bear in mind:
Panes may have a fixed desired size.
Panes may be set to expand maximally on either axis.
Panes may be set to fit to the sum of their content buffers (accounting for alignment).
Panes may be set to float.
Two panes set to float and expand on the same axis will not overlap.
EXPANDing panes may be adjacent to non-floating self-coordinating panes...
Two panes wanting a height of ten each on a five line window will overflow offscreen.
Using FIT for an axis on an undersized Window will also overflow offscreen.
'''
pass
def coordinate(self, panes=[], index=0):
'''
Update pane coordinate tuples based on their height and width relative to other panes
within the dimensions of the current window.
We account for panes with a height of 1 where the bottom coordinates are the same as the top.
Account for floating panes and self-coordinating panes adjacent to panes set to EXPAND.
Coordinates are of the form:
[
((top-left-from-top, top-left-from-left),
(top-right-from-top, top-right-from-left)),
((bottom-left-from-top, bottom-left-from-left),
(bottom-right-from-top, bottom-right-from-left))
]
We can then use these to determine things such as whether corners are inverted and how
many characters may be drawn
'''
pass
def addstr(self, h, w, text, attrs=0):
'''
A safe addstr wrapper
'''
pass
def update_window_size(self):
'''
Update the current window object with its current
height and width and clear the screen if they've changed.
'''
pass
def addstr(self, h, w, text, attrs=0):
'''
Adds new panes to the window
'''
pass
def init_pane(self, pane):
pass
def block(self):
pass
def unblock(self):
pass
def get(self, name, default=None, cache=False):
'''
Get a pane by name, possibly from the cache. Return None if not found.
'''
pass
def __setitem__(self, name, new_pane):
pass
def __getitem__(self, name):
pass
def __len__(self):
pass
def __iter__(self):
'''
Iterate over self.panes by automatically flattening lists.
'''
pass
| 20 | 13 | 35 | 4 | 23 | 9 | 8 | 0.41 | 1 | 12 | 2 | 0 | 19 | 11 | 19 | 19 | 690 | 93 | 429 | 91 | 409 | 176 | 406 | 89 | 386 | 64 | 1 | 9 | 159 |
147,572 |
LukeB42/Window
|
LukeB42_Window/window.py
|
window.Window
|
class Window(object):
"""
A window can have multiple panes responsible for different things.
This object filters input characters through the .process_input() method on all
panes marked as active.
The list of panes orders panes vertically from highest to lowest.
Elements in the list of panes can also be lists of panes ordered from left to right.
Set blocking to True to wait for input before redrawing the screen.
Set debug to True to draw any exception messages and to print character codes on the last line.
In non-blocking mode a default delay of 0.030 seconds (as the interpreter can clock them..) is
used so as not hog CPU time. Higher values can be used for implementing things like wall clocks.
"""
def __init__(self, blocking=True):
"""
Create a Window instance.
You may want to wait for user input if the connection is over SSH.
This can be done by checking for 'SSH_CONNECTION' in os.environ.
"""
self.blocking = blocking
self.running = None
self.blocking = None
self.debug = None
self.window = None
self.height = None
self.width = None
self.panes = []
self.pane_cache = []
self.exit_keys = []
self.friendly = True
self.delay = 0.030
def start(self):
"""
Window event loop
"""
self.window = _curses.initscr()
_curses.savetty()
_curses.start_color()
_curses.use_default_colors()
self.window.leaveok(1)
_curses.raw()
self.window.keypad(1)
_curses.noecho()
_curses.cbreak()
_curses.nonl()
_curses.curs_set(0)
if self.blocking:
self.window.nodelay(0)
else:
self.window.nodelay(1)
self.running = True
while self.running:
self.cycle()
if self.friendly and not self.blocking:
time.sleep(self.delay)
self.stop()
def cycle(self):
"""
Permits composition with asyncio/your own event loop.
while True:
sockets.poll()
update_with_network_data(window)
window.cycle()
"""
self.draw()
self.process_input()
def stop(self):
"""
Restore the TTY to its original state.
"""
_curses.nocbreak()
self.window.keypad(0)
_curses.echo()
_curses.resetty()
_curses.endwin()
self.running = False
def draw(self):
# Check for a resize
self.update_window_size()
# Compute the coordinates of all currently attached panes
self.calculate_pane_heights_and_widths()
self.coordinate()
# update all pane content
[pane.update() for pane in self if not pane.hidden]
# Draw panes within their areas based on pane.coords
# Draw pane frames, accounting for alignment, to window coordinates.
# If, for example, a pane is self-coordinating and its bottom right value
# is higher than its top right, then we can deduce that the square left with
# top-right as its lower-left is to be omitted from being drawn with this pane.
# Coordinates are of the form:
# [
# ((top-left-from-top, top-left-from-left),
# (top-right-from-top, top-right-from-left)),
# ((bottom-left-from-top, bottom-left-from-left),
# (bottom-right-from-top, bottom-right-from-left))
# ]
for pane in self:
if pane.hidden: continue
# Set y,x to top left of pane.coords
top_left_top = pane.coords[0][0][0]
top_left_left = pane.coords[0][0][1]
top_right_top = pane.coords[0][1][0]
top_right_left = pane.coords[0][1][1]
bottom_left_top = pane.coords[1][0][0]
bottom_left_left = pane.coords[1][0][1]
bottom_right_top = pane.coords[1][1][0]
bottom_right_left = pane.coords[1][1][1]
y = 0 # from top
x = 0 # from left
l = 0 # line length
# You will see some conversions to int within slices in the following section.
# This is to ensure Python 3 compatibility.
for frame in pane.content:
(text, align, attrs) = frame
for i, line in enumerate(text.split("\n")):
# Don't attempt to draw below the window
if (i+y) > (bottom_left_top - top_left_top): break
# if i+y > pane.height: break
# if i+y > bottom_left_top or i+y > bottom_right_top: break
l = len(line)
# Truncate non-wrapping panes
if not pane.wrap:
# self.truncate_to_fit(line, pane.coords)
# Honour inverted upper right corners
if top_right_top > top_left_top or top_right_left < bottom_right_left:
# if the current cursor is above or level with
# where the top-right corner inverts
if y >= top_right_top:
# and the bottom left inverts
if bottom_left_top < bottom_right_top and y >= bottom_left_top:
# then perform lower left to top right corner inversion
line = line[:int(top_right_left - bottom_left_left)]
else:
# otherwise our line length is from the top left to the top-right
line = line[:int(top_right_left - top_left_left)]
# Honour inverted lower right corners
if bottom_right_top < bottom_left_top or top_right_left > bottom_right_left:
# if the current cursor is below or level with
# where the lower-right corner inverts
if y >= bottom_right_top:
# and the top left inverts
if top_left_top > top_right_top and y >= top_left_top:
# then perform upper left to lower right inversion
line = line[:int(bottom_right_left - top_left_left)]
# otherwise our line length is from bottom left to bottom right
else:
line = line[:int(bottom_right_left - bottom_left_left)]
# Honour inverted upper left corners
if top_left_left > bottom_left_left or top_left_top > top_right_top:
# if the current cursor is above or level with
# where the top-left corner inverts
if y >= top_left_top:
# and the lower right inverts
if bottom_right_top < bottom_left_top and y >= bottom_right_top:
# perform upper left to lower right inversion
line = line[:bottom_right_left - top_left_left]
# otherwise we're just fitting to the coordinates
else:
line = line[:int(top_right_left - top_left_left)]
# Honour inverted lower left corners
if bottom_left_left > top_left_left:
# if the current cursor is below or level with
# where the lower left corner inverts
if y >= bottom_left_top:
# and the upper right inverts
if top_right_top > top_left_top and y <= top_right_top:
# perform lower left to top right inversion
line = line[:int(top_right_left - bottom_left_left)]
# otherwise we're just fitting to the coordinates
else:
line = line[:int(bottom_right_left - bottom_left_left)]
# All non-wrapping panes
if l > pane.width:
line = line[:pane.width]
if top_left_left+x+l > self.width:
line = line[:int(self.width - top_left_left)]
# Purposefully wrap panes by incrementing y and resetting x
# pane.wrap = 1 for wordwrapping
# pane.wrap = 2 for character wrapping
else:
# The important thing to remember is that the "first line"
# of a wrapping line is coming through this path
# TODO: Wrap text based on the coordinate system
if top_left_left+x+l > top_right_left - top_left_left:
hilight_attrs = attrs
if self.debug:
hilight_attrs = palette("black", "yellow")
else:
hilight_attrs = attrs
if pane.wrap == 1 or pane.wrap == True:
line = line.split()
for c,j in enumerate(line):
if y > bottom_left_top - top_left_top: break
# Place a space between words after the first if word-wrapping
if c and isinstance(line, list):
j = ' ' + j
# Move to the next line if the cursor + j would draw past the top right
if top_left_left+x+len(j) > top_right_left:
y += 1
x = 0
if len(j) > 1 and j[0] == ' ':
j = j[1:]
# Draw ... if j doesnt fit in the line
if len(j) > top_right_left - top_left_left+x:
if not c:
y -= 1
t = '...'[:(top_right_left - top_left_left+x)]
self.addstr(top_left_top+i+y, top_left_left+x, t, hilight_attrs)
continue
self.addstr(top_left_top+i+y, top_left_left+x, j, hilight_attrs)
x += len(j)
l = x # The length of the line is the
# current position on the horizontal.
# Process next line in current frame
# the value for i will increment, presuming there's a newline..
if self.debug:
self.addstr(self.height-8,0, str(i))
self.addstr(self.height-7,0, str(c))
self.addstr(self.height-6,0, str(x))
x = 0
continue
# TODO: Text alignment
# Account for an inverted top left corner
if top_left_top > top_right_top and y >= top_left_top:
self.addstr(top_left_top+i+y, bottom_left_left+x, line, attrs)
# Account for an inverted bottom left corner
elif bottom_left_top < bottom_right_top and y >= bottom_left_top:
self.addstr(top_left_top+i+y, bottom_left_left+x, line, attrs)
else:
self.addstr(top_left_top+i+y, top_left_left+x, line, attrs)
x=0
# leave cursor at the end of the last line after processing the line.
x = l
y += i
def process_input(self):
"""
Send input to panes marked as active after checking for
a request to redraw the screen (^L), a request to exit,
and optionally display character codes as they're received.
"""
try:
character = self.window.getch()
except Exception as e:
character = -1
if self.debug:
self.addstr(self.height-1, self.width - len(e.message) + 1, e.message)
# Check for any keys we've been told to exit on
if character in self.exit_keys:
self.stop()
# Force redraw the screen on ^L
if character == 12:
self.window.clear()
return
# Send input to active panes (hidden panes can still receive input)
if character != -1:
[pane.process_input(character) for pane in self if pane.active ]
# Print character codes to the bottom center if debugging.
if self.debug:
self.addstr(self.height-1, self.width/2, " "*4)
self.addstr(self.height-1, self.width/2 - len(str(character)) / 2, str(character))
def calculate_pane_heights_and_widths(self):
"""
Update pane heights and widths based on the current window and their desired geometry.
What to bear in mind:
Panes may have a fixed desired size.
Panes may be set to expand maximally on either axis.
Panes may be set to fit to the sum of their content buffers (accounting for alignment).
Panes may be set to float.
Two panes set to float and expand on the same axis will not overlap.
EXPANDing panes may be adjacent to non-floating self-coordinating panes...
Two panes wanting a height of ten each on a five line window will overflow offscreen.
Using FIT for an axis on an undersized Window will also overflow offscreen.
"""
# Do a pass for heights
# Every pane must be represented in order to map properly later
growing_panes = []
claimed_columns = 0
for v_index, element in enumerate(self.panes):
# Get maximal height from panes in sublists
if type(element) == list:
expanding_in_sublist = [] # A list we'll append to growing_panes
claimed_from_sublist = [] # The heights gleaned from this pass
for h_index, pane in enumerate(element):
if pane.hidden: continue
# Let height be max L/R distance from top if self-coordinating
if pane.coords and pane.self_coordinating:
pane.height = max([pane.coords[1][0][0],pane.coords[1][1][0]])
claimed_from_sublist.append(pane.height)
continue
if len(pane.geometry) < 2:
pane.height = 0
continue
desired_height = pane.geometry[1]
if isinstance(desired_height, int):
pane.height = desired_height
claimed_from_sublist.append(pane.height)
continue
elif isinstance(desired_height, str):
# Calculate the width of panes set to FIT
if desired_height == FIT:
buffer = ""
for frame in pane.content:
buffer += frame[0]
pane.height = len(buffer.split('\n'))
claimed_from_sublist.append(pane.height)
continue
elif desired_height == EXPAND:
expanding_in_sublist.append(pane)
continue
pane.height = desired_height
# Append any expanding panes to growing_panes as a list
if expanding_in_sublist:
growing_panes.append(expanding_in_sublist)
# The total claimed columns for this sublist:
if claimed_from_sublist:
claimed_columns += max(claimed_from_sublist)
else:
if element.hidden: continue
if element.coords and element.self_coordinating:
element.height = max([element.coords[1][0][0], element.coords[1][1][0]])
claimed_columns += element.height
continue
if len(element.geometry) < 2:
element.height = 0
continue
desired_height = element.geometry[1]
if isinstance(desired_height, int):
element.height = desired_height
claimed_columns += element.height
continue
elif isinstance(desired_height, str):
# Calculate the width of panes set to FIT
if desired_height == FIT:
buffer = ""
for frame in element.content:
buffer += frame[0]
element.height = len(buffer.split('\n'))
claimed_columns += element.height
continue
elif desired_height == EXPAND:
growing_panes.append(element)
continue
# Calculate how many rows are left by panes with fixed heights
if growing_panes:
g = len(growing_panes)
remaining_space = self.height - claimed_columns
typical_expanse = remaining_space / g
tracking = 0
rmg = remaining_space % g
# Calculate adjustments if the height isn't evenly shared
for i, pane in enumerate(growing_panes):
if isinstance(pane, list):
for k,p in enumerate(pane):
p.height = typical_expanse
if not i:
# Account for claimed space
for x in range(len(growing_panes)):
if rmg == x:
p.height -= len(growing_panes) - (x+1)
# Adjust for an extra column that can't be evenly shared
if self.height % 2:
if not claimed_columns:
p.height += 1
else:
p.height -= claimed_columns
else:
p.height -= claimed_columns
if not k:
tracking += p.height
else:
pane.height = typical_expanse
if not i:
for x in range(len(growing_panes)):
if rmg == x:
pane.height -= len(growing_panes) - (x+1)
if self.height % 2:
if not claimed_columns:
pane.height += 1
else:
pane.height -= claimed_columns
else:
pane.height -= claimed_columns
tracking += pane.height
#s = "Growing rows: %i, %s number of rows: %s, claimed: %i, remaining: %i, remaining/growing: %i,rmodg: %i" % \
# (g, "odd" if self.height % 2 else "even", self.height, claimed_columns,remaining_space, typical_expanse, remaining_space%g)
# self.addstr(self.height-1, self.width-len(s),s)
# Then a pass for widths.
for v_index, element in enumerate(self.panes):
claimed_rows = 0
growing_panes = []
# Get panes who will be sharing the x axis
if type(element) == list:
for h_index, pane in enumerate(element):
if pane.hidden: continue
# Calculate the widest part of a self-coordinating pane
if pane.coords and pane.self_coordinating:
rightmost = [pane.coords[0][1][1],pane.coords[1][1][1]]
pane.width = max(rightmost)
continue
if not pane.geometry:
pane.width = 0
continue
desired_width = pane.geometry[0]
if isinstance(desired_width, int):
claimed_rows += desired_width
pane.width = desired_width
continue
elif isinstance(desired_width, str):
# Calculate the width of panes set to FIT
if desired_width == FIT:
buffer = ""
for frame in pane.content:
buffer += frame[0]
pane.width = max(map(len, buffer.split('\n')))
claimed_rows += pane.width
continue
elif desired_width == EXPAND:
growing_panes.append(pane)
continue
else:
if element.hidden: continue
if not element.geometry:
element.width = 0
continue
desired_geometry = element.geometry[0]
if element.coords and element.self_coordinating:
rightmost = [element.coords[0][1][1],element.coords[1][1][1]]
element.width = max(rightmost)
continue
if isinstance(desired_geometry, int):
element.width = desired_geometry
continue
if isinstance(desired_geometry, str):
if desired_geometry == FIT:
buffer = ""
for frame in element.content:
buffer += frame[0]
element.width = max(map(len, buffer.split('\n')))
elif desired_geometry == EXPAND:
element.width = self.width
# Calculate the space to be shared between panes set to EXPAND
remaining_space = self.width - claimed_rows
for pane in growing_panes:
pane.width = remaining_space / len(growing_panes)
# Grant the rightmost panes an extra row if self.width is uneven:
if self.width % 2:
for pane in self.panes:
if isinstance(pane, list):
for i, p in enumerate(reversed(pane)):
if i == 0 and not p.self_coordinating and p.geometry \
and p.geometry[0] == EXPAND and not p.hidden:
p.width += 1
else:
if not pane.self_coordinating and pane.geometry \
and pane.geometry[0] == EXPAND and not pane.hidden:
pane.width += 1
continue
if self.debug:
self.addstr(self.height-5, 0, "Window height: " + str(self.height))
self.addstr(self.height-4, 0, "Window width: " + str(self.width))
self.addstr(self.height-2, 0, "Heights: " + str([p.height for p in self]))
self.addstr(self.height-1, 0, "Widths: " + str([p.width for p in self]))
def coordinate(self, panes=[], index=0):
"""
Update pane coordinate tuples based on their height and width relative to other panes
within the dimensions of the current window.
We account for panes with a height of 1 where the bottom coordinates are the same as the top.
Account for floating panes and self-coordinating panes adjacent to panes set to EXPAND.
Coordinates are of the form:
[
((top-left-from-top, top-left-from-left),
(top-right-from-top, top-right-from-left)),
((bottom-left-from-top, bottom-left-from-left),
(bottom-right-from-top, bottom-right-from-left))
]
We can then use these to determine things such as whether corners are inverted and how
many characters may be drawn
"""
y = 0 # height
for i, element in enumerate(self.panes):
x = 0 # width
if isinstance(element, list):
current_height = 0
for j, pane in enumerate(element):
if pane.hidden: continue
current_width = pane.width
current_height = pane.height
upper = ((y, x), (y, x+current_width))
lower = ((y+(current_height if current_height > 1 else 0), x),
(y+(current_height if current_height > 1 else 0), x+current_width))
pane.coords = [upper, lower]
x += current_width
y += (current_height+1 if current_height > 1 else 1)
else:
if element.hidden: continue
current_width = element.width
current_height = element.height
upper = ((y, x), (y, x+current_width))
lower = ((y+(current_height if current_height > 1 else 0), x),
(y+(current_height if current_height > 1 else 0), x+current_width))
element.coords = [upper, lower]
y += (current_height+1 if current_height > 1 else 1)
if self.debug:
coordinates = "Coordinates: " + str([p.coords for p in self])
if len(coordinates) > self.width:
coordinates = coordinates[:self.width - 3]
coordinates += '...'
self.addstr(self.height-3, 0, coordinates)
def addstr(self, h, w, text, attrs=0):
"""
A safe addstr wrapper
"""
self.update_window_size()
if h > self.height or w > self.width:
return
try:
# Python curses addstr doesn't deal with non-ascii characters
#self.window.addstr(h, w, text.encode("ascii", "ignore"), attrs)
self.window.addstr(h, w, text, attrs)
except Exception as e:
pass
def update_window_size(self):
"""
Update the current window object with its current
height and width and clear the screen if they've changed.
"""
height, width = self.window.getmaxyx()
if self.height != height or self.width != width:
self.height, self.width = height, width
self.window.clear()
def add(self, pane):
"""
Adds new panes to the window
"""
if isinstance(pane, list):
initialised_panes = []
for p in pane:
initialised_panes.append(self.init_pane(p))
self.panes.append(initialised_panes)
else:
pane = self.init_pane(pane)
self.panes.append(pane)
def init_pane(self, pane):
if not pane.name:
raise PaneError("Unnamed pane. How're you gonna move this thing around?")
pane.active = True
pane.window = self
for existing_pane in self:
if existing_pane.name == pane.name:
raise WindowError("A pane is already attached with the name %s" % pane.name)
return pane
def block(self):
self.window.blocking = True
self.window.window.nodelay(0)
def unblock(self):
self.window.blocking = False
self.window.window.nodelay(1)
def get(self, name, default=None, cache=False):
"""
Get a pane by name, possibly from the cache. Return None if not found.
"""
if cache == True:
for pane in self.cache:
if pane.name == name:
return pane
return default
for pane in self:
if pane.name == name:
return pane
return default
def __setitem__(self, name, new_pane):
for i, pane in enumerate(self):
if not isinstance(pane, list):
if pane.name == name:
self.panes[i] = new_pane
else:
for x, horiz_pane in enumerate(pane):
if horiz_pane.name == name:
self.panes[i][x] = new_pane
raise KeyError("Unknown pane %s" % name)
def __getitem__(self, name):
for pane in self:
if pane.name == name:
return name
raise KeyError("Unknown pane %s" % name)
def __len__(self):
return len([p for p in self])
def __iter__(self):
"""
Iterate over self.panes by automatically flattening lists.
"""
panes = []
for pane in self.panes:
if type(pane) == list:
panes.extend(pane)
else:
panes.append(pane)
return iter(panes)
|
class Window(object):
'''
A window can have multiple panes responsible for different things.
This object filters input characters through the .process_input() method on all
panes marked as active.
The list of panes orders panes vertically from highest to lowest.
Elements in the list of panes can also be lists of panes ordered from left to right.
Set blocking to True to wait for input before redrawing the screen.
Set debug to True to draw any exception messages and to print character codes on the last line.
In non-blocking mode a default delay of 0.030 seconds (as the interpreter can clock them..) is
used so as not hog CPU time. Higher values can be used for implementing things like wall clocks.
'''
def __init__(self, blocking=True):
'''
Create a Window instance.
You may want to wait for user input if the connection is over SSH.
This can be done by checking for 'SSH_CONNECTION' in os.environ.
'''
pass
def start(self):
'''
Window event loop
'''
pass
def cycle(self):
'''
Permits composition with asyncio/your own event loop.
while True:
sockets.poll()
update_with_network_data(window)
window.cycle()
'''
pass
def stop(self):
'''
Restore the TTY to its original state.
'''
pass
def draw(self):
pass
def process_input(self):
'''
Send input to panes marked as active after checking for
a request to redraw the screen (^L), a request to exit,
and optionally display character codes as they're received.
'''
pass
def calculate_pane_heights_and_widths(self):
'''
Update pane heights and widths based on the current window and their desired geometry.
What to bear in mind:
Panes may have a fixed desired size.
Panes may be set to expand maximally on either axis.
Panes may be set to fit to the sum of their content buffers (accounting for alignment).
Panes may be set to float.
Two panes set to float and expand on the same axis will not overlap.
EXPANDing panes may be adjacent to non-floating self-coordinating panes...
Two panes wanting a height of ten each on a five line window will overflow offscreen.
Using FIT for an axis on an undersized Window will also overflow offscreen.
'''
pass
def coordinate(self, panes=[], index=0):
'''
Update pane coordinate tuples based on their height and width relative to other panes
within the dimensions of the current window.
We account for panes with a height of 1 where the bottom coordinates are the same as the top.
Account for floating panes and self-coordinating panes adjacent to panes set to EXPAND.
Coordinates are of the form:
[
((top-left-from-top, top-left-from-left),
(top-right-from-top, top-right-from-left)),
((bottom-left-from-top, bottom-left-from-left),
(bottom-right-from-top, bottom-right-from-left))
]
We can then use these to determine things such as whether corners are inverted and how
many characters may be drawn
'''
pass
def addstr(self, h, w, text, attrs=0):
'''
A safe addstr wrapper
'''
pass
def update_window_size(self):
'''
Update the current window object with its current
height and width and clear the screen if they've changed.
'''
pass
def addstr(self, h, w, text, attrs=0):
'''
Adds new panes to the window
'''
pass
def init_pane(self, pane):
pass
def block(self):
pass
def unblock(self):
pass
def get(self, name, default=None, cache=False):
'''
Get a pane by name, possibly from the cache. Return None if not found.
'''
pass
def __setitem__(self, name, new_pane):
pass
def __getitem__(self, name):
pass
def __len__(self):
pass
def __iter__(self):
'''
Iterate over self.panes by automatically flattening lists.
'''
pass
| 20 | 13 | 35 | 4 | 23 | 9 | 8 | 0.41 | 1 | 12 | 2 | 0 | 19 | 11 | 19 | 19 | 690 | 93 | 429 | 91 | 409 | 176 | 406 | 89 | 386 | 64 | 1 | 9 | 159 |
147,573 |
LukeB42/Window
|
LukeB42_Window/examples/advent.py
|
advent.TestMenu
|
class TestMenu(Menu):
"""
An example menu
"""
geometry = [FIT, FIT]
items = [
[1, 'fight','handle_fight'],
[0, 'items','handle_items'],
[0, 'magic','handle_magic'],
[0, 'flee','handle_flee'],
]
def handle_fight(self):
gamearea = self.window.get("gamearea")
gamearea.change_content(0, "The Grue dissolved.", ALIGN_LEFT, palette(-1,-1))
def handle_items(self):
for p in reversed(self.window.panes):
if isinstance(p, list):
p.reverse()
break
def handle_magic(self):
if self.geometry[0] == EXPAND:
self.geometry[0] = FIT
if self.geometry[0] == FIT:
self.geometry[0] = 30
else:
self.geometry[0] = EXPAND
def handle_flee(self):
self.window.stop()
|
class TestMenu(Menu):
'''
An example menu
'''
def handle_fight(self):
pass
def handle_items(self):
pass
def handle_magic(self):
pass
def handle_flee(self):
pass
| 5 | 1 | 4 | 0 | 4 | 0 | 2 | 0.12 | 1 | 2 | 0 | 0 | 4 | 0 | 4 | 12 | 32 | 4 | 25 | 9 | 20 | 3 | 19 | 9 | 14 | 3 | 3 | 2 | 8 |
147,574 |
LukeB42/Window
|
LukeB42_Window/examples/advent.py
|
advent.Player
|
class Player(Person):
pass
|
class Player(Person):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 2 | 0 | 0 |
147,575 |
LukeB42/Window
|
LukeB42_Window/examples/advent.py
|
advent.CombatMenu
|
class CombatMenu(Menu):
"""
Menu navigation for combat
"""
geometry = [EXPAND, EXPAND]
|
class CombatMenu(Menu):
'''
Menu navigation for combat
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 8 | 5 | 0 | 2 | 2 | 1 | 3 | 2 | 2 | 1 | 0 | 3 | 0 | 0 |
147,576 |
LukeB42/Window
|
LukeB42_Window/window.py
|
window.Editor
|
class Editor(Pane):
"""
Defines a text editor/input pane.
"""
geometry = [EXPAND, EXPAND]
buffer = ""
def update(self):
if len(self.content) >= 1:
self.change_content(1, "%i\n" % len(self.buffer))
def process_input(self, character):
self.window.window.clear()
if character == 23 and self.buffer: # Clear buffer on ^W
self.buffer = ''
if character == 263 and self.buffer: # Handle backspace
self.buffer = self.buffer[:-1]
elif character == 10 or character == 13: # Handle the return key
self.buffer += "\n"
else:
try:
self.buffer += chr(character) # Append input to buffer
except:
# Shouldn't no-op here but there really isn't anything to do.
pass
import random
colours = palette(-1, random.choice(["blue","red"]))
self.change_content(0, self.buffer, ALIGN_LEFT, colours)
|
class Editor(Pane):
'''
Defines a text editor/input pane.
'''
def update(self):
pass
def process_input(self, character):
pass
| 3 | 1 | 10 | 0 | 10 | 3 | 4 | 0.36 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 8 | 28 | 2 | 22 | 7 | 18 | 8 | 20 | 7 | 16 | 5 | 2 | 2 | 7 |
147,577 |
LukeB42/Window
|
LukeB42_Window/window.py
|
window.Editor
|
class Editor(Pane):
"""
Defines a text editor/input pane.
"""
geometry = [EXPAND, EXPAND]
buffer = ""
def update(self):
if len(self.content) >= 1:
self.change_content(1, "%i\n" % len(self.buffer))
def process_input(self, character):
self.window.window.clear()
if character == 23 and self.buffer: # Clear buffer on ^W
self.buffer = ''
if character == 263 and self.buffer: # Handle backspace
self.buffer = self.buffer[:-1]
elif character == 10 or character == 13: # Handle the return key
self.buffer += "\n"
else:
try:
self.buffer += chr(character) # Append input to buffer
except:
# Shouldn't no-op here but there really isn't anything to do.
pass
import random
colours = palette(-1, random.choice(["blue","red"]))
self.change_content(0, self.buffer, ALIGN_LEFT, colours)
|
class Editor(Pane):
'''
Defines a text editor/input pane.
'''
def update(self):
pass
def process_input(self, character):
pass
| 3 | 1 | 10 | 0 | 10 | 3 | 4 | 0.36 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 8 | 28 | 2 | 22 | 7 | 18 | 8 | 20 | 7 | 16 | 5 | 2 | 2 | 7 |
147,578 |
LukeB42/Window
|
LukeB42_Window/examples/advent.py
|
advent.NPC
|
class NPC(Person):
friendlyness = 10
|
class NPC(Person):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 2 | 0 | 0 |
147,579 |
LukeB42/Window
|
LukeB42_Window/examples/advent.py
|
advent.Location
|
class Location(object):
name = ""
description = ""
|
class Location(object):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
147,580 |
LukeB42/Window
|
LukeB42_Window/examples/advent.py
|
advent.Input
|
class Input(Pane):
"""
A test pane.
"""
geometry = [EXPAND, 1] # horiz, vert
buffer = ""
def update(self):
new_line = "> "
self.change_content(0, new_line)
# if len(self.content) >= 2:
# self.change_content(2, "%i\n" % len(self.buffer))
def process_input(self, character):
self.window.window.clear()
if character == 263 and self.buffer: # Handle backspace
self.buffer = self.buffer[:-1]
elif character == 10 or character == 13: # Handle the return key
inputs = self.buffer.split("\n")
if "menu" in inputs:
menu = self.window.get("menu")
menu.hidden = False if menu.hidden else True
menu.active = True if not menu.active else False
# Yup... Can launch ptpython with the "python" command.
elif "python" in inputs:
try:
from ptpython.repl import embed
self.window.stop()
l = {"pane": self, "window": self.window}
embed(locals=l, vi_mode=True)
self.buffer = ""
self.window.start()
except:
pass
elif "exit" in inputs:
self.window.stop()
self.buffer = ""
else:
try: self.buffer += chr(character) # Append input to buffer
except: pass
import random
colours = palette(-1, random.choice(["yellow","red"]))
self.change_content(1, self.buffer, ALIGN_LEFT, colours)
|
class Input(Pane):
'''
A test pane.
'''
def update(self):
pass
def process_input(self, character):
pass
| 3 | 1 | 17 | 0 | 16 | 2 | 6 | 0.29 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 8 | 43 | 2 | 35 | 12 | 30 | 10 | 33 | 12 | 28 | 10 | 2 | 3 | 11 |
147,581 |
LukeB42/Window
|
LukeB42_Window/examples/advent.py
|
advent.HealthBar
|
class HealthBar(Pane):
"""
Player condition (health, mana, attr)
Doubles as a loading bar if used in reverse.
"""
geometry = [EXPAND, 1]
def update(self):
h = self.window.player.health
if h[0] <= 0:
self.window.stop()
amt = int(self.width * float(h[0]) / float(h[1]))
healthbar = "Health: %3.f/%i" % (h[0],h[1])
healthbar += ' ' * (amt - len(healthbar))
if h[0] < (h[1] / 3):
colours = palette("black", "red")
elif h[0] < (h[1] / 2):
colours = palette("black", "yellow")
else:
colours = palette("black", "green")
self.change_content(0, healthbar, ALIGN_LEFT, colours)
self.change_content(1, ' ' * int(self.width - len(healthbar)), ALIGN_LEFT, palette(-1,-1))
|
class HealthBar(Pane):
'''
Player condition (health, mana, attr)
Doubles as a loading bar if used in reverse.
'''
def update(self):
pass
| 2 | 1 | 19 | 4 | 15 | 0 | 4 | 0.24 | 1 | 2 | 0 | 0 | 1 | 0 | 1 | 7 | 26 | 5 | 17 | 7 | 15 | 4 | 15 | 7 | 13 | 4 | 2 | 1 | 4 |
147,582 |
LukeB42/Window
|
LukeB42_Window/examples/advent.py
|
advent.GameArea
|
class GameArea(Pane):
"""
The main area where events are written to.
"""
geometry = [EXPAND, EXPAND]
intro = """Light, Cytoplasm, RNA messenger molecules,
Intention, Abstraction, Message Integrity, Omnidirectional Infinity
You find yourself manifesting onwards from beyond all spheres of force and matter.
A definite spacetime condenses into view.
You're perceptually drifting along the starboard side of a marchant frigate.
The frigate is heading for the orbit of a nearby planet.
You feel the articulation of suit thrusters guiding you on autopilot alongside
the frigate.
Somewhere in your heart a Mandelbrot set zooms in and out simultaneously.
Solve articulation with the passive neural interface to latch on at an airlock.
"""
outro = """
You think the required forms to shift through a thin veil of dust, towards
the body of the frigate. The onboard guidance computer flies by wire to a
maintenence station.
<YOU ARE NOT A DROID>
A signal convulses either you, the suit, or the entire yousuit assembly into taking heed
The drone on your back detaches and having been assaying the signals coming from
the frigate the whole time, begins performing aikido in terms of the authentication
protocol used for accessing a maintenence tunnel.
The drone is not a smooth talker. The frigate thinks of you as a hostile parasite.
"""
def update(self):
if not self.content:
self.change_content(0, self.intro, ALIGN_LEFT, palette(-1,-1))
def process_input(self, character):
# self.window.player.health[0] -= 1
pass
|
class GameArea(Pane):
'''
The main area where events are written to.
'''
def update(self):
pass
def process_input(self, character):
pass
| 3 | 1 | 3 | 0 | 3 | 1 | 2 | 0.14 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 8 | 48 | 15 | 29 | 6 | 26 | 4 | 9 | 6 | 6 | 2 | 2 | 1 | 3 |
147,583 |
LukeB42/Window
|
LukeB42_Window/examples/kilo.py
|
kilo.Status
|
class Status(Pane):
geometry = [EXPAND, 1]
col = ["black","white"]
# col = ["white",-1]
saving = False
buffer = ""
def update(self):
if not self.saving:
self.compute_status_line()
def process_input(self, character):
if self.saving:
self.window.window.clear()
if character == 15:
pass
elif character == 263 and self.buffer: # Handle backspace
self.buffer = self.buffer[:-1]
elif character == 10 or character == 13: # Handle the return key
path = os.path.expanduser(self.buffer)
fd = open(path, "w")
fd.write(self.editor.buffer)
fd.close()
self.buffer = ""
self.saving = False
self.editor.active = True
else:
try: self.buffer += chr(character) # Append input to buffer
except: pass
line = "Filename: " + self.buffer
line += ' ' * (self.width - len(line))
self.change_content(0, line, ALIGN_LEFT, palette(self.col[0], self.col[1]))
def compute_status_line(self):
line = ''
c = len(self.editor.buffer)
if c:
line = "C%i, " % c
w = len(self.editor.buffer.split())
if w:
line += "W%i, " % w
l = len(self.editor.buffer.split('\n'))
if l:
line += "L%i" % l
filler = ' ' * int(((self.width /2) - (len(line) / 2)))
line = filler + line
line += ' ' * (self.width-len(line))
self.change_content(0, line, ALIGN_LEFT, palette(self.col[0], self.col[1]))
|
class Status(Pane):
def update(self):
pass
def process_input(self, character):
pass
def compute_status_line(self):
pass
| 4 | 0 | 13 | 0 | 13 | 1 | 4 | 0.09 | 1 | 1 | 0 | 0 | 3 | 0 | 3 | 9 | 48 | 3 | 44 | 16 | 40 | 4 | 43 | 16 | 39 | 6 | 2 | 3 | 12 |
147,584 |
LukeB42/Window
|
LukeB42_Window/examples/advent.py
|
advent.ManaBar
|
class ManaBar(Pane):
geometry = [EXPAND, 1]
def update(self):
h = self.window.player.mana
amt = int(self.width * float(h[0]) / float(h[1]))
healthbar = "Mana: %3.f/%i" % (h[0],h[1])
healthbar += ' ' * (amt - len(healthbar))
if h[0] < (h[1] / 4):
colours = palette("black", "yellow")
# elif h[0] < (h[1] / 2):
# colours = palette("black", "yellow")
else:
colours = palette("black", "blue")
self.change_content(0, healthbar, ALIGN_LEFT, colours)
self.change_content(1, ' ' * int(self.width - len(healthbar)), ALIGN_LEFT, palette(-1,-1))
|
class ManaBar(Pane):
def update(self):
pass
| 2 | 0 | 17 | 4 | 11 | 2 | 2 | 0.15 | 1 | 2 | 0 | 0 | 1 | 0 | 1 | 7 | 19 | 4 | 13 | 7 | 11 | 2 | 12 | 7 | 10 | 2 | 2 | 1 | 2 |
147,585 |
LuminosoInsight/langcodes
|
LuminosoInsight_langcodes/langcodes/__init__.py
|
langcodes.Language
|
class Language:
"""
The Language class defines the results of parsing a language tag.
Language objects have the following attributes, any of which may be
unspecified (in which case their value is None):
- *language*: the code for the language itself.
- *script*: the 4-letter code for the writing system being used.
- *territory*: the 2-letter or 3-digit code for the country or similar territory
of the world whose usage of the language appears in this text.
- *extlangs*: a list of more specific language codes that follow the language
code. (This is allowed by the language code syntax, but deprecated.)
- *variants*: codes for specific variations of language usage that aren't
covered by the *script* or *territory* codes.
- *extensions*: information that's attached to the language code for use in
some specific system, such as Unicode collation orders.
- *private*: a code starting with `x-` that has no defined meaning.
The `Language.get` method converts a string to a Language instance.
It's also available at the top level of this module as the `get` function.
"""
ATTRIBUTES = [
'language',
'extlangs',
'script',
'territory',
'variants',
'extensions',
'private',
]
# When looking up "likely subtags" data, we try looking up the data for
# increasingly less specific versions of the language code.
BROADER_KEYSETS = [
{'language', 'script', 'territory'},
{'language', 'territory'},
{'language', 'script'},
{'language'},
{'script'},
{},
]
MATCHABLE_KEYSETS = [
{'language', 'script', 'territory'},
{'language', 'script'},
{'language'},
]
# Values cached at the class level
_INSTANCES: Dict[tuple, 'Language'] = {}
_PARSE_CACHE: Dict[Tuple[str, bool], 'Language'] = {}
def __init__(
self,
language: Optional[str] = None,
extlangs: Optional[Sequence[str]] = None,
script: Optional[str] = None,
territory: Optional[str] = None,
variants: Optional[Sequence[str]] = None,
extensions: Optional[Sequence[str]] = None,
private: Optional[str] = None,
):
"""
The constructor for Language objects.
It's inefficient to call this directly, because it can't return
an existing instance. Instead, call Language.make(), which
has the same signature.
"""
self.language = language
self.extlangs = extlangs
self.script = script
self.territory = territory
self.variants = variants
self.extensions = extensions
self.private = private
# Cached values
self._simplified: 'Language' = None
self._searchable: 'Language' = None
self._broader: List[str] = None
self._assumed: 'Language' = None
self._filled: 'Language' = None
self._macrolanguage: Optional['Language'] = None
self._str_tag: str = None
self._dict: dict = None
self._disp_separator: str = None
self._disp_pattern: str = None
# Make sure the str_tag value is cached
self.to_tag()
@classmethod
def make(
cls,
language: Optional[str] = None,
extlangs: Optional[Sequence[str]] = None,
script: Optional[str] = None,
territory: Optional[str] = None,
variants: Optional[Sequence[str]] = None,
extensions: Optional[Sequence[str]] = None,
private: Optional[str] = None,
) -> 'Language':
"""
Create a Language object by giving any subset of its attributes.
If this value has been created before, return the existing value.
"""
values = (
language,
tuple(extlangs or ()),
script,
territory,
tuple(variants or ()),
tuple(extensions or ()),
private,
)
if values in cls._INSTANCES:
return cls._INSTANCES[values]
instance = cls(
language=language,
extlangs=extlangs,
script=script,
territory=territory,
variants=variants,
extensions=extensions,
private=private,
)
cls._INSTANCES[values] = instance
return instance
@staticmethod
def get(tag: Union[str, 'Language'], normalize=True) -> 'Language':
"""
Create a Language object from a language tag string.
If normalize=True, non-standard or overlong tags will be replaced as
they're interpreted. This is recommended.
Here are several examples of language codes, which are also test cases.
Most language codes are straightforward, but these examples will get
pretty obscure toward the end.
>>> Language.get('en-US')
Language.make(language='en', territory='US')
>>> Language.get('zh-Hant')
Language.make(language='zh', script='Hant')
>>> Language.get('und')
Language.make()
This function is idempotent, in case you already have a Language object:
>>> Language.get(Language.get('en-us'))
Language.make(language='en', territory='US')
The non-code 'root' is sometimes used to represent the lack of any
language information, similar to 'und'.
>>> Language.get('root')
Language.make()
By default, getting a Language object will automatically convert
deprecated tags:
>>> Language.get('iw')
Language.make(language='he')
>>> Language.get('in')
Language.make(language='id')
One type of deprecated tag that should be replaced is for sign
languages, which used to all be coded as regional variants of a
fictitious global sign language called 'sgn'. Of course, there is no
global sign language, so sign languages now have their own language
codes.
>>> Language.get('sgn-US')
Language.make(language='ase')
>>> Language.get('sgn-US', normalize=False)
Language.make(language='sgn', territory='US')
'en-gb-oed' is a tag that's grandfathered into the standard because it
has been used to mean "spell-check this with Oxford English Dictionary
spelling", but that tag has the wrong shape. We interpret this as the
new standardized tag 'en-gb-oxendict', unless asked not to normalize.
>>> Language.get('en-gb-oed')
Language.make(language='en', territory='GB', variants=['oxendict'])
>>> Language.get('en-gb-oed', normalize=False)
Language.make(language='en-gb-oed')
'zh-min-nan' is another oddly-formed tag, used to represent the
Southern Min language, which includes Taiwanese as a regional form. It
now has its own language code.
>>> Language.get('zh-min-nan')
Language.make(language='nan')
The vague tag 'zh-min' is now also interpreted as 'nan', with a private
extension indicating that it had a different form:
>>> Language.get('zh-min')
Language.make(language='nan', private='x-zh-min')
Occasionally Wiktionary will use 'extlang' tags in strange ways, such
as using the tag 'und-ibe' for some unspecified Iberian language.
>>> Language.get('und-ibe')
Language.make(extlangs=['ibe'])
Here's an example of replacing multiple deprecated tags.
The language tag 'sh' (Serbo-Croatian) ended up being politically
problematic, and different standards took different steps to address
this. The IANA made it into a macrolanguage that contains 'sr', 'hr',
and 'bs'. Unicode further decided that it's a legacy tag that should
be interpreted as 'sr-Latn', which the language matching rules say
is mutually intelligible with all those languages.
We complicate the example by adding on the territory tag 'QU', an old
provisional tag for the European Union, which is now standardized as
'EU'.
>>> Language.get('sh-QU')
Language.make(language='sr', script='Latn', territory='EU')
"""
if isinstance(tag, Language):
if not normalize:
# shortcut: we have the tag already
return tag
# We might need to normalize this tag. Convert it back into a
# string tag, to cover all the edge cases of normalization in a
# way that we've already solved.
tag = tag.to_tag()
if (tag, normalize) in Language._PARSE_CACHE:
return Language._PARSE_CACHE[tag, normalize]
data: Dict[str, Any] = {}
# If the complete tag appears as something to normalize, do the
# normalization right away. Smash case and convert underscores to
# hyphens when checking, because the case normalization that comes from
# parse_tag() hasn't been applied yet.
tag_lower = normalize_characters(tag)
if normalize and tag_lower in LANGUAGE_REPLACEMENTS:
tag = LANGUAGE_REPLACEMENTS[tag_lower]
components = parse_tag(tag)
for typ, value in components:
if typ == 'extlang' and normalize and 'language' in data:
# smash extlangs when possible
minitag = f"{data['language']}-{value}"
norm = LANGUAGE_REPLACEMENTS.get(normalize_characters(minitag))
if norm is not None:
data.update(Language.get(norm, normalize).to_dict())
else:
data.setdefault('extlangs', []).append(value)
elif typ in {'extlang', 'variant', 'extension'}:
data.setdefault(typ + 's', []).append(value)
elif typ == 'language':
if value == 'und':
pass
elif normalize:
replacement = LANGUAGE_REPLACEMENTS.get(value.lower())
if replacement is not None:
# parse the replacement if necessary -- this helps with
# Serbian and Moldovan
data.update(Language.get(replacement, normalize).to_dict())
else:
data['language'] = value
else:
data['language'] = value
elif typ == 'territory':
if normalize:
data['territory'] = TERRITORY_REPLACEMENTS.get(value.lower(), value)
else:
data['territory'] = value
elif typ == 'grandfathered':
# If we got here, we got a grandfathered tag but we were asked
# not to normalize it, or the CLDR data doesn't know how to
# normalize it. The best we can do is set the entire tag as the
# language.
data['language'] = value
else:
data[typ] = value
result = Language.make(**data)
Language._PARSE_CACHE[tag, normalize] = result
return result
def to_tag(self) -> str:
"""
Convert a Language back to a standard language tag, as a string.
This is also the str() representation of a Language object.
>>> Language.make(language='en', territory='GB').to_tag()
'en-GB'
>>> Language.make(language='yue', script='Hant', territory='HK').to_tag()
'yue-Hant-HK'
>>> Language.make(script='Arab').to_tag()
'und-Arab'
>>> str(Language.make(territory='IN'))
'und-IN'
"""
if self._str_tag is not None:
return self._str_tag
subtags = ['und']
if self.language:
subtags[0] = self.language
if self.extlangs:
for extlang in sorted(self.extlangs):
subtags.append(extlang)
if self.script:
subtags.append(self.script)
if self.territory:
subtags.append(self.territory)
if self.variants:
for variant in sorted(self.variants):
subtags.append(variant)
if self.extensions:
for ext in self.extensions:
subtags.append(ext)
if self.private:
subtags.append(self.private)
self._str_tag = '-'.join(subtags)
return self._str_tag
def simplify_script(self) -> 'Language':
"""
Remove the script from some parsed language data, if the script is
redundant with the language.
>>> Language.make(language='en', script='Latn').simplify_script()
Language.make(language='en')
>>> Language.make(language='yi', script='Latn').simplify_script()
Language.make(language='yi', script='Latn')
>>> Language.make(language='yi', script='Hebr').simplify_script()
Language.make(language='yi')
"""
if self._simplified is not None:
return self._simplified
if self.language and self.script:
if DEFAULT_SCRIPTS.get(self.language) == self.script:
result = self.update_dict({'script': None})
self._simplified = result
return self._simplified
self._simplified = self
return self._simplified
def assume_script(self) -> 'Language':
"""
Fill in the script if it's missing, and if it can be assumed from the
language subtag. This is the opposite of `simplify_script`.
>>> Language.make(language='en').assume_script()
Language.make(language='en', script='Latn')
>>> Language.make(language='yi').assume_script()
Language.make(language='yi', script='Hebr')
>>> Language.make(language='yi', script='Latn').assume_script()
Language.make(language='yi', script='Latn')
This fills in nothing when the script cannot be assumed -- such as when
the language has multiple scripts, or it has no standard orthography:
>>> Language.make(language='sr').assume_script()
Language.make(language='sr')
>>> Language.make(language='eee').assume_script()
Language.make(language='eee')
It also doesn't fill anything in when the language is unspecified.
>>> Language.make(territory='US').assume_script()
Language.make(territory='US')
"""
if self._assumed is not None:
return self._assumed
if self.language and not self.script:
try:
self._assumed = self.update_dict(
{'script': DEFAULT_SCRIPTS[self.language]}
)
except KeyError:
self._assumed = self
else:
self._assumed = self
return self._assumed
def prefer_macrolanguage(self) -> 'Language':
"""
BCP 47 doesn't specify what to do with macrolanguages and the languages
they contain. The Unicode CLDR, on the other hand, says that when a
macrolanguage has a dominant standardized language, the macrolanguage
code should be used for that language. For example, Mandarin Chinese
is 'zh', not 'cmn', according to Unicode, and Malay is 'ms', not 'zsm'.
This isn't a rule you'd want to follow in all cases -- for example, you may
want to be able to specifically say that 'ms' (the Malay macrolanguage)
contains both 'zsm' (Standard Malay) and 'id' (Indonesian). But applying
this rule helps when interoperating with the Unicode CLDR.
So, applying `prefer_macrolanguage` to a Language object will
return a new object, replacing the language with the macrolanguage if
it is the dominant language within that macrolanguage. It will leave
non-dominant languages that have macrolanguages alone.
>>> Language.get('arb').prefer_macrolanguage()
Language.make(language='ar')
>>> Language.get('cmn-Hant').prefer_macrolanguage()
Language.make(language='zh', script='Hant')
>>> Language.get('yue-Hant').prefer_macrolanguage()
Language.make(language='yue', script='Hant')
"""
if self._macrolanguage is not None:
return self._macrolanguage
language = self.language or 'und'
if language in NORMALIZED_MACROLANGUAGES:
self._macrolanguage = self.update_dict(
{'language': NORMALIZED_MACROLANGUAGES[language]}
)
else:
self._macrolanguage = self
return self._macrolanguage
def to_alpha3(self, variant: str = 'T') -> str:
"""
Get the three-letter language code for this language, even if it's
canonically written with a two-letter code.
These codes are the 'alpha3' codes defined by ISO 639-2.
When this function returns, it always returns a 3-letter string. If
there is no known alpha3 code for the language, it raises a LookupError.
In cases where the distinction matters, we default to the 'terminology'
code. You can pass `variant='B'` to get the 'bibliographic' code instead.
For example, the terminology code for German is 'deu', while the
bibliographic code is 'ger'.
(The confusion between these two sets of codes is a good reason to avoid
using alpha3 codes. Every language that has two different alpha3 codes
also has an alpha2 code that's preferred, such as 'de' for German.)
>>> Language.get('fr').to_alpha3()
'fra'
>>> Language.get('fr-CA').to_alpha3()
'fra'
>>> Language.get('fr').to_alpha3(variant='B')
'fre'
>>> Language.get('de').to_alpha3(variant='T')
'deu'
>>> Language.get('ja').to_alpha3()
'jpn'
>>> Language.get('un').to_alpha3()
Traceback (most recent call last):
...
LookupError: 'un' is not a known language code, and has no alpha3 code.
All valid two-letter language codes have corresponding alpha3 codes,
even the un-normalized ones. If they were assigned an alpha3 code by ISO
before they were assigned a normalized code by CLDR, these codes may be
different:
>>> Language.get('tl', normalize=False).to_alpha3()
'tgl'
>>> Language.get('tl').to_alpha3()
'fil'
>>> Language.get('sh', normalize=False).to_alpha3()
'hbs'
Three-letter codes are preserved, even if they're unknown:
>>> Language.get('qqq').to_alpha3()
'qqq'
>>> Language.get('und').to_alpha3()
'und'
"""
variant = variant.upper()
if variant not in 'BT':
raise ValueError("Variant must be 'B' or 'T'")
language = self.language
if language is None:
return 'und'
elif len(language) == 3:
return language
else:
if variant == 'B' and language in LANGUAGE_ALPHA3_BIBLIOGRAPHIC:
return LANGUAGE_ALPHA3_BIBLIOGRAPHIC[language]
elif language in LANGUAGE_ALPHA3:
return LANGUAGE_ALPHA3[language]
else:
raise LookupError(
f"{language!r} is not a known language code, "
"and has no alpha3 code."
)
def broader_tags(self) -> List[str]:
"""
Iterate through increasingly general tags for this language.
This isn't actually that useful for matching two arbitrary language tags
against each other, but it is useful for matching them against a known
standardized form, such as in the CLDR data.
The list of broader versions to try appears in UTR 35, section 4.3,
"Likely Subtags".
>>> Language.get('nn-Latn-NO-x-thingy').broader_tags()
['nn-Latn-NO-x-thingy', 'nn-Latn-NO', 'nn-NO', 'nn-Latn', 'nn', 'und-Latn', 'und']
>>> Language.get('arb-Arab').broader_tags()
['arb-Arab', 'ar-Arab', 'arb', 'ar', 'und-Arab', 'und']
"""
if self._broader is not None:
return self._broader
self._broader = [self.to_tag()]
seen = set([self.to_tag()])
for keyset in self.BROADER_KEYSETS:
for start_language in (self, self.prefer_macrolanguage()):
filtered = start_language._filter_attributes(keyset)
tag = filtered.to_tag()
if tag not in seen:
self._broader.append(tag)
seen.add(tag)
return self._broader
def broaden(self) -> 'List[Language]':
"""
Like `broader_tags`, but returrns Language objects instead of strings.
"""
return [Language.get(tag) for tag in self.broader_tags()]
def maximize(self) -> 'Language':
"""
The Unicode CLDR contains a "likelySubtags" data file, which can guess
reasonable values for fields that are missing from a language tag.
This is particularly useful for comparing, for example, "zh-Hant" and
"zh-TW", two common language tags that say approximately the same thing
via rather different information. (Using traditional Han characters is
not the same as being in Taiwan, but each implies that the other is
likely.)
These implications are provided in the CLDR supplemental data, and are
based on the likelihood of people using the language to transmit text
on the Internet. (This is why the overall default is English, not
Chinese.)
It's important to recognize that these tags amplify majorities, and
that not all language support fits into a "likely" language tag.
>>> str(Language.get('zh-Hant').maximize())
'zh-Hant-TW'
>>> str(Language.get('zh-TW').maximize())
'zh-Hant-TW'
>>> str(Language.get('ja').maximize())
'ja-Jpan-JP'
>>> str(Language.get('pt').maximize())
'pt-Latn-BR'
>>> str(Language.get('und-Arab').maximize())
'ar-Arab-EG'
>>> str(Language.get('und-CH').maximize())
'de-Latn-CH'
As many standards are, this is US-centric:
>>> str(Language.make().maximize())
'en-Latn-US'
"Extlangs" have no likely-subtags information, so they will give
maximized results that make no sense:
>>> str(Language.get('und-ibe').maximize())
'en-ibe-Latn-US'
"""
if self._filled is not None:
return self._filled
for tag in self.broader_tags():
if tag in LIKELY_SUBTAGS:
result = Language.get(LIKELY_SUBTAGS[tag], normalize=False)
result = result.update(self)
self._filled = result
return result
raise RuntimeError(
"Couldn't fill in likely values. This represents a problem with "
"the LIKELY_SUBTAGS data."
)
# Support an old, wordier name for the method
fill_likely_values = maximize
def match_score(self, supported: 'Language') -> int:
"""
DEPRECATED: use .distance() instead, which uses newer data and is _lower_
for better matching languages.
"""
warnings.warn(
"`match_score` is deprecated because it's based on deprecated CLDR info. "
"Use `distance` instead, which is _lower_ for better matching languages. ",
DeprecationWarning,
)
return 100 - min(self.distance(supported), 100)
def distance(self, supported: 'Language', ignore_script: bool = False) -> int:
"""
Suppose that `self` is the language that the user desires, and
`supported` is a language that is actually supported.
This method returns a number from 0 to 134 measuring the 'distance'
between the languages (lower numbers are better). This is not a
symmetric relation. If `ignore_script` is `True`, the script will
not be used in the comparison, possibly resulting in a smaller
'distance'.
The language distance is not really about the linguistic similarity or
history of the languages; instead, it's based largely on sociopolitical
factors, indicating which language speakers are likely to know which
other languages in the present world. Much of the heuristic is about
finding a widespread 'world language' like English, Chinese, French, or
Russian that speakers of a more localized language will accept.
A version that works on language tags, as strings, is in the function
`tag_distance`. See that function for copious examples.
"""
if supported == self:
return 0
# CLDR has realized that these matching rules are undermined when the
# unspecified language 'und' gets maximized to 'en-Latn-US', so this case
# is specifically not maximized:
if self.language is None and self.script is None and self.territory is None:
desired_triple = ('und', 'Zzzz', 'ZZ')
else:
desired_complete = self.prefer_macrolanguage().maximize()
desired_triple = (
desired_complete.language,
None if ignore_script else desired_complete.script,
desired_complete.territory,
)
if (
supported.language is None
and supported.script is None
and supported.territory is None
):
supported_triple = ('und', 'Zzzz', 'ZZ')
else:
supported_complete = supported.prefer_macrolanguage().maximize()
supported_triple = (
supported_complete.language,
None if ignore_script else supported_complete.script,
supported_complete.territory,
)
return tuple_distance_cached(desired_triple, supported_triple)
def is_valid(self) -> bool:
"""
Checks whether the language, script, territory, and variants
(if present) are all tags that have meanings assigned by IANA.
For example, 'ja' (Japanese) is a valid tag, and 'jp' is not.
The data is current as of CLDR 40.
>>> Language.get('ja').is_valid()
True
>>> Language.get('jp').is_valid()
False
>>> Language.get('en-001').is_valid()
True
>>> Language.get('en-000').is_valid()
False
>>> Language.get('en-Latn').is_valid()
True
>>> Language.get('en-Latnx').is_valid()
False
>>> Language.get('und').is_valid()
True
>>> Language.get('en-GB-oxendict').is_valid()
True
>>> Language.get('en-GB-oxenfree').is_valid()
False
>>> Language.get('x-heptapod').is_valid()
True
Some scripts are, confusingly, not included in CLDR's 'validity' pattern.
If a script appears in the IANA registry, we consider it valid.
>>> Language.get('ur-Aran').is_valid()
True
>>> Language.get('cu-Cyrs').is_valid()
True
A language tag with multiple extlangs will parse, but is not valid.
The only allowed example is 'zh-min-nan', which normalizes to the
language 'nan'.
>>> Language.get('zh-min-nan').is_valid()
True
>>> Language.get('sgn-ase-bfi').is_valid()
False
These examples check that duplicate tags are not valid:
>>> Language.get('de-1901').is_valid()
True
>>> Language.get('de-1901-1901').is_valid()
False
>>> Language.get('en-a-bbb-c-ddd').is_valid()
True
>>> Language.get('en-a-bbb-a-ddd').is_valid()
False
Of course, you should be prepared to catch a failure to parse the
language code at all:
>>> Language.get('C').is_valid()
Traceback (most recent call last):
...
langcodes.tag_parser.LanguageTagError: Expected a language code, got 'c'
"""
if self.extlangs is not None:
# An erratum to BCP 47 says that tags with more than one extlang are
# invalid.
if len(self.extlangs) > 1:
return False
subtags = [self.language, self.script, self.territory]
checked_subtags = []
if self.variants is not None:
subtags.extend(self.variants)
for subtag in subtags:
if subtag is not None:
checked_subtags.append(subtag)
if not subtag.startswith('x-') and not VALIDITY.match(subtag):
if subtag not in ALL_SCRIPTS:
return False
# We check extensions for validity by ensuring that there aren't
# two extensions introduced by the same letter. For example, you can't
# have two 'u-' extensions.
if self.extensions:
checked_subtags.extend([extension[:2] for extension in self.extensions])
if len(set(checked_subtags)) != len(checked_subtags):
return False
return True
def has_name_data(self) -> bool:
"""
Return True when we can name languages in this language. Requires
`language_data` to be installed.
This is true when the language, or one of its 'broader' versions, is in
the list of CLDR target languages.
>>> Language.get('fr').has_name_data()
True
>>> Language.get('so').has_name_data()
True
>>> Language.get('enc').has_name_data()
False
>>> Language.get('und').has_name_data()
False
"""
try:
from language_data.name_data import LANGUAGES_WITH_NAME_DATA
except ImportError:
print(LANGUAGE_NAME_IMPORT_MESSAGE, file=sys.stdout)
raise
matches = set(self.broader_tags()) & LANGUAGES_WITH_NAME_DATA
return bool(matches)
# These methods help to show what the language tag means in natural
# language. They actually apply the language-matching algorithm to find
# the right language to name things in.
def _get_name(
self, attribute: str, language: Union[str, 'Language'], max_distance: int
) -> str:
try:
from language_data.names import code_to_names
except ImportError:
print(LANGUAGE_NAME_IMPORT_MESSAGE, file=sys.stdout)
raise
assert attribute in self.ATTRIBUTES
if isinstance(language, str):
language = Language.get(language)
attr_value = getattr(self, attribute)
if attr_value is None:
if attribute == 'language':
attr_value = 'und'
else:
return None
names = code_to_names(attr_value)
result = self._best_name(names, language, max_distance)
if result is not None:
return result
else:
# Construct a string like "Unknown language [zzz]"
placeholder = None
if attribute == 'language':
placeholder = 'und'
elif attribute == 'script':
placeholder = 'Zzzz'
elif attribute == 'territory':
placeholder = 'ZZ'
unknown_name = None
if placeholder is not None:
names = code_to_names(placeholder)
unknown_name = self._best_name(names, language, max_distance)
if unknown_name is None:
unknown_name = 'Unknown language subtag'
return f'{unknown_name} [{attr_value}]'
def _best_name(
self, names: Mapping[str, str], language: 'Language', max_distance: int
):
matchable_languages = set(language.broader_tags())
possible_languages = [
key for key in sorted(names.keys()) if key in matchable_languages
]
target_language, score = closest_match(
language, possible_languages, max_distance
)
if target_language in names:
return names[target_language]
else:
return names.get(DEFAULT_LANGUAGE)
def language_name(
self,
language: Union[str, 'Language'] = DEFAULT_LANGUAGE,
max_distance: int = 25,
) -> str:
"""
Give the name of the language (not the entire tag, just the language part)
in a natural language. The target language can be given as a string or
another Language object.
By default, things are named in English:
>>> Language.get('fr').language_name()
'French'
>>> Language.get('el').language_name()
'Greek'
But you can ask for language names in numerous other languages:
>>> Language.get('fr').language_name('fr')
'français'
>>> Language.get('el').language_name('fr')
'grec'
Why does everyone get Slovak and Slovenian confused? Let's ask them.
>>> Language.get('sl').language_name('sl')
'slovenščina'
>>> Language.get('sk').language_name('sk')
'slovenčina'
>>> Language.get('sl').language_name('sk')
'slovinčina'
>>> Language.get('sk').language_name('sl')
'slovaščina'
"""
return self._get_name('language', language, max_distance)
def display_name(
self,
language: Union[str, 'Language'] = DEFAULT_LANGUAGE,
max_distance: int = 25,
) -> str:
"""
It's often helpful to be able to describe a language code in a way that a user
(or you) can understand, instead of in inscrutable short codes. The
`display_name` method lets you describe a Language object *in a language*.
The `.display_name(language, min_score)` method will look up the name of the
language. The names come from the IANA language tag registry, which is only in
English, plus CLDR, which names languages in many commonly-used languages.
The default language for naming things is English:
>>> Language.make(language='fr').display_name()
'French'
>>> Language.make().display_name()
'Unknown language'
>>> Language.get('zh-Hans').display_name()
'Chinese (Simplified)'
>>> Language.get('en-US').display_name()
'English (United States)'
But you can ask for language names in numerous other languages:
>>> Language.get('fr').display_name('fr')
'français'
>>> Language.get('fr').display_name('es')
'francés'
>>> Language.make().display_name('es')
'lengua desconocida'
>>> Language.get('zh-Hans').display_name('de')
'Chinesisch (Vereinfacht)'
>>> Language.get('en-US').display_name('zh-Hans')
'英语(美国)'
"""
reduced = self.simplify_script()
language = Language.get(language)
language_name = reduced.language_name(language, max_distance)
extra_parts = []
if reduced.script is not None:
extra_parts.append(reduced.script_name(language, max_distance))
if reduced.territory is not None:
extra_parts.append(reduced.territory_name(language, max_distance))
if extra_parts:
clarification = language._display_separator().join(extra_parts)
pattern = language._display_pattern()
return pattern.format(language_name, clarification)
else:
return language_name
def _display_pattern(self) -> str:
"""
Get the pattern, according to CLDR, that should be used for clarifying
details of a language code.
"""
# Technically we are supposed to look up this pattern in each language.
# Practically, it's the same in every language except Chinese, where the
# parentheses are full-width.
if self._disp_pattern is not None:
return self._disp_pattern
if self.distance(Language.get('zh')) <= 25 or self.distance(Language.get('zh-Hant')) <= 25:
self._disp_pattern = "{0}({1})"
else:
self._disp_pattern = "{0} ({1})"
return self._disp_pattern
def _display_separator(self) -> str:
"""
Get the symbol that should be used to separate multiple clarifying
details -- such as a comma in English, or an ideographic comma in
Japanese.
Requires that `language_data` is installed.
"""
try:
from language_data.names import DISPLAY_SEPARATORS
except ImportError:
print(LANGUAGE_NAME_IMPORT_MESSAGE, file=sys.stdout)
raise
if self._disp_separator is not None:
return self._disp_separator
matched, _dist = closest_match(self, DISPLAY_SEPARATORS.keys())
self._disp_separator = DISPLAY_SEPARATORS[matched]
return self._disp_separator
def autonym(self, max_distance: int = 9) -> str:
"""
Give the display name of this language *in* this language.
Requires that `language_data` is installed.
>>> Language.get('fr').autonym()
'français'
>>> Language.get('es').autonym()
'español'
>>> Language.get('ja').autonym()
'日本語'
This uses the `display_name()` method, so it can include the name of a
script or territory when appropriate.
>>> Language.get('en-AU').autonym()
'English (Australia)'
>>> Language.get('sr-Latn').autonym()
'srpski (latinica)'
>>> Language.get('sr-Cyrl').autonym()
'српски (ћирилица)'
>>> Language.get('pa').autonym()
'ਪੰਜਾਬੀ'
>>> Language.get('pa-Arab').autonym()
'پنجابی (عربی)'
This only works for language codes that CLDR has locale data for. You
can't ask for the autonym of 'ja-Latn' and get 'nihongo (rōmaji)'.
"""
lang = self.prefer_macrolanguage()
return lang.display_name(language=lang, max_distance=max_distance)
def script_name(
self,
language: Union[str, 'Language'] = DEFAULT_LANGUAGE,
max_distance: int = 25,
) -> str:
"""
Describe the script part of the language tag in a natural language.
Requires that `language_data` is installed.
"""
return self._get_name('script', language, max_distance)
def territory_name(
self,
language: Union[str, 'Language'] = DEFAULT_LANGUAGE,
max_distance: int = 25,
) -> str:
"""
Describe the territory part of the language tag in a natural language.
Requires that `language_data` is installed.
"""
return self._get_name('territory', language, max_distance)
def region_name(
self,
language: Union[str, 'Language'] = DEFAULT_LANGUAGE,
max_distance: int = 25,
) -> str:
warnings.warn(
"`region_name` has been renamed to `territory_name` for consistency",
DeprecationWarning,
)
return self.territory_name(language, max_distance)
@property
def region(self):
warnings.warn(
"The `region` property has been renamed to `territory` for consistency",
DeprecationWarning,
)
return self.territory
def variant_names(
self,
language: Union[str, 'Language'] = DEFAULT_LANGUAGE,
max_distance: int = 25,
) -> Sequence[str]:
"""
Deprecated in version 3.0.
We don't store names for variants anymore, so this just returns the list
of variant codes, such as ['oxendict'] for en-GB-oxendict.
"""
warnings.warn(
"variant_names is deprecated and just returns the variant codes",
DeprecationWarning,
)
return self.variants or []
def describe(
self,
language: Union[str, 'Language'] = DEFAULT_LANGUAGE,
max_distance: int = 25,
) -> dict:
"""
Return a dictionary that describes a given language tag in a specified
natural language. Requires that `language_data` is installed.
See `language_name` and related methods for more specific versions of this.
The desired `language` will in fact be matched against the available
options using the matching technique that this module provides. We can
illustrate many aspects of this by asking for a description of Shavian
script (a phonetic script for English devised by author George Bernard
Shaw), and where you might find it, in various languages.
>>> shaw = Language.make(script='Shaw').maximize()
>>> shaw.describe('en')
{'language': 'English', 'script': 'Shavian', 'territory': 'United Kingdom'}
>>> shaw.describe('fr')
{'language': 'anglais', 'script': 'shavien', 'territory': 'Royaume-Uni'}
>>> shaw.describe('es')
{'language': 'inglés', 'script': 'shaviano', 'territory': 'Reino Unido'}
>>> shaw.describe('pt')
{'language': 'inglês', 'script': 'shaviano', 'territory': 'Reino Unido'}
>>> shaw.describe('uk')
{'language': 'англійська', 'script': 'шоу', 'territory': 'Велика Британія'}
>>> shaw.describe('arb')
{'language': 'الإنجليزية', 'script': 'الشواني', 'territory': 'المملكة المتحدة'}
>>> shaw.describe('th')
{'language': 'อังกฤษ', 'script': 'ซอเวียน', 'territory': 'สหราชอาณาจักร'}
>>> shaw.describe('zh-Hans')
{'language': '英语', 'script': '萧伯纳式文', 'territory': '英国'}
>>> shaw.describe('zh-Hant')
{'language': '英文', 'script': '簫柏納字符', 'territory': '英國'}
>>> shaw.describe('ja')
{'language': '英語', 'script': 'ショー文字', 'territory': 'イギリス'}
When we don't have a localization for the language, we fall back on English,
because the IANA provides names for all known codes in English.
>>> shaw.describe('lol')
{'language': 'English', 'script': 'Shavian', 'territory': 'United Kingdom'}
When the language tag itself is a valid tag but with no known meaning, we
say so in the appropriate language.
>>> Language.get('xyz-ZY').display_name()
'Unknown language [xyz] (Unknown Region [ZY])'
>>> Language.get('xyz-ZY').display_name('es')
'lengua desconocida [xyz] (Región desconocida [ZY])'
"""
names = {}
if self.language:
names['language'] = self.language_name(language, max_distance)
if self.script:
names['script'] = self.script_name(language, max_distance)
if self.territory:
names['territory'] = self.territory_name(language, max_distance)
return names
def speaking_population(self) -> int:
"""
Get an estimate of how many people in the world speak this language,
derived from CLDR data. Requires that `language_data` is installed.
Only the language and territory codes will be considered. If a
territory code is included, the population will count only the
speakers of the language in that territory.
Script subtags are disregarded, because it doesn't make sense to ask
how many people speak in a particular writing script.
>>> Language.get('es').speaking_population()
493528077
>>> Language.get('pt').speaking_population()
237496885
>>> Language.get('es-BR').speaking_population()
76218
>>> Language.get('pt-BR').speaking_population()
192661560
>>> Language.get('vo').speaking_population()
0
"""
try:
from language_data.population_data import LANGUAGE_SPEAKING_POPULATION
except ImportError:
print(LANGUAGE_NAME_IMPORT_MESSAGE, file=sys.stdout)
raise
lang = self._filter_attributes(['language', 'territory'])
return LANGUAGE_SPEAKING_POPULATION.get(str(lang), 0)
def writing_population(self) -> int:
"""
Get an estimate of how many people in the world read and write
this language, derived from CLDR data. Requires that `language_data`
is installed.
For many languages that aren't typically written, this is an
overestimate, according to CLDR -- the data often includes people who
speak that language but write in a different language.
Only the language, script, and territory codes will be considered.
If a territory code is included, the population will count only the
speakers of the language in that territory.
>>> all = Language.get('zh').writing_population()
>>> all
1240841517
>>> traditional = Language.get('zh-Hant').writing_population()
>>> traditional
36863340
>>> simplified = Language.get('zh-Hans').writing_population()
>>> all == traditional + simplified
True
>>> Language.get('zh-Hant-HK').writing_population()
6439733
>>> Language.get('zh-Hans-HK').writing_population()
338933
Note that if you want to get the total Chinese writing population
of Hong Kong, you need to avoid normalization that would interpret
'zh-HK' as 'zh-Hant-HK'.
>>> Language.get('zh-HK', normalize=False).writing_population()
6778666
Unknown or unspecified language codes get a population of 0.
>>> Language.get('xyz').writing_population()
0
>>> Language.get('und').writing_population()
0
"""
try:
from language_data.population_data import LANGUAGE_WRITING_POPULATION
except ImportError:
print(LANGUAGE_NAME_IMPORT_MESSAGE, file=sys.stdout)
raise
lang = self._filter_attributes(['language', 'script', 'territory'])
if str(lang) in LANGUAGE_WRITING_POPULATION:
return LANGUAGE_WRITING_POPULATION[str(lang)]
else:
lang = lang.simplify_script()
return LANGUAGE_WRITING_POPULATION.get(str(lang), 0)
@staticmethod
def find_name(
tagtype: str, name: str, language: Optional[Union[str, 'Language']] = None
) -> 'Language':
"""
Find the subtag of a particular `tagtype` that has the given `name`.
Requires that `language_data` is installed.
The default language, "und", will allow matching names in any language,
so you can get the code 'fr' by looking up "French", "Français", or
"francés".
Occasionally, names are ambiguous in a way that can be resolved by
specifying what name the language is supposed to be in. For example,
there is a language named 'Malayo' in English, but it's different from
the language named 'Malayo' in Spanish (which is Malay). Specifying the
language will look up the name in a trie that is only in that language.
In a previous version, we thought we were going to deprecate the
`language` parameter, as there weren't significant cases of conflicts
in names of things between languages. Well, we got more data, and
conflicts in names are everywhere.
Specifying the language that the name should be in is still not
required, but it will help to make sure that names can be
round-tripped.
>>> Language.find_name('language', 'francés')
Language.make(language='fr')
>>> Language.find_name('territory', 'United Kingdom')
Language.make(territory='GB')
>>> Language.find_name('script', 'Arabic')
Language.make(script='Arab')
>>> Language.find_name('language', 'norsk bokmål')
Language.make(language='nb')
>>> Language.find_name('language', 'norsk')
Language.make(language='no')
>>> Language.find_name('language', 'norsk', 'en')
Traceback (most recent call last):
...
LookupError: Can't find any language named 'norsk'
>>> Language.find_name('language', 'norsk', 'no')
Language.make(language='no')
>>> Language.find_name('language', 'malayo', 'en')
Language.make(language='mbp')
>>> Language.find_name('language', 'malayo', 'es')
Language.make(language='ms')
Some language names resolve to more than a language. For example,
the name 'Brazilian Portuguese' resolves to a language and a territory,
and 'Simplified Chinese' resolves to a language and a script. In these
cases, a Language object with multiple subtags will be returned.
>>> Language.find_name('language', 'Brazilian Portuguese', 'en')
Language.make(language='pt', territory='BR')
>>> Language.find_name('language', 'Simplified Chinese', 'en')
Language.make(language='zh', script='Hans')
A small amount of fuzzy matching is supported: if the name can be
shortened to match a single language name, you get that language.
This allows, for example, "Hakka dialect" to match "Hakka".
>>> Language.find_name('language', 'Hakka dialect')
Language.make(language='hak')
"""
try:
from language_data.names import name_to_code
except ImportError:
print(LANGUAGE_NAME_IMPORT_MESSAGE, file=sys.stdout)
raise
# No matter what form of language we got, normalize it to a single
# language subtag
if isinstance(language, Language):
language = language.language
elif isinstance(language, str):
language = get(language).language
if language is None:
language = 'und'
code = name_to_code(tagtype, name, language)
if code is None:
raise LookupError(f"Can't find any {tagtype} named {name!r}")
if '-' in code:
return Language.get(code)
else:
data = {tagtype: code}
return Language.make(**data)
@staticmethod
def find(
name: str, language: Optional[Union[str, 'Language']] = None
) -> 'Language':
"""
A concise version of `find_name`, used to get a language tag by its
name in a natural language. The language can be omitted in the large
majority of cases, where the language name is not ambiguous.
>>> Language.find('Türkçe')
Language.make(language='tr')
>>> Language.find('brazilian portuguese')
Language.make(language='pt', territory='BR')
>>> Language.find('simplified chinese')
Language.make(language='zh', script='Hans')
Some language names are ambiguous: for example, there is a language
named 'Fala' in English (with code 'fax'), but 'Fala' is also the
Kwasio word for French. In this case, specifying the language that
the name is in is necessary for disambiguation.
>>> Language.find('fala')
Language.make(language='fr')
>>> Language.find('fala', 'nmg')
Language.make(language='fr')
>>> Language.find('fala', 'en')
Language.make(language='fax')
"""
return Language.find_name('language', name, language)
def to_dict(self) -> dict:
"""
Get a dictionary of the attributes of this Language object, which
can be useful for constructing a similar object.
"""
if self._dict is not None:
return self._dict
result = {}
for key in self.ATTRIBUTES:
value = getattr(self, key)
if value:
result[key] = value
self._dict = result
return result
def update(self, other: 'Language') -> 'Language':
"""
Update this Language with the fields of another Language.
"""
return Language.make(
language=other.language or self.language,
extlangs=other.extlangs or self.extlangs,
script=other.script or self.script,
territory=other.territory or self.territory,
variants=other.variants or self.variants,
extensions=other.extensions or self.extensions,
private=other.private or self.private,
)
def update_dict(self, newdata: dict) -> 'Language':
"""
Update the attributes of this Language from a dictionary.
"""
return Language.make(
language=newdata.get('language', self.language),
extlangs=newdata.get('extlangs', self.extlangs),
script=newdata.get('script', self.script),
territory=newdata.get('territory', self.territory),
variants=newdata.get('variants', self.variants),
extensions=newdata.get('extensions', self.extensions),
private=newdata.get('private', self.private),
)
@staticmethod
def _filter_keys(d: dict, keys: Iterable[str]) -> dict:
"""
Select a subset of keys from a dictionary.
"""
return {key: d[key] for key in keys if key in d}
def _filter_attributes(self, keyset: Iterable[str]) -> 'Language':
"""
Return a copy of this object with a subset of its attributes set.
"""
filtered = self._filter_keys(self.to_dict(), keyset)
return Language.make(**filtered)
def _searchable_form(self) -> 'Language':
"""
Convert a parsed language tag so that the information it contains is in
the best form for looking up information in the CLDR.
"""
if self._searchable is not None:
return self._searchable
self._searchable = (
self._filter_attributes({'language', 'script', 'territory'})
.simplify_script()
.prefer_macrolanguage()
)
return self._searchable
def __eq__(self, other):
if self is other:
return True
if not isinstance(other, Language):
return False
return self._str_tag == other._str_tag
def __hash__(self) -> int:
return hash(self._str_tag)
def __getitem__(self, key: str) -> Optional[Union[str, List[str]]]:
if key in self.ATTRIBUTES:
return getattr(self, key)
else:
raise KeyError(key)
def __contains__(self, key: str) -> bool:
return key in self.ATTRIBUTES and getattr(self, key)
def __repr__(self) -> str:
items = []
for attr in self.ATTRIBUTES:
if getattr(self, attr):
value = getattr(self, attr)
items.append(f'{attr}={value!r}')
joined = ', '.join(items)
return f"Language.make({joined})"
def __str__(self) -> str:
return self.to_tag()
|
class Language:
'''
The Language class defines the results of parsing a language tag.
Language objects have the following attributes, any of which may be
unspecified (in which case their value is None):
- *language*: the code for the language itself.
- *script*: the 4-letter code for the writing system being used.
- *territory*: the 2-letter or 3-digit code for the country or similar territory
of the world whose usage of the language appears in this text.
- *extlangs*: a list of more specific language codes that follow the language
code. (This is allowed by the language code syntax, but deprecated.)
- *variants*: codes for specific variations of language usage that aren't
covered by the *script* or *territory* codes.
- *extensions*: information that's attached to the language code for use in
some specific system, such as Unicode collation orders.
- *private*: a code starting with `x-` that has no defined meaning.
The `Language.get` method converts a string to a Language instance.
It's also available at the top level of this module as the `get` function.
'''
def __init__(
self,
language: Optional[str] = None,
extlangs: Optional[Sequence[str]] = None,
script: Optional[str] = None,
territory: Optional[str] = None,
variants: Optional[Sequence[str]] = None,
extensions: Optional[Sequence[str]] = None,
private: Optional[str] = None,
):
'''
The constructor for Language objects.
It's inefficient to call this directly, because it can't return
an existing instance. Instead, call Language.make(), which
has the same signature.
'''
pass
@classmethod
def make(
cls,
language: Optional[str] = None,
extlangs: Optional[Sequence[str]] = None,
script: Optional[str] = None,
territory: Optional[str] = None,
variants: Optional[Sequence[str]] = None,
extensions: Optional[Sequence[str]] = None,
private: Optional[str] = None,
) -> 'Language':
'''
Create a Language object by giving any subset of its attributes.
If this value has been created before, return the existing value.
'''
pass
@staticmethod
def get(tag: Union[str, 'Language'], normalize=True) -> 'Language':
'''
Create a Language object from a language tag string.
If normalize=True, non-standard or overlong tags will be replaced as
they're interpreted. This is recommended.
Here are several examples of language codes, which are also test cases.
Most language codes are straightforward, but these examples will get
pretty obscure toward the end.
>>> Language.get('en-US')
Language.make(language='en', territory='US')
>>> Language.get('zh-Hant')
Language.make(language='zh', script='Hant')
>>> Language.get('und')
Language.make()
This function is idempotent, in case you already have a Language object:
>>> Language.get(Language.get('en-us'))
Language.make(language='en', territory='US')
The non-code 'root' is sometimes used to represent the lack of any
language information, similar to 'und'.
>>> Language.get('root')
Language.make()
By default, getting a Language object will automatically convert
deprecated tags:
>>> Language.get('iw')
Language.make(language='he')
>>> Language.get('in')
Language.make(language='id')
One type of deprecated tag that should be replaced is for sign
languages, which used to all be coded as regional variants of a
fictitious global sign language called 'sgn'. Of course, there is no
global sign language, so sign languages now have their own language
codes.
>>> Language.get('sgn-US')
Language.make(language='ase')
>>> Language.get('sgn-US', normalize=False)
Language.make(language='sgn', territory='US')
'en-gb-oed' is a tag that's grandfathered into the standard because it
has been used to mean "spell-check this with Oxford English Dictionary
spelling", but that tag has the wrong shape. We interpret this as the
new standardized tag 'en-gb-oxendict', unless asked not to normalize.
>>> Language.get('en-gb-oed')
Language.make(language='en', territory='GB', variants=['oxendict'])
>>> Language.get('en-gb-oed', normalize=False)
Language.make(language='en-gb-oed')
'zh-min-nan' is another oddly-formed tag, used to represent the
Southern Min language, which includes Taiwanese as a regional form. It
now has its own language code.
>>> Language.get('zh-min-nan')
Language.make(language='nan')
The vague tag 'zh-min' is now also interpreted as 'nan', with a private
extension indicating that it had a different form:
>>> Language.get('zh-min')
Language.make(language='nan', private='x-zh-min')
Occasionally Wiktionary will use 'extlang' tags in strange ways, such
as using the tag 'und-ibe' for some unspecified Iberian language.
>>> Language.get('und-ibe')
Language.make(extlangs=['ibe'])
Here's an example of replacing multiple deprecated tags.
The language tag 'sh' (Serbo-Croatian) ended up being politically
problematic, and different standards took different steps to address
this. The IANA made it into a macrolanguage that contains 'sr', 'hr',
and 'bs'. Unicode further decided that it's a legacy tag that should
be interpreted as 'sr-Latn', which the language matching rules say
is mutually intelligible with all those languages.
We complicate the example by adding on the territory tag 'QU', an old
provisional tag for the European Union, which is now standardized as
'EU'.
>>> Language.get('sh-QU')
Language.make(language='sr', script='Latn', territory='EU')
'''
pass
def to_tag(self) -> str:
'''
Convert a Language back to a standard language tag, as a string.
This is also the str() representation of a Language object.
>>> Language.make(language='en', territory='GB').to_tag()
'en-GB'
>>> Language.make(language='yue', script='Hant', territory='HK').to_tag()
'yue-Hant-HK'
>>> Language.make(script='Arab').to_tag()
'und-Arab'
>>> str(Language.make(territory='IN'))
'und-IN'
'''
pass
def simplify_script(self) -> 'Language':
'''
Remove the script from some parsed language data, if the script is
redundant with the language.
>>> Language.make(language='en', script='Latn').simplify_script()
Language.make(language='en')
>>> Language.make(language='yi', script='Latn').simplify_script()
Language.make(language='yi', script='Latn')
>>> Language.make(language='yi', script='Hebr').simplify_script()
Language.make(language='yi')
'''
pass
def assume_script(self) -> 'Language':
'''
Fill in the script if it's missing, and if it can be assumed from the
language subtag. This is the opposite of `simplify_script`.
>>> Language.make(language='en').assume_script()
Language.make(language='en', script='Latn')
>>> Language.make(language='yi').assume_script()
Language.make(language='yi', script='Hebr')
>>> Language.make(language='yi', script='Latn').assume_script()
Language.make(language='yi', script='Latn')
This fills in nothing when the script cannot be assumed -- such as when
the language has multiple scripts, or it has no standard orthography:
>>> Language.make(language='sr').assume_script()
Language.make(language='sr')
>>> Language.make(language='eee').assume_script()
Language.make(language='eee')
It also doesn't fill anything in when the language is unspecified.
>>> Language.make(territory='US').assume_script()
Language.make(territory='US')
'''
pass
def prefer_macrolanguage(self) -> 'Language':
'''
BCP 47 doesn't specify what to do with macrolanguages and the languages
they contain. The Unicode CLDR, on the other hand, says that when a
macrolanguage has a dominant standardized language, the macrolanguage
code should be used for that language. For example, Mandarin Chinese
is 'zh', not 'cmn', according to Unicode, and Malay is 'ms', not 'zsm'.
This isn't a rule you'd want to follow in all cases -- for example, you may
want to be able to specifically say that 'ms' (the Malay macrolanguage)
contains both 'zsm' (Standard Malay) and 'id' (Indonesian). But applying
this rule helps when interoperating with the Unicode CLDR.
So, applying `prefer_macrolanguage` to a Language object will
return a new object, replacing the language with the macrolanguage if
it is the dominant language within that macrolanguage. It will leave
non-dominant languages that have macrolanguages alone.
>>> Language.get('arb').prefer_macrolanguage()
Language.make(language='ar')
>>> Language.get('cmn-Hant').prefer_macrolanguage()
Language.make(language='zh', script='Hant')
>>> Language.get('yue-Hant').prefer_macrolanguage()
Language.make(language='yue', script='Hant')
'''
pass
def to_alpha3(self, variant: str = 'T') -> str:
'''
Get the three-letter language code for this language, even if it's
canonically written with a two-letter code.
These codes are the 'alpha3' codes defined by ISO 639-2.
When this function returns, it always returns a 3-letter string. If
there is no known alpha3 code for the language, it raises a LookupError.
In cases where the distinction matters, we default to the 'terminology'
code. You can pass `variant='B'` to get the 'bibliographic' code instead.
For example, the terminology code for German is 'deu', while the
bibliographic code is 'ger'.
(The confusion between these two sets of codes is a good reason to avoid
using alpha3 codes. Every language that has two different alpha3 codes
also has an alpha2 code that's preferred, such as 'de' for German.)
>>> Language.get('fr').to_alpha3()
'fra'
>>> Language.get('fr-CA').to_alpha3()
'fra'
>>> Language.get('fr').to_alpha3(variant='B')
'fre'
>>> Language.get('de').to_alpha3(variant='T')
'deu'
>>> Language.get('ja').to_alpha3()
'jpn'
>>> Language.get('un').to_alpha3()
Traceback (most recent call last):
...
LookupError: 'un' is not a known language code, and has no alpha3 code.
All valid two-letter language codes have corresponding alpha3 codes,
even the un-normalized ones. If they were assigned an alpha3 code by ISO
before they were assigned a normalized code by CLDR, these codes may be
different:
>>> Language.get('tl', normalize=False).to_alpha3()
'tgl'
>>> Language.get('tl').to_alpha3()
'fil'
>>> Language.get('sh', normalize=False).to_alpha3()
'hbs'
Three-letter codes are preserved, even if they're unknown:
>>> Language.get('qqq').to_alpha3()
'qqq'
>>> Language.get('und').to_alpha3()
'und'
'''
pass
def broader_tags(self) -> List[str]:
'''
Iterate through increasingly general tags for this language.
This isn't actually that useful for matching two arbitrary language tags
against each other, but it is useful for matching them against a known
standardized form, such as in the CLDR data.
The list of broader versions to try appears in UTR 35, section 4.3,
"Likely Subtags".
>>> Language.get('nn-Latn-NO-x-thingy').broader_tags()
['nn-Latn-NO-x-thingy', 'nn-Latn-NO', 'nn-NO', 'nn-Latn', 'nn', 'und-Latn', 'und']
>>> Language.get('arb-Arab').broader_tags()
['arb-Arab', 'ar-Arab', 'arb', 'ar', 'und-Arab', 'und']
'''
pass
def broaden(self) -> 'List[Language]':
'''
Like `broader_tags`, but returrns Language objects instead of strings.
'''
pass
def maximize(self) -> 'Language':
'''
The Unicode CLDR contains a "likelySubtags" data file, which can guess
reasonable values for fields that are missing from a language tag.
This is particularly useful for comparing, for example, "zh-Hant" and
"zh-TW", two common language tags that say approximately the same thing
via rather different information. (Using traditional Han characters is
not the same as being in Taiwan, but each implies that the other is
likely.)
These implications are provided in the CLDR supplemental data, and are
based on the likelihood of people using the language to transmit text
on the Internet. (This is why the overall default is English, not
Chinese.)
It's important to recognize that these tags amplify majorities, and
that not all language support fits into a "likely" language tag.
>>> str(Language.get('zh-Hant').maximize())
'zh-Hant-TW'
>>> str(Language.get('zh-TW').maximize())
'zh-Hant-TW'
>>> str(Language.get('ja').maximize())
'ja-Jpan-JP'
>>> str(Language.get('pt').maximize())
'pt-Latn-BR'
>>> str(Language.get('und-Arab').maximize())
'ar-Arab-EG'
>>> str(Language.get('und-CH').maximize())
'de-Latn-CH'
As many standards are, this is US-centric:
>>> str(Language.make().maximize())
'en-Latn-US'
"Extlangs" have no likely-subtags information, so they will give
maximized results that make no sense:
>>> str(Language.get('und-ibe').maximize())
'en-ibe-Latn-US'
'''
pass
def match_score(self, supported: 'Language') -> int:
'''
DEPRECATED: use .distance() instead, which uses newer data and is _lower_
for better matching languages.
'''
pass
def distance(self, supported: 'Language', ignore_script: bool = False) -> int:
'''
Suppose that `self` is the language that the user desires, and
`supported` is a language that is actually supported.
This method returns a number from 0 to 134 measuring the 'distance'
between the languages (lower numbers are better). This is not a
symmetric relation. If `ignore_script` is `True`, the script will
not be used in the comparison, possibly resulting in a smaller
'distance'.
The language distance is not really about the linguistic similarity or
history of the languages; instead, it's based largely on sociopolitical
factors, indicating which language speakers are likely to know which
other languages in the present world. Much of the heuristic is about
finding a widespread 'world language' like English, Chinese, French, or
Russian that speakers of a more localized language will accept.
A version that works on language tags, as strings, is in the function
`tag_distance`. See that function for copious examples.
'''
pass
def is_valid(self) -> bool:
'''
Checks whether the language, script, territory, and variants
(if present) are all tags that have meanings assigned by IANA.
For example, 'ja' (Japanese) is a valid tag, and 'jp' is not.
The data is current as of CLDR 40.
>>> Language.get('ja').is_valid()
True
>>> Language.get('jp').is_valid()
False
>>> Language.get('en-001').is_valid()
True
>>> Language.get('en-000').is_valid()
False
>>> Language.get('en-Latn').is_valid()
True
>>> Language.get('en-Latnx').is_valid()
False
>>> Language.get('und').is_valid()
True
>>> Language.get('en-GB-oxendict').is_valid()
True
>>> Language.get('en-GB-oxenfree').is_valid()
False
>>> Language.get('x-heptapod').is_valid()
True
Some scripts are, confusingly, not included in CLDR's 'validity' pattern.
If a script appears in the IANA registry, we consider it valid.
>>> Language.get('ur-Aran').is_valid()
True
>>> Language.get('cu-Cyrs').is_valid()
True
A language tag with multiple extlangs will parse, but is not valid.
The only allowed example is 'zh-min-nan', which normalizes to the
language 'nan'.
>>> Language.get('zh-min-nan').is_valid()
True
>>> Language.get('sgn-ase-bfi').is_valid()
False
These examples check that duplicate tags are not valid:
>>> Language.get('de-1901').is_valid()
True
>>> Language.get('de-1901-1901').is_valid()
False
>>> Language.get('en-a-bbb-c-ddd').is_valid()
True
>>> Language.get('en-a-bbb-a-ddd').is_valid()
False
Of course, you should be prepared to catch a failure to parse the
language code at all:
>>> Language.get('C').is_valid()
Traceback (most recent call last):
...
langcodes.tag_parser.LanguageTagError: Expected a language code, got 'c'
'''
pass
def has_name_data(self) -> bool:
'''
Return True when we can name languages in this language. Requires
`language_data` to be installed.
This is true when the language, or one of its 'broader' versions, is in
the list of CLDR target languages.
>>> Language.get('fr').has_name_data()
True
>>> Language.get('so').has_name_data()
True
>>> Language.get('enc').has_name_data()
False
>>> Language.get('und').has_name_data()
False
'''
pass
def _get_name(
self, attribute: str, language: Union[str, 'Language'], max_distance: int
) -> str:
pass
def _best_name(
self, names: Mapping[str, str], language: 'Language', max_distance: int
):
pass
def language_name(
self,
language: Union[str, 'Language'] = DEFAULT_LANGUAGE,
max_distance: int = 25,
) -> str:
'''
Give the name of the language (not the entire tag, just the language part)
in a natural language. The target language can be given as a string or
another Language object.
By default, things are named in English:
>>> Language.get('fr').language_name()
'French'
>>> Language.get('el').language_name()
'Greek'
But you can ask for language names in numerous other languages:
>>> Language.get('fr').language_name('fr')
'français'
>>> Language.get('el').language_name('fr')
'grec'
Why does everyone get Slovak and Slovenian confused? Let's ask them.
>>> Language.get('sl').language_name('sl')
'slovenščina'
>>> Language.get('sk').language_name('sk')
'slovenčina'
>>> Language.get('sl').language_name('sk')
'slovinčina'
>>> Language.get('sk').language_name('sl')
'slovaščina'
'''
pass
def display_name(
self,
language: Union[str, 'Language'] = DEFAULT_LANGUAGE,
max_distance: int = 25,
) -> str:
'''
It's often helpful to be able to describe a language code in a way that a user
(or you) can understand, instead of in inscrutable short codes. The
`display_name` method lets you describe a Language object *in a language*.
The `.display_name(language, min_score)` method will look up the name of the
language. The names come from the IANA language tag registry, which is only in
English, plus CLDR, which names languages in many commonly-used languages.
The default language for naming things is English:
>>> Language.make(language='fr').display_name()
'French'
>>> Language.make().display_name()
'Unknown language'
>>> Language.get('zh-Hans').display_name()
'Chinese (Simplified)'
>>> Language.get('en-US').display_name()
'English (United States)'
But you can ask for language names in numerous other languages:
>>> Language.get('fr').display_name('fr')
'français'
>>> Language.get('fr').display_name('es')
'francés'
>>> Language.make().display_name('es')
'lengua desconocida'
>>> Language.get('zh-Hans').display_name('de')
'Chinesisch (Vereinfacht)'
>>> Language.get('en-US').display_name('zh-Hans')
'英语(美国)'
'''
pass
def _display_pattern(self) -> str:
'''
Get the pattern, according to CLDR, that should be used for clarifying
details of a language code.
'''
pass
def _display_separator(self) -> str:
'''
Get the symbol that should be used to separate multiple clarifying
details -- such as a comma in English, or an ideographic comma in
Japanese.
Requires that `language_data` is installed.
'''
pass
def autonym(self, max_distance: int = 9) -> str:
'''
Give the display name of this language *in* this language.
Requires that `language_data` is installed.
>>> Language.get('fr').autonym()
'français'
>>> Language.get('es').autonym()
'español'
>>> Language.get('ja').autonym()
'日本語'
This uses the `display_name()` method, so it can include the name of a
script or territory when appropriate.
>>> Language.get('en-AU').autonym()
'English (Australia)'
>>> Language.get('sr-Latn').autonym()
'srpski (latinica)'
>>> Language.get('sr-Cyrl').autonym()
'српски (ћирилица)'
>>> Language.get('pa').autonym()
'ਪੰਜਾਬੀ'
>>> Language.get('pa-Arab').autonym()
'پنجابی (عربی)'
This only works for language codes that CLDR has locale data for. You
can't ask for the autonym of 'ja-Latn' and get 'nihongo (rōmaji)'.
'''
pass
def script_name(
self,
language: Union[str, 'Language'] = DEFAULT_LANGUAGE,
max_distance: int = 25,
) -> str:
'''
Describe the script part of the language tag in a natural language.
Requires that `language_data` is installed.
'''
pass
def territory_name(
self,
language: Union[str, 'Language'] = DEFAULT_LANGUAGE,
max_distance: int = 25,
) -> str:
'''
Describe the territory part of the language tag in a natural language.
Requires that `language_data` is installed.
'''
pass
def region_name(
self,
language: Union[str, 'Language'] = DEFAULT_LANGUAGE,
max_distance: int = 25,
) -> str:
pass
@property
def region_name(
self,
language: Union[str, 'Language'] = DEFAULT_LANGUAGE,
max_distance: int = 25,
) -> str:
pass
def variant_names(
self,
language: Union[str, 'Language'] = DEFAULT_LANGUAGE,
max_distance: int = 25,
) -> Sequence[str]:
'''
Deprecated in version 3.0.
We don't store names for variants anymore, so this just returns the list
of variant codes, such as ['oxendict'] for en-GB-oxendict.
'''
pass
def describe(
self,
language: Union[str, 'Language'] = DEFAULT_LANGUAGE,
max_distance: int = 25,
) -> dict:
'''
Return a dictionary that describes a given language tag in a specified
natural language. Requires that `language_data` is installed.
See `language_name` and related methods for more specific versions of this.
The desired `language` will in fact be matched against the available
options using the matching technique that this module provides. We can
illustrate many aspects of this by asking for a description of Shavian
script (a phonetic script for English devised by author George Bernard
Shaw), and where you might find it, in various languages.
>>> shaw = Language.make(script='Shaw').maximize()
>>> shaw.describe('en')
{'language': 'English', 'script': 'Shavian', 'territory': 'United Kingdom'}
>>> shaw.describe('fr')
{'language': 'anglais', 'script': 'shavien', 'territory': 'Royaume-Uni'}
>>> shaw.describe('es')
{'language': 'inglés', 'script': 'shaviano', 'territory': 'Reino Unido'}
>>> shaw.describe('pt')
{'language': 'inglês', 'script': 'shaviano', 'territory': 'Reino Unido'}
>>> shaw.describe('uk')
{'language': 'англійська', 'script': 'шоу', 'territory': 'Велика Британія'}
>>> shaw.describe('arb')
{'language': 'الإنجليزية', 'script': 'الشواني', 'territory': 'المملكة المتحدة'}
>>> shaw.describe('th')
{'language': 'อังกฤษ', 'script': 'ซอเวียน', 'territory': 'สหราชอาณาจักร'}
>>> shaw.describe('zh-Hans')
{'language': '英语', 'script': '萧伯纳式文', 'territory': '英国'}
>>> shaw.describe('zh-Hant')
{'language': '英文', 'script': '簫柏納字符', 'territory': '英國'}
>>> shaw.describe('ja')
{'language': '英語', 'script': 'ショー文字', 'territory': 'イギリス'}
When we don't have a localization for the language, we fall back on English,
because the IANA provides names for all known codes in English.
>>> shaw.describe('lol')
{'language': 'English', 'script': 'Shavian', 'territory': 'United Kingdom'}
When the language tag itself is a valid tag but with no known meaning, we
say so in the appropriate language.
>>> Language.get('xyz-ZY').display_name()
'Unknown language [xyz] (Unknown Region [ZY])'
>>> Language.get('xyz-ZY').display_name('es')
'lengua desconocida [xyz] (Región desconocida [ZY])'
'''
pass
def speaking_population(self) -> int:
'''
Get an estimate of how many people in the world speak this language,
derived from CLDR data. Requires that `language_data` is installed.
Only the language and territory codes will be considered. If a
territory code is included, the population will count only the
speakers of the language in that territory.
Script subtags are disregarded, because it doesn't make sense to ask
how many people speak in a particular writing script.
>>> Language.get('es').speaking_population()
493528077
>>> Language.get('pt').speaking_population()
237496885
>>> Language.get('es-BR').speaking_population()
76218
>>> Language.get('pt-BR').speaking_population()
192661560
>>> Language.get('vo').speaking_population()
0
'''
pass
def writing_population(self) -> int:
'''
Get an estimate of how many people in the world read and write
this language, derived from CLDR data. Requires that `language_data`
is installed.
For many languages that aren't typically written, this is an
overestimate, according to CLDR -- the data often includes people who
speak that language but write in a different language.
Only the language, script, and territory codes will be considered.
If a territory code is included, the population will count only the
speakers of the language in that territory.
>>> all = Language.get('zh').writing_population()
>>> all
1240841517
>>> traditional = Language.get('zh-Hant').writing_population()
>>> traditional
36863340
>>> simplified = Language.get('zh-Hans').writing_population()
>>> all == traditional + simplified
True
>>> Language.get('zh-Hant-HK').writing_population()
6439733
>>> Language.get('zh-Hans-HK').writing_population()
338933
Note that if you want to get the total Chinese writing population
of Hong Kong, you need to avoid normalization that would interpret
'zh-HK' as 'zh-Hant-HK'.
>>> Language.get('zh-HK', normalize=False).writing_population()
6778666
Unknown or unspecified language codes get a population of 0.
>>> Language.get('xyz').writing_population()
0
>>> Language.get('und').writing_population()
0
'''
pass
@staticmethod
def find_name(
tagtype: str, name: str, language: Optional[Union[str, 'Language']] = None
) -> 'Language':
'''
Find the subtag of a particular `tagtype` that has the given `name`.
Requires that `language_data` is installed.
The default language, "und", will allow matching names in any language,
so you can get the code 'fr' by looking up "French", "Français", or
"francés".
Occasionally, names are ambiguous in a way that can be resolved by
specifying what name the language is supposed to be in. For example,
there is a language named 'Malayo' in English, but it's different from
the language named 'Malayo' in Spanish (which is Malay). Specifying the
language will look up the name in a trie that is only in that language.
In a previous version, we thought we were going to deprecate the
`language` parameter, as there weren't significant cases of conflicts
in names of things between languages. Well, we got more data, and
conflicts in names are everywhere.
Specifying the language that the name should be in is still not
required, but it will help to make sure that names can be
round-tripped.
>>> Language.find_name('language', 'francés')
Language.make(language='fr')
>>> Language.find_name('territory', 'United Kingdom')
Language.make(territory='GB')
>>> Language.find_name('script', 'Arabic')
Language.make(script='Arab')
>>> Language.find_name('language', 'norsk bokmål')
Language.make(language='nb')
>>> Language.find_name('language', 'norsk')
Language.make(language='no')
>>> Language.find_name('language', 'norsk', 'en')
Traceback (most recent call last):
...
LookupError: Can't find any language named 'norsk'
>>> Language.find_name('language', 'norsk', 'no')
Language.make(language='no')
>>> Language.find_name('language', 'malayo', 'en')
Language.make(language='mbp')
>>> Language.find_name('language', 'malayo', 'es')
Language.make(language='ms')
Some language names resolve to more than a language. For example,
the name 'Brazilian Portuguese' resolves to a language and a territory,
and 'Simplified Chinese' resolves to a language and a script. In these
cases, a Language object with multiple subtags will be returned.
>>> Language.find_name('language', 'Brazilian Portuguese', 'en')
Language.make(language='pt', territory='BR')
>>> Language.find_name('language', 'Simplified Chinese', 'en')
Language.make(language='zh', script='Hans')
A small amount of fuzzy matching is supported: if the name can be
shortened to match a single language name, you get that language.
This allows, for example, "Hakka dialect" to match "Hakka".
>>> Language.find_name('language', 'Hakka dialect')
Language.make(language='hak')
'''
pass
@staticmethod
def find_name(
tagtype: str, name: str, language: Optional[Union[str, 'Language']] = None
) -> 'Language':
'''
A concise version of `find_name`, used to get a language tag by its
name in a natural language. The language can be omitted in the large
majority of cases, where the language name is not ambiguous.
>>> Language.find('Türkçe')
Language.make(language='tr')
>>> Language.find('brazilian portuguese')
Language.make(language='pt', territory='BR')
>>> Language.find('simplified chinese')
Language.make(language='zh', script='Hans')
Some language names are ambiguous: for example, there is a language
named 'Fala' in English (with code 'fax'), but 'Fala' is also the
Kwasio word for French. In this case, specifying the language that
the name is in is necessary for disambiguation.
>>> Language.find('fala')
Language.make(language='fr')
>>> Language.find('fala', 'nmg')
Language.make(language='fr')
>>> Language.find('fala', 'en')
Language.make(language='fax')
'''
pass
def to_dict(self) -> dict:
'''
Get a dictionary of the attributes of this Language object, which
can be useful for constructing a similar object.
'''
pass
def update(self, other: 'Language') -> 'Language':
'''
Update this Language with the fields of another Language.
'''
pass
def update_dict(self, newdata: dict) -> 'Language':
'''
Update the attributes of this Language from a dictionary.
'''
pass
@staticmethod
def _filter_keys(d: dict, keys: Iterable[str]) -> dict:
'''
Select a subset of keys from a dictionary.
'''
pass
def _filter_attributes(self, keyset: Iterable[str]) -> 'Language':
'''
Return a copy of this object with a subset of its attributes set.
'''
pass
def _searchable_form(self) -> 'Language':
'''
Convert a parsed language tag so that the information it contains is in
the best form for looking up information in the CLDR.
'''
pass
def __eq__(self, other):
pass
def __hash__(self) -> int:
pass
def __getitem__(self, key: str) -> Optional[Union[str, List[str]]]:
pass
def __contains__(self, key: str) -> bool:
pass
def __repr__(self) -> str:
pass
def __str__(self) -> str:
pass
| 51 | 35 | 31 | 5 | 12 | 15 | 3 | 1.18 | 0 | 13 | 0 | 0 | 39 | 17 | 44 | 44 | 1,482 | 254 | 564 | 194 | 453 | 664 | 381 | 134 | 330 | 16 | 0 | 4 | 145 |
147,586 |
LuminosoInsight/langcodes
|
LuminosoInsight_langcodes/langcodes/tag_parser.py
|
langcodes.tag_parser.LanguageTagError
|
class LanguageTagError(ValueError):
pass
|
class LanguageTagError(ValueError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
147,587 |
LuminosoInsight/luminoso-api-client-python
|
LuminosoInsight_luminoso-api-client-python/luminoso_api/v5_client.py
|
luminoso_api.v5_client.LuminosoClient
|
class LuminosoClient(object):
"""
A tool for making authenticated requests to the Luminoso API version 5.
A LuminosoClient is a thin wrapper around the API documented at
https://daylight.luminoso.com/api/v5/. As such, you interact with it by
calling its methods that correspond to HTTP methods: `.get(url)`,
`.post(url)`, `.put(url)`, `.patch(url)`, and `.delete(url)`.
These URLs are relative to a 'base URL' for the LuminosoClient. For
example, you can make requests for a specific project by creating a
LuminosoClient for
`https://daylight.luminoso.com/api/v5/projects/<project_id>`.
Methods take parameters as keyword arguments, and encode them in the
appropriate way for the request, which is described in the individual
documentation for each method.
The easiest way to create a LuminosoClient is using the
`LuminosoClient.connect()` static method.
In addition to the base URL, the LuminosoClient has a `root_url`,
pointing to the root of the API, such as
https://daylight.luminoso.com/api/v5. This is used, for example, as a
starting point for the `client_for_path` method: when it gets a path
starting with `/`, it will go back to the `root_url` instead of adding to
the existing URL.
"""
_URL_BASE = URL_BASE
def __init__(self, session, url, user_agent_suffix=None, timeout=None):
"""
Create a LuminosoClient given an existing Session object that has a
_TokenAuth object as its .auth attribute.
It is probably easier to call LuminosoClient.connect() to handle
the authentication for you.
"""
self.session = session
self.timeout = timeout
self.url = ensure_trailing_slash(url)
# Don't warn this time; warning happened in connect()
self.root_url = self.get_root_url(url, warn=False)
# Calculate the full user agent suffix, but also store the suffix so it
# can be preserved by client_for_path().
self._user_agent_suffix = user_agent_suffix
self.user_agent = 'LuminosoClient/' + VERSION
if user_agent_suffix is not None:
self.user_agent += ' ' + user_agent_suffix
def __repr__(self):
return '<LuminosoClient for %s>' % self.url
@classmethod
def connect(cls, url=None, token_file=None, token=None,
user_agent_suffix=None, timeout=None):
"""
Returns an object that makes requests to the API, authenticated
with a saved or specified long-lived token, at URLs beginning with
`url`.
If no URL is specified, or if the specified URL is a path such as
'/projects' without a scheme and domain, the client will default to
https://daylight.luminoso.com/api/v5/.
If neither token nor token_file are specified, the client will look
for a token in $HOME/.luminoso/tokens.json. The file should contain
a single json dictionary of the format
`{'root_url': 'token', 'root_url2': 'token2', ...}`.
Requests made with this client will have the user agent
"LuminosoClient" and the version number. You can optionally pass a
string to be appended to this, though for most uses of the client this
is unnecessary.
"""
if url is None:
url = '/'
if url.startswith('http'):
root_url = cls.get_root_url(url)
else:
url = cls._URL_BASE + '/' + url.lstrip('/')
root_url = cls._URL_BASE
if token is None:
token_file = token_file or get_token_filename()
try:
with open(token_file) as tf:
token_dict = json.load(tf)
except FileNotFoundError:
raise LuminosoAuthError('No token file at %s' % token_file)
netloc = urlparse(root_url).netloc
try:
token = token_dict[netloc]
except KeyError:
# Some code to help people transition from using URLs with
# "analytics" to URLs with "daylight" by looking for a token
# with the old URL and using it if it exists
legacy_netloc = netloc.replace('daylight', 'analytics')
if legacy_netloc in token_dict:
logger.warning('Using token for legacy domain %s; saving it'
' for %s', legacy_netloc, netloc)
token = token_dict[legacy_netloc]
cls.save_token(token, domain=netloc,
token_file=token_file)
else:
raise LuminosoAuthError('No token stored for %s' % root_url)
session = requests.session()
session.auth = _TokenAuth(token)
# By default, requests will only retry things like connection timeouts,
# not any server responses. We use urllib3's Retry class to say that,
# if a call failed specifically on a 429 ("too many requests"), wait a
# full second and try again. (Technically it tries again immediately,
# but then it gets another 429 and tries again at twice the backoff
# factor.) The total retries is 10, which is 256 seconds (four
# minutes, 16 seconds; or a cumulative wait of 8.5 minutes).
retry_strategy = Retry(total=10, backoff_factor=.5,
status_forcelist=[429])
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("https://", adapter)
session.mount("http://", adapter)
return cls(session, url, user_agent_suffix=user_agent_suffix,
timeout=timeout)
@classmethod
def save_token(cls, token=None, domain='daylight.luminoso.com',
token_file=None):
"""
Take a long-lived API token and store it to a local file. Long-lived
tokens *should* be retrieved through the UI and specified as the
`token` argument to this method. As a dispreferred alternative, if no
token is specified, you will be prompted for a username and password
and a new token will be created and saved.
Other optional arguments are the domain for which the token is valid
and the file in which to store the token.
"""
# Make this as friendly as possible: turn any of
# "daylight.luminoso.com", "daylight.luminoso.com/api/v5", or
# "https://daylight.luminoso.com/" into just the domain
if '://' in domain:
parsed = urlparse(domain)
domain = parsed.netloc
protocol = parsed.scheme
else:
domain = domain.split('/')[0]
protocol = None
if token is None:
if domain == 'daylight.luminoso.com':
protocol = 'https'
while protocol is None:
prompt = input('Use https? (y/n, default=y): ').lower()
if not prompt or prompt.startswith('y'):
protocol = 'https'
elif prompt.startswith('n'):
protocol = 'http'
url = f'{protocol}://{domain}/'
username = input('Username: ')
password = getpass('Password: ')
session = requests.session()
headers = {'user-agent': f'LuminosoClient/{VERSION} save_token()',
'Content-Type': 'application/json'}
temp_token_resp = session.post(
url.rstrip('/') + '/api/v5/login/', headers=headers,
data=json.dumps({'username': username, 'password': password})
)
temp_token_resp.raise_for_status()
temp_token = temp_token_resp.json()['token']
headers = {**headers, 'Authorization': 'Token ' + temp_token}
token_resp = session.post(
url.rstrip('/') + '/api/v5/tokens/',
data=json.dumps(
{'password': password,
'description': ('token created through'
' LuminosoClient.save_token()')}
),
headers=headers,
)
token_resp.raise_for_status()
token = token_resp.json()['token']
headers.pop('Content-Type')
session.post(url.rstrip('/') + '/api/v5/logout/', headers=headers)
token_file = token_file or get_token_filename()
if os.path.exists(token_file):
saved_tokens = json.load(open(token_file))
else:
saved_tokens = {}
saved_tokens[domain] = token
directory, filename = os.path.split(token_file)
if directory and not os.path.exists(directory):
os.makedirs(directory)
with open(token_file, 'w') as f:
json.dump(saved_tokens, f)
def _request(self, req_type, url, **kwargs):
"""
Make a request via the `requests` module. If the result has an HTTP
error status, convert that to a Python exception.
"""
kwargs.setdefault('headers', {})['user-agent'] = self.user_agent
if self.timeout is not None:
kwargs['timeout'] = self.timeout
logger.debug('%s %s' % (req_type, url))
try:
result = self.session.request(req_type, url, **kwargs)
try:
result.raise_for_status()
except requests.HTTPError:
error = result.text
try:
error = json.loads(error)
except ValueError:
pass
if result.status_code in (401, 403):
error_class = LuminosoAuthError
elif result.status_code in (400, 404, 405):
error_class = LuminosoClientError
elif result.status_code >= 500:
error_class = LuminosoServerError
else:
error_class = LuminosoError
raise error_class(error)
except requests.Timeout:
raise LuminosoTimeoutError()
return result
def _json_request(self, req_type, url, **kwargs):
"""
Make a request of the specified type and expect a JSON object in
response.
"""
response = self._request(req_type, url, **kwargs)
try:
json_response = response.json()
except ValueError:
logger.error("Received response with no JSON: %s %s" %
(response, response.content))
raise LuminosoError('Response body contained no JSON.')
return json_response
# Simple REST operations
def get(self, path='', **params):
"""
Make a GET request to the given path, and return the JSON-decoded
result.
Keyword parameters will be converted to URL parameters.
GET requests are requests that retrieve information without changing
anything on the server.
"""
params = jsonify_parameters(params)
url = ensure_trailing_slash(self.url + path.lstrip('/'))
return self._json_request('get', url, params=params)
def post(self, path='', **params):
"""
Make a POST request to the given path, and return the JSON-decoded
result.
Keyword parameters will be converted to form values, sent in the body
of the POST.
POST requests are requests that cause a change on the server,
especially those that ask to create and return an object of some kind.
"""
url = ensure_trailing_slash(self.url + path.lstrip('/'))
return self._json_request('post', url, data=json.dumps(params),
headers={'Content-Type': 'application/json'})
def put(self, path='', **params):
"""
Make a PUT request to the given path, and return the JSON-decoded
result.
Keyword parameters will be converted to form values, sent in the body
of the PUT.
PUT requests are usually requests to *update* the object represented by
this URL. Unlike POST requests, PUT requests can be safely duplicated.
"""
url = ensure_trailing_slash(self.url + path.lstrip('/'))
return self._json_request('put', url, data=json.dumps(params),
headers={'Content-Type': 'application/json'})
def patch(self, path='', **params):
"""
Make a PATCH request to the given path, and return the JSON-decoded
result.
Keyword parameters will be converted to form values, sent in the body
of the PATCH.
PATCH requests are usually requests to make *small fixes* to the
object represented by this URL.
"""
url = ensure_trailing_slash(self.url + path.lstrip('/'))
return self._json_request('patch', url, data=json.dumps(params),
headers={'Content-Type': 'application/json'})
def delete(self, path='', **params):
"""
Make a DELETE request to the given path, and return the JSON-decoded
result.
Keyword parameters will be converted to URL parameters.
DELETE requests ask to delete the object represented by this URL.
"""
params = jsonify_parameters(params)
url = ensure_trailing_slash(self.url + path.lstrip('/'))
return self._json_request('delete', url, params=params)
# Useful abstractions
def client_for_path(self, path):
"""
Returns a new client with the same root URL and authentication, but
a different specific URL. For instance, if you have a client pointed
at https://daylight.luminoso.com/api/v5/, and you want new ones for
Project A and Project B, you would call:
client_a = client.client_for_path('projects/<project_id_a>')
client_b = client.client_for_path('projects/<project_id_b>')
and your base client would remian unchanged.
Paths with leading slashes are appended to the root url; otherwise,
paths are set relative to the current path.
"""
if path.startswith('/'):
url = self.root_url + path
else:
url = self.url + path
return self.__class__(
self.session, url, user_agent_suffix=self._user_agent_suffix
)
def change_path(self, path):
"""
A deprecated alias for client_for_path(path), included only for
backward compatibility.
"""
logger.warning('The change_path method has been renamed to'
' client_for_path.')
return self.client_for_path(path)
def upload(self, path, docs, **params):
"""
A deprecated alias for post(path, docs=docs), included only for
backward compatibility.
"""
logger.warning('The upload method is deprecated; use post instead.')
return self.post(path, docs=docs)
def wait_for_build(self, interval=5, path=None):
"""
A convenience method designed to inform you when a project build has
completed, not counting the post-build sentiment step. This makes most
API calls available, other than those requiring sentiment.
It polls the API every `interval` seconds until there is not a build
running. At that point, it returns the "last_build_info" field of the
project record if the build succeeded, and raises a LuminosoError with
the field as its message if the build failed.
If a `path` is not specified, this method will assume that its URL is
the URL for the project. Otherwise, it will use the specified path
(which should be "/projects/<project_id>/").
"""
return self._wait_for_build(interval=interval, path=path)
def wait_for_sentiment_build(self, interval=30, path=None):
"""
A convenience method designed to inform you when a project build has
completed, including the sentiment build. Otherwise identical to
`wait_for_build`.
"""
return self._wait_for_build(interval=interval, path=path,
wait_for_sentiment=True)
def _wait_for_build(self, interval=5, path=None, wait_for_sentiment=False):
path = path or ''
start = time.time()
next_log = 0
while True:
response = self.get(path)['last_build_info']
if not response:
raise ValueError('This project is not building!')
if wait_for_sentiment and not response['sentiment']:
raise ValueError('This project is not building sentiment!')
# _check_for_completion() raises a LuminosoError if the build
# failed; we catch it and raise a new one so that we can include
# the entire response, and not just the internal sentiment
# response, in the case where it's the sentiment check that fails
try:
if (self._check_for_completion(response) and
(not wait_for_sentiment or
self._check_for_completion(response['sentiment']))):
return response
except LuminosoError:
raise LuminosoError(response)
elapsed = time.time() - start
if elapsed > next_log:
logger.info('Still waiting (%d seconds elapsed).', next_log)
next_log += 120
time.sleep(interval)
@staticmethod
def _check_for_completion(status):
if status['stop_time']:
if status['success']:
return True
else:
raise LuminosoError
return False
def save_to_file(self, path, filename, **params):
"""
Saves binary content to a file with name filename. filename should
include the appropriate file extension, such as .xlsx or .txt, e.g.,
filename = 'sample.xlsx'.
Useful for downloading .xlsx files.
"""
url = ensure_trailing_slash(self.url + path.lstrip('/'))
content = self._request('get', url, params=params).content
with open(filename, 'wb') as f:
f.write(content)
@staticmethod
def get_root_url(url, warn=True):
"""
Get the "root URL" for a URL, as described in the LuminosoClient
documentation.
"""
parsed_url = urlparse(url)
# Make sure it's a complete URL, not a relative one
if not parsed_url.scheme:
raise ValueError('Please supply a full URL, beginning with http://'
' or https:// .')
# Issue a warning if the path didn't already start with /api/v5
root_url = '%s://%s/api/v5' % (parsed_url.scheme, parsed_url.netloc)
if warn and not parsed_url.path.startswith('/api/v5'):
logger.warning('Using %s as the root url' % root_url)
return root_url
|
class LuminosoClient(object):
'''
A tool for making authenticated requests to the Luminoso API version 5.
A LuminosoClient is a thin wrapper around the API documented at
https://daylight.luminoso.com/api/v5/. As such, you interact with it by
calling its methods that correspond to HTTP methods: `.get(url)`,
`.post(url)`, `.put(url)`, `.patch(url)`, and `.delete(url)`.
These URLs are relative to a 'base URL' for the LuminosoClient. For
example, you can make requests for a specific project by creating a
LuminosoClient for
`https://daylight.luminoso.com/api/v5/projects/<project_id>`.
Methods take parameters as keyword arguments, and encode them in the
appropriate way for the request, which is described in the individual
documentation for each method.
The easiest way to create a LuminosoClient is using the
`LuminosoClient.connect()` static method.
In addition to the base URL, the LuminosoClient has a `root_url`,
pointing to the root of the API, such as
https://daylight.luminoso.com/api/v5. This is used, for example, as a
starting point for the `client_for_path` method: when it gets a path
starting with `/`, it will go back to the `root_url` instead of adding to
the existing URL.
'''
def __init__(self, session, url, user_agent_suffix=None, timeout=None):
'''
Create a LuminosoClient given an existing Session object that has a
_TokenAuth object as its .auth attribute.
It is probably easier to call LuminosoClient.connect() to handle
the authentication for you.
'''
pass
def __repr__(self):
pass
@classmethod
def connect(cls, url=None, token_file=None, token=None,
user_agent_suffix=None, timeout=None):
'''
Returns an object that makes requests to the API, authenticated
with a saved or specified long-lived token, at URLs beginning with
`url`.
If no URL is specified, or if the specified URL is a path such as
'/projects' without a scheme and domain, the client will default to
https://daylight.luminoso.com/api/v5/.
If neither token nor token_file are specified, the client will look
for a token in $HOME/.luminoso/tokens.json. The file should contain
a single json dictionary of the format
`{'root_url': 'token', 'root_url2': 'token2', ...}`.
Requests made with this client will have the user agent
"LuminosoClient" and the version number. You can optionally pass a
string to be appended to this, though for most uses of the client this
is unnecessary.
'''
pass
@classmethod
def save_token(cls, token=None, domain='daylight.luminoso.com',
token_file=None):
'''
Take a long-lived API token and store it to a local file. Long-lived
tokens *should* be retrieved through the UI and specified as the
`token` argument to this method. As a dispreferred alternative, if no
token is specified, you will be prompted for a username and password
and a new token will be created and saved.
Other optional arguments are the domain for which the token is valid
and the file in which to store the token.
'''
pass
def _request(self, req_type, url, **kwargs):
'''
Make a request via the `requests` module. If the result has an HTTP
error status, convert that to a Python exception.
'''
pass
def _json_request(self, req_type, url, **kwargs):
'''
Make a request of the specified type and expect a JSON object in
response.
'''
pass
def get(self, path='', **params):
'''
Make a GET request to the given path, and return the JSON-decoded
result.
Keyword parameters will be converted to URL parameters.
GET requests are requests that retrieve information without changing
anything on the server.
'''
pass
def post(self, path='', **params):
'''
Make a POST request to the given path, and return the JSON-decoded
result.
Keyword parameters will be converted to form values, sent in the body
of the POST.
POST requests are requests that cause a change on the server,
especially those that ask to create and return an object of some kind.
'''
pass
def put(self, path='', **params):
'''
Make a PUT request to the given path, and return the JSON-decoded
result.
Keyword parameters will be converted to form values, sent in the body
of the PUT.
PUT requests are usually requests to *update* the object represented by
this URL. Unlike POST requests, PUT requests can be safely duplicated.
'''
pass
def patch(self, path='', **params):
'''
Make a PATCH request to the given path, and return the JSON-decoded
result.
Keyword parameters will be converted to form values, sent in the body
of the PATCH.
PATCH requests are usually requests to make *small fixes* to the
object represented by this URL.
'''
pass
def delete(self, path='', **params):
'''
Make a DELETE request to the given path, and return the JSON-decoded
result.
Keyword parameters will be converted to URL parameters.
DELETE requests ask to delete the object represented by this URL.
'''
pass
def client_for_path(self, path):
'''
Returns a new client with the same root URL and authentication, but
a different specific URL. For instance, if you have a client pointed
at https://daylight.luminoso.com/api/v5/, and you want new ones for
Project A and Project B, you would call:
client_a = client.client_for_path('projects/<project_id_a>')
client_b = client.client_for_path('projects/<project_id_b>')
and your base client would remian unchanged.
Paths with leading slashes are appended to the root url; otherwise,
paths are set relative to the current path.
'''
pass
def change_path(self, path):
'''
A deprecated alias for client_for_path(path), included only for
backward compatibility.
'''
pass
def upload(self, path, docs, **params):
'''
A deprecated alias for post(path, docs=docs), included only for
backward compatibility.
'''
pass
def wait_for_build(self, interval=5, path=None):
'''
A convenience method designed to inform you when a project build has
completed, not counting the post-build sentiment step. This makes most
API calls available, other than those requiring sentiment.
It polls the API every `interval` seconds until there is not a build
running. At that point, it returns the "last_build_info" field of the
project record if the build succeeded, and raises a LuminosoError with
the field as its message if the build failed.
If a `path` is not specified, this method will assume that its URL is
the URL for the project. Otherwise, it will use the specified path
(which should be "/projects/<project_id>/").
'''
pass
def wait_for_sentiment_build(self, interval=30, path=None):
'''
A convenience method designed to inform you when a project build has
completed, including the sentiment build. Otherwise identical to
`wait_for_build`.
'''
pass
def _wait_for_build(self, interval=5, path=None, wait_for_sentiment=False):
pass
@staticmethod
def _check_for_completion(status):
pass
def save_to_file(self, path, filename, **params):
'''
Saves binary content to a file with name filename. filename should
include the appropriate file extension, such as .xlsx or .txt, e.g.,
filename = 'sample.xlsx'.
Useful for downloading .xlsx files.
'''
pass
@staticmethod
def get_root_url(url, warn=True):
'''
Get the "root URL" for a URL, as described in the LuminosoClient
documentation.
'''
pass
| 25 | 18 | 20 | 2 | 11 | 7 | 3 | 0.73 | 1 | 12 | 6 | 0 | 16 | 6 | 20 | 20 | 456 | 59 | 229 | 76 | 202 | 168 | 186 | 67 | 165 | 9 | 1 | 3 | 54 |
147,588 |
LuminosoInsight/luminoso-api-client-python
|
LuminosoInsight_luminoso-api-client-python/luminoso_api/errors.py
|
luminoso_api.errors.LuminosoTimeoutError
|
class LuminosoTimeoutError(LuminosoError):
pass
|
class LuminosoTimeoutError(LuminosoError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
147,589 |
LuminosoInsight/luminoso-api-client-python
|
LuminosoInsight_luminoso-api-client-python/luminoso_api/v5_client.py
|
luminoso_api.v5_client._TokenAuth
|
class _TokenAuth(requests.auth.AuthBase):
"""
An object designed to attach to a requests.Session object to handle
Luminoso API authentication.
"""
def __init__(self, token):
self.token = token
def __call__(self, request):
request.headers['Authorization'] = 'Token ' + self.token
return request
|
class _TokenAuth(requests.auth.AuthBase):
'''
An object designed to attach to a requests.Session object to handle
Luminoso API authentication.
'''
def __init__(self, token):
pass
def __call__(self, request):
pass
| 3 | 1 | 3 | 0 | 3 | 0 | 1 | 0.67 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 11 | 1 | 6 | 4 | 3 | 4 | 6 | 4 | 3 | 1 | 1 | 0 | 2 |
147,590 |
LuminosoInsight/luminoso-api-client-python
|
LuminosoInsight_luminoso-api-client-python/luminoso_api/errors.py
|
luminoso_api.errors.LuminosoServerError
|
class LuminosoServerError(LuminosoError):
pass
|
class LuminosoServerError(LuminosoError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
147,591 |
LuminosoInsight/luminoso-api-client-python
|
LuminosoInsight_luminoso-api-client-python/luminoso_api/errors.py
|
luminoso_api.errors.LuminosoSessionExpired
|
class LuminosoSessionExpired(LuminosoAuthError):
pass
|
class LuminosoSessionExpired(LuminosoAuthError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
147,592 |
LuminosoInsight/luminoso-api-client-python
|
LuminosoInsight_luminoso-api-client-python/luminoso_api/errors.py
|
luminoso_api.errors.LuminosoLoginError
|
class LuminosoLoginError(LuminosoAuthError):
pass
|
class LuminosoLoginError(LuminosoAuthError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
147,593 |
LuminosoInsight/luminoso-api-client-python
|
LuminosoInsight_luminoso-api-client-python/luminoso_api/errors.py
|
luminoso_api.errors.LuminosoError
|
class LuminosoError(Exception):
pass
|
class LuminosoError(Exception):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 5 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
147,594 |
LuminosoInsight/luminoso-api-client-python
|
LuminosoInsight_luminoso-api-client-python/luminoso_api/errors.py
|
luminoso_api.errors.LuminosoClientError
|
class LuminosoClientError(LuminosoError):
pass
|
class LuminosoClientError(LuminosoError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
147,595 |
LuminosoInsight/luminoso-api-client-python
|
LuminosoInsight_luminoso-api-client-python/luminoso_api/errors.py
|
luminoso_api.errors.LuminosoAPIError
|
class LuminosoAPIError(LuminosoError):
pass
|
class LuminosoAPIError(LuminosoError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
147,596 |
LuminosoInsight/luminoso-api-client-python
|
LuminosoInsight_luminoso-api-client-python/luminoso_api/errors.py
|
luminoso_api.errors.LuminosoAuthError
|
class LuminosoAuthError(LuminosoError):
pass
|
class LuminosoAuthError(LuminosoError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
147,597 |
LuminosoInsight/ordered-set
|
LuminosoInsight_ordered-set/ordered_set/__init__.py
|
ordered_set.OrderedSet
|
class OrderedSet(MutableSet[T], Sequence[T]):
"""
An OrderedSet is a custom MutableSet that remembers its order, so that
every entry has an index that can be looked up.
Example:
>>> OrderedSet([1, 1, 2, 3, 2])
OrderedSet([1, 2, 3])
"""
def __init__(self, initial: OrderedSetInitializer[T] = None):
self.items: List[T] = []
self.map: Dict[T, int] = {}
if initial is not None:
# In terms of duck-typing, the default __ior__ is compatible with
# the types we use, but it doesn't expect all the types we
# support as values for `initial`.
self |= initial # type: ignore
def __len__(self) -> int:
"""
Returns the number of unique elements in the ordered set
Example:
>>> len(OrderedSet([]))
0
>>> len(OrderedSet([1, 2]))
2
"""
return len(self.items)
@overload
def __getitem__(self, index: slice) -> "OrderedSet[T]":
...
@overload
def __getitem__(self, index: Sequence[int]) -> List[T]:
...
@overload
def __getitem__(self, index: int) -> T:
...
# concrete implementation
def __getitem__(self, index):
"""
Get the item at a given index.
If `index` is a slice, you will get back that slice of items, as a
new OrderedSet.
If `index` is a list or a similar iterable, you'll get a list of
items corresponding to those indices. This is similar to NumPy's
"fancy indexing". The result is not an OrderedSet because you may ask
for duplicate indices, and the number of elements returned should be
the number of elements asked for.
Example:
>>> oset = OrderedSet([1, 2, 3])
>>> oset[1]
2
"""
if isinstance(index, slice) and index == SLICE_ALL:
return self.copy()
elif isinstance(index, Iterable):
return [self.items[i] for i in index]
elif isinstance(index, slice) or hasattr(index, "__index__"):
result = self.items[index]
if isinstance(result, list):
return self.__class__(result)
else:
return result
else:
raise TypeError("Don't know how to index an OrderedSet by %r" % index)
def copy(self) -> "OrderedSet[T]":
"""
Return a shallow copy of this object.
Example:
>>> this = OrderedSet([1, 2, 3])
>>> other = this.copy()
>>> this == other
True
>>> this is other
False
"""
return self.__class__(self)
# Define the gritty details of how an OrderedSet is serialized as a pickle.
# We leave off type annotations, because the only code that should interact
# with these is a generalized tool such as pickle.
def __getstate__(self):
if len(self) == 0:
# In pickle, the state can't be an empty list.
# We need to return a truthy value, or else __setstate__ won't be run.
#
# This could have been done more gracefully by always putting the state
# in a tuple, but this way is backwards- and forwards- compatible with
# previous versions of OrderedSet.
return (None,)
else:
return list(self)
def __setstate__(self, state):
if state == (None,):
self.__init__([])
else:
self.__init__(state)
def __contains__(self, key: object) -> bool:
"""
Test if the item is in this ordered set.
Example:
>>> 1 in OrderedSet([1, 3, 2])
True
>>> 5 in OrderedSet([1, 3, 2])
False
"""
return key in self.map
# Technically type-incompatible with MutableSet, because we return an
# int instead of nothing. This is also one of the things that makes
# OrderedSet convenient to use.
def add(self, key: T) -> int:
"""
Add `key` as an item to this OrderedSet, then return its index.
If `key` is already in the OrderedSet, return the index it already
had.
Example:
>>> oset = OrderedSet()
>>> oset.append(3)
0
>>> print(oset)
OrderedSet([3])
"""
if key not in self.map:
self.map[key] = len(self.items)
self.items.append(key)
return self.map[key]
append = add
def update(self, sequence: SetLike[T]) -> int:
"""
Update the set with the given iterable sequence, then return the index
of the last element inserted.
Example:
>>> oset = OrderedSet([1, 2, 3])
>>> oset.update([3, 1, 5, 1, 4])
4
>>> print(oset)
OrderedSet([1, 2, 3, 5, 4])
"""
item_index = 0
try:
for item in sequence:
item_index = self.add(item)
except TypeError:
raise ValueError(f"Argument needs to be an iterable, got {type(sequence)}")
return item_index
@overload
def index(self, key: Sequence[T]) -> List[int]:
...
@overload
def index(self, key: T) -> int:
...
# concrete implementation
def index(self, key):
"""
Get the index of a given entry, raising an IndexError if it's not
present.
`key` can be an iterable of entries that is not a string, in which case
this returns a list of indices.
Example:
>>> oset = OrderedSet([1, 2, 3])
>>> oset.index(2)
1
"""
if isinstance(key, Iterable) and not _is_atomic(key):
return [self.index(subkey) for subkey in key]
return self.map[key]
# Provide some compatibility with pd.Index
get_loc = index
get_indexer = index
def pop(self, index: int = -1) -> T:
"""
Remove and return item at index (default last).
Raises KeyError if the set is empty.
Raises IndexError if index is out of range.
Example:
>>> oset = OrderedSet([1, 2, 3])
>>> oset.pop()
3
"""
if not self.items:
raise KeyError("Set is empty")
elem = self.items[index]
del self.items[index]
del self.map[elem]
return elem
def discard(self, key: T) -> None:
"""
Remove an element. Do not raise an exception if absent.
The MutableSet mixin uses this to implement the .remove() method, which
*does* raise an error when asked to remove a non-existent item.
Example:
>>> oset = OrderedSet([1, 2, 3])
>>> oset.discard(2)
>>> print(oset)
OrderedSet([1, 3])
>>> oset.discard(2)
>>> print(oset)
OrderedSet([1, 3])
"""
if key in self:
i = self.map[key]
del self.items[i]
del self.map[key]
for k, v in self.map.items():
if v >= i:
self.map[k] = v - 1
def clear(self) -> None:
"""
Remove all items from this OrderedSet.
"""
del self.items[:]
self.map.clear()
def __iter__(self) -> Iterator[T]:
"""
Example:
>>> list(iter(OrderedSet([1, 2, 3])))
[1, 2, 3]
"""
return iter(self.items)
def __reversed__(self) -> Iterator[T]:
"""
Example:
>>> list(reversed(OrderedSet([1, 2, 3])))
[3, 2, 1]
"""
return reversed(self.items)
def __repr__(self) -> str:
if not self:
return f"{self.__class__.__name__}()"
return f"{self.__class__.__name__}({list(self)!r})"
def __eq__(self, other: object) -> bool:
"""
Returns true if the containers have the same items. If `other` is a
Sequence, then order is checked, otherwise it is ignored.
Example:
>>> oset = OrderedSet([1, 3, 2])
>>> oset == [1, 3, 2]
True
>>> oset == [1, 2, 3]
False
>>> oset == [2, 3]
False
>>> oset == OrderedSet([3, 2, 1])
False
"""
if isinstance(other, Sequence):
# Check that this OrderedSet contains the same elements, in the
# same order, as the other object.
return list(self) == list(other)
try:
other_as_set = set(other)
except TypeError:
# If `other` can't be converted into a set, it's not equal.
return False
else:
return set(self) == other_as_set
def union(self, *sets: SetLike[T]) -> "OrderedSet[T]":
"""
Combines all unique items.
Each items order is defined by its first appearance.
Example:
>>> oset = OrderedSet.union(OrderedSet([3, 1, 4, 1, 5]), [1, 3], [2, 0])
>>> print(oset)
OrderedSet([3, 1, 4, 5, 2, 0])
>>> oset.union([8, 9])
OrderedSet([3, 1, 4, 5, 2, 0, 8, 9])
>>> oset | {10}
OrderedSet([3, 1, 4, 5, 2, 0, 10])
"""
cls: type = OrderedSet
if isinstance(self, OrderedSet):
cls = self.__class__
containers = map(list, it.chain([self], sets))
items = it.chain.from_iterable(containers)
return cls(items)
def __and__(self, other: SetLike[T]) -> "OrderedSet[T]":
# the parent implementation of this is backwards
return self.intersection(other)
def intersection(self, *sets: SetLike[T]) -> "OrderedSet[T]":
"""
Returns elements in common between all sets. Order is defined only
by the first set.
Example:
>>> oset = OrderedSet.intersection(OrderedSet([0, 1, 2, 3]), [1, 2, 3])
>>> print(oset)
OrderedSet([1, 2, 3])
>>> oset.intersection([2, 4, 5], [1, 2, 3, 4])
OrderedSet([2])
>>> oset.intersection()
OrderedSet([1, 2, 3])
"""
cls: type = OrderedSet
items: OrderedSetInitializer[T] = self
if isinstance(self, OrderedSet):
cls = self.__class__
if sets:
common = set.intersection(*map(set, sets))
items = (item for item in self if item in common)
return cls(items)
def difference(self, *sets: SetLike[T]) -> "OrderedSet[T]":
"""
Returns all elements that are in this set but not the others.
Example:
>>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]))
OrderedSet([1, 3])
>>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]), OrderedSet([3]))
OrderedSet([1])
>>> OrderedSet([1, 2, 3]) - OrderedSet([2])
OrderedSet([1, 3])
>>> OrderedSet([1, 2, 3]).difference()
OrderedSet([1, 2, 3])
"""
cls = self.__class__
items: OrderedSetInitializer[T] = self
if sets:
other = set.union(*map(set, sets))
items = (item for item in self if item not in other)
return cls(items)
def issubset(self, other: SetLike[T]) -> bool:
"""
Report whether another set contains this set.
Example:
>>> OrderedSet([1, 2, 3]).issubset({1, 2})
False
>>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})
True
>>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})
False
"""
if len(self) > len(other): # Fast check for obvious cases
return False
return all(item in other for item in self)
def issuperset(self, other: SetLike[T]) -> bool:
"""
Report whether this set contains another set.
Example:
>>> OrderedSet([1, 2]).issuperset([1, 2, 3])
False
>>> OrderedSet([1, 2, 3, 4]).issuperset({1, 2, 3})
True
>>> OrderedSet([1, 4, 3, 5]).issuperset({1, 2, 3})
False
"""
if len(self) < len(other): # Fast check for obvious cases
return False
return all(item in self for item in other)
def symmetric_difference(self, other: SetLike[T]) -> "OrderedSet[T]":
"""
Return the symmetric difference of two OrderedSets as a new set.
That is, the new set will contain all elements that are in exactly
one of the sets.
Their order will be preserved, with elements from `self` preceding
elements from `other`.
Example:
>>> this = OrderedSet([1, 4, 3, 5, 7])
>>> other = OrderedSet([9, 7, 1, 3, 2])
>>> this.symmetric_difference(other)
OrderedSet([4, 5, 9, 2])
"""
cls: type = OrderedSet
if isinstance(self, OrderedSet):
cls = self.__class__
diff1 = cls(self).difference(other)
diff2 = cls(other).difference(self)
return diff1.union(diff2)
def _update_items(self, items: list) -> None:
"""
Replace the 'items' list of this OrderedSet with a new one, updating
self.map accordingly.
"""
self.items = items
self.map = {item: idx for (idx, item) in enumerate(items)}
def difference_update(self, *sets: SetLike[T]) -> None:
"""
Update this OrderedSet to remove items from one or more other sets.
Example:
>>> this = OrderedSet([1, 2, 3])
>>> this.difference_update(OrderedSet([2, 4]))
>>> print(this)
OrderedSet([1, 3])
>>> this = OrderedSet([1, 2, 3, 4, 5])
>>> this.difference_update(OrderedSet([2, 4]), OrderedSet([1, 4, 6]))
>>> print(this)
OrderedSet([3, 5])
"""
items_to_remove = set() # type: Set[T]
for other in sets:
items_as_set = set(other) # type: Set[T]
items_to_remove |= items_as_set
self._update_items([item for item in self.items if item not in items_to_remove])
def intersection_update(self, other: SetLike[T]) -> None:
"""
Update this OrderedSet to keep only items in another set, preserving
their order in this set.
Example:
>>> this = OrderedSet([1, 4, 3, 5, 7])
>>> other = OrderedSet([9, 7, 1, 3, 2])
>>> this.intersection_update(other)
>>> print(this)
OrderedSet([1, 3, 7])
"""
other = set(other)
self._update_items([item for item in self.items if item in other])
def symmetric_difference_update(self, other: SetLike[T]) -> None:
"""
Update this OrderedSet to remove items from another set, then
add items from the other set that were not present in this set.
Example:
>>> this = OrderedSet([1, 4, 3, 5, 7])
>>> other = OrderedSet([9, 7, 1, 3, 2])
>>> this.symmetric_difference_update(other)
>>> print(this)
OrderedSet([4, 5, 9, 2])
"""
items_to_add = [item for item in other if item not in self]
items_to_remove = set(other)
self._update_items(
[item for item in self.items if item not in items_to_remove] + items_to_add
)
|
class OrderedSet(MutableSet[T], Sequence[T]):
'''
An OrderedSet is a custom MutableSet that remembers its order, so that
every entry has an index that can be looked up.
Example:
>>> OrderedSet([1, 1, 2, 3, 2])
OrderedSet([1, 2, 3])
'''
def __init__(self, initial: OrderedSetInitializer[T] = None):
pass
def __len__(self) -> int:
'''
Returns the number of unique elements in the ordered set
Example:
>>> len(OrderedSet([]))
0
>>> len(OrderedSet([1, 2]))
2
'''
pass
@overload
def __getitem__(self, index: slice) -> "OrderedSet[T]":
pass
@overload
def __getitem__(self, index: slice) -> "OrderedSet[T]":
pass
@overload
def __getitem__(self, index: slice) -> "OrderedSet[T]":
pass
def __getitem__(self, index: slice) -> "OrderedSet[T]":
'''
Get the item at a given index.
If `index` is a slice, you will get back that slice of items, as a
new OrderedSet.
If `index` is a list or a similar iterable, you'll get a list of
items corresponding to those indices. This is similar to NumPy's
"fancy indexing". The result is not an OrderedSet because you may ask
for duplicate indices, and the number of elements returned should be
the number of elements asked for.
Example:
>>> oset = OrderedSet([1, 2, 3])
>>> oset[1]
2
'''
pass
def copy(self) -> "OrderedSet[T]":
'''
Return a shallow copy of this object.
Example:
>>> this = OrderedSet([1, 2, 3])
>>> other = this.copy()
>>> this == other
True
>>> this is other
False
'''
pass
def __getstate__(self):
pass
def __setstate__(self, state):
pass
def __contains__(self, key: object) -> bool:
'''
Test if the item is in this ordered set.
Example:
>>> 1 in OrderedSet([1, 3, 2])
True
>>> 5 in OrderedSet([1, 3, 2])
False
'''
pass
def add(self, key: T) -> int:
'''
Add `key` as an item to this OrderedSet, then return its index.
If `key` is already in the OrderedSet, return the index it already
had.
Example:
>>> oset = OrderedSet()
>>> oset.append(3)
0
>>> print(oset)
OrderedSet([3])
'''
pass
def update(self, sequence: SetLike[T]) -> int:
'''
Update the set with the given iterable sequence, then return the index
of the last element inserted.
Example:
>>> oset = OrderedSet([1, 2, 3])
>>> oset.update([3, 1, 5, 1, 4])
4
>>> print(oset)
OrderedSet([1, 2, 3, 5, 4])
'''
pass
@overload
def index(self, key: Sequence[T]) -> List[int]:
pass
@overload
def index(self, key: Sequence[T]) -> List[int]:
pass
def index(self, key: Sequence[T]) -> List[int]:
'''
Get the index of a given entry, raising an IndexError if it's not
present.
`key` can be an iterable of entries that is not a string, in which case
this returns a list of indices.
Example:
>>> oset = OrderedSet([1, 2, 3])
>>> oset.index(2)
1
'''
pass
def pop(self, index: int = -1) -> T:
'''
Remove and return item at index (default last).
Raises KeyError if the set is empty.
Raises IndexError if index is out of range.
Example:
>>> oset = OrderedSet([1, 2, 3])
>>> oset.pop()
3
'''
pass
def discard(self, key: T) -> None:
'''
Remove an element. Do not raise an exception if absent.
The MutableSet mixin uses this to implement the .remove() method, which
*does* raise an error when asked to remove a non-existent item.
Example:
>>> oset = OrderedSet([1, 2, 3])
>>> oset.discard(2)
>>> print(oset)
OrderedSet([1, 3])
>>> oset.discard(2)
>>> print(oset)
OrderedSet([1, 3])
'''
pass
def clear(self) -> None:
'''
Remove all items from this OrderedSet.
'''
pass
def __iter__(self) -> Iterator[T]:
'''
Example:
>>> list(iter(OrderedSet([1, 2, 3])))
[1, 2, 3]
'''
pass
def __reversed__(self) -> Iterator[T]:
'''
Example:
>>> list(reversed(OrderedSet([1, 2, 3])))
[3, 2, 1]
'''
pass
def __repr__(self) -> str:
pass
def __eq__(self, other: object) -> bool:
'''
Returns true if the containers have the same items. If `other` is a
Sequence, then order is checked, otherwise it is ignored.
Example:
>>> oset = OrderedSet([1, 3, 2])
>>> oset == [1, 3, 2]
True
>>> oset == [1, 2, 3]
False
>>> oset == [2, 3]
False
>>> oset == OrderedSet([3, 2, 1])
False
'''
pass
def union(self, *sets: SetLike[T]) -> "OrderedSet[T]":
'''
Combines all unique items.
Each items order is defined by its first appearance.
Example:
>>> oset = OrderedSet.union(OrderedSet([3, 1, 4, 1, 5]), [1, 3], [2, 0])
>>> print(oset)
OrderedSet([3, 1, 4, 5, 2, 0])
>>> oset.union([8, 9])
OrderedSet([3, 1, 4, 5, 2, 0, 8, 9])
>>> oset | {10}
OrderedSet([3, 1, 4, 5, 2, 0, 10])
'''
pass
def __and__(self, other: SetLike[T]) -> "OrderedSet[T]":
pass
def intersection(self, *sets: SetLike[T]) -> "OrderedSet[T]":
'''
Returns elements in common between all sets. Order is defined only
by the first set.
Example:
>>> oset = OrderedSet.intersection(OrderedSet([0, 1, 2, 3]), [1, 2, 3])
>>> print(oset)
OrderedSet([1, 2, 3])
>>> oset.intersection([2, 4, 5], [1, 2, 3, 4])
OrderedSet([2])
>>> oset.intersection()
OrderedSet([1, 2, 3])
'''
pass
def difference(self, *sets: SetLike[T]) -> "OrderedSet[T]":
'''
Returns all elements that are in this set but not the others.
Example:
>>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]))
OrderedSet([1, 3])
>>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]), OrderedSet([3]))
OrderedSet([1])
>>> OrderedSet([1, 2, 3]) - OrderedSet([2])
OrderedSet([1, 3])
>>> OrderedSet([1, 2, 3]).difference()
OrderedSet([1, 2, 3])
'''
pass
def issubset(self, other: SetLike[T]) -> bool:
'''
Report whether another set contains this set.
Example:
>>> OrderedSet([1, 2, 3]).issubset({1, 2})
False
>>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})
True
>>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})
False
'''
pass
def issuperset(self, other: SetLike[T]) -> bool:
'''
Report whether this set contains another set.
Example:
>>> OrderedSet([1, 2]).issuperset([1, 2, 3])
False
>>> OrderedSet([1, 2, 3, 4]).issuperset({1, 2, 3})
True
>>> OrderedSet([1, 4, 3, 5]).issuperset({1, 2, 3})
False
'''
pass
def symmetric_difference(self, other: SetLike[T]) -> "OrderedSet[T]":
'''
Return the symmetric difference of two OrderedSets as a new set.
That is, the new set will contain all elements that are in exactly
one of the sets.
Their order will be preserved, with elements from `self` preceding
elements from `other`.
Example:
>>> this = OrderedSet([1, 4, 3, 5, 7])
>>> other = OrderedSet([9, 7, 1, 3, 2])
>>> this.symmetric_difference(other)
OrderedSet([4, 5, 9, 2])
'''
pass
def _update_items(self, items: list) -> None:
'''
Replace the 'items' list of this OrderedSet with a new one, updating
self.map accordingly.
'''
pass
def difference_update(self, *sets: SetLike[T]) -> None:
'''
Update this OrderedSet to remove items from one or more other sets.
Example:
>>> this = OrderedSet([1, 2, 3])
>>> this.difference_update(OrderedSet([2, 4]))
>>> print(this)
OrderedSet([1, 3])
>>> this = OrderedSet([1, 2, 3, 4, 5])
>>> this.difference_update(OrderedSet([2, 4]), OrderedSet([1, 4, 6]))
>>> print(this)
OrderedSet([3, 5])
'''
pass
def intersection_update(self, other: SetLike[T]) -> None:
'''
Update this OrderedSet to keep only items in another set, preserving
their order in this set.
Example:
>>> this = OrderedSet([1, 4, 3, 5, 7])
>>> other = OrderedSet([9, 7, 1, 3, 2])
>>> this.intersection_update(other)
>>> print(this)
OrderedSet([1, 3, 7])
'''
pass
def symmetric_difference_update(self, other: SetLike[T]) -> None:
'''
Update this OrderedSet to remove items from another set, then
add items from the other set that were not present in this set.
Example:
>>> this = OrderedSet([1, 4, 3, 5, 7])
>>> other = OrderedSet([9, 7, 1, 3, 2])
>>> this.symmetric_difference_update(other)
>>> print(this)
OrderedSet([4, 5, 9, 2])
'''
pass
| 39 | 24 | 13 | 1 | 5 | 7 | 2 | 1.58 | 2 | 15 | 0 | 0 | 33 | 2 | 33 | 33 | 480 | 64 | 163 | 68 | 124 | 258 | 150 | 63 | 116 | 5 | 1 | 3 | 59 |
147,598 |
LuminosoInsight/ordered-set
|
LuminosoInsight_ordered-set/test/test_ordered_set.py
|
test_ordered_set.FancyIndexTester
|
class FancyIndexTester:
"""
Make sure we can index by a NumPy ndarray, without having to import
NumPy.
"""
def __init__(self, indices):
self.indices = indices
def __iter__(self):
return iter(self.indices)
def __index__(self):
raise TypeError("NumPy arrays have weird __index__ methods")
def __eq__(self, other):
# Emulate NumPy being fussy about the == operator
raise TypeError
|
class FancyIndexTester:
'''
Make sure we can index by a NumPy ndarray, without having to import
NumPy.
'''
def __init__(self, indices):
pass
def __iter__(self):
pass
def __index__(self):
pass
def __eq__(self, other):
pass
| 5 | 1 | 2 | 0 | 2 | 0 | 1 | 0.56 | 0 | 1 | 0 | 0 | 4 | 1 | 4 | 4 | 18 | 4 | 9 | 6 | 4 | 5 | 9 | 6 | 4 | 1 | 0 | 0 | 4 |
147,599 |
LuminosoInsight/python-ftfy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LuminosoInsight_python-ftfy/ftfy/bad_codecs/sloppy.py
|
ftfy.bad_codecs.sloppy.make_sloppy_codec.Codec
|
class Codec(codecs.Codec):
def encode(self, input: str, errors: str | None = "strict") -> tuple[bytes, int]:
return codecs.charmap_encode(input, errors, encoding_table)
def decode(self, input: bytes, errors: str | None = "strict") -> tuple[str, int]:
# type: ignore[arg-type]
return codecs.charmap_decode(input, errors, decoding_table)
|
class Codec(codecs.Codec):
def encode(self, input: str, errors: str | None = "strict") -> tuple[bytes, int]:
pass
def decode(self, input: bytes, errors: str | None = "strict") -> tuple[str, int]:
pass
| 3 | 0 | 2 | 0 | 2 | 1 | 1 | 0.2 | 1 | 4 | 0 | 2 | 2 | 0 | 2 | 4 | 6 | 1 | 5 | 3 | 2 | 1 | 5 | 3 | 2 | 1 | 1 | 0 | 2 |
147,600 |
LuminosoInsight/python-ftfy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LuminosoInsight_python-ftfy/ftfy/bad_codecs/sloppy.py
|
ftfy.bad_codecs.sloppy.make_sloppy_codec.IncrementalDecoder
|
class IncrementalDecoder(codecs.IncrementalDecoder):
# type: ignore[override]
def decode(self, input: bytes, final: bool = False) -> str:
# type: ignore[arg-type]
return codecs.charmap_decode(input, self.errors, decoding_table)[0]
|
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input: bytes, final: bool = False) -> str:
pass
| 2 | 0 | 2 | 0 | 2 | 2 | 1 | 0.67 | 1 | 3 | 0 | 0 | 1 | 0 | 1 | 6 | 3 | 0 | 3 | 2 | 1 | 2 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
147,601 |
LuminosoInsight/python-ftfy
|
scripts/char_data_table.py
|
char_data_table.CharData
|
class CharData:
name: str
codept: int
encodings: list[tuple[str, int]]
def sort_key(self) -> tuple[int, str, int]:
if self.name.startswith("LATIN "):
return (0, self.name, self.codept)
return (1, "", self.codept)
|
class CharData:
def sort_key(self) -> tuple[int, str, int]:
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 2 | 0 | 0 | 3 | 0 | 0 | 1 | 0 | 1 | 1 | 9 | 1 | 8 | 2 | 6 | 0 | 8 | 2 | 6 | 2 | 0 | 1 | 2 |
147,602 |
LuminosoInsight/python-ftfy
|
ftfy/__init__.py
|
ftfy.ExplainedText
|
class ExplainedText(NamedTuple):
"""
The return type from ftfy's functions that provide an "explanation" of which
steps it applied to fix the text, such as :func:`fix_and_explain()`.
When the 'explain' option is disabled, these functions return the same
type, but the `explanation` will be None.
"""
text: str
explanation: list[ExplanationStep] | None
|
class ExplainedText(NamedTuple):
'''
The return type from ftfy's functions that provide an "explanation" of which
steps it applied to fix the text, such as :func:`fix_and_explain()`.
When the 'explain' option is disabled, these functions return the same
type, but the `explanation` will be None.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 2 | 3 | 1 | 2 | 6 | 3 | 1 | 2 | 0 | 1 | 0 | 0 |
147,603 |
LuminosoInsight/python-ftfy
|
ftfy/__init__.py
|
ftfy.ExplanationStep
|
class ExplanationStep(NamedTuple):
"""
A step in an ExplainedText, explaining how to decode text.
The possible actions are:
- "encode": take in a string and encode it as bytes, with the given encoding
- "decode": take in bytes and decode them as a string, with the given encoding
- "transcode": convert bytes to bytes with a particular named function
- "apply": convert str to str with a particular named function
The `parameter` is the name of the encoding or function to use. If it's a
function, it must appear in the FIXERS dictionary.
"""
action: str
parameter: str
def __repr__(self) -> str:
"""
Get the string representation of an ExplanationStep. We output the
representation of the equivalent tuple, for simplicity.
"""
return repr(tuple(self))
|
class ExplanationStep(NamedTuple):
'''
A step in an ExplainedText, explaining how to decode text.
The possible actions are:
- "encode": take in a string and encode it as bytes, with the given encoding
- "decode": take in bytes and decode them as a string, with the given encoding
- "transcode": convert bytes to bytes with a particular named function
- "apply": convert str to str with a particular named function
The `parameter` is the name of the encoding or function to use. If it's a
function, it must appear in the FIXERS dictionary.
'''
def __repr__(self) -> str:
'''
Get the string representation of an ExplanationStep. We output the
representation of the equivalent tuple, for simplicity.
'''
pass
| 2 | 2 | 6 | 0 | 2 | 4 | 1 | 2.8 | 1 | 2 | 0 | 0 | 1 | 0 | 1 | 1 | 24 | 5 | 5 | 2 | 3 | 14 | 5 | 2 | 3 | 1 | 1 | 0 | 1 |
147,604 |
LuminosoInsight/python-ftfy
|
ftfy/__init__.py
|
ftfy.TextFixerConfig
|
class TextFixerConfig(NamedTuple):
r"""
A TextFixerConfig object stores configuration options for ftfy.
It's implemented as a namedtuple with defaults, so you can instantiate
it by providing the values to change from their defaults as keyword arguments.
For example, to disable 'unescape_html' and keep the rest of the defaults::
TextFixerConfig(unescape_html=False)
Here are the options and their default values:
- `unescape_html`: "auto"
Configures whether to replace HTML entities such as & with the character
they represent. "auto" says to do this by default, but disable it when a
literal < character appears, indicating that the input is actual HTML and
entities should be preserved. The value can be True, to always enable this
fixer, or False, to always disable it.
- `remove_terminal_escapes`: True
Removes "ANSI" terminal escapes, such as for changing the color of text in a
terminal window.
- `fix_encoding`: True
Detect mojibake and attempt to fix it by decoding the text in a different
encoding standard.
The following four options affect `fix_encoding` works, and do nothing if
`fix_encoding` is False:
- `restore_byte_a0`: True
Allow a literal space (U+20) to be interpreted as a non-breaking space
(U+A0) when that would make it part of a fixable mojibake string.
Because spaces are very common characters, this could lead to false
positives, but we try to apply it only when there's strong evidence for
mojibake. Disabling `restore_byte_a0` is safer from false positives,
but creates false negatives.
- `replace_lossy_sequences`: True
Detect mojibake that has been partially replaced by the characters
'�' or '?'. If the mojibake could be decoded otherwise, replace the
detected sequence with '�'.
- `decode_inconsistent_utf8`: True
When we see sequences that distinctly look like UTF-8 mojibake, but
there's no consistent way to reinterpret the string in a new encoding,
replace the mojibake with the appropriate UTF-8 characters anyway.
This helps to decode strings that are concatenated from different
encodings.
- `fix_c1_controls`: True
Replace C1 control characters (the useless characters U+80 - U+9B that
come from Latin-1) with their Windows-1252 equivalents, like HTML5 does,
even if the whole string doesn't decode as Latin-1.
- `fix_latin_ligatures`: True
Replace common Latin-alphabet ligatures, such as ``fi``, with the
letters they're made of.
- `fix_character_width`: True
Replace fullwidth Latin characters and halfwidth Katakana with
their more standard widths.
- `uncurl_quotes`: True
Replace curly quotes with straight quotes.
- `fix_line_breaks`: True
Replace various forms of line breaks with the standard Unix line
break, ``\n``.
- `fix_surrogates`: True
Replace sequences of UTF-16 surrogate codepoints with the character
they were meant to encode. This fixes text that was decoded with the
obsolete UCS-2 standard, and allows it to support high-numbered
codepoints such as emoji.
- `remove_control_chars`: True
Remove certain control characters that have no displayed effect on text.
- `normalization`: "NFC"
Choose what kind of Unicode normalization is applied. Usually, we apply
NFC normalization, so that letters followed by combining characters become
single combined characters.
Changing this to "NFKC" applies more compatibility conversions, such as
replacing the 'micro sign' with a standard Greek lowercase mu, which looks
identical. However, some NFKC normalizations change the meaning of text,
such as converting "10³" to "103".
`normalization` can be None, to apply no normalization.
- `max_decode_length`: 1_000_000
The maximum size of "segment" that ftfy will try to fix all at once.
- `explain`: True
Whether to compute 'explanations', lists describing what ftfy changed.
When this is False, the explanation will be None, and the code that
builds the explanation will be skipped, possibly saving time.
Functions that accept TextFixerConfig and don't return an explanation
will automatically set `explain` to False.
"""
unescape_html: str | bool = "auto"
remove_terminal_escapes: bool = True
fix_encoding: bool = True
restore_byte_a0: bool = True
replace_lossy_sequences: bool = True
decode_inconsistent_utf8: bool = True
fix_c1_controls: bool = True
fix_latin_ligatures: bool = True
fix_character_width: bool = True
uncurl_quotes: bool = True
fix_line_breaks: bool = True
fix_surrogates: bool = True
remove_control_chars: bool = True
normalization: Literal["NFC", "NFD", "NFKC", "NFKD"] | None = "NFC"
max_decode_length: int = 1000000
explain: bool = True
|
class TextFixerConfig(NamedTuple):
'''
A TextFixerConfig object stores configuration options for ftfy.
It's implemented as a namedtuple with defaults, so you can instantiate
it by providing the values to change from their defaults as keyword arguments.
For example, to disable 'unescape_html' and keep the rest of the defaults::
TextFixerConfig(unescape_html=False)
Here are the options and their default values:
- `unescape_html`: "auto"
Configures whether to replace HTML entities such as & with the character
they represent. "auto" says to do this by default, but disable it when a
literal < character appears, indicating that the input is actual HTML and
entities should be preserved. The value can be True, to always enable this
fixer, or False, to always disable it.
- `remove_terminal_escapes`: True
Removes "ANSI" terminal escapes, such as for changing the color of text in a
terminal window.
- `fix_encoding`: True
Detect mojibake and attempt to fix it by decoding the text in a different
encoding standard.
The following four options affect `fix_encoding` works, and do nothing if
`fix_encoding` is False:
- `restore_byte_a0`: True
Allow a literal space (U+20) to be interpreted as a non-breaking space
(U+A0) when that would make it part of a fixable mojibake string.
Because spaces are very common characters, this could lead to false
positives, but we try to apply it only when there's strong evidence for
mojibake. Disabling `restore_byte_a0` is safer from false positives,
but creates false negatives.
- `replace_lossy_sequences`: True
Detect mojibake that has been partially replaced by the characters
'�' or '?'. If the mojibake could be decoded otherwise, replace the
detected sequence with '�'.
- `decode_inconsistent_utf8`: True
When we see sequences that distinctly look like UTF-8 mojibake, but
there's no consistent way to reinterpret the string in a new encoding,
replace the mojibake with the appropriate UTF-8 characters anyway.
This helps to decode strings that are concatenated from different
encodings.
- `fix_c1_controls`: True
Replace C1 control characters (the useless characters U+80 - U+9B that
come from Latin-1) with their Windows-1252 equivalents, like HTML5 does,
even if the whole string doesn't decode as Latin-1.
- `fix_latin_ligatures`: True
Replace common Latin-alphabet ligatures, such as ``fi``, with the
letters they're made of.
- `fix_character_width`: True
Replace fullwidth Latin characters and halfwidth Katakana with
their more standard widths.
- `uncurl_quotes`: True
Replace curly quotes with straight quotes.
- `fix_line_breaks`: True
Replace various forms of line breaks with the standard Unix line
break, ``\n``.
- `fix_surrogates`: True
Replace sequences of UTF-16 surrogate codepoints with the character
they were meant to encode. This fixes text that was decoded with the
obsolete UCS-2 standard, and allows it to support high-numbered
codepoints such as emoji.
- `remove_control_chars`: True
Remove certain control characters that have no displayed effect on text.
- `normalization`: "NFC"
Choose what kind of Unicode normalization is applied. Usually, we apply
NFC normalization, so that letters followed by combining characters become
single combined characters.
Changing this to "NFKC" applies more compatibility conversions, such as
replacing the 'micro sign' with a standard Greek lowercase mu, which looks
identical. However, some NFKC normalizations change the meaning of text,
such as converting "10³" to "103".
`normalization` can be None, to apply no normalization.
- `max_decode_length`: 1_000_000
The maximum size of "segment" that ftfy will try to fix all at once.
- `explain`: True
Whether to compute 'explanations', lists describing what ftfy changed.
When this is False, the explanation will be None, and the code that
builds the explanation will be skipped, possibly saving time.
Functions that accept TextFixerConfig and don't return an explanation
will automatically set `explain` to False.
'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 4.59 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 137 | 42 | 17 | 17 | 16 | 78 | 17 | 17 | 16 | 0 | 1 | 0 | 0 |
147,605 |
LuminosoInsight/python-ftfy
|
ftfy/bad_codecs/utf8_variants.py
|
ftfy.bad_codecs.utf8_variants.IncrementalDecoder
|
class IncrementalDecoder(UTF8IncrementalDecoder):
"""
An incremental decoder that extends Python's built-in UTF-8 decoder.
This encoder needs to take in bytes, possibly arriving in a stream, and
output the correctly decoded text. The general strategy for doing this
is to fall back on the real UTF-8 decoder whenever possible, because
the real UTF-8 decoder is way optimized, but to call specialized methods
we define here for the cases the real encoder isn't expecting.
"""
@staticmethod
def _buffer_decode( # type: ignore[override]
input: bytes, errors: Optional[str], final: bool
) -> tuple[str, int]:
"""
Decode bytes that may be arriving in a stream, following the Codecs
API.
`input` is the incoming sequence of bytes. `errors` tells us how to
handle errors, though we delegate all error-handling cases to the real
UTF-8 decoder to ensure correct behavior. `final` indicates whether
this is the end of the sequence, in which case we should raise an
error given incomplete input.
Returns as much decoded text as possible, and the number of bytes
consumed.
"""
# decoded_segments are the pieces of text we have decoded so far,
# and position is our current position in the byte string. (Bytes
# before this position have been consumed, and bytes after it have
# yet to be decoded.)
decoded_segments = []
position = 0
while True:
# Use _buffer_decode_step to decode a segment of text.
decoded, consumed = IncrementalDecoder._buffer_decode_step(
input[position:], errors, final
)
if consumed == 0:
# Either there's nothing left to decode, or we need to wait
# for more input. Either way, we're done for now.
break
# Append the decoded text to the list, and update our position.
decoded_segments.append(decoded)
position += consumed
if final:
# _buffer_decode_step must consume all the bytes when `final` is
# true.
assert position == len(input)
return "".join(decoded_segments), position
@staticmethod
def _buffer_decode_step(input: bytes, errors: Optional[str], final: bool) -> tuple[str, int]:
"""
There are three possibilities for each decoding step:
- Decode as much real UTF-8 as possible.
- Decode a six-byte CESU-8 sequence at the current position.
- Decode a Java-style null at the current position.
This method figures out which step is appropriate, and does it.
"""
# Get a reference to the superclass method that we'll be using for
# most of the real work.
sup = UTF8IncrementalDecoder._buffer_decode
# Find the next byte position that indicates a variant of UTF-8.
match = SPECIAL_BYTES_RE.search(input)
if match is None:
return sup(input, errors, final)
cutoff = match.start()
if cutoff > 0:
return sup(input[:cutoff], errors, True)
# Some byte sequence that we intend to handle specially matches
# at the beginning of the input.
if input.startswith(b"\xc0"):
if len(input) > 1:
# Decode the two-byte sequence 0xc0 0x80.
return "\u0000", 2
if final:
# We hit the end of the stream. Let the superclass method
# handle it.
return sup(input, errors, True)
# Wait to see another byte.
return "", 0
# Decode a possible six-byte sequence starting with 0xed.
return IncrementalDecoder._buffer_decode_surrogates(sup, input, errors, final)
@staticmethod
def _buffer_decode_surrogates(
sup: Callable[[bytes, Optional[str], bool], tuple[str, int]],
input: bytes,
errors: Optional[str],
final: bool,
) -> tuple[str, int]:
"""
When we have improperly encoded surrogates, we can still see the
bits that they were meant to represent.
The surrogates were meant to encode a 20-bit number, to which we
add 0x10000 to get a codepoint. That 20-bit number now appears in
this form:
11101101 1010abcd 10efghij 11101101 1011klmn 10opqrst
The CESU8_RE above matches byte sequences of this form. Then we need
to extract the bits and assemble a codepoint number from them.
"""
if len(input) < 6:
if final:
# We found 0xed near the end of the stream, and there aren't
# six bytes to decode. Delegate to the superclass method to
# handle it as normal UTF-8. It might be a Hangul character
# or an error.
return sup(input, errors, final)
# We found a surrogate, the stream isn't over yet, and we don't
# know enough of the following bytes to decode anything, so
# consume zero bytes and wait.
return "", 0
if CESU8_RE.match(input):
# Given this is a CESU-8 sequence, do some math to pull out
# the intended 20-bit value, and consume six bytes.
codepoint = (
((input[1] & 0x0F) << 16)
+ ((input[2] & 0x3F) << 10)
+ ((input[4] & 0x0F) << 6)
+ (input[5] & 0x3F)
+ 0x10000
)
return chr(codepoint), 6
# This looked like a CESU-8 sequence, but it wasn't one.
# 0xed indicates the start of a three-byte sequence, so give
# three bytes to the superclass to decode as usual.
return sup(input[:3], errors, False)
|
class IncrementalDecoder(UTF8IncrementalDecoder):
'''
An incremental decoder that extends Python's built-in UTF-8 decoder.
This encoder needs to take in bytes, possibly arriving in a stream, and
output the correctly decoded text. The general strategy for doing this
is to fall back on the real UTF-8 decoder whenever possible, because
the real UTF-8 decoder is way optimized, but to call specialized methods
we define here for the cases the real encoder isn't expecting.
'''
@staticmethod
def _buffer_decode( # type: ignore[override]
input: bytes, errors: Optional[str], final: bool
) -> tuple[str, int]:
'''
Decode bytes that may be arriving in a stream, following the Codecs
API.
`input` is the incoming sequence of bytes. `errors` tells us how to
handle errors, though we delegate all error-handling cases to the real
UTF-8 decoder to ensure correct behavior. `final` indicates whether
this is the end of the sequence, in which case we should raise an
error given incomplete input.
Returns as much decoded text as possible, and the number of bytes
consumed.
'''
pass
@staticmethod
def _buffer_decode_step(input: bytes, errors: Optional[str], final: bool) -> tuple[str, int]:
'''
There are three possibilities for each decoding step:
- Decode as much real UTF-8 as possible.
- Decode a six-byte CESU-8 sequence at the current position.
- Decode a Java-style null at the current position.
This method figures out which step is appropriate, and does it.
'''
pass
@staticmethod
def _buffer_decode_surrogates(
sup: Callable[[bytes, Optional[str], bool], tuple[str, int]],
input: bytes,
errors: Optional[str],
final: bool,
) -> tuple[str, int]:
'''
When we have improperly encoded surrogates, we can still see the
bits that they were meant to represent.
The surrogates were meant to encode a 20-bit number, to which we
add 0x10000 to get a codepoint. That 20-bit number now appears in
this form:
11101101 1010abcd 10efghij 11101101 1011klmn 10opqrst
The CESU8_RE above matches byte sequences of this form. Then we need
to extract the bits and assemble a codepoint number from them.
'''
pass
| 7 | 4 | 41 | 4 | 17 | 20 | 5 | 1.25 | 1 | 5 | 0 | 0 | 0 | 0 | 3 | 14 | 140 | 17 | 55 | 21 | 41 | 69 | 37 | 11 | 33 | 6 | 4 | 2 | 14 |
147,606 |
LuminosoInsight/python-ftfy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LuminosoInsight_python-ftfy/ftfy/bad_codecs/sloppy.py
|
ftfy.bad_codecs.sloppy.make_sloppy_codec.StreamWriter
|
class StreamWriter(Codec, codecs.StreamWriter):
pass
|
class StreamWriter(Codec, codecs.StreamWriter):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 13 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 2 | 0 | 0 |
147,607 |
LuminosoInsight/python-ftfy
|
ftfy/bad_codecs/utf8_variants.py
|
ftfy.bad_codecs.utf8_variants.StreamReader
|
class StreamReader(codecs.StreamReader):
@staticmethod
def decode(input: bytes, errors: str = "strict") -> tuple[str, int]:
return IncrementalDecoder(errors).decode(input, final=True), len(input)
|
class StreamReader(codecs.StreamReader):
@staticmethod
def decode(input: bytes, errors: str = "strict") -> tuple[str, int]:
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 5 | 1 | 0 | 0 | 0 | 1 | 16 | 4 | 0 | 4 | 3 | 1 | 0 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
147,608 |
LuminosoInsight/python-ftfy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LuminosoInsight_python-ftfy/ftfy/bad_codecs/sloppy.py
|
ftfy.bad_codecs.sloppy.make_sloppy_codec.StreamReader
|
class StreamReader(Codec, codecs.StreamReader):
pass
|
class StreamReader(Codec, codecs.StreamReader):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 17 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 2 | 0 | 0 |
147,609 |
LuminosoInsight/python-ftfy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LuminosoInsight_python-ftfy/ftfy/bad_codecs/sloppy.py
|
ftfy.bad_codecs.sloppy.make_sloppy_codec.IncrementalEncoder
|
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input: str, final: bool = False) -> bytes:
return codecs.charmap_encode(input, self.errors, encoding_table)[0]
|
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input: str, final: bool = False) -> bytes:
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 3 | 0 | 0 | 1 | 0 | 1 | 6 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
147,610 |
LuminosoInsight/python-ftfy
|
ftfy/bad_codecs/utf8_variants.py
|
ftfy.bad_codecs.utf8_variants.StreamWriter
|
class StreamWriter(codecs.StreamWriter):
@staticmethod
def encode(input: str, errors: str = "strict") -> tuple[bytes, int]:
return IncrementalEncoder(errors).encode(input, final=True), len(input)
|
class StreamWriter(codecs.StreamWriter):
@staticmethod
def encode(input: str, errors: str = "strict") -> tuple[bytes, int]:
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 4 | 0 | 0 | 0 | 0 | 1 | 12 | 4 | 0 | 4 | 3 | 1 | 0 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
147,611 |
LuqueDaniel/pybooru
|
LuqueDaniel_pybooru/pybooru/danbooru.py
|
pybooru.danbooru.Danbooru
|
class Danbooru(_Pybooru, DanbooruApi_Mixin):
"""Danbooru class (inherits: Pybooru and DanbooruApi_Mixin).
To initialize Pybooru, you need to specify one of these two
parameters: 'site_name' or 'site_url'. If you specify 'site_name', Pybooru
checks whether there is in the list of default sites (You can get list
of sites in the 'resources' module).
To specify a site that isn't in list of default sites, you need use
'site_url' parameter and specify url.
Some actions may require you to log in. always specify two parameters to
log in: 'username' and 'api_key'.
Attributes:
site_name (str): Get or set site name set.
site_url (str): Get or set the URL of Moebooru/Danbooru based site.
username (str): Return user name.
api_key (str): Return API key.
last_call (dict): Return last call.
"""
def __init__(self, site_name='', site_url='', username='', api_key='', proxies=None):
"""Initialize Danbooru.
Keyword arguments:
site_name (str): Get or set site name set.
site_url (str): Get or set the URL of Moebooru/Danbooru based site.
username (str): Your username of the site (Required only for
functions that modify the content).
api_key (str): Your api key of the site (Required only for
functions that modify the content).
proxies (dict): Your proxies to connect to the danbooru site
(Required only when your network is blocked).
"""
super(Danbooru, self).__init__(site_name, site_url, username, proxies)
self.api_key = api_key
def _get(self, api_call, params=None, method='GET', auth=False,
file_=None):
"""Function to preapre API call.
Parameters:
api_call (str): API function to be called.
params (str): API function parameters.
method (str): (Defauld: GET) HTTP method (GET, POST, PUT or
DELETE)
file_ (file): File to upload (only uploads).
Raise:
PybooruError: When 'username' or 'api_key' are not set.
"""
url = "{0}/{1}".format(self.site_url, api_call)
if method == 'GET':
request_args = {'params': params}
else:
request_args = {'data': params, 'files': file_}
# Adds auth. Also adds auth if username and api_key are specified
# Members+ have less restrictions
if auth or (self.username and self.api_key):
if self.username and self.api_key:
request_args['auth'] = (self.username, self.api_key)
else:
raise PybooruError("'username' and 'api_key' attribute of "
"Danbooru are required.")
# Do call
return self._request(url, api_call, request_args, method)
|
class Danbooru(_Pybooru, DanbooruApi_Mixin):
'''Danbooru class (inherits: Pybooru and DanbooruApi_Mixin).
To initialize Pybooru, you need to specify one of these two
parameters: 'site_name' or 'site_url'. If you specify 'site_name', Pybooru
checks whether there is in the list of default sites (You can get list
of sites in the 'resources' module).
To specify a site that isn't in list of default sites, you need use
'site_url' parameter and specify url.
Some actions may require you to log in. always specify two parameters to
log in: 'username' and 'api_key'.
Attributes:
site_name (str): Get or set site name set.
site_url (str): Get or set the URL of Moebooru/Danbooru based site.
username (str): Return user name.
api_key (str): Return API key.
last_call (dict): Return last call.
'''
def __init__(self, site_name='', site_url='', username='', api_key='', proxies=None):
'''Initialize Danbooru.
Keyword arguments:
site_name (str): Get or set site name set.
site_url (str): Get or set the URL of Moebooru/Danbooru based site.
username (str): Your username of the site (Required only for
functions that modify the content).
api_key (str): Your api key of the site (Required only for
functions that modify the content).
proxies (dict): Your proxies to connect to the danbooru site
(Required only when your network is blocked).
'''
pass
def _get(self, api_call, params=None, method='GET', auth=False,
file_=None):
'''Function to preapre API call.
Parameters:
api_call (str): API function to be called.
params (str): API function parameters.
method (str): (Defauld: GET) HTTP method (GET, POST, PUT or
DELETE)
file_ (file): File to upload (only uploads).
Raise:
PybooruError: When 'username' or 'api_key' are not set.
'''
pass
| 3 | 3 | 24 | 4 | 9 | 12 | 3 | 2.22 | 2 | 2 | 1 | 0 | 2 | 1 | 2 | 93 | 71 | 13 | 18 | 7 | 14 | 40 | 14 | 6 | 11 | 4 | 2 | 2 | 5 |
147,612 |
LuqueDaniel/pybooru
|
LuqueDaniel_pybooru/pybooru/exceptions.py
|
pybooru.exceptions.PybooruAPIError
|
class PybooruAPIError(PybooruError):
"""Class to catch all API errors."""
pass
|
class PybooruAPIError(PybooruError):
'''Class to catch all API errors.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 3 | 0 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
147,613 |
LuqueDaniel/pybooru
|
LuqueDaniel_pybooru/pybooru/exceptions.py
|
pybooru.exceptions.PybooruError
|
class PybooruError(Exception):
"""Class to catch Pybooru error message."""
pass
|
class PybooruError(Exception):
'''Class to catch Pybooru error message.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 2 | 0 | 0 | 0 | 10 | 3 | 0 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
147,614 |
LuqueDaniel/pybooru
|
LuqueDaniel_pybooru/pybooru/exceptions.py
|
pybooru.exceptions.PybooruHTTPError
|
class PybooruHTTPError(PybooruError):
"""Class to catch HTTP error message."""
def __init__(self, msg, http_code, url):
"""Initialize PybooruHTTPError.
Keyword arguments:
msg (str): The error message.
http_code (int): The HTTP status code.
url (str): The URL.
"""
super(PybooruHTTPError, self).__init__(msg, http_code, url)
self._msg = "{0}: {1} - {2}, {3} - URL: {4}".format(
msg, http_code, HTTP_STATUS_CODE[http_code][0],
HTTP_STATUS_CODE[http_code][1], url)
def __str__(self):
"""Print exception."""
return self._msg
|
class PybooruHTTPError(PybooruError):
'''Class to catch HTTP error message.'''
def __init__(self, msg, http_code, url):
'''Initialize PybooruHTTPError.
Keyword arguments:
msg (str): The error message.
http_code (int): The HTTP status code.
url (str): The URL.
'''
pass
def __str__(self):
'''Print exception.'''
pass
| 3 | 3 | 8 | 1 | 4 | 4 | 1 | 1 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 12 | 19 | 3 | 8 | 4 | 5 | 8 | 6 | 4 | 3 | 1 | 4 | 0 | 2 |
147,615 |
LuqueDaniel/pybooru
|
LuqueDaniel_pybooru/pybooru/pybooru.py
|
pybooru.pybooru._Pybooru
|
class _Pybooru(object):
"""Pybooru main class.
Attributes:
site_name (str): Get or set site name set.
site_url (str): Get or set the URL of Moebooru/Danbooru based site.
username (str): Return user name.
last_call (dict): Return last call.
"""
def __init__(self, site_name='', site_url='', username='', proxies=None):
"""Initialize Pybooru.
Keyword arguments:
site_name (str): The site name in 'SITE_LIST', default sites.
site_url (str): URL of on Moebooru/Danbooru based sites.
username (str): Your username of the site (Required only for
functions that modify the content).
Raises:
PybooruError: When 'site_name' and 'site_url' are empty.
"""
# Attributes
self.__site_name = '' # for site_name property
self.__site_url = '' # for site_url property
self.username = username
self.proxies = proxies
self.last_call = {}
# Set HTTP Client
self.client = requests.Session()
headers = {'user-agent': 'Pybooru/{0}'.format(__version__),
'content-type': 'application/json; charset=utf-8'}
self.client.headers = headers
# Validate site_name or site_url
if site_name:
self.site_name = site_name
elif site_url:
self.site_url = site_url
else:
raise PybooruError("Unexpected empty arguments, specify parameter "
"'site_name' or 'site_url'.")
@property
def site_name(self):
"""Get or set site name.
:getter: Return site name.
:setter: Validate and set site name.
:type: string
"""
return self.__site_name
@site_name.setter
def site_name(self, site_name):
"""Function that sets and checks the site name and set url.
Parameters:
site_name (str): The site name in 'SITE_LIST', default sites.
Raises:
PybooruError: When 'site_name' isn't valid.
"""
if site_name in SITE_LIST:
self.__site_name = site_name
self.__site_url = SITE_LIST[site_name]['url']
else:
raise PybooruError(
"The 'site_name' is not valid, specify a valid 'site_name'.")
@property
def site_url(self):
"""Get or set site url.
:getter: Return site url.
:setter: Validate and set site url.
:type: string
"""
return self.__site_url
@site_url.setter
def site_url(self, url):
"""URL setter and validator for site_url property.
Parameters:
url (str): URL of on Moebooru/Danbooru based sites.
Raises:
PybooruError: When URL scheme or URL are invalid.
"""
# Regular expression to URL validate
regex = re.compile(
r'^(?:http|https)://' # Scheme only HTTP/HTTPS
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?| \
[A-Z0-9-]{2,}(?<!-)\.?)|' # Domain
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # or ipv4
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # or ipv6
r'(?::\d+)?' # Port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
# Validate URL
if re.match('^(?:http|https)://', url):
if re.search(regex, url):
self.__site_url = url
else:
raise PybooruError("Invalid URL: {0}".format(url))
else:
raise PybooruError(
"Invalid URL scheme, use HTTP or HTTPS: {0}".format(url))
@staticmethod
def _get_status(status_code):
"""Get status message for status code.
Parameters:
status_code (int): HTTP status code.
Returns:
status message (str).
"""
return "{0}, {1}".format(*HTTP_STATUS_CODE.get(
status_code, ('Undefined', 'undefined')))
def _request(self, url, api_call, request_args, method='GET'):
"""Function to request and returning JSON data.
Parameters:
url (str): Base url call.
api_call (str): API function to be called.
request_args (dict): All requests parameters.
method (str): (Defauld: GET) HTTP method 'GET' or 'POST'
Raises:
PybooruHTTPError: HTTP Error.
requests.exceptions.Timeout: When HTTP Timeout.
ValueError: When can't decode JSON response.
"""
try:
if method != 'GET':
# Reset content-type for data encoded as a multipart form
self.client.headers.update({'content-type': None})
response = self.client.request(method, url, proxies=self.proxies, **request_args)
self.last_call.update({
'API': api_call,
'url': response.url,
'status_code': response.status_code,
'status': self._get_status(response.status_code),
'headers': response.headers
})
if response.status_code in (200, 201, 202):
return response.json()
elif response.status_code == 204:
return True
raise PybooruHTTPError("In _request", response.status_code,
response.url)
except requests.exceptions.Timeout:
raise PybooruError("Timeout! url: {0}".format(response.url))
except ValueError as e:
raise PybooruError("JSON Error: {0} in line {1} column {2}".format(
e.msg, e.lineno, e.colno))
|
class _Pybooru(object):
'''Pybooru main class.
Attributes:
site_name (str): Get or set site name set.
site_url (str): Get or set the URL of Moebooru/Danbooru based site.
username (str): Return user name.
last_call (dict): Return last call.
'''
def __init__(self, site_name='', site_url='', username='', proxies=None):
'''Initialize Pybooru.
Keyword arguments:
site_name (str): The site name in 'SITE_LIST', default sites.
site_url (str): URL of on Moebooru/Danbooru based sites.
username (str): Your username of the site (Required only for
functions that modify the content).
Raises:
PybooruError: When 'site_name' and 'site_url' are empty.
'''
pass
@property
def site_name(self):
'''Get or set site name.
:getter: Return site name.
:setter: Validate and set site name.
:type: string
'''
pass
@site_name.setter
def site_name(self):
'''Function that sets and checks the site name and set url.
Parameters:
site_name (str): The site name in 'SITE_LIST', default sites.
Raises:
PybooruError: When 'site_name' isn't valid.
'''
pass
@property
def site_url(self):
'''Get or set site url.
:getter: Return site url.
:setter: Validate and set site url.
:type: string
'''
pass
@site_url.setter
def site_url(self):
'''URL setter and validator for site_url property.
Parameters:
url (str): URL of on Moebooru/Danbooru based sites.
Raises:
PybooruError: When URL scheme or URL are invalid.
'''
pass
@staticmethod
def _get_status(status_code):
'''Get status message for status code.
Parameters:
status_code (int): HTTP status code.
Returns:
status message (str).
'''
pass
def _request(self, url, api_call, request_args, method='GET'):
'''Function to request and returning JSON data.
Parameters:
url (str): Base url call.
api_call (str): API function to be called.
request_args (dict): All requests parameters.
method (str): (Defauld: GET) HTTP method 'GET' or 'POST'
Raises:
PybooruHTTPError: HTTP Error.
requests.exceptions.Timeout: When HTTP Timeout.
ValueError: When can't decode JSON response.
'''
pass
| 13 | 8 | 21 | 3 | 10 | 9 | 2 | 0.88 | 1 | 4 | 2 | 2 | 6 | 6 | 7 | 7 | 165 | 26 | 78 | 23 | 65 | 69 | 46 | 17 | 38 | 6 | 1 | 2 | 17 |
147,616 |
LuqueDaniel/pybooru
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LuqueDaniel_pybooru/pybooru/moebooru.py
|
pybooru.moebooru.Moebooru
|
class Moebooru(_Pybooru, MoebooruApi_Mixin):
"""Moebooru class (inherits: Pybooru and MoebooruApi_Mixin).
To initialize Pybooru, you need to specify one of these two
parameters: 'site_name' or 'site_url'. If you specify 'site_name', Pybooru
checks whether there is in the list of default sites (You can get list
of sites in the 'resources' module).
To specify a site that isn't in list of default sites, you need use
'site_url' parameter and specify url.
Some actions may require you to log in. always specify three parameters to
log in: 'hash_string', 'username' and 'password'. Default sites has an
associate hash string.
Attributes:
site_name (str): Get or set site name set.
site_url (str): Get or set the URL of Moebooru/Danbooru based site.
api_version (str): Version of Moebooru API.
username (str): Return user name.
password (str): Return password in plain text.
hash_string (str): Return hash_string of the site.
last_call (dict) last call.
"""
def __init__(self, site_name='', site_url='', username='', password='',
hash_string='', api_version='1.13.0+update.3', proxies=None):
"""Initialize Moebooru.
Keyword arguments:
site_name (str): Get or set site name set.
site_url (str): Get or set the URL of Moebooru/Danbooru based site.
api_version (str): Version of Moebooru API.
hash_string (str): String that is hashed (required to login).
(See the API documentation of the site for more
information).
username (str): Your username of the site (Required only for
functions that modify the content).
password (str): Your user password in plain text (Required only
for functions that modify the content).
proxies (dict): Your proxies to connect to the danbooru site
(Required only when your network is blocked).
"""
super(Moebooru, self).__init__(site_name, site_url, username, proxies)
self.api_version = api_version.lower()
self.hash_string = hash_string
self.password = password
self.password_hash = None
@_Pybooru.site_name.setter
def site_name(self, site_name):
"""Sets api_version and hash_string.
Parameters:
site_name (str): The site name in 'SITE_LIST', default sites.
Raises:
PybooruError: When 'site_name' isn't valid.
"""
# Set base class property site_name
_Pybooru.site_name.fset(self, site_name)
if ('api_version' and 'hashed_string') in SITE_LIST[site_name]:
self.api_version = SITE_LIST[site_name]['api_version']
self.hash_string = SITE_LIST[site_name]['hashed_string']
def _build_url(self, api_call):
"""Build request url.
Parameters:
api_call (str): Base API Call.
Returns:
Complete url (str).
"""
if self.api_version in ('1.13.0', '1.13.0+update.1', '1.13.0+update.2'):
if '/' not in api_call:
return "{0}/{1}/index.json".format(self.site_url, api_call)
return "{0}/{1}.json".format(self.site_url, api_call)
def _build_hash_string(self):
"""Function for build password hash string.
Raises:
PybooruError: When isn't provide hash string.
PybooruError: When aren't provide username or password.
PybooruError: When Pybooru can't add password to hash strring.
"""
# Build AUTENTICATION hash_string
# Check if hash_string exists
if self.site_name in SITE_LIST or self.hash_string:
if self.username and self.password:
try:
hash_string = self.hash_string.format(self.password)
except TypeError:
raise PybooruError("Pybooru can't add 'password' "
"to 'hash_string'")
# encrypt hashed_string to SHA1 and return hexdigest string
self.password_hash = hashlib.sha1(
hash_string.encode('utf-8')).hexdigest()
else:
raise PybooruError("Specify the 'username' and 'password' "
"parameters of the Pybooru object, for "
"setting 'password_hash' attribute.")
else:
raise PybooruError(
"Specify the 'hash_string' parameter of the Pybooru"
" object, for the functions that requires login.")
def _get(self, api_call, params, method='GET', file_=None):
"""Function to preapre API call.
Parameters:
api_call (str): API function to be called.
params (dict): API function parameters.
method (str): (Defauld: GET) HTTP method 'GET' or 'POST'
file_ (file): File to upload.
"""
url = self._build_url(api_call)
if method == 'GET':
request_args = {'params': params}
else:
if self.password_hash is None:
self._build_hash_string()
# Set login
params['login'] = self.username
params['password_hash'] = self.password_hash
request_args = {'data': params, 'files': file_}
# Do call
return self._request(url, api_call, request_args, method)
|
class Moebooru(_Pybooru, MoebooruApi_Mixin):
'''Moebooru class (inherits: Pybooru and MoebooruApi_Mixin).
To initialize Pybooru, you need to specify one of these two
parameters: 'site_name' or 'site_url'. If you specify 'site_name', Pybooru
checks whether there is in the list of default sites (You can get list
of sites in the 'resources' module).
To specify a site that isn't in list of default sites, you need use
'site_url' parameter and specify url.
Some actions may require you to log in. always specify three parameters to
log in: 'hash_string', 'username' and 'password'. Default sites has an
associate hash string.
Attributes:
site_name (str): Get or set site name set.
site_url (str): Get or set the URL of Moebooru/Danbooru based site.
api_version (str): Version of Moebooru API.
username (str): Return user name.
password (str): Return password in plain text.
hash_string (str): Return hash_string of the site.
last_call (dict) last call.
'''
def __init__(self, site_name='', site_url='', username='', password='',
hash_string='', api_version='1.13.0+update.3', proxies=None):
'''Initialize Moebooru.
Keyword arguments:
site_name (str): Get or set site name set.
site_url (str): Get or set the URL of Moebooru/Danbooru based site.
api_version (str): Version of Moebooru API.
hash_string (str): String that is hashed (required to login).
(See the API documentation of the site for more
information).
username (str): Your username of the site (Required only for
functions that modify the content).
password (str): Your user password in plain text (Required only
for functions that modify the content).
proxies (dict): Your proxies to connect to the danbooru site
(Required only when your network is blocked).
'''
pass
@_Pybooru.site_name.setter
def site_name(self, site_name):
'''Sets api_version and hash_string.
Parameters:
site_name (str): The site name in 'SITE_LIST', default sites.
Raises:
PybooruError: When 'site_name' isn't valid.
'''
pass
def _build_url(self, api_call):
'''Build request url.
Parameters:
api_call (str): Base API Call.
Returns:
Complete url (str).
'''
pass
def _build_hash_string(self):
'''Function for build password hash string.
Raises:
PybooruError: When isn't provide hash string.
PybooruError: When aren't provide username or password.
PybooruError: When Pybooru can't add password to hash strring.
'''
pass
def _get(self, api_call, params, method='GET', file_=None):
'''Function to preapre API call.
Parameters:
api_call (str): API function to be called.
params (dict): API function parameters.
method (str): (Defauld: GET) HTTP method 'GET' or 'POST'
file_ (file): File to upload.
'''
pass
| 7 | 6 | 21 | 2 | 9 | 9 | 3 | 1.35 | 2 | 3 | 1 | 0 | 5 | 4 | 5 | 45 | 134 | 21 | 48 | 15 | 40 | 65 | 37 | 13 | 31 | 4 | 2 | 3 | 13 |
147,617 |
LuqueDaniel/pybooru
|
LuqueDaniel_pybooru/pybooru/api_danbooru.py
|
pybooru.api_danbooru.DanbooruApi_Mixin
|
class DanbooruApi_Mixin(object):
"""Contains all Danbooru API calls.
* API Version commit: 9996030
* Doc: https://danbooru.donmai.us/wiki_pages/43568
"""
def post_list(self, **params):
"""Get a list of posts.
Parameters:
limit (int): How many posts you want to retrieve. There is a hard
limit of 100 posts per request.
page (int): The page number.
tags (str): The tags to search for. Any tag combination that works
on the web site will work here. This includes all the
meta-tags.
md5 (str): The md5 of the image to search for.
random (bool): Can be: True, False.
raw (bool): When this parameter is set the tags parameter will not
be parsed for aliased tags, metatags or multiple tags,
and will instead be parsed as a single literal tag.
"""
return self._get('posts.json', params)
def post_show(self, post_id):
"""Get a post.
Parameters:
post_id (int): Where post_id is the post id.
"""
return self._get('posts/{0}.json'.format(post_id))
def post_update(self, post_id, tag_string=None, rating=None, source=None,
parent_id=None, has_embedded_notes=None,
is_rating_locked=None, is_note_locked=None,
is_status_locked=None):
"""Update a specific post (Requires login).
Parameters:
post_id (int): The id number of the post to update.
tag_string (str): A space delimited list of tags.
rating (str): The rating for the post. Can be: safe, questionable,
or explicit.
source (str): If this is a URL, Danbooru will download the file.
parent_id (int): The ID of the parent post.
has_embedded_notes (int): Can be 1, 0.
is_rating_locked (int): Can be: 0, 1 (Builder+ only).
is_note_locked (int): Can be: 0, 1 (Builder+ only).
is_status_locked (int): Can be: 0, 1 (Admin only).
"""
params = {
'post[tag_string]': tag_string,
'post[rating]': rating,
'ost[source]': source,
'post[parent_id]': parent_id,
'post[has_embedded_notes]': has_embedded_notes,
'post[is_rating_locked]': is_rating_locked,
'post[is_note_locked]': is_note_locked,
'post[is_status_locked]': is_status_locked
}
return self._get('posts/{0}.json'.format(post_id), params, 'PUT',
auth=True)
def post_revert(self, post_id, version_id):
"""Function to reverts a post to a previous version (Requires login).
Parameters:
post_id (int):
version_id (int): The post version id to revert to.
"""
return self._get('posts/{0}/revert.json'.format(post_id),
{'version_id': version_id}, 'PUT', auth=True)
def post_copy_notes(self, post_id, other_post_id):
"""Function to copy notes (requires login).
Parameters:
post_id (int):
other_post_id (int): The id of the post to copy notes to.
"""
return self._get('posts/{0}/copy_notes.json'.format(post_id),
{'other_post_id': other_post_id}, 'PUT', auth=True)
def post_mark_translated(self, post_id, check_translation,
partially_translated):
"""Mark post as translated (Requires login) (UNTESTED).
If you set check_translation and partially_translated to 1 post will
be tagged as 'translated_request'
Parameters:
post_id (int):
check_translation (int): Can be 0, 1.
partially_translated (int): Can be 0, 1
"""
param = {
'post[check_translation]': check_translation,
'post[partially_translated]': partially_translated
}
return self._get('posts/{0}/mark_as_translated.json'.format(post_id),
param, method='PUT', auth=True)
def post_vote(self, post_id, score):
"""Action lets you vote for a post (Requires login).
Danbooru: Post votes/create.
Parameters:
post_id (int):
score (str): Can be: up, down.
"""
return self._get('posts/{0}/votes.json'.format(post_id),
{'score': score}, 'POST', auth=True)
def post_unvote(self, post_id):
"""Action lets you unvote for a post (Requires login).
Parameters:
post_id (int):
"""
return self._get('posts/{0}/unvote.json'.format(post_id),
method='PUT', auth=True)
def post_flag_list(self, creator_id=None, creator_name=None, post_id=None,
reason_matches=None, is_resolved=None, category=None):
"""Function to flag a post (Requires login).
Parameters:
creator_id (int): The user id of the flag's creator.
creator_name (str): The name of the flag's creator.
post_id (int): The post id if the flag.
"""
params = {
'search[creator_id]': creator_id,
'search[creator_name]': creator_name,
'search[post_id]': post_id,
}
return self._get('post_flags.json', params, auth=True)
def post_flag_show(self, flag_id):
"""Show specific flagged post (Requires login).
Parameters:
flag_id (int):
"""
return self._get('post_appeals/{0}.json'.format(flag_id), auth=True)
def post_flag_create(self, post_id, reason):
"""Function to flag a post.
Parameters:
post_id (int): The id of the flagged post.
reason (str): The reason of the flagging.
"""
params = {'post_flag[post_id]': post_id, 'post_flag[reason]': reason}
return self._get('post_flags.json', params, 'POST', auth=True)
def post_appeals_list(self, creator_id=None, creator_name=None,
post_id=None):
"""Function to return list of appeals (Requires login).
Parameters:
creator_id (int): The user id of the appeal's creator.
creator_name (str): The name of the appeal's creator.
post_id (int): The post id if the appeal.
"""
params = {
'creator_id': creator_id,
'creator_name': creator_name,
'post_id': post_id
}
return self._get('post_appeals.json', params, auth=True)
def post_appeals_show(self, appeal_id):
"""Show a specific post appeal (Requires login) (UNTESTED).
Parameters:
appeal_id:
"""
return self._get('post_appeals/{0}.json'.format(appeal_id), auth=True)
def post_appeals_create(self, post_id, reason):
"""Function to create appeals (Requires login).
Parameters:
post_id (int): The id of the appealed post.
reason (str) The reason of the appeal.
"""
params = {'post_appeal[post_id]': post_id,
'post_appeal[reason]': reason}
return self._get('post_appeals.json', params, 'POST', auth=True)
def post_versions_list(self, updater_name=None, updater_id=None,
post_id=None, start_id=None):
"""Get list of post versions.
Parameters:
updater_name (str):
updater_id (int):
post_id (int):
start_id (int):
"""
params = {
'search[updater_name]': updater_name,
'search[updater_id]': updater_id,
'search[post_id]': post_id,
'search[start_id]': start_id
}
return self._get('post_versions.json', params)
def post_versions_show(self, version_id):
"""Show a specific post version (UNTESTED).
Parameters:
version_id (int):
"""
return self._get('post_versions/{0}.json'.format(version_id))
def post_versions_undo(self, version_id):
"""Undo post version (Requires login) (UNTESTED).
Parameters:
version_id (int):
"""
return self._get('post_versions/{0}/undo.json'.format(version_id),
method='PUT', auth=True)
def count_posts(self, tags=None):
"""Show the number of posts on Danbooru or a specific tag search.
Parameters:
tags (str):
"""
return self._get("counts/posts.json", {"tags": tags})
def upload_list(self, uploader_id=None, uploader_name=None, source=None):
"""Search and return an uploads list (Requires login).
Parameters:
uploader_id (int): The id of the uploader.
uploader_name (str): The name of the uploader.
source (str): The source of the upload (exact string match).
"""
params = {
'search[uploader_id]': uploader_id,
'search[uploader_name]': uploader_name,
'search[source]': source
}
return self._get('uploads.json', params, auth=True)
def upload_show(self, upload_id):
"""Get an upload (Requires login).
Parameters:
upload_id (int):
"""
return self._get('uploads/{0}.json'.format(upload_id), auth=True)
def upload_create(self, tags, rating, file_=None, source=None,
parent_id=None):
"""Function to create a new upload (Requires login).
Parameters:
tags (str):
rating (str): Can be: `s`, `q`, or `e`. Alternatively, you can
specify `rating:safe`, `rating:questionable`, or
`rating:explicit` in the tag string.
file_ (file_path): The file data encoded as a multipart form.
source (str): The source URL.
parent_id (int): The parent post id.
Raises:
PybooruAPIError: When file_ or source are empty.
"""
if file_ or source is not None:
params = {
'upload[source]': source,
'upload[rating]': rating,
'upload[parent_id]': parent_id,
'upload[tag_string]': tags
}
file_ = {'upload[file]': open(file_, 'rb')}
return self._get('uploads.json', params, 'POST', auth=True,
file_=file_)
else:
raise PybooruAPIError("'file_' or 'source' is required.")
def comment_list(self, group_by, limit=None, page=None, body_matches=None,
post_id=None, post_tags_match=None, creator_name=None,
creator_id=None, is_deleted=None):
"""Return a list of comments.
Parameters:
limit (int): How many posts you want to retrieve.
page (int): The page number.
group_by: Can be 'comment', 'post'. Comment will return recent
comments. Post will return posts that have been recently
commented on.
body_matches (str): Body contains the given terms.
post_id (int):
post_tags_match (str): The comment's post's tags match the
given terms. Meta-tags not supported.
creator_name (str): The name of the creator (exact match).
creator_id (int): The user id of the creator.
is_deleted (bool): Can be: True, False.
Raises:
PybooruAPIError: When 'group_by' is invalid.
"""
params = {
'group_by': group_by,
'limit': limit,
'page': page,
'search[body_matches]': body_matches,
'search[post_id]': post_id,
'search[post_tags_match]': post_tags_match,
'search[creator_name]': creator_name,
'search[creator_id]': creator_id,
'search[is_deleted]': is_deleted
}
return self._get('comments.json', params)
def comment_create(self, post_id, body, do_not_bump_post=None):
"""Action to lets you create a comment (Requires login).
Parameters:
post_id (int):
body (str):
do_not_bump_post (bool): Set to 1 if you do not want the post to be
bumped to the top of the comment listing.
"""
params = {
'comment[post_id]': post_id,
'comment[body]': body,
'comment[do_not_bump_post]': do_not_bump_post
}
return self._get('comments.json', params, 'POST', auth=True)
def comment_update(self, comment_id, body):
"""Function to update a comment (Requires login).
Parameters:
comment_id (int):
body (str):
"""
params = {'comment[body]': body}
return self._get('comments/{0}.json'.format(comment_id), params, 'PUT',
auth=True)
def comment_show(self, comment_id):
"""Get a specific comment.
Parameters:
comment_id (int): The id number of the comment to retrieve.
"""
return self._get('comments/{0}.json'.format(comment_id))
def comment_delete(self, comment_id):
"""Remove a specific comment (Requires login).
Parameters:
comment_id (int): The id number of the comment to remove.
"""
return self._get('comments/{0}.json'.format(comment_id),
method='DELETE', auth=True)
def comment_undelete(self, comment_id):
"""Undelete a specific comment (Requires login) (UNTESTED).
Parameters:
comment_id (int):
"""
return self._get('comments/{0}/undelete.json'.format(comment_id),
method='POST', auth=True)
def comment_vote(self, comment_id, score):
"""Lets you vote for a comment (Requires login).
Parameters:
comment_id (int):
score (str): Can be: up, down.
"""
params = {'score': score}
return self._get('comments/{0}/votes.json'.format(comment_id), params,
method='POST', auth=True)
def comment_unvote(self, comment_id):
"""Lets you unvote a specific comment (Requires login).
Parameters:
comment_id (int):
"""
return self._get('posts/{0}/unvote.json'.format(comment_id),
method='POST', auth=True)
def favorite_list(self, user_id=None):
"""Return a list with favorite posts (Requires login).
Parameters:
user_id (int): Which user's favorites to show. Defaults to your own
if not specified.
"""
return self._get('favorites.json', {'user_id': user_id}, auth=True)
def favorite_add(self, post_id):
"""Add post to favorite (Requires login).
Parameters:
post_id (int): The post to favorite.
"""
return self._get('favorites.json', {'post_id': post_id}, 'POST',
auth=True)
def favorite_remove(self, post_id):
"""Remove a post from favorites (Requires login).
Parameters:
post_id (int): Where post_id is the post id.
"""
return self._get('favorites/{0}.json'.format(post_id), method='DELETE',
auth=True)
def dmail_list(self, message_matches=None, to_name=None, to_id=None,
from_name=None, from_id=None, read=None):
"""Return list of Dmails. You can only view dmails you own
(Requires login).
Parameters:
message_matches (str): The message body contains the given terms.
to_name (str): The recipient's name.
to_id (int): The recipient's user id.
from_name (str): The sender's name.
from_id (int): The sender's user id.
read (bool): Can be: true, false.
"""
params = {
'search[message_matches]': message_matches,
'search[to_name]': to_name,
'search[to_id]': to_id,
'search[from_name]': from_name,
'search[from_id]': from_id,
'search[read]': read
}
return self._get('dmails.json', params, auth=True)
def dmail_show(self, dmail_id):
"""Return a specific dmail. You can only view dmails you own
(Requires login).
Parameters:
dmail_id (int): Where dmail_id is the dmail id.
"""
return self._get('dmails/{0}.json'.format(dmail_id), auth=True)
def dmail_create(self, to_name, title, body):
"""Create a dmail (Requires login)
Parameters:
to_name (str): The recipient's name.
title (str): The title of the message.
body (str): The body of the message.
"""
params = {
'dmail[to_name]': to_name,
'dmail[title]': title,
'dmail[body]': body
}
return self._get('dmails.json', params, 'POST', auth=True)
def dmail_delete(self, dmail_id):
"""Delete a dmail. You can only delete dmails you own (Requires login).
Parameters:
dmail_id (int): where dmail_id is the dmail id.
"""
return self._get('dmails/{0}.json'.format(dmail_id), method='DELETE',
auth=True)
def artist_list(self, query=None, artist_id=None, creator_name=None,
creator_id=None, is_active=None, is_banned=None,
empty_only=None, order=None):
"""Get an artist of a list of artists.
Parameters:
query (str):
This field has multiple uses depending on what the query starts
with:
'http:desired_url':
Search for artist with this URL.
'name:desired_url':
Search for artists with the given name as their base name.
'other:other_name':
Search for artists with the given name in their other
names.
'group:group_name':
Search for artists belonging to the group with the given
name.
'status:banned':
Search for artists that are banned. else Search for the
given name in the base name and the other names.
artist_id (id): The artist id.
creator_name (str): Exact creator name.
creator_id (id): Artist creator id.
is_active (bool): Can be: true, false
is_banned (bool): Can be: true, false
empty_only (True): Search for artists that have 0 posts. Can be:
true
order (str): Can be: name, updated_at.
"""
params = {
'search[name]': query,
'search[id]': artist_id,
'search[creator_name]': creator_name,
'search[creator_id]': creator_id,
'search[is_active]': is_active,
'search[is_banned]': is_banned,
'search[empty_only]': empty_only,
'search[order]': order
}
return self._get('artists.json', params)
def artist_show(self, artist_id):
"""Return a specific artist.
Parameters:
artist_id (int): Where artist_id is the artist id.
"""
return self._get('artists/{0}.json'.format(artist_id))
def artist_create(self, name, other_names_comma=None, group_name=None,
url_string=None, body=None):
"""Function to create an artist (Requires login) (UNTESTED).
Parameters:
name (str):
other_names_comma (str): List of alternative names for this
artist, comma delimited.
group_name (str): The name of the group this artist belongs to.
url_string (str): List of URLs associated with this artist,
whitespace or newline delimited.
body (str): DText that will be used to create a wiki entry at the
same time.
"""
params = {
'artist[name]': name,
'artist[other_names_comma]': other_names_comma,
'artist[group_name]': group_name,
'artist[url_string]': url_string,
'artist[body]': body,
}
return self.get('artists.json', params, method='POST', auth=True)
def artist_update(self, artist_id, name=None, other_names_comma=None,
group_name=None, url_string=None, body=None):
"""Function to update artists (Requires login) (UNTESTED).
Parameters:
artist_id (str):
name (str): Artist name.
other_names_comma (str): List of alternative names for this
artist, comma delimited.
group_name (str): The name of the group this artist belongs to.
url_string (str): List of URLs associated with this artist,
whitespace or newline delimited.
body (str): DText that will be used to create/update a wiki entry
at the same time.
"""
params = {
'artist[name]': name,
'artist[other_names_comma]': other_names_comma,
'artist[group_name]': group_name,
'artist[url_string]': url_string,
'artist[body]': body
}
return self .get('artists/{0}.json'.format(artist_id), params,
method='PUT', auth=True)
def artist_delete(self, artist_id):
"""Action to lets you delete an artist (Requires login) (UNTESTED)
(Only Builder+).
Parameters:
artist_id (int): Where artist_id is the artist id.
"""
return self._get('artists/{0}.json'.format(artist_id), method='DELETE',
auth=True)
def artist_undelete(self, artist_id):
"""Lets you undelete artist (Requires login) (UNTESTED) (Only Builder+).
Parameters:
artist_id (int):
"""
return self._get('artists/{0}/undelete.json'.format(artist_id),
method='POST', auth=True)
def artist_banned(self):
"""This is a shortcut for an artist listing search with
name=status:banned."""
return self._get('artists/banned.json')
def artist_revert(self, artist_id, version_id):
"""Revert an artist (Requires login) (UNTESTED).
Parameters:
artist_id (int): The artist id.
version_id (int): The artist version id to revert to.
"""
params = {'version_id': version_id}
return self._get('artists/{0}/revert.json'.format(artist_id), params,
method='PUT', auth=True)
def artist_versions(self, name=None, updater_name=None, updater_id=None,
artist_id=None, is_active=None, is_banned=None,
order=None):
"""Get list of artist versions (Requires login).
Parameters:
name (str):
updater_name (str):
updater_id (int):
artist_id (int):
is_active (bool): Can be: True, False.
is_banned (bool): Can be: True, False.
order (str): Can be: name (Defaults to ID)
"""
params = {
'search[name]': name,
'search[updater_name]': updater_name,
'search[updater_id]': updater_id,
'search[artist_id]': artist_id,
'search[is_active]': is_active,
'search[is_banned]': is_banned,
'search[order]': order
}
return self._get('artist_versions.json', params, auth=True)
def artist_commentary_list(self, text_matches=None, post_id=None,
post_tags_match=None, original_present=None,
translated_present=None):
"""list artist commentary.
Parameters:
text_matches (str):
post_id (int):
post_tags_match (str): The commentary's post's tags match the
giventerms. Meta-tags not supported.
original_present (str): Can be: yes, no.
translated_present (str): Can be: yes, no.
"""
params = {
'search[text_matches]': text_matches,
'search[post_id]': post_id,
'search[post_tags_match]': post_tags_match,
'search[original_present]': original_present,
'search[translated_present]': translated_present
}
return self._get('artist_commentaries.json', params)
def artist_commentary_create_update(self, post_id, original_title,
original_description, translated_title,
translated_description):
"""Create or update artist commentary (Requires login) (UNTESTED).
Parameters:
post_id (int): Post id.
original_title (str): Original title.
original_description (str): Original description.
translated_title (str): Translated title.
translated_description (str): Translated description.
"""
params = {
'artist_commentary[post_id]': post_id,
'artist_commentary[original_title]': original_title,
'artist_commentary[original_description]': original_description,
'artist_commentary[translated_title]': translated_title,
'artist_commentary[translated_description]': translated_description
}
return self._get('artist_commentaries/create_or_update.json', params,
method='POST', auth=True)
def artist_commentary_revert(self, id_, version_id):
"""Revert artist commentary (Requires login) (UNTESTED).
Parameters:
id_ (int): The artist commentary id.
version_id (int): The artist commentary version id to
revert to.
"""
params = {'version_id': version_id}
return self._get('artist_commentaries/{0}/revert.json'.format(id_),
params, method='PUT', auth=True)
def artist_commentary_versions(self, post_id, updater_id):
"""Return list of artist commentary versions.
Parameters:
updater_id (int):
post_id (int):
"""
params = {'search[updater_id]': updater_id, 'search[post_id]': post_id}
return self._get('artist_commentary_versions.json', params)
def note_list(self, body_matches=None, post_id=None, post_tags_match=None,
creator_name=None, creator_id=None, is_active=None):
"""Return list of notes.
Parameters:
body_matches (str): The note's body matches the given terms.
post_id (int): A specific post.
post_tags_match (str): The note's post's tags match the given terms.
creator_name (str): The creator's name. Exact match.
creator_id (int): The creator's user id.
is_active (bool): Can be: True, False.
"""
params = {
'search[body_matches]': body_matches,
'search[post_id]': post_id,
'search[post_tags_match]': post_tags_match,
'search[creator_name]': creator_name,
'search[creator_id]': creator_id,
'search[is_active]': is_active
}
return self._get('notes.json', params)
def note_show(self, note_id):
"""Get a specific note.
Parameters:
note_id (int): Where note_id is the note id.
"""
return self._get('notes/{0}.json'.format(note_id))
def note_create(self, post_id, coor_x, coor_y, width, height, body):
"""Function to create a note (Requires login) (UNTESTED).
Parameters:
post_id (int):
coor_x (int): The x coordinates of the note in pixels,
with respect to the top-left corner of the image.
coor_y (int): The y coordinates of the note in pixels,
with respect to the top-left corner of the image.
width (int): The width of the note in pixels.
height (int): The height of the note in pixels.
body (str): The body of the note.
"""
params = {
'note[post_id]': post_id,
'note[x]': coor_x,
'note[y]': coor_y,
'note[width]': width,
'note[height]': height,
'note[body]': body
}
return self._get('notes.json', params, method='POST', auth=True)
def note_update(self, note_id, coor_x=None, coor_y=None, width=None,
height=None, body=None):
"""Function to update a note (Requires login) (UNTESTED).
Parameters:
note_id (int): Where note_id is the note id.
coor_x (int): The x coordinates of the note in pixels,
with respect to the top-left corner of the image.
coor_y (int): The y coordinates of the note in pixels,
with respect to the top-left corner of the image.
width (int): The width of the note in pixels.
height (int): The height of the note in pixels.
body (str): The body of the note.
"""
params = {
'note[x]': coor_x,
'note[y]': coor_y,
'note[width]': width,
'note[height]': height,
'note[body]': body
}
return self._get('notes/{0}.jso'.format(note_id), params, method='PUT',
auth=True)
def note_delete(self, note_id):
"""delete a specific note (Requires login) (UNTESTED).
Parameters:
note_id (int): Where note_id is the note id.
"""
return self._get('notes/{0}.json'.format(note_id), method='DELETE',
auth=True)
def note_revert(self, note_id, version_id):
"""Function to revert a specific note (Requires login) (UNTESTED).
Parameters:
note_id (int): Where note_id is the note id.
version_id (int): The note version id to revert to.
"""
return self._get('notes/{0}/revert.json'.format(note_id),
{'version_id': version_id}, method='PUT', auth=True)
def note_versions(self, updater_id=None, post_id=None, note_id=None):
"""Get list of note versions.
Parameters:
updater_id (int):
post_id (int):
note_id (int):
"""
params = {
'search[updater_id]': updater_id,
'search[post_id]': post_id,
'search[note_id]': note_id
}
return self._get('note_versions.json', params)
def user_list(self, name=None, name_matches=None, min_level=None,
max_level=None, level=None, user_id=None, order=None):
"""Function to get a list of users or a specific user.
Levels:
Users have a number attribute called level representing their role.
The current levels are:
Member 20, Gold 30, Platinum 31, Builder 32, Contributor 33,
Janitor 35, Moderator 40 and Admin 50.
Parameters:
name (str): Supports patterns.
name_matches (str): Same functionality as name.
min_level (int): Minimum level (see section on levels).
max_level (int): Maximum level (see section on levels).
level (int): Current level (see section on levels).
user_id (int): The user id.
order (str): Can be: 'name', 'post_upload_count', 'note_count',
'post_update_count', 'date'.
"""
params = {
'search[name]': name,
'search[name_matches]': name_matches,
'search[min_level]': min_level,
'search[max_level]': max_level,
'search[level]': level,
'search[id]': user_id,
'search[order]': order
}
return self._get('users.json', params)
def user_show(self, user_id):
"""Get a specific user.
Parameters:
user_id (int): Where user_id is the user id.
"""
return self._get('users/{0}.json'.format(user_id))
def pool_list(self, name_matches=None, pool_ids=None, category=None,
description_matches=None, creator_name=None, creator_id=None,
is_deleted=None, is_active=None, order=None):
"""Get a list of pools.
Parameters:
name_matches (str):
pool_ids (str): Can search for multiple ID's at once, separated by
commas.
description_matches (str):
creator_name (str):
creator_id (int):
is_active (bool): Can be: true, false.
is_deleted (bool): Can be: True, False.
order (str): Can be: name, created_at, post_count, date.
category (str): Can be: series, collection.
"""
params = {
'search[name_matches]': name_matches,
'search[id]': pool_ids,
'search[description_matches]': description_matches,
'search[creator_name]': creator_name,
'search[creator_id]': creator_id,
'search[is_active]': is_active,
'search[is_deleted]': is_deleted,
'search[order]': order,
'search[category]': category
}
return self._get('pools.json', params)
def pool_show(self, pool_id):
"""Get a specific pool.
Parameters:
pool_id (int): Where pool_id is the pool id.
"""
return self._get('pools/{0}.json'.format(pool_id))
def pool_create(self, name, description, category):
"""Function to create a pool (Requires login) (UNTESTED).
Parameters:
name (str): Pool name.
description (str): Pool description.
category (str): Can be: series, collection.
"""
params = {
'pool[name]': name,
'pool[description]': description,
'pool[category]': category
}
return self._get('pools.json', params, method='POST', auth=True)
def pool_update(self, pool_id, name=None, description=None, post_ids=None,
is_active=None, category=None):
"""Update a pool (Requires login) (UNTESTED).
Parameters:
pool_id (int): Where pool_id is the pool id.
name (str):
description (str):
post_ids (str): List of space delimited post ids.
is_active (int): Can be: 1, 0.
category (str): Can be: series, collection.
"""
params = {
'pool[name]': name,
'pool[description]': description,
'pool[post_ids]': post_ids,
'pool[is_active]': is_active,
'pool[category]': category
}
return self._get('pools/{0}.json'.format(pool_id), params,
method='PUT', auth=True)
def pool_delete(self, pool_id):
"""Delete a pool (Requires login) (UNTESTED) (Moderator+).
Parameters:
pool_id (int): Where pool_id is the pool id.
"""
return self._get('pools/{0}.json'.format(pool_id), method='DELETE',
auth=True)
def pool_undelete(self, pool_id):
"""Undelete a specific poool (Requires login) (UNTESTED) (Moderator+).
Parameters:
pool_id (int): Where pool_id is the pool id.
"""
return self._get('pools/{0}/undelete.json'.format(pool_id),
method='POST', auth=True)
def pool_revert(self, pool_id, version_id):
"""Function to revert a specific pool (Requires login) (UNTESTED).
Parameters:
pool_id (int): Where pool_id is the pool id.
version_id (int):
"""
return self._get('pools/{0}/revert.json'.format(pool_id),
{'version_id': version_id}, method='PUT', auth=True)
def pool_versions(self, updater_id=None, updater_name=None, pool_id=None):
"""Get list of pool versions.
Parameters:
updater_id (int):
updater_name (str):
pool_id (int):
"""
params = {
'search[updater_id]': updater_id,
'search[updater_name]': updater_name,
'search[pool_id]': pool_id
}
return self._get('pool_versions.json', params)
def tag_list(self, name_matches=None, name=None, category=None,
hide_empty=None, has_wiki=None, has_artist=None, order=None, limit=1000, page=1):
"""Get a list of tags.
Parameters:
name_matches (str): Can be: part or full name.
name (str): Allows searching for multiple tags with exact given
names, separated by commas. e.g.
search[name]=touhou,original,k-on! would return the
three listed tags.
category (str): Can be: 0, 1, 3, 4 (general, artist, copyright,
character respectively).
hide_empty (str): Can be: yes, no. Excludes tags with 0 posts
when "yes".
has_wiki (str): Can be: yes, no.
has_artist (str): Can be: yes, no.
order (str): Can be: name, date, count.
limit (int): Limit of one page, no more than 1000.
page (int): Page.
"""
if limit > 1000:
warnings.warn(UserWarning(f'Limit over 1000 is not supported by API, but {limit!r} found.'), stacklevel=2)
params = {
'search[name_matches]': name_matches,
'search[name]': name,
'search[category]': category,
'search[hide_empty]': hide_empty,
'search[has_wiki]': has_wiki,
'search[has_artist]': has_artist,
'search[order]': order,
'limit': str(limit),
'page': str(page),
}
return self._get('tags.json', params)
def tag_show(self, tag_id):
"""Show a specific tag.
Parameters:
tag_id (int):
"""
return self._get('tags/{0}.json'.format(tag_id))
def tag_update(self, tag_id, category):
"""Lets you update a tag (Requires login) (UNTESTED).
Parameters:
tag_id (int):
category (str): Can be: 0, 1, 3, 4 (general, artist, copyright,
character respectively).
"""
param = {'tag[category]': category}
return self._get('pools/{0}.json'.format(tag_id), param, method='PUT',
auth=True)
def tag_aliases(self, name_matches=None, antecedent_name=None,
tag_id=None):
"""Get tags aliases.
Parameters:
name_matches (str): Match antecedent or consequent name.
antecedent_name (str): Match antecedent name (exact match).
tag_id (int): The tag alias id.
"""
params = {
'search[name_matches]': name_matches,
'search[antecedent_name]': antecedent_name,
'search[id]': tag_id
}
return self._get('tag_aliases.json', params)
def tag_implications(self, name_matches=None, antecedent_name=None,
tag_id=None):
"""Get tags implications.
Parameters:
name_matches (str): Match antecedent or consequent name.
antecedent_name (str): Match antecedent name (exact match).
tag_id (int): Tag implication id.
"""
params = {
'search[name_matches]': name_matches,
'search[antecedent_name]': antecedent_name,
'search[id]': tag_id
}
return self._get('tag_implications.json', params)
def tag_related(self, query, category=None):
"""Get related tags.
Parameters:
query (str): The tag to find the related tags for.
category (str): If specified, show only tags of a specific
category. Can be: General 0, Artist 1, Copyright
3 and Character 4.
"""
params = {'query': query, 'category': category}
return self._get('related_tag.json', params)
def wiki_list(self, title=None, creator_id=None, body_matches=None,
other_names_match=None, creator_name=None, hide_deleted=None,
other_names_present=None, order=None):
"""Function to retrieves a list of every wiki page.
Parameters:
title (str): Page title.
creator_id (int): Creator id.
body_matches (str): Page content.
other_names_match (str): Other names.
creator_name (str): Creator name.
hide_deleted (str): Can be: yes, no.
other_names_present (str): Can be: yes, no.
order (str): Can be: date, title.
"""
params = {
'search[title]': title,
'search[creator_id]': creator_id,
'search[body_matches]': body_matches,
'search[other_names_match]': other_names_match,
'search[creator_name]': creator_name,
'search[hide_deleted]': hide_deleted,
'search[other_names_present]': other_names_present,
'search[order]': order
}
return self._get('wiki_pages.json', params)
def wiki_show(self, wiki_page_id):
"""Retrieve a specific page of the wiki.
Parameters:
wiki_page_id (int): Where page_id is the wiki page id.
"""
return self._get('wiki_pages/{0}.json'.format(wiki_page_id))
def wiki_create(self, title, body, other_names=None):
"""Action to lets you create a wiki page (Requires login) (UNTESTED).
Parameters:
title (str): Page title.
body (str): Page content.
other_names (str): Other names.
"""
params = {
'wiki_page[title]': title,
'wiki_page[body]': body,
'wiki_page[other_names]': other_names
}
return self._get('wiki_pages.json', params, method='POST', auth=True)
def wiki_update(self, page_id, title=None, body=None,
other_names=None, is_locked=None, is_deleted=None):
"""Action to lets you update a wiki page (Requires login) (UNTESTED).
Parameters:
page_id (int): Whre page_id is the wiki page id.
title (str): Page title.
body (str): Page content.
other_names (str): Other names.
is_locked (int): Can be: 0, 1 (Builder+).
is_deleted (int): Can be: 0, 1 (Builder+).
"""
params = {
'wiki_page[title]': title,
'wiki_page[body]': body,
'wiki_page[other_names]': other_names
}
return self._get('wiki_pages/{0}.json'.format(page_id), params,
method='PUT', auth=True)
def wiki_delete(self, page_id):
"""Delete a specific page wiki (Requires login) (UNTESTED) (Builder+).
Parameters:
page_id (int):
"""
return self._get('wiki_pages/{0}.json'.format(page_id), auth=True,
method='DELETE')
def wiki_revert(self, wiki_page_id, version_id):
"""Revert page to a previeous version (Requires login) (UNTESTED).
Parameters:
wiki_page_id (int): Where page_id is the wiki page id.
version_id (int):
"""
return self._get('wiki_pages/{0}/revert.json'.format(wiki_page_id),
{'version_id': version_id}, method='PUT', auth=True)
def wiki_versions_list(self, page_id, updater_id):
"""Return a list of wiki page version.
Parameters:
page_id (int):
updater_id (int):
"""
params = {
'earch[updater_id]': updater_id,
'search[wiki_page_id]': page_id
}
return self._get('wiki_page_versions.json', params)
def wiki_versions_show(self, page_id):
"""Return a specific wiki page version.
Parameters:
page_id (int): Where page_id is the wiki page version id.
"""
return self._get('wiki_page_versions/{0}.json'.format(page_id))
def forum_topic_list(self, title_matches=None, title=None,
category_id=None):
"""Function to get forum topics.
Parameters:
title_matches (str): Search body for the given terms.
title (str): Exact title match.
category_id (int): Can be: 0, 1, 2 (General, Tags, Bugs & Features
respectively).
"""
params = {
'search[title_matches]': title_matches,
'search[title]': title,
'search[category_id]': category_id
}
return self._get('forum_topics.json', params)
def forum_topic_show(self, topic_id):
"""Retrieve a specific forum topic.
Parameters:
topic_id (int): Where topic_id is the forum topic id.
"""
return self._get('forum_topics/{0}.json'.format(topic_id))
def forum_topic_create(self, title, body, category=None):
"""Function to create topic (Requires login) (UNTESTED).
Parameters:
title (str): topic title.
body (str): Message of the initial post.
category (str): Can be: 0, 1, 2 (General, Tags, Bugs & Features
respectively).
"""
params = {
'forum_topic[title]': title,
'forum_topic[original_post_attributes][body]': body,
'forum_topic[category_id]': category
}
return self._get('forum_topics.json', params, method='POST', auth=True)
def forum_topic_update(self, topic_id, title=None, category=None):
"""Update a specific topic (Login Requires) (UNTESTED).
Parameters:
topic_id (int): Where topic_id is the topic id.
title (str): Topic title.
category (str): Can be: 0, 1, 2 (General, Tags, Bugs & Features
respectively).
"""
params = {
'forum_topic[title]': title,
'forum_topic[category_id]': category
}
return self._get('forum_topics/{0}.json'.format(topic_id), params,
method='PUT', auth=True)
def forum_topic_delete(self, topic_id):
"""Delete a topic (Login Requires) (Moderator+) (UNTESTED).
Parameters:
topic_id (int): Where topic_id is the topic id.
"""
return self._get('forum_topics/{0}.json'.format(topic_id),
method='DELETE', auth=True)
def forum_topic_undelete(self, topic_id):
"""Un delete a topic (Login requries) (Moderator+) (UNTESTED).
Parameters:
topic_id (int): Where topic_id is the topic id.
"""
return self._get('forum_topics/{0}/undelete.json'.format(topic_id),
method='POST', auth=True)
def forum_post_list(self, creator_id=None, creator_name=None,
topic_id=None, topic_title_matches=None,
topic_category_id=None, body_matches=None):
"""Return a list of forum posts.
Parameters:
creator_id (int):
creator_name (str):
topic_id (int):
topic_title_matches (str):
topic_category_id (int): Can be: 0, 1, 2 (General, Tags, Bugs &
Features respectively).
body_matches (str): Can be part of the post content.
"""
params = {
'search[creator_id]': creator_id,
'search[creator_name]': creator_name,
'search[topic_id]': topic_id,
'search[topic_title_matches]': topic_title_matches,
'search[topic_category_id]': topic_category_id,
'search[body_matches]': body_matches
}
return self._get('forum_posts.json', params)
def forum_post_create(self, topic_id, body):
"""Create a forum post (Requires login).
Parameters:
topic_id (int):
body (str): Post content.
"""
params = {'forum_post[topic_id]': topic_id, 'forum_post[body]': body}
return self._get('forum_posts.json', params, method='POST', auth=True)
def forum_post_update(self, topic_id, body):
"""Update a specific forum post (Requries login)(Moderator+)(UNTESTED).
Parameters:
post_id (int): Forum topic id.
body (str): Post content.
"""
params = {'forum_post[body]': body}
return self._get('forum_posts/{0}.json'.format(topic_id), params,
method='PUT', auth=True)
def forum_post_delete(self, post_id):
"""Delete a specific forum post (Requires login)(Moderator+)(UNTESTED).
Parameters:
post_id (int): Forum post id.
"""
return self._get('forum_posts/{0}.json'.format(post_id),
method='DELETE', auth=True)
def forum_post_undelete(self, post_id):
"""Undelete a specific forum post (Requires login)(Moderator+)(UNTESTED).
Parameters:
post_id (int): Forum post id.
"""
return self._get('forum_posts/{0}/undelete.json'.format(post_id),
method='POST', auth=True)
|
class DanbooruApi_Mixin(object):
'''Contains all Danbooru API calls.
* API Version commit: 9996030
* Doc: https://danbooru.donmai.us/wiki_pages/43568
'''
def post_list(self, **params):
'''Get a list of posts.
Parameters:
limit (int): How many posts you want to retrieve. There is a hard
limit of 100 posts per request.
page (int): The page number.
tags (str): The tags to search for. Any tag combination that works
on the web site will work here. This includes all the
meta-tags.
md5 (str): The md5 of the image to search for.
random (bool): Can be: True, False.
raw (bool): When this parameter is set the tags parameter will not
be parsed for aliased tags, metatags or multiple tags,
and will instead be parsed as a single literal tag.
'''
pass
def post_show(self, post_id):
'''Get a post.
Parameters:
post_id (int): Where post_id is the post id.
'''
pass
def post_update(self, post_id, tag_string=None, rating=None, source=None,
parent_id=None, has_embedded_notes=None,
is_rating_locked=None, is_note_locked=None,
is_status_locked=None):
'''Update a specific post (Requires login).
Parameters:
post_id (int): The id number of the post to update.
tag_string (str): A space delimited list of tags.
rating (str): The rating for the post. Can be: safe, questionable,
or explicit.
source (str): If this is a URL, Danbooru will download the file.
parent_id (int): The ID of the parent post.
has_embedded_notes (int): Can be 1, 0.
is_rating_locked (int): Can be: 0, 1 (Builder+ only).
is_note_locked (int): Can be: 0, 1 (Builder+ only).
is_status_locked (int): Can be: 0, 1 (Admin only).
'''
pass
def post_revert(self, post_id, version_id):
'''Function to reverts a post to a previous version (Requires login).
Parameters:
post_id (int):
version_id (int): The post version id to revert to.
'''
pass
def post_copy_notes(self, post_id, other_post_id):
'''Function to copy notes (requires login).
Parameters:
post_id (int):
other_post_id (int): The id of the post to copy notes to.
'''
pass
def post_mark_translated(self, post_id, check_translation,
partially_translated):
'''Mark post as translated (Requires login) (UNTESTED).
If you set check_translation and partially_translated to 1 post will
be tagged as 'translated_request'
Parameters:
post_id (int):
check_translation (int): Can be 0, 1.
partially_translated (int): Can be 0, 1
'''
pass
def post_vote(self, post_id, score):
'''Action lets you vote for a post (Requires login).
Danbooru: Post votes/create.
Parameters:
post_id (int):
score (str): Can be: up, down.
'''
pass
def post_unvote(self, post_id):
'''Action lets you unvote for a post (Requires login).
Parameters:
post_id (int):
'''
pass
def post_flag_list(self, creator_id=None, creator_name=None, post_id=None,
reason_matches=None, is_resolved=None, category=None):
'''Function to flag a post (Requires login).
Parameters:
creator_id (int): The user id of the flag's creator.
creator_name (str): The name of the flag's creator.
post_id (int): The post id if the flag.
'''
pass
def post_flag_show(self, flag_id):
'''Show specific flagged post (Requires login).
Parameters:
flag_id (int):
'''
pass
def post_flag_create(self, post_id, reason):
'''Function to flag a post.
Parameters:
post_id (int): The id of the flagged post.
reason (str): The reason of the flagging.
'''
pass
def post_appeals_list(self, creator_id=None, creator_name=None,
post_id=None):
'''Function to return list of appeals (Requires login).
Parameters:
creator_id (int): The user id of the appeal's creator.
creator_name (str): The name of the appeal's creator.
post_id (int): The post id if the appeal.
'''
pass
def post_appeals_show(self, appeal_id):
'''Show a specific post appeal (Requires login) (UNTESTED).
Parameters:
appeal_id:
'''
pass
def post_appeals_create(self, post_id, reason):
'''Function to create appeals (Requires login).
Parameters:
post_id (int): The id of the appealed post.
reason (str) The reason of the appeal.
'''
pass
def post_versions_list(self, updater_name=None, updater_id=None,
post_id=None, start_id=None):
'''Get list of post versions.
Parameters:
updater_name (str):
updater_id (int):
post_id (int):
start_id (int):
'''
pass
def post_versions_show(self, version_id):
'''Show a specific post version (UNTESTED).
Parameters:
version_id (int):
'''
pass
def post_versions_undo(self, version_id):
'''Undo post version (Requires login) (UNTESTED).
Parameters:
version_id (int):
'''
pass
def count_posts(self, tags=None):
'''Show the number of posts on Danbooru or a specific tag search.
Parameters:
tags (str):
'''
pass
def upload_list(self, uploader_id=None, uploader_name=None, source=None):
'''Search and return an uploads list (Requires login).
Parameters:
uploader_id (int): The id of the uploader.
uploader_name (str): The name of the uploader.
source (str): The source of the upload (exact string match).
'''
pass
def upload_show(self, upload_id):
'''Get an upload (Requires login).
Parameters:
upload_id (int):
'''
pass
def upload_create(self, tags, rating, file_=None, source=None,
parent_id=None):
'''Function to create a new upload (Requires login).
Parameters:
tags (str):
rating (str): Can be: `s`, `q`, or `e`. Alternatively, you can
specify `rating:safe`, `rating:questionable`, or
`rating:explicit` in the tag string.
file_ (file_path): The file data encoded as a multipart form.
source (str): The source URL.
parent_id (int): The parent post id.
Raises:
PybooruAPIError: When file_ or source are empty.
'''
pass
def comment_list(self, group_by, limit=None, page=None, body_matches=None,
post_id=None, post_tags_match=None, creator_name=None,
creator_id=None, is_deleted=None):
'''Return a list of comments.
Parameters:
limit (int): How many posts you want to retrieve.
page (int): The page number.
group_by: Can be 'comment', 'post'. Comment will return recent
comments. Post will return posts that have been recently
commented on.
body_matches (str): Body contains the given terms.
post_id (int):
post_tags_match (str): The comment's post's tags match the
given terms. Meta-tags not supported.
creator_name (str): The name of the creator (exact match).
creator_id (int): The user id of the creator.
is_deleted (bool): Can be: True, False.
Raises:
PybooruAPIError: When 'group_by' is invalid.
'''
pass
def comment_create(self, post_id, body, do_not_bump_post=None):
'''Action to lets you create a comment (Requires login).
Parameters:
post_id (int):
body (str):
do_not_bump_post (bool): Set to 1 if you do not want the post to be
bumped to the top of the comment listing.
'''
pass
def comment_update(self, comment_id, body):
'''Function to update a comment (Requires login).
Parameters:
comment_id (int):
body (str):
'''
pass
def comment_show(self, comment_id):
'''Get a specific comment.
Parameters:
comment_id (int): The id number of the comment to retrieve.
'''
pass
def comment_delete(self, comment_id):
'''Remove a specific comment (Requires login).
Parameters:
comment_id (int): The id number of the comment to remove.
'''
pass
def comment_undelete(self, comment_id):
'''Undelete a specific comment (Requires login) (UNTESTED).
Parameters:
comment_id (int):
'''
pass
def comment_vote(self, comment_id, score):
'''Lets you vote for a comment (Requires login).
Parameters:
comment_id (int):
score (str): Can be: up, down.
'''
pass
def comment_unvote(self, comment_id):
'''Lets you unvote a specific comment (Requires login).
Parameters:
comment_id (int):
'''
pass
def favorite_list(self, user_id=None):
'''Return a list with favorite posts (Requires login).
Parameters:
user_id (int): Which user's favorites to show. Defaults to your own
if not specified.
'''
pass
def favorite_add(self, post_id):
'''Add post to favorite (Requires login).
Parameters:
post_id (int): The post to favorite.
'''
pass
def favorite_remove(self, post_id):
'''Remove a post from favorites (Requires login).
Parameters:
post_id (int): Where post_id is the post id.
'''
pass
def dmail_list(self, message_matches=None, to_name=None, to_id=None,
from_name=None, from_id=None, read=None):
'''Return list of Dmails. You can only view dmails you own
(Requires login).
Parameters:
message_matches (str): The message body contains the given terms.
to_name (str): The recipient's name.
to_id (int): The recipient's user id.
from_name (str): The sender's name.
from_id (int): The sender's user id.
read (bool): Can be: true, false.
'''
pass
def dmail_show(self, dmail_id):
'''Return a specific dmail. You can only view dmails you own
(Requires login).
Parameters:
dmail_id (int): Where dmail_id is the dmail id.
'''
pass
def dmail_create(self, to_name, title, body):
'''Create a dmail (Requires login)
Parameters:
to_name (str): The recipient's name.
title (str): The title of the message.
body (str): The body of the message.
'''
pass
def dmail_delete(self, dmail_id):
'''Delete a dmail. You can only delete dmails you own (Requires login).
Parameters:
dmail_id (int): where dmail_id is the dmail id.
'''
pass
def artist_list(self, query=None, artist_id=None, creator_name=None,
creator_id=None, is_active=None, is_banned=None,
empty_only=None, order=None):
'''Get an artist of a list of artists.
Parameters:
query (str):
This field has multiple uses depending on what the query starts
with:
'http:desired_url':
Search for artist with this URL.
'name:desired_url':
Search for artists with the given name as their base name.
'other:other_name':
Search for artists with the given name in their other
names.
'group:group_name':
Search for artists belonging to the group with the given
name.
'status:banned':
Search for artists that are banned. else Search for the
given name in the base name and the other names.
artist_id (id): The artist id.
creator_name (str): Exact creator name.
creator_id (id): Artist creator id.
is_active (bool): Can be: true, false
is_banned (bool): Can be: true, false
empty_only (True): Search for artists that have 0 posts. Can be:
true
order (str): Can be: name, updated_at.
'''
pass
def artist_show(self, artist_id):
'''Return a specific artist.
Parameters:
artist_id (int): Where artist_id is the artist id.
'''
pass
def artist_create(self, name, other_names_comma=None, group_name=None,
url_string=None, body=None):
'''Function to create an artist (Requires login) (UNTESTED).
Parameters:
name (str):
other_names_comma (str): List of alternative names for this
artist, comma delimited.
group_name (str): The name of the group this artist belongs to.
url_string (str): List of URLs associated with this artist,
whitespace or newline delimited.
body (str): DText that will be used to create a wiki entry at the
same time.
'''
pass
def artist_update(self, artist_id, name=None, other_names_comma=None,
group_name=None, url_string=None, body=None):
'''Function to update artists (Requires login) (UNTESTED).
Parameters:
artist_id (str):
name (str): Artist name.
other_names_comma (str): List of alternative names for this
artist, comma delimited.
group_name (str): The name of the group this artist belongs to.
url_string (str): List of URLs associated with this artist,
whitespace or newline delimited.
body (str): DText that will be used to create/update a wiki entry
at the same time.
'''
pass
def artist_delete(self, artist_id):
'''Action to lets you delete an artist (Requires login) (UNTESTED)
(Only Builder+).
Parameters:
artist_id (int): Where artist_id is the artist id.
'''
pass
def artist_undelete(self, artist_id):
'''Lets you undelete artist (Requires login) (UNTESTED) (Only Builder+).
Parameters:
artist_id (int):
'''
pass
def artist_banned(self):
'''This is a shortcut for an artist listing search with
name=status:banned.'''
pass
def artist_revert(self, artist_id, version_id):
'''Revert an artist (Requires login) (UNTESTED).
Parameters:
artist_id (int): The artist id.
version_id (int): The artist version id to revert to.
'''
pass
def artist_versions(self, name=None, updater_name=None, updater_id=None,
artist_id=None, is_active=None, is_banned=None,
order=None):
'''Get list of artist versions (Requires login).
Parameters:
name (str):
updater_name (str):
updater_id (int):
artist_id (int):
is_active (bool): Can be: True, False.
is_banned (bool): Can be: True, False.
order (str): Can be: name (Defaults to ID)
'''
pass
def artist_commentary_list(self, text_matches=None, post_id=None,
post_tags_match=None, original_present=None,
translated_present=None):
'''list artist commentary.
Parameters:
text_matches (str):
post_id (int):
post_tags_match (str): The commentary's post's tags match the
giventerms. Meta-tags not supported.
original_present (str): Can be: yes, no.
translated_present (str): Can be: yes, no.
'''
pass
def artist_commentary_create_update(self, post_id, original_title,
original_description, translated_title,
translated_description):
'''Create or update artist commentary (Requires login) (UNTESTED).
Parameters:
post_id (int): Post id.
original_title (str): Original title.
original_description (str): Original description.
translated_title (str): Translated title.
translated_description (str): Translated description.
'''
pass
def artist_commentary_revert(self, id_, version_id):
'''Revert artist commentary (Requires login) (UNTESTED).
Parameters:
id_ (int): The artist commentary id.
version_id (int): The artist commentary version id to
revert to.
'''
pass
def artist_commentary_versions(self, post_id, updater_id):
'''Return list of artist commentary versions.
Parameters:
updater_id (int):
post_id (int):
'''
pass
def note_list(self, body_matches=None, post_id=None, post_tags_match=None,
creator_name=None, creator_id=None, is_active=None):
'''Return list of notes.
Parameters:
body_matches (str): The note's body matches the given terms.
post_id (int): A specific post.
post_tags_match (str): The note's post's tags match the given terms.
creator_name (str): The creator's name. Exact match.
creator_id (int): The creator's user id.
is_active (bool): Can be: True, False.
'''
pass
def note_show(self, note_id):
'''Get a specific note.
Parameters:
note_id (int): Where note_id is the note id.
'''
pass
def note_create(self, post_id, coor_x, coor_y, width, height, body):
'''Function to create a note (Requires login) (UNTESTED).
Parameters:
post_id (int):
coor_x (int): The x coordinates of the note in pixels,
with respect to the top-left corner of the image.
coor_y (int): The y coordinates of the note in pixels,
with respect to the top-left corner of the image.
width (int): The width of the note in pixels.
height (int): The height of the note in pixels.
body (str): The body of the note.
'''
pass
def note_update(self, note_id, coor_x=None, coor_y=None, width=None,
height=None, body=None):
'''Function to update a note (Requires login) (UNTESTED).
Parameters:
note_id (int): Where note_id is the note id.
coor_x (int): The x coordinates of the note in pixels,
with respect to the top-left corner of the image.
coor_y (int): The y coordinates of the note in pixels,
with respect to the top-left corner of the image.
width (int): The width of the note in pixels.
height (int): The height of the note in pixels.
body (str): The body of the note.
'''
pass
def note_delete(self, note_id):
'''delete a specific note (Requires login) (UNTESTED).
Parameters:
note_id (int): Where note_id is the note id.
'''
pass
def note_revert(self, note_id, version_id):
'''Function to revert a specific note (Requires login) (UNTESTED).
Parameters:
note_id (int): Where note_id is the note id.
version_id (int): The note version id to revert to.
'''
pass
def note_versions(self, updater_id=None, post_id=None, note_id=None):
'''Get list of note versions.
Parameters:
updater_id (int):
post_id (int):
note_id (int):
'''
pass
def user_list(self, name=None, name_matches=None, min_level=None,
max_level=None, level=None, user_id=None, order=None):
'''Function to get a list of users or a specific user.
Levels:
Users have a number attribute called level representing their role.
The current levels are:
Member 20, Gold 30, Platinum 31, Builder 32, Contributor 33,
Janitor 35, Moderator 40 and Admin 50.
Parameters:
name (str): Supports patterns.
name_matches (str): Same functionality as name.
min_level (int): Minimum level (see section on levels).
max_level (int): Maximum level (see section on levels).
level (int): Current level (see section on levels).
user_id (int): The user id.
order (str): Can be: 'name', 'post_upload_count', 'note_count',
'post_update_count', 'date'.
'''
pass
def user_show(self, user_id):
'''Get a specific user.
Parameters:
user_id (int): Where user_id is the user id.
'''
pass
def pool_list(self, name_matches=None, pool_ids=None, category=None,
description_matches=None, creator_name=None, creator_id=None,
is_deleted=None, is_active=None, order=None):
'''Get a list of pools.
Parameters:
name_matches (str):
pool_ids (str): Can search for multiple ID's at once, separated by
commas.
description_matches (str):
creator_name (str):
creator_id (int):
is_active (bool): Can be: true, false.
is_deleted (bool): Can be: True, False.
order (str): Can be: name, created_at, post_count, date.
category (str): Can be: series, collection.
'''
pass
def pool_show(self, pool_id):
'''Get a specific pool.
Parameters:
pool_id (int): Where pool_id is the pool id.
'''
pass
def pool_create(self, name, description, category):
'''Function to create a pool (Requires login) (UNTESTED).
Parameters:
name (str): Pool name.
description (str): Pool description.
category (str): Can be: series, collection.
'''
pass
def pool_update(self, pool_id, name=None, description=None, post_ids=None,
is_active=None, category=None):
'''Update a pool (Requires login) (UNTESTED).
Parameters:
pool_id (int): Where pool_id is the pool id.
name (str):
description (str):
post_ids (str): List of space delimited post ids.
is_active (int): Can be: 1, 0.
category (str): Can be: series, collection.
'''
pass
def pool_delete(self, pool_id):
'''Delete a pool (Requires login) (UNTESTED) (Moderator+).
Parameters:
pool_id (int): Where pool_id is the pool id.
'''
pass
def pool_undelete(self, pool_id):
'''Undelete a specific poool (Requires login) (UNTESTED) (Moderator+).
Parameters:
pool_id (int): Where pool_id is the pool id.
'''
pass
def pool_revert(self, pool_id, version_id):
'''Function to revert a specific pool (Requires login) (UNTESTED).
Parameters:
pool_id (int): Where pool_id is the pool id.
version_id (int):
'''
pass
def pool_versions(self, updater_id=None, updater_name=None, pool_id=None):
'''Get list of pool versions.
Parameters:
updater_id (int):
updater_name (str):
pool_id (int):
'''
pass
def tag_list(self, name_matches=None, name=None, category=None,
hide_empty=None, has_wiki=None, has_artist=None, order=None, limit=1000, page=1):
'''Get a list of tags.
Parameters:
name_matches (str): Can be: part or full name.
name (str): Allows searching for multiple tags with exact given
names, separated by commas. e.g.
search[name]=touhou,original,k-on! would return the
three listed tags.
category (str): Can be: 0, 1, 3, 4 (general, artist, copyright,
character respectively).
hide_empty (str): Can be: yes, no. Excludes tags with 0 posts
when "yes".
has_wiki (str): Can be: yes, no.
has_artist (str): Can be: yes, no.
order (str): Can be: name, date, count.
limit (int): Limit of one page, no more than 1000.
page (int): Page.
'''
pass
def tag_show(self, tag_id):
'''Show a specific tag.
Parameters:
tag_id (int):
'''
pass
def tag_update(self, tag_id, category):
'''Lets you update a tag (Requires login) (UNTESTED).
Parameters:
tag_id (int):
category (str): Can be: 0, 1, 3, 4 (general, artist, copyright,
character respectively).
'''
pass
def tag_aliases(self, name_matches=None, antecedent_name=None,
tag_id=None):
'''Get tags aliases.
Parameters:
name_matches (str): Match antecedent or consequent name.
antecedent_name (str): Match antecedent name (exact match).
tag_id (int): The tag alias id.
'''
pass
def tag_implications(self, name_matches=None, antecedent_name=None,
tag_id=None):
'''Get tags implications.
Parameters:
name_matches (str): Match antecedent or consequent name.
antecedent_name (str): Match antecedent name (exact match).
tag_id (int): Tag implication id.
'''
pass
def tag_related(self, query, category=None):
'''Get related tags.
Parameters:
query (str): The tag to find the related tags for.
category (str): If specified, show only tags of a specific
category. Can be: General 0, Artist 1, Copyright
3 and Character 4.
'''
pass
def wiki_list(self, title=None, creator_id=None, body_matches=None,
other_names_match=None, creator_name=None, hide_deleted=None,
other_names_present=None, order=None):
'''Function to retrieves a list of every wiki page.
Parameters:
title (str): Page title.
creator_id (int): Creator id.
body_matches (str): Page content.
other_names_match (str): Other names.
creator_name (str): Creator name.
hide_deleted (str): Can be: yes, no.
other_names_present (str): Can be: yes, no.
order (str): Can be: date, title.
'''
pass
def wiki_show(self, wiki_page_id):
'''Retrieve a specific page of the wiki.
Parameters:
wiki_page_id (int): Where page_id is the wiki page id.
'''
pass
def wiki_create(self, title, body, other_names=None):
'''Action to lets you create a wiki page (Requires login) (UNTESTED).
Parameters:
title (str): Page title.
body (str): Page content.
other_names (str): Other names.
'''
pass
def wiki_update(self, page_id, title=None, body=None,
other_names=None, is_locked=None, is_deleted=None):
'''Action to lets you update a wiki page (Requires login) (UNTESTED).
Parameters:
page_id (int): Whre page_id is the wiki page id.
title (str): Page title.
body (str): Page content.
other_names (str): Other names.
is_locked (int): Can be: 0, 1 (Builder+).
is_deleted (int): Can be: 0, 1 (Builder+).
'''
pass
def wiki_delete(self, page_id):
'''Delete a specific page wiki (Requires login) (UNTESTED) (Builder+).
Parameters:
page_id (int):
'''
pass
def wiki_revert(self, wiki_page_id, version_id):
'''Revert page to a previeous version (Requires login) (UNTESTED).
Parameters:
wiki_page_id (int): Where page_id is the wiki page id.
version_id (int):
'''
pass
def wiki_versions_list(self, page_id, updater_id):
'''Return a list of wiki page version.
Parameters:
page_id (int):
updater_id (int):
'''
pass
def wiki_versions_show(self, page_id):
'''Return a specific wiki page version.
Parameters:
page_id (int): Where page_id is the wiki page version id.
'''
pass
def forum_topic_list(self, title_matches=None, title=None,
category_id=None):
'''Function to get forum topics.
Parameters:
title_matches (str): Search body for the given terms.
title (str): Exact title match.
category_id (int): Can be: 0, 1, 2 (General, Tags, Bugs & Features
respectively).
'''
pass
def forum_topic_show(self, topic_id):
'''Retrieve a specific forum topic.
Parameters:
topic_id (int): Where topic_id is the forum topic id.
'''
pass
def forum_topic_create(self, title, body, category=None):
'''Function to create topic (Requires login) (UNTESTED).
Parameters:
title (str): topic title.
body (str): Message of the initial post.
category (str): Can be: 0, 1, 2 (General, Tags, Bugs & Features
respectively).
'''
pass
def forum_topic_update(self, topic_id, title=None, category=None):
'''Update a specific topic (Login Requires) (UNTESTED).
Parameters:
topic_id (int): Where topic_id is the topic id.
title (str): Topic title.
category (str): Can be: 0, 1, 2 (General, Tags, Bugs & Features
respectively).
'''
pass
def forum_topic_delete(self, topic_id):
'''Delete a topic (Login Requires) (Moderator+) (UNTESTED).
Parameters:
topic_id (int): Where topic_id is the topic id.
'''
pass
def forum_topic_undelete(self, topic_id):
'''Un delete a topic (Login requries) (Moderator+) (UNTESTED).
Parameters:
topic_id (int): Where topic_id is the topic id.
'''
pass
def forum_post_list(self, creator_id=None, creator_name=None,
topic_id=None, topic_title_matches=None,
topic_category_id=None, body_matches=None):
'''Return a list of forum posts.
Parameters:
creator_id (int):
creator_name (str):
topic_id (int):
topic_title_matches (str):
topic_category_id (int): Can be: 0, 1, 2 (General, Tags, Bugs &
Features respectively).
body_matches (str): Can be part of the post content.
'''
pass
def forum_post_create(self, topic_id, body):
'''Create a forum post (Requires login).
Parameters:
topic_id (int):
body (str): Post content.
'''
pass
def forum_post_update(self, topic_id, body):
'''Update a specific forum post (Requries login)(Moderator+)(UNTESTED).
Parameters:
post_id (int): Forum topic id.
body (str): Post content.
'''
pass
def forum_post_delete(self, post_id):
'''Delete a specific forum post (Requires login)(Moderator+)(UNTESTED).
Parameters:
post_id (int): Forum post id.
'''
pass
def forum_post_undelete(self, post_id):
'''Undelete a specific forum post (Requires login)(Moderator+)(UNTESTED).
Parameters:
post_id (int): Forum post id.
'''
pass
| 92 | 92 | 13 | 1 | 6 | 7 | 1 | 1.15 | 1 | 3 | 1 | 2 | 91 | 0 | 91 | 91 | 1,318 | 187 | 525 | 176 | 397 | 606 | 236 | 140 | 144 | 2 | 1 | 1 | 93 |
147,618 |
LuqueDaniel/pybooru
|
LuqueDaniel_pybooru/pybooru/api_moebooru.py
|
pybooru.api_moebooru.MoebooruApi_Mixin
|
class MoebooruApi_Mixin(object):
"""Contains all Moebooru API calls.
* API Versions: 1.13.0+update.3 and 1.13.0
* doc: https://yande.re/help/api or https://konachan.com/help/api
"""
def post_list(self, **params):
"""Get a list of posts.
Parameters:
tags (str): The tags to search for. Any tag combination that works
on the web site will work here. This includes all the
meta-tags.
limit (int): How many posts you want to retrieve. There is a limit
of 100:param posts per request.
page (int): The page number.
"""
return self._get('post', params)
def post_create(self, tags, file_=None, rating=None, source=None,
rating_locked=None, note_locked=None, parent_id=None,
md5=None):
"""Function to create a new post (Requires login).
There are only two mandatory fields: you need to supply the
'tags', and you need to supply the 'file_', either through a
multipart form or through a source URL (Requires login) (UNTESTED).
Parameters:
tags (str): A space delimited list of tags.
file_ (str): The file data encoded as a multipart form. Path of
content.
rating (str): The rating for the post. Can be: safe, questionable,
or explicit.
source (str): If this is a URL, Moebooru will download the file.
rating_locked (bool): Set to True to prevent others from changing
the rating.
note_locked (bool): Set to True to prevent others from adding notes.
parent_id (int): The ID of the parent post.
md5 (str): Supply an MD5 if you want Moebooru to verify the file
after uploading. If the MD5 doesn't match, the post is
destroyed.
Raises:
PybooruAPIError: When file or source are empty.
"""
if file_ or source is not None:
params = {
'post[tags]': tags,
'post[source]': source,
'post[rating]': rating,
'post[is_rating_locked]': rating_locked,
'post[is_note_locked]': note_locked,
'post[parent_id]': parent_id,
'md5': md5}
file_ = {'post[file]': open(file_, 'rb')}
return self._get('post/create', params, 'POST', file_)
else:
raise PybooruAPIError("'file_' or 'source' is required.")
def post_update(self, post_id, tags=None, file_=None, rating=None,
source=None, is_rating_locked=None, is_note_locked=None,
parent_id=None):
"""Update a specific post.
Only the 'post_id' parameter is required. Leave the other parameters
blank if you don't want to change them (Requires login).
Parameters:
post_id (int): The id number of the post to update.
tags (str): A space delimited list of tags. Specify previous tags.
file_ (str): The file data ENCODED as a multipart form.
rating (str): The rating for the post. Can be: safe, questionable,
or explicit.
source (str): If this is a URL, Moebooru will download the file.
rating_locked (bool): Set to True to prevent others from changing
the rating.
note_locked (bool): Set to True to prevent others from adding
notes.
parent_id (int): The ID of the parent post.
"""
params = {
'id': post_id,
'post[tags]': tags,
'post[rating]': rating,
'post[source]': source,
'post[is_rating_locked]': is_rating_locked,
'post[is_note_locked]': is_note_locked,
'post[parent_id]': parent_id
}
if file_ is not None:
file_ = {'post[file]': open(file_, 'rb')}
return self._get('post/update', params, 'PUT', file_)
else:
return self._get('post/update', params, 'PUT')
def post_destroy(self, post_id):
"""Function to destroy a specific post.
You must also be the user who uploaded the post (or you must be a
moderator) (Requires Login) (UNTESTED).
Parameters:
post_id (int): The id number of the post to delete.
"""
return self._get('post/destroy', {'id': post_id}, method='DELETE')
def post_revert_tags(self, post_id, history_id):
"""Function to reverts a post to a previous set of tags
(Requires login) (UNTESTED).
Parameters:
post_id (int): The post id number to update.
history_id (int): The id number of the tag history.
"""
params = {'id': post_id, 'history_id': history_id}
return self._get('post/revert_tags', params, 'PUT')
def post_vote(self, post_id, score):
"""Action lets you vote for a post (Requires login).
Parameters:
post_id (int): The post id.
score (int):
* 0: No voted or Remove vote.
* 1: Good.
* 2: Great.
* 3: Favorite, add post to favorites.
Raises:
PybooruAPIError: When score is > 3.
"""
if score <= 3 and score >= 0:
params = {'id': post_id, 'score': score}
return self._get('post/vote', params, 'POST')
else:
raise PybooruAPIError("Value of 'score' only can be 0, 1, 2 or 3.")
def tag_list(self, **params):
"""Get a list of tags.
Parameters:
name (str): The exact name of the tag.
id (int): The id number of the tag.
limit (int): How many tags to retrieve. Setting this to 0 will
return every tag (Default value: 0).
page (int): The page number.
order (str): Can be 'date', 'name' or 'count'.
after_id (int): Return all tags that have an id number greater
than this.
"""
return self._get('tag', params)
def tag_update(self, name=None, tag_type=None, is_ambiguous=None):
"""Action to lets you update tag (Requires login) (UNTESTED).
Parameters:
name (str): The name of the tag to update.
tag_type (int):
* General: 0.
* artist: 1.
* copyright: 3.
* character: 4.
is_ambiguous (int): Whether or not this tag is ambiguous. Use 1
for True and 0 for False.
"""
params = {
'name': name,
'tag[tag_type]': tag_type,
'tag[is_ambiguous]': is_ambiguous
}
return self._get('tag/update', params, 'PUT')
def tag_related(self, **params):
"""Get a list of related tags.
Parameters:
tags (str): The tag names to query.
type (str): Restrict results to this tag type. Can be general,
artist, copyright, or character.
"""
return self._get('tag/related', params)
def artist_list(self, **params):
"""Get a list of artists.
Parameters:
name (str): The name (or a fragment of the name) of the artist.
order (str): Can be date or name.
page (int): The page number.
"""
return self._get('artist', params)
def artist_create(self, name, urls=None, alias=None, group=None):
"""Function to create an artist (Requires login) (UNTESTED).
Parameters:
name (str): The artist's name.
urls (str): A list of URLs associated with the artist, whitespace
delimited.
alias (str): The artist that this artist is an alias for. Simply
enter the alias artist's name.
group (str): The group or cicle that this artist is a member of.
Simply:param enter the group's name.
"""
params = {
'artist[name]': name,
'artist[urls]': urls,
'artist[alias]': alias,
'artist[group]': group
}
return self._get('artist/create', params, method='POST')
def artist_update(self, artist_id, name=None, urls=None, alias=None,
group=None):
"""Function to update artists (Requires Login) (UNTESTED).
Only the artist_id parameter is required. The other parameters are
optional.
Parameters:
artist_id (int): The id of thr artist to update (Type: INT).
name (str): The artist's name.
urls (str): A list of URLs associated with the artist, whitespace
delimited.
alias (str): The artist that this artist is an alias for. Simply
enter the alias artist's name.
group (str): The group or cicle that this artist is a member of.
Simply enter the group's name.
"""
params = {
'id': artist_id,
'artist[name]': name,
'artist[urls]': urls,
'artist[alias]': alias,
'artist[group]': group
}
return self._get('artist/update', params, method='PUT')
def artist_destroy(self, artist_id):
"""Action to lets you remove artist (Requires login) (UNTESTED).
Parameters:
artist_id (int): The id of the artist to destroy.
"""
return self._get('artist/destroy', {'id': artist_id}, method='POST')
def comment_show(self, comment_id):
"""Get a specific comment.
Parameters:
comment_id (str): The id number of the comment to retrieve.
"""
return self._get('comment/show', {'id': comment_id})
def comment_create(self, post_id, comment_body, anonymous=None):
"""Action to lets you create a comment (Requires login).
Parameters:
post_id (int): The post id number to which you are responding.
comment_body (str): The body of the comment.
anonymous (int): Set to 1 if you want to post this comment
anonymously.
"""
params = {
'comment[post_id]': post_id,
'comment[body]': comment_body,
'comment[anonymous]': anonymous
}
return self._get('comment/create', params, method='POST')
def comment_destroy(self, comment_id):
"""Remove a specific comment (Requires login).
Parameters:
comment_id (int): The id number of the comment to remove.
"""
return self._get('comment/destroy', {'id': comment_id}, 'DELETE')
def wiki_list(self, **params):
"""Function to retrieves a list of every wiki page.
Parameters:
query (str): A word or phrase to search for (Default: None).
order (str): Can be: title, date (Default: title).
limit (int): The number of pages to retrieve (Default: 100).
page (int): The page number.
"""
return self._get('wiki', params)
def wiki_create(self, title, body):
"""Action to lets you create a wiki page (Requires login) (UNTESTED).
Parameters:
title (str): The title of the wiki page.
body (str): The body of the wiki page.
"""
params = {'wiki_page[title]': title, 'wiki_page[body]': body}
return self._get('wiki/create', params, method='POST')
def wiki_update(self, title, new_title=None, page_body=None):
"""Action to lets you update a wiki page (Requires login) (UNTESTED).
Parameters:
title (str): The title of the wiki page to update.
new_title (str): The new title of the wiki page.
page_body (str): The new body of the wiki page.
"""
params = {
'title': title,
'wiki_page[title]': new_title,
'wiki_page[body]': page_body
}
return self._get('wiki/update', params, method='PUT')
def wiki_show(self, **params):
"""Get a specific wiki page.
Parameters:
title (str): The title of the wiki page to retrieve.
version (int): The version of the page to retrieve.
"""
return self._get('wiki/show', params)
def wiki_destroy(self, title):
"""Function to delete a specific wiki page (Requires login)
(Only moderators) (UNTESTED).
Parameters:
title (str): The title of the page to delete.
"""
return self._get('wiki/destroy', {'title': title}, method='DELETE')
def wiki_lock(self, title):
"""Function to lock a specific wiki page (Requires login)
(Only moderators) (UNTESTED).
Parameters:
title (str): The title of the page to lock.
"""
return self._get('wiki/lock', {'title': title}, 'POST')
def wiki_unlock(self, title):
"""Function to unlock a specific wiki page (Requires login)
(Only moderators) (UNTESTED).
Parameters:
title (str): The title of the page to unlock.
"""
return self._get('wiki/unlock', {'title': title}, method='POST')
def wiki_revert(self, title, version):
"""Function to revert a specific wiki page (Requires login) (UNTESTED).
Parameters:
title (str): The title of the wiki page to update.
version (int): The version to revert to.
"""
params = {'title': title, 'version': version}
return self._get('wiki/revert', params, method='PUT')
def wiki_history(self, title):
"""Get history of specific wiki page.
Parameters:
title (str): The title of the wiki page to retrieve versions for.
"""
return self._get('wiki/history', {'title': title})
def note_list(self, **params):
"""Get note list.
Parameters:
post_id (int): The post id number to retrieve notes for.
"""
return self._get('note', params)
def note_search(self, query):
"""Search specific note.
Parameters:
query (str): A word or phrase to search for.
"""
return self._get('note/search', {'query': query})
def note_history(self, **params):
"""Get history of notes.
Parameters:
post_id (int): The post id number to retrieve note versions for.
id (int): The note id number to retrieve versions for.
limit (int): How many versions to retrieve (Default: 10).
page (int): The note id number to retrieve versions for.
"""
return self._get('note/history', params)
def note_revert(self, note_id, version):
"""Function to revert a specific note (Requires login) (UNTESTED).
Parameters:
note_id (int): The note id to update.
version (int): The version to revert to.
"""
params = {'id': note_id, 'version': version}
return self._get('note/revert', params, method='PUT')
def note_create_update(self, post_id=None, coor_x=None, coor_y=None,
width=None, height=None, is_active=None, body=None,
note_id=None):
"""Function to create or update note (Requires login) (UNTESTED).
Parameters:
post_id (int): The post id number this note belongs to.
coor_x (int): The X coordinate of the note.
coor_y (int): The Y coordinate of the note.
width (int): The width of the note.
height (int): The height of the note.
is_active (int): Whether or not the note is visible. Set to 1 for
active, 0 for inactive.
body (str): The note message.
note_id (int): If you are updating a note, this is the note id
number to update.
"""
params = {
'id': note_id,
'note[post]': post_id,
'note[x]': coor_x,
'note[y]': coor_y,
'note[width]': width,
'note[height]': height,
'note[body]': body,
'note[is_active]': is_active
}
return self._get('note/update', params, method='POST')
def user_search(self, **params):
"""Search users.
If you don't specify any parameters you'll _get a listing of all users.
Parameters:
id (int): The id number of the user.
name (str): The name of the user.
"""
return self._get('user', params)
def forum_list(self, **params):
"""Function to get forum posts.
If you don't specify any parameters you'll _get a listing of all users.
Parameters:
parent_id (int): The parent ID number. You'll return all the
responses to that forum post.
"""
return self._get('forum', params)
def pool_list(self, **params):
"""Function to get pools.
If you don't specify any parameters you'll get a list of all pools.
Parameters:
query (str): The title.
page (int): The page number.
"""
return self._get('pool', params)
def pool_posts(self, **params):
"""Function to get pools posts.
If you don't specify any parameters you'll get a list of all pools.
Parameters:
id (int): The pool id number.
page (int): The page number.
"""
return self._get('pool/show', params)
def pool_update(self, pool_id, name=None, is_public=None,
description=None):
"""Function to update a pool (Requires login) (UNTESTED).
Parameters:
pool_id (int): The pool id number.
name (str): The name.
is_public (int): 1 or 0, whether or not the pool is public.
description (str): A description of the pool.
"""
params = {
'id': pool_id,
'pool[name]': name,
'pool[is_public]': is_public,
'pool[description]': description
}
return self._get('pool/update', params, method='PUT')
def pool_create(self, name, description, is_public):
"""Function to create a pool (Require login) (UNTESTED).
Parameters:
name (str): The name.
description (str): A description of the pool.
is_public (int): 1 or 0, whether or not the pool is public.
"""
params = {'pool[name]': name, 'pool[description]': description,
'pool[is_public]': is_public}
return self._get('pool/create', params, method='POST')
def pool_destroy(self, pool_id):
"""Function to destroy a specific pool (Require login) (UNTESTED).
Parameters:
pool_id (int): The pool id number.
"""
return self._get('pool/destroy', {'id': pool_id}, method='DELETE')
def pool_add_post(self, **params):
"""Function to add a post (Require login) (UNTESTED).
Parameters:
pool_id (int): The pool to add the post to.
post_id (int): The post to add.
"""
return self._get('pool/add_post', params, method='PUT')
def pool_remove_post(self, **params):
"""Function to remove a post (Require login) (UNTESTED).
Parameters:
pool_id (int): The pool to remove the post to.
post_id (int): The post to remove.
"""
return self._get('pool/remove_post', params, method='PUT')
def favorite_list_users(self, post_id):
"""Function to return a list with all users who have added to favorites
a specific post.
Parameters:
post_id (int): The post id.
"""
response = self._get('favorite/list_users', {'id': post_id})
# Return list with users
return response['favorited_users'].split(',')
|
class MoebooruApi_Mixin(object):
'''Contains all Moebooru API calls.
* API Versions: 1.13.0+update.3 and 1.13.0
* doc: https://yande.re/help/api or https://konachan.com/help/api
'''
def post_list(self, **params):
'''Get a list of posts.
Parameters:
tags (str): The tags to search for. Any tag combination that works
on the web site will work here. This includes all the
meta-tags.
limit (int): How many posts you want to retrieve. There is a limit
of 100:param posts per request.
page (int): The page number.
'''
pass
def post_create(self, tags, file_=None, rating=None, source=None,
rating_locked=None, note_locked=None, parent_id=None,
md5=None):
'''Function to create a new post (Requires login).
There are only two mandatory fields: you need to supply the
'tags', and you need to supply the 'file_', either through a
multipart form or through a source URL (Requires login) (UNTESTED).
Parameters:
tags (str): A space delimited list of tags.
file_ (str): The file data encoded as a multipart form. Path of
content.
rating (str): The rating for the post. Can be: safe, questionable,
or explicit.
source (str): If this is a URL, Moebooru will download the file.
rating_locked (bool): Set to True to prevent others from changing
the rating.
note_locked (bool): Set to True to prevent others from adding notes.
parent_id (int): The ID of the parent post.
md5 (str): Supply an MD5 if you want Moebooru to verify the file
after uploading. If the MD5 doesn't match, the post is
destroyed.
Raises:
PybooruAPIError: When file or source are empty.
'''
pass
def post_update(self, post_id, tags=None, file_=None, rating=None,
source=None, is_rating_locked=None, is_note_locked=None,
parent_id=None):
'''Update a specific post.
Only the 'post_id' parameter is required. Leave the other parameters
blank if you don't want to change them (Requires login).
Parameters:
post_id (int): The id number of the post to update.
tags (str): A space delimited list of tags. Specify previous tags.
file_ (str): The file data ENCODED as a multipart form.
rating (str): The rating for the post. Can be: safe, questionable,
or explicit.
source (str): If this is a URL, Moebooru will download the file.
rating_locked (bool): Set to True to prevent others from changing
the rating.
note_locked (bool): Set to True to prevent others from adding
notes.
parent_id (int): The ID of the parent post.
'''
pass
def post_destroy(self, post_id):
'''Function to destroy a specific post.
You must also be the user who uploaded the post (or you must be a
moderator) (Requires Login) (UNTESTED).
Parameters:
post_id (int): The id number of the post to delete.
'''
pass
def post_revert_tags(self, post_id, history_id):
'''Function to reverts a post to a previous set of tags
(Requires login) (UNTESTED).
Parameters:
post_id (int): The post id number to update.
history_id (int): The id number of the tag history.
'''
pass
def post_vote(self, post_id, score):
'''Action lets you vote for a post (Requires login).
Parameters:
post_id (int): The post id.
score (int):
* 0: No voted or Remove vote.
* 1: Good.
* 2: Great.
* 3: Favorite, add post to favorites.
Raises:
PybooruAPIError: When score is > 3.
'''
pass
def tag_list(self, **params):
'''Get a list of tags.
Parameters:
name (str): The exact name of the tag.
id (int): The id number of the tag.
limit (int): How many tags to retrieve. Setting this to 0 will
return every tag (Default value: 0).
page (int): The page number.
order (str): Can be 'date', 'name' or 'count'.
after_id (int): Return all tags that have an id number greater
than this.
'''
pass
def tag_update(self, name=None, tag_type=None, is_ambiguous=None):
'''Action to lets you update tag (Requires login) (UNTESTED).
Parameters:
name (str): The name of the tag to update.
tag_type (int):
* General: 0.
* artist: 1.
* copyright: 3.
* character: 4.
is_ambiguous (int): Whether or not this tag is ambiguous. Use 1
for True and 0 for False.
'''
pass
def tag_related(self, **params):
'''Get a list of related tags.
Parameters:
tags (str): The tag names to query.
type (str): Restrict results to this tag type. Can be general,
artist, copyright, or character.
'''
pass
def artist_list(self, **params):
'''Get a list of artists.
Parameters:
name (str): The name (or a fragment of the name) of the artist.
order (str): Can be date or name.
page (int): The page number.
'''
pass
def artist_create(self, name, urls=None, alias=None, group=None):
'''Function to create an artist (Requires login) (UNTESTED).
Parameters:
name (str): The artist's name.
urls (str): A list of URLs associated with the artist, whitespace
delimited.
alias (str): The artist that this artist is an alias for. Simply
enter the alias artist's name.
group (str): The group or cicle that this artist is a member of.
Simply:param enter the group's name.
'''
pass
def artist_update(self, artist_id, name=None, urls=None, alias=None,
group=None):
'''Function to update artists (Requires Login) (UNTESTED).
Only the artist_id parameter is required. The other parameters are
optional.
Parameters:
artist_id (int): The id of thr artist to update (Type: INT).
name (str): The artist's name.
urls (str): A list of URLs associated with the artist, whitespace
delimited.
alias (str): The artist that this artist is an alias for. Simply
enter the alias artist's name.
group (str): The group or cicle that this artist is a member of.
Simply enter the group's name.
'''
pass
def artist_destroy(self, artist_id):
'''Action to lets you remove artist (Requires login) (UNTESTED).
Parameters:
artist_id (int): The id of the artist to destroy.
'''
pass
def comment_show(self, comment_id):
'''Get a specific comment.
Parameters:
comment_id (str): The id number of the comment to retrieve.
'''
pass
def comment_create(self, post_id, comment_body, anonymous=None):
'''Action to lets you create a comment (Requires login).
Parameters:
post_id (int): The post id number to which you are responding.
comment_body (str): The body of the comment.
anonymous (int): Set to 1 if you want to post this comment
anonymously.
'''
pass
def comment_destroy(self, comment_id):
'''Remove a specific comment (Requires login).
Parameters:
comment_id (int): The id number of the comment to remove.
'''
pass
def wiki_list(self, **params):
'''Function to retrieves a list of every wiki page.
Parameters:
query (str): A word or phrase to search for (Default: None).
order (str): Can be: title, date (Default: title).
limit (int): The number of pages to retrieve (Default: 100).
page (int): The page number.
'''
pass
def wiki_create(self, title, body):
'''Action to lets you create a wiki page (Requires login) (UNTESTED).
Parameters:
title (str): The title of the wiki page.
body (str): The body of the wiki page.
'''
pass
def wiki_update(self, title, new_title=None, page_body=None):
'''Action to lets you update a wiki page (Requires login) (UNTESTED).
Parameters:
title (str): The title of the wiki page to update.
new_title (str): The new title of the wiki page.
page_body (str): The new body of the wiki page.
'''
pass
def wiki_show(self, **params):
'''Get a specific wiki page.
Parameters:
title (str): The title of the wiki page to retrieve.
version (int): The version of the page to retrieve.
'''
pass
def wiki_destroy(self, title):
'''Function to delete a specific wiki page (Requires login)
(Only moderators) (UNTESTED).
Parameters:
title (str): The title of the page to delete.
'''
pass
def wiki_lock(self, title):
'''Function to lock a specific wiki page (Requires login)
(Only moderators) (UNTESTED).
Parameters:
title (str): The title of the page to lock.
'''
pass
def wiki_unlock(self, title):
'''Function to unlock a specific wiki page (Requires login)
(Only moderators) (UNTESTED).
Parameters:
title (str): The title of the page to unlock.
'''
pass
def wiki_revert(self, title, version):
'''Function to revert a specific wiki page (Requires login) (UNTESTED).
Parameters:
title (str): The title of the wiki page to update.
version (int): The version to revert to.
'''
pass
def wiki_history(self, title):
'''Get history of specific wiki page.
Parameters:
title (str): The title of the wiki page to retrieve versions for.
'''
pass
def note_list(self, **params):
'''Get note list.
Parameters:
post_id (int): The post id number to retrieve notes for.
'''
pass
def note_search(self, query):
'''Search specific note.
Parameters:
query (str): A word or phrase to search for.
'''
pass
def note_history(self, **params):
'''Get history of notes.
Parameters:
post_id (int): The post id number to retrieve note versions for.
id (int): The note id number to retrieve versions for.
limit (int): How many versions to retrieve (Default: 10).
page (int): The note id number to retrieve versions for.
'''
pass
def note_revert(self, note_id, version):
'''Function to revert a specific note (Requires login) (UNTESTED).
Parameters:
note_id (int): The note id to update.
version (int): The version to revert to.
'''
pass
def note_create_update(self, post_id=None, coor_x=None, coor_y=None,
width=None, height=None, is_active=None, body=None,
note_id=None):
'''Function to create or update note (Requires login) (UNTESTED).
Parameters:
post_id (int): The post id number this note belongs to.
coor_x (int): The X coordinate of the note.
coor_y (int): The Y coordinate of the note.
width (int): The width of the note.
height (int): The height of the note.
is_active (int): Whether or not the note is visible. Set to 1 for
active, 0 for inactive.
body (str): The note message.
note_id (int): If you are updating a note, this is the note id
number to update.
'''
pass
def user_search(self, **params):
'''Search users.
If you don't specify any parameters you'll _get a listing of all users.
Parameters:
id (int): The id number of the user.
name (str): The name of the user.
'''
pass
def forum_list(self, **params):
'''Function to get forum posts.
If you don't specify any parameters you'll _get a listing of all users.
Parameters:
parent_id (int): The parent ID number. You'll return all the
responses to that forum post.
'''
pass
def pool_list(self, **params):
'''Function to get pools.
If you don't specify any parameters you'll get a list of all pools.
Parameters:
query (str): The title.
page (int): The page number.
'''
pass
def pool_posts(self, **params):
'''Function to get pools posts.
If you don't specify any parameters you'll get a list of all pools.
Parameters:
id (int): The pool id number.
page (int): The page number.
'''
pass
def pool_update(self, pool_id, name=None, is_public=None,
description=None):
'''Function to update a pool (Requires login) (UNTESTED).
Parameters:
pool_id (int): The pool id number.
name (str): The name.
is_public (int): 1 or 0, whether or not the pool is public.
description (str): A description of the pool.
'''
pass
def pool_create(self, name, description, is_public):
'''Function to create a pool (Require login) (UNTESTED).
Parameters:
name (str): The name.
description (str): A description of the pool.
is_public (int): 1 or 0, whether or not the pool is public.
'''
pass
def pool_destroy(self, pool_id):
'''Function to destroy a specific pool (Require login) (UNTESTED).
Parameters:
pool_id (int): The pool id number.
'''
pass
def pool_add_post(self, **params):
'''Function to add a post (Require login) (UNTESTED).
Parameters:
pool_id (int): The pool to add the post to.
post_id (int): The post to add.
'''
pass
def pool_remove_post(self, **params):
'''Function to remove a post (Require login) (UNTESTED).
Parameters:
pool_id (int): The pool to remove the post to.
post_id (int): The post to remove.
'''
pass
def favorite_list_users(self, post_id):
'''Function to return a list with all users who have added to favorites
a specific post.
Parameters:
post_id (int): The post id.
'''
pass
| 41 | 41 | 13 | 1 | 4 | 7 | 1 | 1.69 | 1 | 1 | 1 | 2 | 40 | 0 | 40 | 40 | 546 | 91 | 169 | 65 | 120 | 286 | 105 | 57 | 64 | 2 | 1 | 1 | 43 |
147,619 |
Lvl4Sword/Killer
|
killer/posix/power.py
|
killer.posix.power.DeviceType
|
class DeviceType(Enum):
"""Describes the main type of the supply."""
BATTERY = 'Battery'
MAINS = 'Mains'
UPS = 'UPS'
USB = 'USB'
|
class DeviceType(Enum):
'''Describes the main type of the supply.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 6 | 0 | 5 | 5 | 4 | 1 | 5 | 5 | 4 | 0 | 4 | 0 | 0 |
147,620 |
Lvl4Sword/Killer
|
killer/killer_posix.py
|
killer.killer_posix.KillerPosix
|
class KillerPosix(KillerBase):
def __init__(self, config_path: str = None, debug: bool = False):
super().__init__(config_path, debug)
def detect_bt(self):
bt_config = self.config['bluetooth']
try:
bt_command = subprocess.check_output(["bt-device", "--list"],
shell=False).decode()
except Exception as e:
log.debug('Bluetooth: none detected (exception: {0})'.format(e))
else:
if self.DEBUG:
# TODO: Clean up
bt_devices = bt_command.split('\n')
if len(bt_devices) == 3 and bt_devices[2] == '':
log.debug('Bluetooth:', bt_command.split('\n')[1])
else:
log.debug('Bluetooth:', ', '.join(bt_command.split('\n')[1:]))
else:
paired_devices = re.findall(BT_MAC_REGEX, bt_command)
devices_names = re.findall(BT_NAME_REGEX, bt_command)
for each in range(0, len(paired_devices)):
if paired_devices[each] not in bt_config['paired_whitelist']:
self.kill_the_system('Bluetooth Paired: {0}'.format(paired_devices[each]))
else:
connected = subprocess.check_output(
["bt-device", "-i",
paired_devices[each]],
shell=False).decode()
connected_text = re.findall(BT_CONNECTED_REGEX, connected)
if connected_text[0].endswith("1") \
and paired_devices[each] not in bt_config['connected_whitelist']:
self.kill_the_system('Bluetooth Connected MAC Disallowed: {0}'.format(paired_devices[each]))
elif connected_text[0].endswith("1") and each in bt_config['connected_whitelist']:
if devices_names[each] != bt_config['paired_whitelist'][each]:
self.kill_the_system('Bluetooth Connected Name Mismatch: {0}'.format(devices_names[each]))
def detect_usb(self):
ids = re.findall(USB_ID_REGEX, subprocess.check_output("lsusb", shell=False).decode())
log.debug('USB:', ', '.join(ids) if ids else 'none detected')
for each_device in ids:
if each_device not in self.config['linux']['usb_id_whitelist']:
self.kill_the_system('USB Allowed Whitelist: {0}'.format(each_device))
else:
if self.config['linux']['usb_id_whitelist'][each_device] != ids.count(each_device):
self.kill_the_system('USB Duplicate Device: {0}'.format(each_device))
for device in self.config['linux']['usb_connected_whitelist']:
if device not in ids:
self.kill_the_system('USB Connected Whitelist: {0}'.format(device))
def detect_ac(self):
if self.DEBUG:
devices = ', '.join(power.get_devices(power.DeviceType.MAINS))
log.debug('AC:', devices if devices else 'none detected')
if not power.is_online(self.config['linux']['ac_file']):
self.kill_the_system('AC')
def detect_battery(self):
if self.DEBUG:
devices = ', '.join(power.get_devices(power.DeviceType.BATTERY))
log.debug('Battery:', devices if devices else 'none detected')
try:
if not power.is_present(self.config['linux']['battery_file']):
self.kill_the_system('Battery')
except FileNotFoundError:
pass
def detect_tray(self):
disk_tray = self.config['linux']['cdrom_drive']
fd = os.open(disk_tray, os.O_RDONLY | os.O_NONBLOCK)
rv = fcntl.ioctl(fd, 0x5326)
os.close(fd)
log.debug('CD Tray:', rv)
if rv != 1:
self.kill_the_system('CD Tray')
def detect_ethernet(self):
with open(self.config['linux']['ethernet_connected_file']) as ethernet:
connected = int(ethernet.readline().strip())
log.debug('Ethernet:', connected)
if connected:
self.kill_the_system('Ethernet')
def kill_the_system(self, warning: str):
super().kill_the_system(warning)
if not self.DEBUG:
subprocess.Popen(["/sbin/poweroff", "-f"])
|
class KillerPosix(KillerBase):
def __init__(self, config_path: str = None, debug: bool = False):
pass
def detect_bt(self):
pass
def detect_usb(self):
pass
def detect_ac(self):
pass
def detect_battery(self):
pass
def detect_tray(self):
pass
def detect_ethernet(self):
pass
def kill_the_system(self, warning: str):
pass
| 9 | 0 | 11 | 1 | 10 | 0 | 4 | 0.01 | 1 | 9 | 1 | 0 | 8 | 0 | 8 | 38 | 96 | 15 | 80 | 28 | 71 | 1 | 70 | 26 | 61 | 9 | 5 | 6 | 32 |
147,621 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/HTMLPlotter/TVarFigure1D.py
|
pytplot.HTMLPlotter.TVarFigure1D.TVarFigure1D
|
class TVarFigure1D(object):
def __init__(self, tvar_name, auto_color, show_xaxis=False, slice=False):
self.tvar_name = tvar_name
self.auto_color = auto_color
self.show_xaxis = show_xaxis
if 'show_all_axes' in pytplot.tplot_opt_glob:
if pytplot.tplot_opt_glob['show_all_axes']:
self.show_xaxis = True
self.slice = slice
# Variables needed across functions
self.colors = ['black', 'red', 'green', 'navy', 'orange', 'firebrick', 'pink', 'blue', 'olive']
self.lineglyphs = []
self.linenum = 0
self.interactive_plot = None
self.fig = Figure(x_axis_type='datetime',
tools=pytplot.tplot_opt_glob['tools'],
y_axis_type=self._getyaxistype())
self.fig.add_tools(BoxZoomTool(dimensions='width'))
self._format()
@staticmethod
def get_axis_label_color():
if pytplot.tplot_opt_glob['black_background']:
text_color = '#000000'
else:
text_color = '#FFFFFF'
return text_color
@staticmethod
def getaxistype():
axis_type = 'time'
link_y_axis = False
return axis_type, link_y_axis
def getfig(self):
if self.slice:
return [self.fig, self.interactive_plot]
else:
return [self.fig]
def setsize(self, width, height):
self.fig.plot_width = width
if self.show_xaxis:
self.fig.plot_height = height + 22
else:
self.fig.plot_height = height
def add_title(self):
if 'title_text' in pytplot.tplot_opt_glob:
if pytplot.tplot_opt_glob['title_text'] != '':
title1 = Title(text=pytplot.tplot_opt_glob['title_text'],
align=pytplot.tplot_opt_glob['title_align'],
text_font_size=pytplot.tplot_opt_glob['title_size'],
text_color=self.get_axis_label_color())
self.fig.title = title1
self.fig.plot_height += 22
def buildfigure(self):
self._setminborder()
self._setxrange()
self._setxaxis()
self._setyrange()
self._addtimebars()
self._visdata()
self._setxaxislabel()
self._setyaxislabel()
self._addhoverlines()
self._addlegend()
def _format(self):
# Formatting stuff
self.fig.grid.grid_line_color = None
self.fig.axis.major_tick_line_color = None
self.fig.axis.major_label_standoff = 0
self.fig.xaxis.formatter = dttf
self.fig.title = None
self.fig.toolbar.active_drag = 'auto'
if not self.show_xaxis:
self.fig.xaxis.major_label_text_font_size = '0pt'
self.fig.xaxis.visible = False
def _setxrange(self):
# Check if x range is not set, if not, set good ones
if 'x_range' not in pytplot.tplot_opt_glob:
datasets = [pytplot.data_quants[self.tvar_name]]
x_min_list = []
x_max_list = []
for oplot_name in pytplot.data_quants[self.tvar_name].attrs['plot_options']['overplots']:
datasets.append(pytplot.data_quants[oplot_name])
for dataset in datasets:
x_min_list.append(np.nanmin(dataset.coords['time']))
x_max_list.append(np.nanmax(dataset.coords['time']))
pytplot.tplot_opt_glob['x_range'] = [np.nanmin(x_min_list), np.nanmax(x_max_list)]
tplot_x_range = [np.nanmin(x_min_list), np.nanmax(x_max_list)]
if self.show_xaxis:
pytplot.lim_info['xfull'] = tplot_x_range
pytplot.lim_info['xlast'] = tplot_x_range
# Bokeh uses milliseconds since epoch for some reason
x_range = Range1d(int(pytplot.tplot_opt_glob['x_range'][0]) * 1000.0,
int(pytplot.tplot_opt_glob['x_range'][1]) * 1000.0)
self.fig.x_range = x_range
def _setyrange(self):
if self._getyaxistype() == 'log':
if pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][0] <= 0 or \
pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][1] <= 0:
return
y_range = Range1d(pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][0],
pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][1])
self.fig.y_range = y_range
def _setminborder(self):
self.fig.min_border_bottom = pytplot.tplot_opt_glob['min_border_bottom']
self.fig.min_border_top = pytplot.tplot_opt_glob['min_border_top']
if 'vertical_spacing' in pytplot.tplot_opt_glob:
self.fig.min_border_bottom = int(pytplot.tplot_opt_glob['vertical_spacing'] / 2.0)
self.fig.min_border_top = int(pytplot.tplot_opt_glob['vertical_spacing'] / 2.0)
def _addtimebars(self):
for time_bar in pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar']:
time_bar_line = Span(location=time_bar['location']*1000.0, dimension=time_bar['dimension'],
line_color=time_bar['line_color'], line_width=time_bar['line_width'])
self.fig.renderers.extend([time_bar_line])
def _set_roi_lines(self, dataset):
# Locating the two times between which there's a roi
time = dataset.coords['time'].values
roi_1 = pytplot.tplot_utilities.str_to_int(pytplot.tplot_opt_glob['roi_lines'][0])
roi_2 = pytplot.tplot_utilities.str_to_int(pytplot.tplot_opt_glob['roi_lines'][1])
# find closest time to user-requested time
x = np.asarray(time)
x_sub_1 = abs(x - roi_1 * np.ones(len(x)))
x_sub_2 = abs(x - roi_2 * np.ones(len(x)))
x_argmin_1 = np.nanargmin(x_sub_1)
x_argmin_2 = np.nanargmin(x_sub_2)
x_closest_1 = x[x_argmin_1]
x_closest_2 = x[x_argmin_2]
# Create roi box
roi_box = BoxAnnotation(left=x_closest_1*1000.0, right=x_closest_2*1000.0, fill_alpha=0.2, fill_color='grey',
line_color='red', line_width=2.5)
self.fig.renderers.extend([roi_box])
def _setxaxis(self):
xaxis1 = DatetimeAxis(major_label_text_font_size='0pt', formatter=dttf)
xaxis1.visible = False
self.fig.add_layout(xaxis1, 'above')
def _getyaxistype(self):
if 'y_axis_type' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']:
return pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_axis_type']
else:
return 'linear'
def _setcolors(self):
if 'line_color' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']:
self.colors = pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['line_color']
def _setxaxislabel(self):
self.fig.xaxis.axis_label = pytplot.data_quants[self.tvar_name].attrs['plot_options']['xaxis_opt']['axis_label']
self.fig.xaxis.axis_label_text_font_size = str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])+'pt'
self.fig.xaxis.axis_label_text_color = self.get_axis_label_color()
def _setyaxislabel(self):
self.fig.yaxis.axis_label = pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['axis_label']
self.fig.yaxis.axis_label_text_font_size = str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])+'pt'
self.fig.yaxis.axis_label_text_color = self.get_axis_label_color()
def _visdata(self):
self._setcolors()
datasets = [pytplot.data_quants[self.tvar_name]]
for oplot_name in pytplot.data_quants[self.tvar_name].attrs['plot_options']['overplots']:
datasets.append(pytplot.data_quants[oplot_name])
for dataset in datasets:
# Get Linestyle
line_style = None
if 'linestyle' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']:
line_style = pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['linestyle']
# Get a list of formatted times
corrected_time = []
for x in dataset.coords['time'].values:
corrected_time.append(tplot_utilities.int_to_str(x))
# Bokeh uses milliseconds since epoch for some reason
x = dataset.coords['time'].values * 1000.0
# Add region of interest (roi) lines if applicable
if 'roi_lines' in pytplot.tplot_opt_glob.keys():
self._set_roi_lines(dataset)
plot_options = dataset.attrs['plot_options']
df = pytplot.tplot_utilities.convert_tplotxarray_to_pandas_dataframe(dataset.name, no_spec_bins=True)
# Create lines from each column in the dataframe
for column_name in df.columns:
y = df[column_name]
# Account for log plotting
if self._getyaxistype() == 'log':
y.loc[y <= 0] = np.NaN
if 'line_style' in plot_options['line_opt']:
if plot_options['line_opt']['line_style'] == 'scatter':
Glyph = X
else:
Glyph = Line
else:
Glyph = Line
# Until what size of a data gap are we removing nan values from the dataset? Set by the user
# (default is to plot as bokeh would normally plot w/o worrying about data gap handling).
limit = pytplot.tplot_opt_glob['data_gap']
if limit != 0:
# Grabbing the times associated with nan values (nan_values), and the associated "position" of those
# keys in the dataset list (nan_keys)
nan_values = y[y.isnull().values].index.tolist()
nan_keys = [y.index.tolist().index(j) for j in nan_values]
nans = dict(zip(nan_keys, nan_values))
count = 0 # Keeping a count of how big of a time gap we have
consec_list = list() # List of consecutive nan values (composed of indices for gaps not bigger than
# the user-specified data gap)
for val in range(len(nan_keys)):
# Avoiding some weird issues with going to the last data point in the nan dictionary keys
if val != (len(nan_keys)-1):
# Difference between one index and another - if consecutive indices, the diff will be 1
diff = abs(nan_keys[val] - nan_keys[val+1])
# calculate time accumulated from one index to the next
t_now = nan_values[val]
t_next = nan_values[val + 1]
time_accum = abs(t_now - t_next)
# If we haven't reached the allowed data gap, just keep track of how big of a gap we're at,
# and the indices in the gap
if diff == 1 and count < limit:
count += time_accum
consec_list.append(nan_keys[val])
# This triggers when we initially exceed the allowed data gap
elif diff == 1 and count >= limit:
pass
# When we find that the previous index and the current one are not consecutive, stop adding to
# the consec_list/overall_list (if applicable), and start over the count of time accumulated
# in a gap, as well as the consecutive list of time values with nans
elif diff != 1:
# Restart the count and add the current val to the list of nan values to remove
count = 0
consec_list.append(nan_keys[val])
times = x.tolist()
for elem in consec_list:
# Unless the data gap was big enough, we need to remove nan values from the data,
# otherwise bokeh will automatically NOT interpolate (the exact opposite of behavior in
# pyqtgraph, which ALWAYS interpolates...).
times.remove(nans[elem]*1000.0)
del y[nans[elem]]
del corrected_time[corrected_time.index(tplot_utilities.int_to_str(nans[elem]))]
# Data to be plotted
line_source = ColumnDataSource(data=dict(x=times, y=y, corrected_time=corrected_time))
else:
# Data to be plotted
line_source = ColumnDataSource(data=dict(x=x, y=y, corrected_time=corrected_time))
if self.auto_color:
line = Glyph(x='x', y='y', line_color=self.colors[self.linenum % len(self.colors)])
else:
line = Glyph(x='x', y='y')
if Glyph == Line:
if 'line_style' not in plot_options['line_opt']:
if line_style is not None:
line.line_dash = line_style[self.linenum % len(line_style)]
else:
line.line_dash = plot_options['line_style']
self.lineglyphs.append(self.fig.add_glyph(line_source, line))
self.linenum += 1
def _addhoverlines(self):
# Add tools
hover = HoverTool()
hover.tooltips = [("Time", "@corrected_time"), ("Value", "@y")]
self.fig.add_tools(hover)
def _addlegend(self):
# Add the Legend if applicable
if 'legend_names' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']:
legend_names = pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['legend_names']
if len(legend_names) != self.linenum:
print("Number of lines do not match length of legend names")
legend = Legend()
legend.location = (0, 0)
legend_items = []
j = 0
for legend_name in legend_names:
legend_items.append((legend_name, [self.lineglyphs[j]]))
j = j+1
if j >= len(self.lineglyphs):
break
legend.items = legend_items
legend.label_text_font_size = str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])+'pt'
legend.border_line_color = None
legend.glyph_height = int(self.fig.plot_height / (len(legend_items) + 1))
self.fig.add_layout(legend, 'right')
|
class TVarFigure1D(object):
def __init__(self, tvar_name, auto_color, show_xaxis=False, slice=False):
pass
@staticmethod
def get_axis_label_color():
pass
@staticmethod
def getaxistype():
pass
def getfig(self):
pass
def setsize(self, width, height):
pass
def add_title(self):
pass
def buildfigure(self):
pass
def _format(self):
pass
def _setxrange(self):
pass
def _setyrange(self):
pass
def _setminborder(self):
pass
def _addtimebars(self):
pass
def _set_roi_lines(self, dataset):
pass
def _setxaxis(self):
pass
def _getyaxistype(self):
pass
def _setcolors(self):
pass
def _setxaxislabel(self):
pass
def _setyaxislabel(self):
pass
def _visdata(self):
pass
def _addhoverlines(self):
pass
def _addlegend(self):
pass
| 24 | 0 | 13 | 1 | 11 | 2 | 3 | 0.17 | 1 | 6 | 0 | 0 | 19 | 9 | 21 | 21 | 306 | 37 | 234 | 91 | 210 | 39 | 211 | 89 | 189 | 21 | 1 | 6 | 63 |
147,622 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/QtPlotter/CustomLinearRegionItem/CustomLinearRegionItem.py
|
CustomLinearRegionItem.CustomLinearRegionItem
|
class CustomLinearRegionItem(pg.LinearRegionItem):
"""Inheriting the LinearRegionItem class because if someone hovers over a region of interest box,
I don't want it to have a different alpha value than when the mouse is not over the box."""
def setMouseHover(self, hover):
# Inform the item that the mouse is(not) hovering over it
if self.mouseHovering == hover:
return
self.mouseHovering = hover
if hover:
c = self.brush.color()
c.setAlpha(c.alpha() * 1)
self.currentBrush = fn.mkBrush(c)
else:
self.currentBrush = self.brush
self.update()
|
class CustomLinearRegionItem(pg.LinearRegionItem):
'''Inheriting the LinearRegionItem class because if someone hovers over a region of interest box,
I don't want it to have a different alpha value than when the mouse is not over the box.'''
def setMouseHover(self, hover):
pass
| 2 | 1 | 12 | 0 | 11 | 1 | 3 | 0.25 | 1 | 0 | 0 | 0 | 1 | 2 | 1 | 1 | 16 | 1 | 12 | 5 | 10 | 3 | 11 | 5 | 9 | 3 | 1 | 1 | 3 |
147,623 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/HTMLPlotter/CustomModels/colorbarsidetitle.py
|
pytplot.HTMLPlotter.CustomModels.colorbarsidetitle.ColorBarSideTitle
|
class ColorBarSideTitle(ColorBar):
__implementation__ = TypeScript(ts_code)
|
class ColorBarSideTitle(ColorBar):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
147,624 |
MAVENSDC/PyTplot
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MAVENSDC_PyTplot/pytplot/__init__.py
|
pytplot.PlotWindow
|
class PlotWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
def init_savepng(self, exporter):
if exporter is None:
return
# Set up the save PNG button/call exportpng function that activates when user presses button
exportdatapngaction = QtWidgets.QAction("Save PNG", self)
exportdatapngaction.triggered.connect(
lambda: self.exportpng(exporter))
# Set up menu bar to display and call creation of save PNG button
menubar = self.menuBar()
menubar.setNativeMenuBar(False)
menubar.addAction(exportdatapngaction)
self.setWindowTitle('PyTplot Window')
def exportpng(self, exporter):
if exporter is None:
print(
"Cannot save the image. Try installing h5py to get around this issue.")
return
# Function called by save PNG button to grab the image from the plot window and save it
fname = QtWidgets.QFileDialog.getSaveFileName(
self, 'Open file', 'pytplot.png', filter="png (*.png *.)")
exporter.parameters()[
'width'] = tplot_opt_glob['window_size'][0]
exporter.parameters()[
'height'] = tplot_opt_glob['window_size'][1]
exporter.export(fname[0])
def newlayout(self, layout):
# Needed for displaying plots
self.setCentralWidget(layout)
|
class PlotWindow(QtWidgets.QMainWindow):
def __init__(self):
pass
def init_savepng(self, exporter):
pass
def exportpng(self, exporter):
pass
def newlayout(self, layout):
pass
| 5 | 0 | 7 | 0 | 5 | 1 | 2 | 0.18 | 1 | 1 | 0 | 0 | 4 | 0 | 4 | 4 | 30 | 4 | 22 | 8 | 17 | 4 | 22 | 8 | 17 | 2 | 1 | 1 | 6 |
147,625 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/HTMLPlotter/CustomModels/timestamp.py
|
pytplot.HTMLPlotter.CustomModels.timestamp.TimeStamp
|
class TimeStamp(LayoutDOM):
__implementation__ = TypeScript(JS_CODE)
text = String(default = "Testing")
|
class TimeStamp(LayoutDOM):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
147,626 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/QtPlotter/PyTPlot_Exporter.py
|
pytplot.QtPlotter.PyTPlot_Exporter.PytplotExporter
|
class PytplotExporter(pg.exporters.ImageExporter):
def __init__(self, item):
Exporter.__init__(self, item)
tr = self.getTargetRect()
if isinstance(item, QtGui.QGraphicsItem):
scene = item.scene()
else:
scene = item
# CHANGE: Used to be scene.views()[0].backgroundBrush()
# That wasn't how to access the background of a GraphicsLayout object
bgbrush = scene.backgroundBrush()
bg = bgbrush.color()
if bgbrush.style() == QtCore.Qt.NoBrush:
bg.setAlpha(0)
self.params = Parameter(name='params', type='group', children=[
{'name': 'width', 'type': 'int', 'value': tr.width(), 'limits': (0, None)},
{'name': 'height', 'type': 'int', 'value': tr.height(), 'limits': (0, None)},
{'name': 'antialias', 'type': 'bool', 'value': True},
{'name': 'background', 'type': 'color', 'value': bg},
])
self.params.param('width').sigValueChanged.connect(self.widthChanged)
self.params.param('height').sigValueChanged.connect(self.heightChanged)
def export(self, fileName=None, toBytes=False, copy=False):
if fileName is None and not toBytes and not copy:
if pg.Qt.USE_PYSIDE:
filter = ["*." + str(f) for f in QtGui.QImageWriter.supportedImageFormats()]
else:
filter = ["*." + bytes(f).decode('utf-8') for f in QtGui.QImageWriter.supportedImageFormats()]
preferred = ['*.png', '*.tif', '*.jpg']
for p in preferred[::-1]:
if p in filter:
filter.remove(p)
filter.insert(0, p)
self.fileSaveDialog(filter=filter)
return
targetRect = QtCore.QRect(0, 0, self.params['width'], self.params['height'])
sourceRect = self.getSourceRect()
# self.png = QtGui.QImage(targetRect.size(), QtGui.QImage.Format_ARGB32)
# self.png.fill(pyqtgraph.mkColor(self.params['background']))
w, h = self.params['width'], self.params['height']
if w == 0 or h == 0:
raise Exception("Cannot export image with size=0 (requested export size is %dx%d)" % (w, h))
bg = np.empty((int(self.params['width']), int(self.params['height']), 4), dtype=np.ubyte)
color = self.params['background']
bg[:, :, 0] = color.blue()
bg[:, :, 1] = color.green()
bg[:, :, 2] = color.red()
bg[:, :, 3] = color.alpha()
self.png = fn.makeQImage(bg, alpha=True)
# set resolution of image:
origTargetRect = self.getTargetRect()
resolutionScale = targetRect.width() / origTargetRect.width()
painter = QtGui.QPainter(self.png)
# dtr = painter.deviceTransform()
try:
self.setExportMode(True,
{'antialias': self.params['antialias'], 'background': self.params['background'],
'painter': painter, 'resolutionScale': resolutionScale})
painter.setRenderHint(QtGui.QPainter.Antialiasing, self.params['antialias'])
# CHANGE: Rendering the scence twice onto the QImage. The first time, make it one pixel in size.
# Next, render the full thing. No idea why we need to render is twice, but we do.
self.getScene().render(painter, QtCore.QRectF(0, 0, 1, 1), QtCore.QRectF(0, 0, 1, 1))
self.getScene().render(painter, QtCore.QRectF(targetRect), QtCore.QRectF(sourceRect))
finally:
self.setExportMode(False)
painter.end()
if copy:
QtGui.QApplication.clipboard().setImage(self.png)
elif toBytes:
return self.png
else:
self.png.save(fileName)
def getPaintItems(self, root=None):
"""Return a list of all items that should be painted in the correct order."""
if root is None:
root = self.item
preItems = []
postItems = []
if isinstance(root, QtGui.QGraphicsScene):
childs = [i for i in root.items() if i.parentItem() is None]
rootItem = []
else:
# CHANGE: For GraphicsLayouts, there is no function for childItems(), so I just
# replaced it with .items()
try:
childs = root.childItems()
except:
childs = root.items()
rootItem = [root]
childs.sort(key=lambda a: a.zValue())
while len(childs) > 0:
ch = childs.pop(0)
tree = self.getPaintItems(ch)
if int(ch.flags() & ch.ItemStacksBehindParent) > 0 or (
ch.zValue() < 0 and int(ch.flags() & ch.ItemNegativeZStacksBehindParent) > 0):
preItems.extend(tree)
else:
postItems.extend(tree)
return preItems + rootItem + postItems
def getTargetRect(self):
# CHANGE: Used to return self.item.sceneBoundingRect(). GraphicsLayouts don't have a
# sceneBoundingRect(), but they have a rect() which appears to work just as well.
return self.item.rect()
def getSourceRect(self):
# CHANGE: Used to return self.item.mapRectToDevice(self.item.boundingRect()). GraphicsLayouts don't have a
# sceneBoundingRect() OR a mapRectToDevice, but they have a rect() which appears to work just as well.
return self.item.rect()
|
class PytplotExporter(pg.exporters.ImageExporter):
def __init__(self, item):
pass
def export(self, fileName=None, toBytes=False, copy=False):
pass
def getPaintItems(self, root=None):
'''Return a list of all items that should be painted in the correct order.'''
pass
def getTargetRect(self):
pass
def getSourceRect(self):
pass
| 6 | 1 | 23 | 2 | 18 | 3 | 4 | 0.16 | 1 | 4 | 0 | 0 | 5 | 2 | 5 | 5 | 121 | 14 | 92 | 29 | 86 | 15 | 77 | 29 | 71 | 8 | 1 | 3 | 19 |
147,627 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/QtPlotter/CustomAxis/DateAxis.py
|
pytplot.QtPlotter.CustomAxis.DateAxis.DateAxis
|
class DateAxis(pg.AxisItem):
"""
This class takes in tplot time variables and creates ticks/tick labels
depending on the time length of the data.
"""
def tickStrings(self, values, scale, spacing):
strns = []
if not values:
return strns
for x in values:
try:
rng = max(values)-min(values)
if rng < 0.001:
string = '%f'
label1 = '%b %d -'
label2 = ' %b %d, %Y'
strns.append(str(round(int(datetime.datetime.utcfromtimestamp(x).strftime(string))/1000000, 6)))
continue
# less than 1 sec of data
elif 0.001 <= rng < 1:
string = '%f'
label1 = '%b %d -'
label2 = ' %b %d, %Y'
strns.append(str(round(int(datetime.datetime.utcfromtimestamp(x).strftime(string))/1000000, 3)))
continue
# Less than five minutes' worth of data
elif 1 <= rng < 300:
# Show hour, min, and sec.
string = '%H:%M:%S'
label1 = '%b %d -'
label2 = ' %b %d, %Y'
# Between five minutes' and four days' worth of data
elif 300 <= rng < 3600*24*4:
# If a new day (some day at 00:00:00 UTC), go ahead and actually
# write out the date
if x % 86400 == 0:
# show YYYY-MM-DD
string = '%Y-%m-%d'
label1 = '%b %d -'
label2 = ' %b %d, %Y'
else:
# Just show hour and min.
string = '%H:%M'
label1 = '%b %d -'
label2 = ' %b %d, %Y'
# Between four days' worth of data and ~ 4 months of data
elif 3600*24*4 <= rng < 4*3600*24*30:
# To keep things uncrowded, just putting month & day, and not the hour/min as well
string = '%m-%d'
label1 = '%b %d -'
label2 = ' %b %d, %Y'
# Between ~ 4 months worth of data and two years' of worth of data
elif 4*3600*24*30 <= rng < 3600*24*30*24:
# Show abbreviated month name and full year (YYYY)
string = '%b-%Y'
label1 = '%Y -'
label2 = ' %Y'
# Greater than two years' worth of data
elif rng >= 3600*24*30*24:
# Just show the year (YYYY)
string = '%Y'
label1 = ''
label2 = ''
strns.append(datetime.datetime.utcfromtimestamp(x).strftime(string))
except ValueError:
# Windows can't handle dates before 1970
strns.append(' ')
return strns
def tickSpacing(self, minVal, maxVal, size):
rng = maxVal - minVal
levels = [(1, 0)]
if rng < 0.001:
levels = [(0.0001, 0)]
elif 0.001 <= rng < 0.01:
levels = [(0.001, 0)]
elif 0.01 <= rng < 0.2:
levels = [(0.01, 0)]
elif 0.2 <= rng < 1:
levels = [(0.1, 0)]
elif 1 <= rng < 3:
levels = [(0.5, 0)]
elif 3 <= rng < 4:
# Show ticks every second if you're looking at < four seconds' worth of data
levels = [(1, 0)]
elif 4 <= rng < 15:
# Show ticks every two seconds if you're looking between four and 15 seconds' worth of data
levels = [(2, 0)]
elif 15 <= rng < 60:
# Show ticks every five seconds if you're looking between 15 seconds' and one minutes' worth of data
levels = [(5, 0)]
elif 60 <= rng < 300:
# Show ticks every 30 seconds if you're looking between 1 and 5 minutes worth of data
levels = [(30, 0)]
elif 300 <= rng < 600:
# Show ticks every minute if you're looking between 5 and 10 minutes worth of data
levels = [(60, 0)]
elif 600 <= rng < 1800:
# Show ticks every 5 minutes if you're looking between 10 and 30 minutes worth of data
levels = [(300, 0)]
elif 1800 <= rng < 3600:
# Show ticks every 15 minutes if you're looking between 30 minutes' and one hours' worth of data
levels = [(900, 0)]
elif 3600 <= rng < 3600*2:
# Show ticks every 30 minutes if you're looking between one and two hours' worth of data
levels = [(1800, 0)]
elif 3600*2 <= rng < 3600*6:
# Show ticks every hour if you're looking between two and six hours' worth of data
levels = [(3600, 0)]
elif 3600*6 <= rng < 3600*12:
# Show ticks every two hours if you're looking between six and 12 hours' worth of data
levels = [(7200, 0)]
elif 3600*12 <= rng < 3600*24:
# Show ticks every four hours if you're looking between 12 hours' and one days' worth of data
levels = [(14400, 0)]
elif 3600*24 <= rng < 3600*24*2:
# Show ticks every six hours if you're looking at between one and two days' worth of data
levels = [(21600, 0)]
elif 3600*24*2 <= rng < 3600*24*4:
# show ticks every 12 hours if you're looking between two and four days' worth of data
levels = [(43200, 0)]
elif 3600*24*4 <= rng < 3600*24*30:
# show ticks every two days if data between four days and ~ 1 month
levels = [(172800, 0)]
elif 3600*24*30 <= rng < 2.0*3600*24*30:
# show ticks every four days if data between 1 month and 2 months
levels = [(345600, 0)]
elif 2*3600*24*30 <= rng < 4*3600*24*30:
# show ticks every 7 days if data between 2 month and 4 months
levels = [(604800, 0)]
elif 4*3600*24*30 <= rng < 3600*24*30*24:
# show ticks ~ every month if data between ~ 4 months and ~ two years
levels = [(2.592e+6, 0)]
elif rng >= 3600*24*30*24:
# show ticks ~ every year if data > two years
# show ~ every year
levels = [(3.154e+7, 0)]
return levels
|
class DateAxis(pg.AxisItem):
'''
This class takes in tplot time variables and creates ticks/tick labels
depending on the time length of the data.
'''
def tickStrings(self, values, scale, spacing):
pass
def tickSpacing(self, minVal, maxVal, size):
pass
| 3 | 1 | 67 | 1 | 49 | 17 | 18 | 0.38 | 1 | 4 | 0 | 0 | 2 | 0 | 2 | 2 | 139 | 2 | 99 | 11 | 96 | 38 | 70 | 11 | 67 | 24 | 1 | 4 | 36 |
147,628 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/QtPlotter/CustomLegend/CustomLegend.py
|
pytplot.QtPlotter.CustomLegend.CustomLegend.CustomLegendItem
|
class CustomLegendItem(pg.LegendItem):
def addItem(self,name1,name2):
label1 = LabelItem(name1)
label2 = LabelItem(name2)
row = self.layout.rowCount()
self.items.append((label1, label2))
self.layout.addItem(label1, row, 0)
self.layout.addItem(label2, row, 1)
self.updateSize()
def removeItem(self, name):
for label, data in self.items:
if label.text == name: # hit
self.items.remove( (label, data) ) # remove from itemlist
self.layout.removeItem(label) # remove from layout
label.close() # remove from drawing
self.layout.removeItem(data)
data.close()
self.updateSize() # redraq box
def setItem(self, label_name, new_data):
for label, data in self.items:
if label.text == label_name:
data.setText(new_data)
return
self.addItem(label_name, new_data)
def paint(self, p, *args):
p.setPen(fn.mkPen(255,255,255,0))
p.setBrush(fn.mkBrush(0,0,0,190))
p.drawRect(self.boundingRect())
def hoverEvent(self, ev):
#ev.acceptDrags(QtCore.Qt.LeftButton)
return
def mouseDragEvent(self, ev):
return
|
class CustomLegendItem(pg.LegendItem):
def addItem(self,name1,name2):
pass
def removeItem(self, name):
pass
def setItem(self, label_name, new_data):
pass
def paint(self, p, *args):
pass
def hoverEvent(self, ev):
pass
def mouseDragEvent(self, ev):
pass
| 7 | 0 | 5 | 0 | 5 | 1 | 2 | 0.19 | 1 | 0 | 0 | 0 | 6 | 0 | 6 | 6 | 39 | 6 | 32 | 12 | 25 | 6 | 32 | 12 | 25 | 3 | 1 | 2 | 10 |
147,629 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/QtPlotter/CustomImage/ColorbarImage.py
|
pytplot.QtPlotter.CustomImage.ColorbarImage.ColorbarImage
|
class ColorbarImage(pg.ImageItem):
'''
For the most part, this class is exactly the same as pg.ImageItem.
This exist literally only because collections.Callable became collections.abc.Callable
and it was causing errors.
'''
def render(self):
# Convert data to QImage for display.
profile = debug.Profiler()
if self.image is None or self.image.size == 0:
return
if isinstance(self.lut, collections.abc.Callable):
lut = self.lut(self.image)
else:
lut = self.lut
if self.autoDownsample:
# reduce dimensions of image based on screen resolution
o = self.mapToDevice(QtCore.QPointF(0, 0))
x = self.mapToDevice(QtCore.QPointF(1, 0))
y = self.mapToDevice(QtCore.QPointF(0, 1))
w = Point(x - o).length()
h = Point(y - o).length()
if w == 0 or h == 0:
self.qimage = None
return
xds = max(1, int(1.0 / w))
yds = max(1, int(1.0 / h))
axes = [1, 0] if self.axisOrder == 'row-major' else [0, 1]
image = fn.downsample(self.image, xds, axis=axes[0])
image = fn.downsample(image, yds, axis=axes[1])
self._lastDownsample = (xds, yds)
else:
image = self.image
# if the image data is a small int, then we can combine levels + lut
# into a single lut for better performance
levels = self.levels
if levels is not None and levels.ndim == 1 and image.dtype in (np.ubyte, np.uint16):
if self._effectiveLut is None:
eflsize = 2 ** (image.itemsize * 8)
ind = np.arange(eflsize)
minlev, maxlev = levels
levdiff = maxlev - minlev
levdiff = 1 if levdiff == 0 else levdiff # don't allow division by 0
if lut is None:
efflut = fn.rescaleData(ind, scale=255. / levdiff,
offset=minlev, dtype=np.ubyte)
else:
lutdtype = np.min_scalar_type(lut.shape[0] - 1)
efflut = fn.rescaleData(ind, scale=(lut.shape[0] - 1) / levdiff,
offset=minlev, dtype=lutdtype, clip=(0, lut.shape[0] - 1))
efflut = lut[efflut]
self._effectiveLut = efflut
lut = self._effectiveLut
levels = None
# Assume images are in column-major order for backward compatibility
# (most images are in row-major order)
if self.axisOrder == 'col-major':
image = image.transpose((1, 0, 2)[:image.ndim])
argb, alpha = fn.makeARGB(image, lut=lut, levels=levels)
self.qimage = fn.makeQImage(argb, alpha, transpose=False)
|
class ColorbarImage(pg.ImageItem):
'''
For the most part, this class is exactly the same as pg.ImageItem.
This exist literally only because collections.Callable became collections.abc.Callable
and it was causing errors.
'''
def render(self):
pass
| 2 | 1 | 61 | 7 | 48 | 7 | 11 | 0.24 | 1 | 1 | 0 | 0 | 1 | 4 | 1 | 1 | 69 | 9 | 49 | 24 | 47 | 12 | 44 | 24 | 42 | 11 | 1 | 3 | 11 |
147,630 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/QtPlotter/CustomAxis/NonLinearAxis.py
|
pytplot.QtPlotter.CustomAxis.NonLinearAxis.NonLinearAxis
|
class NonLinearAxis(pg.AxisItem):
def __init__(self, orientation, pen=None, linkView=None, parent=None, maxTickLength=-5, showValues=True, mapping_function=None, num_ticks=4):
pg.AxisItem.__init__(self, orientation=orientation, pen=pen, linkView=linkView, parent=parent, maxTickLength=maxTickLength, showValues=showValues)
self.f = mapping_function
self.num_ticks = num_ticks
def tickStrings(self, values, scale, spacing):
strns = []
for x in values:
try:
strns.append(str(int(self.f(x))))
except ValueError:
strns.append('')
return strns
def tickValues(self, minVal, maxVal, size):
minVal, maxVal = sorted((minVal, maxVal))
minVal *= self.scale
maxVal *= self.scale
ticks=[]
xrange = maxVal - minVal
for i in range(0, self.num_ticks+1):
ticks.append(minVal+(i*xrange/self.num_ticks))
return [(1.0,ticks)]
|
class NonLinearAxis(pg.AxisItem):
def __init__(self, orientation, pen=None, linkView=None, parent=None, maxTickLength=-5, showValues=True, mapping_function=None, num_ticks=4):
pass
def tickStrings(self, values, scale, spacing):
pass
def tickValues(self, minVal, maxVal, size):
pass
| 4 | 0 | 7 | 0 | 7 | 0 | 2 | 0 | 1 | 4 | 0 | 0 | 3 | 2 | 3 | 3 | 25 | 3 | 22 | 11 | 18 | 0 | 22 | 11 | 18 | 3 | 1 | 2 | 6 |
147,631 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/QtPlotter/CustomViewBox/CustomVB.py
|
pytplot.QtPlotter.CustomViewBox.CustomVB.CustomVB
|
class CustomVB(pg.ViewBox):
def mouseDragEvent(self, ev, axis=None):
return
|
class CustomVB(pg.ViewBox):
def mouseDragEvent(self, ev, axis=None):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 4 | 1 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
147,632 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/QtPlotter/CustomAxis/BlankAxis.py
|
pytplot.QtPlotter.CustomAxis.BlankAxis.BlankAxis
|
class BlankAxis(pg.AxisItem):
#Will need to override other functions in the future for this one
#Right now it chooses weird stupid places for ticks
def __init__(self, orientation, pen=None, linkView=None, parent=None, maxTickLength=-5, showValues=True):
pg.AxisItem.__init__(self, orientation=orientation, pen=pen, linkView=linkView, parent=parent, maxTickLength=maxTickLength, showValues=showValues)
def tickStrings(self, values, scale, spacing):
strns = []
for _ in values:
try:
strns.append('')
except ValueError:
strns.append('')
return strns
|
class BlankAxis(pg.AxisItem):
def __init__(self, orientation, pen=None, linkView=None, parent=None, maxTickLength=-5, showValues=True):
pass
def tickStrings(self, values, scale, spacing):
pass
| 3 | 0 | 5 | 0 | 5 | 0 | 2 | 0.18 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 2 | 14 | 1 | 11 | 5 | 8 | 2 | 11 | 5 | 8 | 3 | 1 | 2 | 4 |
147,633 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/QtPlotter/CustomAxis/AxisItem.py
|
pytplot.QtPlotter.CustomAxis.AxisItem.AxisItem
|
class AxisItem(pg.AxisItem):
"""
GraphicsItem showing a single plot axis with ticks, values, and label.
Can be configured to fit on any side of a plot, and can automatically synchronize its displayed scale with ViewBox
items. Ticks can be extended to draw a grid.
If maxTickLength is negative, ticks point into the plot.
"""
def _updateWidth(self):
if not self.isVisible():
w = 0
else:
if self.fixedWidth is None:
if not self.style['showValues']:
w = 0
elif self.style['autoExpandTextSpace'] is True:
w = self.textWidth
else:
w = self.style['tickTextWidth']
w += self.style['tickTextOffset'][0] if self.style['showValues'] else 0
w += max(0, self.style['tickLength'])
if self.label.isVisible():
# CHANGE
# This was originally multiplied by 0.8, however that resulted in a saved plot's colorbar label
# running into the tick labels
w += self.label.boundingRect().height() * 0.8 # bounding rect is usually an overestimate
else:
w = self.fixedWidth
self.setMaximumWidth(w)
self.setMinimumWidth(w)
self.picture = None
def getWidth(self):
if not self.isVisible():
w = 0
else:
if self.fixedWidth is None:
if not self.style['showValues']:
w = 0
elif self.style['autoExpandTextSpace'] is True:
w = self.textWidth
else:
w = self.style['tickTextWidth']
w += self.style['tickTextOffset'][0] if self.style['showValues'] else 0
w += max(0, self.style['tickLength'])
if self.label.isVisible():
# CHANGE
# This was originally multiplied by 0.8, however that resulted in a saved plot's colorbar label
# running into the tick labels
w += self.label.boundingRect().height() * 0.8 # bounding rect is usually an overestimate
else:
w = self.fixedWidth
return w
def generateDrawSpecs(self, p):
"""
Calls tickValues() and tickStrings() to determine where and how ticks should
be drawn, then generates from this a set of drawing commands to be
interpreted by drawPicture().
"""
profiler = debug.Profiler()
# bounds = self.boundingRect()
bounds = self.mapRectFromParent(self.geometry())
linkedView = self.linkedView()
if linkedView is None or self.grid is False:
tickBounds = bounds
else:
tickBounds = linkedView.mapRectToItem(self, linkedView.boundingRect())
if self.orientation == 'left':
span = (bounds.topRight(), bounds.bottomRight())
tickStart = tickBounds.right()
tickStop = bounds.right()
tickDir = -1
axis = 0
elif self.orientation == 'right':
span = (bounds.topLeft(), bounds.bottomLeft())
tickStart = tickBounds.left()
tickStop = bounds.left()
tickDir = 1
axis = 0
elif self.orientation == 'top':
span = (bounds.bottomLeft(), bounds.bottomRight())
tickStart = tickBounds.bottom()
tickStop = bounds.bottom()
tickDir = -1
axis = 1
elif self.orientation == 'bottom':
span = (bounds.topLeft(), bounds.topRight())
tickStart = tickBounds.top()
tickStop = bounds.top()
tickDir = 1
axis = 1
# print tickStart, tickStop, span
## determine size of this item in pixels
points = list(map(self.mapToDevice, span))
if None in points:
return
lengthInPixels = Point(points[1] - points[0]).length()
if lengthInPixels == 0:
return
# Determine major / minor / subminor axis ticks
if self._tickLevels is None:
tickLevels = self.tickValues(self.range[0], self.range[1], lengthInPixels)
tickStrings = None
else:
## parse self.tickLevels into the formats returned by tickLevels() and tickStrings()
tickLevels = []
tickStrings = []
for level in self._tickLevels:
values = []
strings = []
tickLevels.append((None, values))
tickStrings.append(strings)
for val, strn in level:
values.append(val)
strings.append(strn)
## determine mapping between tick values and local coordinates
dif = self.range[1] - self.range[0]
if dif == 0:
xScale = 1
offset = 0
else:
if axis == 0:
xScale = -bounds.height() / dif
offset = self.range[0] * xScale - bounds.height()
else:
xScale = bounds.width() / dif
offset = self.range[0] * xScale
xRange = [x * xScale - offset for x in self.range]
xMin = min(xRange)
xMax = max(xRange)
profiler('init')
tickPositions = [] # remembers positions of previously drawn ticks
## compute coordinates to draw ticks
## draw three different intervals, long ticks first
tickSpecs = []
for i in range(len(tickLevels)):
tickPositions.append([])
ticks = tickLevels[i][1]
## length of tick
tickLength = self.style['tickLength'] / ((i * 0.5) + 1.0)
lineAlpha = 255 / (i + 1)
if self.grid is not False:
lineAlpha *= self.grid / 255. * np.clip((0.05 * lengthInPixels / (len(ticks) + 1)), 0., 1.)
for v in ticks:
## determine actual position to draw this tick
x = (v * xScale) - offset
if x < xMin or x > xMax: ## last check to make sure no out-of-bounds ticks are drawn
tickPositions[i].append(None)
continue
tickPositions[i].append(x)
p1 = [x, x]
p2 = [x, x]
p1[axis] = tickStart
p2[axis] = tickStop
if self.grid is False:
p2[axis] += tickLength * tickDir
tickPen = self.pen()
color = tickPen.color()
color.setAlpha(int(lineAlpha))
tickPen.setColor(color)
tickSpecs.append((tickPen, Point(p1), Point(p2)))
profiler('compute ticks')
if self.style['stopAxisAtTick'][0] is True:
stop = max(span[0].y(), min(map(min, tickPositions)))
if axis == 0:
span[0].setY(stop)
else:
span[0].setX(stop)
if self.style['stopAxisAtTick'][1] is True:
stop = min(span[1].y(), max(map(max, tickPositions)))
if axis == 0:
span[1].setY(stop)
else:
span[1].setX(stop)
axisSpec = (self.pen(), span[0], span[1])
textOffset = self.style['tickTextOffset'][axis] ## spacing between axis and text
# if self.style['autoExpandTextSpace'] is True:
# textWidth = self.textWidth
# textHeight = self.textHeight
# else:
# textWidth = self.style['tickTextWidth'] ## space allocated for horizontal text
# textHeight = self.style['tickTextHeight'] ## space allocated for horizontal text
textSize2 = 0
textRects = []
textSpecs = [] ## list of draw
# If values are hidden, return early
if not self.style['showValues']:
return (axisSpec, tickSpecs, textSpecs)
for i in range(min(len(tickLevels), self.style['maxTextLevel'] + 1)):
## Get the list of strings to display for this level
if tickStrings is None:
spacing, values = tickLevels[i]
strings = self.tickStrings(values, self.autoSIPrefixScale * self.scale, spacing)
else:
strings = tickStrings[i]
if len(strings) == 0:
continue
## ignore strings belonging to ticks that were previously ignored
for j in range(len(strings)):
if tickPositions[i][j] is None:
strings[j] = None
## Measure density of text; decide whether to draw this level
rects = []
for s in strings:
if s is None:
rects.append(None)
else:
br = p.boundingRect(QtCore.QRectF(0, 0, 100, 100), QtCore.Qt.AlignCenter, str(s))
## boundingRect is usually just a bit too large
## (but this probably depends on per-font metrics?)
br.setHeight(br.height() * 1.4)
rects.append(br)
textRects.append(rects[-1])
if len(textRects) > 0:
## measure all text, make sure there's enough room
if axis == 0:
textSize = np.sum([r.height() for r in textRects])
textSize2 = np.max([r.width() for r in textRects])
else:
textSize = np.sum([r.width() for r in textRects])
textSize2 = np.max([r.height() for r in textRects])
else:
textSize = 0
textSize2 = 0
if i > 0: ## always draw top level
## If the strings are too crowded, stop drawing text now.
## We use three different crowding limits based on the number
## of texts drawn so far.
textFillRatio = float(textSize) / lengthInPixels
finished = False
for nTexts, limit in self.style['textFillLimits']:
if len(textSpecs) >= nTexts and textFillRatio >= limit:
finished = True
break
if finished:
break
# spacing, values = tickLevels[best]
# strings = self.tickStrings(values, self.scale, spacing)
# Determine exactly where tick text should be drawn
for j in range(len(strings)):
vstr = strings[j]
if vstr is None: ## this tick was ignored because it is out of bounds
continue
vstr = str(vstr)
x = tickPositions[i][j]
# textRect = p.boundingRect(QtCore.QRectF(0, 0, 100, 100), QtCore.Qt.AlignCenter, vstr)
textRect = rects[j]
height = textRect.height()
width = textRect.width()
# self.textHeight = height
offset = max(0, self.style['tickLength']) + textOffset
if self.orientation == 'left':
textFlags = QtCore.Qt.TextDontClip | QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter
rect = QtCore.QRectF(tickStop - offset - width, x - (height / 2), width, height)
elif self.orientation == 'right':
textFlags = QtCore.Qt.TextDontClip | QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter
rect = QtCore.QRectF(tickStop + offset, x - (height / 2), width, height)
elif self.orientation == 'top':
textFlags = QtCore.Qt.TextDontClip | QtCore.Qt.AlignCenter | QtCore.Qt.AlignBottom
rect = QtCore.QRectF(x - width / 2., tickStop - offset - height, width, height)
elif self.orientation == 'bottom':
textFlags = QtCore.Qt.TextDontClip | QtCore.Qt.AlignCenter | QtCore.Qt.AlignTop
rect = QtCore.QRectF(x - width / 2., tickStop + offset, width, height)
# p.setPen(self.pen())
# p.drawText(rect, textFlags, vstr)
textSpecs.append((rect, textFlags, vstr))
profiler('compute text')
## update max text size if needed.
self._updateMaxTextSize(textSize2)
return (axisSpec, tickSpecs, textSpecs)
|
class AxisItem(pg.AxisItem):
'''
GraphicsItem showing a single plot axis with ticks, values, and label.
Can be configured to fit on any side of a plot, and can automatically synchronize its displayed scale with ViewBox
items. Ticks can be extended to draw a grid.
If maxTickLength is negative, ticks point into the plot.
'''
def _updateWidth(self):
pass
def getWidth(self):
pass
def generateDrawSpecs(self, p):
'''
Calls tickValues() and tickStrings() to determine where and how ticks should
be drawn, then generates from this a set of drawing commands to be
interpreted by drawPicture().
'''
pass
| 4 | 2 | 97 | 10 | 72 | 18 | 19 | 0.27 | 1 | 6 | 0 | 0 | 3 | 1 | 3 | 3 | 299 | 31 | 217 | 62 | 213 | 59 | 193 | 62 | 189 | 42 | 1 | 4 | 56 |
147,634 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/QtPlotter/CustomImage/UpdatingImage.py
|
pytplot.QtPlotter.CustomImage.UpdatingImage.UpdatingImage
|
class UpdatingImage(pg.ImageItem):
'''
This is the class used to plot images of spectrogram data.
It automatically updates to higher and higher resolutions when you zoom in, thus the name
"updating image".
'''
_MAX_IMAGE_WIDTH = 10000
_MAX_IMAGE_HEIGHT = 2000
def __init__(self, x, y, data, lut, zmin, zmax):
pg.ImageItem.__init__(self)
self.lut = lut
self.w = 100 # This is just an initial value for the width
self.h = 100 # This is just an initial value for the height
self.x = x
self.y = y
self.data = data
self.xmin = np.nanmin(self.x)
self.xmax = np.nanmax(self.x)
self.ymin = np.nanmin(self.y)
self.ymax = np.nanmax(self.y)
self.zmin = zmin
self.zmax = zmax
self.picturenotgened=True
self.updatePicture()
def updatePicture(self, pixel_size=None):
# Get the dimensions in pixels and in plot coordiantes
if pixel_size is None:
width_in_pixels = pytplot.tplot_opt_glob['window_size'][0]
height_in_pixels = pytplot.tplot_opt_glob['window_size'][1]
width_in_plot_coords = pytplot.tplot_opt_glob['window_size'][0]
height_in_plot_coords = pytplot.tplot_opt_glob['window_size'][1]
else:
width_in_pixels = pixel_size.width()
height_in_pixels = pixel_size.height()
width_in_plot_coords = self.getViewBox().viewRect().width()
height_in_plot_coords = self.getViewBox().viewRect().height()
image_width_in_plot_coords = self.xmax - self.xmin
image_height_in_plot_coords = self.ymax - self.ymin
image_width_in_pixels = int(image_width_in_plot_coords/width_in_plot_coords * width_in_pixels)
image_height_in_pixels = int(image_height_in_plot_coords/height_in_plot_coords * height_in_pixels)
if image_width_in_pixels > self._MAX_IMAGE_WIDTH:
image_width_in_pixels = self._MAX_IMAGE_WIDTH
if image_height_in_pixels > self._MAX_IMAGE_HEIGHT:
image_height_in_pixels = self._MAX_IMAGE_HEIGHT
if self.w != image_width_in_pixels or self.h != image_height_in_pixels:
self.w = image_width_in_pixels
self.h = image_height_in_pixels
if self.w == 0:
self.w = 1
if self.h == 0:
self.h = 1
# Create an appropriate grid based on the window size, and interpolate the spectrogram to that
xp = np.linspace(self.xmin, self.xmax, self.w)
yp = np.linspace(self.ymin, self.ymax, self.h)
# Find the closest x values in the data for each pixel on the screen
closest_xs = np.searchsorted(self.x, xp)
# Find the closest y values in the data for each pixel on the screen
closest_ys = []
for yi in yp:
closest_ys.append((np.abs(self.y-yi)).argmin())
# Get the data at those x and y values
data = self.data[closest_xs][:, closest_ys]
# Set the image with that data
self.setImage(data.T, levels=[self.zmin, self.zmax])
#Image can't handle NaNs, but you can set nan to the minimum and make the minimum transparent.
self.setLookupTable(self.lut, update=False)
self.setRect(QtCore.QRectF(self.xmin,self.ymin,self.xmax-self.xmin,self.ymax-self.ymin))
return
def paint(self, p, *args):
'''
I have no idea why, but we need to generate the picture after painting otherwise
it draws incorrectly.
'''
parents = self.getBoundingParents()
for x in parents:
if type(x) is NoPaddingPlot:
parent_viewbox = x
if self.picturenotgened:
self.updatePicture(parent_viewbox.rect())
self.picturenotgened = False
pg.ImageItem.paint(self, p, *args)
self.updatePicture(parent_viewbox.rect())
def render(self):
#The same as pyqtgraph's ImageItem.render, with the exception that the makeARGB function is slightly different
profile = debug.Profiler()
if self.image is None or self.image.size == 0:
return
if isinstance(self.lut, Callable):
lut = self.lut(self.image)
else:
lut = self.lut
if self.autoDownsample:
# reduce dimensions of image based on screen resolution
o = self.mapToDevice(QtCore.QPointF(0,0))
x = self.mapToDevice(QtCore.QPointF(1,0))
y = self.mapToDevice(QtCore.QPointF(0,1))
w = Point(x-o).length()
h = Point(y-o).length()
if w == 0 or h == 0:
self.qimage = None
return
xds = max(1, int(1.0 / w))
yds = max(1, int(1.0 / h))
axes = [1, 0] if self.axisOrder == 'row-major' else [0, 1]
image = fn.downsample(self.image, xds, axis=axes[0])
image = fn.downsample(image, yds, axis=axes[1])
self._lastDownsample = (xds, yds)
else:
image = self.image
# Assume images are in column-major order for backward compatibility
# (most images are in row-major order)
if self.axisOrder == 'col-major':
image = image.transpose((1, 0, 2)[:image.ndim])
argb, alpha = makeARGBwithNaNs(image, lut=lut, levels=self.levels)
self.qimage = fn.makeQImage(argb, alpha, transpose=False)
def setImage(self, image=None, autoLevels=None, **kargs):
"""
Same this as ImageItem.setImage, but we don't update the drawing
"""
profile = debug.Profiler()
gotNewData = False
if image is None:
if self.image is None:
return
else:
gotNewData = True
shapeChanged = (self.image is None or image.shape != self.image.shape)
image = image.view(np.ndarray)
if self.image is None or image.dtype != self.image.dtype:
self._effectiveLut = None
self.image = image
if self.image.shape[0] > 2**15-1 or self.image.shape[1] > 2**15-1:
if 'autoDownsample' not in kargs:
kargs['autoDownsample'] = True
if shapeChanged:
self.prepareGeometryChange()
self.informViewBoundsChanged()
profile()
if autoLevels is None:
if 'levels' in kargs:
autoLevels = False
else:
autoLevels = True
if autoLevels:
img = self.image
while img.size > 2**16:
img = img[::2, ::2]
mn, mx = img.min(), img.max()
if mn == mx:
mn = 0
mx = 255
kargs['levels'] = [mn,mx]
profile()
self.setOpts(update=False, **kargs)
profile()
self.qimage = None
self.update()
profile()
if gotNewData:
self.sigImageChanged.emit()
|
class UpdatingImage(pg.ImageItem):
'''
This is the class used to plot images of spectrogram data.
It automatically updates to higher and higher resolutions when you zoom in, thus the name
"updating image".
'''
def __init__(self, x, y, data, lut, zmin, zmax):
pass
def updatePicture(self, pixel_size=None):
pass
def paint(self, p, *args):
'''
I have no idea why, but we need to generate the picture after painting otherwise
it draws incorrectly.
'''
pass
def render(self):
pass
def setImage(self, image=None, autoLevels=None, **kargs):
'''
Same this as ImageItem.setImage, but we don't update the drawing
'''
pass
| 6 | 3 | 35 | 5 | 27 | 4 | 7 | 0.18 | 1 | 4 | 1 | 0 | 5 | 17 | 5 | 5 | 194 | 34 | 137 | 58 | 131 | 25 | 132 | 58 | 126 | 13 | 1 | 3 | 33 |
147,635 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/QtPlotter/TVarFigureMap.py
|
pytplot.QtPlotter.TVarFigureMap.TVarFigureMap
|
class TVarFigureMap(pg.GraphicsLayout):
def __init__(self, tvar_name, show_xaxis=False):
self.tvar_name = tvar_name
self.show_xaxis = show_xaxis
self.crosshair = pytplot.tplot_opt_glob['crosshair']
# Sets up the layout of the Tplot Object
pg.GraphicsLayout.__init__(self)
self.layout.setHorizontalSpacing(50)
self.layout.setContentsMargins(0, 0, 0, 0)
# Set up the x axis
self.xaxis = pg.AxisItem(orientation='bottom')
self.xaxis.setHeight(35)
self.xaxis.enableAutoSIPrefix(enable=False)
# Set up the y axis
self.yaxis = AxisItem("left")
# Creating axes to bound the plots with lines
self.xaxis2 = pg.AxisItem(orientation='top')
self.xaxis2.setHeight(0)
self.yaxis2 = AxisItem("right")
self.yaxis2.setWidth(0)
vb = NoPaddingPlot()
self.plotwindow = self.addPlot(row=0, col=0, axisItems={'bottom': self.xaxis,
'left': self.yaxis,
"right": self.yaxis2,
"top": self.xaxis2}, viewBox=vb)
self.plotwindow.vb.setLimits(xMin=0, xMax=360, yMin=-90, yMax=90)
if pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['border']:
self.plotwindow.showAxis("top")
self.plotwindow.showAxis("right")
# Set up the view box needed for the legends
self.legendvb = pg.ViewBox(enableMouse=False)
self.legendvb.setMaximumWidth(100)
self.legendvb.setXRange(0, 1, padding=0)
self.legendvb.setYRange(0, 1, padding=0)
self.addItem(self.legendvb, 0, 1)
self.curves = []
self.colors = self._setcolors()
self.colormap = self._setcolormap()
if pytplot.tplot_opt_glob['black_background']:
self.labelStyle = {'font-size':
str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])
+ 'pt', 'color': '#FFF',
'white-space': 'pre-wrap'}
else:
self.labelStyle = {'font-size':
str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])
+ 'pt', 'color': '#000',
'white-space': 'pre-wrap'}
# Set the font size of the axes
font = QtGui.QFont()
font.setPixelSize(pytplot.tplot_opt_glob['axis_font_size'])
self.xaxis.setTickFont(font)
self.yaxis.setTickFont(font)
self.yaxis.setStyle(textFillLimits=pytplot.tplot_opt_glob["axis_tick_num"],
tickFont=font) # Set an absurdly high number for the first 3, ensuring that at least 3 axis labels are always present
if show_xaxis:
self.plotwindow.showAxis('bottom')
else:
self.plotwindow.hideAxis('bottom')
self.label = pg.LabelItem(justify='left')
self.addItem(self.label, row=1, col=0)
# Set legend options
self.hoverlegend = CustomLegendItem(offset=(0, 0))
self.hoverlegend.setItem("Date: ", "0")
self.hoverlegend.setItem("Time: ", "0")
self.hoverlegend.setItem("Latitude:", "0")
self.hoverlegend.setItem("Longitude:", "0")
self.hoverlegend.setVisible(False)
self.hoverlegend.setParentItem(self.plotwindow.vb)
def buildfigure(self):
self._setxrange()
self._setyrange()
self._setyaxistype()
self._setzaxistype()
self._setzrange()
self._setbackground()
self._visdata()
self._setxaxislabel()
self._setyaxislabel()
self._addlegend()
self._addtimebars()
self._addtimelistener()
if self.crosshair:
self._set_crosshairs()
self._addmouseevents()
def _setxaxislabel(self):
self.xaxis.setLabel("Longitude", **self.labelStyle)
def _setyaxislabel(self):
ylabel = pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['axis_label'].replace(" \ ", " <br> ")
if "axis_subtitle" in pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']:
sublabel = pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['axis_subtitle'].replace(" \ ", " <br> ")
self.yaxis.setLabel(f"{ylabel} <br> {sublabel} ", **self.labelStyle)
else:
self.yaxis.setLabel(ylabel, **self.labelStyle)
def getfig(self):
return self
def _visdata(self):
datasets = [pytplot.data_quants[self.tvar_name]]
for oplot_name in pytplot.data_quants[self.tvar_name].attrs['plot_options']['overplots']:
datasets.append(pytplot.data_quants[oplot_name])
cm_index = 0
for dataset_xr in datasets:
# TODO: The below function is essentially a hack for now, because this code was written assuming the data was a dataframe object.
# This needs to be rewritten to use xarray
dataset = pytplot.tplot_utilities.convert_tplotxarray_to_pandas_dataframe(dataset_xr.name, no_spec_bins=True)
coords = pytplot.tplot_utilities.return_interpolated_link_dict(dataset_xr, ['lat', 'lon'])
t_link = coords['lat'].coords['time'].values
lat = coords['lat'].values
# Need to trim down the data points to fit within the link
t_tvar = dataset.index.values
data = dataset[0].values
while t_tvar[-1] > t_link[-1]:
t_tvar = np.delete(t_tvar, -1)
data = np.delete(data, -1)
while t_tvar[0] < t_link[0]:
t_tvar = np.delete(t_tvar, 0)
data = np.delete(data, 0)
t_link = coords['lon'].coords['time'].values
lon = coords['lon'].values
# Need to trim down the data points to fit within the link
while t_tvar[-1] > t_link[-1]:
t_tvar = np.delete(t_tvar, -1)
data = np.delete(data, -1)
while t_tvar[0] < t_link[0]:
t_tvar = np.delete(t_tvar, 0)
data = np.delete(data, 0)
for column_name in dataset.columns:
values = data.tolist()
colors = pytplot.tplot_utilities.get_heatmap_color(color_map=
self.colormap[cm_index % len(self.colormap)],
min_val=self.zmin, max_val=self.zmax, values=values,
zscale=self.zscale)
brushes = []
for color in colors:
brushes.append(pg.mkBrush(color))
self.curves.append(self.plotwindow.scatterPlot(lon.tolist(), lat.tolist(),
pen=pg.mkPen(None), brush=brushes, size=4))
cm_index += 1
def _setyaxistype(self):
if self._getyaxistype() == 'log':
self.plotwindow.setLogMode(y=True)
else:
self.plotwindow.setLogMode(y=False)
return
def _addlegend(self):
zaxis = AxisItem('right')
zlabel = pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['axis_label'].replace(" \ ", " <br> ")
if "axis_subtitle" in pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']:
zsublabel = pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['axis_subtitle'].replace(" \ ", " <br> ")
zaxis.setLabel(f"{zlabel} <br> {zsublabel}", **self.labelStyle)
else:
zaxis.setLabel(zlabel, **self.labelStyle)
if self.show_xaxis:
emptyaxis = BlankAxis('bottom')
emptyaxis.setHeight(35)
p2 = self.addPlot(row=0, col=1, axisItems={'right': zaxis, 'bottom': emptyaxis}, enableMenu=False,
viewBox=self.legendvb)
else:
p2 = self.addPlot(row=0, col=1, axisItems={'right': zaxis}, enableMenu=False, viewBox=self.legendvb)
p2.hideAxis('bottom')
p2.buttonsHidden = True
p2.setMaximumWidth(100)
p2.showAxis('right')
p2.hideAxis('left')
colorbar = ColorbarImage()
colorbar.setImage(np.array([np.linspace(1, 2, 200)]).T)
p2.addItem(colorbar)
p2.setLogMode(y=(self.zscale == 'log'))
p2.setXRange(0, 1, padding=0)
if self.zscale == 'log':
colorbar.setRect(QtCore.QRectF(0, np.log10(self.zmin), 1, np.log10(self.zmax) - np.log10(self.zmin)))
# I have literally no idea why this is true, but I need to set the range twice
p2.setYRange(np.log10(self.zmin), np.log10(self.zmax), padding=0)
p2.setYRange(np.log10(self.zmin), np.log10(self.zmax), padding=0)
else:
colorbar.setRect(QtCore.QRectF(0, self.zmin, 1, self.zmax - self.zmin))
p2.setYRange(self.zmin, self.zmax, padding=0)
colorbar.setLookupTable(self.colormap[0])
def _addmouseevents(self):
if self.plotwindow.scene() is not None:
self.plotwindow.scene().sigMouseMoved.connect(self._mousemoved)
def _mousemoved(self, evt):
# get current position
pos = evt
# if plot window contains position
if self.plotwindow.sceneBoundingRect().contains(pos):
mousepoint = self.plotwindow.vb.mapSceneToView(pos)
# grab x and y mouse locations
index_x = round(float(mousepoint.x()), 2)
index_y = round(float(mousepoint.y()), 2)
# get latitude and longitude arrays
time = pytplot.data_quants[pytplot.data_quants[self.tvar_name].attrs['plot_options']['links']['lat']].coords['time'].values
latitude = pytplot.data_quants[pytplot.data_quants[self.tvar_name].attrs['plot_options']['links']['lat']].values
longitude = pytplot.data_quants[pytplot.data_quants[self.tvar_name].attrs['plot_options']['links']['lon']].values
# find closest time point to cursor
radius = np.sqrt((latitude - index_y) ** 2 + (longitude - index_x) ** 2).argmin()
time_point = time[radius]
# get date and time
date = (pytplot.tplot_utilities.int_to_str(time_point))[0:10]
time = (pytplot.tplot_utilities.int_to_str(time_point))[11:19]
# add crosshairs
pytplot.hover_time.change_hover_time(time_point, name=self.tvar_name)
self.vLine.setVisible(True)
self.hLine.setVisible(True)
self.vLine.setPos(mousepoint.x())
self.hLine.setPos(mousepoint.y())
# Set legend options
self.hoverlegend.setVisible(True)
self.hoverlegend.setItem("Date: ", date)
self.hoverlegend.setItem("Time: ", time)
self.hoverlegend.setItem("Longitude:", str(index_x))
self.hoverlegend.setItem("Latitude:", str(index_y))
else:
self.hoverlegend.setVisible(False)
self.vLine.setVisible(False)
self.hLine.setVisible(False)
def _getyaxistype(self):
return 'linear'
def _setzaxistype(self):
if self._getzaxistype() == 'log':
self.zscale = 'log'
else:
self.zscale = 'linear'
def _getzaxistype(self):
if 'z_axis_type' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']:
return pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['z_axis_type']
else:
return 'linear'
def _setcolors(self):
if 'line_color' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']:
return pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['line_color']
else:
if pytplot.tplot_opt_glob['black_background']:
return pytplot.tplot_utilities.rgb_color(['w', 'r', 'seagreen', 'b', 'darkturquoise', 'm', 'goldenrod'])
else:
return pytplot.tplot_utilities.rgb_color(['k', 'r', 'seagreen', 'b', 'darkturquoise', 'm', 'goldenrod'])
def _setcolormap(self):
colors = []
if 'colormap' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']:
for cm in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['colormap']:
colors.append(pytplot.tplot_utilities.return_lut(cm))
return colors
else:
return [pytplot.tplot_utilities.return_lut("inferno")]
@staticmethod
def getaxistype():
axis_type = 'lat'
link_y_axis = True
return axis_type, link_y_axis
def _setxrange(self):
# Check if x range is set. Otherwise, set it.
if 'map_x_range' in pytplot.tplot_opt_glob:
self.plotwindow.setXRange(pytplot.tplot_opt_glob['map_x_range'][0],
pytplot.tplot_opt_glob['map_x_range'][1])
else:
self.plotwindow.setXRange(0, 360)
def _setyrange(self):
# Check if y range is set. Otherwise, y range is automatic
if 'map_y_range' in pytplot.tplot_opt_glob:
self.plotwindow.setYRange(pytplot.tplot_opt_glob['map_y_range'][0],
pytplot.tplot_opt_glob['map_y_range'][1])
else:
self.plotwindow.vb.setYRange(-90, 90)
def _setzrange(self):
# Get Z Range
if 'z_range' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']:
self.zmin = pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['z_range'][0]
self.zmax = pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['z_range'][1]
else:
dataset_temp = pytplot.data_quants[self.tvar_name].where(pytplot.data_quants[self.tvar_name] != np.inf)
dataset_temp = dataset_temp.where(dataset_temp != -np.inf)
# Cannot have a 0 minimum in a log scale
if self.zscale == 'log':
dataset_temp = dataset_temp.where(dataset_temp > 0)
self.zmax = dataset_temp.max().max().values
self.zmin = dataset_temp.min().min().values
def _addtimebars(self):
# grab tbardict
tbardict = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar']
ltbar = len(tbardict)
for i in range(ltbar):
# get times, color, point size
test_time = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["location"]
color = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["line_color"]
pointsize = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["line_width"]
# correlate given time with corresponding lat/lon points
time = pytplot.data_quants[pytplot.data_quants[self.tvar_name].attrs['plot_options']['links']['lat']].coords['time']
latitude = pytplot.data_quants[pytplot.data_quants[self.tvar_name].attrs['plot_options']['links']['lat']].values
longitude = pytplot.data_quants[pytplot.data_quants[self.tvar_name].attrs['plot_options']['links']['lon']].values
nearest_time_index = np.abs(time - test_time).argmin()
lat_point = latitude[nearest_time_index]
lon_point = longitude[nearest_time_index]
# color = pytplot.tplot_utilities.rgb_color(color)
self.plotwindow.scatterPlot([lon_point], [lat_point], size=pointsize, pen=pg.mkPen(None), brush=color)
return
def _setbackground(self):
if 'alpha' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']:
alpha = pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['alpha']
else:
alpha = 1
if 'basemap' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']:
if os.path.isfile(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['basemap']):
from matplotlib.pyplot import imread
img = imread(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['basemap'],
format='RGBA')
# Need to flip the image upside down...This will probably be fixed in
# a future release, so this will need to be deleted at some point
img = img[::-1]
bm = ColorbarImage(image=img, opacity=alpha)
bm.setRect(QtCore.QRect(0, -90, 360, 180))
self.plotwindow.addItem(bm)
def _set_crosshairs(self):
if pytplot.tplot_opt_glob['black_background']:
self.vLine = pg.InfiniteLine(angle=90, movable=False, pen=pg.mkPen('w'))
self.hLine = pg.InfiniteLine(angle=0, movable=False, pen=pg.mkPen('w'))
else:
self.vLine = pg.InfiniteLine(angle=90, movable=False, pen=pg.mkPen('k'))
self.hLine = pg.InfiniteLine(angle=0, movable=False, pen=pg.mkPen('k'))
self.plotwindow.addItem(self.vLine, ignoreBounds=True)
self.plotwindow.addItem(self.hLine, ignoreBounds=True)
self.vLine.setVisible(False)
self.hLine.setVisible(False)
def _addtimelistener(self):
self.spacecraft_position = self.plotwindow.scatterPlot([], [], size=14, pen=pg.mkPen(None), brush='b')
pytplot.hover_time.register_listener(self._time_mover)
def _time_mover(self, time, name):
if name != self.tvar_name:
hover_time = time
time = \
pytplot.data_quants[pytplot.data_quants[self.tvar_name].attrs['plot_options']['links']['lat']].coords[
'time']
latitude = pytplot.data_quants[
pytplot.data_quants[self.tvar_name].attrs['plot_options']['links']['lat']].values
longitude = pytplot.data_quants[
pytplot.data_quants[self.tvar_name].attrs['plot_options']['links']['lon']].values
nearest_time_index = np.abs(time - hover_time).argmin()
lat_point = latitude[nearest_time_index]
lon_point = longitude[nearest_time_index]
self.spacecraft_position.setData([lon_point], [lat_point])
|
class TVarFigureMap(pg.GraphicsLayout):
def __init__(self, tvar_name, show_xaxis=False):
pass
def buildfigure(self):
pass
def _setxaxislabel(self):
pass
def _setyaxislabel(self):
pass
def getfig(self):
pass
def _visdata(self):
pass
def _setyaxistype(self):
pass
def _addlegend(self):
pass
def _addmouseevents(self):
pass
def _mousemoved(self, evt):
pass
def _getyaxistype(self):
pass
def _setzaxistype(self):
pass
def _getzaxistype(self):
pass
def _setcolors(self):
pass
def _setcolormap(self):
pass
@staticmethod
def getaxistype():
pass
def _setxrange(self):
pass
def _setyrange(self):
pass
def _setzrange(self):
pass
def _addtimebars(self):
pass
def _setbackground(self):
pass
def _set_crosshairs(self):
pass
def _addtimelistener(self):
pass
def _time_mover(self, time, name):
pass
| 26 | 0 | 15 | 1 | 13 | 1 | 2 | 0.11 | 1 | 8 | 5 | 0 | 23 | 21 | 24 | 24 | 386 | 47 | 309 | 109 | 282 | 33 | 268 | 107 | 242 | 9 | 1 | 3 | 59 |
147,636 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/QtPlotter/CustomViewBox/NoPaddingPlot.py
|
pytplot.QtPlotter.CustomViewBox.NoPaddingPlot.NoPaddingPlot
|
class NoPaddingPlot(pg.ViewBox):
def suggestPadding(self, axis):
l = self.width() if axis == 0 else self.height()
if l > 0:
padding = 0.002
else:
padding = 0.002
return padding
|
class NoPaddingPlot(pg.ViewBox):
def suggestPadding(self, axis):
pass
| 2 | 0 | 7 | 0 | 7 | 0 | 3 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 9 | 1 | 8 | 4 | 6 | 0 | 7 | 4 | 5 | 3 | 1 | 1 | 3 |
147,637 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/HTMLPlotter/TVarFigureSpec.py
|
pytplot.HTMLPlotter.TVarFigureSpec.TVarFigureSpec
|
class TVarFigureSpec(object):
def __init__(self, tvar_name, auto_color=False, show_xaxis=False, slice=False, y_axis_type='log'):
self.tvar_name = tvar_name
self.show_xaxis = show_xaxis
if 'show_all_axes' in pytplot.tplot_opt_glob:
if pytplot.tplot_opt_glob['show_all_axes']:
self.show_xaxis = True
self.slice = slice
# Variables needed across functions
self.fig = None
self.colors = []
self.lineglyphs = []
self.linenum = 0
self.zscale = 'log'
self.zmin = 0
self.zmax = 1
self.callback = None
self.slice_plot = None
self.fig = Figure(x_axis_type='datetime',
tools=pytplot.tplot_opt_glob['tools'],
y_axis_type=self._getyaxistype())
self.fig.add_tools(BoxZoomTool(dimensions='width'))
self._format()
@staticmethod
def get_axis_label_color():
if pytplot.tplot_opt_glob['black_background']:
text_color = '#000000'
else:
text_color = '#FFFFFF'
return text_color
@staticmethod
def getaxistype():
axis_type = 'time'
link_y_axis = False
return axis_type, link_y_axis
def getfig(self):
if self.slice:
return [self.fig, self.slice_plot]
else:
return [self.fig]
def setsize(self, width, height):
self.fig.plot_width = width
if self.show_xaxis:
self.fig.plot_height = height + 22
else:
self.fig.plot_height = height
def add_title(self):
if 'title_text' in pytplot.tplot_opt_glob:
if pytplot.tplot_opt_glob['title_text'] != '':
title1 = Title(text=pytplot.tplot_opt_glob['title_text'],
align=pytplot.tplot_opt_glob['title_align'],
text_font_size=pytplot.tplot_opt_glob['title_size'],
text_color=self.get_axis_label_color())
self.fig.title = title1
self.fig.plot_height += 22
def buildfigure(self):
self._setminborder()
self._setxrange()
self._setxaxis()
self._setyrange()
self._setzaxistype()
self._setzrange()
self._addtimebars()
self._visdata()
self._setxaxislabel()
self._setyaxislabel()
self._addhoverlines()
self._addlegend()
def _format(self):
# Formatting stuff
self.fig.grid.grid_line_color = None
self.fig.axis.major_tick_line_color = None
self.fig.axis.major_label_standoff = 0
self.fig.xaxis.formatter = dttf
self.fig.title = None
self.fig.toolbar.active_drag = 'auto'
if not self.show_xaxis:
self.fig.xaxis.major_label_text_font_size = '0pt'
self.fig.xaxis.visible = False
self.fig.lod_factor = 100
self.fig.lod_interval = 30
self.fig.lod_threshold = 100
def _setxrange(self):
# Check if x range is not set, if not, set good ones
if 'x_range' not in pytplot.tplot_opt_glob:
pytplot.tplot_opt_glob['x_range'] = [np.nanmin(pytplot.data_quants[self.tvar_name].coords['time'].values),
np.nanmax(pytplot.data_quants[self.tvar_name].coords['time'].values)]
# Bokeh uses milliseconds since epoch for some reason
x_range = Range1d(int(pytplot.tplot_opt_glob['x_range'][0]) * 1000.0,
int(pytplot.tplot_opt_glob['x_range'][1]) * 1000.0)
if self.show_xaxis:
pytplot.lim_info['xfull'] = x_range
pytplot.lim_info['xlast'] = x_range
self.fig.x_range = x_range
def _setyrange(self):
if self._getyaxistype() == 'log':
if pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][0] <= 0 \
or pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][1] <= 0:
return
y_range = Range1d(pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][0],
pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][1])
self.fig.y_range = y_range
def _setzrange(self):
# Get Z Range
if 'z_range' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']:
self.zmin = pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['z_range'][0]
self.zmax = pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['z_range'][1]
else:
dataset_temp = pytplot.data_quants[self.tvar_name].where(pytplot.data_quants[self.tvar_name] != np.inf)
dataset_temp = dataset_temp.where(pytplot.data_quants[self.tvar_name] != -np.inf)
self.zmax = np.float(dataset_temp.max(skipna=True).values)
self.zmin = np.float(dataset_temp.min(skipna=True).values)
# Cannot have a 0 minimum in a log scale
if self.zscale == 'log':
df = pytplot.tplot_utilities.convert_tplotxarray_to_pandas_dataframe(self.tvar_name, no_spec_bins=True)
zmin_list = []
for column in df.columns:
series = df[column]
zmin_list.append(series.iloc[series.to_numpy().nonzero()[0]].min())
self.zmin = min(zmin_list)
def _setminborder(self):
self.fig.min_border_bottom = pytplot.tplot_opt_glob['min_border_bottom']
self.fig.min_border_top = pytplot.tplot_opt_glob['min_border_top']
def _addtimebars(self):
for time_bar in pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar']:
time_bar_line = Span(location=time_bar['location']*1000.0,
dimension=time_bar['dimension'],
line_color=time_bar['line_color'],
line_width=time_bar['line_width'])
self.fig.renderers.extend([time_bar_line])
def _set_roi_lines(self, time):
# Locating the two times between which there's a roi
roi_1 = pytplot.tplot_utilities.str_to_int(pytplot.tplot_opt_glob['roi_lines'][0])
roi_2 = pytplot.tplot_utilities.str_to_int(pytplot.tplot_opt_glob['roi_lines'][1])
# find closest time to user-requested time
x = np.asarray(time)
x_sub_1 = abs(x - roi_1 * np.ones(len(x)))
x_sub_2 = abs(x - roi_2 * np.ones(len(x)))
x_argmin_1 = np.nanargmin(x_sub_1)
x_argmin_2 = np.nanargmin(x_sub_2)
x_closest_1 = x[x_argmin_1]
x_closest_2 = x[x_argmin_2]
# Create roi box
roi_box = BoxAnnotation(left=x_closest_1*1000.0, right=x_closest_2*1000.0, fill_alpha=0.6, fill_color='grey',
line_color='red', line_width=2.5)
self.fig.renderers.extend([roi_box])
def _setxaxis(self):
xaxis1 = DatetimeAxis(major_label_text_font_size='0pt', formatter=dttf)
xaxis1.visible = False
self.fig.add_layout(xaxis1, 'above')
def _getyaxistype(self):
if 'y_axis_type' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']:
return pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_axis_type']
else:
return 'log'
def _setzaxistype(self):
if 'z_axis_type' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']:
self.zscale = pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['z_axis_type']
def _setcolors(self):
if 'colormap' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']:
for cm in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['colormap']:
self.colors.append(tplot_utilities.return_bokeh_colormap(cm))
else:
self.colors.append(tplot_utilities.return_bokeh_colormap('magma'))
def _setxaxislabel(self):
self.fig.xaxis.axis_label = pytplot.data_quants[self.tvar_name].attrs['plot_options']['xaxis_opt']['axis_label']
self.fig.xaxis.axis_label_text_font_size = str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])+'pt'
self.fig.xaxis.axis_label_text_color = self.get_axis_label_color()
def _setyaxislabel(self):
self.fig.yaxis.axis_label = pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['axis_label']
self.fig.yaxis.axis_label_text_font_size = str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])+'pt'
self.fig.yaxis.axis_label_text_color = self.get_axis_label_color()
def _visdata(self):
self._setcolors()
x = pytplot.data_quants[self.tvar_name].coords['time'].values.tolist()
# Add region of interest (roi) lines if applicable
if 'roi_lines' in pytplot.tplot_opt_glob.keys():
self._set_roi_lines(x)
temp = [a for a in x if (a <= (pytplot.tplot_opt_glob['x_range'][1]) and a >= (pytplot.tplot_opt_glob['x_range'][0]))]
x = temp
# Sometimes X will be huge, we'll need to cut down so that each x will stay about 1 pixel in size
step_size = 1
num_rect_displayed = len(x)
if self.fig.plot_width < num_rect_displayed:
step_size = int(math.floor(num_rect_displayed/self.fig.plot_width))
x[:] = x[0::step_size]
# Determine bin sizes
if 'spec_bins' in pytplot.data_quants[self.tvar_name].coords:
df, bins = pytplot.tplot_utilities.convert_tplotxarray_to_pandas_dataframe(self.tvar_name)
bins_vary = len(pytplot.data_quants[self.tvar_name].coords['spec_bins'].shape) > 1
bins_increasing = pytplot.data_quants[self.tvar_name].attrs['plot_options']['spec_bins_ascending']
else:
df = pytplot.tplot_utilities.convert_tplotxarray_to_pandas_dataframe(self.tvar_name, no_spec_bins=True)
bins = pd.DataFrame(np.arange(len(pytplot.data_quants[self.tvar_name][0]))).transpose()
bins_vary = False
bins_increasing = True
# Get length of arrays
size_x = len(x)
size_y = len(bins.columns)
# These arrays will be populated with data for the rectangle glyphs
color = []
bottom = []
top = []
left = []
right = []
value = []
corrected_time = []
# left, right, and time do not depend on the values in spec_bins
for j in range(size_x-1):
left.append(x[j]*1000.0)
right.append(x[j+1]*1000.0)
corrected_time.append(tplot_utilities.int_to_str(x[j]))
left = left * (size_y-1)
right = right * (size_y-1)
corrected_time = corrected_time * (size_y-1)
# Handle the case of time-varying bin sizes
if bins_vary:
temp_bins = bins.loc[x[0:size_x-1]]
else:
temp_bins = bins.loc[0]
if bins_increasing:
bin_index_range = range(0, size_y-1, 1)
else:
bin_index_range = range(size_y-1, 0, -1)
for i in bin_index_range:
temp = df[i][x[0:size_x-1]].tolist()
value.extend(temp)
color.extend(tplot_utilities.get_heatmap_color(color_map=self.colors[0],
min_val=self.zmin,
max_val=self.zmax,
values=temp,
zscale=self.zscale))
# Handle the case of time-varying bin sizes
if bins_vary:
bottom.extend(temp_bins[i].tolist())
if bins_increasing:
top.extend(temp_bins[i+1].tolist())
else:
top.extend(temp_bins[i-1].tolist())
else:
bottom.extend([temp_bins[i]]*(size_x-1))
if bins_increasing:
top.extend([temp_bins[i+1]]*(size_x-1))
else:
top.extend([temp_bins[i-1]]*(size_x-1))
# Here is where we add all of the rectangles to the plot
cds = ColumnDataSource(data=dict(x=left,
y=bottom,
right=right,
top=top,
z=color,
value=value,
corrected_time=corrected_time))
self.fig.quad(bottom='y', left='x', right='right', top='top', color='z', source=cds)
if self.slice:
if 'y_axis_type' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']:
y_slice_log = 'log'
else:
y_slice_log = 'linear'
self.slice_plot = Figure(plot_height=self.fig.plot_height,
plot_width=self.fig.plot_width,
y_range=(self.zmin, self.zmax),
x_range=(pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][0],
pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][1]),
y_axis_type=y_slice_log)
self.slice_plot.min_border_left = 100
spec_bins = bins
flux = [0]*len(spec_bins)
slice_line_source = ColumnDataSource(data=dict(x=spec_bins, y=flux))
self.slice_plot.line('x', 'y', source=slice_line_source)
self.callback = CustomJS(args=dict(cds=cds, source=slice_line_source), code="""
var geometry = cb_data['geometry'];
var x_data = geometry.x; // current mouse x position in plot coordinates
var y_data = geometry.y; // current mouse y position in plot coordinates
var d2 = source.data;
var asdf = cds.data;
var j = 0;
x=d2['x']
y=d2['y']
time=asdf['x']
energies=asdf['y']
flux=asdf['value']
for (i = 0; i < time.length-1; i++) {
if(x_data >= time[i] && x_data <= time[i+1] ) {
x[j] = energies[i]
y[j] = flux[i]
j=j+1
}
}
j=0
source.change.emit();
""")
def _addhoverlines(self):
# Add tools
hover = HoverTool(callback=self.callback)
hover.tooltips = [("Time", "@corrected_time"), ("Energy", "@y"), ("Value", "@value")]
self.fig.add_tools(hover)
def _addlegend(self):
# Add the color bar
if 'z_axis_type' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']:
if pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['z_axis_type'] == 'log':
color_mapper = LogColorMapper(palette=self.colors[0], low=self.zmin, high=self.zmax)
color_bar = ColorBarSideTitle(color_mapper=color_mapper, ticker=LogTicker(), border_line_color=None,
location=(0, 0))
color_bar.formatter = BasicTickFormatter(precision=2)
else:
color_mapper = LinearColorMapper(palette=self.colors[0], low=self.zmin, high=self.zmax)
color_bar = ColorBarSideTitle(color_mapper=color_mapper, ticker=BasicTicker(), border_line_color=None,
location=(0, 0))
color_bar.formatter = BasicTickFormatter(precision=4)
else:
color_mapper = LogColorMapper(palette=self.colors[0], low=self.zmin, high=self.zmax)
color_bar = ColorBarSideTitle(color_mapper=color_mapper, ticker=LogTicker(), border_line_color=None,
location=(0, 0))
color_bar.formatter = BasicTickFormatter(precision=2)
color_bar.width = 10
color_bar.major_label_text_align = 'left'
color_bar.label_standoff = 5
color_bar.major_label_text_baseline = 'middle'
color_bar.title = pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['axis_label']
color_bar.title_text_font_size = str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])+'pt'
color_bar.title_text_font_style = 'bold'
color_bar.title_standoff = 20
self.fig.add_layout(color_bar, 'right')
|
class TVarFigureSpec(object):
def __init__(self, tvar_name, auto_color=False, show_xaxis=False, slice=False, y_axis_type='log'):
pass
@staticmethod
def get_axis_label_color():
pass
@staticmethod
def getaxistype():
pass
def getfig(self):
pass
def setsize(self, width, height):
pass
def add_title(self):
pass
def buildfigure(self):
pass
def _format(self):
pass
def _setxrange(self):
pass
def _setyrange(self):
pass
def _setzrange(self):
pass
def _setminborder(self):
pass
def _addtimebars(self):
pass
def _set_roi_lines(self, time):
pass
def _setxaxis(self):
pass
def _getyaxistype(self):
pass
def _setzaxistype(self):
pass
def _setcolors(self):
pass
def _setxaxislabel(self):
pass
def _setyaxislabel(self):
pass
def _visdata(self):
pass
def _addhoverlines(self):
pass
def _addlegend(self):
pass
| 26 | 0 | 15 | 1 | 13 | 1 | 2 | 0.07 | 1 | 6 | 1 | 0 | 21 | 12 | 23 | 23 | 367 | 43 | 304 | 91 | 278 | 22 | 235 | 89 | 211 | 13 | 1 | 3 | 57 |
147,638 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/QtPlotter/TVarFigureSpec.py
|
pytplot.QtPlotter.TVarFigureSpec.TVarFigureSpec
|
class TVarFigureSpec(pg.GraphicsLayout):
def __init__(self, tvar_name, show_xaxis=False):
# This sets the default number of points to use when creating a spectrogram image
self.X_PIXEL_LENGTH = 1000
self.Y_PIXEL_HEIGHT = 100
self.tvar_name = tvar_name
self.show_xaxis = show_xaxis
self.crosshair = pytplot.tplot_opt_glob['crosshair']
# Sets up the layout of the Tplot Object
pg.GraphicsLayout.__init__(self)
self.layout.setHorizontalSpacing(10)
self.layout.setContentsMargins(0, 0, 0, 0)
self.show_xaxis = show_xaxis
if 'show_all_axes' in pytplot.tplot_opt_glob:
if pytplot.tplot_opt_glob['show_all_axes']:
self.show_xaxis = True
# Set up the x axis
if self.show_xaxis:
self.xaxis = DateAxis(orientation='bottom')
self.xaxis.setHeight(35)
self.xaxis.enableAutoSIPrefix(enable=False)
else:
self.xaxis = DateAxis(orientation='bottom', showValues=False)
self.xaxis.setHeight(0)
self.xaxis.enableAutoSIPrefix(enable=False)
# Set up the y axis
self.yaxis = AxisItem('left')
self.yaxis.setStyle(textFillLimits=pytplot.tplot_opt_glob["axis_tick_num"]) # Set an absurdly high number for the first 3, ensuring that at least 3 axis labels are always present
# Creating axes to bound the plots with lines
self.xaxis2 = DateAxis(orientation='top', showValues=False)
self.xaxis2.setHeight(0)
self.yaxis2 = AxisItem("right", showValues=False)
self.yaxis2.setWidth(0)
vb = NoPaddingPlot()
# Generate our plot in the graphics layout
self.plotwindow = self.addPlot(row=0, col=0, axisItems={'bottom': self.xaxis,
'left': self.yaxis,
'right': self.yaxis2,
'top': self.xaxis2}, viewBox=vb)
# Turn off zooming in on the y-axis, time resolution is much more important
self.plotwindow.setMouseEnabled(y=pytplot.tplot_opt_glob['y_axis_zoom'])
if pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['border']:
self.plotwindow.showAxis("top")
self.plotwindow.showAxis("right")
# Set up the view box needed for the legends
self.legendvb = pg.ViewBox(enableMouse=False)
self.legendvb.setMaximumWidth(100)
self.legendvb.setXRange(0, 1, padding=0)
self.legendvb.setYRange(0, 1, padding=0)
self.addItem(self.legendvb, 0, 1)
self.curves = []
self.colors = self._setcolors()
self.colormap = self._setcolormap()
if pytplot.tplot_opt_glob['black_background']:
self.labelStyle = {'font-size':
str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])
+ 'pt', 'color': '#FFF',
'white-space': 'pre-wrap'}
else:
self.labelStyle = {'font-size':
str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])
+ 'pt', 'color': '#000',
'white-space': 'pre-wrap'}
# Set the font size of the axes
font = QtGui.QFont()
font.setPixelSize(pytplot.tplot_opt_glob['axis_font_size'])
self.xaxis.setTickFont(font)
self.yaxis.setTickFont(font)
self.yaxis.setStyle(textFillLimits=pytplot.tplot_opt_glob["axis_tick_num"],
tickFont=font) # Set an absurdly high number for the first 3, ensuring that at least 3 axis labels are always present
# Set legend options
self.hoverlegend = CustomLegendItem(offset=(0, 0))
self.hoverlegend.setItem("Date:", "0")
# Allow the user to set x-axis(time), y-axis, and z-axis data names in crosshairs
self.hoverlegend.setItem(pytplot.data_quants[self.tvar_name].attrs['plot_options']['xaxis_opt']['crosshair'] + ':', "0")
self.hoverlegend.setItem(pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['crosshair'] + ':', "0")
self.hoverlegend.setItem(pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['crosshair'] + ':', "0")
self.hoverlegend.setVisible(False)
self.hoverlegend.setParentItem(self.plotwindow.vb)
# Just perform this operation once, so we don't need to keep doing it
self.data_2d = pytplot.tplot_utilities.reduce_spec_dataset(name=self.tvar_name)
@staticmethod
def getaxistype():
axis_type = 'time'
link_y_axis = False
return axis_type, link_y_axis
def _set_crosshairs(self):
if pytplot.tplot_opt_glob['black_background']:
self.vLine = pg.InfiniteLine(angle=90, movable=False, pen=pg.mkPen('w'))
self.hLine = pg.InfiniteLine(angle=0, movable=False, pen=pg.mkPen('w'))
else:
self.vLine = pg.InfiniteLine(angle=90, movable=False, pen=pg.mkPen('k'))
self.hLine = pg.InfiniteLine(angle=0, movable=False, pen=pg.mkPen('k'))
self.plotwindow.addItem(self.vLine, ignoreBounds=True)
self.plotwindow.addItem(self.hLine, ignoreBounds=True)
def _set_roi_lines(self):
if 'roi_lines' in pytplot.tplot_opt_glob.keys():
# Locating the two times between which there's a roi
roi_1 = pytplot.tplot_utilities.str_to_int(pytplot.tplot_opt_glob['roi_lines'][0])
roi_2 = pytplot.tplot_utilities.str_to_int(pytplot.tplot_opt_glob['roi_lines'][1])
# find closest time to user-requested time
x = pytplot.data_quants[self.tvar_name].coords['time']
x_sub_1 = abs(x - roi_1 * np.ones(len(x)))
x_sub_2 = abs(x - roi_2 * np.ones(len(x)))
x_argmin_1 = np.nanargmin(x_sub_1)
x_argmin_2 = np.nanargmin(x_sub_2)
x_closest_1 = x[x_argmin_1]
x_closest_2 = x[x_argmin_2]
# Create a roi box
roi = CustomLinearRegionItem(orientation=pg.LinearRegionItem.Vertical, values=[x_closest_1, x_closest_2])
roi.setBrush([211, 211, 211, 130])
roi.lines[0].setPen('r', width=2.5)
roi.lines[1].setPen('r', width=2.5)
self.plotwindow.addItem(roi)
def buildfigure(self):
self._setxrange()
self._setyrange()
self._setyaxistype()
self._setzaxistype()
self._setzrange()
self._visdata()
self._setxaxislabel()
self._setyaxislabel()
self._addlegend()
self._addtimebars()
self._addmouseevents()
self._set_crosshairs()
self._set_roi_lines()
self._setxrange() # Need to change the x range again one last time, visualizing the data resets it
def _setyaxislabel(self):
ylabel = pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['axis_label'].replace(" \ ", " <br> ")
if "axis_subtitle" in pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']:
sublabel = pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['axis_subtitle'].replace(" \ ", " <br> ")
self.yaxis.setLabel(f"{ylabel} <br> {sublabel}", **self.labelStyle)
else:
self.yaxis.setLabel(ylabel, **self.labelStyle)
def _setxaxislabel(self):
if self.show_xaxis:
self.xaxis.setLabel(pytplot.data_quants[self.tvar_name].attrs['plot_options']['xaxis_opt']['axis_label'], **self.labelStyle)
def getfig(self):
return self
def _visdata(self):
# Determine if the data needs to be reformatted into a standard sized image
try:
if len(self.data_2d.coords['spec_bins'][0]) > 1:
x, y, data = self._format_spec_data_as_image(x_pixel_length = self.X_PIXEL_LENGTH,
y_pixel_height = self.Y_PIXEL_HEIGHT)
else:
x = self.data_2d.coords['time'].values
y = self.data_2d.coords['spec_bins'].values
data = self.data_2d.values
except TypeError:
x = self.data_2d.coords['time'].values
y = self.data_2d.coords['spec_bins'].values
data = self.data_2d.values
# Take the log of the y values if we are using a logarithmic y axis
if self._getyaxistype() == 'log':
y = np.log10(y)
# The the log of the z values if we are using a logarithmic x axis
if self._getzaxistype() == 'log':
data[data <= 0] = np.NaN
data = np.log10(data)
zmin = np.log10(self.zmin)
zmax = np.log10(self.zmax)
else:
zmin = self.zmin
zmax = self.zmax
# Pass in the data to actually create the spectrogram image
specplot = UpdatingImage(x, y, data, self.colormap, zmin, zmax)
self.plotwindow.addItem(specplot)
def _format_spec_data_as_image(self, x_pixel_length=1000, y_pixel_height=100):
'''
This function is used to format data where the coordinates of the y axis are time varying. For instance, data
collected at t=0 could be collected for energy bins at 100GHz, 200Ghz, and 300Ghz, but at t=1 the data was
collected at 1GHz, 50GHz, and 100 Ghz. This smooths things out over the image, and creates NaNs where data
is missing. These NaN's are displayed completely transparently in the UpdatingImage class.
:return: x, y, data
'''
x = self.data_2d.coords['time'].values
# Get a list of 1000 x values
xp = np.linspace(np.nanmin(x), np.nanmax(x), x_pixel_length)
# Grab data from only those values
resampled_data_2d = self.data_2d.sel(time=xp, method='nearest')
# Get a list of 100 y values between the min and the max y values
if self._getyaxistype() == 'log':
yp = np.logspace(np.log10(self.ymin), np.log10(self.ymax), y_pixel_height)
else:
yp = np.linspace(self.ymin, self.ymax, y_pixel_height)
# Determine the closest y values for which we have data at each x value
data_reformatted = [] # This will store the 1000x100 data array, ultimately forming the picture
y_values_at_x0 = resampled_data_2d.coords['spec_bins'][0]
closest_y_index_to_yp = []
for yi in yp:
closest_y_index_to_yp.append((np.abs(y_values_at_x0 - yi)).argmin())
# For each xp, determine the closest value of x we have available. Then, determine the closest values of y at
# each x, and determine the value at those points
prev_bins = y_values_at_x0
prev_closest_ys = closest_y_index_to_yp
for i in range(0, x_pixel_length):
y_values_at_xi = resampled_data_2d.coords['spec_bins'][i]
if (y_values_at_xi == prev_bins).all():
closest_y_index_to_yp = prev_closest_ys
else:
closest_y_index_to_yp = []
for yi in yp:
closest_y_index_to_yp.append((np.abs(y_values_at_xi - yi)).argmin())
prev_closest_ys = closest_y_index_to_yp
prev_bins = y_values_at_xi
# temp_data holds the values for those closest points for a particular point in time
temp_data = resampled_data_2d[i][closest_y_index_to_yp].values
# Try cutting the data off that is outside the bounds
try:
temp_data[yp < np.nanmin(y_values_at_xi)] = np.NaN
temp_data[yp > np.nanmax(y_values_at_xi)] = np.NaN
except RuntimeWarning:
# If the entire bin is NaN the above stuff fails, so just continue on
pass
data_reformatted.append(temp_data)
return xp, yp, np.array(data_reformatted)
def _setyaxistype(self):
if self._getyaxistype() == 'log':
self.plotwindow.setLogMode(y=True)
else:
self.plotwindow.setLogMode(y=False)
return
def _addlegend(self):
zaxis = AxisItem('right')
zlabel = pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['axis_label'].replace(" \ ", " <br> ")
if "axis_subtitle" in pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']:
zsublabel = pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['axis_subtitle'].replace(" \ ", " <br> ")
zaxis.setLabel(f"{zlabel} <br> {zsublabel}", **self.labelStyle)
else:
zaxis.setLabel(zlabel, **self.labelStyle)
if self.show_xaxis:
emptyAxis = BlankAxis('bottom')
emptyAxis.setHeight(35)
p2 = self.addPlot(row=0, col=1, axisItems={'right': zaxis, 'bottom': emptyAxis}, enableMenu=False,
viewBox=self.legendvb)
else:
p2 = self.addPlot(row=0, col=1, axisItems={'right': zaxis}, enableMenu=False, viewBox=self.legendvb)
p2.hideAxis('bottom')
p2.buttonsHidden = True
p2.setMaximumWidth(100)
p2.showAxis('right')
p2.hideAxis('left')
colorbar = ColorbarImage()
colorbar.setImage(np.array([np.linspace(1, 2, 200)]).T)
p2.addItem(colorbar)
p2.setLogMode(y=(self.zscale == 'log'))
p2.setXRange(0, 1, padding=0)
colorbar.setLookupTable(self.colormap)
if self.zscale == 'log':
colorbar.setRect(QtCore.QRectF(0, np.log10(self.zmin), 1, np.log10(self.zmax) - np.log10(self.zmin)))
# I have literally no idea why this is true, but I need to set the range twice
p2.setYRange(np.log10(self.zmin), np.log10(self.zmax), padding=0)
p2.setYRange(np.log10(self.zmin), np.log10(self.zmax), padding=0)
else:
colorbar.setRect(QtCore.QRectF(0, self.zmin, 1, self.zmax - self.zmin))
p2.setYRange(self.zmin, self.zmax, padding=0)
colorbar.setLookupTable(self.colormap)
def _addmouseevents(self):
if self.plotwindow.scene() is not None:
self.plotwindow.scene().sigMouseMoved.connect(self._mousemoved)
def round_sig(self, x, sig=4):
return round(x, sig - int(floor(log10(abs(x)))) - 1)
def _mousemoved(self, evt):
# get current position
pos = evt
# if plot window contains position
if self.plotwindow.sceneBoundingRect().contains(pos):
mousePoint = self.plotwindow.vb.mapSceneToView(pos)
# grab x and y mouse locations
index_x = int(mousePoint.x())
# set log magnitude if log plot
if self._getyaxistype() == 'log':
index_y = self.round_sig(10 ** (float(mousePoint.y())), 4)
else:
index_y = self.round_sig(float(mousePoint.y()), 4)
# find closest time/data to cursor location
x = np.asarray(self.data_2d.coords['time'].values)
x_sub = abs(x - index_x * np.ones(len(x)))
x_argmin = np.nanargmin(x_sub)
x_closest = x[x_argmin]
try:
if len(self.data_2d.coords['spec_bins'][0]) > 1:
y = np.asarray((self.data_2d.coords['spec_bins'][x_argmin]))
else:
y = np.asarray((self.data_2d.coords['spec_bins']))
except:
y = np.asarray((self.data_2d.coords['spec_bins']))
y_sub = abs(y - index_y * np.ones(y.size))
y_argmin = np.nanargmin(y_sub)
y_closest = y[y_argmin]
data_point = self.data_2d[x_argmin][y_argmin].values
# Associate mouse position with current plot you're mousing over.
pytplot.hover_time.change_hover_time(int(mousePoint.x()), name=self.tvar_name)
# add crosshairs
if self.crosshair:
self._update_crosshair_locations(mousePoint.x(), mousePoint.y(), x_closest, y_closest, data_point)
else:
self.hoverlegend.setVisible(False)
self.vLine.setVisible(False)
self.hLine.setVisible(False)
def _update_crosshair_locations(self, mouse_x, mouse_y, x_val, y_val, data_point):
self.vLine.setPos(mouse_x)
self.hLine.setPos(mouse_y)
self.vLine.setVisible(True)
self.hLine.setVisible(True)
date = (pytplot.tplot_utilities.int_to_str(x_val))[0:10]
time = (pytplot.tplot_utilities.int_to_str(x_val))[11:19]
self.hoverlegend.setVisible(True)
self.hoverlegend.setItem("Date:", date)
# Allow the user to set x-axis(time), y-axis, and z-axis data names in crosshairs
self.hoverlegend.setItem(
pytplot.data_quants[self.tvar_name].attrs['plot_options']['xaxis_opt']['crosshair'] + ':', time)
self.hoverlegend.setItem(
pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['crosshair'] + ':', str(y_val))
self.hoverlegend.setItem(
pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['crosshair'] + ':', str(data_point))
def _getyaxistype(self):
if 'y_axis_type' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']:
return pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_axis_type']
else:
return 'linear'
def _setzaxistype(self):
if self._getzaxistype() == 'log':
self.zscale = 'log'
else:
self.zscale = 'linear'
def _getzaxistype(self):
if 'z_axis_type' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']:
return pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['z_axis_type']
else:
return 'log'
def _setcolors(self):
if 'line_color' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']:
return pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['line_color']
else:
return pytplot.tplot_utilities.rgb_color(['k', 'r', 'seagreen', 'b', 'darkturquoise', 'm', 'goldenrod'])
def _setcolormap(self):
if 'colormap' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']:
for cm in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['colormap']:
return tplot_utilities.return_lut(cm)
else:
return tplot_utilities.return_lut("spedas")
def _setxrange(self):
# Check if x range is set. Otherwise, x range is automatic.
if 'x_range' in pytplot.tplot_opt_glob:
self.plotwindow.setXRange(pytplot.tplot_opt_glob['x_range'][0], pytplot.tplot_opt_glob['x_range'][1])
def _setyrange(self):
self.ymin = pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][0]
self.ymax = pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][1]
if self._getyaxistype() == 'log':
if pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][0] <= 0 or \
pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][1] <= 0:
self.ymin = np.nanmin(pytplot.data_quants[self.tvar_name].coords['spec_bins'].values)
self.ymax = np.nanmax(pytplot.data_quants[self.tvar_name].coords['spec_bins'].values)
self.plotwindow.vb.setYRange(np.log10(self.ymin),
np.log10(self.ymax),
padding=0)
else:
self.plotwindow.vb.setYRange(self.ymin,
self.ymax,
padding=0)
def _setzrange(self):
# Get Z Range
if 'z_range' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']:
self.zmin = pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['z_range'][0]
self.zmax = pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['z_range'][1]
else:
dataset_temp = pytplot.data_quants[self.tvar_name].where(pytplot.data_quants[self.tvar_name] != np.inf)
dataset_temp = dataset_temp.where(dataset_temp != -np.inf)
# Cannot have a 0 minimum in a log scale
if self.zscale == 'log':
dataset_temp = dataset_temp.where(dataset_temp > 0)
self.zmax = dataset_temp.max().max().values
self.zmin = dataset_temp.min().min().values
def _addtimebars(self):
# find number of times to plot
dict_length = len(pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'])
# for each time
for i in range(dict_length):
# pull date, color, thickness
date_to_highlight = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["location"]
color = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["line_color"]
thick = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["line_width"]
# make infinite line w/ parameters
# color = pytplot.tplot_utilities.rgb_color(color)
infline = pg.InfiniteLine(pos=date_to_highlight, pen=pg.mkPen(color, width=thick))
# add to plot window
self.plotwindow.addItem(infline)
return
|
class TVarFigureSpec(pg.GraphicsLayout):
def __init__(self, tvar_name, show_xaxis=False):
pass
@staticmethod
def getaxistype():
pass
def _set_crosshairs(self):
pass
def _set_roi_lines(self):
pass
def buildfigure(self):
pass
def _setyaxislabel(self):
pass
def _setxaxislabel(self):
pass
def getfig(self):
pass
def _visdata(self):
pass
def _format_spec_data_as_image(self, x_pixel_length=1000, y_pixel_height=100):
'''
This function is used to format data where the coordinates of the y axis are time varying. For instance, data
collected at t=0 could be collected for energy bins at 100GHz, 200Ghz, and 300Ghz, but at t=1 the data was
collected at 1GHz, 50GHz, and 100 Ghz. This smooths things out over the image, and creates NaNs where data
is missing. These NaN's are displayed completely transparently in the UpdatingImage class.
:return: x, y, data
'''
pass
def _setyaxistype(self):
pass
def _addlegend(self):
pass
def _addmouseevents(self):
pass
def round_sig(self, x, sig=4):
pass
def _mousemoved(self, evt):
pass
def _update_crosshair_locations(self, mouse_x, mouse_y, x_val, y_val, data_point):
pass
def _getyaxistype(self):
pass
def _setzaxistype(self):
pass
def _getzaxistype(self):
pass
def _setcolors(self):
pass
def _setcolormap(self):
pass
def _setxrange(self):
pass
def _setyrange(self):
pass
def _setzrange(self):
pass
def _addtimebars(self):
pass
| 27 | 1 | 17 | 2 | 13 | 2 | 3 | 0.17 | 1 | 14 | 8 | 0 | 24 | 24 | 25 | 25 | 459 | 67 | 339 | 112 | 312 | 59 | 296 | 110 | 270 | 7 | 1 | 3 | 66 |
147,639 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/HTMLPlotter/TVarFigureMap.py
|
pytplot.HTMLPlotter.TVarFigureMap.TVarFigureMap
|
class TVarFigureMap(object):
def __init__(self, tvar_name, auto_color=False, show_xaxis=False, slice=False):
self.tvar_name = tvar_name
self.show_xaxis = show_xaxis
self.slice = slice
# Variables needed across functions
self.fig = None
self.colors = []
self.lineglyphs = []
self.linenum = 0
self.zscale = 'linear'
self.zmin = 0
self.zmax = 1
self.callback = None
self.interactive_plot = None
self.fig = Figure(tools="pan,crosshair,reset,box_zoom",
y_axis_type=self._getyaxistype())
self._format()
@staticmethod
def get_axis_label_color():
if pytplot.tplot_opt_glob['black_background']:
text_color = '#000000'
else:
text_color = '#FFFFFF'
return text_color
@staticmethod
def getaxistype():
axis_type = 'map'
link_y_axis = True
return axis_type, link_y_axis
def getfig(self):
if self.slice:
return [self.fig, self.interactive_plot]
else:
return [self.fig]
def setsize(self, width, height):
self.fig.plot_width = width
if self.show_xaxis:
self.fig.plot_height = height + 22
else:
self.fig.plot_height = height
def add_title(self):
if 'title_text' in pytplot.tplot_opt_glob:
if pytplot.tplot_opt_glob['title_text'] != '':
title1 = Title(text=pytplot.tplot_opt_glob['title_text'],
align=pytplot.tplot_opt_glob['title_align'],
text_font_size=pytplot.tplot_opt_glob['title_size'],
text_color=self.get_axis_label_color())
self.fig.title = title1
self.fig.plot_height += 22
def buildfigure(self):
self._setminborder()
self._setxrange()
self._setxaxis()
self._setyrange()
self._setzrange()
self._setzaxistype()
self._setbackground()
self._visdata()
self._setxaxislabel()
self._setyaxislabel()
self._addhoverlines()
self._addlegend()
self._addtimebars()
def _format(self):
# Formatting stuff
self.fig.grid.grid_line_color = None
self.fig.axis.major_tick_line_color = None
self.fig.axis.major_label_standoff = 0
self.fig.title = None
self.fig.toolbar.active_drag = 'auto'
if not self.show_xaxis:
self.fig.xaxis.major_label_text_font_size = '0pt'
self.fig.xaxis.visible = False
self.fig.lod_factor = 100
self.fig.lod_interval = 30
self.fig.lod_threshold = 100
def _setxrange(self):
# Check if x range is not set, if not, set good ones
if 'map_range' not in pytplot.tplot_opt_glob:
pytplot.tplot_opt_glob['map_range'] = [0, 360]
tplot_x_range = Range1d(0, 360)
if self.show_xaxis:
pytplot.lim_info['xfull'] = tplot_x_range
pytplot.lim_info['xlast'] = tplot_x_range
# Bokeh uses milliseconds since epoch for some reason
x_range = Range1d(pytplot.tplot_opt_glob['map_range'][0],
pytplot.tplot_opt_glob['map_range'][1],
bounds=(0, 360))
self.fig.x_range = x_range
def _setyrange(self):
y_range = Range1d(-90, 90, bounds=(-90, 90))
self.fig.y_range = y_range
def _setzrange(self):
# Get Z Range
if 'z_range' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']:
self.zmin = pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['z_range'][0]
self.zmax = pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['z_range'][1]
else:
dataset_temp = pytplot.data_quants[self.tvar_name].where(pytplot.data_quants[self.tvar_name] != np.inf)
dataset_temp = dataset_temp.where(pytplot.data_quants[self.tvar_name] != -np.inf)
self.zmax = np.float(dataset_temp.max(skipna=True).values)
self.zmin = np.float(dataset_temp.min(skipna=True).values)
# Cannot have a 0 minimum in a log scale
if self.zscale == 'log':
df = pytplot.tplot_utilities.convert_tplotxarray_to_pandas_dataframe(self.tvar_name, no_spec_bins=True)
zmin_list = []
for column in df.columns:
series = df[column]
zmin_list.append(series.iloc[series.to_numpy().nonzero()[0]].min())
self.zmin = min(zmin_list)
def _setminborder(self):
self.fig.min_border_bottom = pytplot.tplot_opt_glob['min_border_bottom']
self.fig.min_border_top = pytplot.tplot_opt_glob['min_border_top']
def _addtimebars(self):
for time_bar in pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar']:
time_bar_line = Span(location=time_bar['location'],
dimension=time_bar['dimension'],
line_color=time_bar['line_color'],
line_width=time_bar['line_width'])
self.fig.renderers.extend([time_bar_line])
# grab tbardict
tbardict = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar']
ltbar = len(tbardict)
# make sure data is in list format
datasets = [pytplot.data_quants[self.tvar_name]]
for oplot_name in pytplot.data_quants[self.tvar_name].attrs['plot_options']['overplots']:
datasets.append(pytplot.data_quants[oplot_name])
for dataset in datasets:
# for location in tbar dict
for i in range(ltbar):
# get times, color, point size
test_time = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["location"]
color = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["line_color"]
pointsize = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["line_width"]
# correlate given time with corresponding lat/lon points
time = pytplot.data_quants[dataset.attrs['plot_options']['links']['lat']].coords['time']
latitude = pytplot.data_quants[dataset.attrs['plot_options']['links']['lat']].values
longitude = pytplot.data_quants[dataset.attrs['plot_options']['links']['lon']].values
nearest_time_index = np.abs(time - test_time).argmin()
lat_point = latitude[nearest_time_index]
lon_point = longitude[nearest_time_index]
# color = pytplot.tplot_utilities.rgb_color(color)
self.fig.circle([lon_point], [lat_point], size=pointsize, color=color)
return
def _setxaxis(self):
# Nothing to set for now
return
def _getyaxistype(self):
# Not going to have a log planet map
return 'linear'
def _setzaxistype(self):
if 'z_axis_type' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']:
self.zscale = pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['z_axis_type']
def _setcolors(self):
if 'colormap' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']:
for cm in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['colormap']:
self.colors.append(pytplot.tplot_utilities.return_bokeh_colormap(cm))
else:
self.colors.append(pytplot.tplot_utilities.return_bokeh_colormap('magma'))
def _setxaxislabel(self):
self.fig.xaxis.axis_label = 'Longitude'
self.fig.xaxis.axis_label_text_font_size = str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])+'pt'
self.fig.xaxis.axis_label_text_color = self.get_axis_label_color()
def _setyaxislabel(self):
self.fig.yaxis.axis_label = 'Latitude'
self.fig.yaxis.axis_label_text_font_size = str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])+'pt'
self.fig.yaxis.axis_label_text_color = self.get_axis_label_color()
def _visdata(self):
self._setcolors()
datasets = [pytplot.data_quants[self.tvar_name]]
for oplot_name in pytplot.data_quants[self.tvar_name].attrs['plot_options']['overplots']:
datasets.append(pytplot.data_quants[oplot_name])
cm_index = 0
for dataset in datasets:
# TODO: Add a check that lon and lat are only 1D
coords = pytplot.tplot_utilities.return_interpolated_link_dict(dataset, ['lon', 'lat'])
t_link_lon = coords['lon'].coords['time'].values
x = coords['lon'].values
t_link_lat = coords['lat'].coords['time'].values
y = coords['lon'].values
df = pytplot.tplot_utilities.convert_tplotxarray_to_pandas_dataframe(dataset.name, no_spec_bins=True)
for column_name in df.columns:
data = df[column_name].values
# Need to trim down the data points to fit within the link
t_tvar = df.index.values
while t_tvar[-1] > t_link_lon[-1]:
t_tvar = np.delete(t_tvar, -1)
data = np.delete(data, -1)
while t_tvar[0] < t_link_lon[0]:
t_tvar = np.delete(t_tvar, 0)
data = np.delete(data, 0)
while t_tvar[-1] > t_link_lat[-1]:
t_tvar = np.delete(t_tvar, -1)
data = np.delete(data, -1)
while t_tvar[0] < t_link_lat[0]:
t_tvar = np.delete(t_tvar, 0)
data = np.delete(data, 0)
colors = []
colors.extend(pytplot.tplot_utilities.get_heatmap_color(
color_map=self.colors[cm_index % len(self.colors)],
min_val=self.zmin,
max_val=self.zmax,
values=data.tolist(),
zscale=self.zscale))
circle_source = ColumnDataSource(data=dict(x=x,
y=y,
value=data.tolist(),
colors=colors))
self.fig.scatter(x='x', y='y',
radius=1.0,
fill_color='colors',
fill_alpha=1,
line_color=None,
source=circle_source)
cm_index += 1
def _addhoverlines(self):
# Add tools
hover = HoverTool()
hover.tooltips = [("Longitude", "@x"), ("Latitude", "@y"), ("Value", "@value")]
self.fig.add_tools(hover)
def _addlegend(self):
# Add the color bar
if 'z_axis_type' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']:
if pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['z_axis_type'] == 'log':
color_mapper = LogColorMapper(palette=self.colors[0],
low=self.zmin,
high=self.zmax)
color_bar = ColorBarSideTitle(color_mapper=color_mapper,
border_line_color=None,
location=(0, 0),
ticker=LogTicker())
else:
color_mapper = LinearColorMapper(palette=self.colors[0],
low=self.zmin,
high=self.zmax)
color_bar = ColorBarSideTitle(color_mapper=color_mapper,
border_line_color=None,
location=(0, 0),
ticker=BasicTicker())
else:
color_mapper = LinearColorMapper(palette=self.colors[0],
low=self.zmin,
high=self.zmax)
color_bar = ColorBarSideTitle(color_mapper=color_mapper,
border_line_color=None,
location=(0, 0),
ticker=BasicTicker())
color_bar.width = 10
color_bar.formatter = BasicTickFormatter(precision=1)
color_bar.major_label_text_align = 'left'
color_bar.label_standoff = 5
color_bar.major_label_text_baseline = 'middle'
color_bar.title = pytplot.data_quants[self.tvar_name].attrs['plot_options']['zaxis_opt']['axis_label']
color_bar.title_text_font_size = str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])+'pt'
color_bar.title_text_font_style = 'bold'
color_bar.title_standoff = 20
self.fig.add_layout(color_bar, 'right')
def _setbackground(self):
if 'alpha' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']:
alpha = pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['alpha']
else:
alpha = 1
if 'basemap' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']:
if os.path.isfile(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['basemap']):
from scipy import misc
img = misc.imread(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['basemap'], mode='RGBA')
# Need to flip the image upside down...This will probably be fixed in
# a future release, so this will need to be deleted at some point
img = img[::-1]
self.fig.image_rgba(image=[img], x=0, y=-90, dw=360, dh=180, alpha=alpha)
|
class TVarFigureMap(object):
def __init__(self, tvar_name, auto_color=False, show_xaxis=False, slice=False):
pass
@staticmethod
def get_axis_label_color():
pass
@staticmethod
def getaxistype():
pass
def getfig(self):
pass
def setsize(self, width, height):
pass
def add_title(self):
pass
def buildfigure(self):
pass
def _format(self):
pass
def _setxrange(self):
pass
def _setyrange(self):
pass
def _setzrange(self):
pass
def _setminborder(self):
pass
def _addtimebars(self):
pass
def _setxaxis(self):
pass
def _getyaxistype(self):
pass
def _setzaxistype(self):
pass
def _setcolors(self):
pass
def _setxaxislabel(self):
pass
def _setyaxislabel(self):
pass
def _visdata(self):
pass
def _addhoverlines(self):
pass
def _addlegend(self):
pass
def _setbackground(self):
pass
| 26 | 0 | 12 | 0 | 11 | 1 | 2 | 0.09 | 1 | 5 | 1 | 0 | 21 | 12 | 23 | 23 | 305 | 34 | 251 | 89 | 224 | 22 | 204 | 87 | 179 | 8 | 1 | 3 | 53 |
147,640 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/HTMLPlotter/TVarFigureAlt.py
|
pytplot.HTMLPlotter.TVarFigureAlt.TVarFigureAlt
|
class TVarFigureAlt(object):
def __init__(self, tvar_name, auto_color, show_xaxis=False, slice=False):
self.tvar_name = tvar_name
self.auto_color = auto_color
self.show_xaxis = show_xaxis
self.slice = slice
# Variables needed across functions
self.colors = ['black', 'red', 'green', 'navy', 'orange', 'firebrick', 'pink', 'blue', 'olive']
self.lineglyphs = []
self.linenum = 0
self.interactive_plot = None
self.fig = Figure(tools=pytplot.tplot_opt_glob['tools'],
y_axis_type=self._getyaxistype())
self.fig.add_tools(BoxZoomTool(dimensions='width'))
self._format()
@staticmethod
def get_axis_label_color():
if pytplot.tplot_opt_glob['black_background']:
text_color = '#000000'
else:
text_color = '#FFFFFF'
return text_color
@staticmethod
def getaxistype():
axis_type = 'altitude'
link_y_axis = False
return axis_type, link_y_axis
def getfig(self):
if self.slice:
return [self.fig, self.interactive_plot]
else:
return [self.fig]
def setsize(self, width, height):
self.fig.plot_width = width
if self.show_xaxis:
self.fig.plot_height = height + 22
else:
self.fig.plot_height = height
def add_title(self):
if 'title_text' in pytplot.tplot_opt_glob:
if pytplot.tplot_opt_glob['title_text'] != '':
title1 = Title(text=pytplot.tplot_opt_glob['title_text'],
align=pytplot.tplot_opt_glob['title_align'],
text_font_size=pytplot.tplot_opt_glob['title_size'],
text_color=self.get_axis_label_color())
self.fig.title = title1
self.fig.plot_height += 22
def buildfigure(self):
self._setminborder()
self._setxrange()
self._setxaxis()
self._setyrange()
self._visdata()
self._setxaxislabel()
self._setyaxislabel()
self._addhoverlines()
self._addlegend()
self._addtimebars()
def _format(self):
# Formatting stuff
self.fig.grid.grid_line_color = None
self.fig.axis.major_tick_line_color = None
self.fig.axis.major_label_standoff = 0
self.fig.title = None
self.fig.toolbar.active_drag = 'auto'
if not self.show_xaxis:
self.fig.xaxis.major_label_text_font_size = '0pt'
self.fig.xaxis.visible = False
def _setxrange(self):
# Check if x range is not set, if not, set good ones
if 'alt_range' not in pytplot.tplot_opt_glob:
datasets = [pytplot.data_quants[self.tvar_name]]
x_min_list = []
x_max_list = []
for oplot_name in pytplot.data_quants[self.tvar_name].attrs['plot_options']['overplots']:
datasets.append(pytplot.data_quants[oplot_name])
for dataset in datasets:
coords = pytplot.tplot_utilities.return_interpolated_link_dict(dataset, ['alt'])
alt = coords['alt'].values
x_min_list.append(np.nanmin(alt.tolist()))
x_max_list.append(np.nanmax(alt.tolist()))
pytplot.tplot_opt_glob['alt_range'] = [np.nanmin(x_min_list), np.nanmax(x_max_list)]
tplot_x_range = [np.nanmin(x_min_list), np.nanmax(x_max_list)]
if self.show_xaxis:
pytplot.lim_info['xfull'] = tplot_x_range
pytplot.lim_info['xlast'] = tplot_x_range
x_range = Range1d(pytplot.tplot_opt_glob['alt_range'][0], pytplot.tplot_opt_glob['alt_range'][1])
self.fig.x_range = x_range
def _setyrange(self):
if self._getyaxistype() == 'log':
if pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][0] <= 0 \
or pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][1] <= 0:
return
y_range = Range1d(pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][0],
pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][1])
self.fig.y_range = y_range
def _setminborder(self):
self.fig.min_border_bottom = pytplot.tplot_opt_glob['min_border_bottom']
self.fig.min_border_top = pytplot.tplot_opt_glob['min_border_top']
def _addtimebars(self):
for time_bar in pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar']:
time_bar_line = Span(location=time_bar['location'],
dimension=time_bar['dimension'],
line_color=time_bar['line_color'],
line_width=time_bar['line_width'])
self.fig.renderers.extend([time_bar_line])
# grab tbardict
tbardict = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar']
ltbar = len(tbardict)
# make sure data is in list format
datasets = [pytplot.data_quants[self.tvar_name]]
for oplot_name in pytplot.data_quants[self.tvar_name].attrs['plot_options']['overplots']:
datasets.append(pytplot.data_quants[oplot_name])
for dataset in datasets:
# TODO: The below function is essentially a hack for now, because this code was written assuming the data was a dataframe object.
# This needs to be rewritten to use xarray
dataset = pytplot.tplot_utilities.convert_tplotxarray_to_pandas_dataframe(dataset.name, no_spec_bins=True)
# for location in tbar dict
for i in range(ltbar):
# get times, color, point size
test_time = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["location"]
color = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["line_color"]
pointsize = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["line_width"]
# correlate given time with corresponding data/alt points
time = pytplot.data_quants[pytplot.data_quants[self.tvar_name].attrs['plot_options']['links']['alt']].coords['time'].values
altitude = pytplot.data_quants[pytplot.data_quants[self.tvar_name].attrs['plot_options']['links']['alt']].values
nearest_time_index = np.abs(time - test_time).argmin()
data_point = dataset.iloc[nearest_time_index][0]
alt_point = altitude[nearest_time_index]
self.fig.circle([alt_point], [data_point], size=pointsize, color=color)
return
def _setxaxis(self):
# Nothing to set for now
return
def _getyaxistype(self):
if 'y_axis_type' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']:
return pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_axis_type']
else:
return 'linear'
def _setcolors(self):
if 'line_color' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']:
self.colors = pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['line_color']
def _setxaxislabel(self):
if 'axis_label' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['xaxis_opt']:
self.fig.xaxis.axis_label = pytplot.data_quants[self.tvar_name].attrs['plot_options']['xaxis_opt']['axis_label']
self.fig.xaxis.axis_label = 'Altitude'
self.fig.xaxis.axis_label_text_font_size = str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])+'pt'
self.fig.xaxis.axis_label_text_color = self.get_axis_label_color()
def _setyaxislabel(self):
self.fig.yaxis.axis_label = pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['axis_label']
self.fig.yaxis.axis_label_text_font_size = str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])+'pt'
self.fig.yaxis.axis_label_text_color = self.get_axis_label_color()
def _visdata(self):
self._setcolors()
# make sure data is in list format
datasets = [pytplot.data_quants[self.tvar_name]]
for oplot_name in pytplot.data_quants[self.tvar_name].attrs['plot_options']['overplots']:
datasets.append(pytplot.data_quants[oplot_name])
for dataset in datasets:
# Get Linestyle
line_style = None
if 'line_style' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['line_opt']:
line_style = pytplot.data_quants[self.tvar_name].attrs['plot_options']['line_opt']['line_style']
coords = pytplot.tplot_utilities.return_interpolated_link_dict(dataset, ['alt'])
t_link = coords['alt'].coords['time'].values
x = coords['alt'].values
df = pytplot.tplot_utilities.convert_tplotxarray_to_pandas_dataframe(dataset.name, no_spec_bins=True)
# Create lines from each column in the dataframe
for column_name in df.columns:
y = df[column_name]
t_tvar = df.index.values
y = df.values
while t_tvar[-1] > t_link[-1]:
t_tvar = np.delete(t_tvar, -1)
y = np.delete(y, -1)
while t_tvar[0] < t_link[0]:
t_tvar = np.delete(t_tvar, 0)
y = np.delete(y, 0)
if self._getyaxistype() == 'log':
y[y <= 0] = np.NaN
line_source = ColumnDataSource(data=dict(x=x, y=y))
if self.auto_color:
line = Circle(x='x', y='y', line_color=self.colors[self.linenum % len(self.colors)])
else:
line = Circle(x='x', y='y')
if 'line_style' not in pytplot.data_quants[self.tvar_name].attrs['plot_options']['line_opt']:
if line_style is not None:
line.line_dash = line_style[self.linenum % len(line_style)]
else:
line.line_dash = pytplot.data_quants[self.tvar_name].attrs['plot_options']['line_opt']['line_style']
self.lineglyphs.append(self.fig.add_glyph(line_source, line))
self.linenum += 1
def _addhoverlines(self):
# Add tools
hover = HoverTool()
hover.tooltips = [("Value", "@y")]
self.fig.add_tools(hover)
def _addlegend(self):
# Add the Legend if applicable
if 'legend_names' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']:
legend_names = pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['legend_names']
if len(legend_names) != self.linenum:
print("Number of lines do not match length of legend names")
legend = Legend()
legend.location = (0, 0)
legend_items = []
j = 0
for legend_name in legend_names:
legend_items.append((legend_name, [self.lineglyphs[j]]))
j = j+1
if j >= len(self.lineglyphs):
break
legend.items = legend_items
legend.label_text_font_size = str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])+'pt'
legend.border_line_color = None
legend.glyph_height = int(self.fig.plot_height / (len(legend_items) + 1))
self.fig.add_layout(legend, 'right')
|
class TVarFigureAlt(object):
def __init__(self, tvar_name, auto_color, show_xaxis=False, slice=False):
pass
@staticmethod
def get_axis_label_color():
pass
@staticmethod
def getaxistype():
pass
def getfig(self):
pass
def setsize(self, width, height):
pass
def add_title(self):
pass
def buildfigure(self):
pass
def _format(self):
pass
def _setxrange(self):
pass
def _setyrange(self):
pass
def _setminborder(self):
pass
def _addtimebars(self):
pass
def _setxaxis(self):
pass
def _getyaxistype(self):
pass
def _setcolors(self):
pass
def _setxaxislabel(self):
pass
def _setyaxislabel(self):
pass
def _visdata(self):
pass
def _addhoverlines(self):
pass
def _addlegend(self):
pass
| 23 | 0 | 11 | 0 | 10 | 1 | 3 | 0.09 | 1 | 4 | 0 | 0 | 18 | 9 | 20 | 20 | 246 | 29 | 201 | 81 | 178 | 18 | 184 | 79 | 163 | 11 | 1 | 4 | 53 |
147,641 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/QtPlotter/TVarFigureAxisOnly.py
|
pytplot.QtPlotter.TVarFigureAxisOnly.TVarFigureAxisOnly
|
class TVarFigureAxisOnly(pg.GraphicsLayout):
def __init__(self, tvar_name):
self.tvar_name = tvar_name
# Sets up the layout of the Tplot Object
pg.GraphicsLayout.__init__(self)
self.layout.setHorizontalSpacing(10)
self.layout.setContentsMargins(0, 0, 0, 0)
if pytplot.tplot_opt_glob['black_background']:
self.labelStyle = {'font-size':
str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])
+ 'pt', 'color': '#FFF'}
else:
self.labelStyle = {'font-size':
str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])
+ 'pt', 'color': '#000'}
vb = CustomVB(enableMouse=False)
self.yaxis = AxisItem("left")
self.yaxis.setLabel(pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['axis_label'], **self.labelStyle)
self.yaxis.label.setRotation(0)
qt_transform = pg.QtGui.QTransform()
qt_transform.translate(0,-40)
self.yaxis.label.setTransform(qt_transform)
#self.yaxis.label.translate(0, -40)
mapping_function = interpolate.interp1d(pytplot.data_quants[self.tvar_name].coords['time'].values, pytplot.data_quants[self.tvar_name].values)
if 'var_label_ticks' in pytplot.data_quants[self.tvar_name].attrs['plot_options']:
num_ticks = pytplot.data_quants[self.tvar_name].attrs['plot_options']['var_label_ticks']
else:
num_ticks=5
xaxis = NonLinearAxis(orientation='bottom', mapping_function=mapping_function, num_ticks=num_ticks)
# Set the font size of the axes
font = QtGui.QFont()
font.setPixelSize(pytplot.tplot_opt_glob['axis_font_size'])
xaxis.setTickFont(font)
self.plotwindow = self.addPlot(row=0, col=0, axisItems={'bottom': xaxis, 'left': self.yaxis}, viewBox=vb, colspan=1)
self.plotwindow.buttonsHidden = True
self.plotwindow.setMaximumHeight(20)
# Set up the view box needed for the legends
self.legendvb = pg.ViewBox(enableMouse=False)
self.legendvb.setMaximumWidth(100)
self.addItem(self.legendvb, 0, 1)
|
class TVarFigureAxisOnly(pg.GraphicsLayout):
def __init__(self, tvar_name):
pass
| 2 | 0 | 45 | 6 | 35 | 6 | 3 | 0.17 | 1 | 4 | 3 | 0 | 1 | 5 | 1 | 1 | 46 | 6 | 36 | 13 | 34 | 6 | 30 | 13 | 28 | 3 | 1 | 1 | 3 |
147,642 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/QtPlotter/TVarFigureAlt.py
|
pytplot.QtPlotter.TVarFigureAlt.TVarFigureAlt
|
class TVarFigureAlt(pg.GraphicsLayout):
def __init__(self, tvar_name, show_xaxis=False, mouse_function=None):
self.tvar_name = tvar_name
self.show_xaxis = show_xaxis
self.crosshair = pytplot.tplot_opt_glob['crosshair']
# Sets up the layout of the Tplot Object
pg.GraphicsLayout.__init__(self)
self.layout.setHorizontalSpacing(50)
self.layout.setContentsMargins(0, 0, 0, 0)
# Set up the x axis
self.xaxis = pg.AxisItem(orientation='bottom')
self.xaxis.setHeight(35)
self.xaxis.enableAutoSIPrefix(enable=False)
# Set up the y axis
self.yaxis = AxisItem("left")
self.yaxis.setStyle(textFillLimits=pytplot.tplot_opt_glob["axis_tick_num"]) # Set an absurdly high number for the first 3, ensuring that at least 3 axis labels are always present
vb = NoPaddingPlot()
# Creating axes to bound the plots with lines
self.xaxis2 = pg.AxisItem(orientation='top')
self.xaxis2.setHeight(0)
self.yaxis2 = AxisItem("right")
self.yaxis2.setWidth(0)
self.plotwindow = self.addPlot(row=0, col=0, axisItems={'bottom': self.xaxis,
'left': self.yaxis,
'right': self.yaxis2,
'top': self.xaxis2}, viewBox=vb)
# Turn off zooming in on the y-axis, altitude resolution is much more important
self.plotwindow.setMouseEnabled(y=pytplot.tplot_opt_glob['y_axis_zoom'])
if pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['border']:
self.plotwindow.showAxis("top")
self.plotwindow.showAxis("right")
# Set up the view box needed for the legends
self.legendvb = pg.ViewBox(enableMouse=False)
self.legendvb.setMaximumWidth(100)
self.legendvb.setXRange(0, 1, padding=0)
self.legendvb.setYRange(0, 1, padding=0)
self.addItem(self.legendvb, 0, 1)
self.curves = []
self.colors = self._setcolors()
self.colormap = self._setcolormap()
if pytplot.tplot_opt_glob['black_background']:
self.labelStyle = {'font-size':
str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])
+ 'pt', 'color': '#FFF',
'white-space': 'pre-wrap'}
else:
self.labelStyle = {'font-size':
str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])
+ 'pt', 'color': '#000',
'white-space': 'pre-wrap'}
# Set the font size of the axes
font = QtGui.QFont()
font.setPixelSize(pytplot.tplot_opt_glob['axis_font_size'])
self.xaxis.setTickFont(font)
self.yaxis.setTickFont(font)
self.yaxis.setStyle(textFillLimits=pytplot.tplot_opt_glob["axis_tick_num"],
tickFont=font) # Set an absurdly high number for the first 3, ensuring that at least 3 axis labels are always present
if show_xaxis:
self.plotwindow.showAxis('bottom')
else:
self.plotwindow.hideAxis('bottom')
self._mouseMovedFunction = mouse_function
if pytplot.tplot_opt_glob["black_background"]:
self.vLine = pg.InfiniteLine(angle=90, movable=False, pen=pg.mkPen('w'))
self.hLine = pg.InfiniteLine(angle=0, movable=False, pen=pg.mkPen('w'))
else:
self.vLine = pg.InfiniteLine(angle=90, movable=False, pen=pg.mkPen('k'))
self.hLine = pg.InfiniteLine(angle=0, movable=False, pen=pg.mkPen('k'))
self.plotwindow.addItem(self.vLine, ignoreBounds=True)
self.plotwindow.addItem(self.hLine, ignoreBounds=True)
self.vLine.setVisible(False)
self.hLine.setVisible(False)
self.label = pg.LabelItem(justify='left')
self.addItem(self.label, row=1, col=0)
# Set legend options
self.hoverlegend = CustomLegendItem(offset=(0, 0))
# Allow the user to set x-axis(time) and y-axis data names in crosshairs
self.hoverlegend.setItem(pytplot.data_quants[self.tvar_name].attrs['plot_options']['xaxis_opt']['crosshair'] + ':', "0")
self.hoverlegend.setItem(pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['crosshair'] + ':', "0")
self.hoverlegend.setVisible(False)
self.hoverlegend.setParentItem(self.plotwindow.vb)
def buildfigure(self):
self._setxrange()
self._setyrange()
self._setyaxistype()
self._setzaxistype()
self._setzrange()
self._visdata()
self._addtimebars()
self._setxaxislabel()
self._setyaxislabel()
if self.crosshair:
self._addmouseevents()
self._addlegend()
def getfig(self):
return self
def _setxaxislabel(self):
self.xaxis.setLabel("Altitude", **self.labelStyle)
def _setyaxislabel(self):
ylabel = pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['axis_label'].replace(" \ ", " <br> ")
if "axis_subtitle" in pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']:
sublabel = pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['axis_subtitle'].replace(" \ ", " <br> ")
self.yaxis.setLabel(f"{ylabel} <br> {sublabel}", **self.labelStyle)
else:
self.yaxis.setLabel(ylabel, **self.labelStyle)
def _setyaxistype(self):
if self._getyaxistype() == 'log':
self.plotwindow.setLogMode(y=True)
else:
self.plotwindow.setLogMode(y=False)
return
def _getyaxistype(self):
if 'y_axis_type' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']:
return pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_axis_type']
else:
return 'linear'
def _setxrange(self):
if 'alt_range' in pytplot.tplot_opt_glob:
self.plotwindow.setXRange(pytplot.tplot_opt_glob['alt_range'][0], pytplot.tplot_opt_glob['alt_range'][1])
else:
return
@staticmethod
def getaxistype():
axis_type = 'altitude'
link_y_axis = False
return axis_type, link_y_axis
def _addmouseevents(self):
if self.plotwindow.scene() is not None:
self.plotwindow.scene().sigMouseMoved.connect(self._mousemoved)
def round_sig(self, x, sig=4):
return round(x, sig - int(floor(log10(abs(x)))) - 1)
def _mousemoved(self, evt):
# get current position
pos = evt
# if plot window contains position
if self.plotwindow.sceneBoundingRect().contains(pos):
mousepoint = self.plotwindow.vb.mapSceneToView(pos)
# grab x and y mouse locations
index_x = int(mousepoint.x())
# set log magnitude if log plot
if self._getyaxistype() == 'log':
index_y = self.round_sig(10 ** (float(mousepoint.y())), 4)
else:
index_y = round(float(mousepoint.y()), 4)
# add crosshairs
if self._mouseMovedFunction is not None:
self._mouseMovedFunction(int(mousepoint.x()))
self.vLine.setPos(mousepoint.x())
self.hLine.setPos(mousepoint.y())
self.vLine.setVisible(True)
self.hLine.setVisible(True)
# Set legend options
self.hoverlegend.setVisible(True)
# Allow the user to set x-axis(time) and y-axis data names in crosshairs
self.hoverlegend.setItem(pytplot.data_quants[self.tvar_name].attrs['plot_options']['xaxis_opt']['crosshair'] + ':', index_x)
self.hoverlegend.setItem(pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['crosshair'] + ':', index_y)
else:
self.hoverlegend.setVisible(False)
self.vLine.setVisible(False)
self.hLine.setVisible(False)
def _addlegend(self):
if 'legend_names' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']:
legend_names = pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['legend_names']
if len(legend_names) != len(self.curves):
print("Number of lines do not match length of legend names")
if len(legend_names) == 1:
pos_array = [.5]
else:
pos_array = np.linspace(1, 0, len(legend_names))
i = 0
for legend_name in legend_names:
if i + 1 == len(legend_names): # Last
text = pg.TextItem(text=legend_name, anchor=(0, 1.5), color=self.colors[i % len(self.colors)])
elif i == 0: # First
text = pg.TextItem(text=legend_name, anchor=(0, -.5), color=self.colors[i % len(self.colors)])
else: # All others
text = pg.TextItem(text=legend_name, anchor=(0, 0.5), color=self.colors[i % len(self.colors)])
self.legendvb.addItem(text)
text.setPos(0, pos_array[i])
i += 1
def _setzaxistype(self):
if self._getzaxistype() == 'log':
self.zscale = 'log'
else:
self.zscale = 'linear'
def _getzaxistype(self):
return
def _setcolors(self):
if 'line_color' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']:
return pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['line_color']
else:
if pytplot.tplot_opt_glob['black_background']:
return pytplot.tplot_utilities.rgb_color(['w', 'r', 'seagreen', 'b', 'darkturquoise', 'm', 'goldenrod'])
else:
return pytplot.tplot_utilities.rgb_color(['k', 'r', 'seagreen', 'b', 'darkturquoise', 'm', 'goldenrod'])
def _setcolormap(self):
return
def _setyrange(self):
if self._getyaxistype() == 'log':
if pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][0] <= 0 or \
pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][1] <= 0:
return
self.plotwindow.vb.setYRange(np.log10(pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][0]),
np.log10(pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][1]),
padding=0)
else:
self.plotwindow.vb.setYRange(pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][0],
pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][1], padding=0)
def _setzrange(self):
return
def _addtimebars(self):
# initialize dataset variable
datasets = []
# grab tbardict
tbardict = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar']
ltbar = len(tbardict)
# make sure data is in list format
datasets = [pytplot.data_quants[self.tvar_name]]
for oplot_name in pytplot.data_quants[self.tvar_name].attrs['plot_options']['overplots']:
datasets.append(pytplot.data_quants[oplot_name])
for dataset in datasets:
# TODO: The below function is essentially a hack for now, because this code was written assuming the data was a dataframe object.
# This needs to be rewritten to use xarray
dataset = pytplot.tplot_utilities.convert_tplotxarray_to_pandas_dataframe(dataset.name, no_spec_bins=True)
# for location in tbar dict
for i in range(ltbar):
# get times, color, point size
test_time = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["location"]
color = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["line_color"]
pointsize = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["line_width"]
# correlate given time with corresponding data/alt points
time = pytplot.data_quants[pytplot.data_quants[self.tvar_name].attrs['plot_options']['links']['alt']].coords['time'].values
altitude = pytplot.data_quants[pytplot.data_quants[self.tvar_name].attrs['plot_options']['links']['alt']].values
nearest_time_index = np.abs(time - test_time).argmin()
data_point = dataset.iloc[nearest_time_index][0]
alt_point = altitude[nearest_time_index]
self.plotwindow.scatterPlot([alt_point], [data_point], size=pointsize, pen=pg.mkPen(None), brush=color)
return
def _visdata(self):
datasets = [pytplot.data_quants[self.tvar_name]]
for oplot_name in pytplot.data_quants[self.tvar_name].attrs['plot_options']['overplots']:
datasets.append(pytplot.data_quants[oplot_name])
line_num = 0
for dataset_xr in datasets:
# TODO: The below function is essentially a hack for now, because this code was written assuming the data was a dataframe object.
# This needs to be rewritten to use xarray
dataset = pytplot.tplot_utilities.convert_tplotxarray_to_pandas_dataframe(dataset_xr.name, no_spec_bins=True)
coords = pytplot.tplot_utilities.return_interpolated_link_dict(dataset_xr, ['alt'])
for i in range(0, len(dataset.columns)):
t_link = coords['alt'].coords['time'].values
x = coords['alt'].values
# Need to trim down the data points to fit within the link
t_tvar = dataset.index.values
data = dataset[i].values
while t_tvar[-1] > t_link[-1]:
t_tvar = np.delete(t_tvar, -1)
data = np.delete(data, -1)
while t_tvar[0] < t_link[0]:
t_tvar = np.delete(t_tvar, 0)
data = np.delete(data, 0)
self.curves.append(self.plotwindow.scatterPlot(x.tolist(), data.tolist(),
pen=pg.mkPen(None), brush=self.colors[line_num %
len(self.colors)]))
line_num += 1
|
class TVarFigureAlt(pg.GraphicsLayout):
def __init__(self, tvar_name, show_xaxis=False, mouse_function=None):
pass
def buildfigure(self):
pass
def getfig(self):
pass
def _setxaxislabel(self):
pass
def _setyaxislabel(self):
pass
def _setyaxistype(self):
pass
def _getyaxistype(self):
pass
def _setxrange(self):
pass
@staticmethod
def getaxistype():
pass
def _addmouseevents(self):
pass
def round_sig(self, x, sig=4):
pass
def _mousemoved(self, evt):
pass
def _addlegend(self):
pass
def _setzaxistype(self):
pass
def _getzaxistype(self):
pass
def _setcolors(self):
pass
def _setcolormap(self):
pass
def _setyrange(self):
pass
def _setzrange(self):
pass
def _addtimebars(self):
pass
def _visdata(self):
pass
| 23 | 0 | 14 | 1 | 11 | 2 | 3 | 0.14 | 1 | 7 | 3 | 0 | 20 | 19 | 21 | 21 | 307 | 43 | 237 | 82 | 214 | 34 | 204 | 81 | 182 | 7 | 1 | 3 | 53 |
147,643 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/QtPlotter/TVarFigure1D.py
|
pytplot.QtPlotter.TVarFigure1D.TVarFigure1D
|
class TVarFigure1D(pg.GraphicsLayout):
def __init__(self, tvar_name, show_xaxis=False):
self.tvar_name = tvar_name
self.show_xaxis = show_xaxis
if 'show_all_axes' in pytplot.tplot_opt_glob:
if pytplot.tplot_opt_glob['show_all_axes']:
self.show_xaxis = True
self.crosshair = pytplot.tplot_opt_glob['crosshair']
# Sets up the layout of the Tplot Object
pg.GraphicsLayout.__init__(self)
self.layout.setHorizontalSpacing(10)
self.layout.setContentsMargins(0, 0, 0, 0)
# Set up the x axis
if self.show_xaxis:
self.xaxis = DateAxis(orientation='bottom')
self.xaxis.setHeight(35)
else:
self.xaxis = DateAxis(orientation='bottom', showValues=False)
self.xaxis.setHeight(0)
self.xaxis.enableAutoSIPrefix(enable=False)
# Set up the y axis
self.yaxis = AxisItem("left")
# Creating axes to bound the plots with lines
self.xaxis2 = DateAxis(orientation='top', showValues=False)
self.xaxis2.setHeight(0)
self.yaxis2 = AxisItem("right", showValues=False)
self.yaxis2.setWidth(0)
vb = NoPaddingPlot()
# Generate our plot in the graphics layout
self.plotwindow = self.addPlot(row=0, col=0, axisItems={'bottom': self.xaxis,
'left': self.yaxis,
'right': self.yaxis2,
'top': self.xaxis2}, viewBox=vb)
#Turn off zooming in on the y-axis, time resolution is much more important
self.plotwindow.setMouseEnabled(y=pytplot.tplot_opt_glob['y_axis_zoom'])
if pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['border']:
self.plotwindow.showAxis("top")
self.plotwindow.showAxis("right")
# Set up the view box needed for the legends
self.legendvb = pg.ViewBox(enableMouse=False)
self.legendvb.setMaximumWidth(100)
self.legendvb.setXRange(0, 1, padding=0)
self.legendvb.setYRange(0, 1, padding=0)
self.addItem(self.legendvb, 0, 1)
self.curves = []
self.colors = self._setcolors()
self.colormap = self._setcolormap()
if pytplot.tplot_opt_glob['black_background']:
self.labelStyle = {'font-size':
str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])
+ 'pt', 'color': '#FFF',
'white-space': 'pre-wrap'}
else:
self.labelStyle = {'font-size':
str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])
+ 'pt', 'color': '#000',
'white-space': 'pre-wrap'}
# Set the font size of the axes
font = QtGui.QFont()
font.setPixelSize(pytplot.tplot_opt_glob['axis_font_size'])
self.xaxis.setTickFont(font)
self.yaxis.setTickFont(font)
self.yaxis.setStyle(textFillLimits=pytplot.tplot_opt_glob["axis_tick_num"], tickFont=font) # Set an absurdly high number for the first 3, ensuring that at least 3 axis labels are always present
# Set legend options
self.hoverlegend = CustomLegendItem(offset=(0, 0))
self.hoverlegend.setItem("Date:", "0")
# Allow the user to set x-axis(time) and y-axis names in crosshairs
self.hoverlegend.setItem(pytplot.data_quants[self.tvar_name].attrs['plot_options']['xaxis_opt']['crosshair']
+ ':', "0")
self.hoverlegend.setItem(pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['crosshair']
+ ':', "0")
self.hoverlegend.setVisible(False)
self.hoverlegend.setParentItem(self.plotwindow.vb)
def _set_crosshairs(self):
if pytplot.tplot_opt_glob["black_background"]:
self.vLine = pg.InfiniteLine(angle=90, movable=False, pen=pg.mkPen('w'))
self.hLine = pg.InfiniteLine(angle=0, movable=False, pen=pg.mkPen('w'))
else:
self.vLine = pg.InfiniteLine(angle=90, movable=False, pen=pg.mkPen('k'))
self.hLine = pg.InfiniteLine(angle=0, movable=False, pen=pg.mkPen('k'))
self.plotwindow.addItem(self.vLine, ignoreBounds=True)
self.plotwindow.addItem(self.hLine, ignoreBounds=True)
self.vLine.setVisible(False)
self.hLine.setVisible(False)
def _set_roi_lines(self):
if 'roi_lines' in pytplot.tplot_opt_glob.keys():
# Locating the two times between which there's a roi
roi_1 = pytplot.tplot_utilities.str_to_int(pytplot.tplot_opt_glob['roi_lines'][0])
roi_2 = pytplot.tplot_utilities.str_to_int(pytplot.tplot_opt_glob['roi_lines'][1])
# find closest time to user-requested time
x = pytplot.data_quants[self.tvar_name].coords['time']
x_sub_1 = abs(x - roi_1 * np.ones(len(x)))
x_sub_2 = abs(x - roi_2 * np.ones(len(x)))
x_argmin_1 = np.nanargmin(x_sub_1)
x_argmin_2 = np.nanargmin(x_sub_2)
x_closest_1 = x[x_argmin_1]
x_closest_2 = x[x_argmin_2]
# Create roi box
roi = CustomLinearRegionItem(orientation=pg.LinearRegionItem.Vertical, values=[x_closest_1, x_closest_2])
roi.setBrush([211, 211, 211, 130])
roi.lines[0].setPen('r', width=2.5)
roi.lines[1].setPen('r', width=2.5)
self.plotwindow.addItem(roi)
def buildfigure(self):
self._setxrange()
self._setyrange()
self._setyaxistype()
self._setzaxistype()
self._setzrange()
self._visdata()
self._setxaxislabel()
self._setyaxislabel()
self._addlegend()
self._addtimebars()
if self.crosshair:
self._set_crosshairs()
self._addmouseevents()
self._set_roi_lines()
def _setxaxislabel(self):
if self.show_xaxis:
self.xaxis.setLabel(pytplot.data_quants[self.tvar_name].attrs['plot_options']['xaxis_opt']['axis_label'], **self.labelStyle)
def _setyaxislabel(self):
ylabel = pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['axis_label'].replace(" \ ", " <br> ")
if "axis_subtitle" in pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']:
ysublabel = pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['axis_subtitle'].replace(" \ ", " <br> ")
self.yaxis.setLabel(f"{ylabel} <br> {ysublabel}", **self.labelStyle)
else:
self.yaxis.setLabel(ylabel, **self.labelStyle)
def getfig(self):
return self
def _visdata(self):
datasets = [pytplot.data_quants[self.tvar_name]]
for oplot_name in pytplot.data_quants[self.tvar_name].attrs['plot_options']['overplots']:
datasets.append(pytplot.data_quants[oplot_name])
line_num = 0
for dataset in datasets:
# TODO: The below function is essentially a hack for now, because this code was written assuming the data was a dataframe object.
# This needs to be rewritten to use xarray
plot_options = dataset.attrs['plot_options']
dataset = pytplot.tplot_utilities.convert_tplotxarray_to_pandas_dataframe(dataset.name, no_spec_bins=True)
for i in range(len(dataset.columns)):
if 'line_style' in plot_options['line_opt']:
if plot_options['line_opt']['line_style'] == 'scatter':
self.curves.append(self.plotwindow.scatterPlot(x=dataset.index.tolist(),
y=dataset[i].tolist(),
pen=self.colors[line_num % len(self.colors)],
symbol='+'))
line_num += 1
continue
limit = pytplot.tplot_opt_glob['data_gap'] # How big a data gap is allowed before those nans (default
# is to plot as pyqtgraph would normally plot w / o worrying about data gap handling).
if limit != 0:
# Grabbing the times associated with nan values (nan_values), and the associated "position" of those
# keys in the dataset list (nan_keys)
nan_values = dataset[i][dataset[i].isnull().values].index.tolist()
nan_keys = [dataset[i].index.tolist().index(j) for j in nan_values]
count = 0 # Keeping a count of how big of a time gap we have
flag = False # This flag changes to true when we accumulate a big enough period of time that we
# exceed the user-specified data gap
consec_list = list() # List of consecutive nan values (composed of indices for gaps not bigger than
# the user-specified data gap)
overall_list = list() # List of consecutive nan values (composed of indices for gaps bigger than
# the user-specified data gap)
for val, actual_value in enumerate(nan_keys):
# Avoiding some weird issues with going to the last data point in the nan dictionary keys
if actual_value != nan_keys[-1]:
# Difference between one index and another - if consecutive indices, the diff will be 1
diff = abs(nan_keys[val] - nan_keys[val+1])
# calculate time accumulated from one index to the next
t_now = nan_values[val]
t_next = nan_values[val + 1]
time_accum = abs(t_now - t_next)
# If we haven't reached the allowed data gap, just keep track of how big of a gap we're at,
# and the indices in the gap
if diff == 1 and count < limit:
count += time_accum
consec_list.append(nan_keys[val])
# This triggers when we initially exceed the allowed data gap
elif diff == 1 and count >= limit and not flag:
count += time_accum
# For some reason if you don't grab the point before the big data gap happened, when you
# plot this, the data gap isn't actually removed...
if consec_list[0] != 0:
consec_list.insert(0, consec_list[0]-1)
# Put the current datagap into the list (overall_list) whose indices will actually be
# removed from the final plot
overall_list.append(consec_list)
overall_list.append([nan_keys[val]])
flag = True
# If we already exceeded the data gap, and the current index is still part of a gap,
# throw that index into the overall_list
elif diff == 1 and count > limit and flag:
count += time_accum
overall_list.append([nan_keys[val]])
# When we find that the previous index and the current one are not consecutive, stop adding
# to the consec_list/overall_list (if applicable), and start over the count of time
# accumulated in a gap, as well as the consecutive list of time values with nans
elif diff != 1:
count = 0
consec_list = []
flag = False
# For some reason if you don't grab the point after the last point where big data gap
# happened, when you plot, the data gap isn't actually removed...
if nan_keys[val-1] in [y for x in overall_list for y in x]:
overall_list.append([nan_keys[val]])
# Flatten the overall_list to just one list, instead of a list of many lists
overall_list = [y for x in overall_list for y in x]
# Remove data gaps removed based on user-input acceptable time gap
# In order to do this, we set the identified indices from overall_list to 0, which in the
# connect keyword argument in self.plotwindow.plot will cause that point to not be plotted
time_filtered = np.array([1]*len(dataset.index.tolist()))
time_filtered[overall_list] = 0
if limit != 0:
# Plot with interpolation of all data gaps
self.curves.append(self.plotwindow.plot(x=dataset.index.tolist(),
y=dataset[i].tolist(),
pen=self.colors[line_num % len(self.colors)],
connect=time_filtered))
else:
# Plot with interpolation of all data gaps
self.curves.append(self.plotwindow.plot(x=dataset.index.tolist(),
y=dataset[i].tolist(),
pen=self.colors[line_num % len(self.colors)]))
line_num += 1
def _setyaxistype(self):
if self._getyaxistype() == 'log':
self.plotwindow.setLogMode(y=True)
else:
self.plotwindow.setLogMode(y=False)
return
def _addlegend(self):
if 'legend_names' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']:
legend_names = pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['legend_names']
n_items = len(legend_names)
bottom_bound = 0.5 + (n_items - 1) * 0.05
top_bound = 0.5 - (n_items - 1) * 0.05
if len(legend_names) != len(self.curves):
print("Number of lines do not match length of legend names")
if len(legend_names) == 1:
pos_array = [.5]
else:
pos_array = np.linspace(bottom_bound, top_bound, len(legend_names))
i = 0
for legend_name in legend_names:
def rgb(red, green, blue): return '#%02x%02x%02x' % (red, green, blue)
r = self.colors[i % len(self.colors)][0]
g = self.colors[i % len(self.colors)][1]
b = self.colors[i % len(self.colors)][2]
hex_num = rgb(r, g, b)
color_text = 'color: ' + hex_num
font_size = 'font-size: ' + str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size'])+'pt'
opts = [color_text, font_size]
full = "<span style='%s'>%s</span>" % ('; '.join(opts), legend_name)
if i + 1 == len(legend_names): # Last
text = pg.TextItem(anchor=(0, 0.5))
text.setHtml(full)
elif i == 0: # First
text = pg.TextItem(anchor=(0, 0.5))
text.setHtml(full)
else: # All others
text = pg.TextItem(anchor=(0, 0.5))
text.setHtml(full)
self.legendvb.addItem(text)
text.setPos(0, pos_array[i])
i += 1
def _addmouseevents(self):
if self.plotwindow.scene() is not None:
self.plotwindow.scene().sigMouseMoved.connect(self._mousemoved)
def round_sig(self, x, sig=4):
return round(x, sig - int(floor(log10(abs(x)))) - 1)
def _mousemoved(self, evt):
# get current position
pos = evt
# if plot window contains position
if self.plotwindow.sceneBoundingRect().contains(pos):
mousepoint = self.plotwindow.vb.mapSceneToView(pos)
# grab x and y mouse locations
index_x = int(mousepoint.x())
# set log magnitude if log plot
if self._getyaxistype() == 'log':
index_y = self.round_sig(10 ** (float(mousepoint.y())), 4)
else:
index_y = round(float(mousepoint.y()), 4)
date = (pytplot.tplot_utilities.int_to_str(index_x))[0:10]
time = (pytplot.tplot_utilities.int_to_str(index_x))[11:19]
# add crosshairs
pytplot.hover_time.change_hover_time(int(mousepoint.x()), self.tvar_name)
if self.crosshair:
self.vLine.setPos(mousepoint.x())
self.hLine.setPos(mousepoint.y())
self.vLine.setVisible(True)
self.hLine.setVisible(True)
self.hoverlegend.setVisible(True)
self.hoverlegend.setItem("Date:", date)
# Allow the user to set x-axis(time) and y-axis data names in crosshairs
self.hoverlegend.setItem(pytplot.data_quants[self.tvar_name].attrs['plot_options']['xaxis_opt']['crosshair'] + ':', time)
self.hoverlegend.setItem(pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['crosshair'] + ':', str(index_y))
else:
self.hoverlegend.setVisible(False)
self.vLine.setVisible(False)
self.hLine.setVisible(False)
def _getyaxistype(self):
if 'y_axis_type' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']:
return pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_axis_type']
else:
return 'linear'
def _setzaxistype(self):
if self._getzaxistype() == 'log':
self.zscale = 'log'
else:
self.zscale = 'linear'
def _getzaxistype(self):
return
def _setcolors(self):
if 'line_color' in pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']:
return pytplot.tplot_utilities.rgb_color(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['line_color'])
else:
if len(pytplot.data_quants[self.tvar_name].data.shape) > 1:
if pytplot.data_quants[self.tvar_name].data.shape[1] == 3:
return pytplot.tplot_utilities.rgb_color(['b', 'g', 'r'])
if pytplot.tplot_opt_glob["black_background"]:
return pytplot.tplot_utilities.rgb_color(['w', 'r', 'seagreen', 'b', 'darkturquoise', 'm', 'goldenrod'])
else:
return pytplot.tplot_utilities.rgb_color(['k', 'r', 'seagreen', 'b', 'darkturquoise', 'm', 'goldenrod'])
def _setcolormap(self):
return
@staticmethod
def getaxistype():
axis_type = 'time'
link_y_axis = False
return axis_type, link_y_axis
def _setxrange(self):
# Check if x range is set. Otherwise, x range is automatic
if 'x_range' in pytplot.tplot_opt_glob:
self.plotwindow.setXRange(pytplot.tplot_opt_glob['x_range'][0], pytplot.tplot_opt_glob['x_range'][1])
def _setyrange(self):
if self._getyaxistype() == 'log':
if pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][0] <= 0 or \
pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][1] <= 0:
return
self.plotwindow.vb.setYRange(np.log10(pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][0]),
np.log10(pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][1]),
padding=0)
else:
self.plotwindow.vb.setYRange(pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][0],
pytplot.data_quants[self.tvar_name].attrs['plot_options']['yaxis_opt']['y_range'][1],
padding=0)
def _setzrange(self):
return
def _addtimebars(self):
# find number of times to plot
dict_length = len(pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'])
# for each time
for i in range(dict_length):
# pull date, color, thickness, and dimensions
if pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["dimension"] == 'height':
angle = 90
else:
angle = 0
date_to_highlight = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["location"]
color = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["line_color"]
thick = pytplot.data_quants[self.tvar_name].attrs['plot_options']['time_bar'][i]["line_width"]
# make infinite line w/ parameters
infline = pg.InfiniteLine(pos=date_to_highlight, pen=pg.mkPen(color, width=thick), angle=angle)
# add to plot window
self.plotwindow.addItem(infline)
return
|
class TVarFigure1D(pg.GraphicsLayout):
def __init__(self, tvar_name, show_xaxis=False):
pass
def _set_crosshairs(self):
pass
def _set_roi_lines(self):
pass
def buildfigure(self):
pass
def _setxaxislabel(self):
pass
def _setyaxislabel(self):
pass
def getfig(self):
pass
def _visdata(self):
pass
def _setyaxistype(self):
pass
def _addlegend(self):
pass
def rgb(red, green, blue):
pass
def _addmouseevents(self):
pass
def round_sig(self, x, sig=4):
pass
def _mousemoved(self, evt):
pass
def _getyaxistype(self):
pass
def _setzaxistype(self):
pass
def _getzaxistype(self):
pass
def _setcolors(self):
pass
def _setcolormap(self):
pass
@staticmethod
def getaxistype():
pass
def _setxrange(self):
pass
def _setyrange(self):
pass
def _setzrange(self):
pass
def _addtimebars(self):
pass
| 26 | 0 | 16 | 1 | 13 | 3 | 3 | 0.22 | 1 | 11 | 5 | 0 | 22 | 17 | 23 | 23 | 419 | 52 | 311 | 108 | 286 | 68 | 267 | 106 | 242 | 16 | 1 | 7 | 71 |
147,644 |
MAVENSDC/PyTplot
|
MAVENSDC_PyTplot/pytplot/__init__.py
|
pytplot.HoverTime
|
class HoverTime(object):
hover_time = 0
functions_to_call = []
def register_listener(self, fn):
self.functions_to_call.append(fn)
return
# New time is time we're hovering over, grabbed from TVarFigure(1D/Spec/Alt/Map)
# name is whatever tplot we're currently hovering over (relevant for 2D interactive
# plots that appear when plotting a spectrogram).
def change_hover_time(self, new_time, name=None):
self.hover_time = new_time
for f in self.functions_to_call:
try:
f(self.hover_time, name)
except Exception as e:
print(e)
return
|
class HoverTime(object):
def register_listener(self, fn):
pass
def change_hover_time(self, new_time, name=None):
pass
| 3 | 0 | 6 | 0 | 6 | 0 | 2 | 0.21 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 2 | 19 | 2 | 14 | 7 | 11 | 3 | 14 | 6 | 11 | 3 | 1 | 2 | 4 |
147,645 |
MAVENSDC/PyTplot
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MAVENSDC_PyTplot/pytplot/AncillaryPlots/position_mars_3d.py
|
pytplot.AncillaryPlots.position_mars_3d.position_mars_3d.PlanetView
|
class PlanetView(gl.GLViewWidget):
spacecraft_x = 0
spacecraft_y = 0
spacecraft_z = 0
# Store the name of the tplot variable stored, so we know if we need to redraw the orbit
tvar_name = 'temp'
def paintGL(self, region=None, viewport=None, useItemNames=False):
glLightfv(GL_LIGHT0, GL_POSITION, [-100000, 0, 0, 0])
super().paintGL(region=region, viewport=viewport, useItemNames=useItemNames)
|
class PlanetView(gl.GLViewWidget):
def paintGL(self, region=None, viewport=None, useItemNames=False):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0.13 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 8 | 0 | 8 | 6 | 6 | 1 | 8 | 6 | 6 | 1 | 1 | 0 | 1 |
147,646 |
MAVENSDC/cdflib
|
cdflib/dataclasses.py
|
cdflib.dataclasses.CDFInfo
|
class CDFInfo:
"""
CDF information.
"""
#: Path to the CDF.
CDF: Union[str, Path]
#: CDF version.
Version: str
#: Endianness of the CDF.
Encoding: int
#: Row/column majority.
Majority: str
#: zVariable names.
rVariables: List[str]
#: rVariable names.
zVariables: List[str]
#: List of dictionary objects that map attribute_name to scope.
Attributes: List[Dict[str, str]]
Copyright: str
#: Checksum indicator.
Checksum: bool
#: Number of dimensions for rVariables.
Num_rdim: int
#: Dimensional sizes for rVariables.
rDim_sizes: List[int]
#: If CDF is compressed at file level.
Compressed: bool
#: Last updated leap second table.
LeapSecondUpdate: Optional[int] = None
|
class CDFInfo:
'''
CDF information.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.07 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 30 | 1 | 14 | 2 | 13 | 15 | 14 | 2 | 13 | 0 | 0 | 0 | 0 |
147,647 |
MAVENSDC/cdflib
|
cdflib/dataclasses.py
|
cdflib.dataclasses.CDRInfo
|
class CDRInfo:
encoding: int
copyright_: str
version: str
majority: int
format_: bool
md5: bool
post25: bool
|
class CDRInfo:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 | 0 | 8 | 1 | 7 | 0 | 8 | 1 | 7 | 0 | 0 | 0 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.