body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
a5a37194f769126a9a92ca472df3642955e2588ed6ad4ea778bac357017fcba8
def __init__(self, postagger, override=False): 'override:\n ' self.postagger = postagger self.override = override
override:
iepy/preprocess/tagger.py
__init__
francolq/iepy
813
python
def __init__(self, postagger, override=False): '\n ' self.postagger = postagger self.override = override
def __init__(self, postagger, override=False): '\n ' self.postagger = postagger self.override = override<|docstring|>override:<|endoftext|>
860605c11f76e50c4d359d6e7bd6e169b4ac8e0c52f6bf167ba8a9e12a9e7d32
@app.route('/') def hello(): 'Return a friendly HTTP greeting.' return 'Hello World!'
Return a friendly HTTP greeting.
appengine/flexible/hello_world/main.py
hello
GurjotSinghBinning0703/python-docs-samples
5,938
python
@app.route('/') def hello(): return 'Hello World!'
@app.route('/') def hello(): return 'Hello World!'<|docstring|>Return a friendly HTTP greeting.<|endoftext|>
308d51db844fc5c278d54015d4a60b6b07dc272adc04189f3802a87b27c600ec
def convert_pinyin_text(self): '\n This method loads the data from the source file, runs the all-important\n _do_convert method and outputs the converted text to the destination file.\n ' self._read_input() self.converted = self.converter.do_convert(self.text) self._write_output()
This method loads the data from the source file, runs the all-important _do_convert method and outputs the converted text to the destination file.
py_pinyin_txt/runner.py
convert_pinyin_text
AtomicMegaNerd/py_pinyin_txt
0
python
def convert_pinyin_text(self): '\n This method loads the data from the source file, runs the all-important\n _do_convert method and outputs the converted text to the destination file.\n ' self._read_input() self.converted = self.converter.do_convert(self.text) self._write_output()
def convert_pinyin_text(self): '\n This method loads the data from the source file, runs the all-important\n _do_convert method and outputs the converted text to the destination file.\n ' self._read_input() self.converted = self.converter.do_convert(self.text) self._write_output()<|docstring|>This method loads the data from the source file, runs the all-important _do_convert method and outputs the converted text to the destination file.<|endoftext|>
12440d4a80728bef4216b953f2bc1f4e7ed52a32cb6bd3df104b395e7aa28a6b
def _read_input(self) -> None: '\n Read the lines in a plain text file and put each line in a list.\n ' self.logger.info(f'Reading source pinyin from file {self.infile}') with open(self.infile, 'r', encoding='utf-8') as infile_fd: for line in infile_fd: self.text.append(line)
Read the lines in a plain text file and put each line in a list.
py_pinyin_txt/runner.py
_read_input
AtomicMegaNerd/py_pinyin_txt
0
python
def _read_input(self) -> None: '\n \n ' self.logger.info(f'Reading source pinyin from file {self.infile}') with open(self.infile, 'r', encoding='utf-8') as infile_fd: for line in infile_fd: self.text.append(line)
def _read_input(self) -> None: '\n \n ' self.logger.info(f'Reading source pinyin from file {self.infile}') with open(self.infile, 'r', encoding='utf-8') as infile_fd: for line in infile_fd: self.text.append(line)<|docstring|>Read the lines in a plain text file and put each line in a list.<|endoftext|>
a305da12fb651d65d354fd4cb263147a0ad8ab238480de5510fb3712221bdbb0
def _write_output(self) -> None: '\n Write each converted line of text to the output file\n ' self.logger.info(f'Writing converted pinyin to file {self.outfile}') with open(self.outfile, 'w', encoding='utf-8') as outfile_fd: outfile_fd.writelines(self.converted)
Write each converted line of text to the output file
py_pinyin_txt/runner.py
_write_output
AtomicMegaNerd/py_pinyin_txt
0
python
def _write_output(self) -> None: '\n \n ' self.logger.info(f'Writing converted pinyin to file {self.outfile}') with open(self.outfile, 'w', encoding='utf-8') as outfile_fd: outfile_fd.writelines(self.converted)
def _write_output(self) -> None: '\n \n ' self.logger.info(f'Writing converted pinyin to file {self.outfile}') with open(self.outfile, 'w', encoding='utf-8') as outfile_fd: outfile_fd.writelines(self.converted)<|docstring|>Write each converted line of text to the output file<|endoftext|>
79d7e39c7c4574e74e68d7926f9fb85d1e5bdc66ed16ea77aa56af190d006778
def provide(self, name): '检查是否提供某功能,即是否提供某接口' return (name in self.provided_features)
检查是否提供某功能,即是否提供某接口
vilya/models/ngit/repo.py
provide
hanxi/code
1,582
python
def provide(self, name): return (name in self.provided_features)
def provide(self, name): return (name in self.provided_features)<|docstring|>检查是否提供某功能,即是否提供某接口<|endoftext|>
bebbe83caadd8c2fbb50f8f8254aa941d986421f66a60e01382d5fa4a9036216
def get_raw_diff(self, ref, from_ref=None, paths=None, **kw): ' get Jagare formated diff dict ' try: diff = self.repo.diff(ref, from_ref=from_ref, paths=paths, **kw) except KeyError: return None return diff
get Jagare formated diff dict
vilya/models/ngit/repo.py
get_raw_diff
hanxi/code
1,582
python
def get_raw_diff(self, ref, from_ref=None, paths=None, **kw): ' ' try: diff = self.repo.diff(ref, from_ref=from_ref, paths=paths, **kw) except KeyError: return None return diff
def get_raw_diff(self, ref, from_ref=None, paths=None, **kw): ' ' try: diff = self.repo.diff(ref, from_ref=from_ref, paths=paths, **kw) except KeyError: return None return diff<|docstring|>get Jagare formated diff dict<|endoftext|>
6d1ca562318367167a1f3f2ef30f37fb07c742a0bf05296de53289e33e165c86
def get_diff(self, ref=None, from_ref=None, linecomments=[], raw_diff=None, paths=None, **kw): ' get ngit wrapped diff object ' _raw_diff = None if raw_diff: _raw_diff = raw_diff elif ref: _raw_diff = self.get_raw_diff(ref, from_ref=from_ref, paths=paths, **kw) if _raw_diff: return Diff(self, _raw_diff, linecomments) else: return None
get ngit wrapped diff object
vilya/models/ngit/repo.py
get_diff
hanxi/code
1,582
python
def get_diff(self, ref=None, from_ref=None, linecomments=[], raw_diff=None, paths=None, **kw): ' ' _raw_diff = None if raw_diff: _raw_diff = raw_diff elif ref: _raw_diff = self.get_raw_diff(ref, from_ref=from_ref, paths=paths, **kw) if _raw_diff: return Diff(self, _raw_diff, linecomments) else: return None
def get_diff(self, ref=None, from_ref=None, linecomments=[], raw_diff=None, paths=None, **kw): ' ' _raw_diff = None if raw_diff: _raw_diff = raw_diff elif ref: _raw_diff = self.get_raw_diff(ref, from_ref=from_ref, paths=paths, **kw) if _raw_diff: return Diff(self, _raw_diff, linecomments) else: return None<|docstring|>get ngit wrapped diff object<|endoftext|>
421b142baf18b84c166aea4a120a3b1a2a4d326f9dea83fe85c94291884aeca6
def get_previours_commit(self, ref, path): 'previours commit that touch the specified path' commits = self.repo.rev_list(ref, path=path, max_count=2, no_merges=True) for commit in commits: if (commit['sha'] != self.repo.sha(ref)): return Commit(self, commit) return None
previours commit that touch the specified path
vilya/models/ngit/repo.py
get_previours_commit
hanxi/code
1,582
python
def get_previours_commit(self, ref, path): commits = self.repo.rev_list(ref, path=path, max_count=2, no_merges=True) for commit in commits: if (commit['sha'] != self.repo.sha(ref)): return Commit(self, commit) return None
def get_previours_commit(self, ref, path): commits = self.repo.rev_list(ref, path=path, max_count=2, no_merges=True) for commit in commits: if (commit['sha'] != self.repo.sha(ref)): return Commit(self, commit) return None<|docstring|>previours commit that touch the specified path<|endoftext|>
8f6f5be81beef91155c9fc91b452e3defa41c45abcb7d6b3e0cc3aa2d253ee07
def get_path_by_ref(self, ref): ' get blob or tree ' path = self.repo.show(ref) if (not path): return None if (path['type'] == 'tree'): path = Tree(self, path['entries']) elif (path['type'] == 'blob'): path = Blob(self, path) else: path = None return path
get blob or tree
vilya/models/ngit/repo.py
get_path_by_ref
hanxi/code
1,582
python
def get_path_by_ref(self, ref): ' ' path = self.repo.show(ref) if (not path): return None if (path['type'] == 'tree'): path = Tree(self, path['entries']) elif (path['type'] == 'blob'): path = Blob(self, path) else: path = None return path
def get_path_by_ref(self, ref): ' ' path = self.repo.show(ref) if (not path): return None if (path['type'] == 'tree'): path = Tree(self, path['entries']) elif (path['type'] == 'blob'): path = Blob(self, path) else: path = None return path<|docstring|>get blob or tree<|endoftext|>
b55a17e0007580116dbe9567b183d520f0b03743849090a6e9a9b1791df49bd3
def __init__(self, w, h): "Only initialises the map, doesn't generate immediately, until gen_map is called." self.width = w self.height = h self.map = Map(w, h)
Only initialises the map, doesn't generate immediately, until gen_map is called.
lib/map.py
__init__
RedMike/pYendor
5
python
def __init__(self, w, h): self.width = w self.height = h self.map = Map(w, h)
def __init__(self, w, h): self.width = w self.height = h self.map = Map(w, h)<|docstring|>Only initialises the map, doesn't generate immediately, until gen_map is called.<|endoftext|>
fb9a4748302e82ee85bd4ce16db53c58b34e33de26a16e94914f17884962ab65
def gen_map(self): 'Returns generated map.' self.map.clear() self.map.add_rect(2, 2, 10, 12, _FLOOR) self.map.add_rect(25, 4, 12, 15, _FLOOR) self.map.add_rect(10, 8, 20, 1, _FLOOR) self.map.add_rect(32, 9, 2, 4, _WALL) self.map.add_rect(5, 8, 2, 1, _WALL) return self.map
Returns generated map.
lib/map.py
gen_map
RedMike/pYendor
5
python
def gen_map(self): self.map.clear() self.map.add_rect(2, 2, 10, 12, _FLOOR) self.map.add_rect(25, 4, 12, 15, _FLOOR) self.map.add_rect(10, 8, 20, 1, _FLOOR) self.map.add_rect(32, 9, 2, 4, _WALL) self.map.add_rect(5, 8, 2, 1, _WALL) return self.map
def gen_map(self): self.map.clear() self.map.add_rect(2, 2, 10, 12, _FLOOR) self.map.add_rect(25, 4, 12, 15, _FLOOR) self.map.add_rect(10, 8, 20, 1, _FLOOR) self.map.add_rect(32, 9, 2, 4, _WALL) self.map.add_rect(5, 8, 2, 1, _WALL) return self.map<|docstring|>Returns generated map.<|endoftext|>
db0356909a5e4662678c8fdd19174d857278c5862eec382195abd66634a7b0a3
def gen_map(self): 'Returns simple left-to-right directional map.' self.map.clear() roughness = 50 length = (self.width - 3) wind = 100 x = 1 y = ((self.height / 2) - 2) height = 3 for i in range(length): self.map.add_rect(x, y, 1, height, _FLOOR) if (random.randint(0, 100) < roughness): height += random.randint((- 2), 2) if (height < 3): height = 3 if ((y + height) >= self.height): height = ((self.height - y) - 1) if (random.randint(0, 100) < wind): y += random.randint((- 2), 2) if (y < 1): y = 1 if ((y + height) >= self.height): y = ((self.height - height) - 1) x += 1 return self.map
Returns simple left-to-right directional map.
lib/map.py
gen_map
RedMike/pYendor
5
python
def gen_map(self): self.map.clear() roughness = 50 length = (self.width - 3) wind = 100 x = 1 y = ((self.height / 2) - 2) height = 3 for i in range(length): self.map.add_rect(x, y, 1, height, _FLOOR) if (random.randint(0, 100) < roughness): height += random.randint((- 2), 2) if (height < 3): height = 3 if ((y + height) >= self.height): height = ((self.height - y) - 1) if (random.randint(0, 100) < wind): y += random.randint((- 2), 2) if (y < 1): y = 1 if ((y + height) >= self.height): y = ((self.height - height) - 1) x += 1 return self.map
def gen_map(self): self.map.clear() roughness = 50 length = (self.width - 3) wind = 100 x = 1 y = ((self.height / 2) - 2) height = 3 for i in range(length): self.map.add_rect(x, y, 1, height, _FLOOR) if (random.randint(0, 100) < roughness): height += random.randint((- 2), 2) if (height < 3): height = 3 if ((y + height) >= self.height): height = ((self.height - y) - 1) if (random.randint(0, 100) < wind): y += random.randint((- 2), 2) if (y < 1): y = 1 if ((y + height) >= self.height): y = ((self.height - height) - 1) x += 1 return self.map<|docstring|>Returns simple left-to-right directional map.<|endoftext|>
e5912056f3d1f6f6e2cfed07c0456abfed1a4780ff078d12e35a82450fb2885c
def __init__(self, w, h): 'Initialised with light-blocking walls.' self.width = w self.height = h self.clear()
Initialised with light-blocking walls.
lib/map.py
__init__
RedMike/pYendor
5
python
def __init__(self, w, h): self.width = w self.height = h self.clear()
def __init__(self, w, h): self.width = w self.height = h self.clear()<|docstring|>Initialised with light-blocking walls.<|endoftext|>
f2503b1bd8a2708fc7f8497640c3fd6afcac56d985c6a6505041b3f36fd369b8
def add_tile(self, x, y, tile): 'Replaces tile with given tuple.' if ((0 < x < self.width) and (0 < y < self.height)): self.tiles[(x + 1)][(y + 1)] = tile
Replaces tile with given tuple.
lib/map.py
add_tile
RedMike/pYendor
5
python
def add_tile(self, x, y, tile): if ((0 < x < self.width) and (0 < y < self.height)): self.tiles[(x + 1)][(y + 1)] = tile
def add_tile(self, x, y, tile): if ((0 < x < self.width) and (0 < y < self.height)): self.tiles[(x + 1)][(y + 1)] = tile<|docstring|>Replaces tile with given tuple.<|endoftext|>
79df312deceac9119fa6b104cceb4e52c8b3f9009cb7e15df71187e45b7a0272
def add_rect(self, x, y, w, h, tile): 'Draws a rectangle of starting at (x,y), (w,h) size.' for i in range(w): for j in range(h): self.add_tile((x + i), (y + j), tile)
Draws a rectangle of starting at (x,y), (w,h) size.
lib/map.py
add_rect
RedMike/pYendor
5
python
def add_rect(self, x, y, w, h, tile): for i in range(w): for j in range(h): self.add_tile((x + i), (y + j), tile)
def add_rect(self, x, y, w, h, tile): for i in range(w): for j in range(h): self.add_tile((x + i), (y + j), tile)<|docstring|>Draws a rectangle of starting at (x,y), (w,h) size.<|endoftext|>
b781b2c4c4a6fef508c1ae5f36094787f13b30d6a3a30ec624280814652746b8
def get_tile(self, x, y): 'Returns wall if tile not in map.' if ((0 < x < self.width) and (0 < y < self.height)): return self.tiles[(x + 1)][(y + 1)] return _WALL
Returns wall if tile not in map.
lib/map.py
get_tile
RedMike/pYendor
5
python
def get_tile(self, x, y): if ((0 < x < self.width) and (0 < y < self.height)): return self.tiles[(x + 1)][(y + 1)] return _WALL
def get_tile(self, x, y): if ((0 < x < self.width) and (0 < y < self.height)): return self.tiles[(x + 1)][(y + 1)] return _WALL<|docstring|>Returns wall if tile not in map.<|endoftext|>
e7b8f42a5da3cfd6642ba2399779109bd2f31a70875a15c439478c6cc5b1ff11
def get_tiles(self): 'Returns the whole map.' return self.get_rect(0, 0, self.width, self.height)
Returns the whole map.
lib/map.py
get_tiles
RedMike/pYendor
5
python
def get_tiles(self): return self.get_rect(0, 0, self.width, self.height)
def get_tiles(self): return self.get_rect(0, 0, self.width, self.height)<|docstring|>Returns the whole map.<|endoftext|>
56353d186611124e3fe796e1f49b7574e2a4b5609b9aa43082fe067171a6807f
def get_rect(self, x, y, w, h): 'Returns a 2D array section of the original map, starting at (x,y) with size (w,h).' ret = [[_WALL for i in range(h)] for j in range(w)] for i in range(w): for j in range(h): ret[i][j] = self.get_tile((x + i), (y + j)) return ret
Returns a 2D array section of the original map, starting at (x,y) with size (w,h).
lib/map.py
get_rect
RedMike/pYendor
5
python
def get_rect(self, x, y, w, h): ret = [[_WALL for i in range(h)] for j in range(w)] for i in range(w): for j in range(h): ret[i][j] = self.get_tile((x + i), (y + j)) return ret
def get_rect(self, x, y, w, h): ret = [[_WALL for i in range(h)] for j in range(w)] for i in range(w): for j in range(h): ret[i][j] = self.get_tile((x + i), (y + j)) return ret<|docstring|>Returns a 2D array section of the original map, starting at (x,y) with size (w,h).<|endoftext|>
7b5096951689c10c4a055013e6b05235150ef5a60c527615448853e59a701941
def get_blocking_light(self, x, y): 'Returns True if the tile is blocking to light.' return self.get_tile(x, y)[1]
Returns True if the tile is blocking to light.
lib/map.py
get_blocking_light
RedMike/pYendor
5
python
def get_blocking_light(self, x, y): return self.get_tile(x, y)[1]
def get_blocking_light(self, x, y): return self.get_tile(x, y)[1]<|docstring|>Returns True if the tile is blocking to light.<|endoftext|>
5b21f52c1e844d9379e02e7a7a0dc75edcbed821597ae6d362d0f52355804261
def get_blocking(self, x, y): 'Returns True if the tile is blocking.' return self.get_tile(x, y)[0]
Returns True if the tile is blocking.
lib/map.py
get_blocking
RedMike/pYendor
5
python
def get_blocking(self, x, y): return self.get_tile(x, y)[0]
def get_blocking(self, x, y): return self.get_tile(x, y)[0]<|docstring|>Returns True if the tile is blocking.<|endoftext|>
eab8d4df8623b07f30cba4a83472065783df7f11621c5a18a816feeece2b9bb0
def save(self): 'Returns list of lines representing map in save format (JSON).\n\n Only stores non (1,1) tiles, to reduce bloat.\n ' lines = ['{'] lines += ['"size" : [{0},{1}],'.format(self.width, self.height)] for i in range(self.width): for j in range(self.height): if (self.get_tile(i, j) != _WALL): lines += ['"{0},{1}" : [{2},{3}],'.format(i, j, *self.get_tile(i, j))] lines[(- 1)] = lines[(- 1)][:(- 1)] lines += ['},'] return lines
Returns list of lines representing map in save format (JSON). Only stores non (1,1) tiles, to reduce bloat.
lib/map.py
save
RedMike/pYendor
5
python
def save(self): 'Returns list of lines representing map in save format (JSON).\n\n Only stores non (1,1) tiles, to reduce bloat.\n ' lines = ['{'] lines += ['"size" : [{0},{1}],'.format(self.width, self.height)] for i in range(self.width): for j in range(self.height): if (self.get_tile(i, j) != _WALL): lines += ['"{0},{1}" : [{2},{3}],'.format(i, j, *self.get_tile(i, j))] lines[(- 1)] = lines[(- 1)][:(- 1)] lines += ['},'] return lines
def save(self): 'Returns list of lines representing map in save format (JSON).\n\n Only stores non (1,1) tiles, to reduce bloat.\n ' lines = ['{'] lines += ['"size" : [{0},{1}],'.format(self.width, self.height)] for i in range(self.width): for j in range(self.height): if (self.get_tile(i, j) != _WALL): lines += ['"{0},{1}" : [{2},{3}],'.format(i, j, *self.get_tile(i, j))] lines[(- 1)] = lines[(- 1)][:(- 1)] lines += ['},'] return lines<|docstring|>Returns list of lines representing map in save format (JSON). Only stores non (1,1) tiles, to reduce bloat.<|endoftext|>
4bd2196e476258f57f61cc66f14ec4541c89cc538d3714095b778b4db0d86cc4
def clear(self): 'Defaults everything to light-blocking walls.' self.tiles = [[_WALL for i in range((self.height + 2))] for j in range((self.width + 2))]
Defaults everything to light-blocking walls.
lib/map.py
clear
RedMike/pYendor
5
python
def clear(self): self.tiles = [[_WALL for i in range((self.height + 2))] for j in range((self.width + 2))]
def clear(self): self.tiles = [[_WALL for i in range((self.height + 2))] for j in range((self.width + 2))]<|docstring|>Defaults everything to light-blocking walls.<|endoftext|>
7dc1205f71ce052b3c51977a976edbf3f1c481c6ffca4860ad3a014d8a9ca713
def send_trigger(event, value1='', value2='', value3=''): ' Send the IFTTT trigger. ' report = {} report['value1'] = str(value1) report['value2'] = str(value2) report['value3'] = str(value3) requests.post(((('https://maker.ifttt.com/trigger/' + event) + '/with/key/') + KEY), data=report)
Send the IFTTT trigger.
examples/python/mcc152/ifttt/ifttt_trigger.py
send_trigger
dtemps123/daqhats
88
python
def send_trigger(event, value1=, value2=, value3=): ' ' report = {} report['value1'] = str(value1) report['value2'] = str(value2) report['value3'] = str(value3) requests.post(((('https://maker.ifttt.com/trigger/' + event) + '/with/key/') + KEY), data=report)
def send_trigger(event, value1=, value2=, value3=): ' ' report = {} report['value1'] = str(value1) report['value2'] = str(value2) report['value3'] = str(value3) requests.post(((('https://maker.ifttt.com/trigger/' + event) + '/with/key/') + KEY), data=report)<|docstring|>Send the IFTTT trigger.<|endoftext|>
45b7eb7204c3b81def1cee334d4873d197f8e0feb6ecb9cc2b09ca00706814a4
def main(): ' Main function ' if (KEY == '<my_key>'): print("The default key must be changed to the user's personal IFTTT Webhooks key before using this example.") sys.exit() mylist = hat_list(filter_by_id=HatIDs.MCC_152) if (not mylist): print('No MCC 152 boards found') sys.exit() print('Using MCC 152 {}.'.format(mylist[0].address)) board = mcc152(mylist[0].address) board.dio_reset() value = board.dio_input_read_bit(CHANNEL) board.dio_config_write_bit(CHANNEL, DIOConfigItem.INPUT_LATCH, 1) board.dio_config_write_bit(CHANNEL, DIOConfigItem.INT_MASK, 0) print('Current input value is {}'.format(value)) print('Waiting for changes, Ctrl-C to exit. ') while True: wait_for_interrupt((- 1)) status = board.dio_int_status_read_bit(CHANNEL) if (status == 1): value = board.dio_input_read_bit(CHANNEL) send_trigger(EVENT_NAME, '{}'.format(value)) print('Sent value {}.'.format(value))
Main function
examples/python/mcc152/ifttt/ifttt_trigger.py
main
dtemps123/daqhats
88
python
def main(): ' ' if (KEY == '<my_key>'): print("The default key must be changed to the user's personal IFTTT Webhooks key before using this example.") sys.exit() mylist = hat_list(filter_by_id=HatIDs.MCC_152) if (not mylist): print('No MCC 152 boards found') sys.exit() print('Using MCC 152 {}.'.format(mylist[0].address)) board = mcc152(mylist[0].address) board.dio_reset() value = board.dio_input_read_bit(CHANNEL) board.dio_config_write_bit(CHANNEL, DIOConfigItem.INPUT_LATCH, 1) board.dio_config_write_bit(CHANNEL, DIOConfigItem.INT_MASK, 0) print('Current input value is {}'.format(value)) print('Waiting for changes, Ctrl-C to exit. ') while True: wait_for_interrupt((- 1)) status = board.dio_int_status_read_bit(CHANNEL) if (status == 1): value = board.dio_input_read_bit(CHANNEL) send_trigger(EVENT_NAME, '{}'.format(value)) print('Sent value {}.'.format(value))
def main(): ' ' if (KEY == '<my_key>'): print("The default key must be changed to the user's personal IFTTT Webhooks key before using this example.") sys.exit() mylist = hat_list(filter_by_id=HatIDs.MCC_152) if (not mylist): print('No MCC 152 boards found') sys.exit() print('Using MCC 152 {}.'.format(mylist[0].address)) board = mcc152(mylist[0].address) board.dio_reset() value = board.dio_input_read_bit(CHANNEL) board.dio_config_write_bit(CHANNEL, DIOConfigItem.INPUT_LATCH, 1) board.dio_config_write_bit(CHANNEL, DIOConfigItem.INT_MASK, 0) print('Current input value is {}'.format(value)) print('Waiting for changes, Ctrl-C to exit. ') while True: wait_for_interrupt((- 1)) status = board.dio_int_status_read_bit(CHANNEL) if (status == 1): value = board.dio_input_read_bit(CHANNEL) send_trigger(EVENT_NAME, '{}'.format(value)) print('Sent value {}.'.format(value))<|docstring|>Main function<|endoftext|>
0984e6016bc70bf1eb2120579f7642cc6138d03cea524ca97ffebbbd33ae83b5
def test_login_required(self): 'Test that login is required to access the endpoint' res = self.client.get(INGREDIENTS_URL) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
Test that login is required to access the endpoint
app/recipe/tests/test_ingredients_api.py
test_login_required
lastlift/recipe-app-api
0
python
def test_login_required(self): res = self.client.get(INGREDIENTS_URL) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
def test_login_required(self): res = self.client.get(INGREDIENTS_URL) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)<|docstring|>Test that login is required to access the endpoint<|endoftext|>
d157941be656902ad554de82b0ddd48612fa1c3a89f8a7c01b48585a6cbfba2c
def test_retrieve_ingredient_list(self): 'Test retrieving a list of ingredients' Ingredient.objects.create(user=self.user, name='Kale') Ingredient.objects.create(user=self.user, name='Salt') res = self.client.get(INGREDIENTS_URL) ingredients = Ingredient.objects.all().order_by('-name') serializer = IngredientSerializer(ingredients, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data)
Test retrieving a list of ingredients
app/recipe/tests/test_ingredients_api.py
test_retrieve_ingredient_list
lastlift/recipe-app-api
0
python
def test_retrieve_ingredient_list(self): Ingredient.objects.create(user=self.user, name='Kale') Ingredient.objects.create(user=self.user, name='Salt') res = self.client.get(INGREDIENTS_URL) ingredients = Ingredient.objects.all().order_by('-name') serializer = IngredientSerializer(ingredients, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data)
def test_retrieve_ingredient_list(self): Ingredient.objects.create(user=self.user, name='Kale') Ingredient.objects.create(user=self.user, name='Salt') res = self.client.get(INGREDIENTS_URL) ingredients = Ingredient.objects.all().order_by('-name') serializer = IngredientSerializer(ingredients, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data)<|docstring|>Test retrieving a list of ingredients<|endoftext|>
54e013a8069788df43ae494eff235f5853a5c22afded5a208e537a44784d68a6
def test_ingredients_limited_to_user(self): 'Test that ingredients for the authenticated user are returned' user2 = get_user_model().objects.create_user('example@example.com', 'test123') Ingredient.objects.create(user=user2, name='Vinegar') ingredient = Ingredient.objects.create(user=self.user, name='Tumeric') res = self.client.get(INGREDIENTS_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data), 1) self.assertEqual(res.data[0]['name'], ingredient.name)
Test that ingredients for the authenticated user are returned
app/recipe/tests/test_ingredients_api.py
test_ingredients_limited_to_user
lastlift/recipe-app-api
0
python
def test_ingredients_limited_to_user(self): user2 = get_user_model().objects.create_user('example@example.com', 'test123') Ingredient.objects.create(user=user2, name='Vinegar') ingredient = Ingredient.objects.create(user=self.user, name='Tumeric') res = self.client.get(INGREDIENTS_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data), 1) self.assertEqual(res.data[0]['name'], ingredient.name)
def test_ingredients_limited_to_user(self): user2 = get_user_model().objects.create_user('example@example.com', 'test123') Ingredient.objects.create(user=user2, name='Vinegar') ingredient = Ingredient.objects.create(user=self.user, name='Tumeric') res = self.client.get(INGREDIENTS_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data), 1) self.assertEqual(res.data[0]['name'], ingredient.name)<|docstring|>Test that ingredients for the authenticated user are returned<|endoftext|>
91fdcb7dea3c82e57c1a445af518918a532226f65ce7e47a8dded49c40e2e214
def test_create_ingredient_successful(self): 'Test create a new ingredient' payload = {'name': 'Cabbage'} self.client.post(INGREDIENTS_URL, payload) exists = Ingredient.objects.filter(user=self.user, name=payload['name']).exists() self.assertTrue(exists)
Test create a new ingredient
app/recipe/tests/test_ingredients_api.py
test_create_ingredient_successful
lastlift/recipe-app-api
0
python
def test_create_ingredient_successful(self): payload = {'name': 'Cabbage'} self.client.post(INGREDIENTS_URL, payload) exists = Ingredient.objects.filter(user=self.user, name=payload['name']).exists() self.assertTrue(exists)
def test_create_ingredient_successful(self): payload = {'name': 'Cabbage'} self.client.post(INGREDIENTS_URL, payload) exists = Ingredient.objects.filter(user=self.user, name=payload['name']).exists() self.assertTrue(exists)<|docstring|>Test create a new ingredient<|endoftext|>
41212fe30649f7dbb7f80fc32d70a573c9c988c4c28c0f7ffa1d538e4c004df0
def test_create_ingredient_invalid(self): 'Test creating an invalid ingredient fails' payload = {'name': ''} res = self.client.post(INGREDIENTS_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
Test creating an invalid ingredient fails
app/recipe/tests/test_ingredients_api.py
test_create_ingredient_invalid
lastlift/recipe-app-api
0
python
def test_create_ingredient_invalid(self): payload = {'name': } res = self.client.post(INGREDIENTS_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
def test_create_ingredient_invalid(self): payload = {'name': } res = self.client.post(INGREDIENTS_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)<|docstring|>Test creating an invalid ingredient fails<|endoftext|>
c8122654e9c294998e0fcb5670db08d593f6e5e75b81b7a0ec87b72ed72e76db
def setProgram(self, program): 'User will call this to set up the program variable' from ..glprogram import GLProgram assert isinstance(program, GLProgram) print('######### QGLWidget setProgram ###############') if hasattr(program, 'name'): self.name = program.name if self.initialized: self.setWindowTitle(program.name) self.program = program program.window = weakref.proxy(self) if hasattr(self, 'devicePixelRatio'): program.view.screenDeviceScale = self.devicePixelRatio() else: program.view.screenDeviceScale = 1 if self.initialized: program.initialize() program.reshapefunc(self.width, self.height) def idleCallback(): self.nextIdleEvent = 0 if self.program: self.program.idlefunc() if (self.nextIdleEvent == 0): self.idleTimer.start(0) self.idleTimer.timeout.connect(idleCallback) else: self.reshape(program.view.w, program.view.h)
User will call this to set up the program variable
Python/klampt/vis/backends/qtbackend.py
setProgram
patricknaughton01/Klampt
238
python
def setProgram(self, program): from ..glprogram import GLProgram assert isinstance(program, GLProgram) print('######### QGLWidget setProgram ###############') if hasattr(program, 'name'): self.name = program.name if self.initialized: self.setWindowTitle(program.name) self.program = program program.window = weakref.proxy(self) if hasattr(self, 'devicePixelRatio'): program.view.screenDeviceScale = self.devicePixelRatio() else: program.view.screenDeviceScale = 1 if self.initialized: program.initialize() program.reshapefunc(self.width, self.height) def idleCallback(): self.nextIdleEvent = 0 if self.program: self.program.idlefunc() if (self.nextIdleEvent == 0): self.idleTimer.start(0) self.idleTimer.timeout.connect(idleCallback) else: self.reshape(program.view.w, program.view.h)
def setProgram(self, program): from ..glprogram import GLProgram assert isinstance(program, GLProgram) print('######### QGLWidget setProgram ###############') if hasattr(program, 'name'): self.name = program.name if self.initialized: self.setWindowTitle(program.name) self.program = program program.window = weakref.proxy(self) if hasattr(self, 'devicePixelRatio'): program.view.screenDeviceScale = self.devicePixelRatio() else: program.view.screenDeviceScale = 1 if self.initialized: program.initialize() program.reshapefunc(self.width, self.height) def idleCallback(): self.nextIdleEvent = 0 if self.program: self.program.idlefunc() if (self.nextIdleEvent == 0): self.idleTimer.start(0) self.idleTimer.timeout.connect(idleCallback) else: self.reshape(program.view.w, program.view.h)<|docstring|>User will call this to set up the program variable<|endoftext|>
fd00df2641d94ba5524ed64a63993934a09a81714a47e02593f89054e92ba6e6
def initialize(self): ' Opens a window and initializes. Called internally, and must be in the visualization thread.' assert (self.program != None), 'QGLWidget initialized without a GLProgram' try: glEnable(GL_MULTISAMPLE) except Exception: print("QGLWidget.initialize(): perhaps Qt didn't initialize properly?") pass self.setMouseTracking(True) self.setFocusPolicy(Qt.StrongFocus) def idleCallback(): self.nextIdleEvent = 0 if self.program: self.program.idlefunc() if (self.nextIdleEvent == 0): self.idleTimer.start(0) self.idleTimer = QTimer(self) self.idleTimer.timeout.connect(idleCallback) self.idleTimer.setSingleShot(True) self.idleTimer.start(0) self.program.initialize() if (self.actionMenu is not None): for a in self.actions: self.actionMenu.addAction(a) else: print('QtGLWidget.initialize: no action menu?') self.initialized = True
Opens a window and initializes. Called internally, and must be in the visualization thread.
Python/klampt/vis/backends/qtbackend.py
initialize
patricknaughton01/Klampt
238
python
def initialize(self): ' ' assert (self.program != None), 'QGLWidget initialized without a GLProgram' try: glEnable(GL_MULTISAMPLE) except Exception: print("QGLWidget.initialize(): perhaps Qt didn't initialize properly?") pass self.setMouseTracking(True) self.setFocusPolicy(Qt.StrongFocus) def idleCallback(): self.nextIdleEvent = 0 if self.program: self.program.idlefunc() if (self.nextIdleEvent == 0): self.idleTimer.start(0) self.idleTimer = QTimer(self) self.idleTimer.timeout.connect(idleCallback) self.idleTimer.setSingleShot(True) self.idleTimer.start(0) self.program.initialize() if (self.actionMenu is not None): for a in self.actions: self.actionMenu.addAction(a) else: print('QtGLWidget.initialize: no action menu?') self.initialized = True
def initialize(self): ' ' assert (self.program != None), 'QGLWidget initialized without a GLProgram' try: glEnable(GL_MULTISAMPLE) except Exception: print("QGLWidget.initialize(): perhaps Qt didn't initialize properly?") pass self.setMouseTracking(True) self.setFocusPolicy(Qt.StrongFocus) def idleCallback(): self.nextIdleEvent = 0 if self.program: self.program.idlefunc() if (self.nextIdleEvent == 0): self.idleTimer.start(0) self.idleTimer = QTimer(self) self.idleTimer.timeout.connect(idleCallback) self.idleTimer.setSingleShot(True) self.idleTimer.start(0) self.program.initialize() if (self.actionMenu is not None): for a in self.actions: self.actionMenu.addAction(a) else: print('QtGLWidget.initialize: no action menu?') self.initialized = True<|docstring|>Opens a window and initializes. Called internally, and must be in the visualization thread.<|endoftext|>
81a5c7c16d1f65b0d80ec245a132407854e94df616567f788e62fbde765d0163
def hide(self): 'Hides the window, if already shown' QGLWidget.hide(self) if self.initialized: self.idlesleep()
Hides the window, if already shown
Python/klampt/vis/backends/qtbackend.py
hide
patricknaughton01/Klampt
238
python
def hide(self): QGLWidget.hide(self) if self.initialized: self.idlesleep()
def hide(self): QGLWidget.hide(self) if self.initialized: self.idlesleep()<|docstring|>Hides the window, if already shown<|endoftext|>
4e1d4e32a094b5d29e47fb8fe96114a48e512038dd9fa62dbe7f381e198a6a36
def show(self): 'Restores from a previous hide call' QGLWidget.show(self) if self.initialized: self.idlesleep(0) self.refresh()
Restores from a previous hide call
Python/klampt/vis/backends/qtbackend.py
show
patricknaughton01/Klampt
238
python
def show(self): QGLWidget.show(self) if self.initialized: self.idlesleep(0) self.refresh()
def show(self): QGLWidget.show(self) if self.initialized: self.idlesleep(0) self.refresh()<|docstring|>Restores from a previous hide call<|endoftext|>
8e6fceb6bbf76d50da30ccbb0b555299ea5fe873b48538340afb715e650fca1e
def close(self): 'Qt thread should call close() after this widget should be closed down to stop\n any existing Qt callbacks.' if (not self.initialized): return print('######### QGLWidget close ###############') self.idleTimer.stop() self.idleTimer.deleteLater() self.idleTimer = None if self.program: self.program.window = None self.program = None self.initialized = False
Qt thread should call close() after this widget should be closed down to stop any existing Qt callbacks.
Python/klampt/vis/backends/qtbackend.py
close
patricknaughton01/Klampt
238
python
def close(self): 'Qt thread should call close() after this widget should be closed down to stop\n any existing Qt callbacks.' if (not self.initialized): return print('######### QGLWidget close ###############') self.idleTimer.stop() self.idleTimer.deleteLater() self.idleTimer = None if self.program: self.program.window = None self.program = None self.initialized = False
def close(self): 'Qt thread should call close() after this widget should be closed down to stop\n any existing Qt callbacks.' if (not self.initialized): return print('######### QGLWidget close ###############') self.idleTimer.stop() self.idleTimer.deleteLater() self.idleTimer = None if self.program: self.program.window = None self.program = None self.initialized = False<|docstring|>Qt thread should call close() after this widget should be closed down to stop any existing Qt callbacks.<|endoftext|>
cd49435edde05a4ba35234a30eac23a0dff57cd3b26601b07df2e839d085f218
def add_action(self, hook, short_text, key=None, description=None): "This is called by the user to add actions to the menu bar.\n\n Args:\n hook (function): a python callback function, taking no arguments, called\n when the action is triggered.\n short_text (str): the text shown in the menu bar.\n key (str, optional): a shortcut keyboard command (can be 'k' or 'Ctrl+k').\n description (str, optional): if provided, this is a tooltip that shows up\n when the user hovers their mouse over the menu item.\n " a = QAction(short_text, self) if (key is not None): a.setShortcut(key) if (description is None): description = short_text a.setStatusTip(description) a.triggered.connect(hook) self.actions.append(a)
This is called by the user to add actions to the menu bar. Args: hook (function): a python callback function, taking no arguments, called when the action is triggered. short_text (str): the text shown in the menu bar. key (str, optional): a shortcut keyboard command (can be 'k' or 'Ctrl+k'). description (str, optional): if provided, this is a tooltip that shows up when the user hovers their mouse over the menu item.
Python/klampt/vis/backends/qtbackend.py
add_action
patricknaughton01/Klampt
238
python
def add_action(self, hook, short_text, key=None, description=None): "This is called by the user to add actions to the menu bar.\n\n Args:\n hook (function): a python callback function, taking no arguments, called\n when the action is triggered.\n short_text (str): the text shown in the menu bar.\n key (str, optional): a shortcut keyboard command (can be 'k' or 'Ctrl+k').\n description (str, optional): if provided, this is a tooltip that shows up\n when the user hovers their mouse over the menu item.\n " a = QAction(short_text, self) if (key is not None): a.setShortcut(key) if (description is None): description = short_text a.setStatusTip(description) a.triggered.connect(hook) self.actions.append(a)
def add_action(self, hook, short_text, key=None, description=None): "This is called by the user to add actions to the menu bar.\n\n Args:\n hook (function): a python callback function, taking no arguments, called\n when the action is triggered.\n short_text (str): the text shown in the menu bar.\n key (str, optional): a shortcut keyboard command (can be 'k' or 'Ctrl+k').\n description (str, optional): if provided, this is a tooltip that shows up\n when the user hovers their mouse over the menu item.\n " a = QAction(short_text, self) if (key is not None): a.setShortcut(key) if (description is None): description = short_text a.setStatusTip(description) a.triggered.connect(hook) self.actions.append(a)<|docstring|>This is called by the user to add actions to the menu bar. Args: hook (function): a python callback function, taking no arguments, called when the action is triggered. short_text (str): the text shown in the menu bar. key (str, optional): a shortcut keyboard command (can be 'k' or 'Ctrl+k'). description (str, optional): if provided, this is a tooltip that shows up when the user hovers their mouse over the menu item.<|endoftext|>
b4cb17c63dbe9733dd73506f7df0102e9f831880a2217c1b1548d9c415df936f
def modifiers(self): 'Call this to retrieve modifiers. Called by frontend.' return self.modifierList
Call this to retrieve modifiers. Called by frontend.
Python/klampt/vis/backends/qtbackend.py
modifiers
patricknaughton01/Klampt
238
python
def modifiers(self): return self.modifierList
def modifiers(self): return self.modifierList<|docstring|>Call this to retrieve modifiers. Called by frontend.<|endoftext|>
beb849180a4f510a70c434087967de9956a5c206976c58a13bcf62daf0271e4e
def idlesleep(self, duration=float('inf')): 'Externally callable. Sleeps the idle callback for t seconds. If t is not provided,\n the idle callback is slept forever' self.idlesleep_signal.emit(duration)
Externally callable. Sleeps the idle callback for t seconds. If t is not provided, the idle callback is slept forever
Python/klampt/vis/backends/qtbackend.py
idlesleep
patricknaughton01/Klampt
238
python
def idlesleep(self, duration=float('inf')): 'Externally callable. Sleeps the idle callback for t seconds. If t is not provided,\n the idle callback is slept forever' self.idlesleep_signal.emit(duration)
def idlesleep(self, duration=float('inf')): 'Externally callable. Sleeps the idle callback for t seconds. If t is not provided,\n the idle callback is slept forever' self.idlesleep_signal.emit(duration)<|docstring|>Externally callable. Sleeps the idle callback for t seconds. If t is not provided, the idle callback is slept forever<|endoftext|>
c329f3ec3deb1c966c5ae9880641af0dd69f943e4586cf852e8e3cd47ad80c44
def refresh(self): 'Externally callable. Requests a refresh of the window' if (not self.refreshed): self.refreshed = True if (not self.isVisible()): return self.refresh_signal.emit()
Externally callable. Requests a refresh of the window
Python/klampt/vis/backends/qtbackend.py
refresh
patricknaughton01/Klampt
238
python
def refresh(self): if (not self.refreshed): self.refreshed = True if (not self.isVisible()): return self.refresh_signal.emit()
def refresh(self): if (not self.refreshed): self.refreshed = True if (not self.isVisible()): return self.refresh_signal.emit()<|docstring|>Externally callable. Requests a refresh of the window<|endoftext|>
8559cf630751fede4278f9d255596d50b8d78736d88d4e5383e517720f5f9d7a
def resizeEvent(self, event): 'Called internally by Qt when Qt resizes the window' QGLWidget.resizeEvent(self, event) (self.width, self.height) = (event.size().width(), event.size().height()) if hasattr(self, 'devicePixelRatio'): scale = self.devicePixelRatio() else: scale = 1 (self.devwidth, self.devheight) = ((self.width * scale), (self.height * scale)) if self.program: self.program.reshapefunc(self.width, self.height) self.refresh()
Called internally by Qt when Qt resizes the window
Python/klampt/vis/backends/qtbackend.py
resizeEvent
patricknaughton01/Klampt
238
python
def resizeEvent(self, event): QGLWidget.resizeEvent(self, event) (self.width, self.height) = (event.size().width(), event.size().height()) if hasattr(self, 'devicePixelRatio'): scale = self.devicePixelRatio() else: scale = 1 (self.devwidth, self.devheight) = ((self.width * scale), (self.height * scale)) if self.program: self.program.reshapefunc(self.width, self.height) self.refresh()
def resizeEvent(self, event): QGLWidget.resizeEvent(self, event) (self.width, self.height) = (event.size().width(), event.size().height()) if hasattr(self, 'devicePixelRatio'): scale = self.devicePixelRatio() else: scale = 1 (self.devwidth, self.devheight) = ((self.width * scale), (self.height * scale)) if self.program: self.program.reshapefunc(self.width, self.height) self.refresh()<|docstring|>Called internally by Qt when Qt resizes the window<|endoftext|>
6973eb1d116c90848bb6e3413c87b58db82105263a5e29236f74186f5c34885d
def reshape(self, w, h): 'Externally callable. Reshapes the window' self.reshape_signal.emit(w, h)
Externally callable. Reshapes the window
Python/klampt/vis/backends/qtbackend.py
reshape
patricknaughton01/Klampt
238
python
def reshape(self, w, h): self.reshape_signal.emit(w, h)
def reshape(self, w, h): self.reshape_signal.emit(w, h)<|docstring|>Externally callable. Reshapes the window<|endoftext|>
6f182821deb54048d2aa399ce812e03727b95059360a2646a67a462891da6a80
def draw_text(self, point, text, size=12, color=None): 'Renders text at the given point (may be 2d or 3d). Frontend should call this to draw text\n in either the display or display_screen method.\n\n Args:\n point (list of floats): either a 2d or 3d point at which to draw the text\n text (str): the text to draw\n size (int, optional): if given, it renders a font in the given size. \n color (list of 3 floats or list of 4 floats) if given, then an RGB or RGBA color value.\n\n ' if color: if (len(color) == 3): glColor3f(*color) else: glColor4f(*color) font = QtGui.QFont() font.setPixelSize(size) if (len(point) == 2): self.renderText(point[0], point[1], 0, text, font) else: self.renderText(point[0], point[1], point[2], text, font)
Renders text at the given point (may be 2d or 3d). Frontend should call this to draw text in either the display or display_screen method. Args: point (list of floats): either a 2d or 3d point at which to draw the text text (str): the text to draw size (int, optional): if given, it renders a font in the given size. color (list of 3 floats or list of 4 floats) if given, then an RGB or RGBA color value.
Python/klampt/vis/backends/qtbackend.py
draw_text
patricknaughton01/Klampt
238
python
def draw_text(self, point, text, size=12, color=None): 'Renders text at the given point (may be 2d or 3d). Frontend should call this to draw text\n in either the display or display_screen method.\n\n Args:\n point (list of floats): either a 2d or 3d point at which to draw the text\n text (str): the text to draw\n size (int, optional): if given, it renders a font in the given size. \n color (list of 3 floats or list of 4 floats) if given, then an RGB or RGBA color value.\n\n ' if color: if (len(color) == 3): glColor3f(*color) else: glColor4f(*color) font = QtGui.QFont() font.setPixelSize(size) if (len(point) == 2): self.renderText(point[0], point[1], 0, text, font) else: self.renderText(point[0], point[1], point[2], text, font)
def draw_text(self, point, text, size=12, color=None): 'Renders text at the given point (may be 2d or 3d). Frontend should call this to draw text\n in either the display or display_screen method.\n\n Args:\n point (list of floats): either a 2d or 3d point at which to draw the text\n text (str): the text to draw\n size (int, optional): if given, it renders a font in the given size. \n color (list of 3 floats or list of 4 floats) if given, then an RGB or RGBA color value.\n\n ' if color: if (len(color) == 3): glColor3f(*color) else: glColor4f(*color) font = QtGui.QFont() font.setPixelSize(size) if (len(point) == 2): self.renderText(point[0], point[1], 0, text, font) else: self.renderText(point[0], point[1], point[2], text, font)<|docstring|>Renders text at the given point (may be 2d or 3d). Frontend should call this to draw text in either the display or display_screen method. Args: point (list of floats): either a 2d or 3d point at which to draw the text text (str): the text to draw size (int, optional): if given, it renders a font in the given size. color (list of 3 floats or list of 4 floats) if given, then an RGB or RGBA color value.<|endoftext|>
d767b06ccf87d158696e34b4286b8ea245a9b7603b09642cc5f60a13cd69ab40
def run(self): 'Starts the main loop' assert (self.window != None), "No windows create()'ed" self.window.show() self.app.exec_()
Starts the main loop
Python/klampt/vis/backends/qtbackend.py
run
patricknaughton01/Klampt
238
python
def run(self): assert (self.window != None), "No windows create()'ed" self.window.show() self.app.exec_()
def run(self): assert (self.window != None), "No windows create()'ed" self.window.show() self.app.exec_()<|docstring|>Starts the main loop<|endoftext|>
b66a6afb52f95be3a73ae141aa5bc02dfef3a3ca5c130b3362b868cd7602b0cb
def readFile(path): ' Returns the String contained in the file passed by parameter.\n\n Returns:\n str: File content on a single string line.\n ' try: with open(path, 'r') as fd: out = ''.join(fd.readlines()) fd.close() return out except IOError: raise
Returns the String contained in the file passed by parameter. Returns: str: File content on a single string line.
mezzanine_developer_extension/utils.py
readFile
educalleja/mezzanine-developer-extension
5
python
def readFile(path): ' Returns the String contained in the file passed by parameter.\n\n Returns:\n str: File content on a single string line.\n ' try: with open(path, 'r') as fd: out = .join(fd.readlines()) fd.close() return out except IOError: raise
def readFile(path): ' Returns the String contained in the file passed by parameter.\n\n Returns:\n str: File content on a single string line.\n ' try: with open(path, 'r') as fd: out = .join(fd.readlines()) fd.close() return out except IOError: raise<|docstring|>Returns the String contained in the file passed by parameter. Returns: str: File content on a single string line.<|endoftext|>
177092137213c2360879c5986960fe67b4d3590903f1bfed9c7f3f3ff5837297
def path_template(template_name): ' Returns the absolute path of the template.\n ' path = os.path.join(current_path, 'templates/box_templates') absolute_path = '{}/{}'.format(path, template_name) return absolute_path
Returns the absolute path of the template.
mezzanine_developer_extension/utils.py
path_template
educalleja/mezzanine-developer-extension
5
python
def path_template(template_name): ' \n ' path = os.path.join(current_path, 'templates/box_templates') absolute_path = '{}/{}'.format(path, template_name) return absolute_path
def path_template(template_name): ' \n ' path = os.path.join(current_path, 'templates/box_templates') absolute_path = '{}/{}'.format(path, template_name) return absolute_path<|docstring|>Returns the absolute path of the template.<|endoftext|>
2def2b174ad8a57d9306afd355b2bc847c29985bea9bf03708721a5baa3f3a3f
def replace_labels_string(element, label, newstring): ' Replaces in the text of Element and its childs the text label for\n newstring\n ' if ((len(element) == 0) and (element.text is not None)): element.text = element.text.replace(label, newstring) else: for child in element: replace_labels_string(child, label, newstring)
Replaces in the text of Element and its childs the text label for newstring
mezzanine_developer_extension/utils.py
replace_labels_string
educalleja/mezzanine-developer-extension
5
python
def replace_labels_string(element, label, newstring): ' Replaces in the text of Element and its childs the text label for\n newstring\n ' if ((len(element) == 0) and (element.text is not None)): element.text = element.text.replace(label, newstring) else: for child in element: replace_labels_string(child, label, newstring)
def replace_labels_string(element, label, newstring): ' Replaces in the text of Element and its childs the text label for\n newstring\n ' if ((len(element) == 0) and (element.text is not None)): element.text = element.text.replace(label, newstring) else: for child in element: replace_labels_string(child, label, newstring)<|docstring|>Replaces in the text of Element and its childs the text label for newstring<|endoftext|>
acba6d2e07ed5c1a948445270657b1328414e3f1e34be16549822bd96627425b
def replace_labels_element(element, label, elements): ' Replaces the label in element for elements\n ' if (len(element) == 0): element.text = element.text.replace(label, '') for e in elements: element.append(e) else: for child in element: replace_labels_element(child, label, elements)
Replaces the label in element for elements
mezzanine_developer_extension/utils.py
replace_labels_element
educalleja/mezzanine-developer-extension
5
python
def replace_labels_element(element, label, elements): ' \n ' if (len(element) == 0): element.text = element.text.replace(label, ) for e in elements: element.append(e) else: for child in element: replace_labels_element(child, label, elements)
def replace_labels_element(element, label, elements): ' \n ' if (len(element) == 0): element.text = element.text.replace(label, ) for e in elements: element.append(e) else: for child in element: replace_labels_element(child, label, elements)<|docstring|>Replaces the label in element for elements<|endoftext|>
0a3dc39664007a4a0a4f5ce4bedc5560443d8da73fa940578baea35028602f26
def get_template(template_name): ' Returns a lxml Element containing the new terminal layout.\n ' template_path = path_template(template_name) new_division = ET.parse(template_path) return new_division.find('div')
Returns a lxml Element containing the new terminal layout.
mezzanine_developer_extension/utils.py
get_template
educalleja/mezzanine-developer-extension
5
python
def get_template(template_name): ' \n ' template_path = path_template(template_name) new_division = ET.parse(template_path) return new_division.find('div')
def get_template(template_name): ' \n ' template_path = path_template(template_name) new_division = ET.parse(template_path) return new_division.find('div')<|docstring|>Returns a lxml Element containing the new terminal layout.<|endoftext|>
c95b0cfaeefe02748d17c47536adbb1f75a0b5ea439c7df6b8ea558dedb796eb
def refactor_terminals(xhtml, style): " Searches all divs whose class='terminal' and replaces it by a \n group of divs that will be used to render the terminal in the blog post.\n " terminals_in_post = xhtml.xpath("//div[@class='terminal']") for terminal in terminals_in_post: parent_object = terminal.getparent() terminal_title = terminal.get('title', '') terminal_li = terminal.getchildren() new_terminal = get_template('{}.template'.format(style)) replace_labels_string(new_terminal, '__TITLE__', terminal_title) replace_labels_element(new_terminal, '__COMMANDS__', terminal_li) parent_object.replace(terminal, new_terminal)
Searches all divs whose class='terminal' and replaces it by a group of divs that will be used to render the terminal in the blog post.
mezzanine_developer_extension/utils.py
refactor_terminals
educalleja/mezzanine-developer-extension
5
python
def refactor_terminals(xhtml, style): " Searches all divs whose class='terminal' and replaces it by a \n group of divs that will be used to render the terminal in the blog post.\n " terminals_in_post = xhtml.xpath("//div[@class='terminal']") for terminal in terminals_in_post: parent_object = terminal.getparent() terminal_title = terminal.get('title', ) terminal_li = terminal.getchildren() new_terminal = get_template('{}.template'.format(style)) replace_labels_string(new_terminal, '__TITLE__', terminal_title) replace_labels_element(new_terminal, '__COMMANDS__', terminal_li) parent_object.replace(terminal, new_terminal)
def refactor_terminals(xhtml, style): " Searches all divs whose class='terminal' and replaces it by a \n group of divs that will be used to render the terminal in the blog post.\n " terminals_in_post = xhtml.xpath("//div[@class='terminal']") for terminal in terminals_in_post: parent_object = terminal.getparent() terminal_title = terminal.get('title', ) terminal_li = terminal.getchildren() new_terminal = get_template('{}.template'.format(style)) replace_labels_string(new_terminal, '__TITLE__', terminal_title) replace_labels_element(new_terminal, '__COMMANDS__', terminal_li) parent_object.replace(terminal, new_terminal)<|docstring|>Searches all divs whose class='terminal' and replaces it by a group of divs that will be used to render the terminal in the blog post.<|endoftext|>
a2dd869da87b38d68c5fc4dee5a70b2922f11c8cb3d9a561423c04473ca5b0cc
def get_code_lines(element): ' Returns an array of spans per line obtained from the attribute. If\n elements childs are elements, the user might be have inserted html in a\n code division. In this case. we will escape the content.\n ' data = [] element_children = element.getchildren() if len(element_children): text_container = ''.join([ET.tostring(e) for e in element_children]) else: text_container = element.text lines = text_container.split('\n') lines = (lines if (lines[0] != '') else lines[1:]) lines = (lines if (lines[(- 1)] != '') else lines[:(- 1)]) for line in lines: el = ET.Element('span') el.text = line data.append(el) return data
Returns an array of spans per line obtained from the attribute. If elements childs are elements, the user might be have inserted html in a code division. In this case. we will escape the content.
mezzanine_developer_extension/utils.py
get_code_lines
educalleja/mezzanine-developer-extension
5
python
def get_code_lines(element): ' Returns an array of spans per line obtained from the attribute. If\n elements childs are elements, the user might be have inserted html in a\n code division. In this case. we will escape the content.\n ' data = [] element_children = element.getchildren() if len(element_children): text_container = .join([ET.tostring(e) for e in element_children]) else: text_container = element.text lines = text_container.split('\n') lines = (lines if (lines[0] != ) else lines[1:]) lines = (lines if (lines[(- 1)] != ) else lines[:(- 1)]) for line in lines: el = ET.Element('span') el.text = line data.append(el) return data
def get_code_lines(element): ' Returns an array of spans per line obtained from the attribute. If\n elements childs are elements, the user might be have inserted html in a\n code division. In this case. we will escape the content.\n ' data = [] element_children = element.getchildren() if len(element_children): text_container = .join([ET.tostring(e) for e in element_children]) else: text_container = element.text lines = text_container.split('\n') lines = (lines if (lines[0] != ) else lines[1:]) lines = (lines if (lines[(- 1)] != ) else lines[:(- 1)]) for line in lines: el = ET.Element('span') el.text = line data.append(el) return data<|docstring|>Returns an array of spans per line obtained from the attribute. If elements childs are elements, the user might be have inserted html in a code division. In this case. we will escape the content.<|endoftext|>
53897b6e208335cf16515b1dfa14586a6b79f483448d9e91bd905ce35cbb2cab
def get_text_lines(text): ' Returns an array of paragraph elements \'<p>\' for every line in the\n text passed by parameter.\n\n Attributes: \n text (str): Text including break lines.\n\n Example:\n >>> s = "This is line\r\n And this is another line"\n >>> result = get_text_lines(text)\n >>> print result\n [<Element p>, <Element p>]\n >>> print result[0].text\n This is a line\n\n ' data = [] lines = text.split('\n') for line in lines: el = ET.Element('p') el.text = line data.append(el) return data
Returns an array of paragraph elements '<p>' for every line in the text passed by parameter. Attributes: text (str): Text including break lines. Example: >>> s = "This is line And this is another line" >>> result = get_text_lines(text) >>> print result [<Element p>, <Element p>] >>> print result[0].text This is a line
mezzanine_developer_extension/utils.py
get_text_lines
educalleja/mezzanine-developer-extension
5
python
def get_text_lines(text): ' Returns an array of paragraph elements \'<p>\' for every line in the\n text passed by parameter.\n\n Attributes: \n text (str): Text including break lines.\n\n Example:\n >>> s = "This is line\r\n And this is another line"\n >>> result = get_text_lines(text)\n >>> print result\n [<Element p>, <Element p>]\n >>> print result[0].text\n This is a line\n\n ' data = [] lines = text.split('\n') for line in lines: el = ET.Element('p') el.text = line data.append(el) return data
def get_text_lines(text): ' Returns an array of paragraph elements \'<p>\' for every line in the\n text passed by parameter.\n\n Attributes: \n text (str): Text including break lines.\n\n Example:\n >>> s = "This is line\r\n And this is another line"\n >>> result = get_text_lines(text)\n >>> print result\n [<Element p>, <Element p>]\n >>> print result[0].text\n This is a line\n\n ' data = [] lines = text.split('\n') for line in lines: el = ET.Element('p') el.text = line data.append(el) return data<|docstring|>Returns an array of paragraph elements '<p>' for every line in the text passed by parameter. Attributes: text (str): Text including break lines. Example: >>> s = "This is line And this is another line" >>> result = get_text_lines(text) >>> print result [<Element p>, <Element p>] >>> print result[0].text This is a line<|endoftext|>
4debff62cf319ff3ac068ee76c9c6cbce3ed310c3a031214eb74ad73c862eb27
def refactor_codes(xhtml): " Searches all divs whose class='terminal' and replaces it by a \n group of divs that will be used to render the terminal in the blog post.\n " codes_in_post = xhtml.xpath("//div[@class='code']") for code in codes_in_post: parent_object = code.getparent() codes_lines = get_code_lines(code) new_code_div = get_template('code.template') replace_labels_element(new_code_div, '__CODELINES__', codes_lines) parent_object.replace(code, new_code_div)
Searches all divs whose class='terminal' and replaces it by a group of divs that will be used to render the terminal in the blog post.
mezzanine_developer_extension/utils.py
refactor_codes
educalleja/mezzanine-developer-extension
5
python
def refactor_codes(xhtml): " Searches all divs whose class='terminal' and replaces it by a \n group of divs that will be used to render the terminal in the blog post.\n " codes_in_post = xhtml.xpath("//div[@class='code']") for code in codes_in_post: parent_object = code.getparent() codes_lines = get_code_lines(code) new_code_div = get_template('code.template') replace_labels_element(new_code_div, '__CODELINES__', codes_lines) parent_object.replace(code, new_code_div)
def refactor_codes(xhtml): " Searches all divs whose class='terminal' and replaces it by a \n group of divs that will be used to render the terminal in the blog post.\n " codes_in_post = xhtml.xpath("//div[@class='code']") for code in codes_in_post: parent_object = code.getparent() codes_lines = get_code_lines(code) new_code_div = get_template('code.template') replace_labels_element(new_code_div, '__CODELINES__', codes_lines) parent_object.replace(code, new_code_div)<|docstring|>Searches all divs whose class='terminal' and replaces it by a group of divs that will be used to render the terminal in the blog post.<|endoftext|>
c1d101f2b4241abbecddb38ede68665bd827b4140477710eba6dc52b0116bbb7
def refactor_logs(xhtml): " Searches all divs whose class='logs' and replaces it by a \n group of divs that will be used to render the terminal in the blog post.\n " logs_in_post = xhtml.xpath("//div[@class='log']") for log in logs_in_post: parent_object = log.getparent() log_lines = get_code_lines(log) new_log_div = get_template('log.template') replace_labels_element(new_log_div, '__LOGLINES__', log_lines) parent_object.replace(log, new_log_div)
Searches all divs whose class='logs' and replaces it by a group of divs that will be used to render the terminal in the blog post.
mezzanine_developer_extension/utils.py
refactor_logs
educalleja/mezzanine-developer-extension
5
python
def refactor_logs(xhtml): " Searches all divs whose class='logs' and replaces it by a \n group of divs that will be used to render the terminal in the blog post.\n " logs_in_post = xhtml.xpath("//div[@class='log']") for log in logs_in_post: parent_object = log.getparent() log_lines = get_code_lines(log) new_log_div = get_template('log.template') replace_labels_element(new_log_div, '__LOGLINES__', log_lines) parent_object.replace(log, new_log_div)
def refactor_logs(xhtml): " Searches all divs whose class='logs' and replaces it by a \n group of divs that will be used to render the terminal in the blog post.\n " logs_in_post = xhtml.xpath("//div[@class='log']") for log in logs_in_post: parent_object = log.getparent() log_lines = get_code_lines(log) new_log_div = get_template('log.template') replace_labels_element(new_log_div, '__LOGLINES__', log_lines) parent_object.replace(log, new_log_div)<|docstring|>Searches all divs whose class='logs' and replaces it by a group of divs that will be used to render the terminal in the blog post.<|endoftext|>
2567200e5aeabddf6ceabd6d3b86749178805390fbbf4a0b4c91eca0c051ed2e
def refactor_tips(xhtml): ' Searches all tip elements and replaces it by a \n group of divs that will be used to render the tip bubble in the blog post.\n ' tips_in_post = xhtml.xpath("//div[@class='tipbox']") for tip in tips_in_post: parent_object = tip.getparent() tip_title = tip.get('title', 'Did you know?') new_tip_div = get_template('tip.template') tip_parapraphs = get_text_lines(tip.text) replace_labels_element(new_tip_div, '__TIPTEXT__', tip_parapraphs) replace_labels_string(new_tip_div, '__TIPTITLE__', tip_title) parent_object.replace(tip, new_tip_div)
Searches all tip elements and replaces it by a group of divs that will be used to render the tip bubble in the blog post.
mezzanine_developer_extension/utils.py
refactor_tips
educalleja/mezzanine-developer-extension
5
python
def refactor_tips(xhtml): ' Searches all tip elements and replaces it by a \n group of divs that will be used to render the tip bubble in the blog post.\n ' tips_in_post = xhtml.xpath("//div[@class='tipbox']") for tip in tips_in_post: parent_object = tip.getparent() tip_title = tip.get('title', 'Did you know?') new_tip_div = get_template('tip.template') tip_parapraphs = get_text_lines(tip.text) replace_labels_element(new_tip_div, '__TIPTEXT__', tip_parapraphs) replace_labels_string(new_tip_div, '__TIPTITLE__', tip_title) parent_object.replace(tip, new_tip_div)
def refactor_tips(xhtml): ' Searches all tip elements and replaces it by a \n group of divs that will be used to render the tip bubble in the blog post.\n ' tips_in_post = xhtml.xpath("//div[@class='tipbox']") for tip in tips_in_post: parent_object = tip.getparent() tip_title = tip.get('title', 'Did you know?') new_tip_div = get_template('tip.template') tip_parapraphs = get_text_lines(tip.text) replace_labels_element(new_tip_div, '__TIPTEXT__', tip_parapraphs) replace_labels_string(new_tip_div, '__TIPTITLE__', tip_title) parent_object.replace(tip, new_tip_div)<|docstring|>Searches all tip elements and replaces it by a group of divs that will be used to render the tip bubble in the blog post.<|endoftext|>
acf5aa47567fd8263cecd288947a3a409b53122d53e4cbde39bd0a0464a034df
def refactor(xhtml, style): " Refactors the xhtml structure. Refactors the following elements:\n - div class='terminal macos'\n - div class='code'\n\n Attributes:\n xhtml (ET.Element): Original blog post xhtml code.\n style (str): Indicates the output style: macos, windows or ubuntu.\n " refactor_codes(xhtml) refactor_logs(xhtml) refactor_tips(xhtml) refactor_terminals(xhtml, style)
Refactors the xhtml structure. Refactors the following elements: - div class='terminal macos' - div class='code' Attributes: xhtml (ET.Element): Original blog post xhtml code. style (str): Indicates the output style: macos, windows or ubuntu.
mezzanine_developer_extension/utils.py
refactor
educalleja/mezzanine-developer-extension
5
python
def refactor(xhtml, style): " Refactors the xhtml structure. Refactors the following elements:\n - div class='terminal macos'\n - div class='code'\n\n Attributes:\n xhtml (ET.Element): Original blog post xhtml code.\n style (str): Indicates the output style: macos, windows or ubuntu.\n " refactor_codes(xhtml) refactor_logs(xhtml) refactor_tips(xhtml) refactor_terminals(xhtml, style)
def refactor(xhtml, style): " Refactors the xhtml structure. Refactors the following elements:\n - div class='terminal macos'\n - div class='code'\n\n Attributes:\n xhtml (ET.Element): Original blog post xhtml code.\n style (str): Indicates the output style: macos, windows or ubuntu.\n " refactor_codes(xhtml) refactor_logs(xhtml) refactor_tips(xhtml) refactor_terminals(xhtml, style)<|docstring|>Refactors the xhtml structure. Refactors the following elements: - div class='terminal macos' - div class='code' Attributes: xhtml (ET.Element): Original blog post xhtml code. style (str): Indicates the output style: macos, windows or ubuntu.<|endoftext|>
a0a553f80ecad41c4283098a017783b89eb80519794b9a63fea0de31e45a87a9
def refactor_html(content, style='macos'): " Generates the HTML output for the blog.\n\n Attributes:\n data (str): Un-cleaned HTML data to be displayed at the blog entry.\n style (str): Determines the output style. Valid values: 'macos',\n 'ubuntu','windows'\n " content = prefactor(content) content_prestore = '<blogpost>{}</blogpost>'.format(content) root = html.fromstring(content_prestore) refactor(root, style) result = ET.tostring(root) return result.replace('<blogpost>', '').replace('</blogpost>', '')
Generates the HTML output for the blog. Attributes: data (str): Un-cleaned HTML data to be displayed at the blog entry. style (str): Determines the output style. Valid values: 'macos', 'ubuntu','windows'
mezzanine_developer_extension/utils.py
refactor_html
educalleja/mezzanine-developer-extension
5
python
def refactor_html(content, style='macos'): " Generates the HTML output for the blog.\n\n Attributes:\n data (str): Un-cleaned HTML data to be displayed at the blog entry.\n style (str): Determines the output style. Valid values: 'macos',\n 'ubuntu','windows'\n " content = prefactor(content) content_prestore = '<blogpost>{}</blogpost>'.format(content) root = html.fromstring(content_prestore) refactor(root, style) result = ET.tostring(root) return result.replace('<blogpost>', ).replace('</blogpost>', )
def refactor_html(content, style='macos'): " Generates the HTML output for the blog.\n\n Attributes:\n data (str): Un-cleaned HTML data to be displayed at the blog entry.\n style (str): Determines the output style. Valid values: 'macos',\n 'ubuntu','windows'\n " content = prefactor(content) content_prestore = '<blogpost>{}</blogpost>'.format(content) root = html.fromstring(content_prestore) refactor(root, style) result = ET.tostring(root) return result.replace('<blogpost>', ).replace('</blogpost>', )<|docstring|>Generates the HTML output for the blog. Attributes: data (str): Un-cleaned HTML data to be displayed at the blog entry. style (str): Determines the output style. Valid values: 'macos', 'ubuntu','windows'<|endoftext|>
f81099bb8c4bd650ef466c5c14ff5921c15e0502495b1e6dc91313d683f97e74
def is_valid_xhtml(content): ' Returns a tuple specifying whether the content passed by parameter is \n valid xhtml code. When the string is not valid xhtml, the second element\n in the tuple contains the error message from the parser. \n ' try: ET.parse(StringIO(unicode(content))) except XMLSyntaxError as e: return (False, e.message) return (True, '')
Returns a tuple specifying whether the content passed by parameter is valid xhtml code. When the string is not valid xhtml, the second element in the tuple contains the error message from the parser.
mezzanine_developer_extension/utils.py
is_valid_xhtml
educalleja/mezzanine-developer-extension
5
python
def is_valid_xhtml(content): ' Returns a tuple specifying whether the content passed by parameter is \n valid xhtml code. When the string is not valid xhtml, the second element\n in the tuple contains the error message from the parser. \n ' try: ET.parse(StringIO(unicode(content))) except XMLSyntaxError as e: return (False, e.message) return (True, )
def is_valid_xhtml(content): ' Returns a tuple specifying whether the content passed by parameter is \n valid xhtml code. When the string is not valid xhtml, the second element\n in the tuple contains the error message from the parser. \n ' try: ET.parse(StringIO(unicode(content))) except XMLSyntaxError as e: return (False, e.message) return (True, )<|docstring|>Returns a tuple specifying whether the content passed by parameter is valid xhtml code. When the string is not valid xhtml, the second element in the tuple contains the error message from the parser.<|endoftext|>
64d50b555a38bc8b91165c1f323ea53710ebd1c3461b5d4a1a81d1a67e99e10b
async def main() -> None: '\n # gen ssl key sh\n > openssl req -newkey rsa:2048 -nodes -keyout rap_ssl.key -x509 -days 365 -out rap_ssl.crt\n ' (await client.start()) print(f'async result: {(await async_sum(1, 3))}') (await client.stop())
# gen ssl key sh > openssl req -newkey rsa:2048 -nodes -keyout rap_ssl.key -x509 -days 365 -out rap_ssl.crt
example/ssl/client.py
main
so1n/rap
3
python
async def main() -> None: '\n # gen ssl key sh\n > openssl req -newkey rsa:2048 -nodes -keyout rap_ssl.key -x509 -days 365 -out rap_ssl.crt\n ' (await client.start()) print(f'async result: {(await async_sum(1, 3))}') (await client.stop())
async def main() -> None: '\n # gen ssl key sh\n > openssl req -newkey rsa:2048 -nodes -keyout rap_ssl.key -x509 -days 365 -out rap_ssl.crt\n ' (await client.start()) print(f'async result: {(await async_sum(1, 3))}') (await client.stop())<|docstring|># gen ssl key sh > openssl req -newkey rsa:2048 -nodes -keyout rap_ssl.key -x509 -days 365 -out rap_ssl.crt<|endoftext|>
cea4cf7413cb7822c76b8c84ec361e69c12d9598d17731496df5135d775cd47e
@router.get('/{cluster_id}/vbd/{vbd_uuid}/plug') @router.post('/{cluster_id}/vbd/{vbd_uuid}/plug') async def _vbd_plug(cluster_id: str, vbd_uuid: str): 'Plug into VBD' try: session = create_session(_id=cluster_id, get_xen_clusters=Settings.get_xen_clusters()) vbd: VBD = VBD.get_by_uuid(session=session, uuid=vbd_uuid) if (vbd is not None): ret = dict(success=vbd.plug()) else: ret = dict(success=False) session.xenapi.session.logout() return ret except Failure as xenapi_error: raise HTTPException(status_code=500, detail=xenapi_failure_jsonify(xenapi_error)) except Fault as xml_rpc_error: raise HTTPException(status_code=int(xml_rpc_error.faultCode), detail=xml_rpc_error.faultString) except RemoteDisconnected as rd_error: raise HTTPException(status_code=500, detail=rd_error.strerror)
Plug into VBD
API/v1/VBD/plug.py
_vbd_plug
zeroday0619/XenXenXenSe
0
python
@router.get('/{cluster_id}/vbd/{vbd_uuid}/plug') @router.post('/{cluster_id}/vbd/{vbd_uuid}/plug') async def _vbd_plug(cluster_id: str, vbd_uuid: str): try: session = create_session(_id=cluster_id, get_xen_clusters=Settings.get_xen_clusters()) vbd: VBD = VBD.get_by_uuid(session=session, uuid=vbd_uuid) if (vbd is not None): ret = dict(success=vbd.plug()) else: ret = dict(success=False) session.xenapi.session.logout() return ret except Failure as xenapi_error: raise HTTPException(status_code=500, detail=xenapi_failure_jsonify(xenapi_error)) except Fault as xml_rpc_error: raise HTTPException(status_code=int(xml_rpc_error.faultCode), detail=xml_rpc_error.faultString) except RemoteDisconnected as rd_error: raise HTTPException(status_code=500, detail=rd_error.strerror)
@router.get('/{cluster_id}/vbd/{vbd_uuid}/plug') @router.post('/{cluster_id}/vbd/{vbd_uuid}/plug') async def _vbd_plug(cluster_id: str, vbd_uuid: str): try: session = create_session(_id=cluster_id, get_xen_clusters=Settings.get_xen_clusters()) vbd: VBD = VBD.get_by_uuid(session=session, uuid=vbd_uuid) if (vbd is not None): ret = dict(success=vbd.plug()) else: ret = dict(success=False) session.xenapi.session.logout() return ret except Failure as xenapi_error: raise HTTPException(status_code=500, detail=xenapi_failure_jsonify(xenapi_error)) except Fault as xml_rpc_error: raise HTTPException(status_code=int(xml_rpc_error.faultCode), detail=xml_rpc_error.faultString) except RemoteDisconnected as rd_error: raise HTTPException(status_code=500, detail=rd_error.strerror)<|docstring|>Plug into VBD<|endoftext|>
6bb9e355fdc5ae49660e349c0dc3799a0f5278dc9f2004ad2d85e2128c3f0b55
@router.delete('/{cluster_id}/vbd/{vbd_uuid}/plug') @router.get('/{cluster_id}/vbd/{vbd_uuid}/unplug') @router.post('/{cluster_id}/vbd/{vbd_uuid}/unplug') async def vbd_unplug(cluster_id: str, vbd_uuid: str): 'Unplug from VBD' try: session = create_session(_id=cluster_id, get_xen_clusters=Settings.get_xen_clusters()) vbd: VBD = VBD.get_by_uuid(session=session, uuid=vbd_uuid) if (vbd is not None): ret = dict(success=vbd.unplug()) else: ret = dict(success=False) session.xenapi.session.logout() return ret except Failure as xenapi_error: raise HTTPException(status_code=500, detail=xenapi_failure_jsonify(xenapi_error)) except Fault as xml_rpc_error: raise HTTPException(status_code=int(xml_rpc_error.faultCode), detail=xml_rpc_error.faultString) except RemoteDisconnected as rd_error: raise HTTPException(status_code=500, detail=rd_error.strerror)
Unplug from VBD
API/v1/VBD/plug.py
vbd_unplug
zeroday0619/XenXenXenSe
0
python
@router.delete('/{cluster_id}/vbd/{vbd_uuid}/plug') @router.get('/{cluster_id}/vbd/{vbd_uuid}/unplug') @router.post('/{cluster_id}/vbd/{vbd_uuid}/unplug') async def vbd_unplug(cluster_id: str, vbd_uuid: str): try: session = create_session(_id=cluster_id, get_xen_clusters=Settings.get_xen_clusters()) vbd: VBD = VBD.get_by_uuid(session=session, uuid=vbd_uuid) if (vbd is not None): ret = dict(success=vbd.unplug()) else: ret = dict(success=False) session.xenapi.session.logout() return ret except Failure as xenapi_error: raise HTTPException(status_code=500, detail=xenapi_failure_jsonify(xenapi_error)) except Fault as xml_rpc_error: raise HTTPException(status_code=int(xml_rpc_error.faultCode), detail=xml_rpc_error.faultString) except RemoteDisconnected as rd_error: raise HTTPException(status_code=500, detail=rd_error.strerror)
@router.delete('/{cluster_id}/vbd/{vbd_uuid}/plug') @router.get('/{cluster_id}/vbd/{vbd_uuid}/unplug') @router.post('/{cluster_id}/vbd/{vbd_uuid}/unplug') async def vbd_unplug(cluster_id: str, vbd_uuid: str): try: session = create_session(_id=cluster_id, get_xen_clusters=Settings.get_xen_clusters()) vbd: VBD = VBD.get_by_uuid(session=session, uuid=vbd_uuid) if (vbd is not None): ret = dict(success=vbd.unplug()) else: ret = dict(success=False) session.xenapi.session.logout() return ret except Failure as xenapi_error: raise HTTPException(status_code=500, detail=xenapi_failure_jsonify(xenapi_error)) except Fault as xml_rpc_error: raise HTTPException(status_code=int(xml_rpc_error.faultCode), detail=xml_rpc_error.faultString) except RemoteDisconnected as rd_error: raise HTTPException(status_code=500, detail=rd_error.strerror)<|docstring|>Unplug from VBD<|endoftext|>
95c88f612d99ebe0061a582928d1b902bf6e54ca520b90ef1b561b29c1c734cd
def fibonacci(count: int) -> list: '\n This function takes a count an input and generated Fibonacci series element count equal to count\n\n # input: \n count : int\n \n # Returns\n list\n\n # Funcationality:\n Calcualtes the sum of last two list elements and appends it to the list until the count is completed.\n by default it generates a list of size 2\n \n For eg: if count is 21 the list will generate fabonacci series of list length as 21\n\n ' fib_list = [0, 1] any(map((lambda _: fib_list.append(sum(fib_list[(- 2):]))), range(2, count))) return fib_list[:count]
This function takes a count an input and generated Fibonacci series element count equal to count # input: count : int # Returns list # Funcationality: Calcualtes the sum of last two list elements and appends it to the list until the count is completed. by default it generates a list of size 2 For eg: if count is 21 the list will generate fabonacci series of list length as 21
07. First Class Function 2/Session7.py
fibonacci
arghya05/EPAi
1
python
def fibonacci(count: int) -> list: '\n This function takes a count an input and generated Fibonacci series element count equal to count\n\n # input: \n count : int\n \n # Returns\n list\n\n # Funcationality:\n Calcualtes the sum of last two list elements and appends it to the list until the count is completed.\n by default it generates a list of size 2\n \n For eg: if count is 21 the list will generate fabonacci series of list length as 21\n\n ' fib_list = [0, 1] any(map((lambda _: fib_list.append(sum(fib_list[(- 2):]))), range(2, count))) return fib_list[:count]
def fibonacci(count: int) -> list: '\n This function takes a count an input and generated Fibonacci series element count equal to count\n\n # input: \n count : int\n \n # Returns\n list\n\n # Funcationality:\n Calcualtes the sum of last two list elements and appends it to the list until the count is completed.\n by default it generates a list of size 2\n \n For eg: if count is 21 the list will generate fabonacci series of list length as 21\n\n ' fib_list = [0, 1] any(map((lambda _: fib_list.append(sum(fib_list[(- 2):]))), range(2, count))) return fib_list[:count]<|docstring|>This function takes a count an input and generated Fibonacci series element count equal to count # input: count : int # Returns list # Funcationality: Calcualtes the sum of last two list elements and appends it to the list until the count is completed. by default it generates a list of size 2 For eg: if count is 21 the list will generate fabonacci series of list length as 21<|endoftext|>
d4db7643215a52a11f80f4f056965e3d981cb3c645e717a942abf49ee3408f5b
def check_result(my_number: list) -> list: '\n This function is used to generate the list of random numbers or take the list from the user and check it against the Fibonacci\n list and display the output.\n\n # input: \n my_number : list List to match against the Fibonacci list given by user\n \n # Returns\n list : returns the matched list\n\n # Functionality:\n It a random list of numbers in the range 1 to 10000 and then matches it with Fibanacci list\n returned from calling Fibonacci function. Then it prints the matched numbers\n\n ' if (not my_number): my_number = [] for _ in range(0, 100000): my_number.append(random.randint(1, 10000)) print(fibonacci(21)) result = list(filter((lambda x: (x in my_number)), fibonacci(21))) result.sort() return result
This function is used to generate the list of random numbers or take the list from the user and check it against the Fibonacci list and display the output. # input: my_number : list List to match against the Fibonacci list given by user # Returns list : returns the matched list # Functionality: It a random list of numbers in the range 1 to 10000 and then matches it with Fibanacci list returned from calling Fibonacci function. Then it prints the matched numbers
07. First Class Function 2/Session7.py
check_result
arghya05/EPAi
1
python
def check_result(my_number: list) -> list: '\n This function is used to generate the list of random numbers or take the list from the user and check it against the Fibonacci\n list and display the output.\n\n # input: \n my_number : list List to match against the Fibonacci list given by user\n \n # Returns\n list : returns the matched list\n\n # Functionality:\n It a random list of numbers in the range 1 to 10000 and then matches it with Fibanacci list\n returned from calling Fibonacci function. Then it prints the matched numbers\n\n ' if (not my_number): my_number = [] for _ in range(0, 100000): my_number.append(random.randint(1, 10000)) print(fibonacci(21)) result = list(filter((lambda x: (x in my_number)), fibonacci(21))) result.sort() return result
def check_result(my_number: list) -> list: '\n This function is used to generate the list of random numbers or take the list from the user and check it against the Fibonacci\n list and display the output.\n\n # input: \n my_number : list List to match against the Fibonacci list given by user\n \n # Returns\n list : returns the matched list\n\n # Functionality:\n It a random list of numbers in the range 1 to 10000 and then matches it with Fibanacci list\n returned from calling Fibonacci function. Then it prints the matched numbers\n\n ' if (not my_number): my_number = [] for _ in range(0, 100000): my_number.append(random.randint(1, 10000)) print(fibonacci(21)) result = list(filter((lambda x: (x in my_number)), fibonacci(21))) result.sort() return result<|docstring|>This function is used to generate the list of random numbers or take the list from the user and check it against the Fibonacci list and display the output. # input: my_number : list List to match against the Fibonacci list given by user # Returns list : returns the matched list # Functionality: It a random list of numbers in the range 1 to 10000 and then matches it with Fibanacci list returned from calling Fibonacci function. Then it prints the matched numbers<|endoftext|>
3318575b94de34abbbe02cd8334eb8ec6058bb69957164edbf3fe7f5e110af91
def my_add(a: list, b: list) -> list: '\n This function takes two list, compares each element, if list 1 ahs even element and list\n 2 has odd element then they are added else ignored\n\n # Input:\n a: List (Input List 1)\n b: List (Input List 2)\n\n # Returns:\n list: Once the addition is done, the result is stored in the list and returned.\n \n # Functionality:\n The two lists are zipped and each tuple is iterated, element 1 of the tuple is checked of \n eveness and element b of the tuple is checked for oddness, if the condition is satisfied\n then they are added and the result is stored in a list.\n ' result = [(x + y) for (x, y) in zip(a, b) if ((x % 2) == 0) if ((y % 2) != 0)] return result
This function takes two list, compares each element, if list 1 ahs even element and list 2 has odd element then they are added else ignored # Input: a: List (Input List 1) b: List (Input List 2) # Returns: list: Once the addition is done, the result is stored in the list and returned. # Functionality: The two lists are zipped and each tuple is iterated, element 1 of the tuple is checked of eveness and element b of the tuple is checked for oddness, if the condition is satisfied then they are added and the result is stored in a list.
07. First Class Function 2/Session7.py
my_add
arghya05/EPAi
1
python
def my_add(a: list, b: list) -> list: '\n This function takes two list, compares each element, if list 1 ahs even element and list\n 2 has odd element then they are added else ignored\n\n # Input:\n a: List (Input List 1)\n b: List (Input List 2)\n\n # Returns:\n list: Once the addition is done, the result is stored in the list and returned.\n \n # Functionality:\n The two lists are zipped and each tuple is iterated, element 1 of the tuple is checked of \n eveness and element b of the tuple is checked for oddness, if the condition is satisfied\n then they are added and the result is stored in a list.\n ' result = [(x + y) for (x, y) in zip(a, b) if ((x % 2) == 0) if ((y % 2) != 0)] return result
def my_add(a: list, b: list) -> list: '\n This function takes two list, compares each element, if list 1 ahs even element and list\n 2 has odd element then they are added else ignored\n\n # Input:\n a: List (Input List 1)\n b: List (Input List 2)\n\n # Returns:\n list: Once the addition is done, the result is stored in the list and returned.\n \n # Functionality:\n The two lists are zipped and each tuple is iterated, element 1 of the tuple is checked of \n eveness and element b of the tuple is checked for oddness, if the condition is satisfied\n then they are added and the result is stored in a list.\n ' result = [(x + y) for (x, y) in zip(a, b) if ((x % 2) == 0) if ((y % 2) != 0)] return result<|docstring|>This function takes two list, compares each element, if list 1 ahs even element and list 2 has odd element then they are added else ignored # Input: a: List (Input List 1) b: List (Input List 2) # Returns: list: Once the addition is done, the result is stored in the list and returned. # Functionality: The two lists are zipped and each tuple is iterated, element 1 of the tuple is checked of eveness and element b of the tuple is checked for oddness, if the condition is satisfied then they are added and the result is stored in a list.<|endoftext|>
a87fe247be6569fee9be94104436c55022cf81e7200dddc912e51f424ea2bb52
def my_alphabet(mystring: str) -> str: '\n This function takes in string as inmput and checks if it contains any vowel\n it removed all the vowels from the string and returns it\n \n # Input:\n mystring: str (Input string over which vowel check operation will be performed.)\n \n # Returns:\n str: string with no vowels\n \n # Functionality:\n This function iterates over the elements of the string and checks if each element \n is in vowel list or not. if not then it adds to a list.\n the list later is then converted to string using join function.\n ' vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] result = ''.join([x for x in mystring if (x not in vowels)]) return result
This function takes in string as inmput and checks if it contains any vowel it removed all the vowels from the string and returns it # Input: mystring: str (Input string over which vowel check operation will be performed.) # Returns: str: string with no vowels # Functionality: This function iterates over the elements of the string and checks if each element is in vowel list or not. if not then it adds to a list. the list later is then converted to string using join function.
07. First Class Function 2/Session7.py
my_alphabet
arghya05/EPAi
1
python
def my_alphabet(mystring: str) -> str: '\n This function takes in string as inmput and checks if it contains any vowel\n it removed all the vowels from the string and returns it\n \n # Input:\n mystring: str (Input string over which vowel check operation will be performed.)\n \n # Returns:\n str: string with no vowels\n \n # Functionality:\n This function iterates over the elements of the string and checks if each element \n is in vowel list or not. if not then it adds to a list.\n the list later is then converted to string using join function.\n ' vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] result = .join([x for x in mystring if (x not in vowels)]) return result
def my_alphabet(mystring: str) -> str: '\n This function takes in string as inmput and checks if it contains any vowel\n it removed all the vowels from the string and returns it\n \n # Input:\n mystring: str (Input string over which vowel check operation will be performed.)\n \n # Returns:\n str: string with no vowels\n \n # Functionality:\n This function iterates over the elements of the string and checks if each element \n is in vowel list or not. if not then it adds to a list.\n the list later is then converted to string using join function.\n ' vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] result = .join([x for x in mystring if (x not in vowels)]) return result<|docstring|>This function takes in string as inmput and checks if it contains any vowel it removed all the vowels from the string and returns it # Input: mystring: str (Input string over which vowel check operation will be performed.) # Returns: str: string with no vowels # Functionality: This function iterates over the elements of the string and checks if each element is in vowel list or not. if not then it adds to a list. the list later is then converted to string using join function.<|endoftext|>
45e1393a42da2201a757a2bd66ce4a5b5ecb9f4a78c7508310cec357b52de16c
def my_relu(mylist: list) -> list: '\n This function takes in list as an input and converts all the negative value of the \n list to positive and keeps positive values intact.\n\n # Input:\n mylist: list(It is a list of integers given by the user)\n \n # Returns: \n list: returns the corrected list\n \n # Functionality:\n Each element of the input list is checked for positive, \n if it is negative then it is replaced with 0.\n ' result = [(x if (x >= 0) else 0) for x in mylist] return result
This function takes in list as an input and converts all the negative value of the list to positive and keeps positive values intact. # Input: mylist: list(It is a list of integers given by the user) # Returns: list: returns the corrected list # Functionality: Each element of the input list is checked for positive, if it is negative then it is replaced with 0.
07. First Class Function 2/Session7.py
my_relu
arghya05/EPAi
1
python
def my_relu(mylist: list) -> list: '\n This function takes in list as an input and converts all the negative value of the \n list to positive and keeps positive values intact.\n\n # Input:\n mylist: list(It is a list of integers given by the user)\n \n # Returns: \n list: returns the corrected list\n \n # Functionality:\n Each element of the input list is checked for positive, \n if it is negative then it is replaced with 0.\n ' result = [(x if (x >= 0) else 0) for x in mylist] return result
def my_relu(mylist: list) -> list: '\n This function takes in list as an input and converts all the negative value of the \n list to positive and keeps positive values intact.\n\n # Input:\n mylist: list(It is a list of integers given by the user)\n \n # Returns: \n list: returns the corrected list\n \n # Functionality:\n Each element of the input list is checked for positive, \n if it is negative then it is replaced with 0.\n ' result = [(x if (x >= 0) else 0) for x in mylist] return result<|docstring|>This function takes in list as an input and converts all the negative value of the list to positive and keeps positive values intact. # Input: mylist: list(It is a list of integers given by the user) # Returns: list: returns the corrected list # Functionality: Each element of the input list is checked for positive, if it is negative then it is replaced with 0.<|endoftext|>
e83da14de182722ae0d40ad9985db9e924027b7ae41bfc252eb4ace43ba805ca
def sigmoid(x: int) -> float: '\n This function squeezes value to 0 to 1.\n \n # Input: \n x: int, it is the number whose sigmoid has to be calculated\n \n # Returns:\n float: This function returns the sigmoid value of the number\n \n # Functionality:\n This function takes a number and performs a\n sigmoid operation over it and returns the result\n ' return (1 / (1 + math.exp((- x))))
This function squeezes value to 0 to 1. # Input: x: int, it is the number whose sigmoid has to be calculated # Returns: float: This function returns the sigmoid value of the number # Functionality: This function takes a number and performs a sigmoid operation over it and returns the result
07. First Class Function 2/Session7.py
sigmoid
arghya05/EPAi
1
python
def sigmoid(x: int) -> float: '\n This function squeezes value to 0 to 1.\n \n # Input: \n x: int, it is the number whose sigmoid has to be calculated\n \n # Returns:\n float: This function returns the sigmoid value of the number\n \n # Functionality:\n This function takes a number and performs a\n sigmoid operation over it and returns the result\n ' return (1 / (1 + math.exp((- x))))
def sigmoid(x: int) -> float: '\n This function squeezes value to 0 to 1.\n \n # Input: \n x: int, it is the number whose sigmoid has to be calculated\n \n # Returns:\n float: This function returns the sigmoid value of the number\n \n # Functionality:\n This function takes a number and performs a\n sigmoid operation over it and returns the result\n ' return (1 / (1 + math.exp((- x))))<|docstring|>This function squeezes value to 0 to 1. # Input: x: int, it is the number whose sigmoid has to be calculated # Returns: float: This function returns the sigmoid value of the number # Functionality: This function takes a number and performs a sigmoid operation over it and returns the result<|endoftext|>
5cc0517ef258337c3809f20355f47748ff16284f6d0ad1719bb33f59ba536c94
def mysigmoid(mylist: list) -> list: '\n This function converted each element of the input list to its sigmoid form\n\n # Input:\n mylist: list, This is the input list where sigmoid operation is performed \n\n # Returns:\n list: It returns the transformed list\n\n # Functionality:\n The input list is iterated and each element is passed as a parameter to sigmoid function\n the result is stored in another list and returned\n\n ' result = [sigmoid(x) for x in mylist] return result
This function converted each element of the input list to its sigmoid form # Input: mylist: list, This is the input list where sigmoid operation is performed # Returns: list: It returns the transformed list # Functionality: The input list is iterated and each element is passed as a parameter to sigmoid function the result is stored in another list and returned
07. First Class Function 2/Session7.py
mysigmoid
arghya05/EPAi
1
python
def mysigmoid(mylist: list) -> list: '\n This function converted each element of the input list to its sigmoid form\n\n # Input:\n mylist: list, This is the input list where sigmoid operation is performed \n\n # Returns:\n list: It returns the transformed list\n\n # Functionality:\n The input list is iterated and each element is passed as a parameter to sigmoid function\n the result is stored in another list and returned\n\n ' result = [sigmoid(x) for x in mylist] return result
def mysigmoid(mylist: list) -> list: '\n This function converted each element of the input list to its sigmoid form\n\n # Input:\n mylist: list, This is the input list where sigmoid operation is performed \n\n # Returns:\n list: It returns the transformed list\n\n # Functionality:\n The input list is iterated and each element is passed as a parameter to sigmoid function\n the result is stored in another list and returned\n\n ' result = [sigmoid(x) for x in mylist] return result<|docstring|>This function converted each element of the input list to its sigmoid form # Input: mylist: list, This is the input list where sigmoid operation is performed # Returns: list: It returns the transformed list # Functionality: The input list is iterated and each element is passed as a parameter to sigmoid function the result is stored in another list and returned<|endoftext|>
6531630e0a03d8db804fa1b0d941c26f6796b1bb24331938cc069380da24b7ce
def mycipher(mystring: str) -> str: '\n This function performs an alphabatical cipher\n\n # Input:\n mystring: str, String over which cipher has to be done\n \n # Returns:\n str: Encrypted String\n \n # Funcationality:\n We need to shift each character by 5, if it is on the bottleneck, it starts again from a.\n here only lowercase alphabets are used. so we check if the order of input character is \n + 5 greater than ord of z, then we substract 26 out of it resuling in -21 (5-26) else\n we add it directly. \n ' result = ''.join([(chr((ord(x) - 21)) if ((ord(x) + 5) > ord('z')) else chr((ord(x) + 5))) for x in mystring]) return result
This function performs an alphabatical cipher # Input: mystring: str, String over which cipher has to be done # Returns: str: Encrypted String # Funcationality: We need to shift each character by 5, if it is on the bottleneck, it starts again from a. here only lowercase alphabets are used. so we check if the order of input character is + 5 greater than ord of z, then we substract 26 out of it resuling in -21 (5-26) else we add it directly.
07. First Class Function 2/Session7.py
mycipher
arghya05/EPAi
1
python
def mycipher(mystring: str) -> str: '\n This function performs an alphabatical cipher\n\n # Input:\n mystring: str, String over which cipher has to be done\n \n # Returns:\n str: Encrypted String\n \n # Funcationality:\n We need to shift each character by 5, if it is on the bottleneck, it starts again from a.\n here only lowercase alphabets are used. so we check if the order of input character is \n + 5 greater than ord of z, then we substract 26 out of it resuling in -21 (5-26) else\n we add it directly. \n ' result = .join([(chr((ord(x) - 21)) if ((ord(x) + 5) > ord('z')) else chr((ord(x) + 5))) for x in mystring]) return result
def mycipher(mystring: str) -> str: '\n This function performs an alphabatical cipher\n\n # Input:\n mystring: str, String over which cipher has to be done\n \n # Returns:\n str: Encrypted String\n \n # Funcationality:\n We need to shift each character by 5, if it is on the bottleneck, it starts again from a.\n here only lowercase alphabets are used. so we check if the order of input character is \n + 5 greater than ord of z, then we substract 26 out of it resuling in -21 (5-26) else\n we add it directly. \n ' result = .join([(chr((ord(x) - 21)) if ((ord(x) + 5) > ord('z')) else chr((ord(x) + 5))) for x in mystring]) return result<|docstring|>This function performs an alphabatical cipher # Input: mystring: str, String over which cipher has to be done # Returns: str: Encrypted String # Funcationality: We need to shift each character by 5, if it is on the bottleneck, it starts again from a. here only lowercase alphabets are used. so we check if the order of input character is + 5 greater than ord of z, then we substract 26 out of it resuling in -21 (5-26) else we add it directly.<|endoftext|>
952cd912de63da58e23182d8f633955fac6a522ff8d488f2c5dc3e9b887b1ed5
def detox(mypara: str) -> bool: '\n This function is used to check if bad words are present in a paragraph or not and flag them\n \n # Input:\n mypara: str, Input paragraph given by the user\n\n # Returns:\n bool: It returns True if any bad word found else returns false\n\n # Functionality:\n The paragraph is split into words and then each word is compared with the bad word list and \n is being flagged, if any true flag is seen, the para is marked as toxic.\n ' if (len(mypara.split()) < 200): raise ValueError('Paragraph length should be minimum 200') lines = ['4r5e', '5h1t', '5hit', 'a55', 'anal', 'anus', 'ar5e', 'arrse', 'arse', 'ass', 'ass-fucker', 'asses', 'assfucker', 'assfukka', 'asshole', 'assholes', 'asswhole', 'a_s_s', 'b!tch', 'b00bs', 'b17ch', 'b1tch', 'ballbag', 'balls', 'ballsack', 'bastard', 'beastial', 'beastiality', 'bellend', 'bestial', 'bestiality', 'bi+ch', 'biatch', 'bitch', 'bitcher', 'bitchers', 'bitches', 'bitchin', 'bitching', 'bloody', 'blow job', 'blowjob', 'blowjobs', 'boiolas', 'bollock', 'bollok', 'boner', 'boob', 'boobs', 'booobs', 'boooobs', 'booooobs', 'booooooobs', 'breasts', 'buceta', 'bugger', 'bum', 'bunny fucker', 'butt', 'butthole', 'buttmunch', 'buttplug', 'c0ck', 'c0cksucker', 'carpet muncher', 'cawk', 'chink', 'cipa', 'cl1t', 'clit', 'clitoris', 'clits', 'cnut', 'cock', 'cock-sucker', 'cockface', 'cockhead', 'cockmunch', 'cockmuncher', 'cocks', 'cocksuck ', 'cocksucked ', 'cocksucker', 'cocksucking', 'cocksucks ', 'cocksuka', 'cocksukka', 'cok', 'cokmuncher', 'coksucka', 'coon', 'cox', 'crap', 'cum', 'cummer', 'cumming', 'cums', 'cumshot', 'cunilingus', 'cunillingus', 'cunnilingus', 'cunt', 'cuntlick ', 'cuntlicker ', 'cuntlicking ', 'cunts', 'cyalis', 'cyberfuc', 'cyberfuck ', 'cyberfucked ', 'cyberfucker', 'cyberfuckers', 'cyberfucking ', 'd1ck', 'damn', 'dick', 'dickhead', 'dildo', 'dildos', 'dink', 'dinks', 'dirsa', 'dlck', 'dog-fucker', 'doggin', 'dogging', 'donkeyribber', 'doosh', 'duche', 'dyke', 'ejaculate', 'ejaculated', 'ejaculates ', 'ejaculating ', 'ejaculatings', 'ejaculation', 'ejakulate', 'f u c k', 'f u c k e r', 'f4nny', 'fag', 'fagging', 'faggitt', 'faggot', 'faggs', 'fagot', 'fagots', 'fags', 'fanny', 'fannyflaps', 'fannyfucker', 'fanyy', 'fatass', 'fcuk', 'fcuker', 'fcuking', 'feck', 'fecker', 'felching', 'fellate', 'fellatio', 'fingerfuck ', 'fingerfucked ', 'fingerfucker ', 'fingerfuckers', 'fingerfucking ', 'fingerfucks ', 'fistfuck', 'fistfucked ', 'fistfucker ', 'fistfuckers ', 'fistfucking ', 'fistfuckings ', 'fistfucks ', 'flange', 'fook', 'fooker', 'fuck', 'fucka', 'fucked', 'fucker', 'fuckers', 'fuckhead', 'fuckheads', 'fuckin', 'fucking', 'fuckings', 'fuckingshitmotherfucker', 'fuckme ', 'fucks', 'fuckwhit', 'fuckwit', 'fudge packer', 'fudgepacker', 'fuk', 'fuker', 'fukker', 'fukkin', 'fuks', 'fukwhit', 'fukwit', 'fux', 'fux0r', 'f_u_c_k', 'gangbang', 'gangbanged ', 'gangbangs ', 'gaylord', 'gaysex', 'goatse', 'God', 'god-dam', 'god-damned', 'goddamn', 'goddamned', 'hardcoresex ', 'hell', 'heshe', 'hoar', 'hoare', 'hoer', 'homo', 'hore', 'horniest', 'horny', 'hotsex', 'jack-off ', 'jackoff', 'jap', 'jerk-off ', 'jism', 'jiz ', 'jizm ', 'jizz', 'kawk', 'knob', 'knobead', 'knobed', 'knobend', 'knobhead', 'knobjocky', 'knobjokey', 'kock', 'kondum', 'kondums', 'kum', 'kummer', 'kumming', 'kums', 'kunilingus', 'l3i+ch', 'l3itch', 'labia', 'lmfao', 'lust', 'lusting', 'm0f0', 'm0fo', 'm45terbate', 'ma5terb8', 'ma5terbate', 'masochist', 'master-bate', 'masterb8', 'masterbat*', 'masterbat3', 'masterbate', 'masterbation', 'masterbations', 'masturbate', 'mo-fo', 'mof0', 'mofo', 'mothafuck', 'mothafucka', 'mothafuckas', 'mothafuckaz', 'mothafucked ', 'mothafucker', 'mothafuckers', 'mothafuckin', 'mothafucking ', 'mothafuckings', 'mothafucks', 'mother fucker', 'motherfuck', 'motherfucked', 'motherfucker', 'motherfuckers', 'motherfuckin', 'motherfucking', 'motherfuckings', 'motherfuckka', 'motherfucks', 'muff', 'mutha', 'muthafecker', 'muthafuckker', 'muther', 'mutherfucker', 'n1gga', 'n1gger', 'nazi', 'nigg3r', 'nigg4h', 'nigga', 'niggah', 'niggas', 'niggaz', 'nigger', 'niggers ', 'nob', 'nob jokey', 'nobhead', 'nobjocky', 'nobjokey', 'numbnuts', 'nutsack', 'orgasim ', 'orgasims ', 'orgasm', 'orgasms ', 'p0rn', 'pawn', 'pecker', 'penis', 'penisfucker', 'phonesex', 'phuck', 'phuk', 'phuked', 'phuking', 'phukked', 'phukking', 'phuks', 'phuq', 'pigfucker', 'pimpis', 'piss', 'pissed', 'pisser', 'pissers', 'pisses ', 'pissflaps', 'pissin ', 'pissing', 'pissoff ', 'poop', 'porn', 'porno', 'pornography', 'pornos', 'prick', 'pricks ', 'pron', 'pube', 'pusse', 'pussi', 'pussies', 'pussy', 'pussys ', 'rectum', 'retard', 'rimjaw', 'rimming', 's hit', 's.o.b.', 'sadist', 'schlong', 'screwing', 'scroat', 'scrote', 'scrotum', 'semen', 'sex', 'sh!+', 'sh!t', 'sh1t', 'shag', 'shagger', 'shaggin', 'shagging', 'shemale', 'shi+', 'shit', 'shitdick', 'shite', 'shited', 'shitey', 'shitfuck', 'shitfull', 'shithead', 'shiting', 'shitings', 'shits', 'shitted', 'shitter', 'shitters ', 'shitting', 'shittings', 'shitty ', 'skank', 'slut', 'sluts', 'smegma', 'smut', 'snatch', 'son-of-a-bitch', 'spac', 'spunk', 's_h_i_t', 't1tt1e5', 't1tties', 'teets', 'teez', 'testical', 'testicle', 'tit', 'titfuck', 'tits', 'titt', 'tittie5', 'tittiefucker', 'titties', 'tittyfuck', 'tittywank', 'titwank', 'tosser', 'turd', 'tw4t', 'twat', 'twathead', 'twatty', 'twunt', 'twunter', 'v14gra', 'v1gra', 'vagina', 'viagra', 'vulva', 'w00se', 'wang', 'wank', 'wanker', 'wanky', 'whoar', 'whore', 'willies', 'willy', 'xrated', 'xxx'] result = any([(False if (x not in lines) else True) for x in mypara.split()]) return result
This function is used to check if bad words are present in a paragraph or not and flag them # Input: mypara: str, Input paragraph given by the user # Returns: bool: It returns True if any bad word found else returns false # Functionality: The paragraph is split into words and then each word is compared with the bad word list and is being flagged, if any true flag is seen, the para is marked as toxic.
07. First Class Function 2/Session7.py
detox
arghya05/EPAi
1
python
def detox(mypara: str) -> bool: '\n This function is used to check if bad words are present in a paragraph or not and flag them\n \n # Input:\n mypara: str, Input paragraph given by the user\n\n # Returns:\n bool: It returns True if any bad word found else returns false\n\n # Functionality:\n The paragraph is split into words and then each word is compared with the bad word list and \n is being flagged, if any true flag is seen, the para is marked as toxic.\n ' if (len(mypara.split()) < 200): raise ValueError('Paragraph length should be minimum 200') lines = ['4r5e', '5h1t', '5hit', 'a55', 'anal', 'anus', 'ar5e', 'arrse', 'arse', 'ass', 'ass-fucker', 'asses', 'assfucker', 'assfukka', 'asshole', 'assholes', 'asswhole', 'a_s_s', 'b!tch', 'b00bs', 'b17ch', 'b1tch', 'ballbag', 'balls', 'ballsack', 'bastard', 'beastial', 'beastiality', 'bellend', 'bestial', 'bestiality', 'bi+ch', 'biatch', 'bitch', 'bitcher', 'bitchers', 'bitches', 'bitchin', 'bitching', 'bloody', 'blow job', 'blowjob', 'blowjobs', 'boiolas', 'bollock', 'bollok', 'boner', 'boob', 'boobs', 'booobs', 'boooobs', 'booooobs', 'booooooobs', 'breasts', 'buceta', 'bugger', 'bum', 'bunny fucker', 'butt', 'butthole', 'buttmunch', 'buttplug', 'c0ck', 'c0cksucker', 'carpet muncher', 'cawk', 'chink', 'cipa', 'cl1t', 'clit', 'clitoris', 'clits', 'cnut', 'cock', 'cock-sucker', 'cockface', 'cockhead', 'cockmunch', 'cockmuncher', 'cocks', 'cocksuck ', 'cocksucked ', 'cocksucker', 'cocksucking', 'cocksucks ', 'cocksuka', 'cocksukka', 'cok', 'cokmuncher', 'coksucka', 'coon', 'cox', 'crap', 'cum', 'cummer', 'cumming', 'cums', 'cumshot', 'cunilingus', 'cunillingus', 'cunnilingus', 'cunt', 'cuntlick ', 'cuntlicker ', 'cuntlicking ', 'cunts', 'cyalis', 'cyberfuc', 'cyberfuck ', 'cyberfucked ', 'cyberfucker', 'cyberfuckers', 'cyberfucking ', 'd1ck', 'damn', 'dick', 'dickhead', 'dildo', 'dildos', 'dink', 'dinks', 'dirsa', 'dlck', 'dog-fucker', 'doggin', 'dogging', 'donkeyribber', 'doosh', 'duche', 'dyke', 'ejaculate', 'ejaculated', 'ejaculates ', 'ejaculating ', 'ejaculatings', 'ejaculation', 'ejakulate', 'f u c k', 'f u c k e r', 'f4nny', 'fag', 'fagging', 'faggitt', 'faggot', 'faggs', 'fagot', 'fagots', 'fags', 'fanny', 'fannyflaps', 'fannyfucker', 'fanyy', 'fatass', 'fcuk', 'fcuker', 'fcuking', 'feck', 'fecker', 'felching', 'fellate', 'fellatio', 'fingerfuck ', 'fingerfucked ', 'fingerfucker ', 'fingerfuckers', 'fingerfucking ', 'fingerfucks ', 'fistfuck', 'fistfucked ', 'fistfucker ', 'fistfuckers ', 'fistfucking ', 'fistfuckings ', 'fistfucks ', 'flange', 'fook', 'fooker', 'fuck', 'fucka', 'fucked', 'fucker', 'fuckers', 'fuckhead', 'fuckheads', 'fuckin', 'fucking', 'fuckings', 'fuckingshitmotherfucker', 'fuckme ', 'fucks', 'fuckwhit', 'fuckwit', 'fudge packer', 'fudgepacker', 'fuk', 'fuker', 'fukker', 'fukkin', 'fuks', 'fukwhit', 'fukwit', 'fux', 'fux0r', 'f_u_c_k', 'gangbang', 'gangbanged ', 'gangbangs ', 'gaylord', 'gaysex', 'goatse', 'God', 'god-dam', 'god-damned', 'goddamn', 'goddamned', 'hardcoresex ', 'hell', 'heshe', 'hoar', 'hoare', 'hoer', 'homo', 'hore', 'horniest', 'horny', 'hotsex', 'jack-off ', 'jackoff', 'jap', 'jerk-off ', 'jism', 'jiz ', 'jizm ', 'jizz', 'kawk', 'knob', 'knobead', 'knobed', 'knobend', 'knobhead', 'knobjocky', 'knobjokey', 'kock', 'kondum', 'kondums', 'kum', 'kummer', 'kumming', 'kums', 'kunilingus', 'l3i+ch', 'l3itch', 'labia', 'lmfao', 'lust', 'lusting', 'm0f0', 'm0fo', 'm45terbate', 'ma5terb8', 'ma5terbate', 'masochist', 'master-bate', 'masterb8', 'masterbat*', 'masterbat3', 'masterbate', 'masterbation', 'masterbations', 'masturbate', 'mo-fo', 'mof0', 'mofo', 'mothafuck', 'mothafucka', 'mothafuckas', 'mothafuckaz', 'mothafucked ', 'mothafucker', 'mothafuckers', 'mothafuckin', 'mothafucking ', 'mothafuckings', 'mothafucks', 'mother fucker', 'motherfuck', 'motherfucked', 'motherfucker', 'motherfuckers', 'motherfuckin', 'motherfucking', 'motherfuckings', 'motherfuckka', 'motherfucks', 'muff', 'mutha', 'muthafecker', 'muthafuckker', 'muther', 'mutherfucker', 'n1gga', 'n1gger', 'nazi', 'nigg3r', 'nigg4h', 'nigga', 'niggah', 'niggas', 'niggaz', 'nigger', 'niggers ', 'nob', 'nob jokey', 'nobhead', 'nobjocky', 'nobjokey', 'numbnuts', 'nutsack', 'orgasim ', 'orgasims ', 'orgasm', 'orgasms ', 'p0rn', 'pawn', 'pecker', 'penis', 'penisfucker', 'phonesex', 'phuck', 'phuk', 'phuked', 'phuking', 'phukked', 'phukking', 'phuks', 'phuq', 'pigfucker', 'pimpis', 'piss', 'pissed', 'pisser', 'pissers', 'pisses ', 'pissflaps', 'pissin ', 'pissing', 'pissoff ', 'poop', 'porn', 'porno', 'pornography', 'pornos', 'prick', 'pricks ', 'pron', 'pube', 'pusse', 'pussi', 'pussies', 'pussy', 'pussys ', 'rectum', 'retard', 'rimjaw', 'rimming', 's hit', 's.o.b.', 'sadist', 'schlong', 'screwing', 'scroat', 'scrote', 'scrotum', 'semen', 'sex', 'sh!+', 'sh!t', 'sh1t', 'shag', 'shagger', 'shaggin', 'shagging', 'shemale', 'shi+', 'shit', 'shitdick', 'shite', 'shited', 'shitey', 'shitfuck', 'shitfull', 'shithead', 'shiting', 'shitings', 'shits', 'shitted', 'shitter', 'shitters ', 'shitting', 'shittings', 'shitty ', 'skank', 'slut', 'sluts', 'smegma', 'smut', 'snatch', 'son-of-a-bitch', 'spac', 'spunk', 's_h_i_t', 't1tt1e5', 't1tties', 'teets', 'teez', 'testical', 'testicle', 'tit', 'titfuck', 'tits', 'titt', 'tittie5', 'tittiefucker', 'titties', 'tittyfuck', 'tittywank', 'titwank', 'tosser', 'turd', 'tw4t', 'twat', 'twathead', 'twatty', 'twunt', 'twunter', 'v14gra', 'v1gra', 'vagina', 'viagra', 'vulva', 'w00se', 'wang', 'wank', 'wanker', 'wanky', 'whoar', 'whore', 'willies', 'willy', 'xrated', 'xxx'] result = any([(False if (x not in lines) else True) for x in mypara.split()]) return result
def detox(mypara: str) -> bool: '\n This function is used to check if bad words are present in a paragraph or not and flag them\n \n # Input:\n mypara: str, Input paragraph given by the user\n\n # Returns:\n bool: It returns True if any bad word found else returns false\n\n # Functionality:\n The paragraph is split into words and then each word is compared with the bad word list and \n is being flagged, if any true flag is seen, the para is marked as toxic.\n ' if (len(mypara.split()) < 200): raise ValueError('Paragraph length should be minimum 200') lines = ['4r5e', '5h1t', '5hit', 'a55', 'anal', 'anus', 'ar5e', 'arrse', 'arse', 'ass', 'ass-fucker', 'asses', 'assfucker', 'assfukka', 'asshole', 'assholes', 'asswhole', 'a_s_s', 'b!tch', 'b00bs', 'b17ch', 'b1tch', 'ballbag', 'balls', 'ballsack', 'bastard', 'beastial', 'beastiality', 'bellend', 'bestial', 'bestiality', 'bi+ch', 'biatch', 'bitch', 'bitcher', 'bitchers', 'bitches', 'bitchin', 'bitching', 'bloody', 'blow job', 'blowjob', 'blowjobs', 'boiolas', 'bollock', 'bollok', 'boner', 'boob', 'boobs', 'booobs', 'boooobs', 'booooobs', 'booooooobs', 'breasts', 'buceta', 'bugger', 'bum', 'bunny fucker', 'butt', 'butthole', 'buttmunch', 'buttplug', 'c0ck', 'c0cksucker', 'carpet muncher', 'cawk', 'chink', 'cipa', 'cl1t', 'clit', 'clitoris', 'clits', 'cnut', 'cock', 'cock-sucker', 'cockface', 'cockhead', 'cockmunch', 'cockmuncher', 'cocks', 'cocksuck ', 'cocksucked ', 'cocksucker', 'cocksucking', 'cocksucks ', 'cocksuka', 'cocksukka', 'cok', 'cokmuncher', 'coksucka', 'coon', 'cox', 'crap', 'cum', 'cummer', 'cumming', 'cums', 'cumshot', 'cunilingus', 'cunillingus', 'cunnilingus', 'cunt', 'cuntlick ', 'cuntlicker ', 'cuntlicking ', 'cunts', 'cyalis', 'cyberfuc', 'cyberfuck ', 'cyberfucked ', 'cyberfucker', 'cyberfuckers', 'cyberfucking ', 'd1ck', 'damn', 'dick', 'dickhead', 'dildo', 'dildos', 'dink', 'dinks', 'dirsa', 'dlck', 'dog-fucker', 'doggin', 'dogging', 'donkeyribber', 'doosh', 'duche', 'dyke', 'ejaculate', 'ejaculated', 'ejaculates ', 'ejaculating ', 'ejaculatings', 'ejaculation', 'ejakulate', 'f u c k', 'f u c k e r', 'f4nny', 'fag', 'fagging', 'faggitt', 'faggot', 'faggs', 'fagot', 'fagots', 'fags', 'fanny', 'fannyflaps', 'fannyfucker', 'fanyy', 'fatass', 'fcuk', 'fcuker', 'fcuking', 'feck', 'fecker', 'felching', 'fellate', 'fellatio', 'fingerfuck ', 'fingerfucked ', 'fingerfucker ', 'fingerfuckers', 'fingerfucking ', 'fingerfucks ', 'fistfuck', 'fistfucked ', 'fistfucker ', 'fistfuckers ', 'fistfucking ', 'fistfuckings ', 'fistfucks ', 'flange', 'fook', 'fooker', 'fuck', 'fucka', 'fucked', 'fucker', 'fuckers', 'fuckhead', 'fuckheads', 'fuckin', 'fucking', 'fuckings', 'fuckingshitmotherfucker', 'fuckme ', 'fucks', 'fuckwhit', 'fuckwit', 'fudge packer', 'fudgepacker', 'fuk', 'fuker', 'fukker', 'fukkin', 'fuks', 'fukwhit', 'fukwit', 'fux', 'fux0r', 'f_u_c_k', 'gangbang', 'gangbanged ', 'gangbangs ', 'gaylord', 'gaysex', 'goatse', 'God', 'god-dam', 'god-damned', 'goddamn', 'goddamned', 'hardcoresex ', 'hell', 'heshe', 'hoar', 'hoare', 'hoer', 'homo', 'hore', 'horniest', 'horny', 'hotsex', 'jack-off ', 'jackoff', 'jap', 'jerk-off ', 'jism', 'jiz ', 'jizm ', 'jizz', 'kawk', 'knob', 'knobead', 'knobed', 'knobend', 'knobhead', 'knobjocky', 'knobjokey', 'kock', 'kondum', 'kondums', 'kum', 'kummer', 'kumming', 'kums', 'kunilingus', 'l3i+ch', 'l3itch', 'labia', 'lmfao', 'lust', 'lusting', 'm0f0', 'm0fo', 'm45terbate', 'ma5terb8', 'ma5terbate', 'masochist', 'master-bate', 'masterb8', 'masterbat*', 'masterbat3', 'masterbate', 'masterbation', 'masterbations', 'masturbate', 'mo-fo', 'mof0', 'mofo', 'mothafuck', 'mothafucka', 'mothafuckas', 'mothafuckaz', 'mothafucked ', 'mothafucker', 'mothafuckers', 'mothafuckin', 'mothafucking ', 'mothafuckings', 'mothafucks', 'mother fucker', 'motherfuck', 'motherfucked', 'motherfucker', 'motherfuckers', 'motherfuckin', 'motherfucking', 'motherfuckings', 'motherfuckka', 'motherfucks', 'muff', 'mutha', 'muthafecker', 'muthafuckker', 'muther', 'mutherfucker', 'n1gga', 'n1gger', 'nazi', 'nigg3r', 'nigg4h', 'nigga', 'niggah', 'niggas', 'niggaz', 'nigger', 'niggers ', 'nob', 'nob jokey', 'nobhead', 'nobjocky', 'nobjokey', 'numbnuts', 'nutsack', 'orgasim ', 'orgasims ', 'orgasm', 'orgasms ', 'p0rn', 'pawn', 'pecker', 'penis', 'penisfucker', 'phonesex', 'phuck', 'phuk', 'phuked', 'phuking', 'phukked', 'phukking', 'phuks', 'phuq', 'pigfucker', 'pimpis', 'piss', 'pissed', 'pisser', 'pissers', 'pisses ', 'pissflaps', 'pissin ', 'pissing', 'pissoff ', 'poop', 'porn', 'porno', 'pornography', 'pornos', 'prick', 'pricks ', 'pron', 'pube', 'pusse', 'pussi', 'pussies', 'pussy', 'pussys ', 'rectum', 'retard', 'rimjaw', 'rimming', 's hit', 's.o.b.', 'sadist', 'schlong', 'screwing', 'scroat', 'scrote', 'scrotum', 'semen', 'sex', 'sh!+', 'sh!t', 'sh1t', 'shag', 'shagger', 'shaggin', 'shagging', 'shemale', 'shi+', 'shit', 'shitdick', 'shite', 'shited', 'shitey', 'shitfuck', 'shitfull', 'shithead', 'shiting', 'shitings', 'shits', 'shitted', 'shitter', 'shitters ', 'shitting', 'shittings', 'shitty ', 'skank', 'slut', 'sluts', 'smegma', 'smut', 'snatch', 'son-of-a-bitch', 'spac', 'spunk', 's_h_i_t', 't1tt1e5', 't1tties', 'teets', 'teez', 'testical', 'testicle', 'tit', 'titfuck', 'tits', 'titt', 'tittie5', 'tittiefucker', 'titties', 'tittyfuck', 'tittywank', 'titwank', 'tosser', 'turd', 'tw4t', 'twat', 'twathead', 'twatty', 'twunt', 'twunter', 'v14gra', 'v1gra', 'vagina', 'viagra', 'vulva', 'w00se', 'wang', 'wank', 'wanker', 'wanky', 'whoar', 'whore', 'willies', 'willy', 'xrated', 'xxx'] result = any([(False if (x not in lines) else True) for x in mypara.split()]) return result<|docstring|>This function is used to check if bad words are present in a paragraph or not and flag them # Input: mypara: str, Input paragraph given by the user # Returns: bool: It returns True if any bad word found else returns false # Functionality: The paragraph is split into words and then each word is compared with the bad word list and is being flagged, if any true flag is seen, the para is marked as toxic.<|endoftext|>
f97e3d320d0e62c3fc397ed9fe94c9954b822f111a2fe19dfc5e65962cb82a9c
def myadd(mynumbers: list) -> int: '\n This function adds only even numbers to list\n\n # Input:\n mynumbers: list, This is a list of numbers provided by theuser\n \n # Returns:\n int: It returns the calculated sum of the integers\n \n # Functionality:\n This function takes in list, filters out all the even number using filter and lambda \n and then passes that list to reduce function to add all the elements of it, then the result\n is returned back.\n\n ' result = reduce((lambda x, y: (x + y)), filter((lambda x: ((x % 2) == 0)), mynumbers)) return result
This function adds only even numbers to list # Input: mynumbers: list, This is a list of numbers provided by theuser # Returns: int: It returns the calculated sum of the integers # Functionality: This function takes in list, filters out all the even number using filter and lambda and then passes that list to reduce function to add all the elements of it, then the result is returned back.
07. First Class Function 2/Session7.py
myadd
arghya05/EPAi
1
python
def myadd(mynumbers: list) -> int: '\n This function adds only even numbers to list\n\n # Input:\n mynumbers: list, This is a list of numbers provided by theuser\n \n # Returns:\n int: It returns the calculated sum of the integers\n \n # Functionality:\n This function takes in list, filters out all the even number using filter and lambda \n and then passes that list to reduce function to add all the elements of it, then the result\n is returned back.\n\n ' result = reduce((lambda x, y: (x + y)), filter((lambda x: ((x % 2) == 0)), mynumbers)) return result
def myadd(mynumbers: list) -> int: '\n This function adds only even numbers to list\n\n # Input:\n mynumbers: list, This is a list of numbers provided by theuser\n \n # Returns:\n int: It returns the calculated sum of the integers\n \n # Functionality:\n This function takes in list, filters out all the even number using filter and lambda \n and then passes that list to reduce function to add all the elements of it, then the result\n is returned back.\n\n ' result = reduce((lambda x, y: (x + y)), filter((lambda x: ((x % 2) == 0)), mynumbers)) return result<|docstring|>This function adds only even numbers to list # Input: mynumbers: list, This is a list of numbers provided by theuser # Returns: int: It returns the calculated sum of the integers # Functionality: This function takes in list, filters out all the even number using filter and lambda and then passes that list to reduce function to add all the elements of it, then the result is returned back.<|endoftext|>
68ac985ae7c2c4c4a5efb4e39e00707799a2ef8ee6b5cda688469c6a9225a0e9
def mymaxchar(mystring: str) -> chr: '\n This function finds the max character from the string.\n\n # Input:\n mystring: list, String provided by theuser\n \n # Returns:\n chr: Biggest printable character in the string\n \n # Functionality:\n This function takes in string, and checks each element if the string with other\n to fundout which is the biggest one.\n ' result = reduce(max, mystring, ' ') return result
This function finds the max character from the string. # Input: mystring: list, String provided by theuser # Returns: chr: Biggest printable character in the string # Functionality: This function takes in string, and checks each element if the string with other to fundout which is the biggest one.
07. First Class Function 2/Session7.py
mymaxchar
arghya05/EPAi
1
python
def mymaxchar(mystring: str) -> chr: '\n This function finds the max character from the string.\n\n # Input:\n mystring: list, String provided by theuser\n \n # Returns:\n chr: Biggest printable character in the string\n \n # Functionality:\n This function takes in string, and checks each element if the string with other\n to fundout which is the biggest one.\n ' result = reduce(max, mystring, ' ') return result
def mymaxchar(mystring: str) -> chr: '\n This function finds the max character from the string.\n\n # Input:\n mystring: list, String provided by theuser\n \n # Returns:\n chr: Biggest printable character in the string\n \n # Functionality:\n This function takes in string, and checks each element if the string with other\n to fundout which is the biggest one.\n ' result = reduce(max, mystring, ' ') return result<|docstring|>This function finds the max character from the string. # Input: mystring: list, String provided by theuser # Returns: chr: Biggest printable character in the string # Functionality: This function takes in string, and checks each element if the string with other to fundout which is the biggest one.<|endoftext|>
86c68b8d16379b10330cd0d361970be3ea378ddfd93030160dd150d96c139cef
def my_atrangi_addition(mynumbers: list) -> int: '\n This function add every 3rd number in the list i.e. at index 2,5,8,...\n\n # Input:\n mynumber: list, This is a list of numbers provided by theuser\n \n # Returns:\n int: It returns the calculated sum of the integers\n \n # Functionality:\n This function takes in list, filters out the list containing all third elements \n and then it is added\n\n ' result = reduce((lambda x, y: (x + y)), mynumbers[2::3]) return result
This function add every 3rd number in the list i.e. at index 2,5,8,... # Input: mynumber: list, This is a list of numbers provided by theuser # Returns: int: It returns the calculated sum of the integers # Functionality: This function takes in list, filters out the list containing all third elements and then it is added
07. First Class Function 2/Session7.py
my_atrangi_addition
arghya05/EPAi
1
python
def my_atrangi_addition(mynumbers: list) -> int: '\n This function add every 3rd number in the list i.e. at index 2,5,8,...\n\n # Input:\n mynumber: list, This is a list of numbers provided by theuser\n \n # Returns:\n int: It returns the calculated sum of the integers\n \n # Functionality:\n This function takes in list, filters out the list containing all third elements \n and then it is added\n\n ' result = reduce((lambda x, y: (x + y)), mynumbers[2::3]) return result
def my_atrangi_addition(mynumbers: list) -> int: '\n This function add every 3rd number in the list i.e. at index 2,5,8,...\n\n # Input:\n mynumber: list, This is a list of numbers provided by theuser\n \n # Returns:\n int: It returns the calculated sum of the integers\n \n # Functionality:\n This function takes in list, filters out the list containing all third elements \n and then it is added\n\n ' result = reduce((lambda x, y: (x + y)), mynumbers[2::3]) return result<|docstring|>This function add every 3rd number in the list i.e. at index 2,5,8,... # Input: mynumber: list, This is a list of numbers provided by theuser # Returns: int: It returns the calculated sum of the integers # Functionality: This function takes in list, filters out the list containing all third elements and then it is added<|endoftext|>
6ccaf15b49efdb9ef5535ff6a824138484ac6bdfd1335a06bd01c78034f0cd7f
def mynumberplate() -> list: '\n This function is used to generate random number plates\n\n # Input:\n None\n \n # Returns:\n list: This function returns list of all the generated number plates.\n \n # Functionality\n The format of number plate has to be KADDAADDDD, D is digit and A is alphabet\n DD has to be in the range 10 to 99 where as DDDD has to be in the range 1000 to 9999\n AA has to be uppercase ascii character, A loop is run 25 times and these values are randomly picked and assigned\n\n ' result = [(((('KA' + str(random.randint(10, 100))) + random.choice(string.ascii_uppercase)) + random.choice(string.ascii_uppercase)) + str(random.randint(1000, 10000))) for _ in range(15)] return result
This function is used to generate random number plates # Input: None # Returns: list: This function returns list of all the generated number plates. # Functionality The format of number plate has to be KADDAADDDD, D is digit and A is alphabet DD has to be in the range 10 to 99 where as DDDD has to be in the range 1000 to 9999 AA has to be uppercase ascii character, A loop is run 25 times and these values are randomly picked and assigned
07. First Class Function 2/Session7.py
mynumberplate
arghya05/EPAi
1
python
def mynumberplate() -> list: '\n This function is used to generate random number plates\n\n # Input:\n None\n \n # Returns:\n list: This function returns list of all the generated number plates.\n \n # Functionality\n The format of number plate has to be KADDAADDDD, D is digit and A is alphabet\n DD has to be in the range 10 to 99 where as DDDD has to be in the range 1000 to 9999\n AA has to be uppercase ascii character, A loop is run 25 times and these values are randomly picked and assigned\n\n ' result = [(((('KA' + str(random.randint(10, 100))) + random.choice(string.ascii_uppercase)) + random.choice(string.ascii_uppercase)) + str(random.randint(1000, 10000))) for _ in range(15)] return result
def mynumberplate() -> list: '\n This function is used to generate random number plates\n\n # Input:\n None\n \n # Returns:\n list: This function returns list of all the generated number plates.\n \n # Functionality\n The format of number plate has to be KADDAADDDD, D is digit and A is alphabet\n DD has to be in the range 10 to 99 where as DDDD has to be in the range 1000 to 9999\n AA has to be uppercase ascii character, A loop is run 25 times and these values are randomly picked and assigned\n\n ' result = [(((('KA' + str(random.randint(10, 100))) + random.choice(string.ascii_uppercase)) + random.choice(string.ascii_uppercase)) + str(random.randint(1000, 10000))) for _ in range(15)] return result<|docstring|>This function is used to generate random number plates # Input: None # Returns: list: This function returns list of all the generated number plates. # Functionality The format of number plate has to be KADDAADDDD, D is digit and A is alphabet DD has to be in the range 10 to 99 where as DDDD has to be in the range 1000 to 9999 AA has to be uppercase ascii character, A loop is run 25 times and these values are randomly picked and assigned<|endoftext|>
ddf277d2fedadd4c53257eb3a582883f2ffe4647f2952ba1b1e89c0b84d06e65
def get_numberplate(numberplate: list) -> list: '\n This function is used to generate random number plates with user choice numbers\n\n # Input:\n None\n \n # Returns:\n list: This function returns list of all the generated number plates.\n \n # Functionality\n The format of number plate has to be KADDAADDDD/DLDDAADDDD, D is digit and A is alphabet\n DD has to be in the range 10 to 99 where as DDDD has to be in the range 1000 to 9999, chosen by the user\n AA has to be uppercase ascii character, A loop is run 25 times and these values are randomly picked and assigned\n\n ' result = [((((random.choice(['KA', 'DL']) + str(random.randint(10, 100))) + random.choice(string.ascii_uppercase)) + random.choice(string.ascii_uppercase)) + str(numberplate[_])) for _ in range(15)] return result
This function is used to generate random number plates with user choice numbers # Input: None # Returns: list: This function returns list of all the generated number plates. # Functionality The format of number plate has to be KADDAADDDD/DLDDAADDDD, D is digit and A is alphabet DD has to be in the range 10 to 99 where as DDDD has to be in the range 1000 to 9999, chosen by the user AA has to be uppercase ascii character, A loop is run 25 times and these values are randomly picked and assigned
07. First Class Function 2/Session7.py
get_numberplate
arghya05/EPAi
1
python
def get_numberplate(numberplate: list) -> list: '\n This function is used to generate random number plates with user choice numbers\n\n # Input:\n None\n \n # Returns:\n list: This function returns list of all the generated number plates.\n \n # Functionality\n The format of number plate has to be KADDAADDDD/DLDDAADDDD, D is digit and A is alphabet\n DD has to be in the range 10 to 99 where as DDDD has to be in the range 1000 to 9999, chosen by the user\n AA has to be uppercase ascii character, A loop is run 25 times and these values are randomly picked and assigned\n\n ' result = [((((random.choice(['KA', 'DL']) + str(random.randint(10, 100))) + random.choice(string.ascii_uppercase)) + random.choice(string.ascii_uppercase)) + str(numberplate[_])) for _ in range(15)] return result
def get_numberplate(numberplate: list) -> list: '\n This function is used to generate random number plates with user choice numbers\n\n # Input:\n None\n \n # Returns:\n list: This function returns list of all the generated number plates.\n \n # Functionality\n The format of number plate has to be KADDAADDDD/DLDDAADDDD, D is digit and A is alphabet\n DD has to be in the range 10 to 99 where as DDDD has to be in the range 1000 to 9999, chosen by the user\n AA has to be uppercase ascii character, A loop is run 25 times and these values are randomly picked and assigned\n\n ' result = [((((random.choice(['KA', 'DL']) + str(random.randint(10, 100))) + random.choice(string.ascii_uppercase)) + random.choice(string.ascii_uppercase)) + str(numberplate[_])) for _ in range(15)] return result<|docstring|>This function is used to generate random number plates with user choice numbers # Input: None # Returns: list: This function returns list of all the generated number plates. # Functionality The format of number plate has to be KADDAADDDD/DLDDAADDDD, D is digit and A is alphabet DD has to be in the range 10 to 99 where as DDDD has to be in the range 1000 to 9999, chosen by the user AA has to be uppercase ascii character, A loop is run 25 times and these values are randomly picked and assigned<|endoftext|>
62a27f1f3a7dc52f1f1b9cc3c790ce8a139f6b41d60300f8031519dba018c3f6
def my_number_plate(state_code: str, numberplate: int) -> str: '\n This function is used to generate custom number plates\n \n # Input:\n state_code: str\n numberplate:int \n \n # Returns:\n list: This function returns list of all the generated number plates.\n \n # Functionality\n The format of number plate has to be KADDAADDDD/DLDDAADDDD, D is digit and A is alphabet\n DD has to be in the range 10 to 99 where as DDDD has to be in the range 1000 to 9999, chosen by the user\n AA has to be uppercase ascii character, A loop is run 25 times and these values are randomly picked and assigned\n ' return ((((state_code + str(random.randint(10, 100))) + random.choice(string.ascii_uppercase)) + random.choice(string.ascii_uppercase)) + str(numberplate))
This function is used to generate custom number plates # Input: state_code: str numberplate:int # Returns: list: This function returns list of all the generated number plates. # Functionality The format of number plate has to be KADDAADDDD/DLDDAADDDD, D is digit and A is alphabet DD has to be in the range 10 to 99 where as DDDD has to be in the range 1000 to 9999, chosen by the user AA has to be uppercase ascii character, A loop is run 25 times and these values are randomly picked and assigned
07. First Class Function 2/Session7.py
my_number_plate
arghya05/EPAi
1
python
def my_number_plate(state_code: str, numberplate: int) -> str: '\n This function is used to generate custom number plates\n \n # Input:\n state_code: str\n numberplate:int \n \n # Returns:\n list: This function returns list of all the generated number plates.\n \n # Functionality\n The format of number plate has to be KADDAADDDD/DLDDAADDDD, D is digit and A is alphabet\n DD has to be in the range 10 to 99 where as DDDD has to be in the range 1000 to 9999, chosen by the user\n AA has to be uppercase ascii character, A loop is run 25 times and these values are randomly picked and assigned\n ' return ((((state_code + str(random.randint(10, 100))) + random.choice(string.ascii_uppercase)) + random.choice(string.ascii_uppercase)) + str(numberplate))
def my_number_plate(state_code: str, numberplate: int) -> str: '\n This function is used to generate custom number plates\n \n # Input:\n state_code: str\n numberplate:int \n \n # Returns:\n list: This function returns list of all the generated number plates.\n \n # Functionality\n The format of number plate has to be KADDAADDDD/DLDDAADDDD, D is digit and A is alphabet\n DD has to be in the range 10 to 99 where as DDDD has to be in the range 1000 to 9999, chosen by the user\n AA has to be uppercase ascii character, A loop is run 25 times and these values are randomly picked and assigned\n ' return ((((state_code + str(random.randint(10, 100))) + random.choice(string.ascii_uppercase)) + random.choice(string.ascii_uppercase)) + str(numberplate))<|docstring|>This function is used to generate custom number plates # Input: state_code: str numberplate:int # Returns: list: This function returns list of all the generated number plates. # Functionality The format of number plate has to be KADDAADDDD/DLDDAADDDD, D is digit and A is alphabet DD has to be in the range 10 to 99 where as DDDD has to be in the range 1000 to 9999, chosen by the user AA has to be uppercase ascii character, A loop is run 25 times and these values are randomly picked and assigned<|endoftext|>
b8344ca02ab955887698de3e84297a8baeca65f4fa3131a57528c68518de661d
def custom_numberplate(fn, statecode: str) -> str: '\n This function is used to create custom statewise numberplates\n\n # Input:\n fn: Funtion (It will be called inside the partial function)\n statecode: str\n \n # Returns:\n str: It return the numberplate in the string\n \n # Functionality:\n This function call partial function which takes function as the input and its variable as the \n parameter. statecode is something given by the user.\n\n ' f = partial(fn, state_code=statecode, numberplate=9999) return f
This function is used to create custom statewise numberplates # Input: fn: Funtion (It will be called inside the partial function) statecode: str # Returns: str: It return the numberplate in the string # Functionality: This function call partial function which takes function as the input and its variable as the parameter. statecode is something given by the user.
07. First Class Function 2/Session7.py
custom_numberplate
arghya05/EPAi
1
python
def custom_numberplate(fn, statecode: str) -> str: '\n This function is used to create custom statewise numberplates\n\n # Input:\n fn: Funtion (It will be called inside the partial function)\n statecode: str\n \n # Returns:\n str: It return the numberplate in the string\n \n # Functionality:\n This function call partial function which takes function as the input and its variable as the \n parameter. statecode is something given by the user.\n\n ' f = partial(fn, state_code=statecode, numberplate=9999) return f
def custom_numberplate(fn, statecode: str) -> str: '\n This function is used to create custom statewise numberplates\n\n # Input:\n fn: Funtion (It will be called inside the partial function)\n statecode: str\n \n # Returns:\n str: It return the numberplate in the string\n \n # Functionality:\n This function call partial function which takes function as the input and its variable as the \n parameter. statecode is something given by the user.\n\n ' f = partial(fn, state_code=statecode, numberplate=9999) return f<|docstring|>This function is used to create custom statewise numberplates # Input: fn: Funtion (It will be called inside the partial function) statecode: str # Returns: str: It return the numberplate in the string # Functionality: This function call partial function which takes function as the input and its variable as the parameter. statecode is something given by the user.<|endoftext|>
0d0296324269191e20c3b7425da9ed78d51d5e7dacd74de0ccdba31697734643
def __init__(self, name, value=None): '\n 初始化新实例 Vertex\n\n :param name: 顶点名称,不同网络可以拥有相同名称的顶点\n :param value: 顶点值,默认为None\n ' hash(name) self.name = name self.value = value
初始化新实例 Vertex :param name: 顶点名称,不同网络可以拥有相同名称的顶点 :param value: 顶点值,默认为None
Projects/src/graph.py
__init__
LonelySteve/data-structure-and-algorithms-tasks
1
python
def __init__(self, name, value=None): '\n 初始化新实例 Vertex\n\n :param name: 顶点名称,不同网络可以拥有相同名称的顶点\n :param value: 顶点值,默认为None\n ' hash(name) self.name = name self.value = value
def __init__(self, name, value=None): '\n 初始化新实例 Vertex\n\n :param name: 顶点名称,不同网络可以拥有相同名称的顶点\n :param value: 顶点值,默认为None\n ' hash(name) self.name = name self.value = value<|docstring|>初始化新实例 Vertex :param name: 顶点名称,不同网络可以拥有相同名称的顶点 :param value: 顶点值,默认为None<|endoftext|>
357b9599730c0475f58e7467edb6ab04ea9b9afbaf2cb341772b612d7d92ecf9
def __hash__(self): '获取哈希值' return hash(self.name)
获取哈希值
Projects/src/graph.py
__hash__
LonelySteve/data-structure-and-algorithms-tasks
1
python
def __hash__(self): return hash(self.name)
def __hash__(self): return hash(self.name)<|docstring|>获取哈希值<|endoftext|>
8aaee1ddb7ee0f100086a7322916561d7e03bc24f4460ebbf6ef1daf71a6371f
@property def adjacency_matrix(self): '获取邻接矩阵' temp_adjacency_matrix = [[self.DEFAULT_UNREACHABLE_MAX_VALUE for _ in range(len(self.vertexes))] for _ in range(len(self.vertexes))] adjacency_dict = self.adjacency_dict for (i, vertex) in enumerate(self.vertexes): for adj_vertex in adjacency_dict[vertex]: j = self.vertexes.index(adj_vertex) temp_adjacency_matrix[i][j] = self.DEFAULT_REACHABLE_VALUE try: edge = self.find_edge(vertex, adj_vertex) if (edge.weight is not None): temp_adjacency_matrix[i][j] = edge.weight except StopIteration: pass return temp_adjacency_matrix
获取邻接矩阵
Projects/src/graph.py
adjacency_matrix
LonelySteve/data-structure-and-algorithms-tasks
1
python
@property def adjacency_matrix(self): temp_adjacency_matrix = [[self.DEFAULT_UNREACHABLE_MAX_VALUE for _ in range(len(self.vertexes))] for _ in range(len(self.vertexes))] adjacency_dict = self.adjacency_dict for (i, vertex) in enumerate(self.vertexes): for adj_vertex in adjacency_dict[vertex]: j = self.vertexes.index(adj_vertex) temp_adjacency_matrix[i][j] = self.DEFAULT_REACHABLE_VALUE try: edge = self.find_edge(vertex, adj_vertex) if (edge.weight is not None): temp_adjacency_matrix[i][j] = edge.weight except StopIteration: pass return temp_adjacency_matrix
@property def adjacency_matrix(self): temp_adjacency_matrix = [[self.DEFAULT_UNREACHABLE_MAX_VALUE for _ in range(len(self.vertexes))] for _ in range(len(self.vertexes))] adjacency_dict = self.adjacency_dict for (i, vertex) in enumerate(self.vertexes): for adj_vertex in adjacency_dict[vertex]: j = self.vertexes.index(adj_vertex) temp_adjacency_matrix[i][j] = self.DEFAULT_REACHABLE_VALUE try: edge = self.find_edge(vertex, adj_vertex) if (edge.weight is not None): temp_adjacency_matrix[i][j] = edge.weight except StopIteration: pass return temp_adjacency_matrix<|docstring|>获取邻接矩阵<|endoftext|>
799b115ffdb8b7ab72d968a46ee06f59311874fca27fae669929bdd6523c67ee
@property def adjacency_dict(self): '获取邻接字典' temp_adj_dict = {v: [] for v in self.vertexes} for (v, row) in temp_adj_dict.items(): if (self.EDGE_CLS == DirectedEdge): for edge in (e for e in self.edges if (e.from_vertex == v)): row.append(edge.to_vertex) elif (self.EDGE_CLS == UndirectedEdge): for edge in (e for e in self.edges if e.has_vertex(v)): row.append(edge.other_vertex(v)) return temp_adj_dict
获取邻接字典
Projects/src/graph.py
adjacency_dict
LonelySteve/data-structure-and-algorithms-tasks
1
python
@property def adjacency_dict(self): temp_adj_dict = {v: [] for v in self.vertexes} for (v, row) in temp_adj_dict.items(): if (self.EDGE_CLS == DirectedEdge): for edge in (e for e in self.edges if (e.from_vertex == v)): row.append(edge.to_vertex) elif (self.EDGE_CLS == UndirectedEdge): for edge in (e for e in self.edges if e.has_vertex(v)): row.append(edge.other_vertex(v)) return temp_adj_dict
@property def adjacency_dict(self): temp_adj_dict = {v: [] for v in self.vertexes} for (v, row) in temp_adj_dict.items(): if (self.EDGE_CLS == DirectedEdge): for edge in (e for e in self.edges if (e.from_vertex == v)): row.append(edge.to_vertex) elif (self.EDGE_CLS == UndirectedEdge): for edge in (e for e in self.edges if e.has_vertex(v)): row.append(edge.other_vertex(v)) return temp_adj_dict<|docstring|>获取邻接字典<|endoftext|>
1047edd5980026f4162b0e8e7b9eed31df96cc271f91955e50b8818f69462f43
@property def reversed_adjacency_dict(self): '逆邻接字典' temp_adj_dict = {v: [] for v in self.vertexes} for (v, row) in temp_adj_dict.items(): if (self.EDGE_CLS == DirectedEdge): for edge in (e for e in self.edges if (e.to_vertex == v)): row.append(edge.from_vertex) elif (self.EDGE_CLS == UndirectedEdge): for edge in (e for e in self.edges if e.has_vertex(v)): row.append(edge.other_vertex(v)) return temp_adj_dict
逆邻接字典
Projects/src/graph.py
reversed_adjacency_dict
LonelySteve/data-structure-and-algorithms-tasks
1
python
@property def reversed_adjacency_dict(self): temp_adj_dict = {v: [] for v in self.vertexes} for (v, row) in temp_adj_dict.items(): if (self.EDGE_CLS == DirectedEdge): for edge in (e for e in self.edges if (e.to_vertex == v)): row.append(edge.from_vertex) elif (self.EDGE_CLS == UndirectedEdge): for edge in (e for e in self.edges if e.has_vertex(v)): row.append(edge.other_vertex(v)) return temp_adj_dict
@property def reversed_adjacency_dict(self): temp_adj_dict = {v: [] for v in self.vertexes} for (v, row) in temp_adj_dict.items(): if (self.EDGE_CLS == DirectedEdge): for edge in (e for e in self.edges if (e.to_vertex == v)): row.append(edge.from_vertex) elif (self.EDGE_CLS == UndirectedEdge): for edge in (e for e in self.edges if e.has_vertex(v)): row.append(edge.other_vertex(v)) return temp_adj_dict<|docstring|>逆邻接字典<|endoftext|>
b1cdc1bd3d5d6f1b9290b7adce902b2d7bf590aee2ecbb8e35aa20d4e2bae701
def get_hosts(node_name: Optional[str]=None, opts: Optional[pulumi.InvokeOptions]=None) -> AwaitableGetHostsResult: '\n Use this data source to access information about an existing resource.\n ' __args__ = dict() __args__['nodeName'] = node_name if (opts is None): opts = pulumi.InvokeOptions() if (opts.version is None): opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('proxmox:System/getHosts:getHosts', __args__, opts=opts, typ=GetHostsResult).value return AwaitableGetHostsResult(addresses=__ret__.addresses, digest=__ret__.digest, entries=__ret__.entries, hostnames=__ret__.hostnames, id=__ret__.id, node_name=__ret__.node_name)
Use this data source to access information about an existing resource.
sdk/python/pulumi_proxmox/system/get_hosts.py
get_hosts
meyskens/pulumi-proxmox
16
python
def get_hosts(node_name: Optional[str]=None, opts: Optional[pulumi.InvokeOptions]=None) -> AwaitableGetHostsResult: '\n \n ' __args__ = dict() __args__['nodeName'] = node_name if (opts is None): opts = pulumi.InvokeOptions() if (opts.version is None): opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('proxmox:System/getHosts:getHosts', __args__, opts=opts, typ=GetHostsResult).value return AwaitableGetHostsResult(addresses=__ret__.addresses, digest=__ret__.digest, entries=__ret__.entries, hostnames=__ret__.hostnames, id=__ret__.id, node_name=__ret__.node_name)
def get_hosts(node_name: Optional[str]=None, opts: Optional[pulumi.InvokeOptions]=None) -> AwaitableGetHostsResult: '\n \n ' __args__ = dict() __args__['nodeName'] = node_name if (opts is None): opts = pulumi.InvokeOptions() if (opts.version is None): opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('proxmox:System/getHosts:getHosts', __args__, opts=opts, typ=GetHostsResult).value return AwaitableGetHostsResult(addresses=__ret__.addresses, digest=__ret__.digest, entries=__ret__.entries, hostnames=__ret__.hostnames, id=__ret__.id, node_name=__ret__.node_name)<|docstring|>Use this data source to access information about an existing resource.<|endoftext|>
bcf5b51a327014088b63f706e1dc3987198031e1f0241bd10b06cf4dd5bcb53c
@property @pulumi.getter def id(self) -> str: '\n The provider-assigned unique ID for this managed resource.\n ' return pulumi.get(self, 'id')
The provider-assigned unique ID for this managed resource.
sdk/python/pulumi_proxmox/system/get_hosts.py
id
meyskens/pulumi-proxmox
16
python
@property @pulumi.getter def id(self) -> str: '\n \n ' return pulumi.get(self, 'id')
@property @pulumi.getter def id(self) -> str: '\n \n ' return pulumi.get(self, 'id')<|docstring|>The provider-assigned unique ID for this managed resource.<|endoftext|>
9ced18cac78f6e3be2dd28c2071aecd9d0b46af64ebcfa0387f8f7c0f2b982cf
def refine_centroid(scorefmp, anchor, radius): '\n Refine the centroid coordinate. It dose not affect the results after testing.\n :param scorefmp: 2-D numpy array, original regressed score map\n :param anchor: python tuple, (x,y) coordinates\n :param radius: int, range of considered scores\n :return: refined anchor, refined score\n ' (x_c, y_c) = anchor x_min = (x_c - radius) x_max = ((x_c + radius) + 1) y_min = (y_c - radius) y_max = ((y_c + radius) + 1) if ((y_max > scorefmp.shape[0]) or (y_min < 0) or (x_max > scorefmp.shape[1]) or (x_min < 0)): return (anchor + (scorefmp[(y_c, x_c)],)) score_box = scorefmp[(y_min:y_max, x_min:x_max)] (x_grid, y_grid) = np.mgrid[((- radius):(radius + 1), (- radius):(radius + 1))] offset_x = ((score_box * x_grid).sum() / score_box.sum()) offset_y = ((score_box * y_grid).sum() / score_box.sum()) x_refine = (x_c + offset_x) y_refine = (y_c + offset_y) refined_anchor = (x_refine, y_refine) return (refined_anchor + (score_box.mean(),))
Refine the centroid coordinate. It dose not affect the results after testing. :param scorefmp: 2-D numpy array, original regressed score map :param anchor: python tuple, (x,y) coordinates :param radius: int, range of considered scores :return: refined anchor, refined score
Tencent/Human Pose Estimation/utils/util.py
refine_centroid
orange-eng/internship
2
python
def refine_centroid(scorefmp, anchor, radius): '\n Refine the centroid coordinate. It dose not affect the results after testing.\n :param scorefmp: 2-D numpy array, original regressed score map\n :param anchor: python tuple, (x,y) coordinates\n :param radius: int, range of considered scores\n :return: refined anchor, refined score\n ' (x_c, y_c) = anchor x_min = (x_c - radius) x_max = ((x_c + radius) + 1) y_min = (y_c - radius) y_max = ((y_c + radius) + 1) if ((y_max > scorefmp.shape[0]) or (y_min < 0) or (x_max > scorefmp.shape[1]) or (x_min < 0)): return (anchor + (scorefmp[(y_c, x_c)],)) score_box = scorefmp[(y_min:y_max, x_min:x_max)] (x_grid, y_grid) = np.mgrid[((- radius):(radius + 1), (- radius):(radius + 1))] offset_x = ((score_box * x_grid).sum() / score_box.sum()) offset_y = ((score_box * y_grid).sum() / score_box.sum()) x_refine = (x_c + offset_x) y_refine = (y_c + offset_y) refined_anchor = (x_refine, y_refine) return (refined_anchor + (score_box.mean(),))
def refine_centroid(scorefmp, anchor, radius): '\n Refine the centroid coordinate. It dose not affect the results after testing.\n :param scorefmp: 2-D numpy array, original regressed score map\n :param anchor: python tuple, (x,y) coordinates\n :param radius: int, range of considered scores\n :return: refined anchor, refined score\n ' (x_c, y_c) = anchor x_min = (x_c - radius) x_max = ((x_c + radius) + 1) y_min = (y_c - radius) y_max = ((y_c + radius) + 1) if ((y_max > scorefmp.shape[0]) or (y_min < 0) or (x_max > scorefmp.shape[1]) or (x_min < 0)): return (anchor + (scorefmp[(y_c, x_c)],)) score_box = scorefmp[(y_min:y_max, x_min:x_max)] (x_grid, y_grid) = np.mgrid[((- radius):(radius + 1), (- radius):(radius + 1))] offset_x = ((score_box * x_grid).sum() / score_box.sum()) offset_y = ((score_box * y_grid).sum() / score_box.sum()) x_refine = (x_c + offset_x) y_refine = (y_c + offset_y) refined_anchor = (x_refine, y_refine) return (refined_anchor + (score_box.mean(),))<|docstring|>Refine the centroid coordinate. It dose not affect the results after testing. :param scorefmp: 2-D numpy array, original regressed score map :param anchor: python tuple, (x,y) coordinates :param radius: int, range of considered scores :return: refined anchor, refined score<|endoftext|>
bcba04faa37d73ce06b19ab8f12c92141707ef1bc0e259dc999415fe476001e3
def forward(self, input): '\n Apply gaussian filter to input.\n Arguments:\n input (torch.Tensor): Input to apply gaussian filter on.\n Returns:\n filtered (torch.Tensor): Filtered output.\n ' return self.conv(input, weight=self.weight.cuda(), groups=self.groups)
Apply gaussian filter to input. Arguments: input (torch.Tensor): Input to apply gaussian filter on. Returns: filtered (torch.Tensor): Filtered output.
Tencent/Human Pose Estimation/utils/util.py
forward
orange-eng/internship
2
python
def forward(self, input): '\n Apply gaussian filter to input.\n Arguments:\n input (torch.Tensor): Input to apply gaussian filter on.\n Returns:\n filtered (torch.Tensor): Filtered output.\n ' return self.conv(input, weight=self.weight.cuda(), groups=self.groups)
def forward(self, input): '\n Apply gaussian filter to input.\n Arguments:\n input (torch.Tensor): Input to apply gaussian filter on.\n Returns:\n filtered (torch.Tensor): Filtered output.\n ' return self.conv(input, weight=self.weight.cuda(), groups=self.groups)<|docstring|>Apply gaussian filter to input. Arguments: input (torch.Tensor): Input to apply gaussian filter on. Returns: filtered (torch.Tensor): Filtered output.<|endoftext|>
c94314d455840810d21e484cffba608477adf9c665980f0510f23eb8d5ad45bd
@router.get('/ready', tags=['ready'], response_model=ReadyResponse, summary='Simple health check.', status_code=200, responses={502: {'model': ErrorResponse}}) async def readiness_check(): 'Run basic application health check.\n\n If the application is up and running then this endpoint will return simple\n response with status ok. Moreover, if it has Redis enabled then connection\n to it will be tested. If Redis ping fails, then this endpoint will return\n 502 HTTP error.\n \x0c\n\n Returns:\n response (ReadyResponse): ReadyResponse model object instance.\n\n Raises:\n HTTPException: If applications has enabled Redis and can not connect\n to it. NOTE! This is the custom exception, not to be mistaken with\n FastAPI.HTTPException class.\n\n ' log.info('Started GET /ready') if (settings.USE_REDIS and (not (await RedisClient.ping()))): log.error('Could not connect to Redis') raise HTTPException(status_code=502, content=ErrorResponse(code=502, message='Could not connect to Redis').dict(exclude_none=True)) return ReadyResponse(status='ok')
Run basic application health check. If the application is up and running then this endpoint will return simple response with status ok. Moreover, if it has Redis enabled then connection to it will be tested. If Redis ping fails, then this endpoint will return 502 HTTP error. Returns: response (ReadyResponse): ReadyResponse model object instance. Raises: HTTPException: If applications has enabled Redis and can not connect to it. NOTE! This is the custom exception, not to be mistaken with FastAPI.HTTPException class.
fastapi_mvc_example/app/controllers/ready.py
readiness_check
rszamszur/fastapi-mvc-example
3
python
@router.get('/ready', tags=['ready'], response_model=ReadyResponse, summary='Simple health check.', status_code=200, responses={502: {'model': ErrorResponse}}) async def readiness_check(): 'Run basic application health check.\n\n If the application is up and running then this endpoint will return simple\n response with status ok. Moreover, if it has Redis enabled then connection\n to it will be tested. If Redis ping fails, then this endpoint will return\n 502 HTTP error.\n \x0c\n\n Returns:\n response (ReadyResponse): ReadyResponse model object instance.\n\n Raises:\n HTTPException: If applications has enabled Redis and can not connect\n to it. NOTE! This is the custom exception, not to be mistaken with\n FastAPI.HTTPException class.\n\n ' log.info('Started GET /ready') if (settings.USE_REDIS and (not (await RedisClient.ping()))): log.error('Could not connect to Redis') raise HTTPException(status_code=502, content=ErrorResponse(code=502, message='Could not connect to Redis').dict(exclude_none=True)) return ReadyResponse(status='ok')
@router.get('/ready', tags=['ready'], response_model=ReadyResponse, summary='Simple health check.', status_code=200, responses={502: {'model': ErrorResponse}}) async def readiness_check(): 'Run basic application health check.\n\n If the application is up and running then this endpoint will return simple\n response with status ok. Moreover, if it has Redis enabled then connection\n to it will be tested. If Redis ping fails, then this endpoint will return\n 502 HTTP error.\n \x0c\n\n Returns:\n response (ReadyResponse): ReadyResponse model object instance.\n\n Raises:\n HTTPException: If applications has enabled Redis and can not connect\n to it. NOTE! This is the custom exception, not to be mistaken with\n FastAPI.HTTPException class.\n\n ' log.info('Started GET /ready') if (settings.USE_REDIS and (not (await RedisClient.ping()))): log.error('Could not connect to Redis') raise HTTPException(status_code=502, content=ErrorResponse(code=502, message='Could not connect to Redis').dict(exclude_none=True)) return ReadyResponse(status='ok')<|docstring|>Run basic application health check. If the application is up and running then this endpoint will return simple response with status ok. Moreover, if it has Redis enabled then connection to it will be tested. If Redis ping fails, then this endpoint will return 502 HTTP error. Returns: response (ReadyResponse): ReadyResponse model object instance. Raises: HTTPException: If applications has enabled Redis and can not connect to it. NOTE! This is the custom exception, not to be mistaken with FastAPI.HTTPException class.<|endoftext|>
7c24eddc58a9130ba46dec13f0d1271ee2d59c7ca75c3f9b884c1973d9bb0c74
@check_enable_terms_and_conditions def get(self, request): '\n list Terms and Conditions\n\n Permission checking:\n 1.login and is admin user.\n ' if (not request.user.admin_permissions.other_permission()): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') terms_and_conditions = TermsAndConditions.objects.all().order_by('-date_created') info_list = [] for term in terms_and_conditions: info = {} info['id'] = term.pk info['name'] = term.name info['version_number'] = term.version_number info['text'] = term.text info['ctime'] = datetime_to_isoformat_timestr(term.date_created) info['activate_time'] = (datetime_to_isoformat_timestr(term.date_active) if term.date_active else '') info_list.append(info) return Response({'term_and_condition_list': info_list})
list Terms and Conditions Permission checking: 1.login and is admin user.
seahub/api2/endpoints/admin/terms_and_conditions.py
get
drizzt/seahub
420
python
@check_enable_terms_and_conditions def get(self, request): '\n list Terms and Conditions\n\n Permission checking:\n 1.login and is admin user.\n ' if (not request.user.admin_permissions.other_permission()): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') terms_and_conditions = TermsAndConditions.objects.all().order_by('-date_created') info_list = [] for term in terms_and_conditions: info = {} info['id'] = term.pk info['name'] = term.name info['version_number'] = term.version_number info['text'] = term.text info['ctime'] = datetime_to_isoformat_timestr(term.date_created) info['activate_time'] = (datetime_to_isoformat_timestr(term.date_active) if term.date_active else ) info_list.append(info) return Response({'term_and_condition_list': info_list})
@check_enable_terms_and_conditions def get(self, request): '\n list Terms and Conditions\n\n Permission checking:\n 1.login and is admin user.\n ' if (not request.user.admin_permissions.other_permission()): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') terms_and_conditions = TermsAndConditions.objects.all().order_by('-date_created') info_list = [] for term in terms_and_conditions: info = {} info['id'] = term.pk info['name'] = term.name info['version_number'] = term.version_number info['text'] = term.text info['ctime'] = datetime_to_isoformat_timestr(term.date_created) info['activate_time'] = (datetime_to_isoformat_timestr(term.date_active) if term.date_active else ) info_list.append(info) return Response({'term_and_condition_list': info_list})<|docstring|>list Terms and Conditions Permission checking: 1.login and is admin user.<|endoftext|>
dd0ea706965783b830379847d3955990a9344db92422e92b9b589fd591f3b74a
@check_enable_terms_and_conditions def post(self, request): '\n Create a term and condition\n\n Permission checking:\n 1.login and is admin user.\n ' if (not request.user.admin_permissions.other_permission()): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') name = request.data.get('name') if (not name): error_msg = 'name invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) version_number = request.data.get('version_number') if (not version_number): error_msg = 'version_number invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: version_number = Decimal(version_number) except Exception as e: logger.error(e) error_msg = ('version_number %s invalid' % version_number) return api_error(status.HTTP_400_BAD_REQUEST, error_msg) text = request.data.get('text') if (not text): error_msg = 'text invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) is_active = request.data.get('is_active') if (not is_active): error_msg = 'is_active invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) is_active = is_active.lower() if (is_active not in ('true', 'false')): error_msg = ('is_active %s invalid' % is_active) return api_error(status.HTTP_400_BAD_REQUEST, error_msg) date_active = (timezone.now() if (is_active == 'true') else None) term = TermsAndConditions.objects.create(name=name, version_number=version_number, text=text, date_active=date_active) info = {} info['id'] = term.pk info['name'] = term.name info['version_number'] = term.version_number info['text'] = term.text info['ctime'] = datetime_to_isoformat_timestr(term.date_created) info['activate_time'] = (datetime_to_isoformat_timestr(term.date_active) if term.date_active else '') return Response(info)
Create a term and condition Permission checking: 1.login and is admin user.
seahub/api2/endpoints/admin/terms_and_conditions.py
post
drizzt/seahub
420
python
@check_enable_terms_and_conditions def post(self, request): '\n Create a term and condition\n\n Permission checking:\n 1.login and is admin user.\n ' if (not request.user.admin_permissions.other_permission()): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') name = request.data.get('name') if (not name): error_msg = 'name invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) version_number = request.data.get('version_number') if (not version_number): error_msg = 'version_number invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: version_number = Decimal(version_number) except Exception as e: logger.error(e) error_msg = ('version_number %s invalid' % version_number) return api_error(status.HTTP_400_BAD_REQUEST, error_msg) text = request.data.get('text') if (not text): error_msg = 'text invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) is_active = request.data.get('is_active') if (not is_active): error_msg = 'is_active invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) is_active = is_active.lower() if (is_active not in ('true', 'false')): error_msg = ('is_active %s invalid' % is_active) return api_error(status.HTTP_400_BAD_REQUEST, error_msg) date_active = (timezone.now() if (is_active == 'true') else None) term = TermsAndConditions.objects.create(name=name, version_number=version_number, text=text, date_active=date_active) info = {} info['id'] = term.pk info['name'] = term.name info['version_number'] = term.version_number info['text'] = term.text info['ctime'] = datetime_to_isoformat_timestr(term.date_created) info['activate_time'] = (datetime_to_isoformat_timestr(term.date_active) if term.date_active else ) return Response(info)
@check_enable_terms_and_conditions def post(self, request): '\n Create a term and condition\n\n Permission checking:\n 1.login and is admin user.\n ' if (not request.user.admin_permissions.other_permission()): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') name = request.data.get('name') if (not name): error_msg = 'name invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) version_number = request.data.get('version_number') if (not version_number): error_msg = 'version_number invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: version_number = Decimal(version_number) except Exception as e: logger.error(e) error_msg = ('version_number %s invalid' % version_number) return api_error(status.HTTP_400_BAD_REQUEST, error_msg) text = request.data.get('text') if (not text): error_msg = 'text invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) is_active = request.data.get('is_active') if (not is_active): error_msg = 'is_active invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) is_active = is_active.lower() if (is_active not in ('true', 'false')): error_msg = ('is_active %s invalid' % is_active) return api_error(status.HTTP_400_BAD_REQUEST, error_msg) date_active = (timezone.now() if (is_active == 'true') else None) term = TermsAndConditions.objects.create(name=name, version_number=version_number, text=text, date_active=date_active) info = {} info['id'] = term.pk info['name'] = term.name info['version_number'] = term.version_number info['text'] = term.text info['ctime'] = datetime_to_isoformat_timestr(term.date_created) info['activate_time'] = (datetime_to_isoformat_timestr(term.date_active) if term.date_active else ) return Response(info)<|docstring|>Create a term and condition Permission checking: 1.login and is admin user.<|endoftext|>
6fea5408e295da2aad87fe4a7af0bec09058c3ce984d5ac9c2113412627dac84
@check_enable_terms_and_conditions def put(self, request, term_id): '\n Update Term and Condition\n\n Permission checking:\n 1.login and is admin user.\n ' if (not request.user.admin_permissions.other_permission()): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') name = request.data.get('name') version_number = request.data.get('version_number') if version_number: try: version_number = Decimal(version_number) except Exception as e: logger.error(e) error_msg = ('version_number %s invalid' % version_number) return api_error(status.HTTP_400_BAD_REQUEST, error_msg) text = request.data.get('text') is_active = request.data.get('is_active') if is_active: is_active = is_active.lower() if (is_active not in ('true', 'false')): error_msg = ('is_active %s invalid' % is_active) return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: term = TermsAndConditions.objects.get(pk=term_id) except TermsAndConditions.DoesNotExist: error_msg = ('term %s not found' % term_id) return api_error(status.HTTP_404_NOT_FOUND, error_msg) if text: term.text = text if name: term.name = name if (version_number and (version_number != term.version_number)): term.version_number = version_number if (is_active == 'true'): term.date_active = timezone.now() if ((is_active == 'true') and (not term.date_active)): term.date_active = timezone.now() if (is_active == 'false'): term.date_active = None term.save() info = {} info['id'] = term.pk info['name'] = term.name info['version_number'] = term.version_number info['text'] = term.text info['ctime'] = datetime_to_isoformat_timestr(term.date_created) info['activate_time'] = (datetime_to_isoformat_timestr(term.date_active) if term.date_active else '') return Response(info)
Update Term and Condition Permission checking: 1.login and is admin user.
seahub/api2/endpoints/admin/terms_and_conditions.py
put
drizzt/seahub
420
python
@check_enable_terms_and_conditions def put(self, request, term_id): '\n Update Term and Condition\n\n Permission checking:\n 1.login and is admin user.\n ' if (not request.user.admin_permissions.other_permission()): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') name = request.data.get('name') version_number = request.data.get('version_number') if version_number: try: version_number = Decimal(version_number) except Exception as e: logger.error(e) error_msg = ('version_number %s invalid' % version_number) return api_error(status.HTTP_400_BAD_REQUEST, error_msg) text = request.data.get('text') is_active = request.data.get('is_active') if is_active: is_active = is_active.lower() if (is_active not in ('true', 'false')): error_msg = ('is_active %s invalid' % is_active) return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: term = TermsAndConditions.objects.get(pk=term_id) except TermsAndConditions.DoesNotExist: error_msg = ('term %s not found' % term_id) return api_error(status.HTTP_404_NOT_FOUND, error_msg) if text: term.text = text if name: term.name = name if (version_number and (version_number != term.version_number)): term.version_number = version_number if (is_active == 'true'): term.date_active = timezone.now() if ((is_active == 'true') and (not term.date_active)): term.date_active = timezone.now() if (is_active == 'false'): term.date_active = None term.save() info = {} info['id'] = term.pk info['name'] = term.name info['version_number'] = term.version_number info['text'] = term.text info['ctime'] = datetime_to_isoformat_timestr(term.date_created) info['activate_time'] = (datetime_to_isoformat_timestr(term.date_active) if term.date_active else ) return Response(info)
@check_enable_terms_and_conditions def put(self, request, term_id): '\n Update Term and Condition\n\n Permission checking:\n 1.login and is admin user.\n ' if (not request.user.admin_permissions.other_permission()): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') name = request.data.get('name') version_number = request.data.get('version_number') if version_number: try: version_number = Decimal(version_number) except Exception as e: logger.error(e) error_msg = ('version_number %s invalid' % version_number) return api_error(status.HTTP_400_BAD_REQUEST, error_msg) text = request.data.get('text') is_active = request.data.get('is_active') if is_active: is_active = is_active.lower() if (is_active not in ('true', 'false')): error_msg = ('is_active %s invalid' % is_active) return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: term = TermsAndConditions.objects.get(pk=term_id) except TermsAndConditions.DoesNotExist: error_msg = ('term %s not found' % term_id) return api_error(status.HTTP_404_NOT_FOUND, error_msg) if text: term.text = text if name: term.name = name if (version_number and (version_number != term.version_number)): term.version_number = version_number if (is_active == 'true'): term.date_active = timezone.now() if ((is_active == 'true') and (not term.date_active)): term.date_active = timezone.now() if (is_active == 'false'): term.date_active = None term.save() info = {} info['id'] = term.pk info['name'] = term.name info['version_number'] = term.version_number info['text'] = term.text info['ctime'] = datetime_to_isoformat_timestr(term.date_created) info['activate_time'] = (datetime_to_isoformat_timestr(term.date_active) if term.date_active else ) return Response(info)<|docstring|>Update Term and Condition Permission checking: 1.login and is admin user.<|endoftext|>
b7eb7db047377ec1282a7b4dcceec10b6c83915f08778ecc188aa16d5c495f76
@check_enable_terms_and_conditions def delete(self, request, term_id): '\n Delete Term and Condition\n\n Permission checking:\n 1.login and is admin user.\n ' if (not request.user.admin_permissions.other_permission()): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') try: term = TermsAndConditions.objects.get(pk=term_id) except TermsAndConditions.DoesNotExist: error_msg = ('term %s not found' % term_id) return api_error(status.HTTP_404_NOT_FOUND, error_msg) try: term.delete() UserTermsAndConditions.objects.filter(terms_id=term_id).delete() except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) return Response({'success': True})
Delete Term and Condition Permission checking: 1.login and is admin user.
seahub/api2/endpoints/admin/terms_and_conditions.py
delete
drizzt/seahub
420
python
@check_enable_terms_and_conditions def delete(self, request, term_id): '\n Delete Term and Condition\n\n Permission checking:\n 1.login and is admin user.\n ' if (not request.user.admin_permissions.other_permission()): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') try: term = TermsAndConditions.objects.get(pk=term_id) except TermsAndConditions.DoesNotExist: error_msg = ('term %s not found' % term_id) return api_error(status.HTTP_404_NOT_FOUND, error_msg) try: term.delete() UserTermsAndConditions.objects.filter(terms_id=term_id).delete() except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) return Response({'success': True})
@check_enable_terms_and_conditions def delete(self, request, term_id): '\n Delete Term and Condition\n\n Permission checking:\n 1.login and is admin user.\n ' if (not request.user.admin_permissions.other_permission()): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') try: term = TermsAndConditions.objects.get(pk=term_id) except TermsAndConditions.DoesNotExist: error_msg = ('term %s not found' % term_id) return api_error(status.HTTP_404_NOT_FOUND, error_msg) try: term.delete() UserTermsAndConditions.objects.filter(terms_id=term_id).delete() except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) return Response({'success': True})<|docstring|>Delete Term and Condition Permission checking: 1.login and is admin user.<|endoftext|>
54817db7a9617e7dbfba09d1cfeda2065e9c8ad535265df430a3cdfb08035b6f
def test_patterns(text, patterns): 'Given source text and a list of patterns, look for\n matches for each pattern within the text and print\n them to stdout.\n ' for (pattern, desc) in patterns: print("'{}' ({})\n".format(pattern, desc)) print(" '{}'".format(text)) for match in re.finditer(pattern, text): s = match.start() e = match.end() substr = text[s:e] n_backslashes = text[:s].count('\\') prefix = ('.' * (s + n_backslashes)) print(" {}'{}'".format(prefix, substr)) print() return
Given source text and a list of patterns, look for matches for each pattern within the text and print them to stdout.
WEEKS/CD_Sata-Structures/_MISC/misc-examples/python3-book-examples/re/re_test_patterns.py
test_patterns
webdevhub42/Lambda
0
python
def test_patterns(text, patterns): 'Given source text and a list of patterns, look for\n matches for each pattern within the text and print\n them to stdout.\n ' for (pattern, desc) in patterns: print("'{}' ({})\n".format(pattern, desc)) print(" '{}'".format(text)) for match in re.finditer(pattern, text): s = match.start() e = match.end() substr = text[s:e] n_backslashes = text[:s].count('\\') prefix = ('.' * (s + n_backslashes)) print(" {}'{}'".format(prefix, substr)) print() return
def test_patterns(text, patterns): 'Given source text and a list of patterns, look for\n matches for each pattern within the text and print\n them to stdout.\n ' for (pattern, desc) in patterns: print("'{}' ({})\n".format(pattern, desc)) print(" '{}'".format(text)) for match in re.finditer(pattern, text): s = match.start() e = match.end() substr = text[s:e] n_backslashes = text[:s].count('\\') prefix = ('.' * (s + n_backslashes)) print(" {}'{}'".format(prefix, substr)) print() return<|docstring|>Given source text and a list of patterns, look for matches for each pattern within the text and print them to stdout.<|endoftext|>
19e5d0fdde7a7b3cebe1542238e9797c55a4dc505b21ba03fac4b062571b5588
def get_paths_from_list(fn_list, prefix='', suffix='', auto_prefix=None): '\n @argument fn_list (STR: filename)\n a file that stores a list of ID/path(s)\n @argument prefix (STR)\n prefix added to paths\n @argument suffix (STR)\n suffix added to paths\n @argument auto_prefix (LIST)\n set True to add common dirname from a list as prefix\n @return processed list of path(s)\n ' l = [] with open(fn_list, 'r') as f: for line in f: l.append(((prefix + line.rstrip()) + suffix)) if (auto_prefix != None): prefix = (os.path.dirname(os.path.commonprefix(auto_prefix)) + '/') l2 = [(prefix + i) for i in l] return l2 else: return l
@argument fn_list (STR: filename) a file that stores a list of ID/path(s) @argument prefix (STR) prefix added to paths @argument suffix (STR) suffix added to paths @argument auto_prefix (LIST) set True to add common dirname from a list as prefix @return processed list of path(s)
scripts/refbias/utils.py
get_paths_from_list
langmead-lab/reference_flow-experiments
0
python
def get_paths_from_list(fn_list, prefix=, suffix=, auto_prefix=None): '\n @argument fn_list (STR: filename)\n a file that stores a list of ID/path(s)\n @argument prefix (STR)\n prefix added to paths\n @argument suffix (STR)\n suffix added to paths\n @argument auto_prefix (LIST)\n set True to add common dirname from a list as prefix\n @return processed list of path(s)\n ' l = [] with open(fn_list, 'r') as f: for line in f: l.append(((prefix + line.rstrip()) + suffix)) if (auto_prefix != None): prefix = (os.path.dirname(os.path.commonprefix(auto_prefix)) + '/') l2 = [(prefix + i) for i in l] return l2 else: return l
def get_paths_from_list(fn_list, prefix=, suffix=, auto_prefix=None): '\n @argument fn_list (STR: filename)\n a file that stores a list of ID/path(s)\n @argument prefix (STR)\n prefix added to paths\n @argument suffix (STR)\n suffix added to paths\n @argument auto_prefix (LIST)\n set True to add common dirname from a list as prefix\n @return processed list of path(s)\n ' l = [] with open(fn_list, 'r') as f: for line in f: l.append(((prefix + line.rstrip()) + suffix)) if (auto_prefix != None): prefix = (os.path.dirname(os.path.commonprefix(auto_prefix)) + '/') l2 = [(prefix + i) for i in l] return l2 else: return l<|docstring|>@argument fn_list (STR: filename) a file that stores a list of ID/path(s) @argument prefix (STR) prefix added to paths @argument suffix (STR) suffix added to paths @argument auto_prefix (LIST) set True to add common dirname from a list as prefix @return processed list of path(s)<|endoftext|>
6e333265e9f17c24aa589291e56aaa2d3fe9a38a877b4a8d5e6b27163572c3dd
def __init__(self): '\n AnalyticsConversationAsyncQueryResponse - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n and the value is json key in definition.\n ' self.swagger_types = {'cursor': 'str', 'data_availability_date': 'datetime', 'conversations': 'list[AnalyticsConversation]'} self.attribute_map = {'cursor': 'cursor', 'data_availability_date': 'dataAvailabilityDate', 'conversations': 'conversations'} self._cursor = None self._data_availability_date = None self._conversations = None
AnalyticsConversationAsyncQueryResponse - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition.
build/PureCloudPlatformClientV2/models/analytics_conversation_async_query_response.py
__init__
cjohnson-ctl/platform-client-sdk-python
10
python
def __init__(self): '\n AnalyticsConversationAsyncQueryResponse - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n and the value is json key in definition.\n ' self.swagger_types = {'cursor': 'str', 'data_availability_date': 'datetime', 'conversations': 'list[AnalyticsConversation]'} self.attribute_map = {'cursor': 'cursor', 'data_availability_date': 'dataAvailabilityDate', 'conversations': 'conversations'} self._cursor = None self._data_availability_date = None self._conversations = None
def __init__(self): '\n AnalyticsConversationAsyncQueryResponse - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n and the value is json key in definition.\n ' self.swagger_types = {'cursor': 'str', 'data_availability_date': 'datetime', 'conversations': 'list[AnalyticsConversation]'} self.attribute_map = {'cursor': 'cursor', 'data_availability_date': 'dataAvailabilityDate', 'conversations': 'conversations'} self._cursor = None self._data_availability_date = None self._conversations = None<|docstring|>AnalyticsConversationAsyncQueryResponse - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition.<|endoftext|>
1baf64d09e2b62fd463fa00791bfa1af45f2a0e51f4432151e4fc09b1469dade
@property def cursor(self): '\n Gets the cursor of this AnalyticsConversationAsyncQueryResponse.\n Optional cursor to indicate where to resume the results\n\n :return: The cursor of this AnalyticsConversationAsyncQueryResponse.\n :rtype: str\n ' return self._cursor
Gets the cursor of this AnalyticsConversationAsyncQueryResponse. Optional cursor to indicate where to resume the results :return: The cursor of this AnalyticsConversationAsyncQueryResponse. :rtype: str
build/PureCloudPlatformClientV2/models/analytics_conversation_async_query_response.py
cursor
cjohnson-ctl/platform-client-sdk-python
10
python
@property def cursor(self): '\n Gets the cursor of this AnalyticsConversationAsyncQueryResponse.\n Optional cursor to indicate where to resume the results\n\n :return: The cursor of this AnalyticsConversationAsyncQueryResponse.\n :rtype: str\n ' return self._cursor
@property def cursor(self): '\n Gets the cursor of this AnalyticsConversationAsyncQueryResponse.\n Optional cursor to indicate where to resume the results\n\n :return: The cursor of this AnalyticsConversationAsyncQueryResponse.\n :rtype: str\n ' return self._cursor<|docstring|>Gets the cursor of this AnalyticsConversationAsyncQueryResponse. Optional cursor to indicate where to resume the results :return: The cursor of this AnalyticsConversationAsyncQueryResponse. :rtype: str<|endoftext|>
ffbdf33dbf6c36119ec55885297d90265fa9cf2abf1a2fdabd4be6b06c5421b6
@cursor.setter def cursor(self, cursor): '\n Sets the cursor of this AnalyticsConversationAsyncQueryResponse.\n Optional cursor to indicate where to resume the results\n\n :param cursor: The cursor of this AnalyticsConversationAsyncQueryResponse.\n :type: str\n ' self._cursor = cursor
Sets the cursor of this AnalyticsConversationAsyncQueryResponse. Optional cursor to indicate where to resume the results :param cursor: The cursor of this AnalyticsConversationAsyncQueryResponse. :type: str
build/PureCloudPlatformClientV2/models/analytics_conversation_async_query_response.py
cursor
cjohnson-ctl/platform-client-sdk-python
10
python
@cursor.setter def cursor(self, cursor): '\n Sets the cursor of this AnalyticsConversationAsyncQueryResponse.\n Optional cursor to indicate where to resume the results\n\n :param cursor: The cursor of this AnalyticsConversationAsyncQueryResponse.\n :type: str\n ' self._cursor = cursor
@cursor.setter def cursor(self, cursor): '\n Sets the cursor of this AnalyticsConversationAsyncQueryResponse.\n Optional cursor to indicate where to resume the results\n\n :param cursor: The cursor of this AnalyticsConversationAsyncQueryResponse.\n :type: str\n ' self._cursor = cursor<|docstring|>Sets the cursor of this AnalyticsConversationAsyncQueryResponse. Optional cursor to indicate where to resume the results :param cursor: The cursor of this AnalyticsConversationAsyncQueryResponse. :type: str<|endoftext|>
4aa747083dc35827edb675fc8208a1cbb277ea76f35a4e70d17aa875312d96d5
@property def data_availability_date(self): '\n Gets the data_availability_date of this AnalyticsConversationAsyncQueryResponse.\n Data available up to at least this datetime. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z\n\n :return: The data_availability_date of this AnalyticsConversationAsyncQueryResponse.\n :rtype: datetime\n ' return self._data_availability_date
Gets the data_availability_date of this AnalyticsConversationAsyncQueryResponse. Data available up to at least this datetime. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z :return: The data_availability_date of this AnalyticsConversationAsyncQueryResponse. :rtype: datetime
build/PureCloudPlatformClientV2/models/analytics_conversation_async_query_response.py
data_availability_date
cjohnson-ctl/platform-client-sdk-python
10
python
@property def data_availability_date(self): '\n Gets the data_availability_date of this AnalyticsConversationAsyncQueryResponse.\n Data available up to at least this datetime. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z\n\n :return: The data_availability_date of this AnalyticsConversationAsyncQueryResponse.\n :rtype: datetime\n ' return self._data_availability_date
@property def data_availability_date(self): '\n Gets the data_availability_date of this AnalyticsConversationAsyncQueryResponse.\n Data available up to at least this datetime. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z\n\n :return: The data_availability_date of this AnalyticsConversationAsyncQueryResponse.\n :rtype: datetime\n ' return self._data_availability_date<|docstring|>Gets the data_availability_date of this AnalyticsConversationAsyncQueryResponse. Data available up to at least this datetime. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z :return: The data_availability_date of this AnalyticsConversationAsyncQueryResponse. :rtype: datetime<|endoftext|>
32dd0bf97df761a37a5fd4ac78eb476985fa7a3b3d3ced4c876b6555b6bd1362
@data_availability_date.setter def data_availability_date(self, data_availability_date): '\n Sets the data_availability_date of this AnalyticsConversationAsyncQueryResponse.\n Data available up to at least this datetime. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z\n\n :param data_availability_date: The data_availability_date of this AnalyticsConversationAsyncQueryResponse.\n :type: datetime\n ' self._data_availability_date = data_availability_date
Sets the data_availability_date of this AnalyticsConversationAsyncQueryResponse. Data available up to at least this datetime. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z :param data_availability_date: The data_availability_date of this AnalyticsConversationAsyncQueryResponse. :type: datetime
build/PureCloudPlatformClientV2/models/analytics_conversation_async_query_response.py
data_availability_date
cjohnson-ctl/platform-client-sdk-python
10
python
@data_availability_date.setter def data_availability_date(self, data_availability_date): '\n Sets the data_availability_date of this AnalyticsConversationAsyncQueryResponse.\n Data available up to at least this datetime. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z\n\n :param data_availability_date: The data_availability_date of this AnalyticsConversationAsyncQueryResponse.\n :type: datetime\n ' self._data_availability_date = data_availability_date
@data_availability_date.setter def data_availability_date(self, data_availability_date): '\n Sets the data_availability_date of this AnalyticsConversationAsyncQueryResponse.\n Data available up to at least this datetime. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z\n\n :param data_availability_date: The data_availability_date of this AnalyticsConversationAsyncQueryResponse.\n :type: datetime\n ' self._data_availability_date = data_availability_date<|docstring|>Sets the data_availability_date of this AnalyticsConversationAsyncQueryResponse. Data available up to at least this datetime. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z :param data_availability_date: The data_availability_date of this AnalyticsConversationAsyncQueryResponse. :type: datetime<|endoftext|>
a1ee2f867ef5451da3dfc9940a39fdf39b1f2f20db7f10d56bdfecac1a6622d0
@property def conversations(self): '\n Gets the conversations of this AnalyticsConversationAsyncQueryResponse.\n\n\n :return: The conversations of this AnalyticsConversationAsyncQueryResponse.\n :rtype: list[AnalyticsConversation]\n ' return self._conversations
Gets the conversations of this AnalyticsConversationAsyncQueryResponse. :return: The conversations of this AnalyticsConversationAsyncQueryResponse. :rtype: list[AnalyticsConversation]
build/PureCloudPlatformClientV2/models/analytics_conversation_async_query_response.py
conversations
cjohnson-ctl/platform-client-sdk-python
10
python
@property def conversations(self): '\n Gets the conversations of this AnalyticsConversationAsyncQueryResponse.\n\n\n :return: The conversations of this AnalyticsConversationAsyncQueryResponse.\n :rtype: list[AnalyticsConversation]\n ' return self._conversations
@property def conversations(self): '\n Gets the conversations of this AnalyticsConversationAsyncQueryResponse.\n\n\n :return: The conversations of this AnalyticsConversationAsyncQueryResponse.\n :rtype: list[AnalyticsConversation]\n ' return self._conversations<|docstring|>Gets the conversations of this AnalyticsConversationAsyncQueryResponse. :return: The conversations of this AnalyticsConversationAsyncQueryResponse. :rtype: list[AnalyticsConversation]<|endoftext|>
0e9985d2bc5dfe5b3323be46d40f5f25f59160ae80404457805724bc34637728
@conversations.setter def conversations(self, conversations): '\n Sets the conversations of this AnalyticsConversationAsyncQueryResponse.\n\n\n :param conversations: The conversations of this AnalyticsConversationAsyncQueryResponse.\n :type: list[AnalyticsConversation]\n ' self._conversations = conversations
Sets the conversations of this AnalyticsConversationAsyncQueryResponse. :param conversations: The conversations of this AnalyticsConversationAsyncQueryResponse. :type: list[AnalyticsConversation]
build/PureCloudPlatformClientV2/models/analytics_conversation_async_query_response.py
conversations
cjohnson-ctl/platform-client-sdk-python
10
python
@conversations.setter def conversations(self, conversations): '\n Sets the conversations of this AnalyticsConversationAsyncQueryResponse.\n\n\n :param conversations: The conversations of this AnalyticsConversationAsyncQueryResponse.\n :type: list[AnalyticsConversation]\n ' self._conversations = conversations
@conversations.setter def conversations(self, conversations): '\n Sets the conversations of this AnalyticsConversationAsyncQueryResponse.\n\n\n :param conversations: The conversations of this AnalyticsConversationAsyncQueryResponse.\n :type: list[AnalyticsConversation]\n ' self._conversations = conversations<|docstring|>Sets the conversations of this AnalyticsConversationAsyncQueryResponse. :param conversations: The conversations of this AnalyticsConversationAsyncQueryResponse. :type: list[AnalyticsConversation]<|endoftext|>
f92515cd38effc7eee4069f2288d78a0f0836df932fb36a84e3b4f7e14233415
def to_dict(self): '\n Returns the model properties as a dict\n ' result = {} for (attr, _) in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value)) elif hasattr(value, 'to_dict'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items())) else: result[attr] = value return result
Returns the model properties as a dict
build/PureCloudPlatformClientV2/models/analytics_conversation_async_query_response.py
to_dict
cjohnson-ctl/platform-client-sdk-python
10
python
def to_dict(self): '\n \n ' result = {} for (attr, _) in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value)) elif hasattr(value, 'to_dict'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items())) else: result[attr] = value return result
def to_dict(self): '\n \n ' result = {} for (attr, _) in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value)) elif hasattr(value, 'to_dict'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items())) else: result[attr] = value return result<|docstring|>Returns the model properties as a dict<|endoftext|>