-
Notifications
You must be signed in to change notification settings - Fork 5
/
little_helpers.py
executable file
·262 lines (211 loc) · 8.45 KB
/
little_helpers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
from pyface.qt import QtGui, QtCore
import numpy as np
import sys
import os
import traceback
from collections import OrderedDict
import ast
import operator as op
from fractions import Fraction
from collections import deque
class CopySelectedCellsAction(QtGui.QAction):
def __init__(self, table_widget):
if not isinstance(table_widget, QtGui.QTableWidget):
raise ValueError(str(
'CopySelectedCellsAction must be initialised with a QTableWidget. A %s was given.' % type(
table_widget)))
super(CopySelectedCellsAction, self).__init__("Copy", table_widget)
self.setShortcut('Ctrl+c')
self.triggered.connect(self.copy_cells_to_clipboard)
self.table_widget = table_widget
def copy_cells_to_clipboard(self):
if len(self.table_widget.selectionModel().selectedIndexes()) > 0:
# sort select indexes into rows and columns
previous = self.table_widget.selectionModel().selectedIndexes()[0]
columns = []
rows = []
for index in self.table_widget.selectionModel().selectedIndexes():
if previous.column() != index.column():
columns.append(rows)
rows = []
rows.append(index.data())
previous = index
columns.append(rows)
# add rows and columns to clipboard
clipboard = ""
nrows = len(columns[0])
ncols = len(columns)
for r in range(nrows):
for c in range(ncols):
clipboard += columns[c][r]
if c != (ncols - 1):
clipboard += '\t'
clipboard += '\n'
# copy to the system clipboard
sys_clip = QtGui.QApplication.clipboard()
sys_clip.setText(clipboard)
class PasteIntoTable(QtGui.QAction):
def __init__(self, table_widget, parent):
if not isinstance(table_widget, QtGui.QTableWidget):
raise ValueError(str(
'CopySelectedCellsAction must be initialised with a QTableWidget. A %s was given.' % type(
table_widget)))
super(PasteIntoTable, self).__init__("Copy", table_widget)
self.setShortcut('Ctrl+v')
self.parent = parent
self.triggered.connect(self.paste_cells_from_clipboard)
self.table_widget = table_widget
def paste_cells_from_clipboard(self):
self.parent.disconnect_tables()
index = self.table_widget.selectedIndexes()[0]
i0 = index.row()
j0 = index.column()
sys_clip = QtGui.QApplication.clipboard()
clipboard = sys_clip.text()
rows = clipboard.split('\n')
n_rows = len(rows)
col_0 = rows[0].split()
n_col = len(col_0)
# data = np.zeros((n_rows,n_col))
for i, row in enumerate(rows):
col = row.split()
for j, el in enumerate(col):
self.table_widget.item(i + i0, j + j0).setText(el)
self.parent.connect_tables()
self.parent.handle_change()
class DequeSet(deque):
def __init__(self,iterable=(), maxlen=None):
iterable_new = []
for x in iterable:
if x not in iterable_new:
iterable_new.append(x)
super().__init__(iterable_new,maxlen)
def append(self, x):
if x in self:
self.remove(x)
super().append(x)
def appendleft(self, x):
if x in self:
self.remove(x)
super().appendleft(x)
def extend(self, x):
for el in x:
self.append(el)
def extendleft(self, x):
for el in x[::-1]:
self.appendleft(el)
def find_possible_sums(repeat):
possible_sums = set()
for i in range(repeat[0] + 1):
for j in range(repeat[1] + 1):
for l in range(repeat[2] + 1):
pos_sum = (i, j, l)
possible_sums.add(pos_sum)
return possible_sums
def find_grid_connections(possible_sums):
connections = set()
for i, pos_sum in enumerate(possible_sums):
for j, pos_sum_1 in enumerate(possible_sums):
diff_sum = (abs(x - y) for x, y in zip(pos_sum, pos_sum_1))
if sum(diff_sum) == 1:
connections.add(tuple(sorted([i, j])))
return connections
def convert_to_ordered(d):
return OrderedDict(sorted(d.items(), key=lambda t: t[0]))
def set_procname(newname):
if sys.platform in ['linux', 'linux2']:
from ctypes import cdll, byref, create_string_buffer
libc = cdll.LoadLibrary('libc.so.6') # Loading a 3rd party library C
buff = create_string_buffer(len(newname) + 1) # Note: One larger than the name (man prctl says that)
buff.value = newname # Null terminated string as it should be
libc.prctl(15, byref(buff), 0, 0, 0)
else:
import ctypes
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(newname.decode())
def get_proc_name():
from ctypes import cdll, byref, create_string_buffer
libc = cdll.LoadLibrary('libc.so.6')
buff = create_string_buffer(128)
# 16 == PR_GET_NAME from <linux/prctl.h>
libc.prctl(16, byref(buff), 0, 0, 0)
return buff.value
def find_data_file(filename):
if getattr(sys, 'frozen', False):
# The application is frozen
datadir = os.path.dirname(sys.executable)
else:
# The application is not frozen
# Change this bit to match where you store your data files:
datadir = os.path.dirname(__file__)
return datadir + filename
def get_stacktrace_as_string(html=True):
exc_type, exc_value, exc_traceback = sys.exc_info()
error = traceback.format_exception(exc_type, exc_value, exc_traceback)
if html:
page_break = '<br>'
else:
page_break = '\n'
joined_error = page_break.join(error)
if html:
joined_error = joined_error.replace(' ', ' ')
return joined_error
# supported operators
operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
ast.USub: op.neg,'sin':np.sin,'cos':np.cos,'tan':np.tan,'sqrt':np.sqrt,'pi':np.pi,
'sind': lambda x: np.sin(x*np.pi/180), 'cosd':lambda x: np.cos(x*np.pi/180), 'tand': lambda x: np.tan(x*np.pi/180)}
def eval_expr(expr):
return eval_(ast.parse(expr, mode='eval').body)
def eval_(node):
if isinstance(node, ast.Num): # <number>
return node.n
elif isinstance(node, ast.BinOp): # <left> <operator> <right>
return operators[type(node.op)](eval_(node.left), eval_(node.right))
elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
return operators[type(node.op)](eval_(node.operand))
elif isinstance(node, ast.Call): # <func>(<arg>)
return operators[node.func.id](eval_(node.args[0]))
elif isinstance(node, ast.Name):
return operators[node.id]
else:
raise TypeError(node)
def find_fraction(num):
frac = Fraction(num).limit_denominator(16)
if frac.numerator == 0:
return '0'
elif frac.denominator == 1:
return '{}'.format(frac.numerator)
elif abs(frac-num) > 1e-14:
return '{0:1.11f}'.format(num)
else:
return '{0}/{1}'.format(frac.numerator, frac.denominator)
def convert_to_bool(x,match_case = False):
if not match_case:
x = x.lower()
x = x.strip()
if x in ['true', '1']:
return True
elif x in ['false', '0']:
return False
else:
raise ValueError('Bad input to convert to bool with' + str(x))
def fix_requests_if_frozen():
def override_where():
""" overrides certifi.core.where to return actual location of cacert.pem"""
# change this to match the location of cacert.pem
return find_data_file('/data/cacert.pem')
# is the program compiled?
if hasattr(sys, "frozen"):
import certifi.core
os.environ["REQUESTS_CA_BUNDLE"] = override_where()
certifi.core.where = override_where
# delay importing until after where() has been replaced
import requests.utils
import requests.adapters
# replace these variables in case these modules were
# imported before we replaced certifi.core.where
requests.utils.DEFAULT_CA_BUNDLE_PATH = override_where()
requests.adapters.DEFAULT_CA_BUNDLE_PATH = override_where()
if __name__ == "__main__":
# print(eval_expr('sind(45)'))
print(find_fraction(6/32))