DIRAC 9.0.0a64__py3-none-any.whl → 9.0.0a67__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.
Files changed (47) hide show
  1. DIRAC/ConfigurationSystem/Client/LocalConfiguration.py +11 -8
  2. DIRAC/ConfigurationSystem/Client/VOMS2CSSynchronizer.py +1 -1
  3. DIRAC/Core/Security/IAMService.py +4 -3
  4. DIRAC/Core/Utilities/ClassAd/ClassAdLight.py +4 -290
  5. DIRAC/Core/Utilities/DErrno.py +5 -309
  6. DIRAC/Core/Utilities/JDL.py +1 -195
  7. DIRAC/Core/Utilities/List.py +1 -127
  8. DIRAC/Core/Utilities/ReturnValues.py +7 -252
  9. DIRAC/Core/Utilities/StateMachine.py +12 -178
  10. DIRAC/Core/Utilities/TimeUtilities.py +10 -253
  11. DIRAC/Core/Utilities/test/Test_JDL.py +0 -3
  12. DIRAC/Core/scripts/dirac_agent.py +1 -1
  13. DIRAC/DataManagementSystem/DB/FTS3DB.py +3 -0
  14. DIRAC/RequestManagementSystem/DB/test/RMSTestScenari.py +2 -0
  15. DIRAC/Resources/Catalog/RucioFileCatalogClient.py +1 -1
  16. DIRAC/Resources/Computing/test/Test_PoolComputingElement.py +2 -1
  17. DIRAC/TransformationSystem/Agent/TransformationCleaningAgent.py +1 -1
  18. DIRAC/Workflow/Modules/test/Test_Modules.py +5 -0
  19. DIRAC/WorkloadManagementSystem/Agent/JobCleaningAgent.py +1 -1
  20. DIRAC/WorkloadManagementSystem/Agent/StalledJobAgent.py +1 -1
  21. DIRAC/WorkloadManagementSystem/Agent/test/Test_Agent_JobAgent.py +2 -0
  22. DIRAC/WorkloadManagementSystem/Agent/test/Test_Agent_PushJobAgent.py +1 -0
  23. DIRAC/WorkloadManagementSystem/Client/JobState/JobManifest.py +32 -261
  24. DIRAC/WorkloadManagementSystem/Client/JobStatus.py +8 -93
  25. DIRAC/WorkloadManagementSystem/DB/JobDBUtils.py +18 -147
  26. DIRAC/WorkloadManagementSystem/DB/StatusUtils.py +125 -0
  27. DIRAC/WorkloadManagementSystem/DB/tests/Test_StatusUtils.py +28 -0
  28. DIRAC/WorkloadManagementSystem/JobWrapper/JobWrapper.py +4 -2
  29. DIRAC/WorkloadManagementSystem/JobWrapper/test/Test_JobWrapper.py +21 -5
  30. DIRAC/WorkloadManagementSystem/JobWrapper/test/Test_JobWrapperTemplate.py +4 -0
  31. DIRAC/WorkloadManagementSystem/Service/JobManagerHandler.py +1 -1
  32. DIRAC/WorkloadManagementSystem/Utilities/JobModel.py +28 -199
  33. DIRAC/WorkloadManagementSystem/Utilities/JobStatusUtility.py +1 -63
  34. DIRAC/WorkloadManagementSystem/Utilities/ParametricJob.py +7 -171
  35. DIRAC/WorkloadManagementSystem/Utilities/jobAdministration.py +0 -123
  36. DIRAC/WorkloadManagementSystem/Utilities/test/Test_JobModel.py +1 -5
  37. DIRAC/WorkloadManagementSystem/Utilities/test/Test_ParametricJob.py +45 -128
  38. DIRAC/__init__.py +55 -54
  39. {dirac-9.0.0a64.dist-info → dirac-9.0.0a67.dist-info}/METADATA +2 -1
  40. {dirac-9.0.0a64.dist-info → dirac-9.0.0a67.dist-info}/RECORD +44 -45
  41. DIRAC/Core/Utilities/test/Test_List.py +0 -150
  42. DIRAC/Core/Utilities/test/Test_Time.py +0 -88
  43. DIRAC/WorkloadManagementSystem/Utilities/test/Test_JobAdministration.py +0 -28
  44. {dirac-9.0.0a64.dist-info → dirac-9.0.0a67.dist-info}/WHEEL +0 -0
  45. {dirac-9.0.0a64.dist-info → dirac-9.0.0a67.dist-info}/entry_points.txt +0 -0
  46. {dirac-9.0.0a64.dist-info → dirac-9.0.0a67.dist-info}/licenses/LICENSE +0 -0
  47. {dirac-9.0.0a64.dist-info → dirac-9.0.0a67.dist-info}/top_level.txt +0 -0
@@ -37,320 +37,16 @@
37
37
  DErrno.ERRX : ['An error message for ERRX that is specific to LHCb']}
38
38
 
39
39
  """
40
- import os
41
40
  import importlib
42
41
  import sys
43
42
 
44
- from DIRAC.Core.Utilities.Extensions import extensionsByPriority
45
-
46
- # To avoid conflict, the error numbers should be greater than 1000
47
- # We decided to group the by range of 100 per system
48
-
49
- # 1000: Generic
50
- # 1100: Core
51
- # 1200: Framework
52
- # 1300: Interfaces
53
- # 1400: Config
54
- # 1500: WMS + Workflow
55
- # 1600: DMS + StorageManagement
56
- # 1700: RMS
57
- # 1800: Accounting + Monitoring
58
- # 1900: TS + Production
59
- # 2000: Resources + RSS
60
-
61
- # ## Generic (10XX)
62
- # Python related: 0X
63
- ETYPE = 1000
64
- EIMPERR = 1001
65
- ENOMETH = 1002
66
- ECONF = 1003
67
- EVALUE = 1004
68
- EEEXCEPTION = 1005
69
- # Files manipulation: 1X
70
- ECTMPF = 1010
71
- EOF = 1011
72
- ERF = 1012
73
- EWF = 1013
74
- ESPF = 1014
75
-
76
- # ## Core (11XX)
77
- # Certificates and Proxy: 0X
78
- EX509 = 1100
79
- EPROXYFIND = 1101
80
- EPROXYREAD = 1102
81
- ECERTFIND = 1103
82
- ECERTREAD = 1104
83
- ENOCERT = 1105
84
- ENOCHAIN = 1106
85
- ENOPKEY = 1107
86
- ENOGROUP = 1108
87
- # DISET: 1X
88
- EDISET = 1110
89
- ENOAUTH = 1111
90
- # 3rd party security: 2X
91
- E3RDPARTY = 1120
92
- EVOMS = 1121
93
- # Databases : 3X
94
- EDB = 1130
95
- EMYSQL = 1131
96
- ESQLA = 1132
97
- # Message Queues: 4X
98
- EMQUKN = 1140
99
- EMQNOM = 1141
100
- EMQCONN = 1142
101
- # OpenSearch
102
- EELNOFOUND = 1146
103
- # Tokens
104
- EATOKENFIND = 1150
105
- EATOKENREAD = 1151
106
- ETOKENTYPE = 1152
107
-
108
- # config
109
- ESECTION = 1400
110
-
111
- # processes
112
- EEZOMBIE = 1147
113
- EENOPID = 1148
114
-
115
- # ## WMS/Workflow
116
- EWMSUKN = 1500
117
- EWMSJDL = 1501
118
- EWMSRESC = 1502
119
- EWMSSUBM = 1503
120
- EWMSJMAN = 1504
121
- EWMSSTATUS = 1505
122
- EWMSNOMATCH = 1510
123
- EWMSPLTVER = 1511
124
- EWMSNOPILOT = 1550
125
-
126
- # ## DMS/StorageManagement (16XX)
127
- EFILESIZE = 1601
128
- EGFAL = 1602
129
- EBADCKS = 1603
130
- EFCERR = 1604
131
-
132
- # ## RMS (17XX)
133
- ERMSUKN = 1700
134
-
135
- # ## TS (19XX)
136
- ETSUKN = 1900
137
- ETSDATA = 1901
138
-
139
- # ## Resources and RSS (20XX)
140
- ERESGEN = 2000
141
- ERESUNA = 2001
142
- ERESUNK = 2002
143
-
144
- # This translates the integer number into the name of the variable
145
- dErrorCode = {
146
- # ## Generic (10XX)
147
- # 100X: Python related
148
- 1000: "ETYPE",
149
- 1001: "EIMPERR",
150
- 1002: "ENOMETH",
151
- 1003: "ECONF",
152
- 1004: "EVALUE",
153
- 1005: "EEEXCEPTION",
154
- # 101X: Files manipulation
155
- 1010: "ECTMPF",
156
- 1011: "EOF",
157
- 1012: "ERF",
158
- 1013: "EWF",
159
- 1014: "ESPF",
160
- # ## Core
161
- # 110X: Certificates and Proxy
162
- 1100: "EX509",
163
- 1101: "EPROXYFIND",
164
- 1102: "EPROXYREAD",
165
- 1103: "ECERTFIND",
166
- 1104: "ECERTREAD",
167
- 1105: "ENOCERT",
168
- 1106: "ENOCHAIN",
169
- 1107: "ENOPKEY",
170
- 1108: "ENOGROUP",
171
- # 111X: DISET
172
- 1110: "EDISET",
173
- 1111: "ENOAUTH",
174
- # 112X: 3rd party security
175
- 1120: "E3RDPARTY",
176
- 1121: "EVOMS",
177
- # 113X: Databases
178
- 1130: "EDB",
179
- 1131: "EMYSQL",
180
- 1132: "ESQLA",
181
- # 114X: Message Queues
182
- 1140: "EMQUKN",
183
- 1141: "EMQNOM",
184
- 1142: "EMQCONN",
185
- # OpenSearch
186
- 1146: "EELNOFOUND",
187
- # 115X: Tokens
188
- 1150: "EATOKENFIND",
189
- 1151: "EATOKENREAD",
190
- 1152: "ETOKENTYPE",
191
- # Config
192
- 1400: "ESECTION",
193
- # Processes
194
- 1147: "EEZOMBIE",
195
- 1148: "EENOPID",
196
- # WMS/Workflow
197
- 1500: "EWMSUKN",
198
- 1501: "EWMSJDL",
199
- 1502: "EWMSRESC",
200
- 1503: "EWMSSUBM",
201
- 1504: "EWMSJMAN",
202
- 1505: "EWMSSTATUS",
203
- 1510: "EWMSNOMATCH",
204
- 1511: "EWMSPLTVER",
205
- 1550: "EWMSNOPILOT",
206
- # DMS/StorageManagement
207
- 1601: "EFILESIZE",
208
- 1602: "EGFAL",
209
- 1603: "EBADCKS",
210
- 1604: "EFCERR",
211
- # RMS
212
- 1700: "ERMSUKN",
213
- # Resources and RSS
214
- 2000: "ERESGEN",
215
- 2001: "ERESUNA",
216
- 2002: "ERESUNK",
217
- # TS
218
- 1900: "ETSUKN",
219
- 1901: "ETSDATA",
220
- }
221
-
222
-
223
- dStrError = { # Generic (10XX)
224
- # 100X: Python related
225
- ETYPE: "Object Type Error",
226
- EIMPERR: "Failed to import library",
227
- ENOMETH: "No such method or function",
228
- ECONF: "Configuration error",
229
- EVALUE: "Wrong value passed",
230
- EEEXCEPTION: "runtime general exception",
231
- # 101X: Files manipulation
232
- ECTMPF: "Failed to create temporary file",
233
- EOF: "Cannot open file",
234
- ERF: "Cannot read from file",
235
- EWF: "Cannot write to file",
236
- ESPF: "Cannot set permissions to file",
237
- # ## Core
238
- # 110X: Certificates and Proxy
239
- EX509: "Generic Error with X509",
240
- EPROXYFIND: "Can't find proxy",
241
- EPROXYREAD: "Can't read proxy",
242
- ECERTFIND: "Can't find certificate",
243
- ECERTREAD: "Can't read certificate",
244
- ENOCERT: "No certificate loaded",
245
- ENOCHAIN: "No chain loaded",
246
- ENOPKEY: "No private key loaded",
247
- ENOGROUP: "No DIRAC group",
248
- # 111X: DISET
249
- EDISET: "DISET Error",
250
- ENOAUTH: "Unauthorized query",
251
- # 112X: 3rd party security
252
- E3RDPARTY: "3rd party security service error",
253
- EVOMS: "VOMS Error",
254
- # 113X: Databases
255
- EDB: "Database Error",
256
- EMYSQL: "MySQL Error",
257
- ESQLA: "SQLAlchemy Error",
258
- # 114X: Message Queues
259
- EMQUKN: "Unknown MQ Error",
260
- EMQNOM: "No messages",
261
- EMQCONN: "MQ connection failure",
262
- # 114X OpenSearch
263
- EELNOFOUND: "Index not found",
264
- # 115X: Tokens
265
- EATOKENFIND: "Can't find a bearer access token.",
266
- EATOKENREAD: "Can't read a bearer access token.",
267
- ETOKENTYPE: "Unsupported access token type.",
268
- # Config
269
- ESECTION: "Section is not found",
270
- # processes
271
- EEZOMBIE: "Zombie process",
272
- EENOPID: "No PID of process",
273
- # WMS/Workflow
274
- EWMSUKN: "Unknown WMS error",
275
- EWMSJDL: "Invalid job description",
276
- EWMSRESC: "Job to reschedule",
277
- EWMSSUBM: "Job submission error",
278
- EWMSJMAN: "Job management error",
279
- EWMSSTATUS: "Job status error",
280
- EWMSNOPILOT: "No pilots found",
281
- EWMSPLTVER: "Pilot version does not match",
282
- EWMSNOMATCH: "No match found",
283
- # DMS/StorageManagement
284
- EFILESIZE: "Bad file size",
285
- EGFAL: "Error with the gfal call",
286
- EBADCKS: "Bad checksum",
287
- EFCERR: "FileCatalog error",
288
- # RMS
289
- ERMSUKN: "Unknown RMS error",
290
- # Resources and RSS
291
- ERESGEN: "Unknown Resource Failure",
292
- ERESUNA: "Resource not available",
293
- ERESUNK: "Unknown Resource",
294
- # TS
295
- ETSUKN: "Unknown Transformation System Error",
296
- ETSDATA: "Invalid Input Data definition",
297
- }
43
+ # Import all the stateless parts from DIRACCommon
44
+ from DIRACCommon.Core.Utilities.DErrno import * # noqa: F401, F403
298
45
 
46
+ from DIRAC.Core.Utilities.Extensions import extensionsByPriority
299
47
 
300
- def strerror(code: int) -> str:
301
- """This method wraps up os.strerror, and behave the same way.
302
- It completes it with the DIRAC specific errors.
303
- """
304
-
305
- if code == 0:
306
- return "Undefined error"
307
-
308
- errMsg = f"Unknown error {code}"
309
-
310
- try:
311
- errMsg = dStrError[code]
312
- except KeyError:
313
- # It is not a DIRAC specific error, try the os one
314
- try:
315
- errMsg = os.strerror(code)
316
- # On some system, os.strerror raises an exception with unknown code,
317
- # on others, it returns a message...
318
- except ValueError:
319
- pass
320
-
321
- return errMsg
322
-
323
-
324
- def cmpError(inErr, candidate):
325
- """This function compares an error (in its old form (a string or dictionary) or in its int form
326
- with a candidate error code.
327
-
328
- :param inErr: a string, an integer, a S_ERROR dictionary
329
- :type inErr: str or int or S_ERROR
330
- :param int candidate: error code to compare with
331
-
332
- :return: True or False
333
-
334
- If an S_ERROR instance is passed, we compare the code with S_ERROR['Errno']
335
- If it is a Integer, we do a direct comparison
336
- If it is a String, we use strerror to check the error string
337
- """
338
-
339
- if isinstance(inErr, str): # old style
340
- # Compare error message strings
341
- errMsg = strerror(candidate)
342
- return errMsg in inErr
343
- elif isinstance(inErr, dict): # if the S_ERROR structure is given
344
- # Check if Errno defined in the dict
345
- errorNumber = inErr.get("Errno")
346
- if errorNumber:
347
- return errorNumber == candidate
348
- errMsg = strerror(candidate)
349
- return errMsg in inErr.get("Message", "")
350
- elif isinstance(inErr, int):
351
- return inErr == candidate
352
- else:
353
- raise TypeError(f"Unknown input error type {type(inErr)}")
48
+ # compatErrorString is used by the extension mechanism but not in DIRACCommon
49
+ compatErrorString = {}
354
50
 
355
51
 
356
52
  def includeExtensionErrors():
@@ -1,203 +1,9 @@
1
1
  """Transformation classes around the JDL format."""
2
2
 
3
- from diraccfg import CFG
4
- from pydantic import ValidationError
3
+ from DIRACCommon.Core.Utilities.JDL import * # noqa: F403,F401
5
4
 
6
- from DIRAC import S_OK, S_ERROR
7
- from DIRAC.Core.Utilities import List
8
- from DIRAC.Core.Utilities.ClassAd.ClassAdLight import ClassAd
9
5
  from DIRAC.WorkloadManagementSystem.Utilities.JobModel import BaseJobDescriptionModel
10
6
 
11
- ARGUMENTS = "Arguments"
12
- BANNED_SITES = "BannedSites"
13
- CPU_TIME = "CPUTime"
14
- EXECUTABLE = "Executable"
15
- EXECUTION_ENVIRONMENT = "ExecutionEnvironment"
16
- GRID_CE = "GridCE"
17
- INPUT_DATA = "InputData"
18
- INPUT_DATA_POLICY = "InputDataPolicy"
19
- INPUT_SANDBOX = "InputSandbox"
20
- JOB_CONFIG_ARGS = "JobConfigArgs"
21
- JOB_TYPE = "JobType"
22
- JOB_GROUP = "JobGroup"
23
- LOG_LEVEL = "LogLevel"
24
- NUMBER_OF_PROCESSORS = "NumberOfProcessors"
25
- MAX_NUMBER_OF_PROCESSORS = "MaxNumberOfProcessors"
26
- MIN_NUMBER_OF_PROCESSORS = "MinNumberOfProcessors"
27
- OUTPUT_DATA = "OutputData"
28
- OUTPUT_PATH = "OutputPath"
29
- OUTPUT_SE = "OutputSE"
30
- PLATFORM = "Platform"
31
- PRIORITY = "Priority"
32
- STD_ERROR = "StdError"
33
- STD_OUTPUT = "StdOutput"
34
- OUTPUT_SANDBOX = "OutputSandbox"
35
- JOB_NAME = "JobName"
36
- SITE = "Site"
37
- TAGS = "Tags"
38
-
39
- OWNER = "Owner"
40
- OWNER_GROUP = "OwnerGroup"
41
- VO = "VirtualOrganization"
42
-
43
- CREDENTIALS_FIELDS = {OWNER, OWNER_GROUP, VO}
44
-
45
-
46
- def loadJDLAsCFG(jdl):
47
- """
48
- Load a JDL as CFG
49
- """
50
-
51
- def cleanValue(value):
52
- value = value.strip()
53
- if value[0] == '"':
54
- entries = []
55
- iPos = 1
56
- current = ""
57
- state = "in"
58
- while iPos < len(value):
59
- if value[iPos] == '"':
60
- if state == "in":
61
- entries.append(current)
62
- current = ""
63
- state = "out"
64
- elif state == "out":
65
- current = current.strip()
66
- if current not in (",",):
67
- return S_ERROR("value seems a list but is not separated in commas")
68
- current = ""
69
- state = "in"
70
- else:
71
- current += value[iPos]
72
- iPos += 1
73
- if state == "in":
74
- return S_ERROR('value is opened with " but is not closed')
75
- return S_OK(", ".join(entries))
76
- else:
77
- return S_OK(value.replace('"', ""))
78
-
79
- def assignValue(key, value, cfg):
80
- key = key.strip()
81
- if len(key) == 0:
82
- return S_ERROR("Invalid key name")
83
- value = value.strip()
84
- if not value:
85
- return S_ERROR(f"No value for key {key}")
86
- if value[0] == "{":
87
- if value[-1] != "}":
88
- return S_ERROR("Value '%s' seems a list but does not end in '}'" % (value))
89
- valList = List.fromChar(value[1:-1])
90
- for i in range(len(valList)):
91
- result = cleanValue(valList[i])
92
- if not result["OK"]:
93
- return S_ERROR(f"Var {key} : {result['Message']}")
94
- valList[i] = result["Value"]
95
- if valList[i] is None:
96
- return S_ERROR(f"List value '{value}' seems invalid for item {i}")
97
- value = ", ".join(valList)
98
- else:
99
- result = cleanValue(value)
100
- if not result["OK"]:
101
- return S_ERROR(f"Var {key} : {result['Message']}")
102
- nV = result["Value"]
103
- if nV is None:
104
- return S_ERROR(f"Value '{value} seems invalid")
105
- value = nV
106
- cfg.setOption(key, value)
107
- return S_OK()
108
-
109
- if jdl[0] == "[":
110
- iPos = 1
111
- else:
112
- iPos = 0
113
- key = ""
114
- value = ""
115
- action = "key"
116
- insideLiteral = False
117
- cfg = CFG()
118
- while iPos < len(jdl):
119
- char = jdl[iPos]
120
- if char == ";" and not insideLiteral:
121
- if key.strip():
122
- result = assignValue(key, value, cfg)
123
- if not result["OK"]:
124
- return result
125
- key = ""
126
- value = ""
127
- action = "key"
128
- elif char == "[" and not insideLiteral:
129
- key = key.strip()
130
- if not key:
131
- return S_ERROR("Invalid key in JDL")
132
- if value.strip():
133
- return S_ERROR(f"Key {key} seems to have a value and open a sub JDL at the same time")
134
- result = loadJDLAsCFG(jdl[iPos:])
135
- if not result["OK"]:
136
- return result
137
- subCfg, subPos = result["Value"]
138
- cfg.createNewSection(key, contents=subCfg)
139
- key = ""
140
- value = ""
141
- action = "key"
142
- insideLiteral = False
143
- iPos += subPos
144
- elif char == "=" and not insideLiteral:
145
- if action == "key":
146
- action = "value"
147
- insideLiteral = False
148
- else:
149
- value += char
150
- elif char == "]" and not insideLiteral:
151
- key = key.strip()
152
- if len(key) > 0:
153
- result = assignValue(key, value, cfg)
154
- if not result["OK"]:
155
- return result
156
- return S_OK((cfg, iPos))
157
- else:
158
- if action == "key":
159
- key += char
160
- else:
161
- value += char
162
- if char == '"':
163
- insideLiteral = not insideLiteral
164
- iPos += 1
165
-
166
- return S_OK((cfg, iPos))
167
-
168
-
169
- def dumpCFGAsJDL(cfg, level=1, tab=" "):
170
- indent = tab * level
171
- contents = [f"{tab * (level - 1)}["]
172
- sections = cfg.listSections()
173
-
174
- for key in cfg:
175
- if key in sections:
176
- contents.append(f"{indent}{key} =")
177
- contents.append(f"{dumpCFGAsJDL(cfg[key], level + 1, tab)};")
178
- else:
179
- val = List.fromChar(cfg[key])
180
- # Some attributes are never lists
181
- if len(val) < 2 or key in [ARGUMENTS, EXECUTABLE, STD_OUTPUT, STD_ERROR]:
182
- value = cfg[key]
183
- try:
184
- try_value = float(value)
185
- contents.append(f"{tab * level}{key} = {value};")
186
- except Exception:
187
- contents.append(f'{tab * level}{key} = "{value}";')
188
- else:
189
- contents.append(f"{indent}{key} =")
190
- contents.append("%s{" % indent)
191
- for iPos in range(len(val)):
192
- try:
193
- value = float(val[iPos])
194
- except Exception:
195
- val[iPos] = f'"{val[iPos]}"'
196
- contents.append(",\n".join([f"{tab * (level + 1)}{value}" for value in val]))
197
- contents.append("%s};" % indent)
198
- contents.append(f"{tab * (level - 1)}]")
199
- return "\n".join(contents)
200
-
201
7
 
202
8
  def jdlToBaseJobDescriptionModel(classAd: ClassAd):
203
9
  """
@@ -1,127 +1 @@
1
- """Collection of DIRAC useful list related modules.
2
- By default on Error they return None.
3
- """
4
- import random
5
- import sys
6
- from typing import Any, TypeVar
7
- from collections.abc import Iterable
8
-
9
- T = TypeVar("T")
10
-
11
-
12
- def uniqueElements(aList: list) -> list:
13
- """Utility to retrieve list of unique elements in a list (order is kept)."""
14
-
15
- # Use dict.fromkeys instead of set ensure the order is preserved
16
- return list(dict.fromkeys(aList))
17
-
18
-
19
- def appendUnique(aList: list, anObject: Any):
20
- """Append to list if object does not exist.
21
-
22
- :param aList: list of elements
23
- :param anObject: object you want to append
24
- """
25
- if anObject not in aList:
26
- aList.append(anObject)
27
-
28
-
29
- def fromChar(inputString: str, sepChar: str = ","):
30
- """Generates a list splitting a string by the required character(s)
31
- resulting string items are stripped and empty items are removed.
32
-
33
- :param inputString: list serialised to string
34
- :param sepChar: separator
35
- :return: list of strings or None if sepChar has a wrong type
36
- """
37
- # to prevent getting an empty String as argument
38
- if not (isinstance(inputString, str) and isinstance(sepChar, str) and sepChar):
39
- return None
40
- return [fieldString.strip() for fieldString in inputString.split(sepChar) if len(fieldString.strip()) > 0]
41
-
42
-
43
- def randomize(aList: Iterable[T]) -> list[T]:
44
- """Return a randomly sorted list.
45
-
46
- :param aList: list to permute
47
- """
48
- tmpList = list(aList)
49
- random.shuffle(tmpList)
50
- return tmpList
51
-
52
-
53
- def pop(aList, popElement):
54
- """Pop the first element equal to popElement from the list.
55
-
56
- :param aList: list
57
- :type aList: python:list
58
- :param popElement: element to pop
59
- """
60
- if popElement in aList:
61
- return aList.pop(aList.index(popElement))
62
-
63
-
64
- def stringListToString(aList: list) -> str:
65
- """This function is used for making MySQL queries with a list of string elements.
66
-
67
- :param aList: list to be serialized to string for making queries
68
- """
69
- return ",".join(f"'{x}'" for x in aList)
70
-
71
-
72
- def intListToString(aList: list) -> str:
73
- """This function is used for making MySQL queries with a list of int elements.
74
-
75
- :param aList: list to be serialized to string for making queries
76
- """
77
- return ",".join(str(x) for x in aList)
78
-
79
-
80
- def getChunk(aList: list, chunkSize: int):
81
- """Generator yielding chunk from a list of a size chunkSize.
82
-
83
- :param aList: list to be splitted
84
- :param chunkSize: lenght of one chunk
85
- :raise: StopIteration
86
-
87
- Usage:
88
-
89
- >>> for chunk in getChunk( aList, chunkSize=10):
90
- process( chunk )
91
-
92
- """
93
- chunkSize = int(chunkSize)
94
- for i in range(0, len(aList), chunkSize):
95
- yield aList[i : i + chunkSize]
96
-
97
-
98
- def breakListIntoChunks(aList: list, chunkSize: int):
99
- """This function takes a list as input and breaks it into list of size 'chunkSize'.
100
- It returns a list of lists.
101
-
102
- :param aList: list of elements
103
- :param chunkSize: len of a single chunk
104
- :return: list of lists of length of chunkSize
105
- :raise: RuntimeError if numberOfFilesInChunk is less than 1
106
- """
107
- if chunkSize < 1:
108
- raise RuntimeError("chunkSize cannot be less than 1")
109
- if isinstance(aList, (set, dict, tuple, {}.keys().__class__, {}.items().__class__, {}.values().__class__)):
110
- aList = list(aList)
111
- return [chunk for chunk in getChunk(aList, chunkSize)]
112
-
113
-
114
- def getIndexInList(anItem: Any, aList: list) -> int:
115
- """Return the index of the element x in the list l
116
- or sys.maxint if it does not exist
117
-
118
- :param anItem: element to look for
119
- :param aList: list to look into
120
-
121
- :return: the index or sys.maxint
122
- """
123
- # try:
124
- if anItem in aList:
125
- return aList.index(anItem)
126
- else:
127
- return sys.maxsize
1
+ from DIRACCommon.Core.Utilities.List import * # noqa: F401,F403