imio.pyutils 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
imio/pyutils/tests.py ADDED
@@ -0,0 +1,258 @@
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # tests utis methods
4
+ # IMIO <support@imio.be>
5
+ #
6
+ from collections import OrderedDict
7
+ from imio.pyutils.system import hashed_filename
8
+ from imio.pyutils.system import read_dir_filter
9
+ from imio.pyutils.system import read_recursive_dir
10
+ from imio.pyutils.utils import add_key_if_value
11
+ from imio.pyutils.utils import all_of_dict_values
12
+ from imio.pyutils.utils import append
13
+ from imio.pyutils.utils import get_clusters
14
+ from imio.pyutils.utils import get_ordinal_clusters
15
+ from imio.pyutils.utils import insert_in_ordereddict
16
+ from imio.pyutils.utils import iterable_as_list_of_list
17
+ from imio.pyutils.utils import letters_sequence
18
+ from imio.pyutils.utils import listify
19
+ from imio.pyutils.utils import merge_dicts
20
+ from imio.pyutils.utils import odict_pos_key
21
+ from imio.pyutils.utils import one_of_dict_values
22
+ from imio.pyutils.utils import radix_like_starting_1
23
+ from imio.pyutils.utils import replace_in_list
24
+ from imio.pyutils.utils import safe_encode
25
+ from imio.pyutils.utils import sort_by_indexes
26
+
27
+ import os
28
+ import types
29
+ import unittest
30
+
31
+
32
+ class TestUtils(unittest.TestCase):
33
+ """ """
34
+
35
+ def test_add_key_if_value(self):
36
+ dic = {}
37
+ add_key_if_value(dic, "a", None)
38
+ self.assertDictEqual(dic, {})
39
+ add_key_if_value(dic, "a", "", strict=True)
40
+ self.assertDictEqual(dic, {})
41
+ add_key_if_value(dic, "a", "")
42
+ self.assertDictEqual(dic, {"a": ""})
43
+ add_key_if_value(dic, "b", "b")
44
+ self.assertDictEqual(dic, {"a": "", "b": "b"})
45
+ add_key_if_value(dic, "c", "c", strict=True)
46
+ self.assertDictEqual(dic, {"a": "", "b": "b", "c": "c"})
47
+
48
+ def test_all_of_dict_values(self):
49
+ self.assertListEqual(all_of_dict_values({1: None, 2: "Good", 3: "", 4: "job"}, [1, 2, 3, 4]), ["Good", "job"])
50
+ self.assertListEqual(
51
+ all_of_dict_values({1: None, 2: "Good", 3: "", 4: "job"}, [2, 4], labels=[u"Two", u"Four"]),
52
+ ["Two=Good", "Four=job"],
53
+ )
54
+ self.assertListEqual(
55
+ all_of_dict_values({1: None, 2: "Good", 3: "", 4: "job"}, [2, 4], labels=[u"Two", u""]), ["Two=Good", "job"]
56
+ )
57
+ self.assertRaises(ValueError, all_of_dict_values, {}, [1], labels=[1, 2])
58
+ self.assertListEqual(all_of_dict_values({}, [1, 2]), [])
59
+
60
+ def test_append(self):
61
+ lst = [1]
62
+ self.assertEqual(append(lst, 2), 2)
63
+ self.assertListEqual(lst, [1, 2])
64
+
65
+ def test_get_clusters(self):
66
+ self.assertEqual(get_clusters([1, 2, 3, 5, 6, 8, 10, 15]), "1-3, 5-6, 8, 10, 15")
67
+ self.assertEqual(get_clusters([1, 2, 3, 5, 5.1, 5.3, 6, 8, 10, 15]), "1-3, 5, 5.1, 5.3, 6, 8, 10, 15")
68
+ self.assertEqual(get_clusters([1, 2, 4, 5, 15], separator="|"), "1-2|4-5|15")
69
+
70
+ def test_get_ordinal_clusters(self):
71
+ self.assertEqual(get_ordinal_clusters([100, 200, 300, 500, 600, 800, 1000, 1500]), "1-3, 5-6, 8, 10, 15")
72
+ self.assertEqual(
73
+ get_ordinal_clusters([100, 200, 300, 500, 501, 503, 600, 700, 1000, 1500]), "1-3, 5-5.1, 5.3, 6-7, 10, 15"
74
+ )
75
+ self.assertEqual(
76
+ get_ordinal_clusters([100, 200, 300, 400, 500, 501, 502, 521, 522, 540, 550, 1200, 1300], separator="|"),
77
+ "1-5.2|5.21-5.22|5.40|5.50|12-13",
78
+ )
79
+ self.assertEqual(
80
+ get_ordinal_clusters(
81
+ [100, 200, 300, 301, 302, 321, 322, 340, 1199, 1200, 1300], cluster_format="from {} to {}"
82
+ ),
83
+ "from 1 to 3.2, from 3.21 to 3.22, 3.40, 11.99, from 12 to 13",
84
+ )
85
+ self.assertEqual(
86
+ get_ordinal_clusters([100, 200, 250, 400, 700], single_cluster_format="({})"), "1-2, (2.50), (4), (7)"
87
+ )
88
+ self.assertEqual(get_ordinal_clusters([10, 20, 30, 31, 32, 110, 112, 130], offset=10), "1-3.2, 11, 11.2, 13")
89
+ self.assertListEqual(
90
+ get_ordinal_clusters([100, 200, 250, 400, 700], as_str=False), [[100, 200], [250], [400], [700]]
91
+ )
92
+
93
+ def test_insert_in_ordered_dict(self):
94
+ dic = OrderedDict([("a", 1), ("b", 2)])
95
+ self.assertEqual(insert_in_ordereddict(dic, ("bad", 3)), None)
96
+ self.assertEqual(
97
+ list(insert_in_ordereddict(dic, ("c", 3), after_key="a").items()), [("a", 1), ("c", 3), ("b", 2)]
98
+ )
99
+ self.assertEqual(
100
+ list(insert_in_ordereddict(dic, ("c", 3), after_key="b").items()), [("a", 1), ("b", 2), ("c", 3)]
101
+ )
102
+ self.assertEqual(insert_in_ordereddict(dic, ("bad", 3), after_key="unk"), None)
103
+ self.assertEqual(
104
+ list(insert_in_ordereddict(dic, ("c", 3), after_key="unk", at_position=1).items()),
105
+ [("a", 1), ("c", 3), ("b", 2)],
106
+ )
107
+ self.assertEqual(
108
+ list(insert_in_ordereddict(dic, ("c", 3), at_position=0).items()), [("c", 3), ("a", 1), ("b", 2)]
109
+ )
110
+ self.assertEqual(
111
+ list(insert_in_ordereddict(dic, ("c", 3), at_position=1).items()), [("a", 1), ("c", 3), ("b", 2)]
112
+ )
113
+ self.assertEqual(
114
+ list(insert_in_ordereddict(dic, ("c", 3), at_position=10).items()), [("a", 1), ("b", 2), ("c", 3)]
115
+ )
116
+ self.assertEqual(list(insert_in_ordereddict(OrderedDict([]), ("c", 3), at_position=1).items()), [("c", 3)])
117
+ self.assertEqual(list(insert_in_ordereddict(dic, ("c", 3), at_position=-1).items()), [("a", 1), ("b", 2)])
118
+
119
+ def test_iterable_as_list_of_list(self):
120
+ lst = [1, 2, 3, 4]
121
+ self.assertListEqual(iterable_as_list_of_list(lst, 4), [lst])
122
+ self.assertListEqual(iterable_as_list_of_list(lst, 6), [lst])
123
+ self.assertListEqual(iterable_as_list_of_list(lst, 2), [[1, 2], [3, 4]])
124
+ self.assertListEqual(iterable_as_list_of_list(lst, 1), [[1], [2], [3], [4]])
125
+ self.assertListEqual(iterable_as_list_of_list(lst, 3), [[1, 2, 3], [4]])
126
+ self.assertRaises(ZeroDivisionError, iterable_as_list_of_list, lst, 0)
127
+
128
+ def test_letters_sequence(self):
129
+ tests = [
130
+ {"lt": "ab", "nths": [(0, ""), (1, "a"), (2, "b"), (3, "aa"), (6, "bb"), (9, "aba")]},
131
+ {
132
+ "lt": "abcdefghijklmnopqrstuvwxyz",
133
+ "nths": [(15, "o"), (26, "z"), (27, "aa"), (100, "cv"), (702, "zz"), (703, "aaa")],
134
+ },
135
+ ]
136
+ for dic in tests:
137
+ lt = dic["lt"]
138
+ for n, res in dic["nths"]:
139
+ self.assertEqual(
140
+ letters_sequence(n, lt), res, "n:{},res:{} <=> {}".format(n, res, letters_sequence(n, lt))
141
+ )
142
+
143
+ def test_merge_dicts(self):
144
+ self.assertEqual(merge_dicts([{"a": [1]}, {"a": [2]}]), {"a": [1, 2]})
145
+ self.assertEqual(merge_dicts([{"a": [1], "b": [0]}, {"a": [2]}]), {"a": [1, 2], "b": [0]})
146
+ self.assertEqual(
147
+ merge_dicts([{"a": [1], "b": [0]}, {"a": [2]}, {"a": [2], "b": [1], "c": [4]}]),
148
+ {"a": [1, 2, 2], "b": [0, 1], "c": [4]},
149
+ )
150
+
151
+ def test_odict_pos_key(self):
152
+ dic = OrderedDict([("a", 1), ("b", 2)])
153
+ self.assertIsNone(odict_pos_key(dic, -1))
154
+ self.assertIsNone(odict_pos_key(dic, 3))
155
+ self.assertEqual(odict_pos_key(dic, 0), "a")
156
+ self.assertEqual(odict_pos_key(dic, 1), "b")
157
+
158
+ def test_one_of_dict_values(self):
159
+ self.assertEqual(one_of_dict_values({1: None, 3: "", 4: "job"}, [1, 2, 3, 4]), "job")
160
+
161
+ def test_radix_like_starting_1(self):
162
+ # Considering a sequence of 2 letters a, b => base 2 (similar to bit values 0, 1 base 2)
163
+ self.assertListEqual(radix_like_starting_1(0, 2), []) # corresponding to nothing (bit would be 0)
164
+ self.assertListEqual(radix_like_starting_1(1, 2), [1]) # corresponding to a (bit would be 1)
165
+ self.assertListEqual(radix_like_starting_1(2, 2), [2]) # corresponding to b (bit would be 10)
166
+ self.assertListEqual(radix_like_starting_1(3, 2), [1, 1]) # corresponding to aa (bit would be 11)
167
+ self.assertListEqual(radix_like_starting_1(4, 2), [1, 2]) # corresponding to ab (bit would be 100)
168
+ self.assertListEqual(radix_like_starting_1(5, 2), [2, 1]) # corresponding to ba
169
+ self.assertListEqual(radix_like_starting_1(6, 2), [2, 2]) # corresponding to bb
170
+ self.assertListEqual(radix_like_starting_1(7, 2), [1, 1, 1]) # corresponding to aaa
171
+
172
+ def test_replace_in_list(self):
173
+ self.assertEqual(replace_in_list([1, 2, 3], 1, 4), [4, 2, 3])
174
+ self.assertEqual(replace_in_list([1, 2, 3], 4, 5), [1, 2, 3])
175
+ self.assertEqual(replace_in_list([1, 2, 3, 1], 1, 5), [5, 2, 3, 5])
176
+ # generator
177
+ res = replace_in_list([1, 2, 3], 1, 4, generator=True)
178
+ self.assertTrue(isinstance(res, types.GeneratorType))
179
+ self.assertEqual(list(res), [4, 2, 3])
180
+
181
+ def test_safe_encode(self):
182
+ self.assertEqual(safe_encode(u"xx"), "xx")
183
+ self.assertEqual(safe_encode(b"xx"), "xx")
184
+ self.assertEqual(safe_encode(5), 5)
185
+
186
+ def test_sort_by_indexes(self):
187
+ lst = ["a", "b", "c", "d", "e", "f", "g"]
188
+ indexes = [1, 3, 5, 2, 4, 6, 6]
189
+ self.assertEqual(sort_by_indexes(lst, indexes), ["a", "d", "b", "e", "c", "f", "g"])
190
+ lst = ["a", "b", "c", "d", "e"]
191
+ indexes = [1, 3, 2, 9, 9]
192
+ self.assertEqual(sort_by_indexes(lst, indexes), ["a", "c", "b", "d", "e"])
193
+
194
+ def test_listify(self):
195
+ self.assertEqual(listify("value"), ["value"])
196
+ self.assertEqual(listify(["value"]), ["value"])
197
+ self.assertEqual(listify(("value")), ["value"])
198
+ self.assertEqual(listify(("value",)), ("value",))
199
+ self.assertEqual(listify(("value",), force=True), ["value"])
200
+
201
+
202
+ class TestSystem(unittest.TestCase):
203
+ """ """
204
+
205
+ def setUp(self):
206
+ file_dir = os.path.dirname(__file__)
207
+ self.dir = file_dir.replace("/pyutils", "")
208
+
209
+ def test_read_recursive_dir(self):
210
+ res = read_recursive_dir(self.dir, "")
211
+ self.assertEqual(len([path for path in res if path.endswith(".py")]), 8)
212
+ self.assertIn("__init__.py", res)
213
+ self.assertIn("pyutils/__init__.py", res)
214
+ # include folder
215
+ self.assertNotIn("pyutils", res)
216
+ res = read_recursive_dir(self.dir, "", with_folder=True)
217
+ self.assertIn("pyutils", res)
218
+ # include full path
219
+ self.assertEqual(len([path for path in res if path.endswith("/pyutils")]), 0)
220
+ res = read_recursive_dir(self.dir, "", with_folder=True, with_full_path=True)
221
+ self.assertEqual(len([path for path in res if path.endswith("/pyutils")]), 1)
222
+ # exclude patterns
223
+ self.assertTrue([path for path in res if path.endswith(".pyc")])
224
+ res = read_recursive_dir(self.dir, "", exclude_patterns=[r"\.pyc$"])
225
+ self.assertFalse([path for path in res if path.endswith(".pyc")])
226
+ res = read_recursive_dir(self.dir, "", exclude_patterns=[r"^pyutils/", r"\.pyc$"])
227
+ self.assertEqual(len(res), 1)
228
+
229
+ def test_read_dir_filter(self):
230
+ res = read_dir_filter(self.dir)
231
+ self.assertIn("__init__.py", res)
232
+ self.assertIn("pyutils", res)
233
+ res = read_dir_filter(self.dir, with_path=True)
234
+ self.assertNotIn("__init__.py", res)
235
+ self.assertIn(os.path.join(self.dir, "__init__.py"), res)
236
+ self.assertIn(os.path.join(self.dir, "pyutils"), res)
237
+ res = read_dir_filter(self.dir, extensions=["py"])
238
+ self.assertIn("__init__.py", res)
239
+ self.assertNotIn("pyutils", res)
240
+ res = read_dir_filter(self.dir, only_folders=True)
241
+ self.assertNotIn("__init__.py", res)
242
+ self.assertIn("pyutils", res)
243
+ res = read_dir_filter(self.dir, patterns=[r".*\.py$"])
244
+ self.assertIn("__init__.py", res)
245
+ self.assertNotIn("pyutils", res)
246
+
247
+ def test_hashed_filename(self):
248
+ self.assertEqual(hashed_filename("", ""), "")
249
+ self.assertEqual(hashed_filename("test.txt", ""), "test.txt")
250
+ self.assertEqual(hashed_filename("test.txt", "", 20), "test.txt")
251
+ self.assertEqual(
252
+ hashed_filename("test.txt", "the string value to differentiate some files"),
253
+ "test_f9fde993c5b66b18fce3a03bf2bd1e11e05c598b.txt",
254
+ )
255
+ self.assertEqual(
256
+ hashed_filename("test.txt", "the string value to differentiate some file"),
257
+ "test_b99fae91a375c3b6fa36fa23a34c666f79375ffe.txt",
258
+ )
imio/pyutils/utils.py ADDED
@@ -0,0 +1,361 @@
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # python utils methods
4
+ # IMIO <support@imio.be>
5
+ #
6
+ from __future__ import print_function
7
+
8
+ from collections import defaultdict
9
+ from collections import OrderedDict
10
+ from itertools import chain
11
+ from operator import methodcaller
12
+ from six import ensure_str
13
+ from six import string_types
14
+ from six.moves import map
15
+ from six.moves import range
16
+ from six.moves import zip
17
+
18
+ import copy
19
+ import itertools
20
+ import logging
21
+ import time
22
+ import timeit
23
+
24
+
25
+ def add_key_if_value(dic, key, value, strict=False):
26
+ """Add a key to a dict only if a value or is not None.
27
+
28
+ :param dic: input dictionary
29
+ :param key: key to add
30
+ :param value: value to add
31
+ :param strict: if True, add only if value is considered boolean True
32
+ """
33
+ if strict:
34
+ if value:
35
+ dic[key] = value
36
+ elif value is not None:
37
+ dic[key] = value
38
+
39
+
40
+ def all_of_dict_values(dic, keys, labels=[], sep=u"="):
41
+ """Returns a not empty values list from a dict following given keys.
42
+
43
+ :param dic: input dictionary
44
+ :param keys: searched keys
45
+ :param labels: corresponding labels
46
+ :param sep: separator between label and value
47
+ :return: list with corresponding values.
48
+ """
49
+ if labels and len(labels) != len(keys):
50
+ raise ValueError(u"labels length must be the same as keys length")
51
+ ret = []
52
+ for i, key in enumerate(keys):
53
+ if dic.get(key):
54
+ ret.append(labels and u"{}{}{}".format(labels[i], labels[i] and sep or u"", dic[key]) or dic[key])
55
+ return ret
56
+
57
+
58
+ def append(lst, value):
59
+ lst.append(value)
60
+ return value
61
+
62
+
63
+ def ftimed(f, nb=100, fmt="{:.7f}"):
64
+ duration, ret = timed(f, nb=nb)
65
+ return fmt.format(duration), ret
66
+
67
+
68
+ def get_clusters(numbers=[], separator=", "):
69
+ """Return given p_numbers by clusters.
70
+ When p_numbers=[1,2,3,5,6,8,9,10,15,17,20],
71
+ the result is '1-3, 5-6, 8-10, 15, 17, 20'."""
72
+ clusters = itertools.groupby(numbers, lambda n, c=itertools.count(): n - next(c))
73
+ res = []
74
+ for group, cluster in clusters:
75
+ clust = list(cluster)
76
+ if len(clust) > 1:
77
+ res.append("{0}-{1}".format(clust[0], clust[-1]))
78
+ else:
79
+ res.append("{0}".format(clust[0]))
80
+ return separator.join(res)
81
+
82
+
83
+ def display_offset_number(number, offset):
84
+ """Display a number with an offset. For example when p_number=123 and offset=100, it returns '1.23'"""
85
+ if number % offset == 0:
86
+ return str(int(number / offset))
87
+ return "{}.{}".format(number // offset, number % offset)
88
+
89
+
90
+ def get_ordinal_clusters(
91
+ numbers=[], cluster_format="{0}-{1}", single_cluster_format="{0}", separator=", ", offset=100, as_str=True
92
+ ):
93
+ """Return given p_numbers by clusters while taking care of the offset (used for sub numering).
94
+ p_offset should be a power of 10, it doesn't make any sense otherwise.
95
+ When p_numbers=[100,200,300,400,500,501,502,521,522,540,550,700,1200,1300] and p_offset=100,
96
+ the result is '1-5.2, 5.21-5.22, 5.40, 5.50, 7, 12-13'."""
97
+
98
+ def _is_in_cluster(number, cluster, offset):
99
+ """Check if a number is in a cluster.
100
+ A number is in a cluster if it follows directly the last number according to the offset"""
101
+ if len(cluster) > 0:
102
+ if number % offset == 0:
103
+ return number - cluster[-1] == offset
104
+ return number - cluster[-1] == 1
105
+ return True
106
+
107
+ # Initialize the first group
108
+ clusters = []
109
+ current_cluster = [numbers[0]]
110
+ for num in numbers[1:]:
111
+ if _is_in_cluster(num, current_cluster, offset):
112
+ current_cluster.append(num)
113
+ else: # we'll start a new cluster
114
+ clusters.append(current_cluster)
115
+ current_cluster = [num]
116
+ clusters.append(current_cluster) # Add the last one
117
+
118
+ if not as_str:
119
+ return clusters
120
+
121
+ res = []
122
+ for cluster in clusters:
123
+ if len(cluster) > 1:
124
+ res.append(
125
+ cluster_format.format(
126
+ display_offset_number(cluster[0], offset), display_offset_number(cluster[-1], offset)
127
+ )
128
+ )
129
+ else:
130
+ res.append(single_cluster_format.format(display_offset_number(cluster[0], offset)))
131
+ return separator.join(res)
132
+
133
+
134
+ def insert_in_ordereddict(dic, value, after_key="", at_position=None):
135
+ """Insert a tuple in an new Ordereddict.
136
+
137
+ :param dic: the original OrderedDict
138
+ :param value: a tuple (key, value) that will be added at correct position
139
+ :param after_key: key name after which the tup is added
140
+ :param at_position: position at which the tup is added. Is also a default if after_key is not found
141
+ :return: a new OrderedDict or None if insertion position is undefined
142
+ """
143
+ position = None
144
+ if after_key:
145
+ position = odict_index(dic, after_key, delta=1)
146
+ if position is None and at_position is not None:
147
+ position = at_position
148
+ if position is None:
149
+ return None
150
+ if position >= len(list(dic.keys())):
151
+ return OrderedDict(list(dic.items()) + [value])
152
+ tuples = []
153
+ for i, tup in enumerate(dic.items()):
154
+ if i == position:
155
+ tuples.append(value)
156
+ tuples.append(tup)
157
+ if not tuples: # dic was empty
158
+ tuples.append(value)
159
+ return OrderedDict(tuples)
160
+
161
+
162
+ def iterable_as_list_of_list(lst, cols=1):
163
+ """Transform an iterable as list of list.
164
+
165
+ :param lst: input iterable
166
+ :param cols: number of columns in the sublists
167
+ :return: list of lists
168
+ """
169
+ res = []
170
+ sublist = []
171
+ for i, item in enumerate(lst, start=1):
172
+ sublist.append(item)
173
+ if not i % cols:
174
+ if sublist:
175
+ res.append(sublist)
176
+ sublist = []
177
+ # put the last sublist in res
178
+ if sublist:
179
+ res.append(sublist)
180
+ return res
181
+
182
+
183
+ def letters_sequence(nth, letters="abcdefghijklmnopqrstuvwxyz"):
184
+ """Return a letters sequence corresponding to the nth number. Useful to generate a lettered suffix.
185
+
186
+ :param nth: nth sequence (0 giving nothing and 1 the first letter)
187
+ :param letters: letters to consider
188
+ :return: a sequenced string
189
+ """
190
+ res = ""
191
+ for pos in radix_like_starting_1(nth, len(letters)):
192
+ res += letters[pos - 1]
193
+ return res
194
+
195
+
196
+ def merge_dicts(dicts, as_dict=True):
197
+ """Merge dicts, extending values of each dicts,
198
+ useful for example when the value is a list.
199
+
200
+ :param dicts: the list of dicts to mergeinput iterable
201
+ :param as_dict: return a dict instead the defaultdict instance
202
+ :return: a single dict (or defaultdict)
203
+ """
204
+ dd = defaultdict(list)
205
+
206
+ # iterate dictionary items
207
+ dict_items = list(map(methodcaller("items"), dicts))
208
+ for k, v in chain.from_iterable(dict_items):
209
+ dd[k].extend(v)
210
+ return as_dict and dict(dd) or dd
211
+
212
+
213
+ def odict_index(odic, key, delta=0):
214
+ """Get key position in an ordereddict"""
215
+ for i, k in enumerate(odic):
216
+ if k == key:
217
+ return i + delta
218
+ return None
219
+
220
+
221
+ def odict_pos_key(odic, pos):
222
+ """Get key corresponding at position"""
223
+ keys = [k for k in odic]
224
+ if pos < 0 or pos >= len(keys):
225
+ return None
226
+ else:
227
+ return keys[pos]
228
+
229
+
230
+ def one_of_dict_values(dic, keys):
231
+ """Take the first value not empty in a dict following given keys"""
232
+ for key in keys:
233
+ if dic.get(key):
234
+ return dic[key]
235
+ return None
236
+
237
+
238
+ def radix_like_starting_1(n, base, L=[]): # noqa
239
+ """Returns a list of positional numbers following a given base but starting with 1 and not 0.
240
+ It's like normal base positions but ignoring 0. Useful for non mathematical sequence (a b aa ab ba bb ...)
241
+
242
+ :param n: the number to analyze
243
+ :param base: the base to use
244
+ :param L: the working list (mist not be originally filled)
245
+ :return: a list of positional numbers
246
+ """
247
+ if n <= 0:
248
+ L.reverse()
249
+ return L
250
+ else:
251
+ return radix_like_starting_1((n % base) and (n // base) or (n // base) - 1, base, L + [(n % base) or base])
252
+
253
+
254
+ def replace_in_list(lst, value, replacement, generator=False):
255
+ """Replace a value in a list of values.
256
+
257
+ :param lst: the list containing value to replace
258
+ :param value: the value to be replaced
259
+ :param replacement: the new value to replace with
260
+ :param generator: will return a generator instead a list when set to True
261
+ :return: a new list/generator with replaced values
262
+ """
263
+
264
+ def _replacer(lst, value, replacement):
265
+ new_lst = list(lst)
266
+ for item in new_lst:
267
+ if item == value:
268
+ yield replacement
269
+ else:
270
+ yield item
271
+
272
+ res = _replacer(lst, value, replacement)
273
+ if not generator:
274
+ res = list(res)
275
+ return res
276
+
277
+
278
+ def safe_encode(value, encoding="utf-8"):
279
+ """Converts a value to encoding, only when it is not already encoded."""
280
+ try:
281
+ return ensure_str(value, encoding=encoding)
282
+ except TypeError:
283
+ return value
284
+
285
+
286
+ def setup_logger(logger, replace=logging.StreamHandler, level=20):
287
+ """Modify logger handler level
288
+
289
+ :param logger: logger to modify
290
+ :param replace: handler type to replace
291
+ :param level: level to set
292
+ """
293
+ for i_c, container in enumerate((logger, logger.parent)):
294
+ found = [i for i, hdl in enumerate(container.handlers) if isinstance(hdl, logging.StreamHandler)]
295
+ if found:
296
+ if i_c:
297
+ logger.parent = container = copy.copy(logger.parent)
298
+ break
299
+ else:
300
+ return
301
+ idx = found[0]
302
+ osh = copy.copy(container.handlers[idx])
303
+ osh.setLevel(level)
304
+ # remove handler from original container handlers (often parent)
305
+ container.handlers = [hdl for i, hdl in enumerate(container.handlers) if i != idx]
306
+ # put handler in logger handlers
307
+ logger.handlers.append(osh)
308
+ logger.setLevel(level)
309
+
310
+
311
+ def sort_by_indexes(lst, indexes, reverse=False):
312
+ """Sort a list following a second list containing the order"""
313
+ return [val for (_, val) in sorted(zip(indexes, lst), key=lambda x: x[0], reverse=reverse)]
314
+
315
+
316
+ def timed(f, nb=100): # TODO must be removed and replaced by timeit
317
+ start = time.time()
318
+ for i in range(nb):
319
+ ret = f()
320
+ return (time.time() - start) / nb, ret # difference of time is float
321
+
322
+
323
+ def time_elapsed(start, cond=True, msg=u"", dec=3, min=0.0):
324
+ """Print elapsed time from start.
325
+
326
+ :param start: start time gotten from time_start function
327
+ :param cond: print condition
328
+ :param msg: message to include in print
329
+ :param dec: decimal precision (default to 3)
330
+ :param min: minimal elapsed value print
331
+
332
+ Usage:
333
+ from imio.pyutils.utils import time_elapsed, time_start
334
+ start = time_start()
335
+ ...
336
+ time_elapsed(start, cond=obj.id=='myid', msg=u'myfunc')
337
+ """
338
+ if not cond:
339
+ return
340
+ elapsed = timeit.default_timer() - start
341
+ if elapsed < min:
342
+ return
343
+ print((u"* {{}}: {{:.{}f}} seconds".format(dec).format(msg, elapsed)))
344
+
345
+
346
+ def time_start():
347
+ """To be used with time_elapsed."""
348
+ return timeit.default_timer()
349
+
350
+
351
+ def listify(value, force=False):
352
+ """Ensure given value is a list-like iterable.
353
+
354
+ :param value: the value to turn into a list if not already the case
355
+ :param force: if value is a tuple, returned as a list
356
+ """
357
+ if isinstance(value, string_types):
358
+ value = [value]
359
+ if force and not isinstance(value, list):
360
+ value = list(value)
361
+ return value
@@ -0,0 +1 @@
1
+ import sys, types, os;p = os.path.join(sys._getframe(1).f_locals['sitedir'], *('imio',));importlib = __import__('importlib.util');__import__('importlib.machinery');m = sys.modules.setdefault('imio', importlib.util.module_from_spec(importlib.machinery.PathFinder.find_spec('imio', [os.path.dirname(p)])));m = m or sys.modules.setdefault('imio', types.ModuleType('imio'));mp = (m or []) and m.__dict__.setdefault('__path__',[]);(p not in mp) and mp.append(p)