ROS Code
 All Classes Namespaces Files Functions Variables
main.py
Go to the documentation of this file.
1 """
2 
3 ROS Code Commands
4 This file contains all the commands in ROS Code
5 
6 """
7 
8 # Python modules
9 import warnings
10 import keyword
11 import importlib
12 
13 # String modules
14 import string
15 import pprint
16 
17 # External Modules
18 import loremipsum
19 import colour
20 
21 # Custom modules
22 from .roserrors import *
23 
24 # Show a shell based input line and return command and parameters
25 
26 
27 def shellinput(initialtext='>> ', splitpart=' '):
28  """
29 
30  Give the user a shell-like interface to enter commands which are returned as a multi-part list containing the command and each of the arguments
31 
32  initialtext:
33  Set the text to be displayed as the prompt. Default is '>>'.
34 
35  splitpart:
36  The character to split when generating the list item. The default is ' '. Set to '' or None to skip splitting.
37 
38  """
39 
40  try:
41  str(initialtext)
42  except BaseException:
43  raise ConversionError("Cannot convert type " + str(type(initialtext)) +
44  "to str")
45  shelluserinput = input(str(initialtext))
46  if splitpart == '' or splitpart is None:
47  return shelluserinput
48  commands = []
49  for item in enumerate(shelluserinput.split(splitpart)):
50  commands.append(item[1])
51  return commands
52 
53 
54 def colourcode(startcolourcode, destinationtype, longhex=False):
55  """
56 
57  Convert a colour code from one format to another
58 
59  startcolourcode:
60  Set the colour code to convert from
61 
62  destinationtype:
63  Set the colour code type to convert to. Possible options are HEX, HSL, RGB, red, blue, green, hue, sat and lum
64 
65  longhex:
66  If converting to hex, provided the long and unsimplified version. The default is False.
67 
68  """
69 
70  c = colour.Color(str(startcolourcode))
71  if destinationtype.lower() == 'hex':
72  if longhex is True:
73  return c.hex_l
74  return c.hex
75  elif destinationtype.lower() == 'hsl':
76  return c.hsl
77  elif destinationtype.lower() == 'rgb':
78  return c.rgb
79  elif destinationtype.lower() == 'red':
80  return c.red
81  elif destinationtype.lower() == 'blue':
82  return c.blue
83  elif destinationtype.lower() == 'green':
84  return c.green
85  elif destinationtype.lower() == 'hue':
86  return c.hue
87  elif destinationtype.lower() == 'sat':
88  return c.saturation
89  elif destinationtype.lower() == 'lum':
90  return c.luminance
91  raise WrongInput("Destination colour code not specified correctly")
92 
93 
94 def changecolour(colourcode, action, amount=100):
95  """
96 
97  Modify a parameter of a colour code
98 
99  colourcode:
100  The colour code representing the colour to convert from.
101 
102  action:
103  The action to perform on the colour. Possible options are red, blue, green, hue, sat, lum
104 
105  amount:
106  The percentage of the action to perform. For example, 100 means apply 100% of the colour (no change). The default is 100.
107 
108  """
109 
110  c = colour.Color(colourcode)
111  if action == 'red':
112  c.red = amount / 100
113  return c
114  elif action == 'blue':
115  c.blue = amount / 100
116  return c
117  elif action == 'green':
118  c.green = amount / 100
119  return c
120  elif action == 'hue':
121  c.hue = amount / 100
122  return c
123  elif action == 'sat':
124  c.saturation = amount / 100
125  return c
126  elif action == 'lum':
127  c.luminance = amount / 100
128  return c
129 
130 
131 def leadingzero(number, minlength):
132  """
133 
134  Add leading zeros to a number
135 
136  number:
137  The number to add the leading zeros to
138 
139  minlength:
140  If the number is shorter than this length than add leading zeros to make the length correct
141 
142  """
143 
144  return str(number).zfill(int(minlength))
145 
146 
147 def absolutenum(number):
148  """
149 
150  Get the absolute value for a number
151 
152  number:
153  The number to get the absolute value for
154 
155  """
156 
157  return abs(number)
158 
159 
160 def splitstring(string, split_character=' ', part=None):
161  """
162 
163  Split a string based on a character and get the parts as a list
164 
165  string:
166  The string to split
167 
168  split_character:
169  The character to split for the string. The default is ' '.
170 
171  part:
172  Get a specific part of the list. The default is None.
173 
174  """
175 
176  if part is None:
177  return str(string).split(split_character)
178  return str(string).split(split_character)[part]
179 
180 
181 def sort(listtosort, key=None, reversesort=False):
182  """
183 
184  Sort a list alphabetically
185 
186  listtosort:
187  The list which will be sorted
188 
189  key:
190  The key to use when sorting. The default is None.
191 
192  reverse:
193  If to sort backwards. The default is False.
194 
195  """
196 
197  return sorted(listtosort, key=key, reverse=reversesort)
198 
199 
200 def pykeyword(operation='list', keywordtotest=None):
201  """
202 
203  Check if a keyword exists in the Python keyword dictionary
204 
205  operation:
206  Whether to list or check the keywords. Possible options are list and check. The default is 'list'.
207 
208  keywordtotest:
209  The keyword to test for if the operation is 'check'. The default is None.
210 
211  """
212 
213  if operation == 'list':
214  return str(keyword.kwlist)
215  elif operation == 'check':
216  return keyword.iskeyword(str(keywordtotest))
217 
218 
219 # Pretty print a list
220 
221 
222 def prettyprinter(listtoprint, stream=None, indent=1, width=80, depth=None):
223  pprint.pprint(listtoprint, stream, indent, width, depth)
224 
225 
226 # Generate a string of Lorem Ipsum
227 
228 
229 def genipsum():
230  # TODO: Make this work.
231  # https://loremipsum.readthedocs.io/en/latest/#api
232  pass
233 
234 
235 # Convert 0 or 1 to False or True
236 
237 
238 def bintobool(integer):
239  if isinteger(integer) and integer < 2 and integer > -1:
240  if integer == 0:
241  return False
242  elif integer == 1:
243  return True
244 
245 
246 # Reload a module
247 
248 
249 def modulereload(modulename):
250  importlib.reload(modulename)
251 
252 
253 # Configure the Python warnings
254 
255 
256 def warnconfig(action='default'):
257  if action == 'default':
258  warnings.filterwarnings('default')
259  elif action == 'error':
260  warnings.filterwarnings('error')
261  elif action == 'ignore':
262  warnings.filterwarnings('ignore')
263  elif action == 'always':
264  warnings.filterwarnings('always')
265  elif action == 'module':
266  warnings.filterwarnings('module')
267  elif action == 'once':
268  warnings.filterwarnings('once')
269 
270 
271 # Print a console message
272 
273 
274 def message_print(text, amount=1):
275  for _ in range(amount):
276  print(text)
277 
278 
279 # Get The Sides Of A Shape
280 
281 
282 def shapesides(inputtocheck, inputtype='shape'):
283  inputtocheck = inputtocheck.lower()
284  shapestosides = {
285  'triangle': 3,
286  'square': 4,
287  'pentagon': 5,
288  'hexagon': 6,
289  'heptagon': 7,
290  'octagon': 8,
291  'nonagon': 9,
292  'decagon': 10,
293  'hendecagon': 11,
294  'dodecagon': 12,
295  'triskaidecagon': 13,
296  'tetrakaidecagon': 14,
297  'pentadecagon': 15,
298  'hexakaidecagon': 16,
299  'heptadecagon': 17,
300  'octakaidecagon': 18,
301  'enneadecagon': 19,
302  'Icosagon': 20,
303  'triacontagon': 30,
304  'tetracontagon': 40,
305  'pentacontagon': 50,
306  'hexacontagon': 60,
307  'heptacontagon': 70,
308  'octacontagon': 80,
309  'enneacontagon': 90,
310  'hectagon': 100,
311  'chiliagon': 1000,
312  'myriagon': 10000,
313  'megagon': 1000000,
314  'googolgon': pow(10, 100)
315  }
316  if inputtype == 'shape':
317  if inputtocheck in shapestosides:
318  return shapestosides[inputtocheck]
319  return "ngon"
320 
321 
322 # Check If A Value Is Able To Be Converted To A Number (Decimal And Integer)
323 
324 
325 def _isnum(value):
326  try:
327  return bool(isinstance(value, int) or isinstance(value, float))
328  except BaseException:
329  return False_
330 
331 
332 # Compare 2 Numbers
333 
334 
335 def comparenum(value1, value2, comparison):
336  if _isnum(value1) and _isnum(value2):
337  comparison = comparison.lower()
338  if comparison == 'equals':
339  return value1 == value2
340  elif comparison == 'not equal':
341  return value1 != value2
342  elif comparison == 'less than':
343  return value1 < value2
344  elif comparison == 'greater than':
345  return value1 > value2
346  elif comparison == 'more than':
347  return value1 > value2
348  elif comparison == 'less than or equal to':
349  return value1 <= value2
350  elif comparison == 'greater than or equal to':
351  return value1 >= value2
352  elif comparison == 'more than or equal to':
353  return value1 >= value2
354 
355 
356 # Throw A Runtime Error
357 
358 
359 def throwerror(errortext):
360  raise RuntimeError("Forced Error: " + str(errortext))
361 
362 
363 # Store A Value In The __ros_stored__ Variable
364 
365 
366 def store(value):
367  global __ros_stored__
368  __ros_stored__ = value
369 
370 
371 # Get The Stored Variable
372 
373 
374 def getstored():
375  return __ros_stored__
376 
377 
378 # Delay For A Specific Amount Of Seconds
379 
380 
381 def delay(seconds):
382  time.sleep(seconds)
383 
384 
385 # Waits For The User To Press Enter
386 
387 
388 def wait_enter(times=1):
389  for _ in range(times):
390  input('')
391 
392 
393 # Convert A Variable To A String
394 
395 
396 def convertstring(value):
397  return str(value)
398 
399 
400 # Return The Opposite Of A Boolean
401 
402 
403 def opposite(boolean):
404  try:
405  return not boolean
406  except BaseException:
407  raise RuntimeError(
408  'An Error Has Occurred: Nor A Bool Or Len Was Provided (0014)')
409 
410 
411 # Check If A Number Is A Decimal
412 
413 
414 def isdecimal(value):
415  return bool(isinstance(value, float))
416 
417 
418 # Check If A Variable Is A String
419 
420 
421 def isstring(variable):
422  return bool(isinstance(variable, str))
423 
424 
425 # Check If A Variable Is A Specific Type
426 
427 
428 def istype(variable, typeexpected):
429  return bool(isinstance(variable, typeexpected))
430 
431 
432 # Check If A Number Is An Integer (Full Number)
433 
434 
435 def isinteger(value):
436  return bool(isinstance(value, int))
437 
438 
439 # Check For A Boolean
440 
441 
442 def isboolean(value):
443  return isinstance(value, bool)
444 
445 
446 # Sing Happy Birthday
447 
448 
449 def happybirthday(person):
450  print('Happy Birthday To You')
451  time.sleep(2)
452  print('Happy Birthday To You')
453  time.sleep(2)
454  print('Happy Birthday Dear ' + str(person[0].upper()) + str(person[1:]))
455  time.sleep(2)
456  print('Happy Birthday To You')
457 
458 
459 # Find The Difference Between 2 Numbers
460 
461 
462 def difference(num1, num2):
463  return abs(num1 - num2)
464 
465 
466 # Check If A Number Is Divisible By Another Number
467 
468 
469 def divisable(num1, num2):
470  return bool(num1 % num2 == 0)
471 
472 
473 # Check If A Variable Is Empty
474 
475 
476 def isempty(variable):
477  return bool(variable == '')
478 
479 
480 # Find The Length Of A Value
481 
482 
483 def length(value):
484  try:
485  return len(convertstring(value))
486  except OverflowError:
487  raise RuntimeError(
488  'An Error Has Occured: The length of the object exceeds \
489  the limit of {0}'.format(str((charlimit()))))
490 
491 
492 # Simulate A Cow Saying Text
493 
494 
495 def cowsay(text='', align='centre'):
496  align = align.lower()
497  cowtext = str(text)
498  topbar = ' '
499  bottombar = ' '
500  spacing = ''
501  for _ in range(len(text) + 2):
502  topbar = topbar + '_'
503  bottombar = bottombar + '-'
504  if align in ["center", "centre"]:
505  for _ in range((int(len(topbar) / 2)) + 1):
506  spacing = spacing + ' '
507  elif align == 'left':
508  spacing = ' '
509  elif align == 'right':
510  for _ in range(len(text) + 2):
511  spacing = spacing + ' '
512  print(topbar)
513  print('( ' + cowtext + ' )')
514  print(bottombar)
515  print(spacing + r'o ^__^ ')
516  print(spacing + r' o (oO)\_______')
517  print(spacing + r' (__)\ )\/\ ')
518  print(spacing + r' U ||----w | ')
519  print(spacing + r' || || ')
520 
521 
522 # Get The Corresponding Letter In A String
523 
524 
525 def getletter(variable, letternumber):
526  return str(variable)[letternumber - 1]
527 
528 
529 # Check If Something Is On The List
530 
531 
532 def onlist(listtocheck, item):
533  return item in listtocheck
534 
535 
536 # Join Two Strings
537 
538 
539 def jointext(firststring, secondstring):
540  return str(firststring) + str(secondstring)
541 
542 
543 # About Information
544 
545 
546 def about():
547  print('You Are Using ROS Code')
548  print('ROS Code Is licensed Under The Apache License 2.0')
549  print('Type "ros.license()" To Read The license')
550 
551 
552 # Get the value of __name__
553 
554 
555 def pyname(ifmain=False):
556  if ifmain is True:
557  return __name__ == "__main__"
558  return __name__
559 
560 
561 # Convert Text To Binary Form
562 
563 
564 def convertbinary(value, argument):
565  if argument == 'to':
566  try:
567  return bin(value)
568  except BaseException:
569  raise RuntimeError('Invalid Value (0016)')
570  elif argument == 'from':
571  try:
572  return format(value)
573  except BaseException:
574  raise RuntimeError('Invalid Value (0016)')
575 
576 
577 # Make The Text Forwards Or Backwards
578 
579 
580 def reversetext(texttoreverse, ignoretype=False):
581  if ignoretype is False:
582  if isinteger(texttoreverse):
583  return int(str(texttoreverse)[::-1])
584  elif isdecimal(texttoreverse):
585  return float(str(texttoreverse)[::-1])
586  return str(texttoreverse)[::-1]
587  return str(texttoreverse)[::-1]
588 
589 
590 # Reverse A List
591 
592 
593 def reverselist(listtoreverse):
594  return listtoreverse.reverse()
595 
596 
597 # Replace Text In A Variable
598 
599 
600 def replacetext(string, texttofind, texttoreplace):
601  return string.replace(texttofind, texttoreplace)
602 
603 
604 # Get User input
605 
606 
607 def userinput(prompttext=""):
608  """
609 
610  Get the input of the user via a universally secure method
611 
612  prompttext:
613  The text to display while receiving the data. The default is "".
614 
615  """
616  if sys.version_info > (3, 0):
617  # Python 3 code in this block
618  return input(str(prompttext))
619  else:
620  # Python 2 code in this block
621  return raw_input(str(prompttext))
622 
623 
624 # Evaluate A Expression Or Operation
625 
626 
627 def evaluate(evaluation):
628  return eval(str(evaluation))
629 
630 
631 # Execute A Line Of Python Code
632 
633 
634 def execute(execution):
635  exec(str(execution))
636 
637 
638 # Get The Type Of A Value
639 
640 
641 def gettype(value):
642  return type(value)
643 
644 
645 # Do a quick module test
646 
647 
648 def pingtest(returntrue=False):
649  if returntrue:
650  return True
651  print("Pong!")
652 
653 
654 # Convert A ASCII Value To A Symbol
655 
656 
657 def convertascii(value, command='to'):
658  command = command.lower()
659  if command == 'to':
660  try:
661  return chr(value)
662  except ValueError:
663  raise RuntimeError('Invalid Symbol Value (0014)')
664  elif command == 'from':
665  try:
666  return ord(value)
667  except ValueError:
668  raise RuntimeError('Invalid Symbol (0015)')
669  else:
670  raise RuntimeError(
671  'An Error Has Occurred: Invalid Operation Entered (0008)')
672 
673 
674 # Get All Available Characters For A Type
675 
676 
677 def availchar(charactertype):
678  if charactertype == 'letters':
679  return string.ascii_letters
680  elif charactertype == 'lowercase':
681  return string.ascii_lowercase
682  elif charactertype == 'uppercase':
683  return string.ascii_uppercase
684  elif charactertype == 'digits':
685  return string.digits
686  elif charactertype == 'hexdigits':
687  return string.hexdigits
688  elif charactertype == 'punctuation':
689  return string.punctuation
690  elif charactertype == 'printable':
691  return string.printable
692  elif charactertype == 'whitespace':
693  return string.whitespace
694  else:
695  raise RuntimeError(
696  'An Error Has Occurred: Invalid Operation Entered (0008)')
697 
698 
699 # Get The Value Of A Word
700 
701 
702 def wordvalue(word):
703  total = 0
704  for i in enumerate(word):
705  total += letternum(word[i])
706  return total
707 
708 
709 # Get the Range Of The Length
710 
711 
712 def enum(arguments):
713  return enumerate(arguments)
714 
715 
716 # Get The Text Between Two Parts
717 
718 
719 def textbetween(variable,
720  firstnum=None,
721  secondnum=None,
722  locationoftext='regular'):
723  if locationoftext == 'regular':
724  return variable[firstnum:secondnum]
725  elif locationoftext == 'toend':
726  return variable[firstnum:]
727  elif locationoftext == 'tostart':
728  return variable[:secondnum]
729 
730 
731 # Get The Number Corresponding To A Letter
732 
733 
734 def letternum(letter):
735  if len(letter) == 1 and isstring(letter):
736  letter = letter.lower
737  alphaletters = availchar('lowercase')
738  for i in range(len(alphaletters)):
739  if getletter(letter, 1) == getletter(alphaletters, i + 1):
740  return i + 1
741 
742 
743 # Return The List Equally Spaced
744 
745 
746 def spacelist(listtospace):
747  output = ''
748  space = ''
749  output += str(listtospace[0])
750  space += ' '
751  for listnum in range(1, len(listtospace)):
752  output += space
753  output += str(listtospace[listnum])
754  return output
755 
756 
757 # List Or Count The Numbers Between Two Numbers
758 
759 
760 def numlistbetween(num1, num2, option='list', listoption='string'):
761  if option == 'list':
762  if listoption == 'string':
763  output = ''
764  output += str(num1)
765  for currentnum in range(num1 + 1, num2 + 1):
766  output += ','
767  output += str(currentnum)
768  elif listoption == 'list':
769  output = []
770  for currentnum in range(num1, num2 + 1):
771  output.append(str(currentnum))
772  return output
773  elif option == 'count':
774  return num2 - num1
775 
776 
777 # Align Text When Given Full Length
778 
779 
780 def textalign(text, maxlength, align='left'):
781  spaces = ''
782  if align == 'left':
783  return text
784  elif align == 'centre' or align == 'center':
785  for _ in range(int((maxlength - len(text)) / 2)):
786  spaces += ' '
787  elif align == 'right':
788  for _ in range(maxlength - len(text)):
789  spaces += ' '
790  return spaces + text
791 
792 
793 # Fix The Formatting Of Decimals And Integers
794 
795 
796 def decintfix(decorint=0):
797  if str(decorint)[-2:] == '.0':
798  return int(decorint)
799  return float(decorint)
800 
801 
802 # License Information
803 
804 
805 def roslicense(raw=False):
806  if raw is False:
807  print('ROS Code is licensed under the Apache License 2.0')
808  print(
809  u'\u2714' +
810  ' Permissions: Commercial use, Modification, Distribution, Patent use And Private use'
811  )
812  print(u'\u274c' + ' Limitations: Trademark use, Liability And Warranty')
813  print(u'\u2139' +
814  ' Conditions: License and copyright notice And State changes')
815  print(
816  'To View, The Full license, Go To https://rosurl.ga/ROS-Code-license'
817  )
818  else:
819  print('ROS Code Is licensed Under The Apache License 2.0')
820  print(
821  'Permissions: Commercial use, Modification, Distribution, Patent use And Private use'
822  )
823  print('Limitations: Trademark use, Liability And Warranty')
824  print('Conditions: License and copyright notice And State changes')
825  print(
826  'To View, The Full license, Go To https://rosurl.ga/ROS-Code-license'
827  )
def delay
Definition: main.py:381
def letternum
Definition: main.py:734
def changecolour
Definition: main.py:94
def isdecimal
Definition: main.py:414
def modulereload
Definition: main.py:249
def wait_enter
Definition: main.py:388
def decintfix
Definition: main.py:796
def convertascii
Definition: main.py:657
def genipsum
Definition: main.py:229
def getstored
Definition: main.py:374
def colourcode
Definition: main.py:54
def charlimit
Definition: system.py:107
def opposite
Definition: main.py:403
def enum
Definition: main.py:712
def convertstring
Definition: main.py:396
def divisable
Definition: main.py:469
def evaluate
Definition: main.py:627
def replacetext
Definition: main.py:600
def numlistbetween
Definition: main.py:760
def onlist
Definition: main.py:532
def happybirthday
Definition: main.py:449
def comparenum
Definition: main.py:335
def message_print
Definition: main.py:274
def wordvalue
Definition: main.py:702
def isboolean
Definition: main.py:442
def prettyprinter
Definition: main.py:222
def isstring
Definition: main.py:421
def reverselist
Definition: main.py:593
def userinput
Definition: main.py:607
def isempty
Definition: main.py:476
def cowsay
Definition: main.py:495
def splitstring
Definition: main.py:160
def getletter
Definition: main.py:525
def textbetween
Definition: main.py:722
def gettype
Definition: main.py:641
def leadingzero
Definition: main.py:131
def convertbinary
Definition: main.py:564
def warnconfig
Definition: main.py:256
def execute
Definition: main.py:634
def shellinput
Definition: main.py:27
def shapesides
Definition: main.py:282
def bintobool
Definition: main.py:238
def isinteger
Definition: main.py:435
def pingtest
Definition: main.py:648
def pykeyword
Definition: main.py:200
def difference
Definition: main.py:462
def availchar
Definition: main.py:677
def istype
Definition: main.py:428
def spacelist
Definition: main.py:746
def store
Definition: main.py:366
def about
Definition: main.py:546
def roslicense
Definition: main.py:805
def sort
Definition: main.py:181
def jointext
Definition: main.py:539
def absolutenum
Definition: main.py:147
def throwerror
Definition: main.py:359
def length
Definition: main.py:483
def pyname
Definition: main.py:555
def textalign
Definition: main.py:780
def reversetext
Definition: main.py:580