repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
IntegerEntry.set
def set(self, num): """ Sets the current value equal to num """ self._value = str(int(num)) self._variable.set(self._value)
python
def set(self, num): """ Sets the current value equal to num """ self._value = str(int(num)) self._variable.set(self._value)
[ "def", "set", "(", "self", ",", "num", ")", ":", "self", ".", "_value", "=", "str", "(", "int", "(", "num", ")", ")", "self", ".", "_variable", ".", "set", "(", "self", ".", "_value", ")" ]
Sets the current value equal to num
[ "Sets", "the", "current", "value", "equal", "to", "num" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L142-L147
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
IntegerEntry.on_key_release_repeat
def on_key_release_repeat(self, *dummy): """ Avoid repeated trigger of callback. When holding a key down, multiple key press and release events are fired in succession. Debouncing is implemented to squash these. """ self.has_prev_key_release = self.after_idle(self.on_key_release, dummy)
python
def on_key_release_repeat(self, *dummy): """ Avoid repeated trigger of callback. When holding a key down, multiple key press and release events are fired in succession. Debouncing is implemented to squash these. """ self.has_prev_key_release = self.after_idle(self.on_key_release, dummy)
[ "def", "on_key_release_repeat", "(", "self", ",", "*", "dummy", ")", ":", "self", ".", "has_prev_key_release", "=", "self", ".", "after_idle", "(", "self", ".", "on_key_release", ",", "dummy", ")" ]
Avoid repeated trigger of callback. When holding a key down, multiple key press and release events are fired in succession. Debouncing is implemented to squash these.
[ "Avoid", "repeated", "trigger", "of", "callback", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L192-L199
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
IntegerEntry.set_bind
def set_bind(self): """ Sets key bindings. """ # Arrow keys and enter self.bind('<Up>', lambda e: self.on_key_press_repeat('Up')) self.bind('<Down>', lambda e: self.on_key_press_repeat('Down')) self.bind('<Shift-Up>', lambda e: self.on_key_press_repeat('Shift-Up')) self.bind('<Shift-Down>', lambda e: self.on_key_press_repeat('Shift-Down')) self.bind('<Control-Up>', lambda e: self.on_key_press_repeat('Control-Up')) self.bind('<Control-Down>', lambda e: self.on_key_press_repeat('Control-Down')) self.bind('<KeyRelease>', lambda e: self.on_key_release_repeat()) # Mouse buttons: bit complex since they don't automatically # run in continuous mode like the arrow keys self.bind('<ButtonPress-1>', self._leftMouseDown) self.bind('<ButtonRelease-1>', self._leftMouseUp) self.bind('<Shift-ButtonPress-1>', self._shiftLeftMouseDown) self.bind('<Shift-ButtonRelease-1>', self._shiftLeftMouseUp) self.bind('<Control-Button-1>', lambda e: self.add(100)) self.bind('<ButtonPress-3>', self._rightMouseDown) self.bind('<ButtonRelease-3>', self._rightMouseUp) self.bind('<Shift-ButtonPress-3>', self._shiftRightMouseDown) self.bind('<Shift-ButtonRelease-3>', self._shiftRightMouseUp) self.bind('<Control-Button-3>', lambda e: self.sub(100)) self.bind('<Double-Button-1>', self._dadd1) self.bind('<Double-Button-3>', self._dsub1) self.bind('<Shift-Double-Button-1>', self._dadd10) self.bind('<Shift-Double-Button-3>', self._dsub10) self.bind('<Control-Double-Button-1>', self._dadd100) self.bind('<Control-Double-Button-3>', self._dsub100) self.bind('<Enter>', self._enter)
python
def set_bind(self): """ Sets key bindings. """ # Arrow keys and enter self.bind('<Up>', lambda e: self.on_key_press_repeat('Up')) self.bind('<Down>', lambda e: self.on_key_press_repeat('Down')) self.bind('<Shift-Up>', lambda e: self.on_key_press_repeat('Shift-Up')) self.bind('<Shift-Down>', lambda e: self.on_key_press_repeat('Shift-Down')) self.bind('<Control-Up>', lambda e: self.on_key_press_repeat('Control-Up')) self.bind('<Control-Down>', lambda e: self.on_key_press_repeat('Control-Down')) self.bind('<KeyRelease>', lambda e: self.on_key_release_repeat()) # Mouse buttons: bit complex since they don't automatically # run in continuous mode like the arrow keys self.bind('<ButtonPress-1>', self._leftMouseDown) self.bind('<ButtonRelease-1>', self._leftMouseUp) self.bind('<Shift-ButtonPress-1>', self._shiftLeftMouseDown) self.bind('<Shift-ButtonRelease-1>', self._shiftLeftMouseUp) self.bind('<Control-Button-1>', lambda e: self.add(100)) self.bind('<ButtonPress-3>', self._rightMouseDown) self.bind('<ButtonRelease-3>', self._rightMouseUp) self.bind('<Shift-ButtonPress-3>', self._shiftRightMouseDown) self.bind('<Shift-ButtonRelease-3>', self._shiftRightMouseUp) self.bind('<Control-Button-3>', lambda e: self.sub(100)) self.bind('<Double-Button-1>', self._dadd1) self.bind('<Double-Button-3>', self._dsub1) self.bind('<Shift-Double-Button-1>', self._dadd10) self.bind('<Shift-Double-Button-3>', self._dsub10) self.bind('<Control-Double-Button-1>', self._dadd100) self.bind('<Control-Double-Button-3>', self._dsub100) self.bind('<Enter>', self._enter)
[ "def", "set_bind", "(", "self", ")", ":", "# Arrow keys and enter", "self", ".", "bind", "(", "'<Up>'", ",", "lambda", "e", ":", "self", ".", "on_key_press_repeat", "(", "'Up'", ")", ")", "self", ".", "bind", "(", "'<Down>'", ",", "lambda", "e", ":", "...
Sets key bindings.
[ "Sets", "key", "bindings", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L218-L252
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
IntegerEntry._pollMouse
def _pollMouse(self): """ Polls @10Hz, with a slight delay at the start. """ if self._mouseJustPressed: delay = 300 self._mouseJustPressed = False else: delay = 100 if self._leftMousePressed: self.add(1) self.after_id = self.after(delay, self._pollMouse) if self._shiftLeftMousePressed: self.add(10) self.after_id = self.after(delay, self._pollMouse) if self._rightMousePressed: self.sub(1) self.after_id = self.after(delay, self._pollMouse) if self._shiftRightMousePressed: self.sub(10) self.after_id = self.after(delay, self._pollMouse)
python
def _pollMouse(self): """ Polls @10Hz, with a slight delay at the start. """ if self._mouseJustPressed: delay = 300 self._mouseJustPressed = False else: delay = 100 if self._leftMousePressed: self.add(1) self.after_id = self.after(delay, self._pollMouse) if self._shiftLeftMousePressed: self.add(10) self.after_id = self.after(delay, self._pollMouse) if self._rightMousePressed: self.sub(1) self.after_id = self.after(delay, self._pollMouse) if self._shiftRightMousePressed: self.sub(10) self.after_id = self.after(delay, self._pollMouse)
[ "def", "_pollMouse", "(", "self", ")", ":", "if", "self", ".", "_mouseJustPressed", ":", "delay", "=", "300", "self", ".", "_mouseJustPressed", "=", "False", "else", ":", "delay", "=", "100", "if", "self", ".", "_leftMousePressed", ":", "self", ".", "add...
Polls @10Hz, with a slight delay at the start.
[ "Polls" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L302-L327
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
IntegerEntry._callback
def _callback(self, *dummy): """ This gets called on any attempt to change the value """ # retrieve the value from the Entry value = self._variable.get() # run the validation. Returns None if no good newvalue = self.validate(value) if newvalue is None: # Invalid: restores previously stored value # no checker run. self._variable.set(self._value) elif newvalue != value: # If the value is different update appropriately # Store new value. self._value = newvalue self._variable.set(self.newvalue) else: # Store new value self._value = value
python
def _callback(self, *dummy): """ This gets called on any attempt to change the value """ # retrieve the value from the Entry value = self._variable.get() # run the validation. Returns None if no good newvalue = self.validate(value) if newvalue is None: # Invalid: restores previously stored value # no checker run. self._variable.set(self._value) elif newvalue != value: # If the value is different update appropriately # Store new value. self._value = newvalue self._variable.set(self.newvalue) else: # Store new value self._value = value
[ "def", "_callback", "(", "self", ",", "*", "dummy", ")", ":", "# retrieve the value from the Entry", "value", "=", "self", ".", "_variable", ".", "get", "(", ")", "# run the validation. Returns None if no good", "newvalue", "=", "self", ".", "validate", "(", "valu...
This gets called on any attempt to change the value
[ "This", "gets", "called", "on", "any", "attempt", "to", "change", "the", "value" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L356-L378
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
PosInt.set_bind
def set_bind(self): """ Sets key bindings -- we need this more than once """ IntegerEntry.set_bind(self) self.bind('<Next>', lambda e: self.set(0))
python
def set_bind(self): """ Sets key bindings -- we need this more than once """ IntegerEntry.set_bind(self) self.bind('<Next>', lambda e: self.set(0))
[ "def", "set_bind", "(", "self", ")", ":", "IntegerEntry", ".", "set_bind", "(", "self", ")", "self", ".", "bind", "(", "'<Next>'", ",", "lambda", "e", ":", "self", ".", "set", "(", "0", ")", ")" ]
Sets key bindings -- we need this more than once
[ "Sets", "key", "bindings", "--", "we", "need", "this", "more", "than", "once" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L416-L421
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
PosInt.validate
def validate(self, value): """ Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes. """ try: # trap blank fields here if not self.blank or value: v = int(value) if v < 0: return None return value except ValueError: return None
python
def validate(self, value): """ Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes. """ try: # trap blank fields here if not self.blank or value: v = int(value) if v < 0: return None return value except ValueError: return None
[ "def", "validate", "(", "self", ",", "value", ")", ":", "try", ":", "# trap blank fields here", "if", "not", "self", ".", "blank", "or", "value", ":", "v", "=", "int", "(", "value", ")", "if", "v", "<", "0", ":", "return", "None", "return", "value", ...
Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes.
[ "Applies", "the", "validation", "criteria", ".", "Returns", "value", "new", "value", "or", "None", "if", "invalid", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L430-L445
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
PosInt.add
def add(self, num): """ Adds num to the current value """ try: val = self.value() + num except: val = num self.set(max(0, val))
python
def add(self, num): """ Adds num to the current value """ try: val = self.value() + num except: val = num self.set(max(0, val))
[ "def", "add", "(", "self", ",", "num", ")", ":", "try", ":", "val", "=", "self", ".", "value", "(", ")", "+", "num", "except", ":", "val", "=", "num", "self", ".", "set", "(", "max", "(", "0", ",", "val", ")", ")" ]
Adds num to the current value
[ "Adds", "num", "to", "the", "current", "value" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L447-L455
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
PosInt.sub
def sub(self, num): """ Subtracts num from the current value """ try: val = self.value() - num except: val = -num self.set(max(0, val))
python
def sub(self, num): """ Subtracts num from the current value """ try: val = self.value() - num except: val = -num self.set(max(0, val))
[ "def", "sub", "(", "self", ",", "num", ")", ":", "try", ":", "val", "=", "self", ".", "value", "(", ")", "-", "num", "except", ":", "val", "=", "-", "num", "self", ".", "set", "(", "max", "(", "0", ",", "val", ")", ")" ]
Subtracts num from the current value
[ "Subtracts", "num", "from", "the", "current", "value" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L457-L465
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
PosInt.ok
def ok(self): """ Returns True if OK to use, else False """ try: v = int(self._value) if v < 0: return False else: return True except: return False
python
def ok(self): """ Returns True if OK to use, else False """ try: v = int(self._value) if v < 0: return False else: return True except: return False
[ "def", "ok", "(", "self", ")", ":", "try", ":", "v", "=", "int", "(", "self", ".", "_value", ")", "if", "v", "<", "0", ":", "return", "False", "else", ":", "return", "True", "except", ":", "return", "False" ]
Returns True if OK to use, else False
[ "Returns", "True", "if", "OK", "to", "use", "else", "False" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L467-L478
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
RangedInt.set_bind
def set_bind(self): """ Sets key bindings -- we need this more than once """ IntegerEntry.set_bind(self) self.bind('<Next>', lambda e: self.set(self.imin)) self.bind('<Prior>', lambda e: self.set(self.imax))
python
def set_bind(self): """ Sets key bindings -- we need this more than once """ IntegerEntry.set_bind(self) self.bind('<Next>', lambda e: self.set(self.imin)) self.bind('<Prior>', lambda e: self.set(self.imax))
[ "def", "set_bind", "(", "self", ")", ":", "IntegerEntry", ".", "set_bind", "(", "self", ")", "self", ".", "bind", "(", "'<Next>'", ",", "lambda", "e", ":", "self", ".", "set", "(", "self", ".", "imin", ")", ")", "self", ".", "bind", "(", "'<Prior>'...
Sets key bindings -- we need this more than once
[ "Sets", "key", "bindings", "--", "we", "need", "this", "more", "than", "once" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L504-L510
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
RangedInt.validate
def validate(self, value): """ Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes. """ try: # trap blank fields here if not self.blank or value: v = int(value) if v < self.imin or v > self.imax: return None return value except ValueError: return None
python
def validate(self, value): """ Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes. """ try: # trap blank fields here if not self.blank or value: v = int(value) if v < self.imin or v > self.imax: return None return value except ValueError: return None
[ "def", "validate", "(", "self", ",", "value", ")", ":", "try", ":", "# trap blank fields here", "if", "not", "self", ".", "blank", "or", "value", ":", "v", "=", "int", "(", "value", ")", "if", "v", "<", "self", ".", "imin", "or", "v", ">", "self", ...
Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes.
[ "Applies", "the", "validation", "criteria", ".", "Returns", "value", "new", "value", "or", "None", "if", "invalid", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L520-L535
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
RangedInt.add
def add(self, num): """ Adds num to the current value """ try: val = self.value() + num except: val = num self.set(min(self.imax, max(self.imin, val)))
python
def add(self, num): """ Adds num to the current value """ try: val = self.value() + num except: val = num self.set(min(self.imax, max(self.imin, val)))
[ "def", "add", "(", "self", ",", "num", ")", ":", "try", ":", "val", "=", "self", ".", "value", "(", ")", "+", "num", "except", ":", "val", "=", "num", "self", ".", "set", "(", "min", "(", "self", ".", "imax", ",", "max", "(", "self", ".", "...
Adds num to the current value
[ "Adds", "num", "to", "the", "current", "value" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L537-L545
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
RangedInt.ok
def ok(self): """ Returns True if OK to use, else False """ try: v = int(self._value) if v < self.imin or v > self.imax: return False else: return True except: return False
python
def ok(self): """ Returns True if OK to use, else False """ try: v = int(self._value) if v < self.imin or v > self.imax: return False else: return True except: return False
[ "def", "ok", "(", "self", ")", ":", "try", ":", "v", "=", "int", "(", "self", ".", "_value", ")", "if", "v", "<", "self", ".", "imin", "or", "v", ">", "self", ".", "imax", ":", "return", "False", "else", ":", "return", "True", "except", ":", ...
Returns True if OK to use, else False
[ "Returns", "True", "if", "OK", "to", "use", "else", "False" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L557-L568
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
RangedMint.set_bind
def set_bind(self): """ Sets key bindings -- we need this more than once """ RangedInt.set_bind(self) self.unbind('<Next>') self.unbind('<Prior>') self.bind('<Next>', lambda e: self.set(self._min())) self.bind('<Prior>', lambda e: self.set(self._max()))
python
def set_bind(self): """ Sets key bindings -- we need this more than once """ RangedInt.set_bind(self) self.unbind('<Next>') self.unbind('<Prior>') self.bind('<Next>', lambda e: self.set(self._min())) self.bind('<Prior>', lambda e: self.set(self._max()))
[ "def", "set_bind", "(", "self", ")", ":", "RangedInt", ".", "set_bind", "(", "self", ")", "self", ".", "unbind", "(", "'<Next>'", ")", "self", ".", "unbind", "(", "'<Prior>'", ")", "self", ".", "bind", "(", "'<Next>'", ",", "lambda", "e", ":", "self"...
Sets key bindings -- we need this more than once
[ "Sets", "key", "bindings", "--", "we", "need", "this", "more", "than", "once" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L589-L597
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
RangedMint.add
def add(self, num): """ Adds num to the current value, jumping up the next multiple of mfac if the result is not a multiple already """ try: val = self.value() + num except: val = num chunk = self.mfac.value() if val % chunk > 0: if num > 0: val = chunk*(val // chunk + 1) elif num < 0: val = chunk*(val // chunk) val = max(self._min(), min(self._max(), val)) self.set(val)
python
def add(self, num): """ Adds num to the current value, jumping up the next multiple of mfac if the result is not a multiple already """ try: val = self.value() + num except: val = num chunk = self.mfac.value() if val % chunk > 0: if num > 0: val = chunk*(val // chunk + 1) elif num < 0: val = chunk*(val // chunk) val = max(self._min(), min(self._max(), val)) self.set(val)
[ "def", "add", "(", "self", ",", "num", ")", ":", "try", ":", "val", "=", "self", ".", "value", "(", ")", "+", "num", "except", ":", "val", "=", "num", "chunk", "=", "self", ".", "mfac", ".", "value", "(", ")", "if", "val", "%", "chunk", ">", ...
Adds num to the current value, jumping up the next multiple of mfac if the result is not a multiple already
[ "Adds", "num", "to", "the", "current", "value", "jumping", "up", "the", "next", "multiple", "of", "mfac", "if", "the", "result", "is", "not", "a", "multiple", "already" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L607-L625
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
RangedMint.ok
def ok(self): """ Returns True if OK to use, else False """ try: v = int(self._value) chunk = self.mfac.value() if v < self.imin or v > self.imax or (v % chunk != 0): return False else: return True except: return False
python
def ok(self): """ Returns True if OK to use, else False """ try: v = int(self._value) chunk = self.mfac.value() if v < self.imin or v > self.imax or (v % chunk != 0): return False else: return True except: return False
[ "def", "ok", "(", "self", ")", ":", "try", ":", "v", "=", "int", "(", "self", ".", "_value", ")", "chunk", "=", "self", ".", "mfac", ".", "value", "(", ")", "if", "v", "<", "self", ".", "imin", "or", "v", ">", "self", ".", "imax", "or", "("...
Returns True if OK to use, else False
[ "Returns", "True", "if", "OK", "to", "use", "else", "False" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L647-L659
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
ListInt.set_bind
def set_bind(self): """ Sets key bindings -- we need this more than once """ IntegerEntry.set_bind(self) self.unbind('<Shift-Up>') self.unbind('<Shift-Down>') self.unbind('<Control-Up>') self.unbind('<Control-Down>') self.unbind('<Double-Button-1>') self.unbind('<Double-Button-3>') self.unbind('<Shift-Button-1>') self.unbind('<Shift-Button-3>') self.unbind('<Control-Button-1>') self.unbind('<Control-Button-3>') self.bind('<Button-1>', lambda e: self.add(1)) self.bind('<Button-3>', lambda e: self.sub(1)) self.bind('<Up>', lambda e: self.add(1)) self.bind('<Down>', lambda e: self.sub(1)) self.bind('<Enter>', self._enter) self.bind('<Next>', lambda e: self.set(self.allowed[0])) self.bind('<Prior>', lambda e: self.set(self.allowed[-1]))
python
def set_bind(self): """ Sets key bindings -- we need this more than once """ IntegerEntry.set_bind(self) self.unbind('<Shift-Up>') self.unbind('<Shift-Down>') self.unbind('<Control-Up>') self.unbind('<Control-Down>') self.unbind('<Double-Button-1>') self.unbind('<Double-Button-3>') self.unbind('<Shift-Button-1>') self.unbind('<Shift-Button-3>') self.unbind('<Control-Button-1>') self.unbind('<Control-Button-3>') self.bind('<Button-1>', lambda e: self.add(1)) self.bind('<Button-3>', lambda e: self.sub(1)) self.bind('<Up>', lambda e: self.add(1)) self.bind('<Down>', lambda e: self.sub(1)) self.bind('<Enter>', self._enter) self.bind('<Next>', lambda e: self.set(self.allowed[0])) self.bind('<Prior>', lambda e: self.set(self.allowed[-1]))
[ "def", "set_bind", "(", "self", ")", ":", "IntegerEntry", ".", "set_bind", "(", "self", ")", "self", ".", "unbind", "(", "'<Shift-Up>'", ")", "self", ".", "unbind", "(", "'<Shift-Down>'", ")", "self", ".", "unbind", "(", "'<Control-Up>'", ")", "self", "....
Sets key bindings -- we need this more than once
[ "Sets", "key", "bindings", "--", "we", "need", "this", "more", "than", "once" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L697-L719
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
ListInt.set_unbind
def set_unbind(self): """ Unsets key bindings -- we need this more than once """ IntegerEntry.set_unbind(self) self.unbind('<Button-1>') self.unbind('<Button-3>') self.unbind('<Up>') self.unbind('<Down>') self.unbind('<Enter>') self.unbind('<Next>') self.unbind('<Prior>')
python
def set_unbind(self): """ Unsets key bindings -- we need this more than once """ IntegerEntry.set_unbind(self) self.unbind('<Button-1>') self.unbind('<Button-3>') self.unbind('<Up>') self.unbind('<Down>') self.unbind('<Enter>') self.unbind('<Next>') self.unbind('<Prior>')
[ "def", "set_unbind", "(", "self", ")", ":", "IntegerEntry", ".", "set_unbind", "(", "self", ")", "self", ".", "unbind", "(", "'<Button-1>'", ")", "self", ".", "unbind", "(", "'<Button-3>'", ")", "self", ".", "unbind", "(", "'<Up>'", ")", "self", ".", "...
Unsets key bindings -- we need this more than once
[ "Unsets", "key", "bindings", "--", "we", "need", "this", "more", "than", "once" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L721-L732
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
ListInt.validate
def validate(self, value): """ Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes. """ try: v = int(value) if v not in self.allowed: return None return value except ValueError: return None
python
def validate(self, value): """ Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes. """ try: v = int(value) if v not in self.allowed: return None return value except ValueError: return None
[ "def", "validate", "(", "self", ",", "value", ")", ":", "try", ":", "v", "=", "int", "(", "value", ")", "if", "v", "not", "in", "self", ".", "allowed", ":", "return", "None", "return", "value", "except", "ValueError", ":", "return", "None" ]
Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes.
[ "Applies", "the", "validation", "criteria", ".", "Returns", "value", "new", "value", "or", "None", "if", "invalid", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L734-L747
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
ListInt.set
def set(self, num): """ Sets current value to num """ if self.validate(num) is not None: self.index = self.allowed.index(num) IntegerEntry.set(self, num)
python
def set(self, num): """ Sets current value to num """ if self.validate(num) is not None: self.index = self.allowed.index(num) IntegerEntry.set(self, num)
[ "def", "set", "(", "self", ",", "num", ")", ":", "if", "self", ".", "validate", "(", "num", ")", "is", "not", "None", ":", "self", ".", "index", "=", "self", ".", "allowed", ".", "index", "(", "num", ")", "IntegerEntry", ".", "set", "(", "self", ...
Sets current value to num
[ "Sets", "current", "value", "to", "num" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L749-L755
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
ListInt.add
def add(self, num): """ Adds num to the current value """ self.index = max(0, min(len(self.allowed)-1, self.index+num)) self.set(self.allowed[self.index])
python
def add(self, num): """ Adds num to the current value """ self.index = max(0, min(len(self.allowed)-1, self.index+num)) self.set(self.allowed[self.index])
[ "def", "add", "(", "self", ",", "num", ")", ":", "self", ".", "index", "=", "max", "(", "0", ",", "min", "(", "len", "(", "self", ".", "allowed", ")", "-", "1", ",", "self", ".", "index", "+", "num", ")", ")", "self", ".", "set", "(", "self...
Adds num to the current value
[ "Adds", "num", "to", "the", "current", "value" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L757-L762
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
FloatEntry.validate
def validate(self, value): """ Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes. """ try: # trap blank fields here if not self.blank or value: float(value) return value except ValueError: return None
python
def validate(self, value): """ Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes. """ try: # trap blank fields here if not self.blank or value: float(value) return value except ValueError: return None
[ "def", "validate", "(", "self", ",", "value", ")", ":", "try", ":", "# trap blank fields here", "if", "not", "self", ".", "blank", "or", "value", ":", "float", "(", "value", ")", "return", "value", "except", "ValueError", ":", "return", "None" ]
Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes.
[ "Applies", "the", "validation", "criteria", ".", "Returns", "value", "new", "value", "or", "None", "if", "invalid", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L810-L823
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
FloatEntry.set
def set(self, num): """ Sets the current value equal to num """ self._value = str(round(float(num), self.nplaces)) self._variable.set(self._value)
python
def set(self, num): """ Sets the current value equal to num """ self._value = str(round(float(num), self.nplaces)) self._variable.set(self._value)
[ "def", "set", "(", "self", ",", "num", ")", ":", "self", ".", "_value", "=", "str", "(", "round", "(", "float", "(", "num", ")", ",", "self", ".", "nplaces", ")", ")", "self", ".", "_variable", ".", "set", "(", "self", ".", "_value", ")" ]
Sets the current value equal to num
[ "Sets", "the", "current", "value", "equal", "to", "num" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L834-L839
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
FloatEntry.set_bind
def set_bind(self): """ Sets key bindings. """ self.bind('<Button-1>', lambda e: self.add(0.1)) self.bind('<Button-3>', lambda e: self.sub(0.1)) self.bind('<Up>', lambda e: self.add(0.1)) self.bind('<Down>', lambda e: self.sub(0.1)) self.bind('<Shift-Up>', lambda e: self.add(1)) self.bind('<Shift-Down>', lambda e: self.sub(1)) self.bind('<Control-Up>', lambda e: self.add(10)) self.bind('<Control-Down>', lambda e: self.sub(10)) self.bind('<Double-Button-1>', self._dadd) self.bind('<Double-Button-3>', self._dsub) self.bind('<Shift-Button-1>', lambda e: self.add(1)) self.bind('<Shift-Button-3>', lambda e: self.sub(1)) self.bind('<Control-Button-1>', lambda e: self.add(10)) self.bind('<Control-Button-3>', lambda e: self.sub(10)) self.bind('<Enter>', self._enter)
python
def set_bind(self): """ Sets key bindings. """ self.bind('<Button-1>', lambda e: self.add(0.1)) self.bind('<Button-3>', lambda e: self.sub(0.1)) self.bind('<Up>', lambda e: self.add(0.1)) self.bind('<Down>', lambda e: self.sub(0.1)) self.bind('<Shift-Up>', lambda e: self.add(1)) self.bind('<Shift-Down>', lambda e: self.sub(1)) self.bind('<Control-Up>', lambda e: self.add(10)) self.bind('<Control-Down>', lambda e: self.sub(10)) self.bind('<Double-Button-1>', self._dadd) self.bind('<Double-Button-3>', self._dsub) self.bind('<Shift-Button-1>', lambda e: self.add(1)) self.bind('<Shift-Button-3>', lambda e: self.sub(1)) self.bind('<Control-Button-1>', lambda e: self.add(10)) self.bind('<Control-Button-3>', lambda e: self.sub(10)) self.bind('<Enter>', self._enter)
[ "def", "set_bind", "(", "self", ")", ":", "self", ".", "bind", "(", "'<Button-1>'", ",", "lambda", "e", ":", "self", ".", "add", "(", "0.1", ")", ")", "self", ".", "bind", "(", "'<Button-3>'", ",", "lambda", "e", ":", "self", ".", "sub", "(", "0....
Sets key bindings.
[ "Sets", "key", "bindings", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L879-L897
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
FloatEntry.set_unbind
def set_unbind(self): """ Unsets key bindings. """ self.unbind('<Button-1>') self.unbind('<Button-3>') self.unbind('<Up>') self.unbind('<Down>') self.unbind('<Shift-Up>') self.unbind('<Shift-Down>') self.unbind('<Control-Up>') self.unbind('<Control-Down>') self.unbind('<Double-Button-1>') self.unbind('<Double-Button-3>') self.unbind('<Shift-Button-1>') self.unbind('<Shift-Button-3>') self.unbind('<Control-Button-1>') self.unbind('<Control-Button-3>') self.unbind('<Enter>')
python
def set_unbind(self): """ Unsets key bindings. """ self.unbind('<Button-1>') self.unbind('<Button-3>') self.unbind('<Up>') self.unbind('<Down>') self.unbind('<Shift-Up>') self.unbind('<Shift-Down>') self.unbind('<Control-Up>') self.unbind('<Control-Down>') self.unbind('<Double-Button-1>') self.unbind('<Double-Button-3>') self.unbind('<Shift-Button-1>') self.unbind('<Shift-Button-3>') self.unbind('<Control-Button-1>') self.unbind('<Control-Button-3>') self.unbind('<Enter>')
[ "def", "set_unbind", "(", "self", ")", ":", "self", ".", "unbind", "(", "'<Button-1>'", ")", "self", ".", "unbind", "(", "'<Button-3>'", ")", "self", ".", "unbind", "(", "'<Up>'", ")", "self", ".", "unbind", "(", "'<Down>'", ")", "self", ".", "unbind",...
Unsets key bindings.
[ "Unsets", "key", "bindings", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L899-L917
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
RangedFloat.set_bind
def set_bind(self): """ Sets key bindings -- we need this more than once """ FloatEntry.set_bind(self) self.bind('<Next>', lambda e: self.set(self.fmin)) self.bind('<Prior>', lambda e: self.set(self.fmax))
python
def set_bind(self): """ Sets key bindings -- we need this more than once """ FloatEntry.set_bind(self) self.bind('<Next>', lambda e: self.set(self.fmin)) self.bind('<Prior>', lambda e: self.set(self.fmax))
[ "def", "set_bind", "(", "self", ")", ":", "FloatEntry", ".", "set_bind", "(", "self", ")", "self", ".", "bind", "(", "'<Next>'", ",", "lambda", "e", ":", "self", ".", "set", "(", "self", ".", "fmin", ")", ")", "self", ".", "bind", "(", "'<Prior>'",...
Sets key bindings -- we need this more than once
[ "Sets", "key", "bindings", "--", "we", "need", "this", "more", "than", "once" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L989-L995
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
RangedFloat.validate
def validate(self, value): """ Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes. """ try: # trap blank fields here if not self.blank or value: v = float(value) if (self.allowzero and v != 0 and v < self.fmin) or \ (not self.allowzero and v < self.fmin) or v > self.fmax: return None return value except ValueError: return None
python
def validate(self, value): """ Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes. """ try: # trap blank fields here if not self.blank or value: v = float(value) if (self.allowzero and v != 0 and v < self.fmin) or \ (not self.allowzero and v < self.fmin) or v > self.fmax: return None return value except ValueError: return None
[ "def", "validate", "(", "self", ",", "value", ")", ":", "try", ":", "# trap blank fields here", "if", "not", "self", ".", "blank", "or", "value", ":", "v", "=", "float", "(", "value", ")", "if", "(", "self", ".", "allowzero", "and", "v", "!=", "0", ...
Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes.
[ "Applies", "the", "validation", "criteria", ".", "Returns", "value", "new", "value", "or", "None", "if", "invalid", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1005-L1021
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
RangedFloat.add
def add(self, num): """ Adds num to the current value """ try: val = self.value() + num except: val = num self.set(min(self.fmax, max(self.fmin, val)))
python
def add(self, num): """ Adds num to the current value """ try: val = self.value() + num except: val = num self.set(min(self.fmax, max(self.fmin, val)))
[ "def", "add", "(", "self", ",", "num", ")", ":", "try", ":", "val", "=", "self", ".", "value", "(", ")", "+", "num", "except", ":", "val", "=", "num", "self", ".", "set", "(", "min", "(", "self", ".", "fmax", ",", "max", "(", "self", ".", "...
Adds num to the current value
[ "Adds", "num", "to", "the", "current", "value" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1023-L1031
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
RangedFloat.ok
def ok(self): """ Returns True if OK to use, else False """ try: v = float(self._value) if v < self.fmin or v > self.fmax: return False else: return True except: return False
python
def ok(self): """ Returns True if OK to use, else False """ try: v = float(self._value) if v < self.fmin or v > self.fmax: return False else: return True except: return False
[ "def", "ok", "(", "self", ")", ":", "try", ":", "v", "=", "float", "(", "self", ".", "_value", ")", "if", "v", "<", "self", ".", "fmin", "or", "v", ">", "self", ".", "fmax", ":", "return", "False", "else", ":", "return", "True", "except", ":", ...
Returns True if OK to use, else False
[ "Returns", "True", "if", "OK", "to", "use", "else", "False" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1043-L1054
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Expose.validate
def validate(self, value): """ This prevents setting any value more precise than 0.00001 """ try: # trap blank fields here if value: v = float(value) if (v != 0 and v < self.fmin) or v > self.fmax: return None if abs(round(100000*v)-100000*v) > 1.e-12: return None return value except ValueError: return None
python
def validate(self, value): """ This prevents setting any value more precise than 0.00001 """ try: # trap blank fields here if value: v = float(value) if (v != 0 and v < self.fmin) or v > self.fmax: return None if abs(round(100000*v)-100000*v) > 1.e-12: return None return value except ValueError: return None
[ "def", "validate", "(", "self", ",", "value", ")", ":", "try", ":", "# trap blank fields here", "if", "value", ":", "v", "=", "float", "(", "value", ")", "if", "(", "v", "!=", "0", "and", "v", "<", "self", ".", "fmin", ")", "or", "v", ">", "self"...
This prevents setting any value more precise than 0.00001
[ "This", "prevents", "setting", "any", "value", "more", "precise", "than", "0", ".", "00001" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1177-L1191
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Expose.set_min
def set_min(self, fmin): """ Updates minimum value """ if round(100000*fmin) != 100000*fmin: raise DriverError('utils.widgets.Expose.set_min: ' + 'fmin must be a multiple of 0.00001') self.fmin = fmin self.set(self.fmin)
python
def set_min(self, fmin): """ Updates minimum value """ if round(100000*fmin) != 100000*fmin: raise DriverError('utils.widgets.Expose.set_min: ' + 'fmin must be a multiple of 0.00001') self.fmin = fmin self.set(self.fmin)
[ "def", "set_min", "(", "self", ",", "fmin", ")", ":", "if", "round", "(", "100000", "*", "fmin", ")", "!=", "100000", "*", "fmin", ":", "raise", "DriverError", "(", "'utils.widgets.Expose.set_min: '", "+", "'fmin must be a multiple of 0.00001'", ")", "self", "...
Updates minimum value
[ "Updates", "minimum", "value" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1202-L1210
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
ActButton.disable
def disable(self): """ Disable the button, if in non-expert mode; unset its activity flag come-what-may. """ if not self._expert: self.config(state='disable') self._active = False
python
def disable(self): """ Disable the button, if in non-expert mode; unset its activity flag come-what-may. """ if not self._expert: self.config(state='disable') self._active = False
[ "def", "disable", "(", "self", ")", ":", "if", "not", "self", ".", "_expert", ":", "self", ".", "config", "(", "state", "=", "'disable'", ")", "self", ".", "_active", "=", "False" ]
Disable the button, if in non-expert mode; unset its activity flag come-what-may.
[ "Disable", "the", "button", "if", "in", "non", "-", "expert", "mode", ";", "unset", "its", "activity", "flag", "come", "-", "what", "-", "may", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1445-L1452
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
ActButton.setNonExpert
def setNonExpert(self): """ Turns off 'expert' status whereby to allow a button to be disabled """ self._expert = False if self._active: self.enable() else: self.disable()
python
def setNonExpert(self): """ Turns off 'expert' status whereby to allow a button to be disabled """ self._expert = False if self._active: self.enable() else: self.disable()
[ "def", "setNonExpert", "(", "self", ")", ":", "self", ".", "_expert", "=", "False", "if", "self", ".", "_active", ":", "self", ".", "enable", "(", ")", "else", ":", "self", ".", "disable", "(", ")" ]
Turns off 'expert' status whereby to allow a button to be disabled
[ "Turns", "off", "expert", "status", "whereby", "to", "allow", "a", "button", "to", "be", "disabled" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1462-L1470
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Sexagesimal.validate
def validate(self, value): """ Applies the validation criteria. Returns value, new value, or None if invalid. """ try: coord.Angle(value, unit=self.unit) return value except ValueError: return None
python
def validate(self, value): """ Applies the validation criteria. Returns value, new value, or None if invalid. """ try: coord.Angle(value, unit=self.unit) return value except ValueError: return None
[ "def", "validate", "(", "self", ",", "value", ")", ":", "try", ":", "coord", ".", "Angle", "(", "value", ",", "unit", "=", "self", ".", "unit", ")", "return", "value", "except", "ValueError", ":", "return", "None" ]
Applies the validation criteria. Returns value, new value, or None if invalid.
[ "Applies", "the", "validation", "criteria", ".", "Returns", "value", "new", "value", "or", "None", "if", "invalid", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1527-L1536
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Sexagesimal.set
def set(self, num): """ Sets the current value equal to num """ self._value = coord.Angle(num, unit=u.deg) self._variable.set(self.as_string())
python
def set(self, num): """ Sets the current value equal to num """ self._value = coord.Angle(num, unit=u.deg) self._variable.set(self.as_string())
[ "def", "set", "(", "self", ",", "num", ")", ":", "self", ".", "_value", "=", "coord", ".", "Angle", "(", "num", ",", "unit", "=", "u", ".", "deg", ")", "self", ".", "_variable", ".", "set", "(", "self", ".", "as_string", "(", ")", ")" ]
Sets the current value equal to num
[ "Sets", "the", "current", "value", "equal", "to", "num" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1547-L1552
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Sexagesimal.add
def add(self, quantity): """ Adds an angle to the value """ newvalue = self._value + quantity self.set(newvalue.deg)
python
def add(self, quantity): """ Adds an angle to the value """ newvalue = self._value + quantity self.set(newvalue.deg)
[ "def", "add", "(", "self", ",", "quantity", ")", ":", "newvalue", "=", "self", ".", "_value", "+", "quantity", "self", ".", "set", "(", "newvalue", ".", "deg", ")" ]
Adds an angle to the value
[ "Adds", "an", "angle", "to", "the", "value" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1555-L1560
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Sexagesimal.sub
def sub(self, quantity): """ Subtracts an angle from the value """ newvalue = self._value - quantity self.set(newvalue.deg)
python
def sub(self, quantity): """ Subtracts an angle from the value """ newvalue = self._value - quantity self.set(newvalue.deg)
[ "def", "sub", "(", "self", ",", "quantity", ")", ":", "newvalue", "=", "self", ".", "_value", "-", "quantity", "self", ".", "set", "(", "newvalue", ".", "deg", ")" ]
Subtracts an angle from the value
[ "Subtracts", "an", "angle", "from", "the", "value" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1563-L1568
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Sexagesimal.ok
def ok(self): """ Returns True if OK to use, else False """ try: coord.Angle(self._value, unit=u.deg) return True except ValueError: return False
python
def ok(self): """ Returns True if OK to use, else False """ try: coord.Angle(self._value, unit=u.deg) return True except ValueError: return False
[ "def", "ok", "(", "self", ")", ":", "try", ":", "coord", ".", "Angle", "(", "self", ".", "_value", ",", "unit", "=", "u", ".", "deg", ")", "return", "True", "except", "ValueError", ":", "return", "False" ]
Returns True if OK to use, else False
[ "Returns", "True", "if", "OK", "to", "use", "else", "False" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1570-L1578
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Sexagesimal._callback
def _callback(self, *dummy): """ This gets called on any attempt to change the value """ # retrieve the value from the Entry value = self._variable.get() # run the validation. Returns None if no good newvalue = self.validate(value) if newvalue is None: # Invalid: restores previously stored value # no checker run. self._variable.set(self.as_string()) else: # Store new value self._value = coord.Angle(value, unit=self.unit) if self.checker: self.checker(*dummy)
python
def _callback(self, *dummy): """ This gets called on any attempt to change the value """ # retrieve the value from the Entry value = self._variable.get() # run the validation. Returns None if no good newvalue = self.validate(value) if newvalue is None: # Invalid: restores previously stored value # no checker run. self._variable.set(self.as_string()) else: # Store new value self._value = coord.Angle(value, unit=self.unit) if self.checker: self.checker(*dummy)
[ "def", "_callback", "(", "self", ",", "*", "dummy", ")", ":", "# retrieve the value from the Entry", "value", "=", "self", ".", "_variable", ".", "get", "(", ")", "# run the validation. Returns None if no good", "newvalue", "=", "self", ".", "validate", "(", "valu...
This gets called on any attempt to change the value
[ "This", "gets", "called", "on", "any", "attempt", "to", "change", "the", "value" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1628-L1644
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Stop.act
def act(self): """ Carries out the action associated with Stop button """ g = get_root(self).globals g.clog.debug('Stop pressed') # Stop exposure meter # do this first, so timer doesn't also try to enable idle mode g.info.timer.stop() def stop_in_background(): try: self.stopping = True if execCommand(g, 'abort'): self.stopped_ok = True else: g.clog.warn('Failed to stop run') self.stopped_ok = False self.stopping = False except Exception as err: g.clog.warn('Failed to stop run. Error = ' + str(err)) self.stopping = False self.stopped_ok = False # stopping can take a while during which the GUI freezes so run in # background. t = threading.Thread(target=stop_in_background) t.daemon = True t.start() self.after(500, self.check)
python
def act(self): """ Carries out the action associated with Stop button """ g = get_root(self).globals g.clog.debug('Stop pressed') # Stop exposure meter # do this first, so timer doesn't also try to enable idle mode g.info.timer.stop() def stop_in_background(): try: self.stopping = True if execCommand(g, 'abort'): self.stopped_ok = True else: g.clog.warn('Failed to stop run') self.stopped_ok = False self.stopping = False except Exception as err: g.clog.warn('Failed to stop run. Error = ' + str(err)) self.stopping = False self.stopped_ok = False # stopping can take a while during which the GUI freezes so run in # background. t = threading.Thread(target=stop_in_background) t.daemon = True t.start() self.after(500, self.check)
[ "def", "act", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "g", ".", "clog", ".", "debug", "(", "'Stop pressed'", ")", "# Stop exposure meter", "# do this first, so timer doesn't also try to enable idle mode", "g", ".", "info", ...
Carries out the action associated with Stop button
[ "Carries", "out", "the", "action", "associated", "with", "Stop", "button" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1719-L1749
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Stop.check
def check(self): """ Checks the status of the stop exposure command This is run in background and can take a few seconds """ g = get_root(self).globals if self.stopped_ok: # Exposure stopped OK; modify buttons self.disable() # try and write FITS table before enabling start button, otherwise # a new start will clear table try: insertFITSHDU(g) except Exception as err: g.clog.warn('Could not add FITS Table to run') g.clog.warn(str(err)) g.observe.start.enable() g.setup.powerOn.disable() g.setup.powerOff.enable() # Report that run has stopped g.clog.info('Run stopped') # enable idle mode now run has stopped g.clog.info('Setting chips to idle') idle = {'appdata': {'app': 'Idle'}} try: success = postJSON(g, idle) if not success: raise Exception('postJSON returned false') except Exception as err: g.clog.warn('Failed to enable idle mode') g.clog.warn(str(err)) g.clog.info('Stopping offsets (if running') try: success = stopNodding(g) if not success: raise Exception('Failed to stop dithering: response was false') except Exception as err: g.clog.warn('Failed to stop GTC offset script') g.clog.warn(str(err)) return True elif self.stopping: # Exposure in process of stopping # Disable lots of buttons self.disable() g.observe.start.disable() g.setup.powerOn.disable() g.setup.powerOff.disable() # wait a second before trying again self.after(500, self.check) else: self.enable() g.observe.start.disable() g.setup.powerOn.disable() g.setup.powerOff.disable() # Start exposure meter g.info.timer.start() return False
python
def check(self): """ Checks the status of the stop exposure command This is run in background and can take a few seconds """ g = get_root(self).globals if self.stopped_ok: # Exposure stopped OK; modify buttons self.disable() # try and write FITS table before enabling start button, otherwise # a new start will clear table try: insertFITSHDU(g) except Exception as err: g.clog.warn('Could not add FITS Table to run') g.clog.warn(str(err)) g.observe.start.enable() g.setup.powerOn.disable() g.setup.powerOff.enable() # Report that run has stopped g.clog.info('Run stopped') # enable idle mode now run has stopped g.clog.info('Setting chips to idle') idle = {'appdata': {'app': 'Idle'}} try: success = postJSON(g, idle) if not success: raise Exception('postJSON returned false') except Exception as err: g.clog.warn('Failed to enable idle mode') g.clog.warn(str(err)) g.clog.info('Stopping offsets (if running') try: success = stopNodding(g) if not success: raise Exception('Failed to stop dithering: response was false') except Exception as err: g.clog.warn('Failed to stop GTC offset script') g.clog.warn(str(err)) return True elif self.stopping: # Exposure in process of stopping # Disable lots of buttons self.disable() g.observe.start.disable() g.setup.powerOn.disable() g.setup.powerOff.disable() # wait a second before trying again self.after(500, self.check) else: self.enable() g.observe.start.disable() g.setup.powerOn.disable() g.setup.powerOff.disable() # Start exposure meter g.info.timer.start() return False
[ "def", "check", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "if", "self", ".", "stopped_ok", ":", "# Exposure stopped OK; modify buttons", "self", ".", "disable", "(", ")", "# try and write FITS table before enabling start button, ...
Checks the status of the stop exposure command This is run in background and can take a few seconds
[ "Checks", "the", "status", "of", "the", "stop", "exposure", "command", "This", "is", "run", "in", "background", "and", "can", "take", "a", "few", "seconds" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1751-L1816
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Target.modver
def modver(self, *args): """ Switches colour of verify button """ g = get_root(self).globals if self.ok(): tname = self.val.get() if tname in self.successes: # known to be in simbad self.verify.config(bg=g.COL['start']) elif tname in self.failures: # known not to be in simbad self.verify.config(bg=g.COL['stop']) else: # not known whether in simbad self.verify.config(bg=g.COL['main']) self.verify.config(state='normal') else: self.verify.config(bg=g.COL['main']) self.verify.config(state='disable') if self.callback is not None: self.callback()
python
def modver(self, *args): """ Switches colour of verify button """ g = get_root(self).globals if self.ok(): tname = self.val.get() if tname in self.successes: # known to be in simbad self.verify.config(bg=g.COL['start']) elif tname in self.failures: # known not to be in simbad self.verify.config(bg=g.COL['stop']) else: # not known whether in simbad self.verify.config(bg=g.COL['main']) self.verify.config(state='normal') else: self.verify.config(bg=g.COL['main']) self.verify.config(state='disable') if self.callback is not None: self.callback()
[ "def", "modver", "(", "self", ",", "*", "args", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "if", "self", ".", "ok", "(", ")", ":", "tname", "=", "self", ".", "val", ".", "get", "(", ")", "if", "tname", "in", "self", "."...
Switches colour of verify button
[ "Switches", "colour", "of", "verify", "button" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1940-L1962
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Target.act
def act(self): """ Carries out the action associated with Verify button """ tname = self.val.get() g = get_root(self).globals g.clog.info('Checking ' + tname + ' in simbad') try: ret = checkSimbad(g, tname) if len(ret) == 0: self.verify.config(bg=g.COL['stop']) g.clog.warn('No matches to "' + tname + '" found.') if tname not in self.failures: self.failures.append(tname) elif len(ret) == 1: self.verify.config(bg=g.COL['start']) g.clog.info(tname + ' verified OK in simbad') g.clog.info('Primary simbad name = ' + ret[0]['Name']) if tname not in self.successes: self.successes.append(tname) else: g.clog.warn('More than one match to "' + tname + '" found') self.verify.config(bg=g.COL['stop']) if tname not in self.failures: self.failures.append(tname) except urllib.error.URLError: g.clog.warn('Simbad lookup timed out') except socket.timeout: g.clog.warn('Simbad lookup timed out')
python
def act(self): """ Carries out the action associated with Verify button """ tname = self.val.get() g = get_root(self).globals g.clog.info('Checking ' + tname + ' in simbad') try: ret = checkSimbad(g, tname) if len(ret) == 0: self.verify.config(bg=g.COL['stop']) g.clog.warn('No matches to "' + tname + '" found.') if tname not in self.failures: self.failures.append(tname) elif len(ret) == 1: self.verify.config(bg=g.COL['start']) g.clog.info(tname + ' verified OK in simbad') g.clog.info('Primary simbad name = ' + ret[0]['Name']) if tname not in self.successes: self.successes.append(tname) else: g.clog.warn('More than one match to "' + tname + '" found') self.verify.config(bg=g.COL['stop']) if tname not in self.failures: self.failures.append(tname) except urllib.error.URLError: g.clog.warn('Simbad lookup timed out') except socket.timeout: g.clog.warn('Simbad lookup timed out')
[ "def", "act", "(", "self", ")", ":", "tname", "=", "self", ".", "val", ".", "get", "(", ")", "g", "=", "get_root", "(", "self", ")", ".", "globals", "g", ".", "clog", ".", "info", "(", "'Checking '", "+", "tname", "+", "' in simbad'", ")", "try",...
Carries out the action associated with Verify button
[ "Carries", "out", "the", "action", "associated", "with", "Verify", "button" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L1964-L1992
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
PowerOn.act
def act(self): """ Power on action """ g = get_root(self).globals g.clog.debug('Power on pressed') if execCommand(g, 'online'): g.clog.info('ESO server online') g.cpars['eso_server_online'] = True if not isPoweredOn(g): success = execCommand(g, 'pon') if not success: g.clog.warn('Unable to power on CLDC') return False # change other buttons self.disable() g.observe.start.enable() g.observe.stop.disable() g.setup.powerOff.enable() success = execCommand(g, 'seqStart') if not success: g.clog.warn('Failed to start sequencer after Power On.') try: g.info.run.configure(text='{0:03d}'.format(getRunNumber(g))) except Exception as err: g.clog.warn('Failed to determine run number at start of run') g.clog.warn(str(err)) g.info.run.configure(text='UNDEF') return True else: g.clog.warn('Failed to bring server online') return False
python
def act(self): """ Power on action """ g = get_root(self).globals g.clog.debug('Power on pressed') if execCommand(g, 'online'): g.clog.info('ESO server online') g.cpars['eso_server_online'] = True if not isPoweredOn(g): success = execCommand(g, 'pon') if not success: g.clog.warn('Unable to power on CLDC') return False # change other buttons self.disable() g.observe.start.enable() g.observe.stop.disable() g.setup.powerOff.enable() success = execCommand(g, 'seqStart') if not success: g.clog.warn('Failed to start sequencer after Power On.') try: g.info.run.configure(text='{0:03d}'.format(getRunNumber(g))) except Exception as err: g.clog.warn('Failed to determine run number at start of run') g.clog.warn(str(err)) g.info.run.configure(text='UNDEF') return True else: g.clog.warn('Failed to bring server online') return False
[ "def", "act", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "g", ".", "clog", ".", "debug", "(", "'Power on pressed'", ")", "if", "execCommand", "(", "g", ",", "'online'", ")", ":", "g", ".", "clog", ".", "info", ...
Power on action
[ "Power", "on", "action" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L2262-L2298
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
InstSetup.setExpertLevel
def setExpertLevel(self): """ Set expert level """ g = get_root(self).globals level = g.cpars['expert_level'] # first define which buttons are visible if level == 0: # simple layout for button in self.all_buttons: button.grid_forget() # then re-grid the two simple ones self.powerOn.grid(row=0, column=0) self.powerOff.grid(row=0, column=1) elif level == 1 or level == 2: # first remove all possible buttons for button in self.all_buttons: button.grid_forget() # restore detailed layout self.cldcOn.grid(row=0, column=1) self.cldcOff.grid(row=1, column=1) self.seqStart.grid(row=2, column=1) self.seqStop.grid(row=3, column=1) self.ngcOnline.grid(row=0, column=0) self.ngcOff.grid(row=1, column=0) self.ngcStandby.grid(row=2, column=0) self.ngcReset.grid(row=3, column=0) # now set whether buttons are permanently enabled or not if level == 0 or level == 1: for button in self.all_buttons: button.setNonExpert() elif level == 2: for button in self.all_buttons: button.setExpert()
python
def setExpertLevel(self): """ Set expert level """ g = get_root(self).globals level = g.cpars['expert_level'] # first define which buttons are visible if level == 0: # simple layout for button in self.all_buttons: button.grid_forget() # then re-grid the two simple ones self.powerOn.grid(row=0, column=0) self.powerOff.grid(row=0, column=1) elif level == 1 or level == 2: # first remove all possible buttons for button in self.all_buttons: button.grid_forget() # restore detailed layout self.cldcOn.grid(row=0, column=1) self.cldcOff.grid(row=1, column=1) self.seqStart.grid(row=2, column=1) self.seqStop.grid(row=3, column=1) self.ngcOnline.grid(row=0, column=0) self.ngcOff.grid(row=1, column=0) self.ngcStandby.grid(row=2, column=0) self.ngcReset.grid(row=3, column=0) # now set whether buttons are permanently enabled or not if level == 0 or level == 1: for button in self.all_buttons: button.setNonExpert() elif level == 2: for button in self.all_buttons: button.setExpert()
[ "def", "setExpertLevel", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "level", "=", "g", ".", "cpars", "[", "'expert_level'", "]", "# first define which buttons are visible", "if", "level", "==", "0", ":", "# simple layout", ...
Set expert level
[ "Set", "expert", "level" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L2373-L2412
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Switch.setExpertLevel
def setExpertLevel(self): """ Modifies widget according to expertise level, which in this case is just matter of hiding or revealing the button to set CCD temps """ g = get_root(self).globals level = g.cpars['expert_level'] if level == 0: if self.val.get() == 'CCD TECs': self.val.set('Observe') self._changed() self.tecs.grid_forget() else: self.tecs.grid(row=0, column=3, sticky=tk.W)
python
def setExpertLevel(self): """ Modifies widget according to expertise level, which in this case is just matter of hiding or revealing the button to set CCD temps """ g = get_root(self).globals level = g.cpars['expert_level'] if level == 0: if self.val.get() == 'CCD TECs': self.val.set('Observe') self._changed() self.tecs.grid_forget() else: self.tecs.grid(row=0, column=3, sticky=tk.W)
[ "def", "setExpertLevel", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "level", "=", "g", ".", "cpars", "[", "'expert_level'", "]", "if", "level", "==", "0", ":", "if", "self", ".", "val", ".", "get", "(", ")", "=...
Modifies widget according to expertise level, which in this case is just matter of hiding or revealing the button to set CCD temps
[ "Modifies", "widget", "according", "to", "expertise", "level", "which", "in", "this", "case", "is", "just", "matter", "of", "hiding", "or", "revealing", "the", "button", "to", "set", "CCD", "temps" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L2477-L2491
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Timer.start
def start(self): """ Starts the timer from zero """ self.startTime = time.time() self.configure(text='{0:<d} s'.format(0)) self.update()
python
def start(self): """ Starts the timer from zero """ self.startTime = time.time() self.configure(text='{0:<d} s'.format(0)) self.update()
[ "def", "start", "(", "self", ")", ":", "self", ".", "startTime", "=", "time", ".", "time", "(", ")", "self", ".", "configure", "(", "text", "=", "'{0:<d} s'", ".", "format", "(", "0", ")", ")", "self", ".", "update", "(", ")" ]
Starts the timer from zero
[ "Starts", "the", "timer", "from", "zero" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L2580-L2586
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Timer.update
def update(self): """ Updates @ 10Hz to give smooth running clock, checks run status @0.2Hz to reduce load on servers. """ g = get_root(self).globals try: self.count += 1 delta = int(round(time.time() - self.startTime)) self.configure(text='{0:<d} s'.format(delta)) if self.count % 50 == 0: if not isRunActive(g): # try and write FITS table before enabling start button, otherwise # a new start will clear table try: insertFITSHDU(g) except Exception as err: g.clog.warn('Could not add FITS Table to run') g.clog.warn(str(err)) g.observe.start.enable() g.observe.stop.disable() g.setup.ngcReset.enable() g.setup.powerOn.disable() g.setup.powerOff.enable() g.clog.info('Timer detected stopped run') warn_cmd = '/usr/bin/ssh observer@192.168.1.1 spd-say "\'exposure finished\'"' subprocess.check_output(warn_cmd, shell=True, stderr=subprocess.PIPE) # enable idle mode now run has stopped g.clog.info('Setting chips to idle') idle = {'appdata': {'app': 'Idle'}} try: success = postJSON(g, idle) if not success: raise Exception('postJSON returned false') except Exception as err: g.clog.warn('Failed to enable idle mode') g.clog.warn(str(err)) g.clog.info('Stopping offsets (if running') try: success = stopNodding(g) if not success: raise Exception('failed to stop dithering') except Exception as err: g.clog.warn('Failed to stop GTC offset script') g.clog.warn(str(err)) self.stop() return except Exception as err: if self.count % 100 == 0: g.clog.warn('Timer.update: error = ' + str(err)) self.id = self.after(100, self.update)
python
def update(self): """ Updates @ 10Hz to give smooth running clock, checks run status @0.2Hz to reduce load on servers. """ g = get_root(self).globals try: self.count += 1 delta = int(round(time.time() - self.startTime)) self.configure(text='{0:<d} s'.format(delta)) if self.count % 50 == 0: if not isRunActive(g): # try and write FITS table before enabling start button, otherwise # a new start will clear table try: insertFITSHDU(g) except Exception as err: g.clog.warn('Could not add FITS Table to run') g.clog.warn(str(err)) g.observe.start.enable() g.observe.stop.disable() g.setup.ngcReset.enable() g.setup.powerOn.disable() g.setup.powerOff.enable() g.clog.info('Timer detected stopped run') warn_cmd = '/usr/bin/ssh observer@192.168.1.1 spd-say "\'exposure finished\'"' subprocess.check_output(warn_cmd, shell=True, stderr=subprocess.PIPE) # enable idle mode now run has stopped g.clog.info('Setting chips to idle') idle = {'appdata': {'app': 'Idle'}} try: success = postJSON(g, idle) if not success: raise Exception('postJSON returned false') except Exception as err: g.clog.warn('Failed to enable idle mode') g.clog.warn(str(err)) g.clog.info('Stopping offsets (if running') try: success = stopNodding(g) if not success: raise Exception('failed to stop dithering') except Exception as err: g.clog.warn('Failed to stop GTC offset script') g.clog.warn(str(err)) self.stop() return except Exception as err: if self.count % 100 == 0: g.clog.warn('Timer.update: error = ' + str(err)) self.id = self.after(100, self.update)
[ "def", "update", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "try", ":", "self", ".", "count", "+=", "1", "delta", "=", "int", "(", "round", "(", "time", ".", "time", "(", ")", "-", "self", ".", "startTime", "...
Updates @ 10Hz to give smooth running clock, checks run status @0.2Hz to reduce load on servers.
[ "Updates" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L2588-L2647
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
InfoFrame.dumpJSON
def dumpJSON(self): """ Return dictionary of data for FITS headers. """ g = get_root(self).globals return dict( RA=self.ra['text'], DEC=self.dec['text'], tel=g.cpars['telins_name'], alt=self._getVal(self.alt), az=self._getVal(self.az), secz=self._getVal(self.airmass), pa=self._getVal(self.pa), foc=self._getVal(self.focus), mdist=self._getVal(self.mdist) )
python
def dumpJSON(self): """ Return dictionary of data for FITS headers. """ g = get_root(self).globals return dict( RA=self.ra['text'], DEC=self.dec['text'], tel=g.cpars['telins_name'], alt=self._getVal(self.alt), az=self._getVal(self.az), secz=self._getVal(self.airmass), pa=self._getVal(self.pa), foc=self._getVal(self.focus), mdist=self._getVal(self.mdist) )
[ "def", "dumpJSON", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "return", "dict", "(", "RA", "=", "self", ".", "ra", "[", "'text'", "]", ",", "DEC", "=", "self", ".", "dec", "[", "'text'", "]", ",", "tel", "=",...
Return dictionary of data for FITS headers.
[ "Return", "dictionary", "of", "data", "for", "FITS", "headers", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L2751-L2766
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
InfoFrame.update_tcs_table
def update_tcs_table(self): """ Periodically update a table of info from the TCS. Only works at GTC """ g = get_root(self).globals if not g.cpars['tcs_on'] or not g.cpars['telins_name'].lower() == 'gtc': self.after(60000, self.update_tcs_table) return try: tel_server = tcs.get_telescope_server() telpars = tel_server.getTelescopeParams() add_gtc_header_table_row(self.tcs_table, telpars) except Exception as err: g.clog.warn('Could not update table of TCS info') # schedule next call for 60s later self.after(60000, self.update_tcs_table)
python
def update_tcs_table(self): """ Periodically update a table of info from the TCS. Only works at GTC """ g = get_root(self).globals if not g.cpars['tcs_on'] or not g.cpars['telins_name'].lower() == 'gtc': self.after(60000, self.update_tcs_table) return try: tel_server = tcs.get_telescope_server() telpars = tel_server.getTelescopeParams() add_gtc_header_table_row(self.tcs_table, telpars) except Exception as err: g.clog.warn('Could not update table of TCS info') # schedule next call for 60s later self.after(60000, self.update_tcs_table)
[ "def", "update_tcs_table", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "if", "not", "g", ".", "cpars", "[", "'tcs_on'", "]", "or", "not", "g", ".", "cpars", "[", "'telins_name'", "]", ".", "lower", "(", ")", "==",...
Periodically update a table of info from the TCS. Only works at GTC
[ "Periodically", "update", "a", "table", "of", "info", "from", "the", "TCS", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L2774-L2793
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
InfoFrame.update_tcs
def update_tcs(self): """ Periodically update TCS info. A long running process, so run in a thread and fill a queue """ g = get_root(self).globals if not g.cpars['tcs_on']: self.after(20000, self.update_tcs) return if g.cpars['telins_name'] == 'WHT': tcsfunc = tcs.getWhtTcs elif g.cpars['telins_name'] == 'GTC': tcsfunc = tcs.getGtcTcs else: g.clog.debug('TCS error: could not recognise ' + g.cpars['telins_name']) return def tcs_threaded_update(): try: ra, dec, pa, focus = tcsfunc() self.tcs_data_queue.put((ra, dec, pa, focus)) except Exception as err: t, v, tb = sys.exc_info() error = traceback.format_exception_only(t, v)[0].strip() tback = 'TCS Traceback (most recent call last):\n' + \ ''.join(traceback.format_tb(tb)) g.FIFO.put(('TCS', error, tback)) t = threading.Thread(target=tcs_threaded_update) t.start() self.after(20000, self.update_tcs)
python
def update_tcs(self): """ Periodically update TCS info. A long running process, so run in a thread and fill a queue """ g = get_root(self).globals if not g.cpars['tcs_on']: self.after(20000, self.update_tcs) return if g.cpars['telins_name'] == 'WHT': tcsfunc = tcs.getWhtTcs elif g.cpars['telins_name'] == 'GTC': tcsfunc = tcs.getGtcTcs else: g.clog.debug('TCS error: could not recognise ' + g.cpars['telins_name']) return def tcs_threaded_update(): try: ra, dec, pa, focus = tcsfunc() self.tcs_data_queue.put((ra, dec, pa, focus)) except Exception as err: t, v, tb = sys.exc_info() error = traceback.format_exception_only(t, v)[0].strip() tback = 'TCS Traceback (most recent call last):\n' + \ ''.join(traceback.format_tb(tb)) g.FIFO.put(('TCS', error, tback)) t = threading.Thread(target=tcs_threaded_update) t.start() self.after(20000, self.update_tcs)
[ "def", "update_tcs", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "if", "not", "g", ".", "cpars", "[", "'tcs_on'", "]", ":", "self", ".", "after", "(", "20000", ",", "self", ".", "update_tcs", ")", "return", "if", ...
Periodically update TCS info. A long running process, so run in a thread and fill a queue
[ "Periodically", "update", "TCS", "info", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L2795-L2829
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
InfoFrame.update_slidepos
def update_slidepos(self): """ Periodically update the slide position. Also farmed out to a thread to avoid hanging GUI main thread """ g = get_root(self).globals if not g.cpars['focal_plane_slide_on']: self.after(20000, self.update_slidepos) return def slide_threaded_update(): try: (pos_ms, pos_mm, pos_px), msg = g.fpslide.slide.return_position() self.slide_pos_queue.put((pos_ms, pos_mm, pos_px)) except Exception as err: t, v, tb = sys.exc_info() error = traceback.format_exception_only(t, v)[0].strip() tback = 'Slide Traceback (most recent call last):\n' + \ ''.join(traceback.format_tb(tb)) g.FIFO.put(('Slide', error, tback)) t = threading.Thread(target=slide_threaded_update) t.start() self.after(20000, self.update_slidepos)
python
def update_slidepos(self): """ Periodically update the slide position. Also farmed out to a thread to avoid hanging GUI main thread """ g = get_root(self).globals if not g.cpars['focal_plane_slide_on']: self.after(20000, self.update_slidepos) return def slide_threaded_update(): try: (pos_ms, pos_mm, pos_px), msg = g.fpslide.slide.return_position() self.slide_pos_queue.put((pos_ms, pos_mm, pos_px)) except Exception as err: t, v, tb = sys.exc_info() error = traceback.format_exception_only(t, v)[0].strip() tback = 'Slide Traceback (most recent call last):\n' + \ ''.join(traceback.format_tb(tb)) g.FIFO.put(('Slide', error, tback)) t = threading.Thread(target=slide_threaded_update) t.start() self.after(20000, self.update_slidepos)
[ "def", "update_slidepos", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "if", "not", "g", ".", "cpars", "[", "'focal_plane_slide_on'", "]", ":", "self", ".", "after", "(", "20000", ",", "self", ".", "update_slidepos", "...
Periodically update the slide position. Also farmed out to a thread to avoid hanging GUI main thread
[ "Periodically", "update", "the", "slide", "position", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L2831-L2855
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
InfoFrame.update
def update(self): """ Updates run & tel status window. Runs once every 2 seconds. """ g = get_root(self).globals if g.astro is None or g.fpslide is None: self.after(100, self.update) return try: if g.cpars['tcs_on']: try: # Poll TCS for ra,dec etc. ra, dec, pa, focus = self.tcs_data_queue.get(block=False) # format ra, dec as HMS coo = coord.SkyCoord(ra, dec, unit=(u.deg, u.deg)) ratxt = coo.ra.to_string(sep=':', unit=u.hour, precision=0) dectxt = coo.dec.to_string(sep=':', unit=u.deg, alwayssign=True, precision=0) self.ra.configure(text=ratxt) self.dec.configure(text=dectxt) # wrap pa from 0 to 360 pa = coord.Longitude(pa*u.deg) self.pa.configure(text='{0:6.2f}'.format(pa.value)) # set focus self.focus.configure(text='{0:+5.2f}'.format(focus)) # Calculate most of the # stuff that we don't get from the telescope now = Time.now() with warnings.catch_warnings(): warnings.simplefilter('ignore') # ignore astropy deprecation warnings lon = g.astro.obs.longitude lst = now.sidereal_time(kind='mean', longitude=lon) ha = coo.ra.hourangle*u.hourangle - lst hatxt = ha.wrap_at(12*u.hourangle).to_string(sep=':', precision=0) self.ha.configure(text=hatxt) altaz_frame = coord.AltAz(obstime=now, location=g.astro.obs) altaz = coo.transform_to(altaz_frame) self.alt.configure(text='{0:<4.1f}'.format(altaz.alt.value)) self.az.configure(text='{0:<5.1f}'.format(altaz.az.value)) # set airmass self.airmass.configure(text='{0:<4.2f}'.format(altaz.secz)) # distance to the moon. Warn if too close # (configurable) to it. md = coord.get_moon(now, g.astro.obs).separation(coo) self.mdist.configure(text='{0:<7.2f}'.format(md.value)) if md < g.cpars['mdist_warn']*u.deg: self.mdist.configure(bg=g.COL['warn']) else: self.mdist.configure(bg=g.COL['main']) except Empty: # silently do nothing if queue is empty pass except Exception as err: self.ra.configure(text='UNDEF') self.dec.configure(text='UNDEF') self.pa.configure(text='UNDEF') self.ha.configure(text='UNDEF') self.alt.configure(text='UNDEF') self.az.configure(text='UNDEF') self.airmass.configure(text='UNDEF') self.mdist.configure(text='UNDEF') g.clog.warn('TCS error: ' + str(err)) if g.cpars['hcam_server_on'] and \ g.cpars['eso_server_online']: # get run number (set by the 'Start' button') try: # get run number from hipercam server run = getRunNumber(g) self.run.configure(text='{0:03d}'.format(run)) # Find the number of frames in this run try: frame_no = getFrameNumber(g) self.frame.configure(text='{0:04d}'.format(frame_no)) except Exception as err: if err.code == 404: self.frame.configure(text='0') else: g.clog.debug('Error occurred trying to set frame') self.frame.configure(text='UNDEF') except Exception as err: g.clog.debug('Error trying to set run: ' + str(err)) # get the slide position # poll at 5x slower rate than the frame if self.count % 5 == 0 and g.cpars['focal_plane_slide_on']: try: pos_ms, pos_mm, pos_px = self.slide_pos_queue.get(block=False) self.fpslide.configure(text='{0:d}'.format( int(round(pos_px)))) if pos_px < 1050.: self.fpslide.configure(bg=g.COL['warn']) else: self.fpslide.configure(bg=g.COL['main']) except Exception as err: pass # get the CCD temperature poll at 5x slower rate than the frame if self.count % 5 == 0: try: if g.ccd_hw is not None and g.ccd_hw.ok: self.ccd_temps.configure(text='OK') self.ccd_temps.configure(bg=g.COL['main']) else: self.ccd_temps.configure(text='ERR') self.ccd_temps.configure(bg=g.COL['warn']) except Exception as err: g.clog.warn(str(err)) self.ccd_temps.configure(text='UNDEF') self.ccd_temps.configure(bg=g.COL['warn']) except Exception as err: # this is a safety catchall trap as it is important # that this routine keeps going g.clog.warn('Unexpected error: ' + str(err)) # run every 2 seconds self.count += 1 self.after(2000, self.update)
python
def update(self): """ Updates run & tel status window. Runs once every 2 seconds. """ g = get_root(self).globals if g.astro is None or g.fpslide is None: self.after(100, self.update) return try: if g.cpars['tcs_on']: try: # Poll TCS for ra,dec etc. ra, dec, pa, focus = self.tcs_data_queue.get(block=False) # format ra, dec as HMS coo = coord.SkyCoord(ra, dec, unit=(u.deg, u.deg)) ratxt = coo.ra.to_string(sep=':', unit=u.hour, precision=0) dectxt = coo.dec.to_string(sep=':', unit=u.deg, alwayssign=True, precision=0) self.ra.configure(text=ratxt) self.dec.configure(text=dectxt) # wrap pa from 0 to 360 pa = coord.Longitude(pa*u.deg) self.pa.configure(text='{0:6.2f}'.format(pa.value)) # set focus self.focus.configure(text='{0:+5.2f}'.format(focus)) # Calculate most of the # stuff that we don't get from the telescope now = Time.now() with warnings.catch_warnings(): warnings.simplefilter('ignore') # ignore astropy deprecation warnings lon = g.astro.obs.longitude lst = now.sidereal_time(kind='mean', longitude=lon) ha = coo.ra.hourangle*u.hourangle - lst hatxt = ha.wrap_at(12*u.hourangle).to_string(sep=':', precision=0) self.ha.configure(text=hatxt) altaz_frame = coord.AltAz(obstime=now, location=g.astro.obs) altaz = coo.transform_to(altaz_frame) self.alt.configure(text='{0:<4.1f}'.format(altaz.alt.value)) self.az.configure(text='{0:<5.1f}'.format(altaz.az.value)) # set airmass self.airmass.configure(text='{0:<4.2f}'.format(altaz.secz)) # distance to the moon. Warn if too close # (configurable) to it. md = coord.get_moon(now, g.astro.obs).separation(coo) self.mdist.configure(text='{0:<7.2f}'.format(md.value)) if md < g.cpars['mdist_warn']*u.deg: self.mdist.configure(bg=g.COL['warn']) else: self.mdist.configure(bg=g.COL['main']) except Empty: # silently do nothing if queue is empty pass except Exception as err: self.ra.configure(text='UNDEF') self.dec.configure(text='UNDEF') self.pa.configure(text='UNDEF') self.ha.configure(text='UNDEF') self.alt.configure(text='UNDEF') self.az.configure(text='UNDEF') self.airmass.configure(text='UNDEF') self.mdist.configure(text='UNDEF') g.clog.warn('TCS error: ' + str(err)) if g.cpars['hcam_server_on'] and \ g.cpars['eso_server_online']: # get run number (set by the 'Start' button') try: # get run number from hipercam server run = getRunNumber(g) self.run.configure(text='{0:03d}'.format(run)) # Find the number of frames in this run try: frame_no = getFrameNumber(g) self.frame.configure(text='{0:04d}'.format(frame_no)) except Exception as err: if err.code == 404: self.frame.configure(text='0') else: g.clog.debug('Error occurred trying to set frame') self.frame.configure(text='UNDEF') except Exception as err: g.clog.debug('Error trying to set run: ' + str(err)) # get the slide position # poll at 5x slower rate than the frame if self.count % 5 == 0 and g.cpars['focal_plane_slide_on']: try: pos_ms, pos_mm, pos_px = self.slide_pos_queue.get(block=False) self.fpslide.configure(text='{0:d}'.format( int(round(pos_px)))) if pos_px < 1050.: self.fpslide.configure(bg=g.COL['warn']) else: self.fpslide.configure(bg=g.COL['main']) except Exception as err: pass # get the CCD temperature poll at 5x slower rate than the frame if self.count % 5 == 0: try: if g.ccd_hw is not None and g.ccd_hw.ok: self.ccd_temps.configure(text='OK') self.ccd_temps.configure(bg=g.COL['main']) else: self.ccd_temps.configure(text='ERR') self.ccd_temps.configure(bg=g.COL['warn']) except Exception as err: g.clog.warn(str(err)) self.ccd_temps.configure(text='UNDEF') self.ccd_temps.configure(bg=g.COL['warn']) except Exception as err: # this is a safety catchall trap as it is important # that this routine keeps going g.clog.warn('Unexpected error: ' + str(err)) # run every 2 seconds self.count += 1 self.after(2000, self.update)
[ "def", "update", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "if", "g", ".", "astro", "is", "None", "or", "g", ".", "fpslide", "is", "None", ":", "self", ".", "after", "(", "100", ",", "self", ".", "update", "...
Updates run & tel status window. Runs once every 2 seconds.
[ "Updates", "run", "&", "tel", "status", "window", ".", "Runs", "once", "every", "2", "seconds", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L2857-L2991
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
AstroFrame.update
def update(self): """ Updates @ 10Hz to give smooth running clock. """ try: # update counter self.counter += 1 g = get_root(self).globals # current time now = Time.now() # configure times self.utc.configure(text=now.datetime.strftime('%H:%M:%S')) self.mjd.configure(text='{0:11.5f}'.format(now.mjd)) with warnings.catch_warnings(): warnings.simplefilter('ignore') # ignore astropy deprecation warnings lon = self.obs.longitude lst = now.sidereal_time(kind='mean', longitude=lon) self.lst.configure(text=lst.to_string(sep=':', precision=0)) if self.counter % 600 == 1: # only re-compute Sun & Moon info once every 600 calls altaz_frame = coord.AltAz(obstime=now, location=self.obs) sun = coord.get_sun(now) sun_aa = sun.transform_to(altaz_frame) moon = coord.get_moon(now, self.obs) moon_aa = moon.transform_to(altaz_frame) elongation = sun.separation(moon) moon_phase_angle = np.arctan2(sun.distance*np.sin(elongation), moon.distance - sun.distance*np.cos(elongation)) moon_phase = (1 + np.cos(moon_phase_angle))/2.0 self.sunalt.configure( text='{0:+03d} deg'.format(int(sun_aa.alt.deg)) ) self.moonra.configure( text=moon.ra.to_string(unit='hour', sep=':', precision=0) ) self.moondec.configure( text=moon.dec.to_string(unit='deg', sep=':', precision=0) ) self.moonalt.configure(text='{0:+03d} deg'.format( int(moon_aa.alt.deg) )) self.moonphase.configure(text='{0:02d} %'.format( int(100.*moon_phase.value) )) if (now > self.lastRiset and now > self.lastAstro): # Only re-compute rise and setting times when necessary, # and only re-compute when both rise/set and astro # twilight times have gone by # For sunrise and set we set the horizon down to match a # standard amount of refraction at the horizon and subtract size of disc horizon = -64*u.arcmin sunset = calc_riseset(now, 'sun', self.obs, 'next', 'setting', horizon) sunrise = calc_riseset(now, 'sun', self.obs, 'next', 'rising', horizon) # Astro twilight: geometric centre at -18 deg horizon = -18*u.deg astroset = calc_riseset(now, 'sun', self.obs, 'next', 'setting', horizon) astrorise = calc_riseset(now, 'sun', self.obs, 'next', 'rising', horizon) if sunrise > sunset: # In the day time we report the upcoming sunset and # end of evening twilight self.lriset.configure(text='Sets:', font=g.DEFAULT_FONT) self.lastRiset = sunset self.lastAstro = astroset elif astrorise > astroset and astrorise < sunrise: # During evening twilight, we report the sunset just # passed and end of evening twilight self.lriset.configure(text='Sets:', font=g.DEFAULT_FONT) horizon = -64*u.arcmin self.lastRiset = calc_riseset(now, 'sun', self.obs, 'previous', 'setting', horizon) self.lastAstro = astroset elif astrorise > astroset and astrorise < sunrise: # During night, report upcoming start of morning # twilight and sunrise self.lriset.configure(text='Rises:', font=g.DEFAULT_FONT) horizon = -64*u.arcmin self.lastRiset = sunrise self.lastAstro = astrorise else: # During morning twilight report start of twilight # just passed and upcoming sunrise self.lriset.configure(text='Rises:', font=g.DEFAULT_FONT) horizon = -18*u.deg self.lastRiset = sunrise self.lastAstro = calc_riseset(now, 'sun', self.obs, 'previous', 'rising', horizon) # Configure the corresponding text fields self.riset.configure( text=self.lastRiset.datetime.strftime("%H:%M:%S") ) self.astro.configure( text=self.lastAstro.datetime.strftime("%H:%M:%S") ) except Exception as err: # catchall g.clog.warn('AstroFrame.update: error = ' + str(err)) # run again after 100 milli-seconds self.after(100, self.update)
python
def update(self): """ Updates @ 10Hz to give smooth running clock. """ try: # update counter self.counter += 1 g = get_root(self).globals # current time now = Time.now() # configure times self.utc.configure(text=now.datetime.strftime('%H:%M:%S')) self.mjd.configure(text='{0:11.5f}'.format(now.mjd)) with warnings.catch_warnings(): warnings.simplefilter('ignore') # ignore astropy deprecation warnings lon = self.obs.longitude lst = now.sidereal_time(kind='mean', longitude=lon) self.lst.configure(text=lst.to_string(sep=':', precision=0)) if self.counter % 600 == 1: # only re-compute Sun & Moon info once every 600 calls altaz_frame = coord.AltAz(obstime=now, location=self.obs) sun = coord.get_sun(now) sun_aa = sun.transform_to(altaz_frame) moon = coord.get_moon(now, self.obs) moon_aa = moon.transform_to(altaz_frame) elongation = sun.separation(moon) moon_phase_angle = np.arctan2(sun.distance*np.sin(elongation), moon.distance - sun.distance*np.cos(elongation)) moon_phase = (1 + np.cos(moon_phase_angle))/2.0 self.sunalt.configure( text='{0:+03d} deg'.format(int(sun_aa.alt.deg)) ) self.moonra.configure( text=moon.ra.to_string(unit='hour', sep=':', precision=0) ) self.moondec.configure( text=moon.dec.to_string(unit='deg', sep=':', precision=0) ) self.moonalt.configure(text='{0:+03d} deg'.format( int(moon_aa.alt.deg) )) self.moonphase.configure(text='{0:02d} %'.format( int(100.*moon_phase.value) )) if (now > self.lastRiset and now > self.lastAstro): # Only re-compute rise and setting times when necessary, # and only re-compute when both rise/set and astro # twilight times have gone by # For sunrise and set we set the horizon down to match a # standard amount of refraction at the horizon and subtract size of disc horizon = -64*u.arcmin sunset = calc_riseset(now, 'sun', self.obs, 'next', 'setting', horizon) sunrise = calc_riseset(now, 'sun', self.obs, 'next', 'rising', horizon) # Astro twilight: geometric centre at -18 deg horizon = -18*u.deg astroset = calc_riseset(now, 'sun', self.obs, 'next', 'setting', horizon) astrorise = calc_riseset(now, 'sun', self.obs, 'next', 'rising', horizon) if sunrise > sunset: # In the day time we report the upcoming sunset and # end of evening twilight self.lriset.configure(text='Sets:', font=g.DEFAULT_FONT) self.lastRiset = sunset self.lastAstro = astroset elif astrorise > astroset and astrorise < sunrise: # During evening twilight, we report the sunset just # passed and end of evening twilight self.lriset.configure(text='Sets:', font=g.DEFAULT_FONT) horizon = -64*u.arcmin self.lastRiset = calc_riseset(now, 'sun', self.obs, 'previous', 'setting', horizon) self.lastAstro = astroset elif astrorise > astroset and astrorise < sunrise: # During night, report upcoming start of morning # twilight and sunrise self.lriset.configure(text='Rises:', font=g.DEFAULT_FONT) horizon = -64*u.arcmin self.lastRiset = sunrise self.lastAstro = astrorise else: # During morning twilight report start of twilight # just passed and upcoming sunrise self.lriset.configure(text='Rises:', font=g.DEFAULT_FONT) horizon = -18*u.deg self.lastRiset = sunrise self.lastAstro = calc_riseset(now, 'sun', self.obs, 'previous', 'rising', horizon) # Configure the corresponding text fields self.riset.configure( text=self.lastRiset.datetime.strftime("%H:%M:%S") ) self.astro.configure( text=self.lastAstro.datetime.strftime("%H:%M:%S") ) except Exception as err: # catchall g.clog.warn('AstroFrame.update: error = ' + str(err)) # run again after 100 milli-seconds self.after(100, self.update)
[ "def", "update", "(", "self", ")", ":", "try", ":", "# update counter", "self", ".", "counter", "+=", "1", "g", "=", "get_root", "(", "self", ")", ".", "globals", "# current time", "now", "=", "Time", ".", "now", "(", ")", "# configure times", "self", ...
Updates @ 10Hz to give smooth running clock.
[ "Updates" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L3081-L3195
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
WinPairs.check
def check(self): """ Checks the values of the window pairs. If any problems are found, it flags them by changing the background colour. Returns (status, synced) status : flag for whether parameters are viable at all synced : flag for whether the windows are synchronised. """ status = True synced = True xbin = self.xbin.value() ybin = self.ybin.value() npair = self.npair.value() g = get_root(self).globals # individual pair checks for xslw, xsrw, ysw, nxw, nyw in zip(self.xsl[:npair], self.xsr[:npair], self.ys[:npair], self.nx[:npair], self.ny[:npair]): xslw.config(bg=g.COL['main']) xsrw.config(bg=g.COL['main']) ysw.config(bg=g.COL['main']) nxw.config(bg=g.COL['main']) nyw.config(bg=g.COL['main']) status = status if xslw.ok() else False status = status if xsrw.ok() else False status = status if ysw.ok() else False status = status if nxw.ok() else False status = status if nyw.ok() else False xsl = xslw.value() xsr = xsrw.value() ys = ysw.value() nx = nxw.value() ny = nyw.value() # Are unbinned dimensions consistent with binning factors? if nx is None or nx % xbin != 0: nxw.config(bg=g.COL['error']) status = False elif (nx // xbin) % 4 != 0: """ The NGC collects pixel data in chunks before transmission. As a result, to avoid loss of data from frames, the binned x-size must be a multiple of 4. """ nxw.config(bg=g.COL['error']) status = False if ny is None or ny % ybin != 0: nyw.config(bg=g.COL['error']) status = False # overlap checks if xsl is None or xsr is None or xsl >= xsr: xsrw.config(bg=g.COL['error']) status = False if xsl is None or xsr is None or nx is None or xsl + nx > xsr: xsrw.config(bg=g.COL['error']) status = False # Are the windows synchronised? This means that they would # be consistent with the pixels generated were the whole CCD # to be binned by the same factors. If relevant values are not # set, we count that as "synced" because the purpose of this is # to enable / disable the sync button and we don't want it to be # enabled just because xs or ys are not set. perform_check = all([param is not None for param in (xsl, xsr, ys, nx, ny)]) if (perform_check and ((xsl - 1) % xbin != 0 or (xsr - 1025) % xbin != 0 or (ys - 1) % ybin != 0)): synced = False # Range checks if xsl is None or nx is None or xsl + nx - 1 > xslw.imax: xslw.config(bg=g.COL['error']) status = False if xsr is None or nx is None or xsr + nx - 1 > xsrw.imax: xsrw.config(bg=g.COL['error']) status = False if ys is None or ny is None or ys + ny - 1 > ysw.imax: ysw.config(bg=g.COL['error']) status = False # Pair overlap checks. Compare one pair with the next one in the # same quadrant (if there is one). Only bother if we have survived # so far, which saves a lot of checks if status: for index in range(npair-2): ys1 = self.ys[index].value() ny1 = self.ny[index].value() ysw2 = self.ys[index+2] ys2 = ysw2.value() if ys1 + ny1 > ys2: ysw2.config(bg=g.COL['error']) status = False if synced: self.sbutt.config(bg=g.COL['main']) self.sbutt.disable() else: if not self.frozen: self.sbutt.enable() self.sbutt.config(bg=g.COL['warn']) return status
python
def check(self): """ Checks the values of the window pairs. If any problems are found, it flags them by changing the background colour. Returns (status, synced) status : flag for whether parameters are viable at all synced : flag for whether the windows are synchronised. """ status = True synced = True xbin = self.xbin.value() ybin = self.ybin.value() npair = self.npair.value() g = get_root(self).globals # individual pair checks for xslw, xsrw, ysw, nxw, nyw in zip(self.xsl[:npair], self.xsr[:npair], self.ys[:npair], self.nx[:npair], self.ny[:npair]): xslw.config(bg=g.COL['main']) xsrw.config(bg=g.COL['main']) ysw.config(bg=g.COL['main']) nxw.config(bg=g.COL['main']) nyw.config(bg=g.COL['main']) status = status if xslw.ok() else False status = status if xsrw.ok() else False status = status if ysw.ok() else False status = status if nxw.ok() else False status = status if nyw.ok() else False xsl = xslw.value() xsr = xsrw.value() ys = ysw.value() nx = nxw.value() ny = nyw.value() # Are unbinned dimensions consistent with binning factors? if nx is None or nx % xbin != 0: nxw.config(bg=g.COL['error']) status = False elif (nx // xbin) % 4 != 0: """ The NGC collects pixel data in chunks before transmission. As a result, to avoid loss of data from frames, the binned x-size must be a multiple of 4. """ nxw.config(bg=g.COL['error']) status = False if ny is None or ny % ybin != 0: nyw.config(bg=g.COL['error']) status = False # overlap checks if xsl is None or xsr is None or xsl >= xsr: xsrw.config(bg=g.COL['error']) status = False if xsl is None or xsr is None or nx is None or xsl + nx > xsr: xsrw.config(bg=g.COL['error']) status = False # Are the windows synchronised? This means that they would # be consistent with the pixels generated were the whole CCD # to be binned by the same factors. If relevant values are not # set, we count that as "synced" because the purpose of this is # to enable / disable the sync button and we don't want it to be # enabled just because xs or ys are not set. perform_check = all([param is not None for param in (xsl, xsr, ys, nx, ny)]) if (perform_check and ((xsl - 1) % xbin != 0 or (xsr - 1025) % xbin != 0 or (ys - 1) % ybin != 0)): synced = False # Range checks if xsl is None or nx is None or xsl + nx - 1 > xslw.imax: xslw.config(bg=g.COL['error']) status = False if xsr is None or nx is None or xsr + nx - 1 > xsrw.imax: xsrw.config(bg=g.COL['error']) status = False if ys is None or ny is None or ys + ny - 1 > ysw.imax: ysw.config(bg=g.COL['error']) status = False # Pair overlap checks. Compare one pair with the next one in the # same quadrant (if there is one). Only bother if we have survived # so far, which saves a lot of checks if status: for index in range(npair-2): ys1 = self.ys[index].value() ny1 = self.ny[index].value() ysw2 = self.ys[index+2] ys2 = ysw2.value() if ys1 + ny1 > ys2: ysw2.config(bg=g.COL['error']) status = False if synced: self.sbutt.config(bg=g.COL['main']) self.sbutt.disable() else: if not self.frozen: self.sbutt.enable() self.sbutt.config(bg=g.COL['warn']) return status
[ "def", "check", "(", "self", ")", ":", "status", "=", "True", "synced", "=", "True", "xbin", "=", "self", ".", "xbin", ".", "value", "(", ")", "ybin", "=", "self", ".", "ybin", ".", "value", "(", ")", "npair", "=", "self", ".", "npair", ".", "v...
Checks the values of the window pairs. If any problems are found, it flags them by changing the background colour. Returns (status, synced) status : flag for whether parameters are viable at all synced : flag for whether the windows are synchronised.
[ "Checks", "the", "values", "of", "the", "window", "pairs", ".", "If", "any", "problems", "are", "found", "it", "flags", "them", "by", "changing", "the", "background", "colour", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L3337-L3449
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
WinPairs.sync
def sync(self): """ Synchronise the settings. This means that the pixel start values are shifted downwards so that they are synchronised with a full-frame binned version. This does nothing if the binning factors == 1. """ # needs some mods for ultracam ?? xbin = self.xbin.value() ybin = self.ybin.value() n = 0 for xsl, xsr, ys, nx, ny in self: if xbin > 1: xsl = xbin*((xsl-1)//xbin)+1 self.xsl[n].set(xsl) xsr = xbin*((xsr-1025)//xbin)+1025 self.xsr[n].set(xsr) if ybin > 1: ys = ybin*((ys-1)//ybin)+1 self.ys[n].set(ys) n += 1 g = get_root(self).globals self.sbutt.config(bg=g.COL['main']) self.sbutt.config(state='disable')
python
def sync(self): """ Synchronise the settings. This means that the pixel start values are shifted downwards so that they are synchronised with a full-frame binned version. This does nothing if the binning factors == 1. """ # needs some mods for ultracam ?? xbin = self.xbin.value() ybin = self.ybin.value() n = 0 for xsl, xsr, ys, nx, ny in self: if xbin > 1: xsl = xbin*((xsl-1)//xbin)+1 self.xsl[n].set(xsl) xsr = xbin*((xsr-1025)//xbin)+1025 self.xsr[n].set(xsr) if ybin > 1: ys = ybin*((ys-1)//ybin)+1 self.ys[n].set(ys) n += 1 g = get_root(self).globals self.sbutt.config(bg=g.COL['main']) self.sbutt.config(state='disable')
[ "def", "sync", "(", "self", ")", ":", "# needs some mods for ultracam ??", "xbin", "=", "self", ".", "xbin", ".", "value", "(", ")", "ybin", "=", "self", ".", "ybin", ".", "value", "(", ")", "n", "=", "0", "for", "xsl", ",", "xsr", ",", "ys", ",", ...
Synchronise the settings. This means that the pixel start values are shifted downwards so that they are synchronised with a full-frame binned version. This does nothing if the binning factors == 1.
[ "Synchronise", "the", "settings", ".", "This", "means", "that", "the", "pixel", "start", "values", "are", "shifted", "downwards", "so", "that", "they", "are", "synchronised", "with", "a", "full", "-", "frame", "binned", "version", ".", "This", "does", "nothi...
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L3451-L3477
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
WinPairs.freeze
def freeze(self): """ Freeze (disable) all settings so they can't be altered """ for xsl, xsr, ys, nx, ny in \ zip(self.xsl, self.xsr, self.ys, self.nx, self.ny): xsl.disable() xsr.disable() ys.disable() nx.disable() ny.disable() self.npair.disable() self.xbin.disable() self.ybin.disable() self.sbutt.disable() self.frozen = True
python
def freeze(self): """ Freeze (disable) all settings so they can't be altered """ for xsl, xsr, ys, nx, ny in \ zip(self.xsl, self.xsr, self.ys, self.nx, self.ny): xsl.disable() xsr.disable() ys.disable() nx.disable() ny.disable() self.npair.disable() self.xbin.disable() self.ybin.disable() self.sbutt.disable() self.frozen = True
[ "def", "freeze", "(", "self", ")", ":", "for", "xsl", ",", "xsr", ",", "ys", ",", "nx", ",", "ny", "in", "zip", "(", "self", ".", "xsl", ",", "self", ".", "xsr", ",", "self", ".", "ys", ",", "self", ".", "nx", ",", "self", ".", "ny", ")", ...
Freeze (disable) all settings so they can't be altered
[ "Freeze", "(", "disable", ")", "all", "settings", "so", "they", "can", "t", "be", "altered" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L3479-L3495
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
WinPairs.disable
def disable(self, everything=False): """ Disable all but possibly not binning, which is needed for FF apps Parameters --------- everything : bool disable binning as well """ self.freeze() if not everything: self.xbin.enable() self.ybin.enable() self.frozen = False
python
def disable(self, everything=False): """ Disable all but possibly not binning, which is needed for FF apps Parameters --------- everything : bool disable binning as well """ self.freeze() if not everything: self.xbin.enable() self.ybin.enable() self.frozen = False
[ "def", "disable", "(", "self", ",", "everything", "=", "False", ")", ":", "self", ".", "freeze", "(", ")", "if", "not", "everything", ":", "self", ".", "xbin", ".", "enable", "(", ")", "self", ".", "ybin", ".", "enable", "(", ")", "self", ".", "f...
Disable all but possibly not binning, which is needed for FF apps Parameters --------- everything : bool disable binning as well
[ "Disable", "all", "but", "possibly", "not", "binning", "which", "is", "needed", "for", "FF", "apps" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L3505-L3518
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
WinPairs.enable
def enable(self): """ Enables WinPair settings """ npair = self.npair.value() for label, xsl, xsr, ys, nx, ny in \ zip(self.label[:npair], self.xsl[:npair], self.xsr[:npair], self.ys[:npair], self.nx[:npair], self.ny[:npair]): label.config(state='normal') xsl.enable() xsr.enable() ys.enable() nx.enable() ny.enable() for label, xsl, xsr, ys, nx, ny in \ zip(self.label[npair:], self.xsl[npair:], self.xsr[npair:], self.ys[npair:], self.nx[npair:], self.ny[npair:]): label.config(state='disable') xsl.disable() xsr.disable() ys.disable() nx.disable() ny.disable() self.npair.enable() self.xbin.enable() self.ybin.enable() self.sbutt.enable()
python
def enable(self): """ Enables WinPair settings """ npair = self.npair.value() for label, xsl, xsr, ys, nx, ny in \ zip(self.label[:npair], self.xsl[:npair], self.xsr[:npair], self.ys[:npair], self.nx[:npair], self.ny[:npair]): label.config(state='normal') xsl.enable() xsr.enable() ys.enable() nx.enable() ny.enable() for label, xsl, xsr, ys, nx, ny in \ zip(self.label[npair:], self.xsl[npair:], self.xsr[npair:], self.ys[npair:], self.nx[npair:], self.ny[npair:]): label.config(state='disable') xsl.disable() xsr.disable() ys.disable() nx.disable() ny.disable() self.npair.enable() self.xbin.enable() self.ybin.enable() self.sbutt.enable()
[ "def", "enable", "(", "self", ")", ":", "npair", "=", "self", ".", "npair", ".", "value", "(", ")", "for", "label", ",", "xsl", ",", "xsr", ",", "ys", ",", "nx", ",", "ny", "in", "zip", "(", "self", ".", "label", "[", ":", "npair", "]", ",", ...
Enables WinPair settings
[ "Enables", "WinPair", "settings" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L3520-L3548
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
WinQuads.check
def check(self): """ Checks the values of the window quads. If any problems are found it flags the offending window by changing the background colour. Returns: status : bool """ status = synced = True xbin = self.xbin.value() ybin = self.ybin.value() nquad = self.nquad.value() g = get_root(self).globals # individual window checks for (xsllw, xsulw, xslrw, xsurw, ysw, nxw, nyw) in zip( self.xsll[:nquad], self.xsul[:nquad], self.xslr[:nquad], self.xsur[:nquad], self.ys[:nquad], self.nx[:nquad], self.ny[:nquad]): all_fields = (xsllw, xsulw, xslrw, xsurw, ysw, nxw, nyw) for field in all_fields: field.config(bg=g.COL['main']) status = status if field.ok() else False xsll = xsllw.value() xsul = xsulw.value() xslr = xslrw.value() xsur = xsurw.value() ys = ysw.value() nx = nxw.value() ny = nyw.value() # Are unbinned dimensions consistent with binning factors? if nx is None or nx % xbin != 0: nxw.config(bg=g.COL['error']) status = False elif (nx // xbin) % 4 != 0: """ The NGC collects pixel data in chunks before transmission. As a result, to avoid loss of data from frames, the binned x-size must be a multiple of 4. """ nxw.config(bg=g.COL['error']) status = False if ny is None or ny % ybin != 0: nyw.config(bg=g.COL['error']) status = False # overlap checks in x direction if xsll is None or xslr is None or xsll >= xslr: xslrw.config(bg=g.COL['error']) status = False if xsul is None or xsur is None or xsul >= xsur: xsurw.config(bg=g.COL['error']) status = False if nx is None or xsll is None or xsll + nx > xslr: xslrw.config(bg=g.COL['error']) status = False if xsul is None or nx is None or xsul + nx > xsur: xsurw.config(bg=g.COL['error']) status = False # Are the windows synchronised? This means that they would # be consistent with the pixels generated were the whole CCD # to be binned by the same factors. If relevant values are not # set, we count that as "synced" because the purpose of this is # to enable / disable the sync button and we don't want it to be # enabled just because xs or ys are not set. perform_check = all([param is not None for param in ( xsll, xslr, ys, nx, ny )]) if (perform_check and ((xsll - 1) % xbin != 0 or (xslr - 1025) % xbin != 0 or (ys - 1) % ybin != 0)): synced = False perform_check = all([param is not None for param in ( xsul, xsur, ys, nx, ny )]) if (perform_check and ((xsul - 1) % xbin != 0 or (xsur - 1025) % xbin != 0 or (ys - 1) % ybin != 0)): synced = False # Range checks rchecks = ((xsll, nx, xsllw), (xslr, nx, xslrw), (xsul, nx, xsulw), (xsur, nx, xsurw), (ys, ny, ysw)) for check in rchecks: val, size, widg = check if val is None or size is None or val + size - 1 > widg.imax: widg.config(bg=g.COL['error']) status = False # Quad overlap checks. Compare one quad with the next one # in the same quadrant if there is one. Only bother if we # have survived so far, which saves a lot of checks. if status: for index in range(nquad-1): ys1 = self.ys[index].value() ny1 = self.ny[index].value() ysw2 = self.ys[index+1] ys2 = ysw2.value() if any([thing is None for thing in (ys1, ny1, ys2)]) or ys1 + ny1 > ys2: ysw2.config(bg=g.COL['error']) status = False if synced: self.sbutt.config(bg=g.COL['main']) self.sbutt.disable() else: if not self.frozen: self.sbutt.enable() self.sbutt.config(bg=g.COL['warn']) return status
python
def check(self): """ Checks the values of the window quads. If any problems are found it flags the offending window by changing the background colour. Returns: status : bool """ status = synced = True xbin = self.xbin.value() ybin = self.ybin.value() nquad = self.nquad.value() g = get_root(self).globals # individual window checks for (xsllw, xsulw, xslrw, xsurw, ysw, nxw, nyw) in zip( self.xsll[:nquad], self.xsul[:nquad], self.xslr[:nquad], self.xsur[:nquad], self.ys[:nquad], self.nx[:nquad], self.ny[:nquad]): all_fields = (xsllw, xsulw, xslrw, xsurw, ysw, nxw, nyw) for field in all_fields: field.config(bg=g.COL['main']) status = status if field.ok() else False xsll = xsllw.value() xsul = xsulw.value() xslr = xslrw.value() xsur = xsurw.value() ys = ysw.value() nx = nxw.value() ny = nyw.value() # Are unbinned dimensions consistent with binning factors? if nx is None or nx % xbin != 0: nxw.config(bg=g.COL['error']) status = False elif (nx // xbin) % 4 != 0: """ The NGC collects pixel data in chunks before transmission. As a result, to avoid loss of data from frames, the binned x-size must be a multiple of 4. """ nxw.config(bg=g.COL['error']) status = False if ny is None or ny % ybin != 0: nyw.config(bg=g.COL['error']) status = False # overlap checks in x direction if xsll is None or xslr is None or xsll >= xslr: xslrw.config(bg=g.COL['error']) status = False if xsul is None or xsur is None or xsul >= xsur: xsurw.config(bg=g.COL['error']) status = False if nx is None or xsll is None or xsll + nx > xslr: xslrw.config(bg=g.COL['error']) status = False if xsul is None or nx is None or xsul + nx > xsur: xsurw.config(bg=g.COL['error']) status = False # Are the windows synchronised? This means that they would # be consistent with the pixels generated were the whole CCD # to be binned by the same factors. If relevant values are not # set, we count that as "synced" because the purpose of this is # to enable / disable the sync button and we don't want it to be # enabled just because xs or ys are not set. perform_check = all([param is not None for param in ( xsll, xslr, ys, nx, ny )]) if (perform_check and ((xsll - 1) % xbin != 0 or (xslr - 1025) % xbin != 0 or (ys - 1) % ybin != 0)): synced = False perform_check = all([param is not None for param in ( xsul, xsur, ys, nx, ny )]) if (perform_check and ((xsul - 1) % xbin != 0 or (xsur - 1025) % xbin != 0 or (ys - 1) % ybin != 0)): synced = False # Range checks rchecks = ((xsll, nx, xsllw), (xslr, nx, xslrw), (xsul, nx, xsulw), (xsur, nx, xsurw), (ys, ny, ysw)) for check in rchecks: val, size, widg = check if val is None or size is None or val + size - 1 > widg.imax: widg.config(bg=g.COL['error']) status = False # Quad overlap checks. Compare one quad with the next one # in the same quadrant if there is one. Only bother if we # have survived so far, which saves a lot of checks. if status: for index in range(nquad-1): ys1 = self.ys[index].value() ny1 = self.ny[index].value() ysw2 = self.ys[index+1] ys2 = ysw2.value() if any([thing is None for thing in (ys1, ny1, ys2)]) or ys1 + ny1 > ys2: ysw2.config(bg=g.COL['error']) status = False if synced: self.sbutt.config(bg=g.COL['main']) self.sbutt.disable() else: if not self.frozen: self.sbutt.enable() self.sbutt.config(bg=g.COL['warn']) return status
[ "def", "check", "(", "self", ")", ":", "status", "=", "synced", "=", "True", "xbin", "=", "self", ".", "xbin", ".", "value", "(", ")", "ybin", "=", "self", ".", "ybin", ".", "value", "(", ")", "nquad", "=", "self", ".", "nquad", ".", "value", "...
Checks the values of the window quads. If any problems are found it flags the offending window by changing the background colour. Returns: status : bool
[ "Checks", "the", "values", "of", "the", "window", "quads", ".", "If", "any", "problems", "are", "found", "it", "flags", "the", "offending", "window", "by", "changing", "the", "background", "colour", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L3720-L3835
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
WinQuads.sync
def sync(self): """ Synchronise the settings. This routine changes the window settings so that the pixel start values are shifted downwards until they are synchronised with a full-frame binned version. This does nothing if the binning factor is 1. """ xbin = self.xbin.value() ybin = self.ybin.value() if xbin == 1 and ybin == 1: self.sbutt.config(state='disable') return for n, (xsll, xsul, xslr, xsur, ys, nx, ny) in enumerate(self): if (xsll-1) % xbin != 0: xsll = xbin * ((xsll-1)//xbin)+1 self.xsll[n].set(xsll) if (xsul-1) % xbin != 0: xsul = xbin * ((xsul-1)//xbin)+1 self.xsul[n].set(xsul) if (xslr-1025) % xbin != 0: xslr = xbin * ((xslr-1025)//xbin)+1025 self.xslr[n].set(xslr) if (xsur-1025) % xbin != 0: xsur = xbin * ((xsur-1025)//xbin)+1025 self.xsur[n].set(xsur) if ybin > 1 and (ys-1) % ybin != 0: ys = ybin*((ys-1)//ybin)+1 self.ys[n].set(ys) self.sbutt.config(bg=g.COL['main']) self.sbutt.config(state='disable')
python
def sync(self): """ Synchronise the settings. This routine changes the window settings so that the pixel start values are shifted downwards until they are synchronised with a full-frame binned version. This does nothing if the binning factor is 1. """ xbin = self.xbin.value() ybin = self.ybin.value() if xbin == 1 and ybin == 1: self.sbutt.config(state='disable') return for n, (xsll, xsul, xslr, xsur, ys, nx, ny) in enumerate(self): if (xsll-1) % xbin != 0: xsll = xbin * ((xsll-1)//xbin)+1 self.xsll[n].set(xsll) if (xsul-1) % xbin != 0: xsul = xbin * ((xsul-1)//xbin)+1 self.xsul[n].set(xsul) if (xslr-1025) % xbin != 0: xslr = xbin * ((xslr-1025)//xbin)+1025 self.xslr[n].set(xslr) if (xsur-1025) % xbin != 0: xsur = xbin * ((xsur-1025)//xbin)+1025 self.xsur[n].set(xsur) if ybin > 1 and (ys-1) % ybin != 0: ys = ybin*((ys-1)//ybin)+1 self.ys[n].set(ys) self.sbutt.config(bg=g.COL['main']) self.sbutt.config(state='disable')
[ "def", "sync", "(", "self", ")", ":", "xbin", "=", "self", ".", "xbin", ".", "value", "(", ")", "ybin", "=", "self", ".", "ybin", ".", "value", "(", ")", "if", "xbin", "==", "1", "and", "ybin", "==", "1", ":", "self", ".", "sbutt", ".", "conf...
Synchronise the settings. This routine changes the window settings so that the pixel start values are shifted downwards until they are synchronised with a full-frame binned version. This does nothing if the binning factor is 1.
[ "Synchronise", "the", "settings", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L3837-L3871
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
WinQuads.freeze
def freeze(self): """ Freeze (disable) all settings """ for fields in zip(self.xsll, self.xsul, self.xslr, self.xsur, self.ys, self.nx, self.ny): for field in fields: field.disable() self.nquad.disable() self.xbin.disable() self.ybin.disable() self.sbutt.disable() self.frozen = True
python
def freeze(self): """ Freeze (disable) all settings """ for fields in zip(self.xsll, self.xsul, self.xslr, self.xsur, self.ys, self.nx, self.ny): for field in fields: field.disable() self.nquad.disable() self.xbin.disable() self.ybin.disable() self.sbutt.disable() self.frozen = True
[ "def", "freeze", "(", "self", ")", ":", "for", "fields", "in", "zip", "(", "self", ".", "xsll", ",", "self", ".", "xsul", ",", "self", ".", "xslr", ",", "self", ".", "xsur", ",", "self", ".", "ys", ",", "self", ".", "nx", ",", "self", ".", "n...
Freeze (disable) all settings
[ "Freeze", "(", "disable", ")", "all", "settings" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L3873-L3885
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
WinQuads.enable
def enable(self): """ Enables WinQuad setting """ nquad = self.nquad.value() for label, xsll, xsul, xslr, xsur, ys, nx, ny in \ zip(self.label[:nquad], self.xsll[:nquad], self.xsul[:nquad], self.xslr[:nquad], self.xsur[:nquad], self.ys[:nquad], self.nx[:nquad], self.ny[:nquad]): label.config(state='normal') for thing in (xsll, xsul, xslr, xsur, ys, nx, ny): thing.enable() for label, xsll, xsul, xslr, xsur, ys, nx, ny in \ zip(self.label[nquad:], self.xsll[nquad:], self.xsul[nquad:], self.xslr[nquad:], self.xsur[nquad:], self.ys[nquad:], self.nx[nquad:], self.ny[nquad:]): label.config(state='disable') for thing in (xsll, xsul, xslr, xsur, ys, nx, ny): thing.disable() self.nquad.enable() self.xbin.enable() self.ybin.enable() self.sbutt.enable()
python
def enable(self): """ Enables WinQuad setting """ nquad = self.nquad.value() for label, xsll, xsul, xslr, xsur, ys, nx, ny in \ zip(self.label[:nquad], self.xsll[:nquad], self.xsul[:nquad], self.xslr[:nquad], self.xsur[:nquad], self.ys[:nquad], self.nx[:nquad], self.ny[:nquad]): label.config(state='normal') for thing in (xsll, xsul, xslr, xsur, ys, nx, ny): thing.enable() for label, xsll, xsul, xslr, xsur, ys, nx, ny in \ zip(self.label[nquad:], self.xsll[nquad:], self.xsul[nquad:], self.xslr[nquad:], self.xsur[nquad:], self.ys[nquad:], self.nx[nquad:], self.ny[nquad:]): label.config(state='disable') for thing in (xsll, xsul, xslr, xsur, ys, nx, ny): thing.disable() self.nquad.enable() self.xbin.enable() self.ybin.enable() self.sbutt.enable()
[ "def", "enable", "(", "self", ")", ":", "nquad", "=", "self", ".", "nquad", ".", "value", "(", ")", "for", "label", ",", "xsll", ",", "xsul", ",", "xslr", ",", "xsur", ",", "ys", ",", "nx", ",", "ny", "in", "zip", "(", "self", ".", "label", "...
Enables WinQuad setting
[ "Enables", "WinQuad", "setting" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L3910-L3934
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Windows.check
def check(self): """ Checks the values of the windows. If any problems are found, it flags them by changing the background colour. Only active windows are checked. Returns status, flag for whether parameters are viable. """ status = True synced = True xbin = self.xbin.value() ybin = self.ybin.value() nwin = self.nwin.value() # individual window checks g = get_root(self).globals for xsw, ysw, nxw, nyw in \ zip(self.xs[:nwin], self.ys[:nwin], self.nx[:nwin], self.ny[:nwin]): xsw.config(bg=g.COL['main']) ysw.config(bg=g.COL['main']) nxw.config(bg=g.COL['main']) nyw.config(bg=g.COL['main']) status = status if xsw.ok() else False status = status if ysw.ok() else False status = status if nxw.ok() else False status = status if nyw.ok() else False xs = xsw.value() ys = ysw.value() nx = nxw.value() ny = nyw.value() # Are unbinned dimensions consistent with binning factors? if nx is None or nx % xbin != 0: nxw.config(bg=g.COL['error']) status = False elif (nx // xbin) % 4 != 0: """ The NGC collects pixel data in chunks before transmission. As a result, to avoid loss of data from frames, the binned x-size must be a multiple of 4. """ nxw.config(bg=g.COL['error']) status = False if ny is None or ny % ybin != 0: nyw.config(bg=g.COL['error']) status = False # Are the windows synchronised? This means that they # would be consistent with the pixels generated were # the whole CCD to be binned by the same factors # If relevant values are not set, we count that as # "synced" because the purpose of this is to enable # / disable the sync button and we don't want it to be # enabled just because xs or ys are not set. if (xs is not None and ys is not None and nx is not None and ny is not None): if (xs < 1025 and ((xs - 1) % xbin != 0 or (ys - 1) % ybin != 0) or ((xs-1025) % xbin != 0 or (ys - 1) % ybin != 0)): synced = False # Range checks if xs is None or nx is None or xs + nx - 1 > xsw.imax: xsw.config(bg=g.COL['error']) status = False if ys is None or ny is None or ys + ny - 1 > ysw.imax: ysw.config(bg=g.COL['error']) status = False # Overlap checks. Compare each window with the next one, requiring # no y overlap and that the second is higher than the first if status: n1 = 0 for ysw1, nyw1 in zip(self.ys[:nwin-1], self.ny[:nwin-1]): ys1 = ysw1.value() ny1 = nyw1.value() n1 += 1 ysw2 = self.ys[n1] ys2 = ysw2.value() if ys2 < ys1 + ny1: ysw2.config(bg=g.COL['error']) status = False if synced: self.sbutt.config(bg=g.COL['main']) self.sbutt.disable() else: if not self.frozen: self.sbutt.enable() self.sbutt.config(bg=g.COL['warn']) return status
python
def check(self): """ Checks the values of the windows. If any problems are found, it flags them by changing the background colour. Only active windows are checked. Returns status, flag for whether parameters are viable. """ status = True synced = True xbin = self.xbin.value() ybin = self.ybin.value() nwin = self.nwin.value() # individual window checks g = get_root(self).globals for xsw, ysw, nxw, nyw in \ zip(self.xs[:nwin], self.ys[:nwin], self.nx[:nwin], self.ny[:nwin]): xsw.config(bg=g.COL['main']) ysw.config(bg=g.COL['main']) nxw.config(bg=g.COL['main']) nyw.config(bg=g.COL['main']) status = status if xsw.ok() else False status = status if ysw.ok() else False status = status if nxw.ok() else False status = status if nyw.ok() else False xs = xsw.value() ys = ysw.value() nx = nxw.value() ny = nyw.value() # Are unbinned dimensions consistent with binning factors? if nx is None or nx % xbin != 0: nxw.config(bg=g.COL['error']) status = False elif (nx // xbin) % 4 != 0: """ The NGC collects pixel data in chunks before transmission. As a result, to avoid loss of data from frames, the binned x-size must be a multiple of 4. """ nxw.config(bg=g.COL['error']) status = False if ny is None or ny % ybin != 0: nyw.config(bg=g.COL['error']) status = False # Are the windows synchronised? This means that they # would be consistent with the pixels generated were # the whole CCD to be binned by the same factors # If relevant values are not set, we count that as # "synced" because the purpose of this is to enable # / disable the sync button and we don't want it to be # enabled just because xs or ys are not set. if (xs is not None and ys is not None and nx is not None and ny is not None): if (xs < 1025 and ((xs - 1) % xbin != 0 or (ys - 1) % ybin != 0) or ((xs-1025) % xbin != 0 or (ys - 1) % ybin != 0)): synced = False # Range checks if xs is None or nx is None or xs + nx - 1 > xsw.imax: xsw.config(bg=g.COL['error']) status = False if ys is None or ny is None or ys + ny - 1 > ysw.imax: ysw.config(bg=g.COL['error']) status = False # Overlap checks. Compare each window with the next one, requiring # no y overlap and that the second is higher than the first if status: n1 = 0 for ysw1, nyw1 in zip(self.ys[:nwin-1], self.ny[:nwin-1]): ys1 = ysw1.value() ny1 = nyw1.value() n1 += 1 ysw2 = self.ys[n1] ys2 = ysw2.value() if ys2 < ys1 + ny1: ysw2.config(bg=g.COL['error']) status = False if synced: self.sbutt.config(bg=g.COL['main']) self.sbutt.disable() else: if not self.frozen: self.sbutt.enable() self.sbutt.config(bg=g.COL['warn']) return status
[ "def", "check", "(", "self", ")", ":", "status", "=", "True", "synced", "=", "True", "xbin", "=", "self", ".", "xbin", ".", "value", "(", ")", "ybin", "=", "self", ".", "ybin", ".", "value", "(", ")", "nwin", "=", "self", ".", "nwin", ".", "val...
Checks the values of the windows. If any problems are found, it flags them by changing the background colour. Only active windows are checked. Returns status, flag for whether parameters are viable.
[ "Checks", "the", "values", "of", "the", "windows", ".", "If", "any", "problems", "are", "found", "it", "flags", "them", "by", "changing", "the", "background", "colour", ".", "Only", "active", "windows", "are", "checked", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L4077-L4177
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Windows.sync
def sync(self, *args): """ Synchronise the settings. This means that the pixel start values are shifted downwards so that they are synchronised with a full-frame binned version. This does nothing if the binning factor == 1 """ xbin = self.xbin.value() ybin = self.ybin.value() n = 0 for xs, ys, nx, ny in self: if xbin > 1 and xs % xbin != 1: if xs < 1025: xs = xbin*((xs-1)//xbin)+1 else: xs = xbin*((xs-1025)//xbin)+1025 self.xs[n].set(xs) if ybin > 1 and ys % ybin != 1: ys = ybin*((ys-1)//ybin)+1 self.ys[n].set(ys) n += 1 self.sbutt.config(bg=g.COL['main']) self.sbutt.config(state='disable')
python
def sync(self, *args): """ Synchronise the settings. This means that the pixel start values are shifted downwards so that they are synchronised with a full-frame binned version. This does nothing if the binning factor == 1 """ xbin = self.xbin.value() ybin = self.ybin.value() n = 0 for xs, ys, nx, ny in self: if xbin > 1 and xs % xbin != 1: if xs < 1025: xs = xbin*((xs-1)//xbin)+1 else: xs = xbin*((xs-1025)//xbin)+1025 self.xs[n].set(xs) if ybin > 1 and ys % ybin != 1: ys = ybin*((ys-1)//ybin)+1 self.ys[n].set(ys) n += 1 self.sbutt.config(bg=g.COL['main']) self.sbutt.config(state='disable')
[ "def", "sync", "(", "self", ",", "*", "args", ")", ":", "xbin", "=", "self", ".", "xbin", ".", "value", "(", ")", "ybin", "=", "self", ".", "ybin", ".", "value", "(", ")", "n", "=", "0", "for", "xs", ",", "ys", ",", "nx", ",", "ny", "in", ...
Synchronise the settings. This means that the pixel start values are shifted downwards so that they are synchronised with a full-frame binned version. This does nothing if the binning factor == 1
[ "Synchronise", "the", "settings", ".", "This", "means", "that", "the", "pixel", "start", "values", "are", "shifted", "downwards", "so", "that", "they", "are", "synchronised", "with", "a", "full", "-", "frame", "binned", "version", ".", "This", "does", "nothi...
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L4179-L4203
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Windows.freeze
def freeze(self): """ Freeze all settings so they can't be altered """ for xs, ys, nx, ny in \ zip(self.xs, self.ys, self.nx, self.ny): xs.disable() ys.disable() nx.disable() ny.disable() self.nwin.disable() self.xbin.disable() self.ybin.disable() self.sbutt.disable() self.frozen = True
python
def freeze(self): """ Freeze all settings so they can't be altered """ for xs, ys, nx, ny in \ zip(self.xs, self.ys, self.nx, self.ny): xs.disable() ys.disable() nx.disable() ny.disable() self.nwin.disable() self.xbin.disable() self.ybin.disable() self.sbutt.disable() self.frozen = True
[ "def", "freeze", "(", "self", ")", ":", "for", "xs", ",", "ys", ",", "nx", ",", "ny", "in", "zip", "(", "self", ".", "xs", ",", "self", ".", "ys", ",", "self", ".", "nx", ",", "self", ".", "ny", ")", ":", "xs", ".", "disable", "(", ")", "...
Freeze all settings so they can't be altered
[ "Freeze", "all", "settings", "so", "they", "can", "t", "be", "altered" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L4205-L4219
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
Windows.enable
def enable(self): """ Enables all settings """ nwin = self.nwin.value() for label, xs, ys, nx, ny in \ zip(self.label[:nwin], self.xs[:nwin], self.ys[:nwin], self.nx[:nwin], self.ny[:nwin]): label.config(state='normal') xs.enable() ys.enable() nx.enable() ny.enable() for label, xs, ys, nx, ny in \ zip(self.label[nwin:], self.xs[nwin:], self.ys[nwin:], self.nx[nwin:], self.ny[nwin:]): label.config(state='disable') xs.disable() ys.disable() nx.disable() ny.disable() self.nwin.enable() self.xbin.enable() self.ybin.enable() self.sbutt.enable()
python
def enable(self): """ Enables all settings """ nwin = self.nwin.value() for label, xs, ys, nx, ny in \ zip(self.label[:nwin], self.xs[:nwin], self.ys[:nwin], self.nx[:nwin], self.ny[:nwin]): label.config(state='normal') xs.enable() ys.enable() nx.enable() ny.enable() for label, xs, ys, nx, ny in \ zip(self.label[nwin:], self.xs[nwin:], self.ys[nwin:], self.nx[nwin:], self.ny[nwin:]): label.config(state='disable') xs.disable() ys.disable() nx.disable() ny.disable() self.nwin.enable() self.xbin.enable() self.ybin.enable() self.sbutt.enable()
[ "def", "enable", "(", "self", ")", ":", "nwin", "=", "self", ".", "nwin", ".", "value", "(", ")", "for", "label", ",", "xs", ",", "ys", ",", "nx", ",", "ny", "in", "zip", "(", "self", ".", "label", "[", ":", "nwin", "]", ",", "self", ".", "...
Enables all settings
[ "Enables", "all", "settings" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L4229-L4255
train
IceflowRE/unidown
unidown/plugin/a_plugin.py
APlugin.check_download
def check_download(self, link_item_dict: Dict[str, LinkItem], folder: Path, log: bool = True) -> Tuple[ Dict[str, LinkItem], Dict[str, LinkItem]]: """ Check if the download of the given dict was successful. No proving if the content of the file is correct too. :param link_item_dict: dict which to check :type link_item_dict: Dict[str, ~unidown.plugin.link_item.LinkItem] :param folder: folder where the downloads are saved :type folder: ~pathlib.Path :param log: if the lost items should be logged :type log: bool :return: succeeded and lost dicts :rtype: Tuple[Dict[str, ~unidown.plugin.link_item.LinkItem], Dict[str, ~unidown.plugin.link_item.LinkItem]] """ succeed = {link: item for link, item in link_item_dict.items() if folder.joinpath(item.name).is_file()} lost = {link: item for link, item in link_item_dict.items() if link not in succeed} if lost and log: for link, item in lost.items(): self.log.error(f"Not downloaded: {self.info.host+link} - {item.name}") return succeed, lost
python
def check_download(self, link_item_dict: Dict[str, LinkItem], folder: Path, log: bool = True) -> Tuple[ Dict[str, LinkItem], Dict[str, LinkItem]]: """ Check if the download of the given dict was successful. No proving if the content of the file is correct too. :param link_item_dict: dict which to check :type link_item_dict: Dict[str, ~unidown.plugin.link_item.LinkItem] :param folder: folder where the downloads are saved :type folder: ~pathlib.Path :param log: if the lost items should be logged :type log: bool :return: succeeded and lost dicts :rtype: Tuple[Dict[str, ~unidown.plugin.link_item.LinkItem], Dict[str, ~unidown.plugin.link_item.LinkItem]] """ succeed = {link: item for link, item in link_item_dict.items() if folder.joinpath(item.name).is_file()} lost = {link: item for link, item in link_item_dict.items() if link not in succeed} if lost and log: for link, item in lost.items(): self.log.error(f"Not downloaded: {self.info.host+link} - {item.name}") return succeed, lost
[ "def", "check_download", "(", "self", ",", "link_item_dict", ":", "Dict", "[", "str", ",", "LinkItem", "]", ",", "folder", ":", "Path", ",", "log", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "Dict", "[", "str", ",", "LinkItem", "]", ",", "D...
Check if the download of the given dict was successful. No proving if the content of the file is correct too. :param link_item_dict: dict which to check :type link_item_dict: Dict[str, ~unidown.plugin.link_item.LinkItem] :param folder: folder where the downloads are saved :type folder: ~pathlib.Path :param log: if the lost items should be logged :type log: bool :return: succeeded and lost dicts :rtype: Tuple[Dict[str, ~unidown.plugin.link_item.LinkItem], Dict[str, ~unidown.plugin.link_item.LinkItem]]
[ "Check", "if", "the", "download", "of", "the", "given", "dict", "was", "successful", ".", "No", "proving", "if", "the", "content", "of", "the", "file", "is", "correct", "too", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/plugin/a_plugin.py#L190-L211
train
IceflowRE/unidown
unidown/plugin/a_plugin.py
APlugin.delete_data
def delete_data(self): """ Delete everything which is related to the plugin. **Do not use if you do not know what you do!** """ self.clean_up() tools.delete_dir_rec(self._download_path) if self._save_state_file.exists(): self._save_state_file.unlink()
python
def delete_data(self): """ Delete everything which is related to the plugin. **Do not use if you do not know what you do!** """ self.clean_up() tools.delete_dir_rec(self._download_path) if self._save_state_file.exists(): self._save_state_file.unlink()
[ "def", "delete_data", "(", "self", ")", ":", "self", ".", "clean_up", "(", ")", "tools", ".", "delete_dir_rec", "(", "self", ".", "_download_path", ")", "if", "self", ".", "_save_state_file", ".", "exists", "(", ")", ":", "self", ".", "_save_state_file", ...
Delete everything which is related to the plugin. **Do not use if you do not know what you do!**
[ "Delete", "everything", "which", "is", "related", "to", "the", "plugin", ".", "**", "Do", "not", "use", "if", "you", "do", "not", "know", "what", "you", "do!", "**" ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/plugin/a_plugin.py#L221-L228
train
IceflowRE/unidown
unidown/plugin/a_plugin.py
APlugin.download_as_file
def download_as_file(self, url: str, folder: Path, name: str, delay: float = 0) -> str: """ Download the given url to the given target folder. :param url: link :type url: str :param folder: target folder :type folder: ~pathlib.Path :param name: target file name :type name: str :param delay: after download wait in seconds :type delay: float :return: url :rtype: str :raises ~urllib3.exceptions.HTTPError: if the connection has an error """ while folder.joinpath(name).exists(): # TODO: handle already existing files self.log.warning('already exists: ' + name) name = name + '_d' with self._downloader.request('GET', url, preload_content=False, retries=urllib3.util.retry.Retry(3)) as reader: if reader.status == 200: with folder.joinpath(name).open(mode='wb') as out_file: out_file.write(reader.data) else: raise HTTPError(f"{url} | {reader.status}") if delay > 0: time.sleep(delay) return url
python
def download_as_file(self, url: str, folder: Path, name: str, delay: float = 0) -> str: """ Download the given url to the given target folder. :param url: link :type url: str :param folder: target folder :type folder: ~pathlib.Path :param name: target file name :type name: str :param delay: after download wait in seconds :type delay: float :return: url :rtype: str :raises ~urllib3.exceptions.HTTPError: if the connection has an error """ while folder.joinpath(name).exists(): # TODO: handle already existing files self.log.warning('already exists: ' + name) name = name + '_d' with self._downloader.request('GET', url, preload_content=False, retries=urllib3.util.retry.Retry(3)) as reader: if reader.status == 200: with folder.joinpath(name).open(mode='wb') as out_file: out_file.write(reader.data) else: raise HTTPError(f"{url} | {reader.status}") if delay > 0: time.sleep(delay) return url
[ "def", "download_as_file", "(", "self", ",", "url", ":", "str", ",", "folder", ":", "Path", ",", "name", ":", "str", ",", "delay", ":", "float", "=", "0", ")", "->", "str", ":", "while", "folder", ".", "joinpath", "(", "name", ")", ".", "exists", ...
Download the given url to the given target folder. :param url: link :type url: str :param folder: target folder :type folder: ~pathlib.Path :param name: target file name :type name: str :param delay: after download wait in seconds :type delay: float :return: url :rtype: str :raises ~urllib3.exceptions.HTTPError: if the connection has an error
[ "Download", "the", "given", "url", "to", "the", "given", "target", "folder", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/plugin/a_plugin.py#L230-L260
train
IceflowRE/unidown
unidown/plugin/a_plugin.py
APlugin.download
def download(self, link_item_dict: Dict[str, LinkItem], folder: Path, desc: str, unit: str, delay: float = 0) -> \ List[str]: """ .. warning:: The parameters may change in future versions. (e.g. change order and accept another host) Download the given LinkItem dict from the plugins host, to the given path. Proceeded with multiple connections :attr:`~unidown.plugin.a_plugin.APlugin._simul_downloads`. After :func:`~unidown.plugin.a_plugin.APlugin.check_download` is recommend. This function don't use an internal `link_item_dict`, `delay` or `folder` directly set in options or instance vars, because it can be used aside of the normal download routine inside the plugin itself for own things. As of this it still needs access to the logger, so a staticmethod is not possible. :param link_item_dict: data which gets downloaded :type link_item_dict: Dict[str, ~unidown.plugin.link_item.LinkItem] :param folder: target download folder :type folder: ~pathlib.Path :param desc: description of the progressbar :type desc: str :param unit: unit of the download, shown in the progressbar :type unit: str :param delay: delay between the downloads in seconds :type delay: float :return: list of urls of downloads without errors :rtype: List[str] """ if 'delay' in self._options: delay = self._options['delay'] # TODO: add other optional host? if not link_item_dict: return [] job_list = [] with ThreadPoolExecutor(max_workers=self._simul_downloads) as executor: for link, item in link_item_dict.items(): job = executor.submit(self.download_as_file, link, folder, item.name, delay) job_list.append(job) pbar = tqdm(as_completed(job_list), total=len(job_list), desc=desc, unit=unit, leave=True, mininterval=1, ncols=100, disable=dynamic_data.DISABLE_TQDM) for _ in pbar: pass download_without_errors = [] for job in job_list: try: download_without_errors.append(job.result()) except HTTPError as ex: self.log.warning("Failed to download: " + str(ex)) # Todo: connection lost handling (check if the connection to the server itself is lost) return download_without_errors
python
def download(self, link_item_dict: Dict[str, LinkItem], folder: Path, desc: str, unit: str, delay: float = 0) -> \ List[str]: """ .. warning:: The parameters may change in future versions. (e.g. change order and accept another host) Download the given LinkItem dict from the plugins host, to the given path. Proceeded with multiple connections :attr:`~unidown.plugin.a_plugin.APlugin._simul_downloads`. After :func:`~unidown.plugin.a_plugin.APlugin.check_download` is recommend. This function don't use an internal `link_item_dict`, `delay` or `folder` directly set in options or instance vars, because it can be used aside of the normal download routine inside the plugin itself for own things. As of this it still needs access to the logger, so a staticmethod is not possible. :param link_item_dict: data which gets downloaded :type link_item_dict: Dict[str, ~unidown.plugin.link_item.LinkItem] :param folder: target download folder :type folder: ~pathlib.Path :param desc: description of the progressbar :type desc: str :param unit: unit of the download, shown in the progressbar :type unit: str :param delay: delay between the downloads in seconds :type delay: float :return: list of urls of downloads without errors :rtype: List[str] """ if 'delay' in self._options: delay = self._options['delay'] # TODO: add other optional host? if not link_item_dict: return [] job_list = [] with ThreadPoolExecutor(max_workers=self._simul_downloads) as executor: for link, item in link_item_dict.items(): job = executor.submit(self.download_as_file, link, folder, item.name, delay) job_list.append(job) pbar = tqdm(as_completed(job_list), total=len(job_list), desc=desc, unit=unit, leave=True, mininterval=1, ncols=100, disable=dynamic_data.DISABLE_TQDM) for _ in pbar: pass download_without_errors = [] for job in job_list: try: download_without_errors.append(job.result()) except HTTPError as ex: self.log.warning("Failed to download: " + str(ex)) # Todo: connection lost handling (check if the connection to the server itself is lost) return download_without_errors
[ "def", "download", "(", "self", ",", "link_item_dict", ":", "Dict", "[", "str", ",", "LinkItem", "]", ",", "folder", ":", "Path", ",", "desc", ":", "str", ",", "unit", ":", "str", ",", "delay", ":", "float", "=", "0", ")", "->", "List", "[", "str...
.. warning:: The parameters may change in future versions. (e.g. change order and accept another host) Download the given LinkItem dict from the plugins host, to the given path. Proceeded with multiple connections :attr:`~unidown.plugin.a_plugin.APlugin._simul_downloads`. After :func:`~unidown.plugin.a_plugin.APlugin.check_download` is recommend. This function don't use an internal `link_item_dict`, `delay` or `folder` directly set in options or instance vars, because it can be used aside of the normal download routine inside the plugin itself for own things. As of this it still needs access to the logger, so a staticmethod is not possible. :param link_item_dict: data which gets downloaded :type link_item_dict: Dict[str, ~unidown.plugin.link_item.LinkItem] :param folder: target download folder :type folder: ~pathlib.Path :param desc: description of the progressbar :type desc: str :param unit: unit of the download, shown in the progressbar :type unit: str :param delay: delay between the downloads in seconds :type delay: float :return: list of urls of downloads without errors :rtype: List[str]
[ "..", "warning", "::" ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/plugin/a_plugin.py#L262-L315
train
IceflowRE/unidown
unidown/plugin/a_plugin.py
APlugin._create_save_state
def _create_save_state(self, link_item_dict: Dict[str, LinkItem]) -> SaveState: """ Create protobuf savestate of the module and the given data. :param link_item_dict: data :type link_item_dict: Dict[str, ~unidown.plugin.link_item.LinkItem] :return: the savestate :rtype: ~unidown.plugin.save_state.SaveState """ return SaveState(dynamic_data.SAVE_STATE_VERSION, self.info, self.last_update, link_item_dict)
python
def _create_save_state(self, link_item_dict: Dict[str, LinkItem]) -> SaveState: """ Create protobuf savestate of the module and the given data. :param link_item_dict: data :type link_item_dict: Dict[str, ~unidown.plugin.link_item.LinkItem] :return: the savestate :rtype: ~unidown.plugin.save_state.SaveState """ return SaveState(dynamic_data.SAVE_STATE_VERSION, self.info, self.last_update, link_item_dict)
[ "def", "_create_save_state", "(", "self", ",", "link_item_dict", ":", "Dict", "[", "str", ",", "LinkItem", "]", ")", "->", "SaveState", ":", "return", "SaveState", "(", "dynamic_data", ".", "SAVE_STATE_VERSION", ",", "self", ".", "info", ",", "self", ".", ...
Create protobuf savestate of the module and the given data. :param link_item_dict: data :type link_item_dict: Dict[str, ~unidown.plugin.link_item.LinkItem] :return: the savestate :rtype: ~unidown.plugin.save_state.SaveState
[ "Create", "protobuf", "savestate", "of", "the", "module", "and", "the", "given", "data", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/plugin/a_plugin.py#L317-L326
train
IceflowRE/unidown
unidown/plugin/a_plugin.py
APlugin.save_save_state
def save_save_state(self, data_dict: Dict[str, LinkItem]): # TODO: add progressbar """ Save meta data about the downloaded things and the plugin to file. :param data_dict: data :type data_dict: Dict[link, ~unidown.plugin.link_item.LinkItem] """ json_data = json_format.MessageToJson(self._create_save_state(data_dict).to_protobuf()) with self._save_state_file.open(mode='w', encoding="utf8") as writer: writer.write(json_data)
python
def save_save_state(self, data_dict: Dict[str, LinkItem]): # TODO: add progressbar """ Save meta data about the downloaded things and the plugin to file. :param data_dict: data :type data_dict: Dict[link, ~unidown.plugin.link_item.LinkItem] """ json_data = json_format.MessageToJson(self._create_save_state(data_dict).to_protobuf()) with self._save_state_file.open(mode='w', encoding="utf8") as writer: writer.write(json_data)
[ "def", "save_save_state", "(", "self", ",", "data_dict", ":", "Dict", "[", "str", ",", "LinkItem", "]", ")", ":", "# TODO: add progressbar", "json_data", "=", "json_format", ".", "MessageToJson", "(", "self", ".", "_create_save_state", "(", "data_dict", ")", "...
Save meta data about the downloaded things and the plugin to file. :param data_dict: data :type data_dict: Dict[link, ~unidown.plugin.link_item.LinkItem]
[ "Save", "meta", "data", "about", "the", "downloaded", "things", "and", "the", "plugin", "to", "file", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/plugin/a_plugin.py#L328-L337
train
IceflowRE/unidown
unidown/plugin/a_plugin.py
APlugin.load_save_state
def load_save_state(self) -> SaveState: """ Load the savestate of the plugin. :return: savestate :rtype: ~unidown.plugin.save_state.SaveState :raises ~unidown.plugin.exceptions.PluginException: broken savestate json :raises ~unidown.plugin.exceptions.PluginException: different savestate versions :raises ~unidown.plugin.exceptions.PluginException: different plugin versions :raises ~unidown.plugin.exceptions.PluginException: different plugin names :raises ~unidown.plugin.exceptions.PluginException: could not parse the protobuf """ if not self._save_state_file.exists(): self.log.info("No savestate file found.") return SaveState(dynamic_data.SAVE_STATE_VERSION, self.info, datetime(1970, 1, 1), {}) savestat_proto = "" with self._save_state_file.open(mode='r', encoding="utf8") as data_file: try: savestat_proto = json_format.Parse(data_file.read(), SaveStateProto(), ignore_unknown_fields=False) except ParseError: raise PluginException( f"Broken savestate json. Please fix or delete (you may lose data in this case) the file: {self._save_state_file}") try: save_state = SaveState.from_protobuf(savestat_proto) except ValueError as ex: raise PluginException(f"Could not parse the protobuf {self._save_state_file}: {ex}") else: del savestat_proto if save_state.version != dynamic_data.SAVE_STATE_VERSION: raise PluginException("Different save state version handling is not implemented yet.") if save_state.plugin_info.version != self.info.version: raise PluginException("Different plugin version handling is not implemented yet.") if save_state.plugin_info.name != self.name: raise PluginException("Save state plugin ({name}) does not match the current ({cur_name}).".format( name=save_state.plugin_info.name, cur_name=self.name)) return save_state
python
def load_save_state(self) -> SaveState: """ Load the savestate of the plugin. :return: savestate :rtype: ~unidown.plugin.save_state.SaveState :raises ~unidown.plugin.exceptions.PluginException: broken savestate json :raises ~unidown.plugin.exceptions.PluginException: different savestate versions :raises ~unidown.plugin.exceptions.PluginException: different plugin versions :raises ~unidown.plugin.exceptions.PluginException: different plugin names :raises ~unidown.plugin.exceptions.PluginException: could not parse the protobuf """ if not self._save_state_file.exists(): self.log.info("No savestate file found.") return SaveState(dynamic_data.SAVE_STATE_VERSION, self.info, datetime(1970, 1, 1), {}) savestat_proto = "" with self._save_state_file.open(mode='r', encoding="utf8") as data_file: try: savestat_proto = json_format.Parse(data_file.read(), SaveStateProto(), ignore_unknown_fields=False) except ParseError: raise PluginException( f"Broken savestate json. Please fix or delete (you may lose data in this case) the file: {self._save_state_file}") try: save_state = SaveState.from_protobuf(savestat_proto) except ValueError as ex: raise PluginException(f"Could not parse the protobuf {self._save_state_file}: {ex}") else: del savestat_proto if save_state.version != dynamic_data.SAVE_STATE_VERSION: raise PluginException("Different save state version handling is not implemented yet.") if save_state.plugin_info.version != self.info.version: raise PluginException("Different plugin version handling is not implemented yet.") if save_state.plugin_info.name != self.name: raise PluginException("Save state plugin ({name}) does not match the current ({cur_name}).".format( name=save_state.plugin_info.name, cur_name=self.name)) return save_state
[ "def", "load_save_state", "(", "self", ")", "->", "SaveState", ":", "if", "not", "self", ".", "_save_state_file", ".", "exists", "(", ")", ":", "self", ".", "log", ".", "info", "(", "\"No savestate file found.\"", ")", "return", "SaveState", "(", "dynamic_da...
Load the savestate of the plugin. :return: savestate :rtype: ~unidown.plugin.save_state.SaveState :raises ~unidown.plugin.exceptions.PluginException: broken savestate json :raises ~unidown.plugin.exceptions.PluginException: different savestate versions :raises ~unidown.plugin.exceptions.PluginException: different plugin versions :raises ~unidown.plugin.exceptions.PluginException: different plugin names :raises ~unidown.plugin.exceptions.PluginException: could not parse the protobuf
[ "Load", "the", "savestate", "of", "the", "plugin", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/plugin/a_plugin.py#L339-L379
train
IceflowRE/unidown
unidown/plugin/a_plugin.py
APlugin.get_updated_data
def get_updated_data(self, old_data: Dict[str, LinkItem]) -> Dict[str, LinkItem]: """ Get links who needs to be downloaded by comparing old and the new data. :param old_data: old data :type old_data: Dict[str, ~unidown.plugin.link_item.LinkItem] :return: data which is newer or dont exist in the old one :rtype: Dict[str, ~unidown.plugin.link_item.LinkItem] """ if not self.download_data: return {} new_link_item_dict = {} for link, link_item in tqdm(self.download_data.items(), desc="Compare with save", unit="item", leave=True, mininterval=1, ncols=100, disable=dynamic_data.DISABLE_TQDM): # TODO: add methode to log lost items, which are in old but not in new # if link in new_link_item_dict: # TODO: is ever false, since its the key of a dict: move to the right place # self.log.warning("Duplicate: " + link + " - " + new_link_item_dict[link] + " : " + link_item) # if the new_data link does not exists in old_data or new_data time is newer if (link not in old_data) or (link_item.time > old_data[link].time): new_link_item_dict[link] = link_item return new_link_item_dict
python
def get_updated_data(self, old_data: Dict[str, LinkItem]) -> Dict[str, LinkItem]: """ Get links who needs to be downloaded by comparing old and the new data. :param old_data: old data :type old_data: Dict[str, ~unidown.plugin.link_item.LinkItem] :return: data which is newer or dont exist in the old one :rtype: Dict[str, ~unidown.plugin.link_item.LinkItem] """ if not self.download_data: return {} new_link_item_dict = {} for link, link_item in tqdm(self.download_data.items(), desc="Compare with save", unit="item", leave=True, mininterval=1, ncols=100, disable=dynamic_data.DISABLE_TQDM): # TODO: add methode to log lost items, which are in old but not in new # if link in new_link_item_dict: # TODO: is ever false, since its the key of a dict: move to the right place # self.log.warning("Duplicate: " + link + " - " + new_link_item_dict[link] + " : " + link_item) # if the new_data link does not exists in old_data or new_data time is newer if (link not in old_data) or (link_item.time > old_data[link].time): new_link_item_dict[link] = link_item return new_link_item_dict
[ "def", "get_updated_data", "(", "self", ",", "old_data", ":", "Dict", "[", "str", ",", "LinkItem", "]", ")", "->", "Dict", "[", "str", ",", "LinkItem", "]", ":", "if", "not", "self", ".", "download_data", ":", "return", "{", "}", "new_link_item_dict", ...
Get links who needs to be downloaded by comparing old and the new data. :param old_data: old data :type old_data: Dict[str, ~unidown.plugin.link_item.LinkItem] :return: data which is newer or dont exist in the old one :rtype: Dict[str, ~unidown.plugin.link_item.LinkItem]
[ "Get", "links", "who", "needs", "to", "be", "downloaded", "by", "comparing", "old", "and", "the", "new", "data", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/plugin/a_plugin.py#L381-L403
train
IceflowRE/unidown
unidown/plugin/a_plugin.py
APlugin.update_dict
def update_dict(self, base: Dict[str, LinkItem], new: Dict[str, LinkItem]): """ Use for updating save state dicts and get the new save state dict. Provides a debug option at info level. Updates the base dict. Basically executes `base.update(new)`. :param base: base dict **gets overridden!** :type base: Dict[str, ~unidown.plugin.link_item.LinkItem] :param new: data which updates the base :type new: Dict[str, ~unidown.plugin.link_item.LinkItem] """ if logging.INFO >= logging.getLevelName(dynamic_data.LOG_LEVEL): # TODO: logging here or outside for link, item in new.items(): if link in base: self.log.info('Actualize item: ' + link + ' | ' + str(base[link]) + ' -> ' + str(item)) base.update(new)
python
def update_dict(self, base: Dict[str, LinkItem], new: Dict[str, LinkItem]): """ Use for updating save state dicts and get the new save state dict. Provides a debug option at info level. Updates the base dict. Basically executes `base.update(new)`. :param base: base dict **gets overridden!** :type base: Dict[str, ~unidown.plugin.link_item.LinkItem] :param new: data which updates the base :type new: Dict[str, ~unidown.plugin.link_item.LinkItem] """ if logging.INFO >= logging.getLevelName(dynamic_data.LOG_LEVEL): # TODO: logging here or outside for link, item in new.items(): if link in base: self.log.info('Actualize item: ' + link + ' | ' + str(base[link]) + ' -> ' + str(item)) base.update(new)
[ "def", "update_dict", "(", "self", ",", "base", ":", "Dict", "[", "str", ",", "LinkItem", "]", ",", "new", ":", "Dict", "[", "str", ",", "LinkItem", "]", ")", ":", "if", "logging", ".", "INFO", ">=", "logging", ".", "getLevelName", "(", "dynamic_data...
Use for updating save state dicts and get the new save state dict. Provides a debug option at info level. Updates the base dict. Basically executes `base.update(new)`. :param base: base dict **gets overridden!** :type base: Dict[str, ~unidown.plugin.link_item.LinkItem] :param new: data which updates the base :type new: Dict[str, ~unidown.plugin.link_item.LinkItem]
[ "Use", "for", "updating", "save", "state", "dicts", "and", "get", "the", "new", "save", "state", "dict", ".", "Provides", "a", "debug", "option", "at", "info", "level", ".", "Updates", "the", "base", "dict", ".", "Basically", "executes", "base", ".", "up...
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/plugin/a_plugin.py#L405-L419
train
IceflowRE/unidown
unidown/plugin/a_plugin.py
APlugin._get_options_dic
def _get_options_dic(self, options: List[str]) -> Dict[str, str]: """ Convert the option list to a dictionary where the key is the option and the value is the related option. Is called in the init. :param options: options given to the plugin. :type options: List[str] :return: dictionary which contains the option key as str related to the option string :rtype Dict[str, str] """ options_dic = {} for option in options: cur_option = option.split("=") if len(cur_option) != 2: self.log.warning(f"'{option}' is not valid and will be ignored.") options_dic[cur_option[0]] = cur_option[1] return options_dic
python
def _get_options_dic(self, options: List[str]) -> Dict[str, str]: """ Convert the option list to a dictionary where the key is the option and the value is the related option. Is called in the init. :param options: options given to the plugin. :type options: List[str] :return: dictionary which contains the option key as str related to the option string :rtype Dict[str, str] """ options_dic = {} for option in options: cur_option = option.split("=") if len(cur_option) != 2: self.log.warning(f"'{option}' is not valid and will be ignored.") options_dic[cur_option[0]] = cur_option[1] return options_dic
[ "def", "_get_options_dic", "(", "self", ",", "options", ":", "List", "[", "str", "]", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "options_dic", "=", "{", "}", "for", "option", "in", "options", ":", "cur_option", "=", "option", ".", "split",...
Convert the option list to a dictionary where the key is the option and the value is the related option. Is called in the init. :param options: options given to the plugin. :type options: List[str] :return: dictionary which contains the option key as str related to the option string :rtype Dict[str, str]
[ "Convert", "the", "option", "list", "to", "a", "dictionary", "where", "the", "key", "is", "the", "option", "and", "the", "value", "is", "the", "related", "option", ".", "Is", "called", "in", "the", "init", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/plugin/a_plugin.py#L421-L437
train
IceflowRE/unidown
unidown/plugin/a_plugin.py
APlugin.get_plugins
def get_plugins() -> Dict[str, pkg_resources.EntryPoint]: """ Get all available plugins for unidown. :return: plugin name list :rtype: Dict[str, ~pkg_resources.EntryPoint] """ return {entry.name: entry for entry in pkg_resources.iter_entry_points('unidown.plugin')}
python
def get_plugins() -> Dict[str, pkg_resources.EntryPoint]: """ Get all available plugins for unidown. :return: plugin name list :rtype: Dict[str, ~pkg_resources.EntryPoint] """ return {entry.name: entry for entry in pkg_resources.iter_entry_points('unidown.plugin')}
[ "def", "get_plugins", "(", ")", "->", "Dict", "[", "str", ",", "pkg_resources", ".", "EntryPoint", "]", ":", "return", "{", "entry", ".", "name", ":", "entry", "for", "entry", "in", "pkg_resources", ".", "iter_entry_points", "(", "'unidown.plugin'", ")", "...
Get all available plugins for unidown. :return: plugin name list :rtype: Dict[str, ~pkg_resources.EntryPoint]
[ "Get", "all", "available", "plugins", "for", "unidown", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/plugin/a_plugin.py#L440-L447
train
HiPERCAM/hcam_widgets
hcam_widgets/astro.py
_equation_of_time
def _equation_of_time(t): """ Find the difference between apparent and mean solar time Parameters ---------- t : `~astropy.time.Time` times (array) Returns ---------- ret1 : `~astropy.units.Quantity` the equation of time """ # Julian centuries since J2000.0 T = (t - Time("J2000")).to(u.year).value / 100 # obliquity of ecliptic (Meeus 1998, eq 22.2) poly_pars = (84381.448, 46.8150, 0.00059, 0.001813) eps = u.Quantity(polyval(T, poly_pars), u.arcsec) y = np.tan(eps/2)**2 # Sun's mean longitude (Meeus 1998, eq 25.2) poly_pars = (280.46646, 36000.76983, 0.0003032) L0 = u.Quantity(polyval(T, poly_pars), u.deg) # Sun's mean anomaly (Meeus 1998, eq 25.3) poly_pars = (357.52911, 35999.05029, 0.0001537) M = u.Quantity(polyval(T, poly_pars), u.deg) # eccentricity of Earth's orbit (Meeus 1998, eq 25.4) poly_pars = (0.016708634, -0.000042037, -0.0000001267) e = polyval(T, poly_pars) # equation of time, radians (Meeus 1998, eq 28.3) eot = (y * np.sin(2*L0) - 2*e*np.sin(M) + 4*e*y*np.sin(M)*np.cos(2*L0) - 0.5*y**2 * np.sin(4*L0) - 5*e**2 * np.sin(2*M)/4) * u.rad return eot.to(u.hourangle)
python
def _equation_of_time(t): """ Find the difference between apparent and mean solar time Parameters ---------- t : `~astropy.time.Time` times (array) Returns ---------- ret1 : `~astropy.units.Quantity` the equation of time """ # Julian centuries since J2000.0 T = (t - Time("J2000")).to(u.year).value / 100 # obliquity of ecliptic (Meeus 1998, eq 22.2) poly_pars = (84381.448, 46.8150, 0.00059, 0.001813) eps = u.Quantity(polyval(T, poly_pars), u.arcsec) y = np.tan(eps/2)**2 # Sun's mean longitude (Meeus 1998, eq 25.2) poly_pars = (280.46646, 36000.76983, 0.0003032) L0 = u.Quantity(polyval(T, poly_pars), u.deg) # Sun's mean anomaly (Meeus 1998, eq 25.3) poly_pars = (357.52911, 35999.05029, 0.0001537) M = u.Quantity(polyval(T, poly_pars), u.deg) # eccentricity of Earth's orbit (Meeus 1998, eq 25.4) poly_pars = (0.016708634, -0.000042037, -0.0000001267) e = polyval(T, poly_pars) # equation of time, radians (Meeus 1998, eq 28.3) eot = (y * np.sin(2*L0) - 2*e*np.sin(M) + 4*e*y*np.sin(M)*np.cos(2*L0) - 0.5*y**2 * np.sin(4*L0) - 5*e**2 * np.sin(2*M)/4) * u.rad return eot.to(u.hourangle)
[ "def", "_equation_of_time", "(", "t", ")", ":", "# Julian centuries since J2000.0", "T", "=", "(", "t", "-", "Time", "(", "\"J2000\"", ")", ")", ".", "to", "(", "u", ".", "year", ")", ".", "value", "/", "100", "# obliquity of ecliptic (Meeus 1998, eq 22.2)", ...
Find the difference between apparent and mean solar time Parameters ---------- t : `~astropy.time.Time` times (array) Returns ---------- ret1 : `~astropy.units.Quantity` the equation of time
[ "Find", "the", "difference", "between", "apparent", "and", "mean", "solar", "time" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/astro.py#L15-L53
train
HiPERCAM/hcam_widgets
hcam_widgets/astro.py
_astropy_time_from_LST
def _astropy_time_from_LST(t, LST, location, prev_next): """ Convert a Local Sidereal Time to an astropy Time object. The local time is related to the LST through the RA of the Sun. This routine uses this relationship to convert a LST to an astropy time object. Returns ------- ret1 : `~astropy.time.Time` time corresponding to LST """ # now we need to figure out time to return from LST raSun = coord.get_sun(t).ra # calculate Greenwich Apparent Solar Time, which we will use as ~UTC for now with warnings.catch_warnings(): warnings.simplefilter('ignore') # ignore astropy deprecation warnings lon = location.longitude solarTime = LST - raSun + 12*u.hourangle - lon # assume this is on the same day as supplied time, and fix later first_guess = Time( u.d*int(t.mjd) + u.hour*solarTime.wrap_at('360d').hour, format='mjd' ) # Equation of time is difference between GAST and UTC eot = _equation_of_time(first_guess) first_guess = first_guess - u.hour * eot.value if prev_next == 'next': # if 'next', we want time to be greater than given time mask = first_guess < t rise_set_time = first_guess + mask * u.sday else: # if 'previous', we want time to be less than given time mask = first_guess > t rise_set_time = first_guess - mask * u.sday return rise_set_time
python
def _astropy_time_from_LST(t, LST, location, prev_next): """ Convert a Local Sidereal Time to an astropy Time object. The local time is related to the LST through the RA of the Sun. This routine uses this relationship to convert a LST to an astropy time object. Returns ------- ret1 : `~astropy.time.Time` time corresponding to LST """ # now we need to figure out time to return from LST raSun = coord.get_sun(t).ra # calculate Greenwich Apparent Solar Time, which we will use as ~UTC for now with warnings.catch_warnings(): warnings.simplefilter('ignore') # ignore astropy deprecation warnings lon = location.longitude solarTime = LST - raSun + 12*u.hourangle - lon # assume this is on the same day as supplied time, and fix later first_guess = Time( u.d*int(t.mjd) + u.hour*solarTime.wrap_at('360d').hour, format='mjd' ) # Equation of time is difference between GAST and UTC eot = _equation_of_time(first_guess) first_guess = first_guess - u.hour * eot.value if prev_next == 'next': # if 'next', we want time to be greater than given time mask = first_guess < t rise_set_time = first_guess + mask * u.sday else: # if 'previous', we want time to be less than given time mask = first_guess > t rise_set_time = first_guess - mask * u.sday return rise_set_time
[ "def", "_astropy_time_from_LST", "(", "t", ",", "LST", ",", "location", ",", "prev_next", ")", ":", "# now we need to figure out time to return from LST", "raSun", "=", "coord", ".", "get_sun", "(", "t", ")", ".", "ra", "# calculate Greenwich Apparent Solar Time, which ...
Convert a Local Sidereal Time to an astropy Time object. The local time is related to the LST through the RA of the Sun. This routine uses this relationship to convert a LST to an astropy time object. Returns ------- ret1 : `~astropy.time.Time` time corresponding to LST
[ "Convert", "a", "Local", "Sidereal", "Time", "to", "an", "astropy", "Time", "object", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/astro.py#L56-L97
train
HiPERCAM/hcam_widgets
hcam_widgets/astro.py
_rise_set_trig
def _rise_set_trig(t, target, location, prev_next, rise_set): """ Crude time at next rise/set of ``target`` using spherical trig. This method is ~15 times faster than `_calcriseset`, and inherently does *not* take the atmosphere into account. The time returned should not be used in calculations; the purpose of this routine is to supply a guess to `_calcriseset`. Parameters ---------- t : `~astropy.time.Time` or other (see below) Time of observation. This will be passed in as the first argument to the `~astropy.time.Time` initializer, so it can be anything that `~astropy.time.Time` will accept (including a `~astropy.time.Time` object) target : `~astropy.coordinates.SkyCoord` Position of target or multiple positions of that target at multiple times (if target moves, like the Sun) location : `~astropy.coordinates.EarthLocation` Observatory location prev_next : str - either 'previous' or 'next' Test next rise/set or previous rise/set rise_set : str - either 'rising' or 'setting' Compute prev/next rise or prev/next set Returns ------- ret1 : `~astropy.time.Time` Time of rise/set """ dec = target.transform_to(coord.ICRS).dec with warnings.catch_warnings(): warnings.simplefilter('ignore') # ignore astropy deprecation warnings lat = location.latitude cosHA = -np.tan(dec)*np.tan(lat.radian) # find the absolute value of the hour Angle HA = coord.Longitude(np.fabs(np.arccos(cosHA))) # if rise, HA is -ve and vice versa if rise_set == 'rising': HA = -HA # LST = HA + RA LST = HA + target.ra return _astropy_time_from_LST(t, LST, location, prev_next)
python
def _rise_set_trig(t, target, location, prev_next, rise_set): """ Crude time at next rise/set of ``target`` using spherical trig. This method is ~15 times faster than `_calcriseset`, and inherently does *not* take the atmosphere into account. The time returned should not be used in calculations; the purpose of this routine is to supply a guess to `_calcriseset`. Parameters ---------- t : `~astropy.time.Time` or other (see below) Time of observation. This will be passed in as the first argument to the `~astropy.time.Time` initializer, so it can be anything that `~astropy.time.Time` will accept (including a `~astropy.time.Time` object) target : `~astropy.coordinates.SkyCoord` Position of target or multiple positions of that target at multiple times (if target moves, like the Sun) location : `~astropy.coordinates.EarthLocation` Observatory location prev_next : str - either 'previous' or 'next' Test next rise/set or previous rise/set rise_set : str - either 'rising' or 'setting' Compute prev/next rise or prev/next set Returns ------- ret1 : `~astropy.time.Time` Time of rise/set """ dec = target.transform_to(coord.ICRS).dec with warnings.catch_warnings(): warnings.simplefilter('ignore') # ignore astropy deprecation warnings lat = location.latitude cosHA = -np.tan(dec)*np.tan(lat.radian) # find the absolute value of the hour Angle HA = coord.Longitude(np.fabs(np.arccos(cosHA))) # if rise, HA is -ve and vice versa if rise_set == 'rising': HA = -HA # LST = HA + RA LST = HA + target.ra return _astropy_time_from_LST(t, LST, location, prev_next)
[ "def", "_rise_set_trig", "(", "t", ",", "target", ",", "location", ",", "prev_next", ",", "rise_set", ")", ":", "dec", "=", "target", ".", "transform_to", "(", "coord", ".", "ICRS", ")", ".", "dec", "with", "warnings", ".", "catch_warnings", "(", ")", ...
Crude time at next rise/set of ``target`` using spherical trig. This method is ~15 times faster than `_calcriseset`, and inherently does *not* take the atmosphere into account. The time returned should not be used in calculations; the purpose of this routine is to supply a guess to `_calcriseset`. Parameters ---------- t : `~astropy.time.Time` or other (see below) Time of observation. This will be passed in as the first argument to the `~astropy.time.Time` initializer, so it can be anything that `~astropy.time.Time` will accept (including a `~astropy.time.Time` object) target : `~astropy.coordinates.SkyCoord` Position of target or multiple positions of that target at multiple times (if target moves, like the Sun) location : `~astropy.coordinates.EarthLocation` Observatory location prev_next : str - either 'previous' or 'next' Test next rise/set or previous rise/set rise_set : str - either 'rising' or 'setting' Compute prev/next rise or prev/next set Returns ------- ret1 : `~astropy.time.Time` Time of rise/set
[ "Crude", "time", "at", "next", "rise", "/", "set", "of", "target", "using", "spherical", "trig", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/astro.py#L100-L150
train
HiPERCAM/hcam_widgets
hcam_widgets/astro.py
calc_riseset
def calc_riseset(t, target_name, location, prev_next, rise_set, horizon): """ Time at next rise/set of ``target``. Parameters ---------- t : `~astropy.time.Time` or other (see below) Time of observation. This will be passed in as the first argument to the `~astropy.time.Time` initializer, so it can be anything that `~astropy.time.Time` will accept (including a `~astropy.time.Time` object) target_name : str 'moon' or 'sun' location : `~astropy.coordinates.EarthLocation` Observatory location prev_next : str - either 'previous' or 'next' Test next rise/set or previous rise/set rise_set : str - either 'rising' or 'setting' Compute prev/next rise or prev/next set location : `~astropy.coordinates.EarthLocation` Location of observer horizon : `~astropy.units.Quantity` Degrees above/below actual horizon to use for calculating rise/set times (i.e., -6 deg horizon = civil twilight, etc.) Returns ------- ret1 : `~astropy.time.Time` Time of rise/set """ target = coord.get_body(target_name, t) t0 = _rise_set_trig(t, target, location, prev_next, rise_set) grid = t0 + np.linspace(-4*u.hour, 4*u.hour, 10) altaz_frame = coord.AltAz(obstime=grid, location=location) target = coord.get_body(target_name, grid) altaz = target.transform_to(altaz_frame) time_limits, altitude_limits = _horiz_cross(altaz.obstime, altaz.alt, rise_set, horizon) return _two_point_interp(time_limits, altitude_limits, horizon)
python
def calc_riseset(t, target_name, location, prev_next, rise_set, horizon): """ Time at next rise/set of ``target``. Parameters ---------- t : `~astropy.time.Time` or other (see below) Time of observation. This will be passed in as the first argument to the `~astropy.time.Time` initializer, so it can be anything that `~astropy.time.Time` will accept (including a `~astropy.time.Time` object) target_name : str 'moon' or 'sun' location : `~astropy.coordinates.EarthLocation` Observatory location prev_next : str - either 'previous' or 'next' Test next rise/set or previous rise/set rise_set : str - either 'rising' or 'setting' Compute prev/next rise or prev/next set location : `~astropy.coordinates.EarthLocation` Location of observer horizon : `~astropy.units.Quantity` Degrees above/below actual horizon to use for calculating rise/set times (i.e., -6 deg horizon = civil twilight, etc.) Returns ------- ret1 : `~astropy.time.Time` Time of rise/set """ target = coord.get_body(target_name, t) t0 = _rise_set_trig(t, target, location, prev_next, rise_set) grid = t0 + np.linspace(-4*u.hour, 4*u.hour, 10) altaz_frame = coord.AltAz(obstime=grid, location=location) target = coord.get_body(target_name, grid) altaz = target.transform_to(altaz_frame) time_limits, altitude_limits = _horiz_cross(altaz.obstime, altaz.alt, rise_set, horizon) return _two_point_interp(time_limits, altitude_limits, horizon)
[ "def", "calc_riseset", "(", "t", ",", "target_name", ",", "location", ",", "prev_next", ",", "rise_set", ",", "horizon", ")", ":", "target", "=", "coord", ".", "get_body", "(", "target_name", ",", "t", ")", "t0", "=", "_rise_set_trig", "(", "t", ",", "...
Time at next rise/set of ``target``. Parameters ---------- t : `~astropy.time.Time` or other (see below) Time of observation. This will be passed in as the first argument to the `~astropy.time.Time` initializer, so it can be anything that `~astropy.time.Time` will accept (including a `~astropy.time.Time` object) target_name : str 'moon' or 'sun' location : `~astropy.coordinates.EarthLocation` Observatory location prev_next : str - either 'previous' or 'next' Test next rise/set or previous rise/set rise_set : str - either 'rising' or 'setting' Compute prev/next rise or prev/next set location : `~astropy.coordinates.EarthLocation` Location of observer horizon : `~astropy.units.Quantity` Degrees above/below actual horizon to use for calculating rise/set times (i.e., -6 deg horizon = civil twilight, etc.) Returns ------- ret1 : `~astropy.time.Time` Time of rise/set
[ "Time", "at", "next", "rise", "/", "set", "of", "target", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/astro.py#L153-L198
train
HiPERCAM/hcam_widgets
hcam_widgets/astro.py
_horiz_cross
def _horiz_cross(t, alt, rise_set, horizon=0*u.degree): """ Find time ``t`` when values in array ``a`` go from negative to positive or positive to negative (exclude endpoints) ``return_limits`` will return nearest times to zero-crossing. Parameters ---------- t : `~astropy.time.Time` Grid of times alt : `~astropy.units.Quantity` Grid of altitudes rise_set : {"rising", "setting"} Calculate either rising or setting across the horizon horizon : float Number of degrees above/below actual horizon to use for calculating rise/set times (i.e., -6 deg horizon = civil twilight, etc.) Returns ------- Returns the lower and upper limits on the time and altitudes of the horizon crossing. """ if rise_set == 'rising': # Find index where altitude goes from below to above horizon condition = (alt[:-1] < horizon) * (alt[1:] > horizon) elif rise_set == 'setting': # Find index where altitude goes from above to below horizon condition = (alt[:-1] > horizon) * (alt[1:] < horizon) if np.count_nonzero(condition) == 0: warnmsg = ('Target does not cross horizon={} within ' '8 hours of trigonometric estimate'.format(horizon)) warnings.warn(warnmsg) # Fill in missing time with MAGIC_TIME time_inds = np.nan times = [np.nan, np.nan] altitudes = [np.nan, np.nan] else: time_inds = np.nonzero(condition)[0][0] times = t[time_inds:time_inds+2] altitudes = alt[time_inds:time_inds+2] return times, altitudes
python
def _horiz_cross(t, alt, rise_set, horizon=0*u.degree): """ Find time ``t`` when values in array ``a`` go from negative to positive or positive to negative (exclude endpoints) ``return_limits`` will return nearest times to zero-crossing. Parameters ---------- t : `~astropy.time.Time` Grid of times alt : `~astropy.units.Quantity` Grid of altitudes rise_set : {"rising", "setting"} Calculate either rising or setting across the horizon horizon : float Number of degrees above/below actual horizon to use for calculating rise/set times (i.e., -6 deg horizon = civil twilight, etc.) Returns ------- Returns the lower and upper limits on the time and altitudes of the horizon crossing. """ if rise_set == 'rising': # Find index where altitude goes from below to above horizon condition = (alt[:-1] < horizon) * (alt[1:] > horizon) elif rise_set == 'setting': # Find index where altitude goes from above to below horizon condition = (alt[:-1] > horizon) * (alt[1:] < horizon) if np.count_nonzero(condition) == 0: warnmsg = ('Target does not cross horizon={} within ' '8 hours of trigonometric estimate'.format(horizon)) warnings.warn(warnmsg) # Fill in missing time with MAGIC_TIME time_inds = np.nan times = [np.nan, np.nan] altitudes = [np.nan, np.nan] else: time_inds = np.nonzero(condition)[0][0] times = t[time_inds:time_inds+2] altitudes = alt[time_inds:time_inds+2] return times, altitudes
[ "def", "_horiz_cross", "(", "t", ",", "alt", ",", "rise_set", ",", "horizon", "=", "0", "*", "u", ".", "degree", ")", ":", "if", "rise_set", "==", "'rising'", ":", "# Find index where altitude goes from below to above horizon", "condition", "=", "(", "alt", "[...
Find time ``t`` when values in array ``a`` go from negative to positive or positive to negative (exclude endpoints) ``return_limits`` will return nearest times to zero-crossing. Parameters ---------- t : `~astropy.time.Time` Grid of times alt : `~astropy.units.Quantity` Grid of altitudes rise_set : {"rising", "setting"} Calculate either rising or setting across the horizon horizon : float Number of degrees above/below actual horizon to use for calculating rise/set times (i.e., -6 deg horizon = civil twilight, etc.) Returns ------- Returns the lower and upper limits on the time and altitudes of the horizon crossing.
[ "Find", "time", "t", "when", "values", "in", "array", "a", "go", "from", "negative", "to", "positive", "or", "positive", "to", "negative", "(", "exclude", "endpoints", ")" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/astro.py#L202-L248
train
HiPERCAM/hcam_widgets
hcam_widgets/astro.py
_two_point_interp
def _two_point_interp(times, altitudes, horizon=0*u.deg): """ Do linear interpolation between two ``altitudes`` at two ``times`` to determine the time where the altitude goes through zero. Parameters ---------- times : `~astropy.time.Time` Two times for linear interpolation between altitudes : array of `~astropy.units.Quantity` Two altitudes for linear interpolation between horizon : `~astropy.units.Quantity` Solve for the time when the altitude is equal to reference_alt. Returns ------- t : `~astropy.time.Time` Time when target crosses the horizon """ if not isinstance(times, Time): return MAGIC_TIME else: slope = (altitudes[1] - altitudes[0])/(times[1].jd - times[0].jd) return Time(times[1].jd - ((altitudes[1] - horizon)/slope).value, format='jd')
python
def _two_point_interp(times, altitudes, horizon=0*u.deg): """ Do linear interpolation between two ``altitudes`` at two ``times`` to determine the time where the altitude goes through zero. Parameters ---------- times : `~astropy.time.Time` Two times for linear interpolation between altitudes : array of `~astropy.units.Quantity` Two altitudes for linear interpolation between horizon : `~astropy.units.Quantity` Solve for the time when the altitude is equal to reference_alt. Returns ------- t : `~astropy.time.Time` Time when target crosses the horizon """ if not isinstance(times, Time): return MAGIC_TIME else: slope = (altitudes[1] - altitudes[0])/(times[1].jd - times[0].jd) return Time(times[1].jd - ((altitudes[1] - horizon)/slope).value, format='jd')
[ "def", "_two_point_interp", "(", "times", ",", "altitudes", ",", "horizon", "=", "0", "*", "u", ".", "deg", ")", ":", "if", "not", "isinstance", "(", "times", ",", "Time", ")", ":", "return", "MAGIC_TIME", "else", ":", "slope", "=", "(", "altitudes", ...
Do linear interpolation between two ``altitudes`` at two ``times`` to determine the time where the altitude goes through zero. Parameters ---------- times : `~astropy.time.Time` Two times for linear interpolation between altitudes : array of `~astropy.units.Quantity` Two altitudes for linear interpolation between horizon : `~astropy.units.Quantity` Solve for the time when the altitude is equal to reference_alt. Returns ------- t : `~astropy.time.Time` Time when target crosses the horizon
[ "Do", "linear", "interpolation", "between", "two", "altitudes", "at", "two", "times", "to", "determine", "the", "time", "where", "the", "altitude", "goes", "through", "zero", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/astro.py#L252-L281
train
IceflowRE/unidown
unidown/dynamic_data.py
init_dirs
def init_dirs(main_dir: Path, logfilepath: Path): """ Initialize the main directories. :param main_dir: main directory :type main_dir: ~pathlib.Path :param logfilepath: log file :type logfilepath: ~pathlib.Path """ global MAIN_DIR, TEMP_DIR, DOWNLOAD_DIR, SAVESTAT_DIR, LOGFILE_PATH MAIN_DIR = main_dir TEMP_DIR = MAIN_DIR.joinpath(Path('temp/')) DOWNLOAD_DIR = MAIN_DIR.joinpath(Path('downloads/')) SAVESTAT_DIR = MAIN_DIR.joinpath(Path('savestates/')) LOGFILE_PATH = MAIN_DIR.joinpath(logfilepath)
python
def init_dirs(main_dir: Path, logfilepath: Path): """ Initialize the main directories. :param main_dir: main directory :type main_dir: ~pathlib.Path :param logfilepath: log file :type logfilepath: ~pathlib.Path """ global MAIN_DIR, TEMP_DIR, DOWNLOAD_DIR, SAVESTAT_DIR, LOGFILE_PATH MAIN_DIR = main_dir TEMP_DIR = MAIN_DIR.joinpath(Path('temp/')) DOWNLOAD_DIR = MAIN_DIR.joinpath(Path('downloads/')) SAVESTAT_DIR = MAIN_DIR.joinpath(Path('savestates/')) LOGFILE_PATH = MAIN_DIR.joinpath(logfilepath)
[ "def", "init_dirs", "(", "main_dir", ":", "Path", ",", "logfilepath", ":", "Path", ")", ":", "global", "MAIN_DIR", ",", "TEMP_DIR", ",", "DOWNLOAD_DIR", ",", "SAVESTAT_DIR", ",", "LOGFILE_PATH", "MAIN_DIR", "=", "main_dir", "TEMP_DIR", "=", "MAIN_DIR", ".", ...
Initialize the main directories. :param main_dir: main directory :type main_dir: ~pathlib.Path :param logfilepath: log file :type logfilepath: ~pathlib.Path
[ "Initialize", "the", "main", "directories", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/dynamic_data.py#L37-L51
train
IceflowRE/unidown
unidown/dynamic_data.py
reset
def reset(): """ Reset all dynamic variables to the default values. """ global MAIN_DIR, TEMP_DIR, DOWNLOAD_DIR, SAVESTAT_DIR, LOGFILE_PATH, USING_CORES, LOG_LEVEL, DISABLE_TQDM, \ SAVE_STATE_VERSION MAIN_DIR = Path('./') TEMP_DIR = MAIN_DIR.joinpath(Path('temp/')) DOWNLOAD_DIR = MAIN_DIR.joinpath(Path('downloads/')) SAVESTAT_DIR = MAIN_DIR.joinpath(Path('savestates/')) LOGFILE_PATH = MAIN_DIR.joinpath(Path('UniDown.log')) USING_CORES = 1 LOG_LEVEL = 'INFO' DISABLE_TQDM = False SAVE_STATE_VERSION = Version('1')
python
def reset(): """ Reset all dynamic variables to the default values. """ global MAIN_DIR, TEMP_DIR, DOWNLOAD_DIR, SAVESTAT_DIR, LOGFILE_PATH, USING_CORES, LOG_LEVEL, DISABLE_TQDM, \ SAVE_STATE_VERSION MAIN_DIR = Path('./') TEMP_DIR = MAIN_DIR.joinpath(Path('temp/')) DOWNLOAD_DIR = MAIN_DIR.joinpath(Path('downloads/')) SAVESTAT_DIR = MAIN_DIR.joinpath(Path('savestates/')) LOGFILE_PATH = MAIN_DIR.joinpath(Path('UniDown.log')) USING_CORES = 1 LOG_LEVEL = 'INFO' DISABLE_TQDM = False SAVE_STATE_VERSION = Version('1')
[ "def", "reset", "(", ")", ":", "global", "MAIN_DIR", ",", "TEMP_DIR", ",", "DOWNLOAD_DIR", ",", "SAVESTAT_DIR", ",", "LOGFILE_PATH", ",", "USING_CORES", ",", "LOG_LEVEL", ",", "DISABLE_TQDM", ",", "SAVE_STATE_VERSION", "MAIN_DIR", "=", "Path", "(", "'./'", ")"...
Reset all dynamic variables to the default values.
[ "Reset", "all", "dynamic", "variables", "to", "the", "default", "values", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/dynamic_data.py#L54-L70
train
IceflowRE/unidown
unidown/dynamic_data.py
check_dirs
def check_dirs(): """ Check the directories if they exist. :raises FileExistsError: if a file exists but is not a directory """ dirs = [MAIN_DIR, TEMP_DIR, DOWNLOAD_DIR, SAVESTAT_DIR] for directory in dirs: if directory.exists() and not directory.is_dir(): raise FileExistsError(str(directory.resolve()) + " cannot be used as a directory.")
python
def check_dirs(): """ Check the directories if they exist. :raises FileExistsError: if a file exists but is not a directory """ dirs = [MAIN_DIR, TEMP_DIR, DOWNLOAD_DIR, SAVESTAT_DIR] for directory in dirs: if directory.exists() and not directory.is_dir(): raise FileExistsError(str(directory.resolve()) + " cannot be used as a directory.")
[ "def", "check_dirs", "(", ")", ":", "dirs", "=", "[", "MAIN_DIR", ",", "TEMP_DIR", ",", "DOWNLOAD_DIR", ",", "SAVESTAT_DIR", "]", "for", "directory", "in", "dirs", ":", "if", "directory", ".", "exists", "(", ")", "and", "not", "directory", ".", "is_dir",...
Check the directories if they exist. :raises FileExistsError: if a file exists but is not a directory
[ "Check", "the", "directories", "if", "they", "exist", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/dynamic_data.py#L73-L82
train
HiPERCAM/hcam_widgets
hcam_widgets/gtc/headers.py
parse_hstring
def parse_hstring(hs): """ Parse a single item from the telescope server into name, value, comment. """ # split the string on = and /, also stripping whitespace and annoying quotes name, value, comment = yield_three( [val.strip().strip("'") for val in filter(None, re.split("[=/]+", hs))] ) # if comment has a slash in it, put it back together try: len(comment) except: pass else: comment = '/'.join(comment) return name, value, comment
python
def parse_hstring(hs): """ Parse a single item from the telescope server into name, value, comment. """ # split the string on = and /, also stripping whitespace and annoying quotes name, value, comment = yield_three( [val.strip().strip("'") for val in filter(None, re.split("[=/]+", hs))] ) # if comment has a slash in it, put it back together try: len(comment) except: pass else: comment = '/'.join(comment) return name, value, comment
[ "def", "parse_hstring", "(", "hs", ")", ":", "# split the string on = and /, also stripping whitespace and annoying quotes", "name", ",", "value", ",", "comment", "=", "yield_three", "(", "[", "val", ".", "strip", "(", ")", ".", "strip", "(", "\"'\"", ")", "for", ...
Parse a single item from the telescope server into name, value, comment.
[ "Parse", "a", "single", "item", "from", "the", "telescope", "server", "into", "name", "value", "comment", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/gtc/headers.py#L27-L43
train
HiPERCAM/hcam_widgets
hcam_widgets/gtc/headers.py
create_header_from_telpars
def create_header_from_telpars(telpars): """ Create a list of fits header items from GTC telescope pars. The GTC telescope server gives a list of string describing FITS header items such as RA, DEC, etc. Arguments --------- telpars : list list returned by server call to getTelescopeParams """ # pars is a list of strings describing tel info in FITS # style, each entry in the list is a different class of # thing (weather, telescope, instrument etc). # first, we munge it into a single list of strings, each one # describing a single item whilst also stripping whitespace pars = [val.strip() for val in (';').join(telpars).split(';') if val.strip() != ''] # apply parse_hstring to everything in pars with warnings.catch_warnings(): warnings.simplefilter('ignore', fits.verify.VerifyWarning) hdr = fits.Header(map(parse_hstring, pars)) return hdr
python
def create_header_from_telpars(telpars): """ Create a list of fits header items from GTC telescope pars. The GTC telescope server gives a list of string describing FITS header items such as RA, DEC, etc. Arguments --------- telpars : list list returned by server call to getTelescopeParams """ # pars is a list of strings describing tel info in FITS # style, each entry in the list is a different class of # thing (weather, telescope, instrument etc). # first, we munge it into a single list of strings, each one # describing a single item whilst also stripping whitespace pars = [val.strip() for val in (';').join(telpars).split(';') if val.strip() != ''] # apply parse_hstring to everything in pars with warnings.catch_warnings(): warnings.simplefilter('ignore', fits.verify.VerifyWarning) hdr = fits.Header(map(parse_hstring, pars)) return hdr
[ "def", "create_header_from_telpars", "(", "telpars", ")", ":", "# pars is a list of strings describing tel info in FITS", "# style, each entry in the list is a different class of", "# thing (weather, telescope, instrument etc).", "# first, we munge it into a single list of strings, each one", "#...
Create a list of fits header items from GTC telescope pars. The GTC telescope server gives a list of string describing FITS header items such as RA, DEC, etc. Arguments --------- telpars : list list returned by server call to getTelescopeParams
[ "Create", "a", "list", "of", "fits", "header", "items", "from", "GTC", "telescope", "pars", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/gtc/headers.py#L46-L72
train
HiPERCAM/hcam_widgets
hcam_widgets/gtc/headers.py
add_gtc_header_table_row
def add_gtc_header_table_row(t, telpars): """ Add a row with current values to GTC table Arguments --------- t : `~astropy.table.Table` The table to append row to telpars : list list returned by server call to getTelescopeParams """ now = Time.now().mjd hdr = create_header_from_telpars(telpars) # make dictionary of vals to put in table vals = {k: v for k, v in hdr.items() if k in VARIABLE_GTC_KEYS} vals['MJD'] = now # store LST as hourangle vals['LST'] = Longitude(vals['LST'], unit=u.hour).hourangle t.add_row(vals)
python
def add_gtc_header_table_row(t, telpars): """ Add a row with current values to GTC table Arguments --------- t : `~astropy.table.Table` The table to append row to telpars : list list returned by server call to getTelescopeParams """ now = Time.now().mjd hdr = create_header_from_telpars(telpars) # make dictionary of vals to put in table vals = {k: v for k, v in hdr.items() if k in VARIABLE_GTC_KEYS} vals['MJD'] = now # store LST as hourangle vals['LST'] = Longitude(vals['LST'], unit=u.hour).hourangle t.add_row(vals)
[ "def", "add_gtc_header_table_row", "(", "t", ",", "telpars", ")", ":", "now", "=", "Time", ".", "now", "(", ")", ".", "mjd", "hdr", "=", "create_header_from_telpars", "(", "telpars", ")", "# make dictionary of vals to put in table", "vals", "=", "{", "k", ":",...
Add a row with current values to GTC table Arguments --------- t : `~astropy.table.Table` The table to append row to telpars : list list returned by server call to getTelescopeParams
[ "Add", "a", "row", "with", "current", "values", "to", "GTC", "table" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/gtc/headers.py#L80-L99
train
IceflowRE/unidown
unidown/plugin/plugin_info.py
PluginInfo.from_protobuf
def from_protobuf(cls, proto: PluginInfoProto) -> PluginInfo: """ Constructor from protobuf. :param proto: protobuf structure :type proto: ~unidown.plugin.protobuf.plugin_info_pb2.PluginInfoProto :return: the PluginInfo :rtype: ~unidown.plugin.plugin_info.PluginInfo :raises ValueError: name of PluginInfo does not exist or is empty inside the protobuf :raises ValueError: version of PluginInfo does not exist or is empty inside the protobuf :raises ValueError: host of PluginInfo does not exist or is empty inside the protobuf """ if proto.name == "": raise ValueError("name of PluginInfo does not exist or is empty inside the protobuf.") elif proto.version == "": raise ValueError("version of PluginInfo does not exist or is empty inside the protobuf.") elif proto.host == "": raise ValueError("host of PluginInfo does not exist or is empty inside the protobuf.") return cls(proto.name, proto.version, proto.host)
python
def from_protobuf(cls, proto: PluginInfoProto) -> PluginInfo: """ Constructor from protobuf. :param proto: protobuf structure :type proto: ~unidown.plugin.protobuf.plugin_info_pb2.PluginInfoProto :return: the PluginInfo :rtype: ~unidown.plugin.plugin_info.PluginInfo :raises ValueError: name of PluginInfo does not exist or is empty inside the protobuf :raises ValueError: version of PluginInfo does not exist or is empty inside the protobuf :raises ValueError: host of PluginInfo does not exist or is empty inside the protobuf """ if proto.name == "": raise ValueError("name of PluginInfo does not exist or is empty inside the protobuf.") elif proto.version == "": raise ValueError("version of PluginInfo does not exist or is empty inside the protobuf.") elif proto.host == "": raise ValueError("host of PluginInfo does not exist or is empty inside the protobuf.") return cls(proto.name, proto.version, proto.host)
[ "def", "from_protobuf", "(", "cls", ",", "proto", ":", "PluginInfoProto", ")", "->", "PluginInfo", ":", "if", "proto", ".", "name", "==", "\"\"", ":", "raise", "ValueError", "(", "\"name of PluginInfo does not exist or is empty inside the protobuf.\"", ")", "elif", ...
Constructor from protobuf. :param proto: protobuf structure :type proto: ~unidown.plugin.protobuf.plugin_info_pb2.PluginInfoProto :return: the PluginInfo :rtype: ~unidown.plugin.plugin_info.PluginInfo :raises ValueError: name of PluginInfo does not exist or is empty inside the protobuf :raises ValueError: version of PluginInfo does not exist or is empty inside the protobuf :raises ValueError: host of PluginInfo does not exist or is empty inside the protobuf
[ "Constructor", "from", "protobuf", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/plugin/plugin_info.py#L48-L66
train
IceflowRE/unidown
unidown/plugin/plugin_info.py
PluginInfo.to_protobuf
def to_protobuf(self) -> PluginInfoProto: """ Create protobuf item. :return: protobuf structure :rtype: ~unidown.plugin.protobuf.link_item_pb2.PluginInfoProto """ proto = PluginInfoProto() proto.name = self.name proto.version = str(self.version) proto.host = self.host return proto
python
def to_protobuf(self) -> PluginInfoProto: """ Create protobuf item. :return: protobuf structure :rtype: ~unidown.plugin.protobuf.link_item_pb2.PluginInfoProto """ proto = PluginInfoProto() proto.name = self.name proto.version = str(self.version) proto.host = self.host return proto
[ "def", "to_protobuf", "(", "self", ")", "->", "PluginInfoProto", ":", "proto", "=", "PluginInfoProto", "(", ")", "proto", ".", "name", "=", "self", ".", "name", "proto", ".", "version", "=", "str", "(", "self", ".", "version", ")", "proto", ".", "host"...
Create protobuf item. :return: protobuf structure :rtype: ~unidown.plugin.protobuf.link_item_pb2.PluginInfoProto
[ "Create", "protobuf", "item", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/plugin/plugin_info.py#L79-L90
train
IceflowRE/unidown
unidown/plugin/save_state.py
SaveState.from_protobuf
def from_protobuf(cls, proto: SaveStateProto) -> SaveState: """ Constructor from protobuf. Can raise ValueErrors from called from_protobuf() parsers. :param proto: protobuf structure :type proto: ~unidown.plugin.protobuf.save_state_pb2.SaveStateProto :return: the SaveState :rtype: ~unidown.plugin.save_state.SaveState :raises ValueError: version of SaveState does not exist or is empty inside the protobuf :raises ~packaging.version.InvalidVersion: version is not PEP440 conform """ data_dict = {} for key, link_item in proto.data.items(): data_dict[key] = LinkItem.from_protobuf(link_item) if proto.version == "": raise ValueError("version of SaveState does not exist or is empty inside the protobuf.") try: version = Version(proto.version) except InvalidVersion: raise InvalidVersion(f"Plugin version is not PEP440 conform: {proto.version}") return cls(version, PluginInfo.from_protobuf(proto.plugin_info), Timestamp.ToDatetime(proto.last_update), data_dict)
python
def from_protobuf(cls, proto: SaveStateProto) -> SaveState: """ Constructor from protobuf. Can raise ValueErrors from called from_protobuf() parsers. :param proto: protobuf structure :type proto: ~unidown.plugin.protobuf.save_state_pb2.SaveStateProto :return: the SaveState :rtype: ~unidown.plugin.save_state.SaveState :raises ValueError: version of SaveState does not exist or is empty inside the protobuf :raises ~packaging.version.InvalidVersion: version is not PEP440 conform """ data_dict = {} for key, link_item in proto.data.items(): data_dict[key] = LinkItem.from_protobuf(link_item) if proto.version == "": raise ValueError("version of SaveState does not exist or is empty inside the protobuf.") try: version = Version(proto.version) except InvalidVersion: raise InvalidVersion(f"Plugin version is not PEP440 conform: {proto.version}") return cls(version, PluginInfo.from_protobuf(proto.plugin_info), Timestamp.ToDatetime(proto.last_update), data_dict)
[ "def", "from_protobuf", "(", "cls", ",", "proto", ":", "SaveStateProto", ")", "->", "SaveState", ":", "data_dict", "=", "{", "}", "for", "key", ",", "link_item", "in", "proto", ".", "data", ".", "items", "(", ")", ":", "data_dict", "[", "key", "]", "...
Constructor from protobuf. Can raise ValueErrors from called from_protobuf() parsers. :param proto: protobuf structure :type proto: ~unidown.plugin.protobuf.save_state_pb2.SaveStateProto :return: the SaveState :rtype: ~unidown.plugin.save_state.SaveState :raises ValueError: version of SaveState does not exist or is empty inside the protobuf :raises ~packaging.version.InvalidVersion: version is not PEP440 conform
[ "Constructor", "from", "protobuf", ".", "Can", "raise", "ValueErrors", "from", "called", "from_protobuf", "()", "parsers", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/plugin/save_state.py#L55-L76
train
IceflowRE/unidown
unidown/plugin/save_state.py
SaveState.to_protobuf
def to_protobuf(self) -> SaveStateProto: """ Create protobuf item. :return: protobuf structure :rtype: ~unidown.plugin.protobuf.save_state_pb2.SaveStateProto """ result = SaveStateProto() result.version = str(self.version) result.last_update.CopyFrom(datetime_to_timestamp(self.last_update)) result.plugin_info.CopyFrom(self.plugin_info.to_protobuf()) for key, link_item in self.link_item_dict.items(): result.data[key].CopyFrom(link_item.to_protobuf()) return result
python
def to_protobuf(self) -> SaveStateProto: """ Create protobuf item. :return: protobuf structure :rtype: ~unidown.plugin.protobuf.save_state_pb2.SaveStateProto """ result = SaveStateProto() result.version = str(self.version) result.last_update.CopyFrom(datetime_to_timestamp(self.last_update)) result.plugin_info.CopyFrom(self.plugin_info.to_protobuf()) for key, link_item in self.link_item_dict.items(): result.data[key].CopyFrom(link_item.to_protobuf()) return result
[ "def", "to_protobuf", "(", "self", ")", "->", "SaveStateProto", ":", "result", "=", "SaveStateProto", "(", ")", "result", ".", "version", "=", "str", "(", "self", ".", "version", ")", "result", ".", "last_update", ".", "CopyFrom", "(", "datetime_to_timestamp...
Create protobuf item. :return: protobuf structure :rtype: ~unidown.plugin.protobuf.save_state_pb2.SaveStateProto
[ "Create", "protobuf", "item", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/plugin/save_state.py#L78-L91
train
markuskiller/textblob-de
textblob_de/ext/_pattern/text/de/inflect.py
definite_article
def definite_article(word, gender=MALE, role=SUBJECT): """ Returns the definite article (der/die/das/die) for a given word. """ return article_definite.get((gender[:1].lower(), role[:3].lower()))
python
def definite_article(word, gender=MALE, role=SUBJECT): """ Returns the definite article (der/die/das/die) for a given word. """ return article_definite.get((gender[:1].lower(), role[:3].lower()))
[ "def", "definite_article", "(", "word", ",", "gender", "=", "MALE", ",", "role", "=", "SUBJECT", ")", ":", "return", "article_definite", ".", "get", "(", "(", "gender", "[", ":", "1", "]", ".", "lower", "(", ")", ",", "role", "[", ":", "3", "]", ...
Returns the definite article (der/die/das/die) for a given word.
[ "Returns", "the", "definite", "article", "(", "der", "/", "die", "/", "das", "/", "die", ")", "for", "a", "given", "word", "." ]
1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/de/inflect.py#L87-L90
train
markuskiller/textblob-de
textblob_de/ext/_pattern/text/de/inflect.py
indefinite_article
def indefinite_article(word, gender=MALE, role=SUBJECT): """ Returns the indefinite article (ein) for a given word. """ return article_indefinite.get((gender[:1].lower(), role[:3].lower()))
python
def indefinite_article(word, gender=MALE, role=SUBJECT): """ Returns the indefinite article (ein) for a given word. """ return article_indefinite.get((gender[:1].lower(), role[:3].lower()))
[ "def", "indefinite_article", "(", "word", ",", "gender", "=", "MALE", ",", "role", "=", "SUBJECT", ")", ":", "return", "article_indefinite", ".", "get", "(", "(", "gender", "[", ":", "1", "]", ".", "lower", "(", ")", ",", "role", "[", ":", "3", "]"...
Returns the indefinite article (ein) for a given word.
[ "Returns", "the", "indefinite", "article", "(", "ein", ")", "for", "a", "given", "word", "." ]
1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/de/inflect.py#L92-L95
train
markuskiller/textblob-de
textblob_de/ext/_pattern/text/de/inflect.py
article
def article(word, function=INDEFINITE, gender=MALE, role=SUBJECT): """ Returns the indefinite (ein) or definite (der/die/das/die) article for the given word. """ return function == DEFINITE \ and definite_article(word, gender, role) \ or indefinite_article(word, gender, role)
python
def article(word, function=INDEFINITE, gender=MALE, role=SUBJECT): """ Returns the indefinite (ein) or definite (der/die/das/die) article for the given word. """ return function == DEFINITE \ and definite_article(word, gender, role) \ or indefinite_article(word, gender, role)
[ "def", "article", "(", "word", ",", "function", "=", "INDEFINITE", ",", "gender", "=", "MALE", ",", "role", "=", "SUBJECT", ")", ":", "return", "function", "==", "DEFINITE", "and", "definite_article", "(", "word", ",", "gender", ",", "role", ")", "or", ...
Returns the indefinite (ein) or definite (der/die/das/die) article for the given word.
[ "Returns", "the", "indefinite", "(", "ein", ")", "or", "definite", "(", "der", "/", "die", "/", "das", "/", "die", ")", "article", "for", "the", "given", "word", "." ]
1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/de/inflect.py#L100-L105
train
markuskiller/textblob-de
textblob_de/ext/_pattern/text/de/inflect.py
referenced
def referenced(word, article=INDEFINITE, gender=MALE, role=SUBJECT): """ Returns a string with the article + the word. """ return "%s %s" % (_article(word, article, gender, role), word)
python
def referenced(word, article=INDEFINITE, gender=MALE, role=SUBJECT): """ Returns a string with the article + the word. """ return "%s %s" % (_article(word, article, gender, role), word)
[ "def", "referenced", "(", "word", ",", "article", "=", "INDEFINITE", ",", "gender", "=", "MALE", ",", "role", "=", "SUBJECT", ")", ":", "return", "\"%s %s\"", "%", "(", "_article", "(", "word", ",", "article", ",", "gender", ",", "role", ")", ",", "w...
Returns a string with the article + the word.
[ "Returns", "a", "string", "with", "the", "article", "+", "the", "word", "." ]
1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/de/inflect.py#L108-L111
train
markuskiller/textblob-de
textblob_de/ext/_pattern/text/de/inflect.py
gender
def gender(word, pos=NOUN): """ Returns the gender (MALE, FEMALE or NEUTRAL) for nouns (majority vote). Returns None for words that are not nouns. """ w = word.lower() if pos == NOUN: # Default rules (baseline = 32%). if w.endswith(gender_masculine): return MASCULINE if w.endswith(gender_feminine): return FEMININE if w.endswith(gender_neuter): return NEUTER # Majority vote. for g in gender_majority_vote: if w.endswith(gender_majority_vote[g]): return g
python
def gender(word, pos=NOUN): """ Returns the gender (MALE, FEMALE or NEUTRAL) for nouns (majority vote). Returns None for words that are not nouns. """ w = word.lower() if pos == NOUN: # Default rules (baseline = 32%). if w.endswith(gender_masculine): return MASCULINE if w.endswith(gender_feminine): return FEMININE if w.endswith(gender_neuter): return NEUTER # Majority vote. for g in gender_majority_vote: if w.endswith(gender_majority_vote[g]): return g
[ "def", "gender", "(", "word", ",", "pos", "=", "NOUN", ")", ":", "w", "=", "word", ".", "lower", "(", ")", "if", "pos", "==", "NOUN", ":", "# Default rules (baseline = 32%).", "if", "w", ".", "endswith", "(", "gender_masculine", ")", ":", "return", "MA...
Returns the gender (MALE, FEMALE or NEUTRAL) for nouns (majority vote). Returns None for words that are not nouns.
[ "Returns", "the", "gender", "(", "MALE", "FEMALE", "or", "NEUTRAL", ")", "for", "nouns", "(", "majority", "vote", ")", ".", "Returns", "None", "for", "words", "that", "are", "not", "nouns", "." ]
1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/de/inflect.py#L147-L163
train