repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
saipurumandla/MapReduce-Mutual-Friends
https://github.com/saipurumandla/MapReduce-Mutual-Friends
66d3d43036c3cb69f401f031c2ee70d7ab71e2b7
ab153cda96f47ffcacca6aeaa8f561c6a372871b
9e3bfee6c0ce47e613b4f3f3497f9a2cd1758fd5
refs/heads/master
2021-01-19T08:12:08.659149
2016-12-22T18:09:10
2016-12-22T18:09:10
77,165,851
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.5876106023788452, "alphanum_fraction": 0.5911504626274109, "avg_line_length": 30.38888931274414, "blob_id": "d70d29671c2e75e233b39aee05a97914eab83cf8", "content_id": "c49a52fa9b318e4749b551d0eec0150057ef1c95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 565, "license_type": "no_license", "max_line_length": 80, "num_lines": 18, "path": "/Mapper.py", "repo_name": "saipurumandla/MapReduce-Mutual-Friends", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n#Author : Harin Purumandla \nimport sys\n\n# input comes from STDIN (standard input)\nfor line in sys.stdin:\n # remove leading and trailing whitespace\n line = line.strip()\n # split the line into words\n #concatenate company with date as make it a key\n key = line.split(\",\")[0]\n friends = line.split(\",\")[1]\n friend=friends.split(\" \")\n for val in friend:\n if int(val) > int(key):\n print('%s,%s\\t%s' % (key, val, friends)) # return the key value pair\n else:\n print('%s,%s\\t%s' % (val, key, friends))\n" }, { "alpha_fraction": 0.5123674869537354, "alphanum_fraction": 0.7173144817352295, "avg_line_length": 39.42856979370117, "blob_id": "1111955875de273d2d90c551958d61681d388626", "content_id": "00921b9192ddaabd2818fdcfcff73ddd22b2ae87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 855, "license_type": "no_license", "max_line_length": 102, "num_lines": 21, "path": "/README.md", "repo_name": "saipurumandla/MapReduce-Mutual-Friends", "src_encoding": "UTF-8", "text": "This project finds the common friends from a given data set.\n\nThe input for mapper is\n<UserID!><,><FriendID!><space><FriendID!>…< FriendID!>\nEx: 101,102 103 104 105 106\nThe output of mapper is in the format of <key, value> pair\nHere key will be <UserID!>,<FriendID!> if userid is greater than friend id else <FriendID!>, <UserID!>\nAnd value is the list of all the friends for the user <FriendID!><space><FriendID!>…< FriendID!>\nEx:\nOutput is\n101,102<tab>102 103 104 105 106\n101,103<tab>102 103 104 105 106\n101,104<tab>102 103 104 105 106\n101,105<tab>102 103 104 105 106\n101,106<tab>102 103 104 105 106\nFor the input 101,102 103 104 105 106\nThe input for reducer is\nThe output of mapper . i.e. <101,102<tab>102 103 104 105 106 >\nThe output of reducer is\n<UserID!><,><UserID!><space><[><FriendID!><,><FriendID!>….< FriendID!><]>\nEx: 101,102 [103,104]\n" }, { "alpha_fraction": 0.5561797618865967, "alphanum_fraction": 0.557584285736084, "avg_line_length": 24.214284896850586, "blob_id": "0c548029e31ceae876a345713728e4e532c26d4b", "content_id": "6b8e4956cfbd187322ac4d45dd5fc347eee0426b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 712, "license_type": "no_license", "max_line_length": 86, "num_lines": 28, "path": "/Reducer.py", "repo_name": "saipurumandla/MapReduce-Mutual-Friends", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n#Author : Harin Purumandla \nimport sys\nimport collections\n\nprevkey = None\nfriends=\"\"\ndef commonFriends():\n parts = friends.split(\" \")\n common = [item for item, count in collections.Counter(parts).items() if count > 1]\n common = map(int, common)\n print('%s %s'%(prevkey, common))\n return \nfor line in sys.stdin:\n line = line.strip()\n key, value = line.split('\\t')\n if prevkey == key:\n friends = friends+\" \"+value\n else:\n if prevkey == None:\n prevkey = key\n friends = friends+\" \"+value\n else:\n commonFriends()\n prevkey = key\n friends=\"\"\n friends = friends+\" \"+value\ncommonFriends()\n\n \n" } ]
3
wrb/abacot
https://github.com/wrb/abacot
f35077fdb1178d2cdd06549949a66d75eb0d0682
c61460c4b4b45b2e2f2ff74a275d4ae1e2662acc
7b4892cb1500086230a1c318e7320bc9d359672c
refs/heads/master
2016-05-25T09:51:44.305992
2012-05-20T16:56:18
2012-05-20T16:56:18
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5640087723731995, "alphanum_fraction": 0.5855888724327087, "avg_line_length": 24.546728134155273, "blob_id": "730f67339eab489c34617fc420734a6ee76c34c2", "content_id": "b5c7d8edc8b6e9d4bf4211579f772f74da0bb006", "detected_licenses": [ "LicenseRef-scancode-public-domain" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5468, "license_type": "permissive", "max_line_length": 99, "num_lines": 214, "path": "/abacot.py", "repo_name": "wrb/abacot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# encoding: utf-8\n\nimport sys, os\nimport cv2\nimport numpy as np\nimport pyopencl as cl\nimport pyopencl.array as cla\n\ndef prepare_ocl():\n ctx = cl.create_some_context()\n queue = cl.CommandQueue(ctx)\n\n prg = cl.Program(ctx, \"\"\"\n// naive transpose on ints\n__kernel void transpose(__global uint *input,\n__global uint *output)\n{\n int i = get_global_id(0);\n int j = get_global_id(1);\n\n int x = get_global_size(0);\n int y = get_global_size(1);\n\n output[j*x + i] = input[i*y + j];\n}\n\n// naive transpose with conversion from char to in\n__kernel void transpose_and_convert(__global char *input,\n__global uint *output)\n{\n int i = get_global_id(0);\n int j = get_global_id(1);\n\n int x = get_global_size(0);\n int y = get_global_size(1);\n\n output[j*x + i] = input[i*y + j];\n}\n\n// row-wise sum\n__kernel void sumr(__global uint *input,\n__global uint *output, uint y)\n{\n uint i = get_global_id(0);\n int acc = 0;\n\n for(uint k = 0; k < y; k++) {\n output[y*i + k] = input[y*i + k] + acc;\n acc = output[y*i + k];\n }\n}\n\n// column-wise sum\n__kernel void sumc(__global uint *input,\n__global uint *output, uint x)\n{\n uint i = get_global_id(0);\n uint j = get_global_id(1);\n uint y = get_global_size(1);\n int acc = 0;\n\n for(uint k = 0; k < x; k++) {\n output[y*(i+k) + j] = input[y*(i+k) + j] + acc;\n acc = output[y*(i+k) + j];\n }\n}\n\n// computes box filter\n__kernel void filter(__global uint *input,\n__global char *output, uint b)\n{\n int i = get_global_id(1);\n int j = get_global_id(0);\n\n int x = get_global_size(1);\n int y = get_global_size(0);\n\n int x1, x2, y1, y2, size;\n\n // compute filter indexes\n x1 = i - b;\n x2 = i + b;\n y1 = j - b;\n y2 = j + b;\n\n // if they are out of the image, clamp them to edges\n if(x1 < 0)\n x1 = 0;\n\n if(x2 > x-1)\n x2 = x-1;\n\n if(y1 < 0)\n y1 = 0;\n\n if(y2 > y-1)\n y2 = y-1;\n\n // compute real filter size so I can normalize the values\n size = (x2 - x1)*(y2 - y1);\n\n // compute filter and normalize\n output[i*y+j] = (input[x1*y + y1] + input[x2*y + y2] - input[x1*y + y2] - input[x*y2 + y1])/size;\n}\n \"\"\").build()\n\n return (ctx, queue, prg)\n\ndef preprocess_image(ctx, queue, image):\n # this is fucked up because opencv can't do no slicin\n r = np.zeros((image.shape[0], image.shape[1]), dtype=image.dtype)\n r[:,:] = image[:,:,0]\n\n g = np.empty_like(r)\n g[:,:] = image[:,:,1]\n\n b = np.empty_like(r)\n b[:,:] = image[:,:,2]\n\n mf = cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR\n\n r_buf = cl.Buffer(ctx, mf, hostbuf=r)\n b_buf = cl.Buffer(ctx, mf, hostbuf=g)\n g_buf = cl.Buffer(ctx, mf, hostbuf=b)\n\n return (r_buf, b_buf, g_buf)\n\ndef summed_area_table(ctx, queue, prg, image, shape):\n r, g, b = image\n x, y = shape\n\n temp = cl.Buffer(ctx, cl.mem_flags.READ_WRITE, x*y*np.dtype('uint32').itemsize)\n r1 = cl.Buffer(ctx, cl.mem_flags.READ_WRITE, x*y*np.dtype('uint32').itemsize)\n g1 = cl.Buffer(ctx, cl.mem_flags.READ_WRITE, x*y*np.dtype('uint32').itemsize)\n b1 = cl.Buffer(ctx, cl.mem_flags.READ_WRITE, x*y*np.dtype('uint32').itemsize)\n\n prg.transpose_and_convert(queue, (x,y), None, r, temp)\n prg.sumc(queue, (1,y), None, temp, temp, np.uint32(x))\n prg.transpose(queue, (y,x), None, temp, r1)\n prg.sumc(queue, (1,y), None, r1, r1, np.uint32(x))\n r.release()\n\n prg.transpose_and_convert(queue, (x,y), None, g, temp)\n prg.sumc(queue, (1,y), None, temp, temp, np.uint32(x))\n prg.transpose(queue, (y,x), None, temp, g1)\n prg.sumc(queue, (1,y), None, g1, g1, np.uint32(x))\n g.release()\n\n prg.transpose_and_convert(queue, (x,y), None, b, temp)\n prg.sumc(queue, (1,y), None, temp, temp, np.uint32(x))\n prg.transpose(queue, (y,x), None, temp, b1)\n prg.sumc(queue, (1,y), None, b1, b1, np.uint32(x))\n b.release()\n temp.release()\n\n return (r1, g1, b1)\n\ndef box_filter(ctx, queue, prg, image, size, shape):\n r, g, b = image\n x, y = shape\n offset = np.uint32(size/2)\n\n r_o = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, x*y)\n prg.filter(queue, (x,y), None, r, r_o, offset)\n r.release()\n\n g_o = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, x*y)\n prg.filter(queue, (x,y), None, g, g_o, offset)\n g.release()\n\n b_o = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, x*y)\n prg.filter(queue, (x,y), None, b, b_o, offset)\n b.release()\n\n return (r_o, g_o, b_o)\n\ndef post_process(queue, image, shape):\n r_b, g_b, b_b = image\n r = np.empty(shape, dtype=np.uint8)\n g = np.empty(shape, dtype=np.uint8)\n b = np.empty(shape, dtype=np.uint8)\n\n cl.enqueue_copy(queue, r, r_b)\n cl.enqueue_copy(queue, g, g_b)\n cl.enqueue_copy(queue, b, b_b)\n\n return np.dstack((r,g,b))\n\ndef process(file_in, file_out, filter_size):\n img = cv2.imread(file_in)\n shape = img.shape[0], img.shape[1]\n ctx, queue, prg = prepare_ocl()\n img = preprocess_image(ctx, queue, img)\n img = summed_area_table(ctx, queue, prg, img, shape)\n img = box_filter(ctx, queue, prg, img, filter_size, shape)\n img = post_process(queue, img, shape)\n img = img.copy()\n cv2.imwrite(file_out, img)\n\ndef main():\n filter_size = 15\n print 'filter size:', filter_size, 'x', filter_size, 'pixels'\n\n if len(sys.argv) == 1:\n process('images/Lenna.png', 'out/Lenna.png', filter_size)\n\n else:\n for arg in sys.argv[1:]:\n in_file = arg\n process(arg, 'out/' + os.path.basename(arg), filter_size)\n\nif __name__ == '__main__':\n main()\n\n" }, { "alpha_fraction": 0.712990939617157, "alphanum_fraction": 0.7703927755355835, "avg_line_length": 49.92307662963867, "blob_id": "ca881fdee027ac43e9dd302067af0062283caa65", "content_id": "925b954e42ed6fe02d838df6023a78fb6fbb4003", "detected_licenses": [ "LicenseRef-scancode-public-domain" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 662, "license_type": "permissive", "max_line_length": 174, "num_lines": 13, "path": "/fetchimages.sh", "repo_name": "wrb/abacot", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\n# big images from nasa\nwget -c --directory-prefix=images http://apod.nasa.gov/apod/image/1201/gcwide_eder_2000.jpg http://apod.nasa.gov/apod/image/1201/ngc1232b_vlt_3969.jpg\n\n# kodak testing images\nwget -c --directory-prefix=images http://r0k.us/graphics/kodak/kodak/kodim19.png http://r0k.us/graphics/kodak/kodak/kodim23.png http://r0k.us/graphics/kodak/kodak/kodim03.png\n\n# lenna\nwget -c --directory-prefix=images https://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png\n\n# some more big images\nwget -c --directory-prefix=images http://www.astray.com/static/earth-huge.png http://blogs.voanews.com/digital-frontiers/files/2011/11/OWSonHalloween.jpg\n" } ]
2
gazwald/irc_client
https://github.com/gazwald/irc_client
3bdaf1d704b52fe91c3050cbc606d201bf8263cc
fb2c75a2f2876fc6472bfce2ae3d548838344744
a9f8789184e386e338a895314397dac66c76721e
refs/heads/master
2020-07-21T22:34:33.541695
2016-10-25T11:40:59
2016-10-25T11:40:59
25,421,325
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7171052694320679, "alphanum_fraction": 0.7236841917037964, "avg_line_length": 22.384614944458008, "blob_id": "1e4aeda55387f77188a65ef4e0cf2f4f6a8d9543", "content_id": "48c19ee0ed1aa73a54bd710f60540e725bf0bf5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 304, "license_type": "no_license", "max_line_length": 105, "num_lines": 13, "path": "/README.md", "repo_name": "gazwald/irc_client", "src_encoding": "UTF-8", "text": "irc_client\n==========\n\nBasic (I can't overestate how basic) command line IRC client.\n\nWritten as more of a proof of concept and to test sockets than an actual desire for a working IRC client.\n\nIf there's time I'll clean it up.\n\nWritten for Python 3.4\n\nUsage: \n./program.py --server localhost --user noob\n" }, { "alpha_fraction": 0.526238203048706, "alphanum_fraction": 0.5306603908538818, "avg_line_length": 26.354839324951172, "blob_id": "de539a03ff1308b6d57e32d12b2adfdbc6660bc4", "content_id": "b2cfffad78f48e0edee62dc5069246580d07a779", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3392, "license_type": "no_license", "max_line_length": 66, "num_lines": 124, "path": "/irc/client.py", "repo_name": "gazwald/irc_client", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport socket\nimport threading\nimport logging\nimport sys\n\n\nclass Client:\n channels = []\n current_channel = None\n\n def __init__(self, remote_host, remote_port=6667):\n \"\"\"\n Create a socket and connect to the server.\n If connection is successful start polling thread.\n \"\"\"\n\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n self.s.connect((remote_host, remote_port))\n except socket.error:\n self.quit(\"Socket error, bailing...\")\n else:\n self.previous_message = \"\"\n self.start_polling()\n\n def start_polling(self):\n \"\"\"\n Creates a thread to continually recieve data from socket.\n \"\"\"\n\n self.poller = threading.Thread(target=self.poll)\n self.poller.daemon = True\n self.poller.start()\n\n def send(self, message):\n \"\"\"\n Formats messages/commands to send to the server.\n \"\"\"\n\n message = bytes(message + '\\r\\n', 'ascii', errors='skip')\n\n sent_total = 0\n while sent_total < len(message):\n try:\n sent = self.s.send(message[sent_total:])\n sent_total += sent\n except socket.BrokenPipeError:\n logging.debug(\"Socket timeout?\")\n print(\"Disconnected\")\n break\n\n def format_data(self, data):\n \"\"\"\n Attempts to format the data into something readable.\n Otherwise it'll just dump whatever it gets.\n \"\"\"\n logging.debug(data)\n\n if 'PRIVMSG' in data:\n split_data = data.split(' ')\n channel = split_data[2]\n user = split_data[0].split('!')[0]\n user = user.strip(':')\n message = split_data[3]\n message = message.strip(':')\n print('%s - <%s>: %s' % (channel, user, message))\n elif 'PING' in data:\n logging.debug(\"Sending PONG...\")\n self.send(data.replace('PING', 'PONG'))\n else:\n print(data)\n\n def recv(self, data):\n \"\"\"\n Can't remember why I'm doing this.\n \"\"\"\n\n return data.decode('utf8')\n\n def poll(self):\n \"\"\"\n While the socket is alive attempt to recieve data\n \"\"\"\n\n while True:\n if self.poller.is_alive():\n self.format_data(self.recv(self.s.recv(1024)))\n else:\n break\n\n def set_user(self, user):\n self.send('NICK %s' % user)\n self.send('USER %s * * : %s' % (user, user))\n\n def set_channel(self, channel):\n if channel not in self.channels:\n msg = 'JOIN %s' % channel\n self.send(msg)\n self.channels.append(channel)\n\n self.current_channel = channel\n\n def get_channel(self):\n return self.current_channel\n\n def switch_channel(self, channel):\n if channel not in self.channels:\n self.set_channel(channel)\n self.channels.append(channel)\n else:\n channel = self.current_channel\n\n logging.debug(\"Current channels: %s\" % self.channels)\n\n def quit(self, message):\n \"\"\"\n Close the socket and perform any other cleanup tasks\n \"\"\"\n\n msg = 'QUIT :Client quit (%s).' % message\n self.send(msg)\n self.s.close()\n sys.exit(message)\n" }, { "alpha_fraction": 0.5202388763427734, "alphanum_fraction": 0.5228931903839111, "avg_line_length": 27.980770111083984, "blob_id": "d263adbc3ef9833d204c1632396b3eed27ec988f", "content_id": "d54fad8449386d5eb930bf86fa556d3c4e86d066", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1507, "license_type": "no_license", "max_line_length": 76, "num_lines": 52, "path": "/program.py", "repo_name": "gazwald/irc_client", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport logging\nimport argparse\nimport os\n\nfrom irc import client\n\n\ndef get_args():\n parser = argparse.ArgumentParser(description='Connect to an IRC server')\n parser.add_argument('--server', required=True)\n parser.add_argument('--user', required=True)\n\n return parser.parse_args()\n\n\ndef main():\n args = get_args()\n\n new_client = client.Client(remote_host=args.server)\n\n if args.user:\n new_client.set_user(args.user)\n\n while True:\n try:\n value = input('> ')\n if '/' in value:\n if 'quit' in value.lower():\n new_client.quit(value.split(' ')[1])\n elif 'join' in value.lower():\n new_client.set_channel(value.split(' ')[1])\n elif 'switch' in value.lower():\n new_client.switch_channel(value.split(' ')[1])\n else:\n # I don't know what you wanted to do\n # Send it and hope for the best\n new_client.send(value)\n else:\n msg = 'PRIVMSG %s :%s' % (new_client.get_channel(), value)\n new_client.send(msg)\n except KeyboardInterrupt:\n new_client.quit(\"CTRL+C'ed away\")\n\n\nif __name__ == \"__main__\":\n log_name = \"%s.log\" % os.path.basename(__file__)\n logging.basicConfig(filename=log_name,\n format='%(asctime)s %(message)s',\n level=logging.DEBUG)\n\n main()\n" } ]
3
yunyh/NXT
https://github.com/yunyh/NXT
38643a8db94cc5a34ba2c247e40e3090dd3d7f20
78c029418db80c7754c96b07ce4f4f8ba8e7225d
3cd6a3d7ffa574c245dabd8cebe8b528f7d61d03
refs/heads/master
2021-01-10T01:10:42.296964
2015-12-14T09:41:08
2015-12-14T09:41:08
47,278,985
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7490272521972656, "alphanum_fraction": 0.7645914554595947, "avg_line_length": 35.71428680419922, "blob_id": "108681c091bf32199d943fcac890e935f362880d", "content_id": "f1ad21233a3d92e870703e53527ced8e24cfbb52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 514, "license_type": "no_license", "max_line_length": 92, "num_lines": 14, "path": "/nxt-remote-control-master/app/src/main/java/org/jfedor/nxtremotecontrol/GcmManager/QuickstartPreferences.java", "repo_name": "yunyh/NXT", "src_encoding": "UTF-8", "text": "package org.jfedor.nxtremotecontrol.GcmManager;\n\n/**\n * Created by YoungHyub on 2015-12-09.\n */\npublic class QuickstartPreferences {\n\n public static final String SEND_TOKEN_TO_SERVER = \"sendTokenServer\";\n public static final String RECEIVE_DEACTIVATION_TO_SERVER = \"receiveDeactivationServer\";\n public static final String REGISTRATION_COMPLETE = \"registrationComplete\";\n public static final String MESSAGE_STATE = \"messageState\";\n public static final String NOT_CONNECTED_NXT = \"not connecting\";\n\n}\n" }, { "alpha_fraction": 0.5899000763893127, "alphanum_fraction": 0.5921995043754578, "avg_line_length": 35.47419357299805, "blob_id": "286f030dbcb6a30b941c0ff7560d177061da2384", "content_id": "202b6b90654d8613d2777fbd6dd4f525debd64c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 11307, "license_type": "no_license", "max_line_length": 133, "num_lines": 310, "path": "/nxt-remote-control-master/app/src/main/java/org/jfedor/nxtremotecontrol/GuardController.java", "repo_name": "yunyh/NXT", "src_encoding": "UTF-8", "text": "package org.jfedor.nxtremotecontrol;\n\n\nimport android.app.Activity;\nimport android.bluetooth.BluetoothAdapter;\nimport android.bluetooth.BluetoothDevice;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.content.SharedPreferences;\nimport android.content.SharedPreferences.OnSharedPreferenceChangeListener;\nimport android.content.res.Configuration;\nimport android.nfc.Tag;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.os.PowerManager;\nimport android.preference.PreferenceManager;\nimport android.support.v4.content.LocalBroadcastManager;\nimport android.text.method.ScrollingMovementMethod;\nimport android.util.Log;\nimport android.view.Menu;\nimport android.view.MenuInflater;\nimport android.view.MenuItem;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.Window;\nimport android.view.View.OnClickListener;\nimport android.view.View.OnTouchListener;\nimport android.widget.Button;\nimport android.widget.ImageButton;\nimport android.widget.SeekBar;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport android.widget.SeekBar.OnSeekBarChangeListener;\n\nimport org.jfedor.nxtremotecontrol.GcmManager.QuickstartPreferences;\nimport org.jfedor.nxtremotecontrol.RestRequest.Item;\nimport org.jfedor.nxtremotecontrol.RestRequest.RestRequest;\n\nimport retrofit.Call;\nimport retrofit.Callback;\nimport retrofit.Response;\nimport retrofit.Retrofit;\n\npublic class GuardController extends Activity {\n \n private boolean NO_BT = false; \n \n private static final int REQUEST_ENABLE_BT = 1;\n private static final int REQUEST_CONNECT_DEVICE = 2;\n private static final int REQUEST_SETTINGS = 3;\n \n public static final int MESSAGE_TOAST = 1;\n public static final int MESSAGE_STATE_CHANGE = 2;\n public static final int MESSAGE_ALERT = 3;\n \n public static final String TOAST = \"toast\";\n\n private BluetoothAdapter mBluetoothAdapter;\n\n private NXTTalker mNXTTalker;\n private BroadcastReceiver mReceiver;\n \n private int mState = NXTTalker.STATE_NONE;\n private int mSavedState = NXTTalker.STATE_NONE;\n private boolean mNewLaunch = true;\n private String mDeviceAddress = null;\n private TextView mStateDisplay;\n private TextView mLogTextView;\n private Button mConnectButton;\n private Button mDisconnectButton;\n\n /** Called when the activity is first created. */\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.main);\n mStateDisplay = (TextView) findViewById(R.id.state_display);\n mConnectButton = (Button) findViewById(R.id.connect_button);\n mConnectButton.setOnClickListener(new OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!NO_BT) {\n findBrick();\n } else {\n mState = NXTTalker.STATE_CONNECTED;\n }\n }\n });\n\n mDisconnectButton = (Button) findViewById(R.id.disconnect_button);\n mDisconnectButton.setOnClickListener(new OnClickListener() {\n @Override\n public void onClick(View v) {\n mNXTTalker.stop();\n }\n });\n mLogTextView = (TextView)findViewById(R.id.log_textview);\n mLogTextView.setMovementMethod(new ScrollingMovementMethod());\n\n if (!NO_BT) {\n mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();\n\n if (mBluetoothAdapter == null) {\n Toast.makeText(this, \"Bluetooth is not available\", Toast.LENGTH_LONG).show();\n finish();\n return;\n }\n }\n mNXTTalker = new NXTTalker(mHandler);\n mReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);\n\n if(QuickstartPreferences.NOT_CONNECTED_NXT.equals(action)){\n updateLog(\"Not connected\");\n }\n\n if(QuickstartPreferences.RECEIVE_DEACTIVATION_TO_SERVER.equals(action)){\n boolean set = sharedPreferences.getBoolean(QuickstartPreferences.SEND_TOKEN_TO_SERVER, false);\n updateLog(\"Send token to server\");\n String state = sharedPreferences.getString(QuickstartPreferences.MESSAGE_STATE, null);\n updateLog(\"Receive Message : \" + state);\n if(set){\n if(state.equals(\"confirm\")) {\n sharedPreferences.edit().putBoolean(QuickstartPreferences.RECEIVE_DEACTIVATION_TO_SERVER, false).apply();\n mNXTTalker.ReStartingPatrol(state);\n }\n else if(state.equals(\"shoot\")){\n mNXTTalker.ReStartingPatrol(state);\n }\n else {\n updateLog(\"Error\");\n }\n }\n else{\n updateLog(\"Already Detecting\");\n }\n }\n }\n };\n }\n\n @Override\n protected void onStart() {\n super.onStart();\n //Log.i(\"NXT\", \"NXTRemoteControl.onStart()\");\n if (!NO_BT) {\n if (!mBluetoothAdapter.isEnabled()) {\n Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);\n startActivityForResult(enableIntent, REQUEST_ENABLE_BT);\n } else {\n if (mSavedState == NXTTalker.STATE_CONNECTED) {\n BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);\n mNXTTalker.connect(device);\n } else {\n if (mNewLaunch) {\n mNewLaunch = false;\n findBrick();\n }\n }\n }\n }\n }\n\n private void findBrick() {\n Intent intent = new Intent(this, ChooseDeviceActivity.class);\n startActivityForResult(intent, REQUEST_CONNECT_DEVICE);\n }\n \n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n switch (requestCode) {\n case REQUEST_ENABLE_BT:\n if (resultCode == Activity.RESULT_OK) {\n findBrick();\n } else {\n Toast.makeText(this, \"Bluetooth not enabled, exiting.\", Toast.LENGTH_LONG).show();\n updateLog(\"Bluetooth not enabled, exiting.\");\n finish();\n }\n break;\n case REQUEST_CONNECT_DEVICE:\n if (resultCode == Activity.RESULT_OK) {\n String address = data.getExtras().getString(ChooseDeviceActivity.EXTRA_DEVICE_ADDRESS);\n BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);\n mDeviceAddress = address;\n mNXTTalker.connect(device);\n }\n break;\n case REQUEST_SETTINGS:\n //XXX?\n break;\n }\n }\n\n @Override\n protected void onResume(){\n super.onResume();\n final IntentFilter intentFilter = new IntentFilter();\n intentFilter.addAction(QuickstartPreferences.RECEIVE_DEACTIVATION_TO_SERVER);\n LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,\n intentFilter);\n }\n\n @Override\n protected void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n if (mState == NXTTalker.STATE_CONNECTED) {\n outState.putString(\"device_address\", mDeviceAddress);\n }\n }\n\n private void displayState() {\n String stateText = null;\n int color = 0;\n switch (mState){ \n case NXTTalker.STATE_NONE:\n stateText = \"Not connected\";\n updateLog(stateText);\n color = 0xffff0000;\n mConnectButton.setVisibility(View.VISIBLE);\n mDisconnectButton.setVisibility(View.GONE);\n setProgressBarIndeterminateVisibility(false);\n break;\n case NXTTalker.STATE_CONNECTING:\n stateText = \"Connecting...\";\n updateLog(stateText);\n color = 0xffffff00;\n mConnectButton.setVisibility(View.GONE);\n mDisconnectButton.setVisibility(View.GONE);\n setProgressBarIndeterminateVisibility(true);\n break;\n case NXTTalker.STATE_CONNECTED:\n stateText = \"Connected\";\n updateLog(stateText);\n color = 0xff00ff00;\n mConnectButton.setVisibility(View.GONE);\n mDisconnectButton.setVisibility(View.VISIBLE);\n setProgressBarIndeterminateVisibility(false);\n break;\n }\n mStateDisplay.setText(stateText);\n mStateDisplay.setTextColor(color);\n }\n\n public void updateLog(final String log){\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n mLogTextView.append(log + \"\\n\");\n int lineTop = mLogTextView.getLineCount();\n int scrollY = lineTop - mLogTextView.getHeight();\n Log.d(\"LineTop\", Integer.toString(lineTop));\n Log.d(\"Scroll Y\", Integer.toString(scrollY));\n Log.d(\"Textview Height\", Integer.toString(mLogTextView.getHeight()));\n if (scrollY > 0) {\n mLogTextView.scrollTo(0, scrollY);\n } else {\n mLogTextView.scrollTo(0, 0);\n }\n }\n });\n }\n\n private final Handler mHandler = new Handler() {\n @Override\n public void handleMessage(Message msg) {\n switch (msg.what) {\n case MESSAGE_TOAST:\n Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();\n break;\n case MESSAGE_STATE_CHANGE:\n mState = msg.arg1;\n updateLog(\"State is \" + Integer.toString(mState));\n displayState();\n break;\n case MESSAGE_ALERT:\n RestRequest.APIService service = new RestRequest().getService();\n Call<Item> itemCall = service.sendAlert(msg.toString());\n updateLog(msg.toString());\n itemCall.enqueue(new retrofit.Callback<Item>() {\n @Override\n public void onResponse(Response<Item> response, Retrofit retrofit) {\n Log.d(\"Handler\", response.message());\n }\n\n @Override\n public void onFailure(Throwable t) {\n\n }\n });\n break;\n }\n }\n };\n\n @Override\n protected void onStop() {\n super.onStop();\n mSavedState = mState;\n updateLog(\"Stop\");\n mNXTTalker.stop();\n }\n}\n" }, { "alpha_fraction": 0.606705367565155, "alphanum_fraction": 0.6144422888755798, "avg_line_length": 25.758621215820312, "blob_id": "09afabb55ee7df19a50935f684a311023cc9b3de", "content_id": "7c0df39ac302c2206c1ecaaf08c7dbf9e8456047", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1551, "license_type": "no_license", "max_line_length": 90, "num_lines": 58, "path": "/nxt-remote-control-master/app/src/main/java/org/jfedor/nxtremotecontrol/RestRequest/RestRequest.java", "repo_name": "yunyh/NXT", "src_encoding": "UTF-8", "text": "package org.jfedor.nxtremotecontrol.RestRequest;\n\n/**\n * Created by YoungHyub on 2015-03-20.\n */\n\nimport retrofit.Call;\nimport retrofit.GsonConverterFactory;\nimport retrofit.http.*;\nimport retrofit.Retrofit;\n\npublic class RestRequest {\n\n // private RestCookieManager cookieManager;\n private Retrofit retrofitAdapter;\n\n public APIService getService(){\n retrofitAdapter = new Retrofit.Builder()\n .baseUrl(\"http://uzuki.me:5000\")\n .addConverterFactory(GsonConverterFactory.create())\n .build();\n\n return retrofitAdapter.create(APIService.class);\n }\n\n\n public interface APIService {\n @FormUrlEncoded\n @POST(\"/api/user/alert/\")\n Call<Item> sendAlert(\n @Field(\"alert\") String alert);\n\n @FormUrlEncoded\n @PUT(\"/api/user/gcm/{devicetype}\")\n Call<Item> sendID(\n @Field(\"id\") String id, @Path(\"devicetype\") String type);\n }\n}\n/*\nclass RestCookieManager extends CookieManager {\n\n private String currentCookie;\n\n @Override\n public void put(URI uri, Map<String, List<String>> stringListMap) throws IOException {\n super.put(uri, stringListMap);\n if (stringListMap != null && stringListMap.get(\"Set-Cookie\") != null)\n for (String string : stringListMap.get(\"Set-Cookie\")) {\n if (string.contains(\"session\")) {\n currentCookie = string;\n }\n }\n }\n\n public String getCurrentCookie() {\n return currentCookie;\n }\n}*/" }, { "alpha_fraction": 0.5541740655899048, "alphanum_fraction": 0.5694493651390076, "avg_line_length": 30.64044952392578, "blob_id": "394bf2102674e6b3ef1e7c42d7575c25b94a2f53", "content_id": "63ba8e0c37f2eda700dd88bde575a907ccb39348", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2935, "license_type": "no_license", "max_line_length": 112, "num_lines": 89, "path": "/thirdparty_server.py", "repo_name": "yunyh/NXT", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport sqlite3\nfrom flask import Flask, jsonify, request, g\nfrom gcm import *\n\nDATABASE = '/home/dbsdudguq/dev/nxt/db_2.db'\nTABLE_DEVICEID = 'DeviceID'\nNXT = 'NXT'\nCLIENT = 'Client'\napp = Flask(__name__)\napp.secret_key = 'AG!@S#(*EVN&%D08182VDf3_#$@+*#'\ngcm = GCM(\"AIzaSyBAlqjhRMSMaAvco3BihwjopLbObQo5TWE\")\nsendMessage = {'message': 'message', 'param2': 'value2'}\n\ndef get_db():\n db = getattr(g, '_database', None)\n if db is None:\n db = g._database = sqlite3.connect(DATABASE)\n return db\n\n@app.teardown_appcontext\ndef close_connection(exception):\n db = getattr(g, '_database', None)\n if db is not None:\n db.close()\n\n@app.route('/')\ndef index():\n return 'Safety Login'\n\n#GCM ID 등록 함수\n@app.route('/api/user/gcm/<devicetype>', methods=['PUT'])\ndef registration_id(devicetype):\n id = request.form['id']\n cur = get_db().cursor()\n if devicetype is not None:\n cur.execute(\"SELECT * FROM \" + TABLE_DEVICEID + \" WHERE d_id = ? AND d_type = ?\",\n (id, devicetype))\n data = cur.fetchone()\n print(id + \" : \" + devicetype)\n if data is None:\n cur.execute(\"INSERT INTO \" + TABLE_DEVICEID + \" ('d_id', 'd_type') VALUES (?,?) \", (id, devicetype))\n get_db().commit()\n return jsonify({'message': u'등록 완료'}), 200\n else:\n return jsonify({'message': u'등록된 기기'}), 201\n else:\n return jsonify({'message' : u'등록 실패'}), 401\n\n#경고 확인하고 NXT에서 다시 감시 시작을 보내는 함수\n@app.route('/api/user/confirm', methods=['POST'])\ndef confirm_alert():\n status = request.form['status']\n cur = get_db().cursor()\n if status is not None:\n print(status)\n sendMessage['message'] = status\n cur.execute(\"SELECT d_id FROM \" + TABLE_DEVICEID + \" WHERE d_type = '\" + NXT +\"'\")\n data = cur.fetchall()\n list = []\n for row in data:\n list.append(row[0])\n print(list)\n json.dumps(gcm.json_request(registration_ids=list, data=sendMessage))\n return jsonify({'message': u'경고 해제'}), 200\n else:\n print(\"error\")\n return jsonify({'message': u'서버 에러'}), 401\n\n#경고 보내는 함수\n@app.route('/api/user/alert/', methods=['POST'])\ndef send_gcm():\n status = request.form['alert']\n cur = get_db().cursor()\n if status is not None:\n sendMessage['message'] = status\n cur.execute(\"SELECT d_id FROM \" + TABLE_DEVICEID + \" WHERE d_type = '\" + CLIENT +\"'\")\n data = cur.fetchall()\n list = []\n for row in data:\n list.append(row[0])\n print(list)\n json.dumps(gcm.json_request(registration_ids=list, data=sendMessage))\n return jsonify({'message': u'경고 알림'}), 200\n else:\n return jsonify({'message': u'서버 에러'}), 401\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=5000)" }, { "alpha_fraction": 0.7375690340995789, "alphanum_fraction": 0.7596685290336609, "avg_line_length": 31.909090042114258, "blob_id": "32b140ab6732e71abd7a8abbe51a15ba60d9be8d", "content_id": "49c44de43c35f66f1f1e2277bb35cc5bdc11bf23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 362, "license_type": "no_license", "max_line_length": 78, "num_lines": 11, "path": "/GCM/app/src/main/java/com/gcm/younghyup/gcm/MainManager/QuickstartPreferences.java", "repo_name": "yunyh/NXT", "src_encoding": "UTF-8", "text": "package com.gcm.younghyup.gcm.MainManager;\n\n/**\n * Created by YoungHyub on 2015-12-02.\n */\npublic class QuickstartPreferences {\n\n public static final String SEND_TOKEN_TO_SERVER = \"sendTokenServer\";\n public static final String RECEIVE_ALERT_TO_SERVER = \"receiveAlertServer\";\n public static final String REGISTRATION_COMPLETE = \"registrationComplete\";\n}\n" }, { "alpha_fraction": 0.6285714507102966, "alphanum_fraction": 0.6448979377746582, "avg_line_length": 18.600000381469727, "blob_id": "fcd1f2adad4e4c592dd603bc82ed5db7fec41e2c", "content_id": "ceed9d2d030ceeafea4b7b14f4010027e755d65b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 490, "license_type": "no_license", "max_line_length": 50, "num_lines": 25, "path": "/nxt-remote-control-master/app/src/main/java/org/jfedor/nxtremotecontrol/RestRequest/Item.java", "repo_name": "yunyh/NXT", "src_encoding": "UTF-8", "text": "package org.jfedor.nxtremotecontrol.RestRequest;\n\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * Created by YoungHyup on 2015-12-02.\n */\npublic class Item {\n @SerializedName(\"alert\")\n private String alert;\n private String id;\n\n public String getId(){return id;}\n public void setString(String id){\n this.id = id;\n }\n public String getAlert() {\n return alert;\n }\n\n public void setAlert(String alert) {\n this.alert = alert;\n\n }\n}\n" } ]
6
labcores/p_raphael_fonseca
https://github.com/labcores/p_raphael_fonseca
5a4e9703ecec700a36f5be0736e1e877c6f8091d
c5065fc92db5a51e134b23d09d8b11b162e50661
830d1e7b844934ce9a01f789e8d77bcdcc013d9f
refs/heads/master
2020-12-30T10:24:12.812932
2017-10-27T15:12:36
2017-10-27T15:12:36
98,873,455
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.44673848152160645, "alphanum_fraction": 0.4655894637107849, "avg_line_length": 33.453609466552734, "blob_id": "c9e556f4b99dcf9eb81a4b68a75dd858fff61d04", "content_id": "02c9562340c8aae9d2abf8fee4b058d7852e23da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3342, "license_type": "no_license", "max_line_length": 176, "num_lines": 97, "path": "/2017-SBBD-DSW/search-twitter-geo.py", "repo_name": "labcores/p_raphael_fonseca", "src_encoding": "UTF-8", "text": "# Author: Raphael Fonseca\n# Social Computing and Social Network Analysis Laboratory, Federal University of Rio de Janeiro, Brazil\n# Create Date: 2015-07\n# Last Update: 2017-07-27\n\n# -*- coding: utf-8 -*-\n\nimport oauth2 as oauth\nimport json\nimport time\nimport pymongo\n\n# API Authentication - Fill in credentials\nCONSUMER_KEY = \"\"\nCONSUMER_SECRET = \"\"\nACCESS_KEY = \"\"\nACCESS_SECRET = \"\"\n\n# Prepare Authentication\nconsumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)\naccess_token = oauth.Token(key=ACCESS_KEY, secret=ACCESS_SECRET)\nclient = oauth.Client(consumer, access_token)\n\n# Connect to Database\nclientMongo = pymongo.MongoClient(\"localhost\", 27017)\ndb = clientMongo.chosenDatabase\n\n# Choose if you will use since_id. If you do choose to use it, include it in the URL.\nsince_id = '' \n\n# Geolocation of Central Point\n# Format: Latitude, Longitude, Radius from position\n# Example: -22.903426,-43.191478,70km\ngeo=''\n\n# Starting Date. \n# Format: YYYY-MM-DD\nsince=''\n\n# Until the day prior to... \n# Format: YYYY-MM-DD.\nuntil=''\n\n# List of Terms, separate by commas\nquery = ['']\n\n# Language\n# Format: &lang=languageCode\n# Example for Portuguese: &lang=pt\nlanguage=\"\"\n\nfor q in query:\n\n max_id = '0'\n tweetsCounter = 0\n continueFlag = 1\n\n while(continueFlag == 1):\n try:\n\n if(max_id == '0'):\n\n URL = \"https://api.twitter.com/1.1/search/tweets.json?geocode=\"+geo+\"&since=\"+since+\"&until=\"+until+\"&count=100\"+language\n else:\n\n URL = \"https://api.twitter.com/1.1/search/tweets.json?geocode=\"+geo+\"&since=\"+since+\"&until=\"+until+\"&count=100\"+language+\"&max_id=\"+str(max_id)\n max_id_prior = max_id\n response, data = client.request(URL, \"GET\")\n localCollection = json.loads(data)\n for tweet in localCollection['statuses']:\n \n db.localCollection.update({'id': tweet['id']},tweet, upsert=True)\n tweetsCounter = tweetsCounter + 1\n tweet['text']==dict\n tx = tweet['text']\n print(\"Search Term: \"+ q)\n print(\"\\n\")\n print(str(\"Tweet: \" + tx.encode('utf-8')))\n print(\"\\n\")\n print(\"Number of tweets with current term: \")\n print(tweetsCounter)\n print(\"\\n\")\n print(\"Tweet ID: \")\n print(max_id)\n print('======================================================')\n max_id = tweet['id'] - 1\n \n time.sleep(2)\n if(max_id == max_id_prior): \n continueFlag = 0\n \n except Exception, e:\n\n print(e)\n print('slept')\n time.sleep(15*60)\n pass\n" }, { "alpha_fraction": 0.759036123752594, "alphanum_fraction": 0.759036123752594, "avg_line_length": 26.66666603088379, "blob_id": "d0ad588318c9b42a248a2b0ddc68e0c363bfb838", "content_id": "26d685f19a89156f537e0680dcec9e50f0124b89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 83, "license_type": "no_license", "max_line_length": 60, "num_lines": 3, "path": "/README.md", "repo_name": "labcores/p_raphael_fonseca", "src_encoding": "UTF-8", "text": "# Projects of Raphael Fonseca\n\n## Open projects created for my research in CORES Laboratory\n" }, { "alpha_fraction": 0.7235772609710693, "alphanum_fraction": 0.7425474524497986, "avg_line_length": 32.54545593261719, "blob_id": "4f6ee293f81a48604c2816bb6a527fa511d39aab", "content_id": "dd6935c36a351930b5762789ef3ed9c1cd95086e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 369, "license_type": "no_license", "max_line_length": 113, "num_lines": 11, "path": "/2017-SBBD-DSW/README.md", "repo_name": "labcores/p_raphael_fonseca", "src_encoding": "UTF-8", "text": "<hr>\n\n# Files submitted for the SBBD-DSW 2017.\n\n<p> This folder consists of: <br>\n1. Python Script for crawling data from the Twitter API. <br>\n2. Datasets of MongoDB .BSON files along with the .JSON to be restored for validating content. <br>\n3. A hashtag list file containing all the hashtags after the filtering and process described in the article. <br>\n</p>\n\n<hr>\n" } ]
3
KyonkoYuuki/YaBCMOrganizer
https://github.com/KyonkoYuuki/YaBCMOrganizer
d103c14e828ba583b7e99a18993c71e1e4497259
f01f89e26f71bb63e7ca6e8a28944a99cbe10ff5
129c012e616f770e3ad69014c161ab41be13659e
refs/heads/master
2023-06-08T10:12:05.887304
2023-05-27T15:05:45
2023-05-27T15:05:45
192,439,742
0
2
null
2019-06-18T00:57:33
2021-11-16T22:49:43
2023-05-27T15:05:45
Python
[ { "alpha_fraction": 0.5835365056991577, "alphanum_fraction": 0.5895739197731018, "avg_line_length": 36.62331771850586, "blob_id": "718c9703c064dc995720995672d7959fe04ea3de", "content_id": "08a3991bd8ee465680eaaf85fd7ad13cd39aba57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8613, "license_type": "no_license", "max_line_length": 118, "num_lines": 223, "path": "/YaBCM Organizer.py", "repo_name": "KyonkoYuuki/YaBCMOrganizer", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python3.6\r\nimport os\r\nimport sys\r\nimport traceback\r\n\r\nfrom pubsub import pub\r\nimport wx\r\nfrom wx.lib.dialogs import ScrolledMessageDialog\r\nfrom wx.lib.agw.hyperlink import HyperLinkCtrl\r\n\r\nfrom pyxenoverse.bcm import BCM\r\nfrom pyxenoverse.gui import create_backup\r\nfrom yabcm.panels.main import MainPanel\r\nfrom yabcm.panels.entry import EntryPanel\r\nfrom yabcm.dlg.find import FindDialog\r\nfrom yabcm.dlg.replace import ReplaceDialog\r\nfrom pyxenoverse.gui.file_drop_target import FileDropTarget\r\n\r\nVERSION = '0.2.9'\r\n\r\n\r\nclass MainWindow(wx.Frame):\r\n def __init__(self, parent, title, dirname, filename):\r\n sys.excepthook = self.exception_hook\r\n self.dirname = ''\r\n self.bcm = None\r\n self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)\r\n\r\n # A \"-1\" in the size parameter instructs wxWidgets to use the default size.\r\n # In this case, we select 200px width and the default height.\r\n wx.Frame.__init__(self, parent, title=title, size=(1300, 900))\r\n self.statusbar = self.CreateStatusBar() # A Statusbar in the bottom of the window\r\n\r\n # Panels\r\n self.main_panel = MainPanel(self)\r\n self.entry_panel = EntryPanel(self)\r\n\r\n # Setting up the menu.\r\n file_menu= wx.Menu()\r\n file_menu.Append(wx.ID_OPEN)\r\n file_menu.Append(wx.ID_SAVE)\r\n file_menu.Append(wx.ID_ABOUT)\r\n file_menu.Append(wx.ID_EXIT)\r\n\r\n edit_menu = wx.Menu()\r\n edit_menu.Append(wx.ID_FIND)\r\n edit_menu.Append(wx.ID_REPLACE)\r\n\r\n # Creating the menubar.\r\n menu_bar = wx.MenuBar()\r\n menu_bar.Append(file_menu, \"&File\") # Adding the \"filemenu\" to the MenuBar\r\n menu_bar.Append(edit_menu, \"&Edit\")\r\n self.SetMenuBar(menu_bar) # Adding the MenuBar to the Frame content.\r\n\r\n # Publisher\r\n pub.subscribe(self.open_bcm, 'open_bcm')\r\n pub.subscribe(self.load_bcm, 'load_bcm')\r\n pub.subscribe(self.save_bcm, 'save_bcm')\r\n pub.subscribe(self.set_status_bar, 'set_status_bar')\r\n\r\n # Events.\r\n self.Bind(wx.EVT_MENU, self.open_bcm, id=wx.ID_OPEN)\r\n self.Bind(wx.EVT_MENU, self.save_bcm, id=wx.ID_SAVE)\r\n self.Bind(wx.EVT_MENU, self.on_find, id=wx.ID_FIND)\r\n self.Bind(wx.EVT_MENU, self.on_replace, id=wx.ID_REPLACE)\r\n self.Bind(wx.EVT_MENU, self.on_about, id=wx.ID_ABOUT)\r\n self.Bind(wx.EVT_MENU, self.on_exit, id=wx.ID_EXIT)\r\n self.Bind(wx.EVT_MENU, self.main_panel.on_copy, id=wx.ID_COPY)\r\n self.Bind(wx.EVT_MENU, self.main_panel.on_paste, id=wx.ID_PASTE)\r\n self.Bind(wx.EVT_MENU, self.main_panel.on_delete, id=wx.ID_DELETE)\r\n self.Bind(wx.EVT_MENU, self.main_panel.on_add_child, id=wx.ID_ADD)\r\n self.Bind(wx.EVT_MENU, self.main_panel.on_append, id=self.main_panel.append_id)\r\n self.Bind(wx.EVT_MENU, self.main_panel.on_insert, id=self.main_panel.insert_id)\r\n accelerator_table = wx.AcceleratorTable([\r\n (wx.ACCEL_CTRL, ord('o'), wx.ID_OPEN),\r\n (wx.ACCEL_CTRL, ord('s'), wx.ID_SAVE),\r\n (wx.ACCEL_CTRL, ord('f'), wx.ID_FIND),\r\n (wx.ACCEL_CTRL, ord('h'), wx.ID_REPLACE),\r\n ])\r\n self.SetAcceleratorTable(accelerator_table)\r\n self.SetDropTarget(FileDropTarget(self, \"load_bcm\"))\r\n\r\n # Name\r\n self.name = wx.StaticText(self, -1, '(No file loaded)')\r\n font = wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)\r\n self.name.SetFont(font)\r\n\r\n # Buttons\r\n open_button = wx.Button(self, wx.ID_OPEN, \"Load\")\r\n open_button.Bind(wx.EVT_BUTTON, self.open_bcm)\r\n\r\n save_button = wx.Button(self, wx.ID_SAVE, \"Save\")\r\n save_button.Bind(wx.EVT_BUTTON, self.save_bcm)\r\n\r\n hyperlink = HyperLinkCtrl(self, -1, \"What do all these things mean?\",\r\n URL=\"https://docs.google.com/document/d/\"\r\n \"18gaAbNCeJyTgizz5IvvXzjWcH9K5Q1wvUHTeWnp8M-E/edit#heading=h.tx82dphejin1\")\r\n\r\n # Sizer\r\n sizer = wx.BoxSizer(wx.VERTICAL)\r\n button_sizer = wx.BoxSizer()\r\n button_sizer.Add(open_button)\r\n button_sizer.AddSpacer(10)\r\n button_sizer.Add(save_button)\r\n button_sizer.Add(hyperlink, 0, wx.ALL, 10)\r\n\r\n panel_sizer = wx.BoxSizer()\r\n panel_sizer.Add(self.main_panel, 1, wx.ALL | wx.EXPAND)\r\n panel_sizer.Add(self.entry_panel, 2, wx.ALL | wx.EXPAND)\r\n\r\n sizer.Add(self.name, 0, wx.CENTER)\r\n sizer.Add(button_sizer, 0, wx.ALL, 10)\r\n sizer.Add(panel_sizer, 1, wx.ALL | wx.EXPAND)\r\n\r\n self.SetBackgroundColour('white')\r\n self.SetSizer(sizer)\r\n self.SetAutoLayout(1)\r\n\r\n # Lists\r\n self.entry_list = self.main_panel.entry_list\r\n\r\n # Dialogs\r\n self.find = FindDialog(self, self.entry_list, -1)\r\n self.replace = ReplaceDialog(self, self.entry_list, -1)\r\n\r\n sizer.Layout()\r\n self.Show()\r\n\r\n if filename:\r\n self.load_bcm(dirname, filename)\r\n\r\n def exception_hook(self, etype, value, trace):\r\n dlg = ScrolledMessageDialog(self, ''.join(traceback.format_exception(etype, value, trace)), \"Error\")\r\n dlg.ShowModal()\r\n dlg.Destroy()\r\n\r\n def on_about(self, e):\r\n # Create a message dialog box\r\n dlg = wx.MessageDialog(self, f\"Yet Another BCM Organizer v{VERSION} by Kyonko Yuuki\",\r\n \"About BCM Organizer\", wx.OK)\r\n dlg.ShowModal() # Shows it\r\n dlg.Destroy() # finally destroy it when finished.\r\n\r\n def on_exit(self, e):\r\n self.Close(True) # Close the frame.\r\n\r\n def set_status_bar(self, text):\r\n self.statusbar.SetStatusText(text)\r\n\r\n def open_bcm(self, e):\r\n dlg = wx.FileDialog(self, \"Choose a file\", self.dirname, \"\", \"*.bcm\", wx.FD_OPEN)\r\n if dlg.ShowModal() == wx.ID_OK:\r\n self.load_bcm(dlg.GetDirectory(), dlg.GetFilename())\r\n dlg.Destroy()\r\n\r\n def load_bcm(self, dirname, filename):\r\n self.dirname = dirname\r\n path = os.path.join(self.dirname, filename)\r\n self.statusbar.SetStatusText(\"Loading...\")\r\n new_bcm = BCM()\r\n if not new_bcm.load(path):\r\n dlg = wx.MessageDialog(self, f\"{filename} is not a valid BCM\", \"Warning\")\r\n dlg.ShowModal()\r\n dlg.Destroy()\r\n return\r\n self.bcm = new_bcm\r\n self.main_panel.bcm = new_bcm\r\n self.bcm.loadComment(path)\r\n # Build Tree\r\n self.entry_list.DeleteAllItems()\r\n temp_entry_list = {\r\n 0: self.entry_list.AddRoot('Entry 0', data=self.bcm.entries[0])\r\n }\r\n for entry in sorted(self.bcm.entries[1:], key=lambda x: (x.parent, x.address)):\r\n temp_entry_list[entry.address] = self.entry_list.AppendItem(temp_entry_list[entry.parent], '', data=entry)\r\n self.entry_list.Expand(temp_entry_list[0])\r\n\r\n self.main_panel.reindex()\r\n self.main_panel.Layout()\r\n self.entry_panel.Disable()\r\n\r\n self.name.SetLabel(filename)\r\n self.statusbar.SetStatusText(f\"Loaded {path}\")\r\n\r\n def save_bcm(self, e):\r\n if not self.bcm:\r\n dlg = wx.MessageDialog(self, \" No BCM Loaded\", \"Warning\", wx.OK)\r\n dlg.ShowModal() # Shows it\r\n dlg.Destroy() # finally destroy it when finished.\r\n return\r\n\r\n dlg = wx.FileDialog(self, \"Save as...\", self.dirname, \"\", \"*.bcm\", wx.FD_SAVE)\r\n if dlg.ShowModal() == wx.ID_OK:\r\n filename = dlg.GetFilename()\r\n self.dirname = dlg.GetDirectory()\r\n self.statusbar.SetStatusText(\"Saving...\")\r\n create_backup(self.dirname, filename)\r\n path = os.path.join(self.dirname, filename)\r\n self.main_panel.reindex()\r\n self.bcm.save(path)\r\n self.bcm.saveComment(path)\r\n self.statusbar.SetStatusText(f\"Saved {path}\")\r\n saved = wx.MessageDialog(self, f\"Saved to {path} successfully\", \"BCM Saved\")\r\n saved.ShowModal()\r\n saved.Destroy()\r\n dlg.Destroy()\r\n\r\n def on_find(self, _):\r\n if not self.replace.IsShown():\r\n self.find.Show()\r\n\r\n def on_replace(self, _):\r\n if not self.find.IsShown():\r\n self.replace.Show()\r\n\r\n\r\nif __name__ == '__main__':\r\n app = wx.App(False)\r\n dirname = filename = None\r\n if len(sys.argv) > 1:\r\n dirname, filename = os.path.split(sys.argv[1])\r\n frame = MainWindow(None, f\"YaBCM Organizer v{VERSION}\", dirname, filename)\r\n app.MainLoop()\r\n" }, { "alpha_fraction": 0.572227418422699, "alphanum_fraction": 0.5772949457168579, "avg_line_length": 38.11214828491211, "blob_id": "ee238fcffc1d1123d3287cdd5af92f9f6e202c3d", "content_id": "59d306c6efa2577004aa0714a5f8828402021eb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17168, "license_type": "no_license", "max_line_length": 156, "num_lines": 428, "path": "/yabcm/panels/main.py", "repo_name": "KyonkoYuuki/YaBCMOrganizer", "src_encoding": "UTF-8", "text": "import wx\r\nimport pickle\r\nfrom pyxenoverse.bcm import address_to_index, index_to_address, BCMEntry\r\nfrom pyxenoverse.gui import get_next_item, get_first_item, get_item_index\r\nfrom pubsub import pub\r\n\r\nfrom yabcm.dlg.comment import CommentDialog\r\n\r\n\r\nclass MainPanel(wx.Panel):\r\n def __init__(self, parent):\r\n wx.Panel.__init__(self, parent)\r\n self.parent = parent\r\n self.bcm = None\r\n\r\n self.entry_list = wx.TreeCtrl(self, style=wx.TR_MULTIPLE | wx.TR_HAS_BUTTONS | wx.TR_FULL_ROW_HIGHLIGHT | wx.TR_LINES_AT_ROOT | wx.TR_TWIST_BUTTONS)\r\n self.entry_list.Bind(wx.EVT_TREE_ITEM_MENU, self.on_right_click)\r\n self.entry_list.Bind(wx.EVT_TREE_SEL_CHANGED, self.on_select)\r\n self.cdo = wx.CustomDataObject(\"BCMEntry\")\r\n\r\n self.append_id = wx.NewId()\r\n self.insert_id = wx.NewId()\r\n self.comment_id = wx.NewId()\r\n self.Bind(wx.EVT_MENU, self.on_delete, id=wx.ID_DELETE)\r\n self.Bind(wx.EVT_MENU, self.on_copy, id=wx.ID_COPY)\r\n self.Bind(wx.EVT_MENU, self.on_paste, id=wx.ID_PASTE)\r\n self.Bind(wx.EVT_MENU, self.on_add_child, id=wx.ID_ADD)\r\n self.Bind(wx.EVT_MENU, self.on_append, id=self.append_id)\r\n self.Bind(wx.EVT_MENU, self.on_insert, id=self.insert_id)\r\n self.Bind(wx.EVT_MENU, self.on_comment, id=self.comment_id)\r\n accelerator_table = wx.AcceleratorTable([\r\n (wx.ACCEL_CTRL, ord('a'), self.append_id),\r\n (wx.ACCEL_CTRL, ord('i'), self.insert_id),\r\n (wx.ACCEL_CTRL, ord('n'), wx.ID_ADD),\r\n (wx.ACCEL_CTRL, ord('c'), wx.ID_COPY),\r\n (wx.ACCEL_CTRL, ord('v'), wx.ID_PASTE),\r\n (wx.ACCEL_CTRL, ord('q'), self.comment_id),\r\n (wx.ACCEL_NORMAL, wx.WXK_DELETE, wx.ID_DELETE),\r\n ])\r\n self.entry_list.SetAcceleratorTable(accelerator_table)\r\n\r\n pub.subscribe(self.on_select, 'on_select')\r\n pub.subscribe(self.reindex, 'reindex')\r\n pub.subscribe(self.relabel, 'relabel')\r\n\r\n # Use some sizers to see layout options\r\n sizer = wx.BoxSizer(wx.VERTICAL)\r\n sizer.Add(self.entry_list, 1, wx.ALL | wx.EXPAND, 10)\r\n\r\n # Layout sizers\r\n self.SetSizer(sizer)\r\n self.SetAutoLayout(1)\r\n\r\n def on_right_click(self, _):\r\n selections= self.entry_list.GetSelections()\r\n if not selections:\r\n return\r\n menu = wx.Menu()\r\n copy = menu.Append(wx.ID_COPY, \"&Copy\\tCtrl+C\", \"Copy entry\")\r\n paste = menu.Append(wx.ID_PASTE, \"&Paste\\tCtrl+V\", \"Paste entry\")\r\n delete = menu.Append(wx.ID_DELETE, \"&Delete\\tDelete\", \"Delete entry(s)\")\r\n append = menu.Append(self.append_id, \"&Append\\tCtrl+A\", \"Append entry after\")\r\n insert = menu.Append(self.insert_id, \"&Insert\\tCtrl+I\", \"Insert entry before\")\r\n menu.Append(wx.ID_ADD, \"Add &New Child\\tCtrl+N\", \"Add child entry\")\r\n\r\n enabled = len(selections) == 1 and selections[0] != self.entry_list.GetRootItem()\r\n copy.Enable(enabled)\r\n success = False\r\n if enabled and wx.TheClipboard.Open():\r\n success = wx.TheClipboard.IsSupported(wx.DataFormat(\"BCMEntry\"))\r\n wx.TheClipboard.Close()\r\n\r\n #comment stuff\r\n comment = menu.Append(self.comment_id, \"Add Comment\\tCtrl+Q\", \"Add Comment\")\r\n\r\n\r\n for sel in self.entry_list.GetSelections():\r\n entry = self.entry_list.GetItemData(sel)\r\n entry_class_name = entry.__class__.__name__\r\n\r\n if entry.get_name() != \"Entry\":\r\n comment.Enable(False)\r\n break\r\n\r\n paste.Enable(success)\r\n delete.Enable(enabled)\r\n append.Enable(enabled)\r\n insert.Enable(enabled)\r\n self.PopupMenu(menu)\r\n menu.Destroy()\r\n\r\n def on_select(self, _):\r\n item = self.select_single_item(show_error=False)\r\n if not item:\r\n return\r\n pub.sendMessage('load_entry', entry=self.entry_list.GetItemData(item))\r\n\r\n def update_entry(self, item, entry):\r\n self.entry_list.SetItemText(item, f'{entry.index}: Entry (0x{entry.flags:X}){entry.getDisplayComment()}')\r\n\r\n def expand_parents(self, item):\r\n root = self.entry_list.GetRootItem()\r\n parent = self.entry_list.GetItemParent(item)\r\n while parent != root:\r\n self.entry_list.Expand(parent)\r\n parent = self.entry_list.GetItemParent(parent)\r\n\r\n def select_item(self, item):\r\n self.entry_list.UnselectAll()\r\n self.entry_list.SelectItem(item)\r\n self.expand_parents(item)\r\n if not self.entry_list.IsVisible(item):\r\n self.entry_list.ScrollTo(item)\r\n\r\n def get_selected_root_nodes(self):\r\n selected = self.entry_list.GetSelections()\r\n if not selected:\r\n return []\r\n root = self.entry_list.GetRootItem()\r\n\r\n nodes = []\r\n for item in selected:\r\n parent = self.entry_list.GetItemParent(item)\r\n while parent != root and parent.IsOk():\r\n if parent in selected:\r\n break\r\n parent = self.entry_list.GetItemParent(parent)\r\n if parent == root:\r\n nodes.append(item)\r\n return nodes\r\n\r\n def add_entry(self, parent, index):\r\n success = False\r\n cdo = wx.CustomDataObject(\"BCMEntry\")\r\n if wx.TheClipboard.Open():\r\n success = wx.TheClipboard.GetData(cdo)\r\n if success:\r\n entries = pickle.loads(cdo.GetData())\r\n\r\n # Increment addresses so they don't run into existing ones.\r\n # Luckily....there is a limit on how big they can be.\r\n for entry in entries:\r\n entry.address += 0x100000000\r\n entry.child += 0x100000000\r\n entry.parent += 0x100000000\r\n entry.sibling += 0x100000000\r\n else:\r\n entries = [BCMEntry(*(35 * [0]))]\r\n if index == -1:\r\n item = self.entry_list.AppendItem(parent, '', data=entries[0])\r\n else:\r\n item = self.entry_list.InsertItem(parent, index, '', data=entries[0])\r\n\r\n # Get data from parent and surrounding siblings\r\n parent_data = self.entry_list.GetItemData(parent)\r\n prev_item = self.entry_list.GetPrevSibling(item)\r\n prev_data = self.entry_list.GetItemData(prev_item) if prev_item.IsOk() else None\r\n\r\n next_item = self.entry_list.GetNextSibling(item)\r\n next_data = self.entry_list.GetItemData(next_item) if next_item.IsOk() else None\r\n\r\n if next_data:\r\n entries[0].sibling = next_data.address\r\n\r\n temp_entry_list = {\r\n entries[0].address: item\r\n }\r\n for entry in entries[1:]:\r\n temp_entry_list[entry.address] = self.entry_list.AppendItem(temp_entry_list[entry.parent], '', data=entry)\r\n\r\n self.reindex()\r\n\r\n # If siblings aren't set, set them now\r\n update = False\r\n\r\n if parent_data.child == 0:\r\n parent_data.child = entries[0].address\r\n update = True\r\n\r\n if prev_data and next_data and prev_data.sibling == next_data.address:\r\n prev_data.sibling, entries[0].sibling = entries[0].address, next_data.address\r\n update = True\r\n\r\n if prev_data and prev_data.sibling == 0:\r\n prev_data.sibling = entries[0].address\r\n update = True\r\n\r\n if update:\r\n self.reindex()\r\n\r\n self.entry_list.Expand(parent)\r\n self.entry_list.UnselectAll()\r\n self.entry_list.SelectItem(item)\r\n if not self.entry_list.IsVisible(item):\r\n self.entry_list.ScrollTo(item)\r\n return entries\r\n\r\n def get_children(self, entry):\r\n parents = [self.entry_list.GetItemData(entry).address]\r\n children = []\r\n\r\n item = get_next_item(self.entry_list, entry)\r\n while item.IsOk():\r\n data = self.entry_list.GetItemData(item)\r\n if data.parent not in parents:\r\n break\r\n parents.append(data.address)\r\n children.append(item)\r\n item = get_next_item(self.entry_list, item)\r\n\r\n return children\r\n\r\n def select_single_item(self, show_error=True):\r\n selections = self.entry_list.GetSelections()\r\n if len(selections) != 1:\r\n if show_error and len(selections) > 1:\r\n with wx.MessageDialog(self, \"Can only select one entry for this function\", \"Error\") as dlg:\r\n dlg.ShowModal()\r\n return\r\n\r\n return selections[0]\r\n\r\n def on_add_child(self, _):\r\n item = self.select_single_item()\r\n data = self.entry_list.GetItemData(item)\r\n if not item:\r\n return\r\n entries = self.add_entry(item, -1)\r\n if data.child == 0:\r\n data.child = entries[0].address\r\n self.reindex()\r\n pub.sendMessage(\r\n 'set_status_bar', text=f'Added {len(entries)} entry(s) under {self.entry_list.GetItemText(item)}')\r\n\r\n def on_append(self, _):\r\n item = self.select_single_item()\r\n if not item:\r\n return\r\n if item == self.entry_list.GetRootItem():\r\n with wx.MessageDialog(self, \"Cannot add entry next to root entry, must be a child\", \"Warning\") as dlg:\r\n dlg.ShowModal()\r\n return\r\n parent = self.entry_list.GetItemParent(item)\r\n index = get_item_index(self.entry_list, item)\r\n entries = self.add_entry(parent, index + 1)\r\n pub.sendMessage(\r\n 'set_status_bar', text=f'Added {len(entries)} entry(s) after {self.entry_list.GetItemText(item)}')\r\n\r\n def on_insert(self, _):\r\n item = self.select_single_item()\r\n if not item:\r\n return\r\n if item == self.entry_list.GetRootItem():\r\n with wx.MessageDialog(self, \"Cannot add entry before root entry.\", \"Warning\") as dlg:\r\n dlg.ShowModal()\r\n return\r\n parent = self.entry_list.GetItemParent(item)\r\n index = get_item_index(self.entry_list, item)\r\n insert_at_first = True\r\n entries = self.add_entry(parent, index)\r\n self.reindex(insert_at_first=insert_at_first)\r\n print(\"after reindex\")\r\n pub.sendMessage(\r\n 'set_status_bar', text=f'Added {len(entries)} entry(s) before {self.entry_list.GetItemText(item)}')\r\n\r\n def on_delete(self, _):\r\n selections = self.entry_list.GetSelections()\r\n if not selections:\r\n return\r\n if self.entry_list.GetRootItem() in selections:\r\n with wx.MessageDialog(self, \"Cannot delete entry 0\", 'Error', wx.OK) as dlg:\r\n dlg.ShowModal()\r\n return\r\n old_num_entries = len(self.parent.bcm.entries)\r\n\r\n for item in selections:\r\n self.entry_list.Delete(item)\r\n self.reindex()\r\n new_num_entries = len(self.parent.bcm.entries)\r\n pub.sendMessage('disable')\r\n pub.sendMessage('set_status_bar', text=f'Deleted {old_num_entries - new_num_entries} entries')\r\n\r\n def on_comment(self, _):\r\n selected = self.entry_list.GetSelections()\r\n entry = self.entry_list.GetItemData(selected[0])\r\n\r\n comment_val = \"\"\r\n with CommentDialog(self, \"Comment\", entry.getComment(), -1) as dlg:\r\n if dlg.ShowModal() != wx.ID_OK:\r\n return\r\n comment_val = dlg.GetValue()\r\n\r\n for sel in selected:\r\n entry = self.entry_list.GetItemData(sel)\r\n entry.setComment(comment_val)\r\n\r\n # update later to avoid offsetting twice\r\n\r\n self.relabel(index=address_to_index(entry.address))\r\n\r\n self.bcm.has_comments = True\r\n pub.sendMessage('set_status_bar', text=f'Comment Added')\r\n\r\n def on_copy(self, _):\r\n item = self.select_single_item()\r\n if not item or item == self.entry_list.GetRootItem():\r\n return\r\n selections = [item]\r\n if self.entry_list.GetChildrenCount(item) > 0:\r\n with wx.MessageDialog(self, 'Copy children entries as well?', '', wx.YES | wx.NO) as dlg:\r\n if dlg.ShowModal() == wx.ID_YES:\r\n selections.extend(self.get_children(item))\r\n\r\n entries = sorted([self.entry_list.GetItemData(item) for item in selections], key=lambda data: data.address)\r\n\r\n self.cdo = wx.CustomDataObject(\"BCMEntry\")\r\n self.cdo.SetData(pickle.dumps(entries))\r\n if wx.TheClipboard.Open():\r\n wx.TheClipboard.SetData(self.cdo)\r\n wx.TheClipboard.Flush()\r\n wx.TheClipboard.Close()\r\n msg = 'Copied ' + self.entry_list.GetItemText(item)\r\n if len(entries) > 1:\r\n msg += f' and {len(entries) - 1} children'\r\n pub.sendMessage('set_status_bar', text=msg)\r\n\r\n def on_paste(self, _):\r\n item = self.select_single_item()\r\n if not item or item == self.entry_list.GetRootItem():\r\n return\r\n\r\n success = False\r\n cdo = wx.CustomDataObject(\"BCMEntry\")\r\n if wx.TheClipboard.Open():\r\n success = wx.TheClipboard.GetData(cdo)\r\n wx.TheClipboard.Close()\r\n if not success:\r\n return\r\n\r\n paste_data = pickle.loads(cdo.GetData())[0]\r\n entry = self.entry_list.GetItemData(item)\r\n\r\n # Keep address/parent/child\r\n paste_data.address = entry.address\r\n paste_data.parent = entry.parent\r\n paste_data.child = entry.child\r\n paste_data.sibling = entry.sibling\r\n\r\n self.entry_list.SetItemData(item, paste_data)\r\n self.reindex()\r\n pub.sendMessage('load_entry', entry=self.entry_list.GetItemData(item))\r\n pub.sendMessage('set_status_bar', text='Pasted to ' + self.entry_list.GetItemText(item))\r\n\r\n def relabel(self, index):\r\n item = self.entry_list.GetRootItem()\r\n\r\n for _ in range(index):\r\n item = get_next_item(self.entry_list, item)\r\n\r\n entry = self.entry_list.GetItemData(item)\r\n sibling = self.entry_list.GetNextSibling(item)\r\n child, _ = self.entry_list.GetFirstChild(item)\r\n sibling_address = self.entry_list.GetItemData(sibling).address if sibling.IsOk() else 0\r\n child_address = self.entry_list.GetItemData(child).address if child.IsOk() else 0\r\n text = f'Entry {index}'\r\n if sibling_address != entry.sibling:\r\n text += f\", Sibling: {address_to_index(entry.sibling)}\"\r\n if child_address != entry.child:\r\n text += f\", Child: {address_to_index(entry.child)}\"\r\n text += f\"{entry.getDisplayComment()}\"\r\n self.entry_list.SetItemText(item, text)\r\n\r\n def reindex(self, insert_at_first=False):\r\n # Set indexes first\r\n item, _ = get_first_item(self.entry_list)\r\n index = 1\r\n mappings = {}\r\n while item.IsOk():\r\n entry = self.entry_list.GetItemData(item)\r\n old_address, entry.address = entry.address, index_to_address(index)\r\n mappings[old_address] = entry.address\r\n self.entry_list.SetItemText(item, f'Entry {index}')\r\n item = get_next_item(self.entry_list, item)\r\n index += 1\r\n\r\n # Set parent/child/sibling/root\r\n item, _ = get_first_item(self.entry_list)\r\n root = 0\r\n entries = [self.entry_list.GetItemData(self.entry_list.GetRootItem())]\r\n while item.IsOk():\r\n entry = self.entry_list.GetItemData(item)\r\n text = self.entry_list.GetItemText(item)\r\n sibling = self.entry_list.GetNextSibling(item)\r\n child, _ = self.entry_list.GetFirstChild(item)\r\n parent = self.entry_list.GetItemParent(item)\r\n\r\n sibling_address = self.entry_list.GetItemData(sibling).address if sibling.IsOk() else 0\r\n child_address = self.entry_list.GetItemData(child).address if child.IsOk() else 0\r\n\r\n # Root will always be one of the immediate childs to Entry 0\r\n if parent == self.entry_list.GetRootItem():\r\n root = entry.address\r\n\r\n # If the mapping for the sibling/child has been deleted, reset it\r\n\r\n if entry.sibling:\r\n entry.sibling = mappings.get(entry.sibling, 0)\r\n if not entry.sibling:\r\n entry.sibling = sibling_address\r\n\r\n if entry.child:\r\n entry.child = mappings.get(entry.child, 0)\r\n if not entry.child:\r\n entry.child = child_address\r\n\r\n entry.parent = self.entry_list.GetItemData(parent).address if parent != self.entry_list.GetRootItem() else 0\r\n entry.root = root\r\n\r\n if sibling_address != entry.sibling:\r\n text += f\", Sibling: {address_to_index(entry.sibling)}\"\r\n if child_address != entry.child:\r\n text += f\", Child: {address_to_index(entry.child)}\"\r\n text += f\"{entry.getDisplayComment()}\"\r\n self.entry_list.SetItemText(item, text)\r\n\r\n entries.append(entry)\r\n item = get_next_item(self.entry_list, item)\r\n self.parent.bcm.entries = entries\r\n" }, { "alpha_fraction": 0.5370612144470215, "alphanum_fraction": 0.556340754032135, "avg_line_length": 42.38999938964844, "blob_id": "d0b066b975eb8219601a512363341df7d85d62d2", "content_id": "e4d111c6ae0d7e5feb2a36ad97cea65567fd2142", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13019, "license_type": "no_license", "max_line_length": 135, "num_lines": 300, "path": "/yabcm/panels/entry.py", "repo_name": "KyonkoYuuki/YaBCMOrganizer", "src_encoding": "UTF-8", "text": "import wx\nfrom pubsub import pub\nfrom wx.lib.scrolledpanel import ScrolledPanel\nfrom pyxenoverse.bcm import address_to_index, index_to_address\nfrom pyxenoverse.gui import add_entry, EVT_RESULT, EditThread\nfrom pyxenoverse.gui.ctrl.dummy_ctrl import DummyCtrl\nfrom pyxenoverse.gui.ctrl.hex_ctrl import HexCtrl\nfrom pyxenoverse.gui.ctrl.multiple_selection_box import MultipleSelectionBox\nfrom pyxenoverse.gui.ctrl.single_selection_box import SingleSelectionBox\n\nMAX_UINT16 = 0xFFFF\nMAX_UINT32 = 0xFFFFFFFF\nLABEL_STYLE = wx.ALIGN_CENTER_VERTICAL | wx.ALL\n\n\nclass Page(ScrolledPanel):\n def __init__(self, parent, rows=32):\n ScrolledPanel.__init__(self, parent)\n self.sizer = wx.FlexGridSizer(rows=rows, cols=2, hgap=5, vgap=5)\n self.SetSizer(self.sizer)\n self.SetupScrolling()\n\n\nclass EntryPanel(wx.Panel):\n def __init__(self, parent):\n wx.Panel.__init__(self, parent)\n self.parent_panel = parent\n self.entry = None\n self.notebook = wx.Notebook(self)\n self.edit_thread = None\n button_input_panel = Page(self.notebook)\n activator_panel = Page(self.notebook)\n bac_panel = Page(self.notebook)\n misc_panel = Page(self.notebook)\n unknown_panel = Page(self.notebook)\n\n self.notebook.AddPage(button_input_panel, 'Inputs')\n self.notebook.AddPage(activator_panel, 'Activator')\n self.notebook.AddPage(bac_panel, 'BAC')\n self.notebook.AddPage(misc_panel, 'Misc')\n self.notebook.AddPage(unknown_panel, 'Unknown')\n\n sizer = wx.BoxSizer()\n sizer.Add(self.notebook, 1, wx.ALL | wx.EXPAND, 10)\n\n self.address = DummyCtrl()\n self.sibling = self.add_num_entry(misc_panel, 'Sibling Idx', min=0, max=0x7FFFFFFF)\n self.parent = DummyCtrl()\n self.child = self.add_num_entry(misc_panel, 'Child Idx', min=0, max=0x7FFFFFFF)\n self.root = DummyCtrl()\n\n # u_00\n self.u_00 = self.add_hex_entry(unknown_panel, 'U_00', max=MAX_UINT32)\n\n # directional input\n self.directional_input = self.add_multiple_selection_entry(\n button_input_panel, 'Directional Input', cols=2, orient=wx.VERTICAL, choices=[\n ('User Direction', ['Input activated once', 'Up', 'Down', 'Right', 'Left'], True),\n ('Relative Direction', ['Forwards', 'Backwards', 'Left', 'Right'], True)\n ])\n\n # Button input\n self.button_input = self.add_multiple_selection_entry(\n button_input_panel, 'Button Input', title='0xABCDEFGH', cols=3, orient=wx.VERTICAL, choices=[\n ('B/C', ['Lock On', 'Descend', 'Dragon Radar', 'Jump', 'Ultimate attack'], True),\n ('D', ['Skill input', 'Skill display + skill input', 'Ultimate attack + skill input', None], True),\n ('E', None, True),\n ('F', ['Skill display + weak attack', 'Skill display + strong attack',\n 'Skill display + ki blast', 'Skill display + jump'], True),\n ('G', ['Skill display', 'Boost/step', 'Block', None], True),\n ('H', ['Weak attack', 'Strong attack', 'Ki blast', 'Jump'], True)\n ])\n\n # Hold Down Conditions\n self.hold_down_conditions = self.add_multiple_selection_entry(\n button_input_panel, 'Hold Down\\nConditions', majorDimension=1, choices=[\n ('Charge Type', {\n 'Automatic': 0x0,\n 'Manual': 0x1,\n 'Unknown (0x2)': 0x2,\n 'Unknown (0x3)': 0x3,\n }, False),\n ('Options #2', {\n 'Unknown (0x0)': 0x0,\n 'Unknown (0x1)': 0x1,\n 'Unknown (0x2)': 0x2,\n 'Unknown (0x3)': 0x3,\n }, False),\n ('Options #3', {\n 'Unknown (0x0)': 0x0,\n 'Unknown (0x1)': 0x1,\n 'Unknown (0x2)': 0x2,\n 'Unknown (0x3)': 0x3,\n }, False),\n ('Options #4', {\n 'Unknown (0x0)': 0x0,\n 'Unknown (0x1)': 0x1,\n 'Unknown (0x2)': 0x2,\n 'Unknown (0x3)': 0x3,\n }, False),\n ('Action', {\n 'Continue until released': 0x0,\n 'Delay until released': 0x1,\n 'Unknown (0x2)': 0x2,\n 'Stop skill from activating': 0x4\n }, False)\n ])\n\n # Opponent Size Conditions\n self.opponent_size_conditions = self.add_hex_entry(\n activator_panel, 'Opponent Size\\nConditions', max=MAX_UINT32)\n\n # Minimum Loop Duration\n self.minimum_loop_duration = self.add_num_entry(\n activator_panel, 'Minimum Loop\\nConditions', True)\n\n # Maximum Loop Duration\n self.maximum_loop_duration = self.add_num_entry(\n activator_panel, 'Maximum Loop\\nConditions', True)\n\n # Primary Activator Conditions\n self.primary_activator_conditions = self.add_multiple_selection_entry(\n activator_panel, 'Primary Activator\\nConditions', cols=3, orient=wx.VERTICAL, choices=[\n ('Health', [\"User's Health (One Use)\", \"Target's health < 25%\",\n \"When Running BAC Entry Attack Hits\", \"User's Health\"], True),\n ('Collision/stamina', [\"Active Projectile\", 'Stamina > 0%', 'Not near map ceiling', 'Not near certain objects'], True),\n ('Targeting', [\"Opponent Knockback\", None, 'Targeting Opponent'], True),\n ('Touching', [None, None, 'Ground', 'Opponent'], True),\n ('Counter and ki amount', ['Counter melee', 'Counter projectile', 'Ki < 100%', 'Ki > 0%'], True),\n ('Primary activator', ['Transformed', 'Flash on/off unless targeting', None, 'Not Moving'], True),\n ('Distance and transformation', ['Attack Pass on Opponent Guard', 'Close', 'Far', 'Base form'], True),\n ('Position', ['Standing', 'Floating', 'Touching \"ground\"', 'When an attack hits'], True)\n ])\n\n # Activator State\n self.activator_state = self.add_multiple_selection_entry(\n activator_panel, 'Activator State', cols=2, orient=wx.VERTICAL, choices=[\n ('', ['Receiving Damage', 'Jumping', 'Not being damaged', 'Target attacking player'], True),\n ('', ['Idle', 'Combo/skill', 'Boosting', 'Guarding'], True)\n ])\n\n # BAC Stuff\n self.bac_entry_primary = self.add_num_entry(bac_panel, 'BAC Entry Primary', True)\n self.bac_entry_charge = self.add_num_entry(bac_panel, 'BAC Entry Charge', True)\n self.u_24 = self.add_hex_entry(unknown_panel, 'U_24', max=MAX_UINT16)\n self.bac_entry_user_connect = self.add_num_entry(bac_panel, 'BAC Entry\\nUser Connect', True)\n self.bac_entry_victim_connect = self.add_num_entry(bac_panel, 'BAC Entry\\nVictim Connect', True)\n self.bac_entry_airborne = self.add_num_entry(bac_panel, 'BAC Entry Airborne', True)\n self.bac_entry_unknown = self.add_num_entry(bac_panel, 'BAC Entry Targetting Override', True)\n self.random_flag = self.add_multiple_selection_entry(bac_panel, 'Unknown BAC Flags', majorDimension=2, choices=[\n ('', {\n 'None': 0x0,\n 'Random BAC Entry': 0x1,\n 'No Target Correction': 0x2,\n '3 Instance Setup': 0x3,\n 'Unknown (0x4)': 0x4,\n 'Unknown (0x5)': 0x6,\n }, False)\n ])\n\n self.ki_cost = self.add_num_entry(misc_panel, 'Ki Cost', True)\n self.u_44 = self.add_hex_entry(unknown_panel, 'U_44', max=MAX_UINT32)\n self.u_48 = self.add_hex_entry(unknown_panel, 'U_48', max=MAX_UINT32)\n self.receiver_link_id = self.add_hex_entry(misc_panel, 'Receiver Link Id', max=MAX_UINT32)\n self.u_50 = self.add_hex_entry(unknown_panel, 'U_50', max=MAX_UINT32)\n self.stamina_cost = self.add_num_entry(misc_panel, 'Stamina Cost', True)\n self.u_58 = self.add_hex_entry(unknown_panel, 'U_58', max=MAX_UINT32)\n self.ki_required = self.add_num_entry(misc_panel, 'Ki Required', True)\n self.health_required = self.add_float_entry(misc_panel, 'Health Required')\n self.trans_stage = self.add_num_entry(misc_panel, 'Transformation\\nStage')\n self.cus_aura = self.add_num_entry(misc_panel, 'CUS_AURA')\n self.u_68 = self.add_multiple_selection_entry(unknown_panel, 'Unknown Flags', majorDimension=2, choices=[\n ('', {\n 'None': 0x0,\n 'Use Skill Upgrades': 0x1,\n 'Unknown (0x2)': 0x2,\n 'Unknown (0x4)': 0x4,\n 'Opponent Reached Ground?': 0x6,\n 'Unknown (0x8)': 0x8,\n }, False)\n ])\n\n self.u_6a = self.add_hex_entry(unknown_panel, 'U_6A', max=MAX_UINT16)\n self.u_6c = self.add_hex_entry(unknown_panel, 'U_6C', max=MAX_UINT32)\n\n # Binds\n self.Bind(wx.EVT_TEXT, self.on_edit)\n self.Bind(wx.EVT_CHECKBOX, self.save_entry)\n self.Bind(wx.EVT_RADIOBOX, self.save_entry)\n EVT_RESULT(self, self.save_entry)\n\n # Publisher\n pub.subscribe(self.load_entry, 'load_entry')\n pub.subscribe(self.on_disable, 'disable')\n pub.subscribe(self.on_enable, 'enable')\n pub.subscribe(self.focus, 'focus')\n\n # Layout sizers\n self.Disable()\n self.SetSizer(sizer)\n self.SetAutoLayout(1)\n\n def __getitem__(self, item):\n return self.__getattribute__(item)\n\n def on_disable(self):\n self.Disable()\n\n def on_enable(self):\n self.Enable()\n\n @add_entry\n def add_hex_entry(self, parent, _, *args, **kwargs):\n if 'size' not in kwargs:\n kwargs['size'] = (150, -1)\n return HexCtrl(parent, *args, **kwargs)\n\n @add_entry\n def add_num_entry(self, panel, _, unsigned=False, *args, **kwargs):\n if 'size' not in kwargs:\n kwargs['size'] = (150, -1)\n if unsigned:\n kwargs['min'], kwargs['max'] = kwargs.get('min', 0), kwargs.get('max', 65535)\n else:\n kwargs['min'], kwargs['max'] = kwargs.get('min', -32768), kwargs.get('max', 32767)\n return wx.SpinCtrl(panel, *args, **kwargs)\n\n @add_entry\n def add_single_selection_entry(self, panel, _, *args, **kwargs):\n return SingleSelectionBox(panel, *args, **kwargs)\n\n @add_entry\n def add_multiple_selection_entry(self, panel, _, *args, **kwargs):\n return MultipleSelectionBox(panel, *args, **kwargs)\n\n @add_entry\n def add_float_entry(self, panel, _, *args, **kwargs):\n if 'size' not in kwargs:\n kwargs['size'] = (150, -1)\n if 'min' not in kwargs:\n kwargs['min'] = -3.402823466e38\n if 'max' not in kwargs:\n kwargs['max'] = 3.402823466e38\n\n return wx.SpinCtrlDouble(panel, *args, **kwargs)\n\n def on_edit(self, _):\n if not self.edit_thread:\n self.edit_thread = EditThread(self)\n else:\n self.edit_thread.new_sig()\n\n def load_entry(self, entry):\n for name in entry.__fields__:\n if name == 'child' or name == 'sibling':\n self[name].SetValue(address_to_index(entry[name]))\n else:\n self[name].SetValue(entry[name])\n if entry.address == 0:\n self.Disable()\n else:\n self.Enable()\n self.entry = entry\n\n def save_entry(self, _):\n self.edit_thread = None\n if not self.entry:\n return\n relabel = False\n for name in self.entry.__fields__:\n # SpinCtrlDoubles suck\n control = self[name]\n old_value = self.entry[name]\n if isinstance(control, wx.SpinCtrlDouble):\n try:\n new_value = float(control.Children[0].GetValue())\n except ValueError:\n # Keep old value if its mistyped\n new_value = old_value\n elif name == \"child\" or name == \"sibling\":\n num_entries = len(self.parent_panel.bcm.entries)\n new_value = control.GetValue()\n if new_value >= num_entries:\n new_value = num_entries - 1\n control.SetValue(new_value)\n new_value = index_to_address(new_value)\n else:\n new_value = control.GetValue()\n if old_value != new_value:\n self.entry[name] = new_value\n if name == \"child\" or name == \"sibling\":\n relabel = True\n\n if relabel:\n pub.sendMessage('relabel', index=address_to_index(self.entry.address))\n\n def focus(self, entry):\n page = self.notebook.FindPage(self[entry].GetParent())\n self.notebook.ChangeSelection(page)\n self[entry].SetFocus()\n\n\n" }, { "alpha_fraction": 0.749873161315918, "alphanum_fraction": 0.7772704362869263, "avg_line_length": 53.75, "blob_id": "1ff8157b26d71064fa5f25d5260481eceaf150b0", "content_id": "638da46ece8066c39abff365598040719f8587d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1971, "license_type": "no_license", "max_line_length": 153, "num_lines": 36, "path": "/README.md", "repo_name": "KyonkoYuuki/YaBCMOrganizer", "src_encoding": "UTF-8", "text": "# YaBCMOrganizer\nThis tool is here to help out with creating and modifying BCMs. In addition to giving a more organized look into what the various entries do, it can also\n\n* Copy, Delete, and Paste entries\n* Copy an entry and its children in full and add them all elsewhere while preserving its hierarchy\n* Clipboard can be shared between multiple instances to allow easy copying/pasting between different BCM's\n* Automatically reindexes for the OCD\n* Easy link to the BCM section of the Skill/Moveset guide for more explanation on the various thing\n\n# Credits\n* DemonBoy - Idea and testing\n* Eternity - Genser source code helped with the nitty gritty technical bits of the BCM file structure.\n* Smithers & LazyBones - For the Skill/Moveset guide and the research into what each BCM entry field does.\n\n\n# Changelog\n```\n0.1.0 - Initial release\n0.1.1 - Fixed order of BAC Charge and BAC Airborne\n0.1.2 - Add search/replace function\n0.1.3 - Fixed floating point entries not being able to go negative\n0.1.4 - Fixed issue when searching sometimes freezing the program\n0.1.5 - Fixed issue saving\n0.1.6 - Removed conflicting options and shortcuts from main edit menu\n0.1.7 - Added ability to drag/associate files to exe to open them\n0.1.8 - Fixed floats not updating sometimes\n0.2.0 - Added child/sibling links to misc panel, changed backend treectrl for displaying tree,\n allow limited multi select for deleting multiple entries, removed prompt asking to keep children when deleting.\n0.2.1 - Fixed bug where entry0 wasn't added when saving. Improved performance on copying large entries.\n0.2.2 - Add automatic backup creation on saving\n0.2.3 - Improved editing performance with very large BCM's, fixed child/sibling indexes cutting off at 32767\n0.2.4 - Added primary activator conditions\n0.2.5 - Fixed find/replace dialogs so it works with int/hex/float\n0.2.6 - Added new flag selections in unknown and BAC tabs\n fixed names on Primary Activator Conditions \n```\n" } ]
4
mateuszwronski/django19
https://github.com/mateuszwronski/django19
51c2bda2b5ee8cfcdbfeda268b891b5cb482d33f
7b096a3e2cac47b445449cb446fb97805df4f53d
3fa22e5c9df39bfab1082b7d04adf63222569541
refs/heads/master
2022-12-13T00:07:49.672449
2019-10-05T12:54:19
2019-10-05T12:54:19
212,966,075
0
0
null
2019-10-05T08:15:16
2019-10-05T12:54:27
2022-12-08T06:40:44
Python
[ { "alpha_fraction": 0.6818181872367859, "alphanum_fraction": 0.6909090876579285, "avg_line_length": 29, "blob_id": "33630585fbc073926f50c05625b1a0e322e26f1a", "content_id": "126c7799e62cb414114605eb21568c1d3a35c470", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 330, "license_type": "no_license", "max_line_length": 77, "num_lines": 11, "path": "/microblog/posts/urls.py", "repo_name": "mateuszwronski/django19", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom django.views.generic import TemplateView\n\nfrom . import views\n\nurlpatterns = [\n path('1', views.hello_world, name='hello_world'),\n path('2', views.HelloWorldView.as_view()),\n path('3', TemplateView.as_view(\n template_name='posts/index.html', extra_context=dict(name='Piotr'))),\n]\n" } ]
1
alejoxbg/Capulus
https://github.com/alejoxbg/Capulus
e367ea8f61da976bfb975dcb20ef4bbf9306940e
5338bca0118e626e652c5c221cb6be9be6f33130
4fbebe51daf748ac7ff7d3ff7ee6856c995dfdb1
refs/heads/main
2023-08-20T18:03:33.899883
2021-10-22T14:55:24
2021-10-22T14:55:24
352,496,304
2
1
null
2021-03-29T02:46:29
2021-09-23T16:02:41
2021-09-23T16:10:21
Python
[ { "alpha_fraction": 0.6123926043510437, "alphanum_fraction": 0.6540027260780334, "avg_line_length": 23.296703338623047, "blob_id": "ea861df37e2f9607278ae7ffa3f31bd8c862c896", "content_id": "cd52185d404c94436441f54347377d26d6819717", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2211, "license_type": "no_license", "max_line_length": 181, "num_lines": 91, "path": "/Capulus_webots/controllers/Basic_capulus/Basic_capulus.py", "repo_name": "alejoxbg/Capulus", "src_encoding": "UTF-8", "text": "\"\"\"control_4_llantas controller.\"\"\"\n\n# You may need to import some classes of the controller module. Ex:\n# from controller import Robot, Motor, DistanceSensor\nfrom controller import Robot, Keyboard\n\n# create the Robot instance.\nrobot = Robot()\nkeyboard=Keyboard()\n# get the time step of the current world.\ntimestep = 32\n\nkeyboard.enable(timestep)\n\nwheels=[]\nwheelsNames=['LEFT_MOTOR','RIGHT_MOTOR', 'LEFT_LINEAR', 'RIGHT_LINEAR','wheel_l1','wheel_l2','wheel_l3','wheel_l4','wheel_l5','wheel_r1','wheel_r2','wheel_r3','wheel_r4','wheel_r5']\n\nfor i in range(14):\n wheels.append(robot.getDevice(wheelsNames[i]))\n wheels[i].setPosition(float('inf'))\n wheels[i].setVelocity(0.0)\n\n\n\n\navoidObstacleCounter=0\n\n\n# Main loop:\n# - perform simulation steps until Webots is stopping the controller\nwhile robot.step(timestep) != -1:\n leftSpeed=0.0\n rightSpeed=0.0\n leftTrack=0.0\n rightTrack=0.0\n key=keyboard.getKey()\n print(key)\n if key ==87:\n leftSpeed=1.0\n\n elif key == 83:\n leftSpeed=-1.0\n\n elif key==65:\n\n rightSpeed=1.0\n elif key == 68:\n\n rightSpeed=-1.0\n elif key==81:\n\n leftTrack=2.0\n rightTrack=-2.0\n elif key == 69:\n leftTrack=-2.0\n rightTrack=2.0\n elif key==90:\n\n leftTrack=-2.0\n rightTrack=-2.0\n elif key == 67:\n leftTrack=2.0\n rightTrack=2.0\n \n \n wheels[0].setVelocity(leftSpeed)\n wheels[1].setVelocity(rightSpeed)\n wheels[2].setVelocity(-leftTrack/20)\n wheels[3].setVelocity(rightTrack/20)\n wheels[4].setVelocity(leftTrack)\n wheels[5].setVelocity(leftTrack)\n wheels[6].setVelocity(leftTrack)\n wheels[7].setVelocity(leftTrack)\n wheels[8].setVelocity(leftTrack)\n wheels[9].setVelocity(rightTrack)\n wheels[10].setVelocity(rightTrack)\n wheels[11].setVelocity(rightTrack)\n wheels[12].setVelocity(rightTrack)\n wheels[13].setVelocity(rightTrack)\n \n # Read the sensors:\n # Enter here functions to read sensor data, like:\n # val = ds.getValue()\n\n # Process sensor data here.\n\n # Enter here functions to send actuator commands, like:\n # motor.setPosition(10.0)\n pass\n\n# Enter here exit cleanup code.\n" }, { "alpha_fraction": 0.5285795331001282, "alphanum_fraction": 0.555291473865509, "avg_line_length": 34.34000015258789, "blob_id": "1435e946f7fe610db29c2e437f20ded0df7f4474", "content_id": "39defd9e8d956bd896ae4dcf4a457cd97afe775d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8835, "license_type": "permissive", "max_line_length": 100, "num_lines": 250, "path": "/roboclaw_driver/src/roboclaw_driver/roboclaw_control.py", "repo_name": "alejoxbg/Capulus", "src_encoding": "UTF-8", "text": "import threading\n\nfrom . roboclaw import Roboclaw\n\nERRORS = {\n # 0x0000: \"Normal\",\n 0x0001: \"M1 over current warning\",\n 0x0002: \"M2 over current warning\",\n 0x0004: \"Emergency Stop warning\",\n 0x0008: \"Temperature1 error\",\n 0x0010: \"Temperature2 error\",\n 0x0020: \"Main batt voltage high error\",\n 0x0040: \"Logic batt voltage high error\",\n 0x0080: \"Logic batt voltage low error\",\n 0x0100: \"M1 driver fault error\",\n 0x0200: \"M2 driver fault error\",\n 0x0400: \"Main batt voltage high warning\",\n 0x0800: \"Main batt voltage low warning\",\n 0x1000: \"Temperature1 warning\",\n 0x2000: \"Temperature2 warning\",\n # 0x4000: \"M1 home\",\n # 0x8000: \"M2 home\"\n}\n\n\nclass RoboclawStats:\n \"\"\"Holds point-in-time stats values about the motors read from a Roboclaw controller.\n\n Stats:\n m1_enc_val: Motor 1 encoder value (>= 0)\n m2_enc_val: Motor 2 encoder value (>= 0)\n m1_enc_qpps: Motor 1 encoder speed in QPPS (+/-)\n m2_enc_qpps: Motor 2 encoder speed in QPPS (+/-)\n error_messages: List of error messages occuring during stats reading\n\n Notes:\n Quadrature encoders have a range of 0 to 4,294,967,295\n \"\"\"\n def __init__(self):\n self.m1_enc_val = None\n self.m2_enc_val = None\n self.m1_enc_qpps = None\n self.m2_enc_qpps = None\n self.error_messages = []\n\n def __str__(self):\n return \"[M1 enc: {}, qpps: {}] [M2 enc: {}, qpps: {}]\".format(\n self.m1_enc_val, self.m1_enc_qpps,\n self.m2_enc_val, self.m2_enc_qpps\n )\n\n\nclass RoboclawDiagnostics:\n \"\"\"Holds point-in-time diagnostic values read from the Roboclaw controller.\n\n Diagnostics:\n m1_current: Motor 1 current (amps)\n m2_current: Motor 2 current (amps)\n temp: Roboclaw controller temperature (C)\n main_battery_v: Voltage of the main battery (V)\n error_messages: List of error messages occuring during stats reading\n \"\"\"\n def __init__(self):\n self.m1_current = None\n self.m2_current = None\n self.temp1 = None\n self.temp2 = None\n self.main_battery_v = None\n self.logic_battery_v = None\n self.error_messages = []\n\n\nclass RoboclawControl:\n def __init__(self, roboclaw, address=0x80):\n \"\"\"\n Parameters:\n :param Roboclaw roboclaw: The Roboclaw object from the Python driver library\n :param int address: The serial addresss of the Roboclaw controller\n \"\"\"\n self._roboclaw = roboclaw\n self._address = address\n self._serial_lock = threading.RLock()\n\n if isinstance(roboclaw, Roboclaw):\n self._initialize()\n\n @property\n def roboclaw(self):\n return self._roboclaw\n\n def _initialize(self):\n # Connect and initialize the Roboclaw controller over serial\n with self._serial_lock:\n try:\n self._roboclaw.Open()\n except Exception:\n # Pass the exception up so it can be logged by the ROS logging facilities\n # Also, if this fais we really can't continue\n raise\n\n self.stop()\n self._roboclaw.ResetEncoders(self._address)\n\n def stop(self, decel=20000):\n \"\"\"Stop Roboclaw.\n\n Returns: True if the command succeeded, False if failed\n :rtype: bool\n \"\"\"\n with self._serial_lock:\n # return self.SpeedAccelDistanceM1M2(\n # accel=0, speed1=0, distance1=0, speed2=0, distance2=0, reset_buffer=1\n # )\n return self.driveM1M2qpps(0, 0, decel, 0)\n\n def driveM1M2qpps(self, m1_qpps, m2_qpps, accel, max_secs):\n with self._serial_lock:\n\t self._roboclaw.SetPWMMode(self._address,mode=1)\n\t if m1_qpps<0:\n\t\tself._roboclaw.ForwardM1(self._address,val=-m1_qpps)\n\t else:\n\t\tself._roboclaw.BackwardM1(self._address,val=m1_qpps)\n\t if m2_qpps<0:\n\t\tself._roboclaw.ForwardM2(self._address,val=-m2_qpps)\n\t else:\n\t\tself._roboclaw.BackwardM2(self._address,val=m2_qpps)\n return\n\n def read_stats(self):\n \"\"\"Read and return the monitorinng values of the Roboclaw\n\n Returns: Tuple of (success, RoboclawStats object containing the current values of the stats)\n :rtype: (boolean, RoboclawStats)\n \"\"\"\n stats = RoboclawStats()\n read_error = False\n retries = 2\n\n with self._serial_lock:\n # Read encoder value\n for i in range(0, retries):\n response = self._roboclaw.ReadEncM1(self._address)\n if response[0]:\n stats.m1_enc_val = response[1]\n read_error = False\n break\n else:\n stats.error_messages.append(\"ReadEncM1 CRC failed: {}\".format(response[0]))\n read_error = True\n \n if read_error:\n return (False, None)\n\n for i in range(0, retries):\n response = self._roboclaw.ReadEncM2(self._address)\n if response[0]:\n stats.m2_enc_val = response[1]\n read_error = False\n break\n else:\n stats.error_messages.append(\"ReadEncM2 CRC failed: {}\".format(response[0]))\n read_error = True\n if read_error:\n return (False, None)\n\n # Read encoder speed\n for i in range(0, retries):\n response = self._roboclaw.ReadSpeedM1(self._address)\n if response[0]:\n stats.m1_enc_qpps = response[1]\n read_error = False\n break\n else:\n stats.error_messages.append(\"ReadSpeedM1 CRC failed: {}\".format(response[0]))\n read_error = True\n if read_error:\n return (False, None)\n\n for i in range(0, retries):\n response = self._roboclaw.ReadSpeedM2(self._address)\n if response[0]:\n stats.m2_enc_qpps = response[1]\n read_error = False\n break\n else:\n stats.error_messages.append(\"ReadSpeedM2 CRC failed: {}\".format(response[0]))\n read_error = True\n if read_error:\n return (False, None)\n\n # Return (success, stats)\n return (True, stats)\n\n def read_diag(self):\n \"\"\"Read and return the diagnostic values of the Roboclaw\n\n Returns: RoboclawDiagnostics object containing the current values of the diagnostics\n :rtype: RoboclawDiagnostics\n \"\"\"\n diag = RoboclawDiagnostics()\n\n with self._serial_lock:\n # Read motor current\n try:\n success, cur1, cur2 = self._roboclaw.ReadCurrents(self._address)\n diag.m1_current = cur1 / 100.0\n diag.m2_current = cur2 / 100.0\n except ValueError as e:\n diag.error_messages.append(\"Motor currents ValueError: {}\".format(e.message))\n\n # Read Roboclaw temperature\n try:\n success, temp = self._roboclaw.ReadTemp(self._address)\n diag.temp1 = temp / 10.0\n except ValueError as e:\n diag.error_messages.append(\"Temperature 1 ValueError: {}\".format(e.message))\n\n try:\n success, temp = self._roboclaw.ReadTemp2(self._address)\n diag.temp2 = temp / 10.0\n except ValueError as e:\n diag.error_messages.append(\"Temperature 2 ValueError: {}\".format(e.message))\n\n # Read main battery voltage\n try:\n success, volts = self._roboclaw.ReadMainBatteryVoltage(self._address)\n diag.main_battery_v = volts / 10.0\n except ValueError as e:\n diag.error_messages.append(\"Main battery voltage ValueError: {}\".format(e.message))\n\n # Read logic battery voltage\n try:\n success, volts = self._roboclaw.ReadLogicBatteryVoltage(self._address)\n diag.logic_battery_v = volts / 10.0\n except ValueError as e:\n diag.error_messages.append(\n \"Logic battery voltage ValueError: {}\".format(e.message))\n\n # Read errors\n try:\n success, errors = self._roboclaw.ReadError(self._address)\n except ValueError as e:\n diag.error_messages.append(\"Read status/errors ValueError: {}\".format(e.message))\n\n if errors:\n for err in ERRORS.keys():\n if (errors & err):\n diag.error_messages.append(ERRORS[err])\n\n return diag\n" }, { "alpha_fraction": 0.7784430980682373, "alphanum_fraction": 0.7880239486694336, "avg_line_length": 31.115385055541992, "blob_id": "f9619d558de2fdce524ee362723ba1e47f2fa78b", "content_id": "f1936719de536e726620608e4d1c351da503c3c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 835, "license_type": "no_license", "max_line_length": 373, "num_lines": 26, "path": "/README.md", "repo_name": "alejoxbg/Capulus", "src_encoding": "UTF-8", "text": "# Capulus\n\nThis project is the design, construction and software development of a ground mobile robot focused to perform activities within coffee farms, in this repository you can find the CAD models that were used to model and build the robot, the dynamic simulations in webots and the different ROS packages that were used to perform the teleoperation and for its perception system.\n\nYou can see videos of the robot in the following links:\n\nTilt tests:\nhttps://www.youtube.com/watch?v=4jDVVaN-1A8\n\nSpin test:\nhttps://www.youtube.com/watch?v=EYGEjlZiWx4\n\nReal field tests:\nhttps://www.youtube.com/watch?v=VNCkxsc_Qe4\n\nKalman filter localization:\nhttps://www.youtube.com/watch?v=74ZAOpA_L4A\n\n## Circuit\n\n![](https://github.com/alejoxbg/Capulus/blob/main/Circuit.jpg)\n\n## Run\nCone to your ROS worspace\n\n>roslaunch capulus driver.launch\n" }, { "alpha_fraction": 0.5766395330429077, "alphanum_fraction": 0.5927808880805969, "avg_line_length": 31.114286422729492, "blob_id": "fc3f568455364eb436ec59baac0e37d7e4d4d650", "content_id": "2d31beeacc83a372677cb052c048003618483d0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7868, "license_type": "no_license", "max_line_length": 100, "num_lines": 245, "path": "/diff_drive/nodes/capulus_teleop", "repo_name": "alejoxbg/Capulus", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# Copyright (c) 2011, Willow Garage, Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the Willow Garage, Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport rospy\nfrom geometry_msgs.msg import Twist\nimport traceback\nimport threading\n\nimport rospy\nimport diagnostic_updater\nimport diagnostic_msgs\n\nfrom roboclaw_driver.msg import Stats, SpeedCommand\nfrom roboclaw_driver import RoboclawControl, Roboclaw, RoboclawStub\nimport sys, select, os\nif os.name == 'nt':\n import msvcrt\nelse:\n import tty, termios\n\nMAX_LIN_VEL = 2\nMAX_ANG_VEL = 0.5\n\n\nLIN_VEL_STEP_SIZE = 0.1\nANG_VEL_STEP_SIZE = 0.1\n\nmsg = \"\"\"\n CONTROL DE CAPULUS\n---------------------------\nControles:\n\n arriba\n\n <<izquierda ok derecha>>\n\n abajo\n\n (ok-enter: para frenar por completo)\n (e: finalizar conexion con el CAPULUS)\n (r: iniciar marcha y adelante)\n\"\"\"\n\ne = \"\"\"\nCommunications Failed\n\"\"\"\nimport sys,tty,termios\nclass _Getch: \n def __call__(self):\n fd = sys.stdin.fileno()\n old_settings = termios.tcgetattr(fd)\n try:\n \ttty.setraw(sys.stdin.fileno())\n \t ch = sys.stdin.read(1)\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n return ch\n\ndef get():\n inkey = _Getch()\n while(1):\n k=inkey()\n if k!='':break\n #print 'you pressed', ord(k)\n return k\n\ndef vels(target_linear_vel, target_angular_vel):\n return \"currently:\\tlinear vel %s\\t angular vel %s \" % (target_linear_vel,target_angular_vel)\n\ndef makeSimpleProfile(output, input, slop):\n if input > output:\n output = min( input, output + slop )\n elif input < output:\n output = max( input, output - slop )\n else:\n output = input\n\n return output\n\ndef constrain(input, low, high):\n if input < low:\n input = low\n elif input > high:\n input = high\n else:\n input = input\n\n return input\n\ndef checkLinearLimitVelocity(vel):\n\n vel = constrain(vel, -MAX_LIN_VEL, MAX_LIN_VEL)\n\n\n return vel\n\ndef checkAngularLimitVelocity(vel):\n\n vel = constrain(vel, -MAX_ANG_VEL, MAX_ANG_VEL)\n\n return vel\n\nif __name__==\"__main__\":\n if os.name != 'nt':\n settings = termios.tcgetattr(sys.stdin)\n\n rospy.init_node('diff_drive')\n pub = rospy.Publisher('/roboclaw/speed_command', SpeedCommand, queue_size=10)\n\n\n status = 0\n target_linear_vel = 0.0\n target_angular_vel = 0.0\n control_linear_vel = 0.0\n control_angular_vel = 0.0\n\n try:\n print(msg)\n while(1):\n key = ord(get())\n print(key)\n if key == 65 :\n \tif target_linear_vel < 0 and target_linear_vel >= -0.4:\n \t\ttarget_linear_vel=0\n \t\tstatus = status + 1\n \t\tprint(vels(target_linear_vel,target_angular_vel)) \n \telif target_linear_vel >= 0 and target_linear_vel < 0.4:\n \t\ttarget_linear_vel = 0.4\n \t\tstatus = status + 1\n \t\tprint(vels(target_linear_vel,target_angular_vel)) \n \telse:\n \t\ttarget_linear_vel = checkLinearLimitVelocity(target_linear_vel + LIN_VEL_STEP_SIZE)\n \t\tstatus = status + 1\n \t\tprint(vels(target_linear_vel,target_angular_vel))\n elif key == 66 :\n \tif target_linear_vel > 0 and target_linear_vel <= 0.4:\n \t\ttarget_linear_vel = 0\n \t\tstatus = status + 1\n \t\tprint(vels(target_linear_vel,target_angular_vel)) \n \telif target_linear_vel <= 0 and target_linear_vel > -0.4:\n \t\ttarget_linear_vel = -0.4\n \t\tstatus = status + 1\n \t\tprint(vels(target_linear_vel,target_angular_vel)) \n \telse:\n \t\ttarget_linear_vel = checkLinearLimitVelocity(target_linear_vel - LIN_VEL_STEP_SIZE)\n \t\tstatus = status + 1\n \t\tprint(vels(target_linear_vel,target_angular_vel))\n elif key == 67 :\n \tif target_angular_vel < 0 and target_angular_vel >= -0.4:\n \t\ttarget_angular_vel = 0\n \t\tstatus = status + 1\n \t\tprint(vels(target_linear_vel,target_angular_vel)) \n \telif target_angular_vel >= 0 and target_angular_vel < 0.4:\n \t\ttarget_angular_vel = 0.4\n \t\tstatus = status + 1\n \t\tprint(vels(target_linear_vel,target_angular_vel)) \n \telse:\n \t\ttarget_angular_vel = checkAngularLimitVelocity(target_angular_vel + ANG_VEL_STEP_SIZE)\n \t\tstatus = status + 1\n \t\tprint(vels(target_linear_vel,target_angular_vel))\n elif key == 68 :\n \tif target_angular_vel > 0 and target_angular_vel <= 0.4:\n \t\ttarget_angular_vel = 0\n \t\tstatus = status + 1\n \t\tprint(vels(target_linear_vel,target_angular_vel)) \n \telif target_angular_vel <= 0 and target_angular_vel > -0.4:\n \t\ttarget_angular_vel = -0.4\n \t\tstatus = status + 1\n \t\tprint(vels(target_linear_vel,target_angular_vel)) \n \telse:\n \t\ttarget_angular_vel = checkAngularLimitVelocity(target_angular_vel - ANG_VEL_STEP_SIZE)\n \t\tstatus = status + 1\n \t\tprint(vels(target_linear_vel,target_angular_vel))\n elif key == 13 or key ==32:\n \ttarget_linear_vel = 0.0\n \tcontrol_linear_vel = 0.0\n \ttarget_angular_vel = 0.0\n \tcontrol_angular_vel = 0.0\n \tprint(vels(target_linear_vel, target_angular_vel))\n else:\n \tif (key == 101 or key == 3):\n \t\tbreak\n \tif status == 20 :\n \t\tprint(msg)\n \t\tstatus = 0\n\n twist = SpeedCommand()\n\n\n #cinematica de robot diferencial\n Vr = target_linear_vel + 0.181*target_angular_vel\n Vl = target_linear_vel - 0.181*target_angular_vel \n\n \n #velocidad en QPPS\n Vr_ticks = -int(Vr/2*100) # ticks/meter ##Revisar##\n Vl_ticks = int(Vl/2*100)\n\n\n\n twist.m1_qpps =Vr_ticks\n\n \n twist.m2_qpps= Vl_ticks\n\t twist.max_secs=10000\n\n pub.publish(twist)\n except:\n print(e)\n\n finally:\n twist = SpeedCommand()\n twist.m1_qpps =0\n twist.m2_qpps= 0\n\n pub.publish(twist)\n\n if os.name != 'nt':\n termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)\n" }, { "alpha_fraction": 0.5144129991531372, "alphanum_fraction": 0.5387840867042542, "avg_line_length": 25.685314178466797, "blob_id": "8de89b60f39a8c2b76928b8ab7d92db43d22507a", "content_id": "a3dc8084190e8e28bbe488997fd939e23da82167", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3816, "license_type": "no_license", "max_line_length": 144, "num_lines": 143, "path": "/capulus/src/state_publisher.cpp", "repo_name": "alejoxbg/Capulus", "src_encoding": "UTF-8", "text": "#include <string>\n#include <ros/ros.h>\n#include <sensor_msgs/JointState.h>\n#include <tf/transform_broadcaster.h>\n#include <stdlib.h>\n#include <termios.h>\n#include <stdio.h>\n#include <unistd.h>\n\nchar getch()\n{\n fd_set set;\n struct timeval timeout;\n int rv;\n char buff = 0;\n int len = 1;\n int filedesc = 0;\n FD_ZERO(&set);\n FD_SET(filedesc, &set);\n\n timeout.tv_sec = 0;\n timeout.tv_usec = 1000;\n\n rv = select(filedesc + 1, &set, NULL, NULL, &timeout);\n\n struct termios old = {0};\n if (tcgetattr(filedesc, &old) < 0)\n ROS_ERROR(\"tcsetattr()\");\n old.c_lflag &= ~ICANON;\n old.c_lflag &= ~ECHO;\n old.c_cc[VMIN] = 1;\n old.c_cc[VTIME] = 0;\n if (tcsetattr(filedesc, TCSANOW, &old) < 0)\n ROS_ERROR(\"tcsetattr ICANON\");\n\n if(rv == -1)\n ROS_ERROR(\"select\");\n else if(rv == 0)\n ROS_INFO(\"no_key_pressed\");\n else\n read(filedesc, &buff, len );\n\n old.c_lflag |= ICANON;\n old.c_lflag |= ECHO;\n if (tcsetattr(filedesc, TCSADRAIN, &old) < 0)\n ROS_ERROR (\"tcsetattr ~ICANON\");\n return (buff);\n}\n\nint main(int argc, char** argv) {\n ros::init(argc, argv, \"state_publisher\");\n ros::NodeHandle n;\n ros::Publisher joint_pub = n.advertise<sensor_msgs::JointState>(\"joint_states\", 1);\n tf::TransformBroadcaster broadcaster;\n ros::Rate loop_rate(30);\n\n const double degree = M_PI/180;\n\n // robot state\n double base_wheels_inc= 0.1; \n double base_wheels= 6.2831; \n char c;\n double posx=0, posy=0;\n double incx= 0 ,incy=0;\n\n geometry_msgs::TransformStamped odom_trans;\n sensor_msgs::JointState joint_state;\n odom_trans.header.frame_id = \"odom\";\n odom_trans.child_frame_id = \"base_link\";\n\n while (ros::ok()) {\n //update joint_state\n joint_state.header.stamp = ros::Time::now();\n joint_state.name.resize(4);\n joint_state.position.resize(4);\n\tjoint_state.name[0] =\"base_to_wheel1\";\n joint_state.position[0] = base_wheels;\n\tjoint_state.name[1] =\"base_to_wheel2\";\n joint_state.position[1] = base_wheels;\n\tjoint_state.name[2] =\"base_to_wheel3\";\n joint_state.position[2] = base_wheels;\n\tjoint_state.name[3] =\"base_to_wheel4\";\n joint_state.position[3] = base_wheels;\n\n\n c=getch();\n switch(c)\n {\n case 'w':if(incx>0.02){}else{incx+=0.01;};\n break;\n case'd':if(incy>0.02){}else{incy+=0.01;};\n break;\n case 'a':if(incy<-0.02){}else{incy-=0.01;};\n break;\n case's': if(incx<-0.02){}else{incx-=0.01;};\n break;\n default:;\n }\n \n if (c == '\\x03')\n {\n printf(\"\\n\\n . .\\n . |\\\\-^-/| . \\n /| } O.=.O { |\\\\\\n\\n CH3EERS\\n\\n\");\n break;\n }\n\n // update transform\n // (moving in a circle with radius)\n odom_trans.header.stamp = ros::Time::now();\n odom_trans.transform.translation.x = posx;\n odom_trans.transform.translation.y = posy;\n odom_trans.transform.translation.z = 0.0;\n odom_trans.transform.rotation = tf::createQuaternionMsgFromYaw(0);\n\n //send the joint state and transform\n joint_pub.publish(joint_state);\n broadcaster.sendTransform(odom_trans);\n\n\n\t// Create new robot state\n \n if(incx>0){\n base_wheels -= base_wheels_inc;\n if (base_wheels<0) base_wheels = 6.2831;\n\t\t\n\t\t }\n if(incx<0){\n base_wheels += base_wheels_inc;\n if (base_wheels<0) base_wheels = 6.2831;\n\n }\n\n c='q';\n posx+=incx;\n posy+=incy;\n\n\n // This will adjust as needed per iteration\n loop_rate.sleep();\n }\n\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6236025094985962, "alphanum_fraction": 0.6534161567687988, "avg_line_length": 21.36111068725586, "blob_id": "b8678feb15708c2ab4b143edbc1c0318aa8fcddd", "content_id": "3e77dd89f5a3918551e34cb37acadc798d12b29a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1610, "license_type": "no_license", "max_line_length": 68, "num_lines": 72, "path": "/Capulus_webots/controllers/teleop/teleop.py", "repo_name": "alejoxbg/Capulus", "src_encoding": "UTF-8", "text": "\"\"\"control_4_llantas controller.\"\"\"\n\n# You may need to import some classes of the controller module. Ex:\n# from controller import Robot, Motor, DistanceSensor\nfrom controller import Robot, Keyboard\n\n# create the Robot instance.\nrobot = Robot()\nkeyboard=Keyboard()\n# get the time step of the current world.\ntimestep = 64\nkeyboard.enable(timestep)\n\nwheels=[]\nwheelsNames=['wheel1','wheel2','wheel3','wheel4']\n\nfor i in range(4):\n wheels.append(robot.getDevice(wheelsNames[i]))\n wheels[i].setPosition(float('inf'))\n wheels[i].setVelocity(0.0)\n\n\n\nds=[]\ndsNames=['ds_left','ds_right']\n\nfor i in range(2):\n ds.append(robot.getDevice(dsNames[i]))\n ds[i].enable(timestep)\n\n\navoidObstacleCounter=0\n\n\n# Main loop:\n# - perform simulation steps until Webots is stopping the controller\nwhile robot.step(timestep) != -1:\n leftSpeed=0.0\n rightSpeed=0.0\n \n key=keyboard.getKey()\n print(key)\n if key ==87:\n leftSpeed=1.0\n rightSpeed=1.0\n elif key == 83:\n leftSpeed=-1.0\n rightSpeed=-1.0\n elif key==65:\n leftSpeed=-1.0\n rightSpeed=1.0\n elif key == 68:\n leftSpeed=1.0\n rightSpeed=-1.0\n\n \n \n wheels[0].setVelocity(leftSpeed)\n wheels[1].setVelocity(rightSpeed)\n wheels[2].setVelocity(leftSpeed)\n wheels[3].setVelocity(rightSpeed)\n # Read the sensors:\n # Enter here functions to read sensor data, like:\n # val = ds.getValue()\n\n # Process sensor data here.\n\n # Enter here functions to send actuator commands, like:\n # motor.setPosition(10.0)\n pass\n\n# Enter here exit cleanup code.\n" }, { "alpha_fraction": 0.7878788113594055, "alphanum_fraction": 0.7878788113594055, "avg_line_length": 15.5, "blob_id": "5cb9299655a2e228d8efbfcaa0a9cc3df9ddaff4", "content_id": "7449310f4127f833a943697656992f64f0da26c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 33, "license_type": "no_license", "max_line_length": 22, "num_lines": 2, "path": "/capulus/README.md", "repo_name": "alejoxbg/Capulus", "src_encoding": "UTF-8", "text": "# Capulus\nRobot for coffee farms\n" } ]
7
Rhumbix/django-request-logging
https://github.com/Rhumbix/django-request-logging
e781e1205e879d232ac815e7f554b0d68acdc667
afdfe5556c7f4df707105100eda24f92f9f1f4da
90c19e9688ae13bd308036ca6ebf6729751072bd
refs/heads/master
2023-03-09T17:17:18.175038
2022-02-23T04:51:51
2022-02-23T04:51:51
40,688,858
289
91
MIT
2015-08-14T01:05:35
2022-02-18T12:29:09
2022-02-23T04:48:28
Python
[ { "alpha_fraction": 0.6167464256286621, "alphanum_fraction": 0.6234449744224548, "avg_line_length": 43.23280334472656, "blob_id": "ab760ccc02018fdfc5f7b55f7dbba132ed7b6d8b", "content_id": "3eb04d8a4a1bd4f173255a44e398b60caf9dd887", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16720, "license_type": "permissive", "max_line_length": 126, "num_lines": 378, "path": "/request_logging/middleware.py", "repo_name": "Rhumbix/django-request-logging", "src_encoding": "UTF-8", "text": "import logging\nimport re\n\nfrom django import VERSION as django_version\nfrom django.conf import settings\n\ntry:\n # Django >= 1.10\n from django.urls import resolve, Resolver404\nexcept ImportError:\n # Django < 1.10\n from django.core.urlresolvers import resolve, Resolver404\nfrom django.utils.termcolors import colorize\n\nDEFAULT_LOG_LEVEL = logging.DEBUG\nDEFAULT_HTTP_4XX_LOG_LEVEL = logging.ERROR\nDEFAULT_COLORIZE = True\nDEFAULT_MAX_BODY_LENGTH = 50000 # log no more than 3k bytes of content\nIS_DJANGO_VERSION_GTE_3_2_0 = django_version >= (3, 2, 0, \"final\", 0)\nDEFAULT_SENSITIVE_HEADERS = [\n \"Authorization\", \"Proxy-Authorization\"\n] if IS_DJANGO_VERSION_GTE_3_2_0 else [\n \"HTTP_AUTHORIZATION\", \"HTTP_PROXY_AUTHORIZATION\"\n]\nSETTING_NAMES = {\n \"log_level\": \"REQUEST_LOGGING_DATA_LOG_LEVEL\",\n \"http_4xx_log_level\": \"REQUEST_LOGGING_HTTP_4XX_LOG_LEVEL\",\n \"legacy_colorize\": \"REQUEST_LOGGING_DISABLE_COLORIZE\",\n \"colorize\": \"REQUEST_LOGGING_ENABLE_COLORIZE\",\n \"max_body_length\": \"REQUEST_LOGGING_MAX_BODY_LENGTH\",\n \"sensitive_headers\": \"REQUEST_LOGGING_SENSITIVE_HEADERS\",\n}\nBINARY_REGEX = re.compile(r\"(.+Content-Type:.*?)(\\S+)/(\\S+)(?:\\r\\n)*(.+)\", re.S | re.I)\nBINARY_TYPES = (\"image\", \"application\")\nNO_LOGGING_ATTR = \"no_logging\"\nNO_LOGGING_MSG_ATTR = \"no_logging_msg\"\nNO_LOGGING_MSG = \"No logging for this endpoint\"\nNO_LOGGING_DEFAULT_VALUE = getattr(\n settings,\n \"DJANGO_REQUEST_LOGGING_NO_LOGGING_DEFAULT_VALUE\",\n False\n)\nLOG_HEADERS_ATTR = \"log_headers\"\nLOG_HEADERS_DEFAULT_VALUE = getattr(\n settings,\n \"DJANGO_REQUEST_LOGGING_LOG_HEADERS_DEFAULT_VALUE\",\n True\n)\nNO_HEADER_LOGGING_MSG_ATTR = \"no_header_logging_msg\"\nNO_HEADER_LOGGING_MSG = \"No header logging for this endpoint\"\nLOG_BODY_ATTR = \"log_body\"\nLOG_BODY_DEFAULT_VALUE = getattr(\n settings,\n \"DJANGO_REQUEST_LOGGING_LOG_BODY_DEFAULT_VALUE\",\n True\n)\nNO_BODY_LOGGING_MSG_ATTR = \"no_body_logging_msg\"\nNO_BODY_LOGGING_MSG = \"No body logging for this endpoint\"\nLOG_RESPONSE_ATTR = \"response_logging\"\nLOG_RESPONSE_DEFAULT_VALUE = getattr(\n settings,\n \"DJANGO_REQUEST_LOGGING_LOG_RESPONSE_DEFAULT_VALUE\",\n True\n)\nNO_RESPONSE_LOGGING_MSG_ATTR = \"no_response_logging_msg\"\nNO_RESPONSE_LOGGING_MSG = \"No response logging for this endpoint\"\n\nLOGGER_NAME = getattr(\n settings,\n \"DJANGO_REQUEST_LOGGING_LOGGER_NAME\",\n \"django.request\"\n)\nrequest_logger = logging.getLogger(LOGGER_NAME)\n\n\nclass Logger:\n def log(self, level, msg, logging_context):\n args = logging_context[\"args\"]\n kwargs = logging_context[\"kwargs\"]\n for line in re.split(r\"\\r?\\n\", str(msg)):\n request_logger.log(level, line, *args, **kwargs)\n\n def log_error(self, level, msg, logging_context):\n self.log(level, msg, logging_context)\n\n\nclass ColourLogger(Logger):\n def __init__(self, log_colour, log_error_colour):\n self.log_colour = log_colour\n self.log_error_colour = log_error_colour\n\n def log(self, level, msg, logging_context):\n colour = self.log_error_colour if level >= logging.ERROR else self.log_colour\n self._log(level, msg, colour, logging_context)\n\n def log_error(self, level, msg, logging_context):\n # Forces colour to be log_error_colour no matter what level is\n self._log(level, msg, self.log_error_colour, logging_context)\n\n def _log(self, level, msg, colour, logging_context):\n args = logging_context[\"args\"]\n kwargs = logging_context[\"kwargs\"]\n for line in re.split(r\"\\r?\\n\", str(msg)):\n line = colorize(line, fg=colour)\n request_logger.log(level, line, *args, **kwargs)\n\n\nclass LoggingMiddleware(object):\n def __init__(self, get_response=None):\n # ensure that all the member references of LoggingMiddleware are read-only after construction\n # no other methods/properties invocations mutate these references so they can be safely read from any thread\n # https://stackoverflow.com/questions/6214509/is-django-middleware-thread-safe\n # https://stackoverflow.com/questions/10763641/is-this-django-middleware-thread-safe\n # https://blog.roseman.org.uk/2010/02/01/middleware-post-processing-django-gotcha/\n self.get_response = get_response\n\n self.log_level = getattr(settings, SETTING_NAMES[\"log_level\"], DEFAULT_LOG_LEVEL)\n self.http_4xx_log_level = getattr(settings, SETTING_NAMES[\"http_4xx_log_level\"], DEFAULT_HTTP_4XX_LOG_LEVEL)\n self.sensitive_headers = getattr(settings, SETTING_NAMES[\"sensitive_headers\"], DEFAULT_SENSITIVE_HEADERS)\n if not isinstance(self.sensitive_headers, list):\n raise ValueError(\n \"{} should be list. {} is not list.\".format(SETTING_NAMES[\"sensitive_headers\"], self.sensitive_headers)\n )\n\n for log_attr in (\"log_level\", \"http_4xx_log_level\"):\n level = getattr(self, log_attr)\n if level not in [\n logging.NOTSET,\n logging.DEBUG,\n logging.INFO,\n logging.WARNING,\n logging.ERROR,\n logging.CRITICAL,\n ]:\n raise ValueError(\"Unknown log level({}) in setting({})\".format(level, SETTING_NAMES[log_attr]))\n\n # TODO: remove deprecated legacy settings\n enable_colorize = getattr(settings, SETTING_NAMES[\"legacy_colorize\"], None)\n if enable_colorize is None:\n enable_colorize = getattr(settings, SETTING_NAMES[\"colorize\"], DEFAULT_COLORIZE)\n\n if not isinstance(enable_colorize, bool):\n raise ValueError(\n \"{} should be boolean. {} is not boolean.\".format(SETTING_NAMES[\"colorize\"], enable_colorize)\n )\n\n self.max_body_length = getattr(settings, SETTING_NAMES[\"max_body_length\"], DEFAULT_MAX_BODY_LENGTH)\n if not isinstance(self.max_body_length, int):\n raise ValueError(\n \"{} should be int. {} is not int.\".format(SETTING_NAMES[\"max_body_length\"], self.max_body_length)\n )\n\n self.logger = ColourLogger(\"cyan\", \"magenta\") if enable_colorize else Logger()\n\n def __call__(self, request):\n # cache in a local reference (instead of a member reference) and then pass in as argument\n # in order to avoid other threads overwriting the original self.cached_request_body reference,\n # is this done to preserve the original value in case it is mutated during the get_response invocation?\n cached_request_body = request.body\n response = self.get_response(request)\n self.process_request(request, response, cached_request_body)\n self.process_response(request, response)\n return response\n\n def process_request(self, request, response, cached_request_body):\n skip_logging, because = self._should_log_route(request)\n if skip_logging:\n if because is not None:\n return self._skip_logging_request(request, because)\n else:\n return self._log_request(request, response, cached_request_body)\n\n def _get_func(self, request):\n # request.urlconf may be set by middleware or application level code.\n # Use this urlconf if present or default to None.\n # https://docs.djangoproject.com/en/2.1/topics/http/urls/#how-django-processes-a-request\n # https://docs.djangoproject.com/en/2.1/ref/request-response/#attributes-set-by-middleware\n urlconf = getattr(request, \"urlconf\", None)\n\n try:\n route_match = resolve(request.path, urlconf=urlconf)\n except Resolver404:\n return False, None\n\n method = request.method.lower()\n view = route_match.func\n func = view\n # This is for \"django rest framework\"\n if hasattr(view, \"cls\"):\n if hasattr(view, \"actions\"):\n actions = view.actions\n method_name = actions.get(method)\n if method_name:\n func = getattr(view.cls, view.actions[method], None)\n else:\n func = getattr(view.cls, method, None)\n elif hasattr(view, \"view_class\"):\n # This is for django class-based views\n func = getattr(view.view_class, method, None)\n\n return func\n\n def _should_log_route(self, request):\n func = self._get_func(request)\n no_logging = getattr(func, NO_LOGGING_ATTR, NO_LOGGING_DEFAULT_VALUE)\n no_logging_msg = getattr(func, NO_LOGGING_MSG_ATTR, None)\n return no_logging, no_logging_msg\n\n def _should_log_headers(self, request):\n func = self._get_func(request)\n header_logging = getattr(func, LOG_HEADERS_ATTR, LOG_HEADERS_DEFAULT_VALUE)\n no_header_logging_msg = getattr(func, NO_HEADER_LOGGING_MSG_ATTR, None)\n return header_logging, no_header_logging_msg\n\n def _should_log_body(self, request):\n func = self._get_func(request)\n body_logging = getattr(func, LOG_BODY_ATTR, LOG_BODY_DEFAULT_VALUE)\n no_body_logging_msg = getattr(func, NO_BODY_LOGGING_MSG_ATTR, None)\n return body_logging, no_body_logging_msg\n\n def _should_log_response(self, request):\n func = self._get_func(request)\n response_logging = getattr(func, LOG_RESPONSE_ATTR, LOG_RESPONSE_DEFAULT_VALUE)\n no_response_logging_msg = getattr(func, NO_RESPONSE_LOGGING_MSG_ATTR, None)\n return response_logging, no_response_logging_msg\n\n def _skip_logging_request(self, request, reason):\n method_path = \"{} {}\".format(request.method, request.get_full_path())\n no_log_context = {\n \"args\": (),\n \"kwargs\": {\"extra\": {\"no_logging\": reason}},\n }\n self.logger.log(logging.INFO, method_path + \" (not logged because '\" + reason + \"')\", no_log_context)\n\n def _log_request(self, request, response, cached_request_body):\n method_path = \"{} {}\".format(request.method, request.get_full_path())\n logging_context = self._get_logging_context(request, None)\n\n # Determine log level depending on response status\n log_level = self.log_level\n if response is not None:\n if response.status_code in range(400, 500):\n log_level = self.http_4xx_log_level\n elif response.status_code in range(500, 600):\n log_level = logging.ERROR\n\n self.logger.log(logging.INFO, method_path, logging_context)\n self._log_request_headers(request, logging_context, log_level)\n self._log_request_body(request, logging_context, log_level, cached_request_body)\n\n def _log_request_headers(self, request, logging_context, log_level):\n log_headers, because = self._should_log_headers(request)\n if not log_headers:\n if because is not None:\n self.logger.log_error(\n logging.INFO, \"no headers logged\", {\"args\": {}, \"kwargs\": {\"extra\": {\"no_header_logging\": because}}}\n )\n return None\n\n if IS_DJANGO_VERSION_GTE_3_2_0:\n headers = {k: v if k not in self.sensitive_headers else \"*****\" for k, v in request.headers.items()}\n else:\n headers = {\n k: v if k not in self.sensitive_headers else \"*****\"\n for k, v in request.META.items()\n if k.startswith(\"HTTP_\")\n }\n\n if headers:\n self.logger.log(log_level, headers, logging_context)\n\n def _log_request_body(self, request, logging_context, log_level, cached_request_body):\n log_body, because = self._should_log_body(request)\n if not log_body:\n if because is not None:\n self.logger.log_error(\n logging.INFO, \"no body logged\", {\"args\": {}, \"kwargs\": {\"extra\": {\"log_body\": because}}}\n )\n return None\n\n if cached_request_body is not None:\n content_type = request.META.get(\"CONTENT_TYPE\", \"\")\n is_multipart = content_type.startswith(\"multipart/form-data\")\n if is_multipart:\n multipart_boundary = \"--\" + content_type[30:] # First 30 characters are \"multipart/form-data; boundary=\"\n self._log_multipart(self._chunked_to_max(cached_request_body), logging_context, log_level, multipart_boundary)\n else:\n self.logger.log(log_level, self._chunked_to_max(cached_request_body), logging_context)\n\n def process_response(self, request, response):\n resp_log = \"{} {} - {}\".format(request.method, request.get_full_path(), response.status_code)\n skip_logging, because = self._should_log_route(request)\n if skip_logging:\n if because is not None:\n self.logger.log_error(\n logging.INFO, resp_log, {\"args\": {}, \"kwargs\": {\"extra\": {\"no_logging\": because}}}\n )\n return response\n log_response, because = self._should_log_response(request)\n if not log_response:\n if because is not None:\n self.logger.log_error(\n logging.INFO, resp_log, {\"args\": {}, \"kwargs\": {\"extra\": {\"log_response\": because}}}\n )\n return response\n logging_context = self._get_logging_context(request, response)\n\n if response.status_code in range(400, 500):\n if self.http_4xx_log_level == DEFAULT_HTTP_4XX_LOG_LEVEL:\n # default, log as per 5xx\n self.logger.log_error(logging.INFO, resp_log, logging_context)\n self._log_resp(logging.ERROR, response, logging_context)\n else:\n self.logger.log(self.http_4xx_log_level, resp_log, logging_context)\n self._log_resp(self.log_level, response, logging_context)\n elif response.status_code in range(500, 600):\n self.logger.log_error(logging.INFO, resp_log, logging_context)\n self._log_resp(logging.ERROR, response, logging_context)\n else:\n self.logger.log(logging.INFO, resp_log, logging_context)\n self._log_resp(self.log_level, response, logging_context)\n\n return response\n\n def _get_logging_context(self, request, response):\n \"\"\"\n Returns a map with args and kwargs to provide additional context to calls to logging.log().\n This allows the logging context to be created per process request/response call.\n \"\"\"\n return {\n \"args\": (),\n \"kwargs\": {\"extra\": {\"request\": request, \"response\": response}},\n }\n\n def _log_multipart(self, body, logging_context, log_level, multipart_boundary):\n \"\"\"\n Splits multipart body into parts separated by \"boundary\", then matches each part to BINARY_REGEX\n which searches for existence of \"Content-Type\" and capture of what type is this part.\n If it is an image or an application replace that content with \"(binary data)\" string.\n This function will log \"(multipart/form)\" if body can't be decoded by utf-8.\n \"\"\"\n try:\n body_str = body.decode()\n except UnicodeDecodeError:\n self.logger.log(log_level, \"(multipart/form)\", logging_context)\n return\n\n parts = body_str.split(multipart_boundary)\n last = len(parts) - 1\n for i, part in enumerate(parts):\n if \"Content-Type:\" in part:\n match = BINARY_REGEX.search(part)\n if match and match.group(2) in BINARY_TYPES and not match.group(4) in (\"\", \"\\r\\n\"):\n part = match.expand(r\"\\1\\2/\\3\\r\\n\\r\\n(binary data)\\r\\n\")\n\n if i != last:\n part = part + multipart_boundary\n\n self.logger.log(log_level, part, logging_context)\n\n def _log_resp(self, level, response, logging_context):\n if re.match(\"^application/json\", response.get(\"Content-Type\", \"\"), re.I):\n if IS_DJANGO_VERSION_GTE_3_2_0:\n response_headers = response.headers\n else:\n response_headers = response._headers\n self.logger.log(level, response_headers, logging_context)\n if response.streaming:\n # There's a chance that if it's streaming it's because large and it might hit\n # the max_body_length very often. Not to mention that StreamingHttpResponse\n # documentation advises to iterate only once on the content.\n # So the idea here is to just _not_ log it.\n self.logger.log(level, \"(data_stream)\", logging_context)\n else:\n self.logger.log(level, self._chunked_to_max(response.content), logging_context)\n\n def _chunked_to_max(self, msg):\n return msg[0:self.max_body_length]\n" }, { "alpha_fraction": 0.6260504126548767, "alphanum_fraction": 0.6288515329360962, "avg_line_length": 25.44444465637207, "blob_id": "6100d785feef7841491ee729c0f2d9cd964dd5c3", "content_id": "635345346342d0c745811650245f9b0ae1a7e251", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1428, "license_type": "permissive", "max_line_length": 75, "num_lines": 54, "path": "/setup.py", "repo_name": "Rhumbix/django-request-logging", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport re\nimport shutil\nimport sys\nfrom io import open\n\nfrom setuptools import setup\n\n\ndef read(f):\n return open(f, \"r\", encoding=\"utf-8\").read()\n\n\ndef get_version(package):\n \"\"\"\n Return package version as listed in `__version__` in `init.py`.\n \"\"\"\n init_py = open(os.path.join(package, \"__init__.py\")).read()\n return re.search(\"__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py).group(1)\n\n\nversion = get_version(\"request_logging\")\n\n\nif sys.argv[-1] == \"publish\":\n if os.system(\"pip freeze | grep twine\"):\n print(\"twine not installed.\\nUse `pip install twine`.\\nExiting.\")\n sys.exit()\n os.system(\"python setup.py sdist bdist_wheel\")\n os.system(\"twine upload dist/*\")\n print(\"You probably want to also tag the version now:\")\n print(\" git tag -a %s -m 'version %s'\" % (version, version))\n print(\" git push --tags\")\n shutil.rmtree(\"dist\")\n shutil.rmtree(\"build\")\n sys.exit()\n\n\nsetup(\n name=\"django-request-logging\",\n version=version,\n description=\"Django middleware that logs http request body.\",\n long_description=read(\"README.md\"),\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/Rhumbix/django-request-logging.git\",\n author=\"Rhumbix\",\n author_email=\"dev@rhumbix.com\",\n license=\"MIT\",\n packages=[\"request_logging\"],\n install_requires=[\"Django\"],\n zip_safe=False,\n)\n" }, { "alpha_fraction": 0.6257997751235962, "alphanum_fraction": 0.6393241882324219, "avg_line_length": 42.285240173339844, "blob_id": "9c8b7398db98eecb6e6f54d14bf3b83e6671e768", "content_id": "2d9eb44ea4c5923ea354bf653de9e95f6fb81908", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26101, "license_type": "permissive", "max_line_length": 114, "num_lines": 603, "path": "/tests.py", "repo_name": "Rhumbix/django-request-logging", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\nimport io\nimport logging\nimport mock\nimport re\nimport unittest\n\nfrom django.conf import settings\nfrom django.test import RequestFactory, override_settings\nfrom django.http import HttpResponse, StreamingHttpResponse\n\nimport request_logging\nfrom request_logging.middleware import (\n LoggingMiddleware,\n DEFAULT_LOG_LEVEL,\n DEFAULT_COLORIZE,\n DEFAULT_MAX_BODY_LENGTH,\n NO_LOGGING_MSG,\n DEFAULT_HTTP_4XX_LOG_LEVEL,\n IS_DJANGO_VERSION_GTE_3_2_0,\n)\n\nsettings.configure()\n\n\nclass BaseLogTestCase(unittest.TestCase):\n def _assert_logged(self, mock_log, expected_entry):\n calls = mock_log.log.call_args_list\n text = \"\".join([call[0][1] for call in calls])\n self.assertIn(expected_entry, text)\n\n def _assert_logged_with_key_value(self, mock_log, expected_key, expected_value):\n calls = mock_log.log.call_args_list\n text = \"\".join([call[0][1] for call in calls])\n self.assertIn(expected_key, text)\n self.assertEqual(expected_value, text.split(expected_key)[1][4 : len(expected_value) + 4])\n\n def _assert_logged_with_level(self, mock_log, level):\n calls = mock_log.log.call_args_list\n called_levels = set(call[0][0] for call in calls)\n self.assertIn(level, called_levels, \"{} not in {}\".format(level, called_levels))\n\n def _asset_logged_with_additional_args_and_kwargs(self, mock_log, additional_args, kwargs):\n calls = mock_log.log.call_args_list\n for call_args, call_kwargs in calls:\n additional_call_args = call_args[2:]\n self.assertTrue(\n additional_args == additional_call_args,\n \"Expected {} to be {}\".format(additional_call_args, additional_args),\n )\n self.assertTrue(kwargs == call_kwargs, \"Expected {} to be {}\".format(call_kwargs, kwargs))\n\n def _assert_not_logged(self, mock_log, unexpected_entry):\n calls = mock_log.log.call_args_list\n text = \" \".join([call[0][1] for call in calls])\n self.assertNotIn(unexpected_entry, text)\n\n\n@mock.patch.object(request_logging.middleware, \"request_logger\")\nclass MissingRoutes(BaseLogTestCase):\n def setUp(self):\n self.factory = RequestFactory()\n\n def get_response(request):\n response = mock.MagicMock()\n response.status_code = 200\n response.get.return_value = \"application/json\"\n headers = {\"test_headers\": \"test_headers\"}\n if IS_DJANGO_VERSION_GTE_3_2_0:\n response.headers = headers\n else:\n response._headers = headers\n return response\n\n self.middleware = LoggingMiddleware(get_response)\n\n def test_no_exception_risen(self, mock_log):\n body = u\"some body\"\n request = self.factory.post(\"/a-missing-route-somewhere\", data={\"file\": body})\n self.middleware.__call__(request)\n self._assert_logged(mock_log, body)\n\n\n@mock.patch.object(request_logging.middleware, \"request_logger\")\nclass LogTestCase(BaseLogTestCase):\n def setUp(self):\n self.factory = RequestFactory()\n\n def get_response(request):\n response = mock.MagicMock()\n response.status_code = 200\n response.get.return_value = \"application/json\"\n headers = {\"test_headers\": \"test_headers\"}\n if IS_DJANGO_VERSION_GTE_3_2_0:\n response.headers = headers\n else:\n response._headers = headers\n return response\n\n self.middleware = LoggingMiddleware(get_response)\n\n def test_request_body_logged(self, mock_log):\n body = u\"some body\"\n request = self.factory.post(\"/somewhere\", data={\"file\": body})\n self.middleware.__call__(request)\n self._assert_logged(mock_log, body)\n\n def test_request_binary_logged(self, mock_log):\n body = u\"some body\"\n datafile = io.StringIO(body)\n request = self.factory.post(\"/somewhere\", data={\"file\": datafile})\n self.middleware.__call__(request)\n self._assert_logged(mock_log, \"(binary data)\")\n\n def test_request_jpeg_logged(self, mock_log):\n body = (\n b'--BoUnDaRyStRiNg\\r\\nContent-Disposition: form-data; name=\"file\"; filename=\"campaign_carousel_img.jp'\n b'g\"\\r\\nContent-Type: image/jpeg\\r\\n\\r\\n\\xff\\xd8\\xff\\xe1\\x00\\x18Exif\\x00\\x00II*\\x00\\x08\\x00\\x00\\x00'\n b\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xff\\xec\\x00\\x11Ducky\\x00\\x01\\x00\\x04\\x00\\x00\\x00d\\x00\\x00\\xff\\xe1\"\n b\"\\x03{http://ns.adobe.com/\"\n )\n datafile = io.BytesIO(body)\n request = self.factory.post(\"/somewhere\", data={\"file\": datafile})\n self.middleware.__call__(request)\n self._assert_logged(mock_log, \"(multipart/form)\")\n\n def test_request_headers_logged(self, mock_log):\n request = self.factory.post(\"/somewhere\", **{\"HTTP_USER_AGENT\": \"silly-human\"})\n self.middleware.process_request(request, None, request.body)\n if IS_DJANGO_VERSION_GTE_3_2_0:\n self._assert_logged(mock_log, \"User-Agent\")\n else:\n self._assert_logged(mock_log, \"HTTP_USER_AGENT\")\n\n def test_request_headers_sensitive_logged_default(self, mock_log):\n request = self.factory.post(\n \"/somewhere\", **{\"HTTP_AUTHORIZATION\": \"sensitive-token\", \"HTTP_PROXY_AUTHORIZATION\": \"proxy-token\"}\n )\n middleware = LoggingMiddleware()\n middleware.process_request(request, None, request.body)\n if IS_DJANGO_VERSION_GTE_3_2_0:\n self._assert_logged(mock_log, \"Authorization\")\n self._assert_logged_with_key_value(mock_log, \"Authorization\", \"*****\")\n else:\n self._assert_logged(mock_log, \"HTTP_AUTHORIZATION\")\n self._assert_logged_with_key_value(mock_log, \"HTTP_AUTHORIZATION\", \"*****\")\n if IS_DJANGO_VERSION_GTE_3_2_0:\n self._assert_logged(mock_log, \"Proxy-Authorization\")\n self._assert_logged_with_key_value(mock_log, \"Proxy-Authorization\", \"*****\")\n else:\n self._assert_logged(mock_log, \"HTTP_PROXY_AUTHORIZATION\")\n self._assert_logged_with_key_value(mock_log, \"HTTP_PROXY_AUTHORIZATION\", \"*****\")\n\n @override_settings(\n REQUEST_LOGGING_SENSITIVE_HEADERS=[\"Authorization\"]\n if IS_DJANGO_VERSION_GTE_3_2_0\n else [\"HTTP_AUTHORIZATION\"]\n )\n def test_request_headers_sensitive_logged(self, mock_log):\n request = self.factory.post(\n \"/somewhere\",\n **{\n \"HTTP_AUTHORIZATION\": \"sensitive-token\",\n \"HTTP_USER_AGENT\": \"silly-human\",\n \"HTTP_PROXY_AUTHORIZATION\": \"proxy-token\",\n }\n )\n middleware = LoggingMiddleware()\n middleware.process_request(request, None, request.body)\n if IS_DJANGO_VERSION_GTE_3_2_0:\n self._assert_logged(mock_log, \"Authorization\")\n self._assert_logged_with_key_value(mock_log, \"Authorization\", \"*****\")\n else:\n self._assert_logged(mock_log, \"HTTP_AUTHORIZATION\")\n self._assert_logged_with_key_value(mock_log, \"HTTP_AUTHORIZATION\", \"*****\")\n if IS_DJANGO_VERSION_GTE_3_2_0:\n self._assert_logged(mock_log, \"User-Agent\")\n self._assert_logged_with_key_value(mock_log, \"User-Agent\", \"silly-human\")\n else:\n self._assert_logged(mock_log, \"HTTP_USER_AGENT\")\n self._assert_logged_with_key_value(mock_log, \"HTTP_USER_AGENT\", \"silly-human\")\n if IS_DJANGO_VERSION_GTE_3_2_0:\n self._assert_logged(mock_log, \"Proxy-Authorization\")\n self._assert_logged_with_key_value(mock_log, \"Proxy-Authorization\", \"proxy-token\")\n else:\n self._assert_logged(mock_log, \"HTTP_PROXY_AUTHORIZATION\")\n self._assert_logged_with_key_value(mock_log, \"HTTP_PROXY_AUTHORIZATION\", \"proxy-token\")\n\n def test_response_headers_logged(self, mock_log):\n request = self.factory.post(\"/somewhere\")\n response = mock.MagicMock()\n response.get.return_value = \"application/json\"\n headers = {\"test_headers\": \"test_headers\"}\n if IS_DJANGO_VERSION_GTE_3_2_0:\n response.headers = headers\n else:\n response._headers = headers\n self.middleware.process_response(request, response)\n self._assert_logged(mock_log, \"test_headers\")\n\n def test_call_logged(self, mock_log):\n body = u\"some body\"\n request = self.factory.post(\"/somewhere\", data={\"file\": body}, **{\"HTTP_USER_AGENT\": \"silly-human\"})\n self.middleware.__call__(request)\n self._assert_logged(mock_log, body)\n self._assert_logged(mock_log, \"test_headers\")\n if IS_DJANGO_VERSION_GTE_3_2_0:\n self._assert_logged(mock_log, \"User-Agent\")\n else:\n self._assert_logged(mock_log, \"HTTP_USER_AGENT\")\n\n def test_call_binary_logged(self, mock_log):\n body = u\"some body\"\n datafile = io.StringIO(body)\n request = self.factory.post(\"/somewhere\", data={\"file\": datafile}, **{\"HTTP_USER_AGENT\": \"silly-human\"})\n self.middleware.__call__(request)\n self._assert_logged(mock_log, \"(binary data)\")\n self._assert_logged(mock_log, \"test_headers\")\n if IS_DJANGO_VERSION_GTE_3_2_0:\n self._assert_logged(mock_log, \"User-Agent\")\n else:\n self._assert_logged(mock_log, \"HTTP_USER_AGENT\")\n\n def test_call_jpeg_logged(self, mock_log):\n body = (\n b'--BoUnDaRyStRiNg\\r\\nContent-Disposition: form-data; name=\"file\"; filename=\"campaign_carousel_img.jp'\n b'g\"\\r\\nContent-Type: image/jpeg\\r\\n\\r\\n\\xff\\xd8\\xff\\xe1\\x00\\x18Exif\\x00\\x00II*\\x00\\x08\\x00\\x00\\x00'\n b\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xff\\xec\\x00\\x11Ducky\\x00\\x01\\x00\\x04\\x00\\x00\\x00d\\x00\\x00\\xff\\xe1\"\n b\"\\x03{http://ns.adobe.com/\"\n )\n datafile = io.BytesIO(body)\n request = self.factory.post(\"/somewhere\", data={\"file\": datafile}, **{\"HTTP_USER_AGENT\": \"silly-human\"})\n self.middleware.__call__(request)\n self._assert_logged(mock_log, \"(multipart/form)\")\n self._assert_logged(mock_log, \"test_headers\")\n if IS_DJANGO_VERSION_GTE_3_2_0:\n self._assert_logged(mock_log, \"User-Agent\")\n else:\n self._assert_logged(mock_log, \"HTTP_USER_AGENT\")\n\n def test_minimal_logging_when_streaming(self, mock_log):\n uri = \"/somewhere\"\n request = self.factory.get(uri)\n response = StreamingHttpResponse(status=200, streaming_content=b\"OK\", content_type=\"application/json\")\n self.middleware.process_response(request, response=response)\n self._assert_logged(mock_log, \"(data_stream)\")\n\n\n@mock.patch.object(request_logging.middleware, \"request_logger\")\nclass LoggingContextTestCase(BaseLogTestCase):\n def setUp(self):\n self.factory = RequestFactory()\n self.middleware = LoggingMiddleware()\n\n def test_request_logging_context(self, mock_log):\n request = self.factory.post(\"/somewhere\")\n self.middleware.process_request(request, None, request.body)\n self._asset_logged_with_additional_args_and_kwargs(\n mock_log, (), {\"extra\": {\"request\": request, \"response\": None}}\n )\n\n def test_response_logging_context(self, mock_log):\n request = self.factory.post(\"/somewhere\")\n response = mock.MagicMock()\n response.get.return_value = \"application/json\"\n headers = {\"test_headers\": \"test_headers\"}\n if IS_DJANGO_VERSION_GTE_3_2_0:\n response.headers = headers\n else:\n response._headers = headers\n self.middleware.process_response(request, response)\n self._asset_logged_with_additional_args_and_kwargs(\n mock_log, (), {\"extra\": {\"request\": request, \"response\": response}}\n )\n\n def test_get_logging_context_extensibility(self, mock_log):\n request = self.factory.post(\"/somewhere\")\n self.middleware._get_logging_context = lambda request, response: {\n \"args\": (1, True, \"Test\"),\n \"kwargs\": {\"extra\": {\"REQUEST\": request, \"middleware\": self.middleware}, \"exc_info\": True},\n }\n\n self.middleware.process_request(request, None, request.body)\n self._asset_logged_with_additional_args_and_kwargs(\n mock_log,\n (1, True, \"Test\"),\n {\"extra\": {\"REQUEST\": request, \"middleware\": self.middleware}, \"exc_info\": True},\n )\n\n\nclass BaseLogSettingsTestCase(BaseLogTestCase):\n def setUp(self):\n body = u\"some body\"\n datafile = io.StringIO(body)\n self.request = RequestFactory().post(\n \"/somewhere\", data={\"file\": datafile}, **{\"HTTP_USER_AGENT\": \"silly-human\"}\n )\n\n\n@mock.patch.object(request_logging.middleware, \"request_logger\")\nclass LogSettingsLogLevelTestCase(BaseLogSettingsTestCase):\n def test_logging_default_debug_level(self, mock_log):\n middleware = LoggingMiddleware()\n middleware.process_request(self.request, None, self.request.body)\n self._assert_logged_with_level(mock_log, DEFAULT_LOG_LEVEL)\n\n @override_settings(REQUEST_LOGGING_DATA_LOG_LEVEL=logging.INFO)\n def test_logging_with_customized_log_level(self, mock_log):\n middleware = LoggingMiddleware()\n middleware.process_request(self.request, None, self.request.body)\n self._assert_logged_with_level(mock_log, logging.INFO)\n\n @override_settings(REQUEST_LOGGING_DATA_LOG_LEVEL=None)\n def test_invalid_log_level(self, mock_log):\n with self.assertRaises(ValueError):\n LoggingMiddleware()\n\n\n@mock.patch.object(request_logging.middleware, \"request_logger\")\nclass LogSettingsHttp4xxAsErrorTestCase(BaseLogTestCase):\n def setUp(self):\n from django.urls import set_urlconf\n\n set_urlconf(\"test_urls\")\n self.factory = RequestFactory()\n self.request = self.factory.get(\"/not-a-valid-url\")\n\n response = mock.MagicMock()\n response.status_code = 404\n response.get.return_value = \"application/json\"\n headers = {\"test_headers\": \"test_headers\"}\n if IS_DJANGO_VERSION_GTE_3_2_0:\n response.headers = headers\n else:\n response._headers = headers\n\n self.response_404 = response\n\n def test_logging_default_http_4xx_error(self, mock_log):\n middleware = LoggingMiddleware()\n middleware.process_response(self.request, self.response_404)\n self.assertEqual(DEFAULT_HTTP_4XX_LOG_LEVEL, logging.ERROR)\n self._assert_logged_with_level(mock_log, DEFAULT_HTTP_4XX_LOG_LEVEL)\n\n def test_logging_http_4xx_level(self, mock_log):\n for level in (logging.INFO, logging.WARNING, logging.ERROR):\n mock_log.reset_mock()\n with override_settings(REQUEST_LOGGING_HTTP_4XX_LOG_LEVEL=level):\n middleware = LoggingMiddleware()\n middleware.process_response(self.request, self.response_404)\n self._assert_logged_with_level(mock_log, level)\n\n @override_settings(REQUEST_LOGGING_HTTP_4XX_LOG_LEVEL=None)\n def test_invalid_log_level(self, mock_log):\n with self.assertRaises(ValueError):\n LoggingMiddleware()\n\n\n@mock.patch.object(request_logging.middleware, \"request_logger\")\nclass LogSettingsColorizeTestCase(BaseLogSettingsTestCase):\n def test_default_colorize(self, mock_log):\n middleware = LoggingMiddleware()\n middleware.process_request(self.request, None, self.request.body)\n self.assertEqual(DEFAULT_COLORIZE, self._is_log_colorized(mock_log))\n\n @override_settings(REQUEST_LOGGING_ENABLE_COLORIZE=False)\n def test_disable_colorize(self, mock_log):\n middleware = LoggingMiddleware()\n middleware.process_request(self.request, None, self.request.body)\n self.assertFalse(self._is_log_colorized(mock_log))\n\n @override_settings(REQUEST_LOGGING_ENABLE_COLORIZE=\"Not a boolean\")\n def test_invalid_colorize(self, mock_log):\n with self.assertRaises(ValueError):\n LoggingMiddleware()\n\n @override_settings(REQUEST_LOGGING_DISABLE_COLORIZE=False)\n def test_legacy_settings(self, mock_log):\n middleware = LoggingMiddleware()\n middleware.process_request(self.request, None, self.request.body)\n self.assertFalse(self._is_log_colorized(mock_log))\n\n @override_settings(REQUEST_LOGGING_DISABLE_COLORIZE=False, REQUEST_LOGGING_ENABLE_COLORIZE=True)\n def test_legacy_settings_taking_precedence(self, mock_log):\n middleware = LoggingMiddleware()\n middleware.process_request(self.request, None, self.request.body)\n self.assertFalse(self._is_log_colorized(mock_log))\n\n def _is_log_colorized(self, mock_log):\n reset_code = \"\\x1b[0m\"\n calls = mock_log.log.call_args_list\n logs = \" \".join(call[0][1] for call in calls)\n return reset_code in logs\n\n\n@mock.patch.object(request_logging.middleware, \"request_logger\")\nclass LogSettingsMaxLengthTestCase(BaseLogTestCase):\n def setUp(self):\n from django.urls import set_urlconf\n\n set_urlconf(\"test_urls\")\n\n self.factory = RequestFactory()\n\n def get_response(request):\n response = mock.MagicMock()\n response.status_code = 200\n response.get.return_value = \"application/json\"\n headers = {\"test_headers\": \"test_headers\"}\n if IS_DJANGO_VERSION_GTE_3_2_0:\n response.headers = headers\n else:\n response._headers = headers\n return response\n\n self.get_response = get_response\n\n @override_settings(REQUEST_LOGGING_ENABLE_COLORIZE=False)\n def test_default_max_body_length(self, mock_log):\n body = DEFAULT_MAX_BODY_LENGTH * \"0\" + \"1\"\n request = self.factory.post(\"/somewhere\", data={\"file\": body})\n middleware = LoggingMiddleware(self.get_response)\n middleware.__call__(request)\n\n request_body_str = request.body if isinstance(request.body, str) else request.body.decode()\n self._assert_logged(mock_log, re.sub(r\"\\r?\\n\", \"\", request_body_str[:DEFAULT_MAX_BODY_LENGTH]))\n self._assert_not_logged(mock_log, body)\n\n @override_settings(REQUEST_LOGGING_MAX_BODY_LENGTH=150, REQUEST_LOGGING_ENABLE_COLORIZE=False)\n def test_customized_max_body_length(self, mock_log):\n body = 150 * \"0\" + \"1\"\n request = self.factory.post(\"/somewhere\", data={\"file\": body})\n middleware = LoggingMiddleware(self.get_response)\n middleware.__call__(request)\n\n request_body_str = request.body if isinstance(request.body, str) else request.body.decode()\n self._assert_logged(mock_log, re.sub(r\"\\r?\\n\", \"\", request_body_str[:150]))\n self._assert_not_logged(mock_log, body)\n\n @override_settings(REQUEST_LOGGING_MAX_BODY_LENGTH=\"Not an int\")\n def test_invalid_max_body_length(self, mock_log):\n with self.assertRaises(ValueError):\n LoggingMiddleware()\n\n\n@mock.patch.object(request_logging.middleware, \"request_logger\")\nclass DecoratorTestCase(BaseLogTestCase):\n def setUp(self):\n from django.urls import set_urlconf\n\n set_urlconf(\"test_urls\")\n self.factory = RequestFactory()\n self.middleware = LoggingMiddleware()\n\n def test_no_logging_decorator_class_view(self, mock_log):\n body = u\"some super secret body\"\n request = self.factory.post(\"/test_class\", data={\"file\": body})\n self.middleware.process_request(request, None, request.body)\n self._assert_not_logged(mock_log, body)\n self._assert_logged(mock_log, NO_LOGGING_MSG)\n\n def test_no_logging_decorator_func_view(self, mock_log):\n body = u\"some super secret body\"\n request = self.factory.post(\"/test_func\", data={\"file\": body})\n self.middleware.process_request(request, None, request.body)\n self._assert_not_logged(mock_log, body)\n self._assert_logged(mock_log, NO_LOGGING_MSG)\n\n def test_no_logging_decorator_custom_msg(self, mock_log):\n body = u\"some super secret body\"\n request = self.factory.post(\"/test_msg\", data={\"file\": body})\n self.middleware.process_request(request, None, request.body)\n self._assert_not_logged(mock_log, body)\n self._assert_not_logged(mock_log, NO_LOGGING_MSG)\n self._assert_logged(mock_log, \"Custom message\")\n\n def test_no_logging_decorator_silent(self, mock_log):\n body = u\"some super secret body\"\n request = self.factory.post(\"/dont_log_silent\", data={\"file\": body})\n self.middleware.process_request(request, None, request.body)\n self._assert_not_logged(mock_log, body)\n self._assert_not_logged(mock_log, NO_LOGGING_MSG)\n self._assert_not_logged(mock_log, \"not logged because\")\n\n def test_no_logging_empty_response_body(self, mock_log):\n body = u\"our work of art\"\n request = self.factory.post(\"/dont_log_empty_response_body\", data={\"file\": body})\n self.middleware.process_request(request, None, request.body)\n self._assert_not_logged(mock_log, body)\n self._assert_not_logged(mock_log, NO_LOGGING_MSG)\n self._assert_logged(mock_log, \"Empty response body\")\n\n def test_no_logging_alternate_urlconf(self, mock_log):\n body = u\"some super secret body\"\n request = self.factory.post(\"/test_route\", data={\"file\": body})\n request.urlconf = \"test_urls_alternate\"\n self.middleware.process_request(request, None, request.body)\n self._assert_not_logged(mock_log, body)\n self._assert_logged(mock_log, NO_LOGGING_MSG)\n\n def test_still_logs_verb(self, mock_log):\n body = u\"our work of art\"\n request = self.factory.post(\"/dont_log_empty_response_body\", data={\"file\": body})\n self.middleware.process_request(request, None, request.body)\n self._assert_logged(mock_log, \"POST\")\n\n def test_still_logs_path(self, mock_log):\n body = u\"our work of art\"\n uri = \"/dont_log_empty_response_body\"\n request = self.factory.post(uri, data={\"file\": body})\n self.middleware.process_request(request, None, request.body)\n self._assert_logged(mock_log, uri)\n\n\n@mock.patch.object(request_logging.middleware, \"request_logger\")\nclass DRFTestCase(BaseLogTestCase):\n def setUp(self):\n from django.urls import set_urlconf\n\n set_urlconf(\"test_urls\")\n self.factory = RequestFactory()\n self.middleware = LoggingMiddleware()\n\n def test_no_request_logging_is_honored(self, mock_log):\n uri = \"/widgets\"\n request = self.factory.get(uri)\n self.middleware.process_request(request, None, request.body)\n self._assert_logged(mock_log, \"DRF explicit annotation\")\n\n def test_no_response_logging_is_honored(self, mock_log):\n uri = \"/widgets\"\n request = self.factory.get(uri)\n mock_response = HttpResponse('{\"example\":\"response\"}', content_type=\"application/json\", status=422)\n self.middleware.process_response(request, response=mock_response)\n self._assert_not_logged(mock_log, '\"example\":\"response\"')\n self._assert_logged(mock_log, \"/widgets\")\n\n def test_non_existent_drf_route_logs(self, mock_log):\n uri = \"/widgets/1234\"\n request = self.factory.patch(uri, data={\"almost\": \"had you\"})\n self.middleware.process_request(request, None, request.body)\n self._assert_not_logged(mock_log, \"almost\")\n self._assert_not_logged(mock_log, \"had you\")\n\n\n@mock.patch.object(request_logging.middleware, \"request_logger\")\nclass LogRequestAtDifferentLevelsTestCase(BaseLogTestCase):\n def setUp(self):\n from django.urls import set_urlconf\n\n set_urlconf(\"test_urls\")\n self.factory = RequestFactory()\n\n self.request_200 = self.factory.get(\"/fine-thank-you\")\n self.response_200 = mock.MagicMock()\n self.response_200.status_code = 200\n self.response_200.get.return_value = \"application/json\"\n if IS_DJANGO_VERSION_GTE_3_2_0:\n self.response_200.headers = {\"test_headers\": \"test_headers\"}\n else:\n self.response_200._headers = {\"test_headers\": \"test_headers\"}\n\n self.request_404 = self.factory.get(\"/not-a-valid-url\")\n self.response_404 = mock.MagicMock()\n self.response_404.status_code = 404\n self.response_404.get.return_value = \"application/json\"\n if IS_DJANGO_VERSION_GTE_3_2_0:\n self.response_404.headers = {\"test_headers\": \"test_headers\"}\n else:\n self.response_404._headers = {\"test_headers\": \"test_headers\"}\n\n self.request_500 = self.factory.get(\"/bug\")\n self.response_500 = mock.MagicMock()\n self.response_500.status_code = 500\n self.response_500.get.return_value = \"application/json\"\n if IS_DJANGO_VERSION_GTE_3_2_0:\n self.response_500.headers = {\"test_headers\": \"test_headers\"}\n else:\n self.response_500._headers = {\"test_headers\": \"test_headers\"}\n\n def test_log_request_200(self, mock_log):\n mock_log.reset_mock()\n middleware = LoggingMiddleware()\n middleware.process_request(self.request_200, self.response_200, self.request_200.body)\n self._assert_logged_with_level(mock_log, DEFAULT_LOG_LEVEL)\n\n def test_log_request_404_as_4xx(self, mock_log):\n for level in (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR):\n mock_log.reset_mock()\n with override_settings(REQUEST_LOGGING_HTTP_4XX_LOG_LEVEL=level):\n middleware = LoggingMiddleware()\n middleware.process_request(self.request_404, self.response_404, self.request_404.body)\n self._assert_logged_with_level(mock_log, level)\n\n def test_log_request_500_as_error(self, mock_log):\n mock_log.reset_mock()\n middleware = LoggingMiddleware()\n middleware.process_request(self.request_500, self.response_500, self.request_500.body)\n self._assert_logged_with_level(mock_log, logging.ERROR)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" }, { "alpha_fraction": 0.6903932094573975, "alphanum_fraction": 0.7103036046028137, "avg_line_length": 27.295774459838867, "blob_id": "b36226a3fb3308918fa415c3ee7fc8f740e97cb6", "content_id": "fd492b3717b30d19342d26028ea6b1d0a9fdeea0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2009, "license_type": "permissive", "max_line_length": 93, "num_lines": 71, "path": "/test_urls.py", "repo_name": "Rhumbix/django-request-logging", "src_encoding": "UTF-8", "text": "import sys\n\nfrom django.conf.urls import url\nfrom django.http import HttpResponse\nfrom django.views import View\nfrom request_logging.decorators import no_logging\nfrom rest_framework import viewsets, routers\n\n# DRF 3.8.2 is used in python versions 3.4 and older, which needs special handling\nIS_DRF_382 = sys.version_info <= (3, 4)\n\n\ndef general_resource(request):\n return HttpResponse(status=200, body=\"Generic repsonse entity\")\n\n\nclass TestView(View):\n def get(self):\n return HttpResponse(status=200)\n\n @no_logging()\n def post(self, request):\n return HttpResponse(status=200)\n\n\n@no_logging()\ndef view_func(request):\n return HttpResponse(status=200, body=\"view_func with no logging\")\n\n\n@no_logging(\"Custom message\")\ndef view_msg(request):\n return HttpResponse(status=200, body=\"view_msg with no logging with a custom reason why\")\n\n\n@no_logging(silent=True)\ndef dont_log_silent(request):\n return HttpResponse(status=200, body=\"view_msg with silent flag set\")\n\n\n@no_logging(\"Empty response body\")\ndef dont_log_empty_response_body(request):\n return HttpResponse(status=201)\n\n\nclass UnannotatedDRF(viewsets.ModelViewSet):\n @no_logging(\"DRF explicit annotation\")\n def list(self, request):\n return HttpResponse(status=200, body=\"DRF Unannotated\")\n\n @no_logging(\"Takes excessive amounts of time to log\")\n def partial_update(self, request, *args, **kwargs):\n return HttpResponse(status=200, body=\"NO logging\")\n\n\nrouter = routers.SimpleRouter(trailing_slash=False)\nif IS_DRF_382:\n last_arguments = {\"base_name\": \"widgets\"}\nelse:\n last_arguments = {\"basename\": \"widgets\"}\n\nrouter.register(r\"widgets\", UnannotatedDRF, **last_arguments)\n\nurlpatterns = [\n url(r\"^somewhere$\", general_resource),\n url(r\"^test_class$\", TestView.as_view()),\n url(r\"^test_func$\", view_func),\n url(r\"^test_msg$\", view_msg),\n url(r\"^dont_log_empty_response_body$\", dont_log_empty_response_body),\n url(r\"^dont_log_silent$\", dont_log_silent),\n] + router.urls\n" }, { "alpha_fraction": 0.3181818127632141, "alphanum_fraction": 0.4545454680919647, "avg_line_length": 21, "blob_id": "8be3c1fad836f90bfcb77249ad2342741edcab5f", "content_id": "ab55bb1afcfc57eae20afec76d516c55dcd2be7a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22, "license_type": "permissive", "max_line_length": 21, "num_lines": 1, "path": "/request_logging/__init__.py", "repo_name": "Rhumbix/django-request-logging", "src_encoding": "UTF-8", "text": "__version__ = \"0.7.5\"\n" }, { "alpha_fraction": 0.7351115942001343, "alphanum_fraction": 0.7401294112205505, "avg_line_length": 47.858062744140625, "blob_id": "a7a47cce9728988f0c9d919cc2c4dd50e50e2e8a", "content_id": "96ce25779673d13101138796362f852984f50c16", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7573, "license_type": "permissive", "max_line_length": 243, "num_lines": 155, "path": "/README.md", "repo_name": "Rhumbix/django-request-logging", "src_encoding": "UTF-8", "text": "django-request-logging\n==========================\n\nPlug django-request-logging into your Django project and you will have intuitive and color coded request/response payload logging, for both web requests and API requests. Supports Django 1.8+.\n\n## Installing\n\n```bash\n$ pip install django-request-logging\n```\n\nThen add ```request_logging.middleware.LoggingMiddleware``` to your ```MIDDLEWARE```.\n\nFor example:\n\n```python\nMIDDLEWARE = (\n ...,\n 'request_logging.middleware.LoggingMiddleware',\n ...,\n)\n```\n\nAnd configure logging in your app:\n\n```python\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n },\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['console'],\n 'level': 'DEBUG', # change debug level as appropiate\n 'propagate': False,\n },\n },\n}\n```\n\n## Details\n\nMost of the times you don't have to care about these details. But in case you need to dig deep:\n\n* All logs are configured using logger name \"django.request\".\n* If HTTP status code is between 400 - 599, URIs are logged at ERROR level, otherwise they are logged at INFO level.\n* If HTTP status code is between 400 - 599, data are logged at ERROR level, otherwise they are logged at DEBUG level.\n\nSee `REQUEST_LOGGING_HTTP_4XX_LOG_LEVEL` setting to override this.\n\n\nA `no_logging` decorator is included for views with sensitive data. This decorator allows control over logging behaviour of single views via the following parameters:\n```\n* value\n * False: the view does NOT log any activity at all (overrules settings of log_headers, log_body, log_response and automatically sets them to False).\n * True: the view logs incoming requests (potentially log headers, body and response, depending on their specific settings)\n * None: NO_LOGGING_DEFAULT_VALUE is used (can be defined in settings file as DJANGO_REQUEST_LOGGING_NO_LOGGING_DEFAULT_VALUE)\n* msg\n * Reason for deactivation of logging gets logged instead of request itself (only if silent=True and value=False)\n * NO_LOGGING_MSG is used by default\n* log_headers\n * False: request headers will not get logged\n * True: request headers will get logged (if value is True)\n * None: LOG_HEADERS_DEFAULT_VALUE is used (can be defined in settings file as DJANGO_REQUEST_LOGGING_LOG_HEADERS_DEFAULT_VALUE)\n* no_header_logging_msg\n * Reason for deactivation of header logging gets logged instead of headers (only if silent=True and log_headers=False)\n * NO_HEADER_LOGGING_MSG is used by default\n* log_body\n * False: request body will not get logged\n * True: request headers will get logged (if value is True)\n * None: LOG_BODY_DEFAULT_VALUE is used (can be defined in settings file as DJANGO_REQUEST_LOGGING_LOG_BODY_DEFAULT_VALUE)\n* no_body_logging_msg\n * Reason for deactivation of body logging gets logged instead of body (only if silent=True and log_body=False)\n * NO_BODY_LOGGING_MSG is used by default\n* log_response\n * False: response will not get logged\n * True: response will get logged (if value is True)\n * None: LOG_RESPONSE_DEFAULT_VALUE is used (can be defined in settings file as DJANGO_REQUEST_LOGGING_LOG_RESPONSE_DEFAULT_VALUE)\n* no_response_logging_msg\n * Reason for deactivation of body logging gets logged instead of body (only if silent=True and log_body=False)\n * NO_RESPONSE_LOGGING_MSG is used by default\n* silent\n * True: deactivate logging of alternative messages case parts of the logging are deactivated (request/header/body/response)\n * False: alternative messages for deactivated parts of logging (request/header/body/response) are logged instead\n```\n\nBy default, value of Http headers `HTTP_AUTHORIZATION` and `HTTP_PROXY_AUTHORIZATION` are replaced wih `*****`. You can use `REQUEST_LOGGING_SENSITIVE_HEADERS` setting to override this default behaviour with your list of sensitive headers.\n\n## Django settings\nYou can customized some behaves of django-request-logging by following settings in Django `settings.py`.\n### REQUEST_LOGGING_DATA_LOG_LEVEL\nBy default, data will log in DEBUG level, you can change to other valid level (Ex. logging.INFO) if need.\n### REQUEST_LOGGING_ENABLE_COLORIZE\nIt's enabled by default. If you want to log into log file instead of console, you may want to remove ANSI color. You can set `REQUEST_LOGGING_ENABLE_COLORIZE=False` to disable colorize.\n### REQUEST_LOGGING_DISABLE_COLORIZE (Deprecated)\nThis legacy setting will still available, but you should't use this setting anymore. You should use `REQUEST_LOGGING_ENABLE_COLORIZE` instead.\nWe keep this settings for backward compatibility.\n### REQUEST_LOGGING_MAX_BODY_LENGTH\nBy default, max length of a request body and a response content is cut to 50000 characters.\n### REQUEST_LOGGING_HTTP_4XX_LOG_LEVEL\nBy default, HTTP status codes between 400 - 499 are logged at ERROR level. You can set `REQUEST_LOGGING_HTTP_4XX_LOG_LEVEL=logging.WARNING` (etc) to override this.\nIf you set `REQUEST_LOGGING_HTTP_4XX_LOG_LEVEL=logging.INFO` they will be logged the same as normal requests.\n### REQUEST_LOGGING_SENSITIVE_HEADERS\nThe value of the headers defined in this settings will be replaced with `'*****'` to hide the sensitive information while logging. By default it is set as `REQUEST_LOGGING_SENSITIVE_HEADERS = [\"HTTP_AUTHORIZATION\", \"HTTP_PROXY_AUTHORIZATION\"]`\n### DJANGO_REQUEST_LOGGING_LOGGER_NAME\nName of the logger that is used to log django.request occurrances with the new LoggingMiddleware. Defaults to \"django.request\".\n### DJANGO_REQUEST_LOGGING_NO_LOGGING_DEFAULT_VALUE\nGlobal default to activate/deactivate logging of all views. Can be overruled for each individual view by using the @no_logging decator's \"value\" parameter.\n### DJANGO_REQUEST_LOGGING_LOG_HEADERS_DEFAULT_VALUE = True\nGlobal default to activate/deactivate logging of request headers for all views. Can be overruled for each individual view by using the @no_logging decator's \"log_headers\" parameter.\n### DJANGO_REQUEST_LOGGING_LOG_BODY_DEFAULT_VALUE = True\nGlobal default to activate/deactivate logging of request bodys for all views. Can be overruled for each individual view by using the @no_logging decator's \"log_body\" parameter.\n### DJANGO_REQUEST_LOGGING_LOG_RESPONSE_DEFAULT_VALUE = True\nGlobal default to activate/deactivate logging of responses for all views. Can be overruled for each individual view by using the @no_logging decator's \"log_response\" parameter.\n\n\n## Deploying, Etc.\n\n### Maintenance\n\nUse `pyenv` to maintain a set of virtualenvs for 2.7 and a couple versions of Python 3.\nMake sure the `requirements-dev.txt` installs for all of them, at least until we give up on 2.7.\nAt that point, update this README to let users know the last version they can use with 2.7.\n\n### Setup\n\n- `pip install twine pypandoc pbr wheel`\n- If `pypandoc` complains that `pandoc` isn't installed, you can add that via `brew` if you have Homebrew installed\n- You will need a `.pypirc` file in your user root folder that looks like this:\n\n```\n index-servers=\n testpypi\n pypi\n\n [testpypi]\n username = rhumbix\n password = password for dev@rhumbix.com at Pypi\n\n [pypi]\n username = rhumbix\n password = password for dev@rhumbix.com at Pypi\n```\n\n### Publishing\n\n- Bump the version value in `request_logging/__init__.py`\n- Run `python setup.py publish`\n- Manually tag per the instructions in the output of that command\n- TODO: add automagic `git tag` logic to the publish process\n- TODO: setup 2FA at Pypi\n" }, { "alpha_fraction": 0.7317073345184326, "alphanum_fraction": 0.7421602606773376, "avg_line_length": 21.076923370361328, "blob_id": "a5afbf755cc23639fd4e07638d818f0ec2da7429", "content_id": "d10ff9bb1bd9d3a0c716809235f399ce97cbb04f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 287, "license_type": "permissive", "max_line_length": 69, "num_lines": 13, "path": "/test_urls_alternate.py", "repo_name": "Rhumbix/django-request-logging", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom django.http import HttpResponse\nfrom request_logging.decorators import no_logging\n\n\n@no_logging()\ndef view_func(request):\n return HttpResponse(status=200, body=\"view_func with no logging\")\n\n\nurlpatterns = [\n url(r\"^test_route$\", view_func),\n]\n" }, { "alpha_fraction": 0.49584487080574036, "alphanum_fraction": 0.6343490481376648, "avg_line_length": 44.125, "blob_id": "35cb5dd86ec47cfc521c9b8794835152988e999b", "content_id": "c3a661df7f42f86d29b37d47829dd7d482d300cd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 361, "license_type": "permissive", "max_line_length": 73, "num_lines": 8, "path": "/requirements-dev.txt", "repo_name": "Rhumbix/django-request-logging", "src_encoding": "UTF-8", "text": "mock==2.0.0 ; python_version < '3.6'\nmock==4.0.3 ; python_version >= '3.6'\ndjango>=1.11.20,<2.0 ; python_version < '3.0'\ndjango>=1.11.20,<3.0 ; python_version >= '3.0' and python_version < '3.6'\ndjango>=2.0,<3.3.0 ; python_version >= '3.6'\ncoverage==5.5\ndjangorestframework==3.8.2 ; python_version <= '3.4'\ndjangorestframework==3.12.4 ; python_version >= '3.5'\n" }, { "alpha_fraction": 0.7066590189933777, "alphanum_fraction": 0.7066590189933777, "avg_line_length": 59.068965911865234, "blob_id": "f3082c7282471e65c59f24fee16621d3e7f85e6c", "content_id": "6010d48c380cad7a53c5424d3e59867abd385cb5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1742, "license_type": "permissive", "max_line_length": 116, "num_lines": 29, "path": "/request_logging/decorators.py", "repo_name": "Rhumbix/django-request-logging", "src_encoding": "UTF-8", "text": "from .middleware import NO_LOGGING_ATTR, NO_LOGGING_MSG_ATTR, NO_LOGGING_MSG, NO_LOGGING_DEFAULT_VALUE, \\\n LOG_HEADERS_ATTR, LOG_HEADERS_DEFAULT_VALUE, LOG_BODY_ATTR, LOG_BODY_DEFAULT_VALUE, LOG_RESPONSE_ATTR, \\\n LOG_RESPONSE_DEFAULT_VALUE, NO_RESPONSE_LOGGING_MSG_ATTR, NO_RESPONSE_LOGGING_MSG, NO_HEADER_LOGGING_MSG_ATTR, \\\n NO_HEADER_LOGGING_MSG, NO_BODY_LOGGING_MSG_ATTR, NO_BODY_LOGGING_MSG\n\n\ndef no_logging(msg=None, silent=False, value=None, log_headers=None, no_header_logging_msg=None, log_body=None,\n no_body_logging_msg=None, log_response=None, no_response_logging_msg=None):\n def _set_attr(func, attr_name, value, default_value=None):\n setattr(func, attr_name, value if value is not None else default_value)\n\n def _set_attr_msg(func, silent_value, msg_attr_name, message, default_message=None):\n setattr(func, msg_attr_name, (message if message else default_message) if not silent_value else None)\n\n def wrapper(func):\n _set_attr(func, NO_LOGGING_ATTR, value, NO_LOGGING_DEFAULT_VALUE)\n _set_attr_msg(func, silent, NO_LOGGING_MSG_ATTR, msg, NO_LOGGING_MSG)\n\n _set_attr(func, LOG_HEADERS_ATTR, log_headers, LOG_HEADERS_DEFAULT_VALUE)\n _set_attr_msg(func, silent, NO_HEADER_LOGGING_MSG_ATTR, no_header_logging_msg, NO_HEADER_LOGGING_MSG)\n\n _set_attr(func, LOG_BODY_ATTR, log_body, LOG_BODY_DEFAULT_VALUE)\n _set_attr_msg(func, silent, NO_BODY_LOGGING_MSG_ATTR, no_body_logging_msg, NO_BODY_LOGGING_MSG)\n\n _set_attr(func, LOG_RESPONSE_ATTR, log_response, LOG_RESPONSE_DEFAULT_VALUE)\n _set_attr_msg(func, silent, NO_RESPONSE_LOGGING_MSG_ATTR, no_response_logging_msg, NO_RESPONSE_LOGGING_MSG)\n return func\n\n return wrapper\n" } ]
9
iceihehe/189sms
https://github.com/iceihehe/189sms
0cbbf924aa58f701aa35ad13766bda59c3b82bfa
c448984de8b9b71e1be59d0a2596366f02687dcd
c2541e54a312e2f2f93aaab7abc9cab07a50364a
refs/heads/master
2021-01-23T13:50:14.323224
2015-10-20T10:10:40
2015-10-20T10:10:40
40,701,355
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.4856283366680145, "alphanum_fraction": 0.49732619524002075, "avg_line_length": 24.355932235717773, "blob_id": "fa013c937424cd5b9079917cd64237eb1291901b", "content_id": "2c0f32811d43abbfab9b3d3bbc8d68f9a9e70ebc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3048, "license_type": "no_license", "max_line_length": 70, "num_lines": 118, "path": "/basic.py", "repo_name": "iceihehe/189sms", "src_encoding": "UTF-8", "text": "# -*- coding=utf-8 -*-\n# Created Time: 2015年08月14日 星期五 15时16分58秒\n# File Name: basic.py\n\nfrom __future__ import print_function\n\nfrom datetime import datetime\nfrom hashlib import sha1\nimport requests\n# import json\nimport hmac\nimport urllib\n\n\nclass AuthCode(object):\n '''\n 短信验证码\n '''\n def __init__(self, *args, **kwargs):\n self._app_id = kwargs.get('app_id')\n self._app_secret = kwargs.get('app_secret')\n\n def _request(self, method, url, **kwargs):\n\n r = requests.request(\n method=method,\n url=url,\n **kwargs\n )\n r.raise_for_status()\n response_json = r.json()\n\n return response_json\n\n def _get(self, url, **kwargs):\n return self._request(\n method='get',\n url=url,\n **kwargs\n )\n\n def _post(self, url, **kwargs):\n return self._request(\n method='post',\n url=url,\n **kwargs\n )\n\n def grant_access_token(\n self, grant_type='client_credentials', state='', scope=''\n ):\n\n data = {\n 'grant_type': grant_type,\n 'app_id': self._app_id,\n 'app_secret': self._app_secret,\n 'state': state,\n 'scop': scope,\n }\n\n return self._post(\n url='https://oauth.api.189.cn/emp/oauth2/v3/access_token',\n data=data,\n )\n\n def _formatBizQueryParaMap(self, paraMap, urlencode):\n '''格式化参数,签名过程需要使用'''\n slist = sorted(paraMap)\n buff = []\n for k in slist:\n v = urllib.quote(paraMap[k]) if urlencode else paraMap[k]\n buff.append(\"{0}={1}\".format(k, v.encode('utf-8')))\n return \"&\".join(buff)\n\n def get_sign(self, key, raw=''):\n if not raw:\n raw = self._app_secret\n signed = hmac.new(raw, key, sha1).digest()\\\n .encode('base64').rstrip('\\n')\n return signed\n\n def get_token(self):\n\n data = {\n 'app_id': self._app_id,\n 'access_token': self.grant_access_token()['access_token'],\n 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),\n }\n\n d = self._formatBizQueryParaMap(data, False)\n data.update({\n 'sign': self.get_sign(d),\n })\n\n return self._get(\n url='http://api.189.cn/v2/dm/randcode/token',\n params=data,\n )\n\n def send_randcode(self, token, url, phone):\n data = {\n 'app_id': self._app_id,\n 'access_token': self.grant_access_token()['access_token'],\n 'token': token,\n 'url': url,\n 'phone': phone,\n 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),\n }\n\n d = self._formatBizQueryParaMap(data, False)\n data.update({\n 'sign': self.get_sign(d),\n })\n\n return self._post(\n url='http://api.189.cn/v2/dm/randcode/send',\n data=data,\n )\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.800000011920929, "avg_line_length": 9, "blob_id": "6c90dfc0a043ed9b987c6734c79dc5fb642d266e", "content_id": "e823f5974895e22b9bfef6dac772db7603c4ec27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 34, "license_type": "no_license", "max_line_length": 10, "num_lines": 2, "path": "/README.md", "repo_name": "iceihehe/189sms", "src_encoding": "UTF-8", "text": "# 189sms\n测试189短信验证码\n" } ]
2
skarthikaeyan/clieser
https://github.com/skarthikaeyan/clieser
b551457ed6e8118d03a7879c2aa97f2354a7e0b1
39698112634ee57fd5b7243a3d9e85a3d62405be
55b4407c2117945097e7e1b1a1d15d2d14df28af
refs/heads/master
2021-05-06T13:23:39.174093
2017-12-07T07:19:21
2017-12-07T07:19:21
113,267,712
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5384126901626587, "alphanum_fraction": 0.5460317730903625, "avg_line_length": 25.694915771484375, "blob_id": "2fd8d866f6e7f30ccb04cd62046a474b9dbd7d47", "content_id": "f7c5cf713530e19f1bdf6681bd330e02530a96eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1575, "license_type": "no_license", "max_line_length": 83, "num_lines": 59, "path": "/client.py", "repo_name": "skarthikaeyan/clieser", "src_encoding": "UTF-8", "text": "import sys\nimport socket\nimport time\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #creating socket sock\nhost = socket.gethostname() #getting local ip\nprint(host)\nport = 65535\n\ntry:\n sock.connect((host,port))\n print(\"connected\")\n\nexcept socket.error as e:\n print(\"Try again\"+str(e))\n sock.close()\n sys.exit()\n\nprint(\"Type your Message\")\ntry:\n a=raw_input(\"You: \").encode()\n while True:\n #encoding to byte\n if not a or 'exit' in a or 'logout' in a or 'thank you' in a or 'bye' in a:\n sock.send(a)\n time.sleep(1)\n print(\"Server: Thank you\")\n print(\"Server Disconnected...\")\n sock.close()\n break\n\n else:\n a=bytes(a)\n sock.send(a)\n #sending the input as input is not from file b' is not used\n b=sock.recv(1024)\n nw=str(b)\n #if the string contains following words server will be disconnected\n\n if 'exit' in nw or 'logout' in nw or 'thank you' in nw or 'bye' in nw:\n sock.send(b'thank you')\n time.sleep(1)\n print('Server: '+b)\n print('Server Disconnected...')\n sock.close()\n sys.exit()\n\n else:\n print(\"Server: \"+b)\n a=raw_input(\"You: \").encode()\n\nexcept KeyboardInterrupt as k:#making KeyboardInterrupt reasonable\n print(\"\\nDisconnected...\")\n sock.send(b'exit')\n time.sleep(1)\n sock.close() #closing the socket\n sys.exit()\n\nsock.close()\n" }, { "alpha_fraction": 0.5183823704719543, "alphanum_fraction": 0.5279411673545837, "avg_line_length": 25.153846740722656, "blob_id": "73a52e72b3f8d412f601903d961609424c0525a1", "content_id": "813e9a52a5ca564e910c7eddea99e104190dd6b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2720, "license_type": "no_license", "max_line_length": 108, "num_lines": 104, "path": "/ser.py", "repo_name": "skarthikaeyan/clieser", "src_encoding": "UTF-8", "text": "import socket\nimport sys\nimport string\nimport time\n\nsock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)#create a socket\nsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)#reuse the socket once more if not closed properly\nhost=socket.gethostname()\nport=65535\n\n\ntry:\n sock.bind((host,port))\nexcept socket.error as e:\n print(\"error\",e)\n sys.exit()\n\nsock.listen(1)\nprint(\"Waiting for connection...\")\ncom, addr = sock.accept()\nprint(\"Connected to \" + str(addr).strip('()'))\n\ntry:\n a = com.recv(1024).decode()\n a=str(a)\n a=a.lower()\n a=a.replace(\"'\",\"\") #making the string readble for program\n\n if 'exit' in a or 'logout' in a or 'thank you' in a or 'bye' in a or not a:\n print(\"Client: \"+a)\n com.close()\n time.sleep(1)\n print(\"Client disconnected...\")\n sys.exit()\n\n print(\"Client: \"+a)\n words=a.split()\n length=len(words)\n i=0\n\n while True:#frist while loop is for processing the introduction runs only once\n if not a:\n print(\"No Input\")\n com.send(b'thank You')\n time.sleep(1)\n com.close()\n sys.exit()\n\n else:\n\n if words[0]==\"hello\":\n c=\"Hi \"\n\n else:\n c=\"Hello \"\n\n if words[i]!=\"hello\" and words[i]!=\"hi\" and words[i]!=\"im\":\n w = words[i]\n w=w.capitalize()\n w = c + w\n w.encode()\n com.send(w)\n print('You: '+w)\n time.sleep(1)\n break\n\n else:\n i+=1\n continue\n#infinite loops error occurs when i put following code above\n while True:#second while is for 1 to 1 communication\n nw=com.recv(1024)\n nw=str(nw)\n nw=nw.lower()\n\n if 'exit' in nw or 'logout' in nw or 'thank you' in nw or 'bye' in nw or not nw:\n print(\"Client: \"+nw)\n com.send(b'thank you')\n print(\"Client Disconnected...\")#to check client sends exit message\n time.sleep(1)\n com.close()\n sys.exit()\n\n else:\n print(\"Client: \"+nw)\n sdata=raw_input(\"You: \")\n\n if 'exit' in sdata or 'logout' in sdata or 'thank you' in sdata or 'bye' in sdata or not sdata:\n com.send(sdata)\n com.close()\n time.sleep(1)\n sys.exit() #to check server sends exit message\n\n sdata=sdata.decode()\n com.send(sdata)\n\nexcept KeyboardInterrupt as k:\n com.send(b'thank you')#KeyboardInterrupt to make readable\n print(\"Disconnected...\")\n time.sleep(1)\n com.close()\n sys.exit()\n\ncom.close()\n" }, { "alpha_fraction": 0.8125, "alphanum_fraction": 0.8125, "avg_line_length": 15, "blob_id": "2525ab9d3757503af3f9a4c2e39a77d0d6b53101", "content_id": "531736a49a2b91f5861ad22f7cd05fb4e64c2413", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 32, "license_type": "no_license", "max_line_length": 21, "num_lines": 2, "path": "/README.md", "repo_name": "skarthikaeyan/clieser", "src_encoding": "UTF-8", "text": "# clieser\nClient-server Program\n" } ]
3
hangxuu/Notes-and-Blog
https://github.com/hangxuu/Notes-and-Blog
0658503231bb704a0e9a9bdb2313526a1e6b28f6
06779f5236ef58a03122d6e230ce98bc07b22b78
42bd33ce51bce0c1c51cda98755d4da1002aab67
refs/heads/master
2023-01-10T01:45:29.120695
2020-11-06T13:32:19
2020-11-06T13:32:19
179,838,037
3
0
null
null
null
null
null
[ { "alpha_fraction": 0.5885369777679443, "alphanum_fraction": 0.5951734781265259, "avg_line_length": 23.55555534362793, "blob_id": "9d2709113dd6232d5811ed8002de7759625eb301", "content_id": "36de9a7cc3fdafca8837df25ea65c9479b041243", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3315, "license_type": "no_license", "max_line_length": 61, "num_lines": 135, "path": "/codes/effective_python/item62/item62.py", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "import atexit\nimport gc\nimport io\nimport time\nimport collections\nimport os\nimport random\nimport string\nfrom tempfile import TemporaryDirectory\nfrom threading import Lock, Thread\n\nrandom.seed(1234)\n\n\n# Example 1\nclass NoNewData(Exception):\n pass\n\n\ndef readline(handle):\n offset = handle.tell()\n handle.seek(0, 2)\n length = handle.tell()\n\n if length == offset:\n raise NoNewData\n\n handle.seek(offset, 0)\n return handle.readline()\n\n\ndef tail_file(handle, interval, write_func):\n while not handle.closed:\n try:\n line = readline(handle)\n except NoNewData:\n time.sleep(interval)\n else:\n write_func(line)\n\n\ndef run_threads(handles, interval, output_path):\n with open(output_path, 'wb') as output:\n lock = Lock()\n\n def write(data):\n with lock:\n output.write(data)\n\n threads = []\n for handle in handles:\n args = (handle, interval, write)\n thread = Thread(target=tail_file, args=args)\n thread.start()\n threads.append(thread)\n\n for thread in threads:\n thread.join()\n\n\ndef write_random_data(path, write_count, interval):\n with open(path, 'wb') as f:\n for i in range(write_count):\n time.sleep(random.random() * interval)\n letters = random.choices(\n string.ascii_lowercase, k=10)\n data = f'{path}-{i:02}-{\"\".join(letters)}\\n'\n f.write(data.encode())\n f.flush()\n\n\ndef start_write_threads(directory, file_count):\n paths = []\n for i in range(file_count):\n path = os.path.join(directory, str(i))\n with open(path, 'w'):\n # Make sure the file at this path will exist when\n # the reading thread tries to poll it.\n pass\n paths.append(path)\n args = (path, 10, 0.1)\n thread = Thread(target=write_random_data, args=args)\n thread.start()\n return paths\n\n\ndef close_all(handles):\n time.sleep(1)\n for handle in handles:\n handle.close()\n\n\ndef setup():\n tmpdir = TemporaryDirectory()\n input_paths = start_write_threads(tmpdir.name, 5)\n\n handles = []\n for path in input_paths:\n handle = open(path, 'rb')\n handles.append(handle)\n\n Thread(target=close_all, args=(handles,)).start()\n\n output_path = os.path.join(tmpdir.name, 'merged')\n return tmpdir, input_paths, handles, output_path\n\n\n# Example 5\ndef confirm_merge(input_paths, output_path):\n found = collections.defaultdict(list)\n with open(output_path, 'rb') as f:\n for line in f:\n for path in input_paths:\n if line.find(path.encode()) == 0:\n found[path].append(line)\n\n expected = collections.defaultdict(list)\n for path in input_paths:\n with open(path, 'rb') as f:\n expected[path].extend(f.readlines())\n\n for key, expected_lines in expected.items():\n found_lines = found[key]\n assert expected_lines == found_lines, \\\n f'{expected_lines!r} == {found_lines!r}'\n # print(f'{expected_lines!r} == {found_lines!r}')\n\n\ntmpdir, input_paths, handles, output_path = setup()\n\nrun_threads(handles, 0.1, output_path)\n\nconfirm_merge(input_paths, output_path)\n\ntmpdir.cleanup()\n" }, { "alpha_fraction": 0.7050346732139587, "alphanum_fraction": 0.7126960754394531, "avg_line_length": 34.367740631103516, "blob_id": "94d7e3d46dd0ea0d64e08ca7380208172dee5f28", "content_id": "46815a5beae170535638e8ce3047c69644bfd0b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8890, "license_type": "no_license", "max_line_length": 257, "num_lines": 155, "path": "/notes/python并发编程.md", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "<!-- GFM-TOC -->\n* [一、多进程](#多进程)\n * [什么时候用多进程](#什么时候用多进程)\n * [多进程怎么用](#多进程怎么用)\n* [二、多线程](#多线程)\n * [什么时候用多线程](#什么时候用多线程)\n * [多线程怎么用](#多线程怎么用)\n* [三、协程](#协程)\n * [什么时候用协程](#什么时候用协程)\n * [协程怎么用](#协程怎么用)\n* [四、多线程及协程的一些示例代码](#多线程及协程的一些示例代码)\n* [参考资料](#参考资料)\n\n<!-- GFM-TOC -->\n\n## 多进程\n进程是操作系统资源分配的基本单位。\n### 什么时候用多进程\n当需要真正的并行计算时,使用多进程能同时使用多个CPU核心。因此多进程特别适合CPU密集型应用。\n### 多进程怎么用\n对于高度并行的任务(各个任务之间没有依赖,不用交流,结果也是独立的),``concurrent.futures``的``ProcessPoolExecutor``类是第一选择。使用也很简单。示例:\n```python\nfrom concurrent import futures\n\ndef sha(size):\n # 计算型函数\n ...\n \nSIZE = 3 # sha函数的参数\nJOBS = 12 # 任务数\n\n...\nwith futures.ProcessPoolExecutor() as executor:\n to_do = (executor.submit(sha, SIZE) for i in range(JOBS))\n for future in futures.as_completed(to_do):\n res = future.result()\n print(res)\n```\n如果使用场景较复杂,例如需要在进程之间传递数据,那么可以使用更底层的``multiprocessing``模块来处理。\n\n## 多线程\n线程是操作系统独立调度的基本单位。\n\n### 什么时候用多线程\nGIL:全局解释器锁。Cpython执行python程序分为两步:1,把源程序翻译成字节码;2,使用基于堆栈的解释器运行字节码(字节码解释器的状态必须在python程序运行时保持一致)。Cpython解释器本身就不是线程安全的。因此需要加锁。GIL是互斥锁,以防止Cpython受到抢占式多线程的影响。\n\nPython标准库中的所有阻塞型 I/O 函数都会释放 GIL,允许其他线程运行。``time.sleep()``函数也会释放 GIL。因此,尽管有 GIL,Python 线程还是能在 I/O 密集型应用中发挥作用。因此python多线程特别适合I/O密集型应用。\n\n### 多线程怎么用\n同多进程,对于高度并行的任务,``concurrent.futures``的``ThreadPoolExecutor``类是第一选择。使用和``ProcessPoolExecutor``类似,如下例:\n```python\nfrom concurrent import futures\n...\ndef download_many_thread(alnum, total):\n with futures.ThreadPoolExecutor(max_workers=20) as executor:\n to_do = []\n for i in range(1, total + 1):\n future = executor.submit(download_one_for_multi, (alnum, i))\n to_do.append(future)\n result = []\n for future in futures.as_completed(to_do):\n res = future.result()\n result.append(res)\n # 结果顺序与调用顺序不一致(乱序,谁先运行结束谁在前面)\n return result\n```\n可以看出``ThreadPoolExecutor``类在用法上和``ProcessPoolExecutor``类基本相同。``ThreadPoolExecutor``类需要传入``max_workers``参数指定线程池大小,这个根据需要可以开到很大。而``ProcessPoolExecutor``一般不需要这个参数,它会默认使用``os.cpu_count()``函数返回的CPU数量。\n\n除了使用``executor.submit``和``futures.as_complete``组合,也可以直接使用``executor.map``完成上述功能。\n```python\ndef download_many_thread(alnum, total):\n with ThreadPoolExecutor(max_workers=20) as executor:\n results = executor.map(download_one_for_multi, [(alnum, i) for i in range(1, total + 1)])\n # 结果顺序与调用顺序一致\n return results\n```\n使用``executor.submit``和``futures.as_complete``更灵活。因为``executor.submit``可以调用不同的可调用对象,``executor.map``只能处理同一个可调用对象。此外,传给``futures.as_complete``函数的期物(Future对象,可以理解为正在运行的函数)集合可以来自多个``Executor``实例,例如一些由``ThreadPoolExecutor``实例创建, 另一些由``ProcessPoolExecutor``实例创建。\n\n如果需要结果顺序与调用顺序保持一致呢?也不是一定要用``executor.map``,``futures.as_completed``函数也可以解决这个问题:把期物存储在一个字典中,提交期物时把期物与相关的信息联系起来;这样,``as_completed`` 迭代器产出期物后,就可以使用那些信息。示例:\n```python\ndef download_many_thread3(alnum, total):\n with ThreadPoolExecutor(max_workers=20) as executor:\n # 使用字典而不是列表\n to_do_map = {}\n for i in range(1, total + 1):\n future = executor.submit(download_one_for_multi, (alnum, i))\n to_do_map[future] = i\n\n results = []\n for future in futures.as_completed(to_do_map):\n res = future.result()\n results.append((res, to_do_map[future]))\n # 根据字典保存的信息做排序即可(这里保存的就是生成期物的顺序)。\n results = [item[0] for item in sorted(results, key=lambda a:a[1])]\n return results\n```\n\n如果使用场景较复杂,例如线程之间需要交流,或者会发生资源争用,需要用到锁或信号量。那么可以使用更底层的``threading``模块来处理。\n\n## 协程\n协程相比多线程有什么优点?为什么要使用协程?\n\n线程是由操作系统调度的,属于抢夺式多任务。就拿生产者消费者的例子说明。操作系统公平地运行这两个线程。假如生产者生产了一半时间片用完,操作系统就会保存它的生产现场。然后去运行消费者线程,由于消费者现在没有东西消费,它就会一直空等待,白白浪费一个时间片。\n\n而协程属于协作式多任务。由协程自己控制何时让出时间片。生产者协程生产完毕后让出时间片,并通知等待它的消费者,此时消费者得到时间片后直接消费。就不会有CPU算力的浪费。\n\n### 什么时候用协程\n和多线程的使用场景相同:适合IO密集型应用。并且把多线程里的阻塞IO改为异步IO。\n### 协程怎么用\n现在已经不推荐使用 ``yield from`` 实现协程了。应该使用 ``async/await``定义协程,以及使用``asyncio``包实现异步IO,处理并发。\n\n生产者-消费者的协程版本:\n```python\nimport asyncio\n\nasync def consumer(i):\n item = await producer(i)\n print(f\"Consuming {item}\")\n\n\nasync def producer(i):\n # 模拟生产者生产时间\n await asyncio.sleep(1)\n print(f\"Producing {i}\")\n return i\n\n\nasync def main():\n need, i = 10, 0\n while i < need:\n await consumer(i)\n i += 1\n print(\"Work done\")\n\nasyncio.run(main())\n\n```\n《fluent python》 里的一段话能帮大家通俗理解 ``asyncio`` 的使用方法:使用 asyncio 包时,我们编写的异步代码中包含由 asyncio 本身驱动的协程(即委派生成器),而生成器最终把职责委托给 asyncio 包或第三方库(如 aiohttp)中的协程。这种处理方式相当于架起了管道,让 asyncio 事件循环(通过我们编写的协程)驱动执行低层异步 I/O 操作的库函数。\n\n上例就是由 ``asyncio`` 驱动 ``main`` 协程,然后协程里一直 ``await`` 到执行异步IO操作的库函数 ``asyncio.sleep(1)``,这个 ``sleep`` 函数模拟生产者的生产过程。当生产完成后,事件循环把响应发给等待结果的消费者。得到响应后,消费者消费掉生产者的东西(打印输出),事件循环又把相应发给 ``main``协程,``main``协程记录已生产元素的件数(``i += 1``),向前执行到下一个 ``await`` 处,然后让出时间片(把控制权还给主循环)。\n\n## 多线程及协程的一些示例代码\n一个网络下载程序的单线程,多线程以及协程版本。上文中的部分代码片段即来自这些脚本。\n- 普通单线程版本 [download_normal.py](https://github.com/hangxuu/Notes-and-Blog/blob/master/codes/concurrency/download_normal.py)\n- 多线程版本 [download_thread.py](https://github.com/hangxuu/Notes-and-Blog/blob/master/codes/concurrency/download_thread.py)\n- 协程版本 [download_asyncio.py](https://github.com/hangxuu/Notes-and-Blog/blob/master/codes/concurrency/download_asyncio.py).\n\n《fluent python》中一个线程和协程对比的例子。\n- 线程版本 [spinner_thread.py](https://github.com/hangxuu/Notes-and-Blog/blob/master/codes/concurrency/spinner_thread.py)\n- 协程版本 [spinner_asyncio.py](https://github.com/hangxuu/Notes-and-Blog/blob/master/codes/concurrency/spinner_asyncio.py)\n\n## 参考资料\n- [也来谈谈协程](https://zhuanlan.zhihu.com/p/147608872)\n- 《fluent python》 chapter 16 - 18\n- 《Effective python 2ed》 chapter 7\n" }, { "alpha_fraction": 0.6470765471458435, "alphanum_fraction": 0.6506931781768799, "avg_line_length": 31.539215087890625, "blob_id": "e19910824da901d1d121ad4d32ae713b4421827b", "content_id": "b2c29c22202c1adba336c4ee81363382fed7e860", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5480, "license_type": "no_license", "max_line_length": 241, "num_lines": 102, "path": "/notes/python避坑不完全指南.md", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "### (1)尽量避免多分支返回,特别是多层if(两层以上)嵌套的情况\n先来看个例子。下面函数的功能是完善省市信息,如果 ``utype`` 是 ``c``,说明 ``city_or_prov`` 是城市,如果为 ``p``,则为省份。如果不传 ``utype`` ,则直接返回 ``city_or_prov`` 参数。\n```python\ndef add_suffix(city_or_prov, utype=None):\n if utype == 'c':\n if city_or_prov[-1] != '市':\n return city_or_prov + '市'\n elif utype == 'p':\n if city_or_prov[-1] != '省':\n return city_or_prov + '省'\n else:\n return city_or_prov\n```\n大家能看出上面函数有什么问题吗?如果传入 ``('上海', 'c')``,那么返回 ``上海市`` 。没有问题。传入 ``('陕西', 'p')`` 也不会有问题。可是如果传入 ``('上海市', 'c')``,这时程序会返回``None``!!因为程序进入第一个``if``后不满足第二个``if``条件,而后续也没有相应代码,所以程序直接返回默认值``None``。python不要求返回值类型必须一致,甚至可以不返回值,但我们在享受这种灵活性的同时要警惕不要制造隐含的bug。\n\n修改的方法是使用单一``return``语句。上例修改如下:\n```python\ndef add_suffix(city_or_prov, utype):\n if utype == 'c':\n if city_or_prov[-1] != '市':\n city_or_prov = city_or_prov + '市'\n elif utype == 'p':\n if city_or_prov[-1] != '省':\n city_or_prov = city_or_prov + '省'\n\n return city_or_prov\n```\n**if语句中修改变量后不要直接返回,而是统一赋给一个变量,在函数末尾进行返回。**\n\n提出这个建议的原因是,一层``if``的话,我们往往能够记得写相应的``else``,可一旦``if``嵌套超过一层,我们就很容易忽略写对应的``else``子句。此时应该使用单一``return``语句,而不要在各个分支内分别``return``。\n\n### (2)不要滥用``try/except``块\n我看过很多人写的代码,一进函数体就``try``,然后在函数末尾``except``,或者稍微好点,只把一大部分而不是全部代码包到``try/except``块里。\n大概类似这样:\n```python\ndef run(example_list):\n try:\n item = example_list[0]\n item += 1\n # code to process item and other codes\n ...\n ...\n except Exception as e:\n logger.error(e)\n```\n这样程序跑起来基本上不会崩,但同时也失去了异常处理的意义。很多人只要程序正常结束了,就不会去看日志。更何况多进程的程序一旦跑起来日志基本上就乱的不能看了,所以即使去看日志,想找到``error``也是难上加难。\n\n那么应该怎么做呢?\n\n**“尽早暴露错误”** 原则,如果程序要崩溃,那就让它尽早崩溃,然后修改bug,提高质量。具体到代码中,还是以上面例子为例:\n```python\ndef run(example_list):\n try:\n item = example_list[0]\n except Exception as e:\n logger.error(e)\n else:\n item += 1\n # code to process item and other codes\n ...\n ...\n```\n把确定不会出错的代码转移至``else``子句。``try``中只放可能会引发异常的语句。这样,当错误发生时,就能更快的定位到错误的位置。特别是``try``里面有多条可能会引发异常的语句时(上例只写了一条),应该把它们分开,使每个``try``中只含一条可能会引发异常的语句。\n\n### (3)不要在程序中使用文件相对路径\n这个例子可能不是很好帖,先说结论。**在函数调用的过程中,当前路径.代表的是被执行的脚本文件的所在路径**。也就是说,执行不同的脚本文件,对同一相对路径的解析会出现不同的结果!!\n\n项目的目录树如下图,同级目录已用相同颜色标出。\n\n![目录树](https://github.com/hangxuu/blog/blob/master/images/path_1.png)\n\n``E:\\test_dir\\test_path\\codes\\read_file.py`` 文件如下:\n``` python\nimport os\n\nfile_path = '../data/hello.txt'\nprint(os.path.abspath(file_path))\nwith open(file_path, 'r') as f:\n for line in f:\n print(line)\n```\n我在这个脚本中使用了文件相对路径。\n\n直接运行这个脚本,``print(os.path.abspath(file_path))`` 的输出是 ``E:\\test_dir\\test_path\\data\\hello.txt``。\n\n运行 ``E:\\test_dir\\a_test_file.py``文件(该文件只有一句``from test_path.codes import read_file``),``print(os.path.abspath(file_path))`` 的输出是 ``E:\\data\\hello.txt``。\n\n可见,相对路径的解析会根据执行脚本的不同而不同。如上例,程序自然会报 ``FileNotFoundError``,但如果你的项目所有使用这个相对路径的脚本都在同一目录下,或者运气好目录的深度相同,那就不会报错,而会成为一个隐形的bug。\n\n解决方法:\n修改 ``E:\\test_dir\\test_path\\codes\\read_file.py`` 文件如下:\n``` python\nimport os\n\nfile_abs_path = os.path.abspath(__file__)\nfile_path = os.path.join(os.path.dirname(os.path.dirname(file_abs_path)), 'data', 'hello.txt')\nprint(file_path)\nwith open(file_path, 'r') as f:\n for line in f:\n print(line)\n```\n``file_abs_path = os.path.abspath(__file__)`` 会得到当前脚本(该行程序所在脚本)的绝对路径,然后用 ``os`` 模块提供的方法一步步去寻找所需文件。这样虽然写起来是麻烦了一些。但可以解决路径解析问题,而且还做到了跨平台兼容。" }, { "alpha_fraction": 0.7617021203041077, "alphanum_fraction": 0.7702127695083618, "avg_line_length": 51.33333206176758, "blob_id": "fdd735651ef0e56491f0425db3ac35dd3ee2b70d", "content_id": "1eb61e2327a38c933fb90ad127099b4578e41e91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 508, "license_type": "no_license", "max_line_length": 119, "num_lines": 9, "path": "/README.md", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "# 读书笔记\n\n- [Effective Python 2nd Edition](https://github.com/hangxuu/blog/blob/master/notes/Effective_Python_Notes.md)\n- [数据密集型应用系统设计](https://github.com/hangxuu/blog/blob/master/notes/Designing_data-intensive_applications.md)\n- [The Linux Command Line 2nd Edition](https://github.com/hangxuu/blog/blob/master/notes/the_linux_command_line.md)\n\n# 课程笔记\n\n- [MIT 6.NULL - The Missing Semester of Your CS Education](https://github.com/hangxuu/blog/blob/master/notes/6_null.md)" }, { "alpha_fraction": 0.5839874148368835, "alphanum_fraction": 0.5965462923049927, "avg_line_length": 20.449438095092773, "blob_id": "00df2c264b425b4049d2ce4fdca347171ee42e17", "content_id": "fbe6d0a4adb17a00c7bdd69137bca5455289c957", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2005, "license_type": "no_license", "max_line_length": 58, "num_lines": 89, "path": "/codes/effective_python/item40/item40.py", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "class MyBaseClass:\n def __init__(self, value):\n self.value = value\n\n\nclass MyChildClass(MyBaseClass):\n def __init__(self):\n # 显式指定父类名称,如果父类改变,需改写 __init__ 方法\n MyBaseClass.__init__(self, 5)\n\n\nclass TimesTwo:\n def __init__(self):\n self.value *= 2\n\n\nclass PlusFive:\n def __init__(self):\n self.value += 5\n\n\nclass OneWay(MyBaseClass, TimesTwo, PlusFive):\n def __init__(self, value):\n MyBaseClass.__init__(self, value)\n TimesTwo.__init__(self)\n PlusFive.__init__(self)\n\n\nfoo = OneWay(5)\nprint('First ordering value is (5 * 2) + 5 = ', foo.value)\n\n\nclass AnotherWay(MyBaseClass, PlusFive, TimesTwo):\n def __init__(self, value):\n MyBaseClass.__init__(self, value)\n PlusFive.__init__(self)\n TimesTwo.__init__(self)\n\n\nbar = AnotherWay(5)\nprint('Another ordering value is ', bar.value)\n\n\n# 菱形继承\nclass TimesSeven(MyBaseClass):\n def __init__(self, value):\n MyBaseClass.__init__(self, value)\n self.value *= 7\n\n\nclass PlusNine(MyBaseClass):\n def __init__(self, value):\n MyBaseClass.__init__(self, value)\n self.value += 9\n\n\nclass ThisWay(TimesSeven, PlusNine):\n def __init__(self, value):\n TimesSeven.__init__(self, value)\n PlusNine.__init__(self, value)\n\n\nfoo = ThisWay(5)\n# 公共父类 MyBaseClass 被调用两次,第二次覆写了第一次的结果\nprint('Should be (5 * 7) + 9 = 44 but is', foo.value)\n\n\nclass TimesSevenCorrect(MyBaseClass):\n def __init__(self, value):\n super().__init__(value)\n self.value *= 7\n\n\nclass PlusNineCorrect(MyBaseClass):\n def __init__(self, value):\n super().__init__(value)\n self.value += 9\n\n\nclass GoodWay(TimesSevenCorrect, PlusNineCorrect):\n def __init__(self, value):\n super().__init__(value)\n\n\nfoo = GoodWay(5)\nprint('Should be 7 * (5 + 9) = 98 and is', foo.value)\n\nmro_str = '\\n'.join(repr(cls) for cls in GoodWay.mro())\nprint(mro_str)\n\n\n" }, { "alpha_fraction": 0.6539855003356934, "alphanum_fraction": 0.6648550629615784, "avg_line_length": 17.366666793823242, "blob_id": "63a5cf7313acd97709e3ff46189606eecba94d31", "content_id": "2d9f3c611a01d661a9a391ef7d579363c3ad8693", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 552, "license_type": "no_license", "max_line_length": 49, "num_lines": 30, "path": "/codes/effective_python/item53/block_io.py", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "import select\nimport socket\nimport time\nfrom threading import Thread\n\n\ndef slow_systemcall():\n select.select([socket.socket()], [], [], 0.1)\n\nstart = time.time()\nfor _ in range(5):\n slow_systemcall()\n\nend = time.time()\ndelta = end - start\nprint(f'Seq took {delta:.3f} seconds')\n\nstart = time.time()\nthreads = []\nfor _ in range(5):\n thread = Thread(target=slow_systemcall)\n thread.start()\n threads.append(thread)\n\nfor thread in threads:\n thread.join()\n\nend = time.time()\ndelta = end - start\nprint(f'Threads took {delta:.3f} seconds')\n\n" }, { "alpha_fraction": 0.5522388219833374, "alphanum_fraction": 0.5795308947563171, "avg_line_length": 22.928571701049805, "blob_id": "5b785d865ca796044b09d7c8a201110dff44da76", "content_id": "e00ceb710464479b7e41d024c738649ea3d3b837", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2357, "license_type": "no_license", "max_line_length": 73, "num_lines": 98, "path": "/codes/design_pattern/jd_strategy.py", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "from collections import namedtuple\n\nCustomer = namedtuple('Customer', 'name level')\npromos = []\n\n\nclass LineItem:\n\n def __init__(self, product, quantity, price):\n self.product = product\n self.quantity = quantity\n self.price = price\n\n self.total = self.price * self.quantity\n\n\nclass Order:\n\n def __init__(self, customer, cart, promotion=None):\n self.customer = customer\n self.cart = list(cart)\n self.promotion = promotion\n\n def total(self):\n if not hasattr(self, '__total'):\n self.__total = sum(item.total for item in self.cart)\n return self.__total\n\n def due(self):\n if self.promotion is None:\n discount = 0\n else:\n discount = self.promotion(self)\n return self.total() - discount\n\n def __repr__(self):\n return f'<Order total: {self.total():.2f} due: {self.due():.2f}>'\n\n\ndef promotion(promo_func):\n promos.append(promo_func)\n return promo_func\n\n\n@promotion\ndef promo_99_for_4(order):\n discount = 0\n items = order.cart\n items.sort(key=lambda a: a.price, reverse=True)\n i, total = 0, 0\n for item in items:\n if item.quantity >= 4 - i:\n total += (4 - i) * item.price\n break\n else:\n i += item.quantity\n total += item.total\n discount += total - 99\n return discount\n\n\n@promotion\ndef promo_great_than_2(order):\n discount = 0\n nums = sum(item.quantity for item in order.cart)\n if nums >= 2:\n discount += order.total() * .1\n return discount\n\n\n@promotion\ndef promo_great_than_3(order):\n discount = 0\n nums = sum(item.quantity for item in order.cart)\n if nums >= 3:\n discount += order.total() * .2\n return discount\n\n\ndef best_promo(order):\n return max(promo(order) for promo in promos)\n\n\nif __name__ == \"__main__\":\n joe = Customer('John Doe', 'plus')\n ann = Customer('Ann Smith', 'normal')\n cart = [\n LineItem('百香果', 2, 29),\n LineItem('大台芒', 3, 39),\n ]\n print(Order(joe, cart, promo_99_for_4))\n # total: 175, due: 128.00\n print(Order(joe, cart, promo_great_than_2))\n # total: 175, due: 157.50\n print(Order(joe, cart, promo_great_than_3))\n # total: 175, due: 140.00\n print(Order(joe, cart, best_promo))\n # total: 175, due: 128.00 -- best promotion\n" }, { "alpha_fraction": 0.6234676241874695, "alphanum_fraction": 0.6275539994239807, "avg_line_length": 20.148147583007812, "blob_id": "6777bf2d2767f93a76e17c97cff135606633da5c", "content_id": "c4ca0369ce4547bc0066c45ad68da546d8042bf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3508, "license_type": "no_license", "max_line_length": 63, "num_lines": 162, "path": "/codes/effective_python/item39/item39.py", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "class InputData:\n def read(self):\n raise NotImplementedError\n\n\nclass PathInputData(InputData):\n def __init__(self, path):\n super(PathInputData, self).__init__()\n self.path = path\n\n # read是实例方法多态\n def read(self):\n with open(self.path) as f:\n return f.read()\n\n\nclass Worker:\n def __init__(self, input_data):\n self.input_data = input_data\n self.result = None\n\n def map(self):\n raise NotImplementedError\n\n def reduce(self, other):\n raise NotImplementedError\n\n\nclass LineCounterWorker(Worker):\n\n # 实例方法多态\n def map(self):\n data = self.input_data.read()\n self.result = data.count('\\n')\n\n def reduce(self, other):\n self.result += other.result\n\n\nimport os\n\n\ndef generate_input(data_dir):\n for name in os.listdir(data_dir):\n # 写死了\n yield PathInputData(os.path.join(data_dir, name))\n\n\ndef create_workers(input_list):\n workers = []\n for input_data in input_list:\n # 写死了\n workers.append(LineCounterWorker(input_data))\n\n return workers\n\n\nfrom threading import Thread\n\n\ndef execute(workers):\n threads = [Thread(target=w.map) for w in workers]\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n\n first, *rest = workers\n for worker in rest:\n first.reduce(worker)\n return first.result\n\n\ndef mapreduce(data_dir):\n inputs = generate_input(data_dir)\n workers = create_workers(inputs)\n return execute(workers)\n\n\nimport random\n\n\ndef write_test_files(tmpdir):\n os.makedirs(tmpdir)\n for i in range(100):\n with open(os.path.join(tmpdir, str(i)), 'w') as f:\n f.write('\\n' * random.randint(0, 100))\n\n\ntmpdir = 'test_inputs'\nwrite_test_files(tmpdir)\n\nresult = mapreduce(tmpdir)\nprint(f\"There are {result} lines.\")\n\n\n# 类方法多态\nclass GenericInputData:\n def read(self):\n raise NotImplementedError\n\n @classmethod\n def generate_inputs(cls, config):\n raise NotImplementedError\n\n\nclass PathInputData2(GenericInputData):\n def __init__(self, path):\n super(PathInputData2, self).__init__()\n self.path = path\n\n # read是实例方法多态\n def read(self):\n with open(self.path) as f:\n return f.read()\n\n @classmethod\n def generate_inputs(cls, config):\n data_dir = config['data_dir']\n for name in os.listdir(data_dir):\n yield cls(os.path.join(data_dir, name))\n\n\nclass GenericWorker:\n def __init__(self, input_data):\n self.input_data = input_data\n self.result = None\n\n def map(self):\n raise NotImplementedError\n\n def reduce(self, other):\n raise NotImplementedError\n\n @classmethod\n def create_workers(cls, input_class, config):\n workers = []\n # 类方法多态\n for input_data in input_class.generate_inputs(config):\n workers.append(cls(input_data))\n return workers\n\n\nclass LineCounterWorker2(GenericWorker):\n\n def map(self):\n data = self.input_data.read()\n self.result = data.count('\\n')\n\n def reduce(self, other):\n self.result += other.result\n\n\ndef mapreduce2(worker_class, input_class, config):\n # 类方法多态\n workers = worker_class.create_workers(input_class, config)\n return execute(workers)\n\n\nconfig = {'data_dir': tmpdir}\nresult = mapreduce2(LineCounterWorker2, PathInputData2, config)\nprint(f\"There are {result} lines.\")\n" }, { "alpha_fraction": 0.4725848436355591, "alphanum_fraction": 0.49521324038505554, "avg_line_length": 21.979999542236328, "blob_id": "df4520b9a0aa82139d94899012024589d886b3c4", "content_id": "dc7045484bf2f679c9a02575884bf9e2dfc92950", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1459, "license_type": "no_license", "max_line_length": 70, "num_lines": 50, "path": "/codes/machine_learning/perceptron/perceptron.py", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "\"\"\"\nauthor: hangxuu@qq.com\n\n\"\"\"\n\nimport numpy as np\n\n\ndef preceptron(x_data, y_label, iter_times=1000, accuracy: float = 1):\n \"\"\"\n 感知机是二分类的线性分类模型,属于判别模型。\n f(x) = sign(w•x + b)\n 训练感知器模型,输入训练样本以及对应的分类,iter_times控制最大的迭代轮次数,accuracy为期望达到的精度\n x_data: type: m * n 矩阵\n y_label: type: m 维向量\n return: 训练得到的 w,b\n\n \"\"\"\n # m为样本个数,n为特征个数\n m, n = x_data.shape\n # 初始化w和b为0值\n w = np.zeros(n)\n b = 0\n # 学习率,控制梯度下降的速率\n alpha = 0.001\n # 最大迭代次数,精确率,当迭代次数到达最大迭代次数或者准确率到达指定精度,训练结束,返回结果\n iter_times = iter_times\n accuracy = accuracy\n\n for iter_ in range(iter_times):\n count = 0\n for i, x in enumerate(x_data):\n y = y_label[i]\n # x @ w 求x 和 w的内积\n if y * (x @ w + b) <= 0:\n w += alpha * y * x\n b += alpha * y\n count += 1\n acc = (m - count) / m\n print('Round {}'.format(iter_), end=', ')\n print('accuracy =', acc)\n if acc > accuracy:\n break\n return w, b\n\n\nif __name__ == \"__main__\":\n x = np.array([[3, 3], [4, 3], [1, 1]])\n y = np.array([1, 1, -1])\n preceptron(x, y, accuracy=0.97)\n" }, { "alpha_fraction": 0.6130191683769226, "alphanum_fraction": 0.625, "avg_line_length": 26.217391967773438, "blob_id": "32d2feb0bf37c704dc998ba507a61670a46a0aa2", "content_id": "3c725b639fc83ef21fc4efcda3f8c48036ea2d95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2850, "license_type": "no_license", "max_line_length": 97, "num_lines": 92, "path": "/codes/concurrency/download_thread.py", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "\"\"\"\nauthor: hangxuu@qq.com\n\n\"\"\"\n\nimport requests\nimport os\nimport time\nfrom concurrent.futures import ThreadPoolExecutor\nfrom concurrent import futures\n\n\nBASE_DIR = r'C:Downloads\\test'\nBASE_URL = f'https://www.example.com'\n\n\ndef save_fig(image, filename):\n if not os.path.exists(BASE_DIR):\n os.mkdir(BASE_DIR)\n path = os.path.join(BASE_DIR, filename)\n with open(path, 'wb') as f:\n f.write(image)\n print(f\"{filename} downloaded!\")\n\n\ndef get_image(alnum, num):\n url = f'{BASE_URL}{alnum}/{num}.jpg'\n resp = requests.get(url)\n return resp.content\n\n\n# 使用map需要注意,需写为单参数函数,传入元组,在函数中进行序列解包。\ndef download_one_for_multi(args):\n alnum, num = args\n filename = f'{alnum}_{num}.jpg'\n image = get_image(alnum, num)\n save_fig(image, filename)\n return filename\n\n\ndef download_many_thread(alnum, total):\n with ThreadPoolExecutor(max_workers=20) as executor:\n results = executor.map(download_one_for_multi, [(alnum, i) for i in range(1, total + 1)])\n # 结果顺序与调用顺序一致\n return results\n\n\n# 更灵活的版本,使用 submit 和 as_completed 实现。\n# 说它更灵活是因为 submit 可以调用不同的可调用对象,map 只能处理同一个可调用对象。\ndef download_many_thread2(alnum, total):\n with ThreadPoolExecutor(max_workers=20) as executor:\n to_do = []\n for i in range(1, total + 1):\n future = executor.submit(download_one_for_multi, (alnum, i))\n to_do.append(future)\n\n results = []\n for future in futures.as_completed(to_do):\n res = future.result()\n results.append(res)\n # 结果顺序与调用顺序不一致(乱序,谁先运行结束谁在前面)\n return results\n\n\ndef download_many_thread3(alnum, total):\n with ThreadPoolExecutor(max_workers=20) as executor:\n # 使用字典而不是列表\n to_do_map = {}\n for i in range(1, total + 1):\n future = executor.submit(download_one_for_multi, (alnum, i))\n to_do_map[future] = i\n\n results = []\n for future in futures.as_completed(to_do_map):\n res = future.result()\n results.append((res, to_do_map[future]))\n # 根据字典保存的信息做排序即可(这里保存的就是生成期物的顺序)。\n results = [item[0] for item in sorted(results, key=lambda a:a[1])]\n return results\n\n\nif __name__ == \"__main__\":\n\t# 示例多线程多参数传递\n alnum = '13052'\n num = 64\n start = time.time()\n # res = download_many_thread2(alnum, num) # 版本1\n # res = download_many_thread2(alnum, num) # 版本2\n res = download_many_thread3(alnum, num) # 版本3\n print(list(res))\n end = time.time()\n print(f\"Total use {end - start:.2f} seconds\")\n" }, { "alpha_fraction": 0.8098811507225037, "alphanum_fraction": 0.8098811507225037, "avg_line_length": 22.865671157836914, "blob_id": "4d9831397bf9abe9a04b1f386e1ed5eb7b9b570f", "content_id": "76fcd3043ac000a4c19e9049067e5e06b18ed147", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4241, "license_type": "no_license", "max_line_length": 138, "num_lines": 67, "path": "/notes/Designing_data-intensive_applications.md", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "# 数据密集型应用系统设计\n\n<!-- GFM-TOC -->\n\n* [一、可靠、可扩展与可维护的应用系统](#可靠、可扩展与可维护的应用系统)\n* [二、数据模型与查询语言](#数据模型与查询语言)\n* [三、数据存储与检索](#数据存储与检索)\n\n<!-- GFM-TOC -->\n\n\n## 可靠、可扩展与可维护的应用系统\n对可靠性、可扩展性与可维护性的理解。\n\n可靠性\n- 硬件故障:为硬件添加冗余。\n- 软件错误\n- 人为失误:以最小出错的方式来设计系统、分离接口、充分测试、监控系统、人员培训等。\n\n可扩展性\n- 描述负载:服务器每秒请求处理次数、聊天室同时活动用户数量、缓存命中率等。\n- 描述性能:吞吐量、服务的响应时间,通常用百分位数来表示。\n- 垂直扩展(升级到更强大的机器)与水平扩展(将负载分布到多个更小的机器)\n\n可维护性\n- 可运维性:方便运营团队来保持系统平稳运行。\n- 简单性:简化复杂度。设计抽象,可重用组件。\n- 可演化性:易于改变。简单易懂的系统往往比复杂的系统更容易修改。\n\n## 数据模型与查询语言\n\n### 关系模型与文档模型\n对于个人简历的例子,JSON表示比多表模式具有更好的局部性。如果要在关系模式中读取一份简历,那么要么执行多个查询(通过user_id查询每个表),要么在users表及其从属表之间执行混乱的多路联结。而对于JSON表示方法,所有的相关信息都在一个地方,一次查询就够了。\n\n文档模型通过支持树状结构省去了关系模型的联结操作,但其难以表示多对一以及多对多关系。\n\n多对一关系是数据规范化的结果,那么就先谈谈数据规范化。比如美国,如果个人简历中的国籍列是文本类型,那么可能有人写美国,有人写美利坚合众国或者其它名称,就会造成数据的不一致,如果以后由于某种原因,美国改名为丑国,那就得更改所有的副本。使用标准化的地理区域和行业列表,有以下优势:\n\n- 所有的简历保持样式和输入值一致。\n- 避免歧义(例如,如果存在一些同名的城市)\n- 易于更新:名字只保存在一个地方,因此,如果需要改变,可以很容易全面更新。\n- 本地化支持以及更好的搜索支持。\n\n### 关系数据库与文档数据库现状\n支持文档数据模型的主要论点是模式灵活性,由于局部性而带来较好的性能,对于某些应用来说,它更接近于应用程序所使用的数据结构。关系模型则强在联结操作、 多对一和多对多关系更简洁的表达上,与文档模型抗衡。\n\n文档模型中的模式灵活性\n\n- 读时模式:数据的结构是隐式的,只有在读取时才解释。 --文档模型\n- 写时模式:模式是显式的,并且数据库确保数据写入时都必须遵循。 --关系模型\n\n类似编程语言中的动态类型检查和静态类型检查。\n\n近些年,关系数据库和文档数据库变得越来越相近,融合关系模型与文档模型是未来数据库发展的一条很好的途径。\n\n### 图模型\n简单的多对多关系可以使用关系模型处理,但是随着数据之间的关联越来越复杂,将数据建模转化为图模型会更加自然。\n\n图由两种对象组成:顶点和边。书中介绍了图模型的属性图和三元组表示方法,这里不细说。关于图模型有一些值得注意的地方:\n- 任何顶点都可以连接到其他任何顶点。 没有模式限制哪种事物可以或不可以关联。\n- 给定某个顶点,可以高效地得到它的所有入边和出边,从而遍历图, 即沿着这些顶点链条一直向前或向后。\n- 通过对不同类型的关系使用不同的标签,可以在单个图中存储多种不同类型的信息,同时仍然保持整洁的数据模型。\n\n### 查询语言\n书中介绍了SQL、MapReduce、Cypher、SPARQL、Datalog,其中Datalog语法与prolog相似,prolog是逻辑编程语言,完全不同于C++,Haskell等命令式或函数式语言,可以学习学习以拓展思路。\n\n## 数据存储与检索\n" }, { "alpha_fraction": 0.7204968929290771, "alphanum_fraction": 0.7267080545425415, "avg_line_length": 16.88888931274414, "blob_id": "2b93b471d81b473fba953676817c80f84cca5a97", "content_id": "0b6e70181ed0e52d7e379fa5d9198a7b3a4e6d1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 223, "license_type": "no_license", "max_line_length": 35, "num_lines": 9, "path": "/notes/python最佳实践.md", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "### (1)多用 assert\n\n``` python\nassert expression [, arguments]\n# 等价于\nif not expression:\n raise AssertionError(arguments)\n```\n让程序在自己控制的条件下运行,arguments 输出一些错误原因。\n" }, { "alpha_fraction": 0.5956651568412781, "alphanum_fraction": 0.6173393130302429, "avg_line_length": 24.730770111083984, "blob_id": "afdd51182e4070e23808672300c78761dc27d75e", "content_id": "858d3e9ece4e882cc94585f8cceabdbb69da3b8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1338, "license_type": "no_license", "max_line_length": 48, "num_lines": 52, "path": "/codes/effective_python/item37/item37.py", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "from collections import namedtuple, defaultdict\n\nGrade = namedtuple('Grade', ('score', 'weight'))\n\n\nclass Subject:\n def __init__(self):\n self._grade = []\n\n def report_grade(self, score, weight):\n self._grade.append(Grade(score, weight))\n\n def average_grade(self):\n total, total_weight = 0, 0\n for grade in self._grade:\n total += grade.score * grade.weight\n total_weight += grade.weight\n return total / total_weight\n\n\nclass Student:\n def __init__(self):\n self._subjects = defaultdict(Subject)\n\n def get_subject(self, name):\n return self._subjects[name]\n\n def average_grade(self):\n total = 0\n for subject in self._subjects.values():\n total += subject.average_grade()\n return total / len(self._subjects)\n\n\nclass Gradebook:\n def __init__(self):\n self._student = defaultdict(Student)\n\n def get_student(self, name):\n return self._student[name]\n\n\nbook = Gradebook()\nalbert = book.get_student('Albert Einstein')\nmath = albert.get_subject('Math')\nmath.report_grade(75, 0.05) # test\nmath.report_grade(65, 0.15) # mid term\nmath.report_grade(70, 0.80) # final paper\ngym = albert.get_subject('Gym')\ngym.report_grade(100, 0.40) # mid term\ngym.report_grade(85, 0.60) # final\nprint(albert.average_grade())\n" }, { "alpha_fraction": 0.6069930195808411, "alphanum_fraction": 0.6121878027915955, "avg_line_length": 25.06770896911621, "blob_id": "d15c3f30a908ee402077499410226f40c3fc5c74", "content_id": "1fd54f4ea5fa6bd388b0298e9d010a220a680bb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5025, "license_type": "no_license", "max_line_length": 69, "num_lines": 192, "path": "/codes/effective_python/item63/item63.py", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "import atexit\nimport gc\nimport io\nimport time\nimport collections\nimport os\nimport random\nimport string\nimport asyncio\nfrom tempfile import TemporaryDirectory\nfrom threading import Thread\n\nrandom.seed(1234)\npolicy = asyncio.get_event_loop_policy()\npolicy._loop_factory = asyncio.SelectorEventLoop\n\n\n# Make sure Windows processes exit cleanly\ndef close_open_files():\n everything = gc.get_objects()\n for obj in everything:\n if isinstance(obj, io.IOBase):\n obj.close()\n\n\natexit.register(close_open_files)\n\n\nclass WriteThread(Thread):\n def __init__(self, output_path):\n super().__init__()\n self.output_path = output_path\n self.output = None\n self.loop = asyncio.new_event_loop()\n\n def run(self):\n asyncio.set_event_loop(self.loop)\n with open(self.output_path, 'wb') as self.output:\n self.loop.run_forever()\n\n # Run one final round of callbacks so the await on\n # stop() in another event loop will be resolved.\n self.loop.run_until_complete(asyncio.sleep(0))\n\n# Example 4\n async def real_write(self, data):\n self.output.write(data)\n\n async def write(self, data):\n coro = self.real_write(data)\n future = asyncio.run_coroutine_threadsafe(\n coro, self.loop)\n await asyncio.wrap_future(future)\n\n# Example 5\n async def real_stop(self):\n self.loop.stop()\n\n async def stop(self):\n coro = self.real_stop()\n future = asyncio.run_coroutine_threadsafe(\n coro, self.loop)\n await asyncio.wrap_future(future)\n\n# Example 6\n async def __aenter__(self):\n loop = asyncio.get_event_loop()\n await loop.run_in_executor(None, self.start)\n return self\n\n async def __aexit__(self, *_):\n await self.stop()\n\n\n# Example 1\nclass NoNewData(Exception):\n\n def __str__(self):\n return \"No New Data!\"\n\n\ndef readline(handle):\n offset = handle.tell()\n handle.seek(0, 2)\n length = handle.tell()\n\n if length == offset:\n raise NoNewData\n\n handle.seek(offset, 0)\n return handle.readline()\n\n\nasync def tail_async(handle, interval, write_func):\n loop = asyncio.get_event_loop()\n while not handle.closed:\n try:\n # 在协程里运行同步函数\n line = await loop.run_in_executor(None, readline, handle)\n except NoNewData:\n await asyncio.sleep(interval)\n else:\n await write_func(line)\n\n\nasync def run_tasks(handles, interval, output_path):\n\n async with WriteThread(output_path) as output:\n tasks = []\n for handle in handles:\n coro = tail_async(handle, interval, output.write)\n task = asyncio.create_task(coro)\n tasks.append(task)\n await asyncio.gather(*tasks)\n\n\ndef write_random_data(path, write_count, interval):\n with open(path, 'wb') as f:\n for i in range(write_count):\n time.sleep(random.random() * interval)\n letters = random.choices(\n string.ascii_lowercase, k=10)\n data = f'{path}-{i:02}-{\"\".join(letters)}\\n'\n f.write(data.encode())\n f.flush()\n\n\ndef start_write_threads(directory, file_count):\n paths = []\n for i in range(file_count):\n path = os.path.join(directory, str(i))\n with open(path, 'w'):\n # Make sure the file at this path will exist when\n # the reading thread tries to poll it.\n pass\n paths.append(path)\n args = (path, 10, 0.1)\n thread = Thread(target=write_random_data, args=args)\n thread.start()\n return paths\n\n\ndef close_all(handles):\n time.sleep(1)\n for handle in handles:\n handle.close()\n\n\ndef setup():\n tmpdir = TemporaryDirectory()\n input_paths = start_write_threads(tmpdir.name, 5)\n\n handles = []\n for path in input_paths:\n handle = open(path, 'rb')\n handles.append(handle)\n\n Thread(target=close_all, args=(handles,)).start()\n\n output_path = os.path.join(tmpdir.name, 'merged')\n # print(tmpdir, input_paths, handles, output_path)\n return tmpdir, input_paths, handles, output_path\n\n\n# Example 5\ndef confirm_merge(input_paths, output_path):\n found = collections.defaultdict(list)\n with open(output_path, 'rb') as f:\n for line in f:\n for path in input_paths:\n if line.find(path.encode()) == 0:\n found[path].append(line)\n\n expected = collections.defaultdict(list)\n for path in input_paths:\n with open(path, 'rb') as f:\n expected[path].extend(f.readlines())\n\n for key, expected_lines in expected.items():\n found_lines = found[key]\n assert expected_lines == found_lines, \\\n f'{expected_lines!r} == {found_lines!r}'\n # print(f'{expected_lines!r} == {found_lines!r}')\n\n\ntmpdir, input_paths, handles, output_path = setup()\n\nasyncio.run(run_tasks(handles, 0.1, output_path))\n\nconfirm_merge(input_paths, output_path)\n\ntmpdir.cleanup()\n" }, { "alpha_fraction": 0.6399634480476379, "alphanum_fraction": 0.6524520516395569, "avg_line_length": 28.845455169677734, "blob_id": "4def8f71822a57b53f167267c4d8aa9042743187", "content_id": "278107be4eafd8831795793696f82b9ca52cdab5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3461, "license_type": "no_license", "max_line_length": 91, "num_lines": 110, "path": "/codes/machine_learning/perceptron/titanic_prediction.py", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "\"\"\"\nauthor: hangxuu@qq.com\n\n\"\"\"\n\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import OneHotEncoder, StandardScaler\n\nfrom perceptron import preceptron\nfrom sklearn.linear_model import Perceptron\n\n\nclass DataFrameSelector(BaseEstimator, TransformerMixin):\n def __init__(self, attr_names):\n self.attr_names = attr_names\n\n def fit(self, X, y=None):\n return self\n\n def transform(self, X):\n return X[self.attr_names]\n\n\nclass MostFrequentImputer(BaseEstimator, TransformerMixin):\n def fit(self, X, y=None):\n self.most_frequent_ = pd.Series([X[c].value_counts().index[0] for c in X],\n index=X.columns)\n return self\n\n def transform(self, X):\n return X.fillna(self.most_frequent_)\n\n\ndef load_data(file_name='titanic/train.csv'):\n train_data = pd.read_csv(file_name)\n return train_data\n\n\ndef preprocessing_data(data):\n num_pipeline = Pipeline([\n (\"numetic\", DataFrameSelector([\"Age\", \"SibSp\", 'Parch', \"Fare\"])),\n (\"imputer\", SimpleImputer(strategy='median')),\n # (\"std_scaler\", StandardScaler()),\n ])\n # num_pipeline.fit_transform(data)\n cat_pipeline = Pipeline([\n (\"select_cat\", DataFrameSelector([\"Sex\", \"Pclass\", \"Embarked\"])),\n (\"imputer\", MostFrequentImputer()),\n (\"cat_encoder\", OneHotEncoder(sparse=False))\n ])\n # cat_pipeline.fit_transform(data)\n preprocess_pipeline = FeatureUnion(transformer_list=[\n (\"num_pipeline\", num_pipeline),\n (\"cat_pipeline\", cat_pipeline),\n ])\n x_data = preprocess_pipeline.fit_transform(data)\n\n return x_data\n\n\ndef train(x_data, y_label, iter_times=5000, accuracy=0.97):\n w, b = preceptron(x_data, y_label, iter_times, accuracy)\n return w, b\n\n\ndef predict(x_test, w, b):\n rst = x_test @ w + b\n rst[rst > 0] = 1\n rst[rst < 0] = 0\n rst = rst.astype(np.int64)\n return rst\n\n\ndef main():\n train_data = load_data(file_name='titanic/train.csv')\n test_data = load_data(file_name='titanic/test.csv')\n train_y_label = train_data['Survived']\n train_y_label.loc[train_y_label == 0] = -1\n train_y_label = train_y_label.values\n train_data_preprocess = preprocessing_data(train_data)\n test_data_preprocess = preprocessing_data(test_data)\n w, b = preceptron(train_data_preprocess, train_y_label, iter_times=1000, accuracy=0.75)\n ans = predict(test_data_preprocess, w, b)\n result = pd.DataFrame({\"PassengerId\": test_data['PassengerId'], \"Survived\": ans})\n print(result)\n result.to_csv('my_submission.csv', index=False)\n # 最终得分0.73684\n # 精确度最后也就到0.73左右,说明该数据集并非线性可分,用感知机模型会出现欠拟合。\n\n # sklearn Perceptron,得分0.62左右。\n clf = Perceptron()\n clf.fit(train_data_preprocess, train_y_label)\n ans = clf.predict(test_data_preprocess)\n ans[ans > 0] = 1\n ans[ans < 0] = 0\n ans = ans.astype(np.int64)\n result = pd.DataFrame({\"PassengerId\": test_data['PassengerId'], \"Survived\": ans})\n print(result)\n result.to_csv('my_submission.csv', index=False)\n\n # 这么看来自己实现的模型比sklearn实现的效果好?哈哈,当然不敢这么说。这个数据集数据还是太少!\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6805482506752014, "alphanum_fraction": 0.6905640363693237, "avg_line_length": 32.85714340209961, "blob_id": "ec69c72e1d847a392b16e82d9d325f87771d2093", "content_id": "b7deebfb3695e2db9aa31b402dec4f6b01f1acd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2702, "license_type": "no_license", "max_line_length": 150, "num_lines": 56, "path": "/notes/the_linux_command_line.md", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "# The Linux Command Line\n\n<!-- GFM-TOC -->\n\n* [一、learning the shell](#learning-the-shell)\n\n\n<!-- GFM-TOC -->\n\n## learning the shell\n\n### exploring the system\n- df:查看磁盘使用情况。\n- pwd:打印当前工作目录。\n- cd:修改工作目录。``cd``回到个人主目录,``cd -``回到上一个工作目录,``cd ~usrename``切到 username 的个人主目录。\n- file:``file filename`` determine a file’s type.\n- less:``less filename`` Viewing File Contents, ``q`` to exit.\n- ls: ``ls -a`` 列出所有文件,包括隐藏文件。 ``ls -d`` 列出目录。 ``ls -lh`` 组合长格式,human-readable。``ls --reverse``输出逆序显式。\n- cp: copy files and dictionaries\n- mv: move/rename files and dictionaries\n- mkdir: Create directories \n- rm: Remove files and directories \n- ln: Create hard and symbolic links\n\n软链接和硬链接的区别:软链接可以链接目录和文件,硬链接只能链接文件;硬链接相当于引用计数,每创建一个硬链接,对该文件的引用加一,之后无论是删除硬链接还是删除原文件,对该文件(内存块)的引用减一,当引用为0时系统删除该文件。软链接则相当于指针(独立于原文件的特殊文件),当原文件删除后,软链接就会失效。\n\n### commands\ncommand有四种不同的类型:(1)一个可执行程序,(2)shell builtins,(3)shell function,(4)an alias 别名。\n- type: Display a Command’s Type, 上述四种之一。\n- which\n- help\n- man\n- apropos\n- info\n- whatis: Display one-line manual page descriptions.\n- alias: Create an alias for a command. for example, ``alias foo='cd /home; ls'``.\n\n### redirection\n- cat: Concatenate files. ``cat filename1 filename2 > filename``, ``&>, &>>``.\n- sort: Sort lines of text. 用于管道\n- uniq: Report or omit repeated lines. 用于管道\n- grep: Print lines matching a pattern. ``grep 0*.jpg`` 打印所有以0开头,.jpg结尾的文件名。``-i 忽略大小写``\n- wc: Print newline, word, and byte counts for each file. ``-l 只打印行数``\n- head: Output the first part of a file. ``-n 打印前 n 行``\n- tail: Output the last part of a file. ``-n 打印后 n 行, -f 实时查看日志文件时使用``.\n- tee: Read from standard input and write to standard output and files. 用于把管道中间的结果保存到文件。\n\n\n### Permissions\n\n- chmod: 修改文件/文件夹权限。常用:7 (rwx), 6 (rw-), 5 (r-x), 4 (r--), and 0 (---).\n\n### Processes\nlinux启动过程:1. BIOS开机自检。2. 启动引导过程。3. 加载内核及函数模块。4. 调用init进程。5. 登录。\n\n常用命令:ps, top, jobs, bg, fg, kill, killall, shutdown\n\n" }, { "alpha_fraction": 0.6584380269050598, "alphanum_fraction": 0.6814559698104858, "avg_line_length": 26.66974449157715, "blob_id": "ec9b4642ba3245affcca30370704a3ad01467c48", "content_id": "6ee61590b8a845ed83a05890bc6faac271607d2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 41949, "license_type": "no_license", "max_line_length": 361, "num_lines": 975, "path": "/notes/Effective_Python_Notes.md", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "# Effective Python Notes\n\n<!-- GFM-TOC -->\n* [一、Pythonic](#Pythonic)\n* [二、列表和字典](#列表和字典)\n* [三、函数](#函数)\n* [四、推导式与生成器](#推导式与生成器)\n* [五、类和接口](#类和接口)\n* [七、并发与并行](#并发与并行)\n* [八、鲁棒性与性能](#鲁棒性与性能)\n<!-- GFM-TOC -->\n\n## Pythonic\n\n### (1)弄清你的python版本\n\n``` python\n# in terminal\npython --version \n# or \npython3 --version\n# in code\nimport sys\nprint(sys.version_info)\n# or\nprint(sys.version)\n```\n\n这条建议的目的是:**确保机器执行程序的python版本和你预期的为同一版本。** 可以在程序中加层保障,比如该程序需要python3.6及以上版本才可以执行,那么可在程序开头加上以下代码:\n\n``` python\nimport sys\nassert sys.version_info >= (3, 6)\n\n```\n\n这样,当机器执行的python版本小于3.6时就会报``AssertionError``异常。此时,你可能需要做的就是安装合适版本的python解释器。\n\n### (2)PEP8规范\n\n代码风格请遵循PEP8规范,这样可以写出更好看以及更易懂的代码。具体内容请参阅 [官方文档](https://www.python.org/dev/peps/pep-0008/) 。\n\n### (3)弄清楚bytes和str的区别\n\n- bytes存的是8位无符号值,str存的是Unicode码位。str是给人看的,bytes是给机器看的。\n- 把码位转换为字节序列的过程是编码,把字节序列转换为码位的过程是解码。\n- Unicode三明治:尽早将bytes解码为Unicode,尽晚将Unicode编码为bytes。在程序中只使用Unicode字符。\n- 不对外部数据编码做任何假设,读/写文件时请显式指定编码。\n\n代码示例:\n\n``` python\nIn [18]: a = b'hello world'\n# a为ASCII编码的字节序列\nIn [19]: list(a)\nOut[19]: [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]\n\nIn [20]: b = 'hello world'\n# b为Unicode码位\nIn [21]: list(b)\nOut[21]: ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']\n\n# 字节序列 --> 码位(解码,显式指定编码)\nIn [22]: list(a.decode(encoding='utf-8'))\nOut[22]: ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']\n\n# 码位 --> 字节序列(编码,显式指定编码)\nIn [23]: list(b.encode(encoding='utf-8'))\nOut[23]: [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]\n```\n读写文件示例:\n``` python\nwith open(filename, 'r', encoding='utf-8') as f:\n # deal with f\n\nwith open(filename, 'w', encoding='utf-8') as f:\n f.write('some Unicode string')\n```\n如果要直接读写二进制文件,则将'r', 'w' 相应换为 'rb', wb'即可。\n\n### (4)字符串格式化(F-string)\n\npython提供了四种格式化字符串方法。\n\n1. C 风格的 % 格式\n2. format函数\n3. str.format()方法\n4. F-string\n\n有人喜欢用第一种,有人喜欢用第三种(比如我),而作者推荐用第四种。我的建议是选择一种用熟练就行,推荐第四种F-string。\n因为F-string可以少打很多字。\n示例:\n``` python\nIn [1]: key = 'my_val'\n\nIn [2]: value = 1.2345\n\n# C 风格 % 格式\nIn [3]: s1 = '%-10s = %.2f' % (key, value)\n\nIn [4]: s1\nOut[4]: 'my_val = 1.23'\n\n# str.format()函数\nIn [5]: s2 = '{:<10} = {:.2f}'.format(key, value)\n\nIn [6]: s2\nOut[6]: 'my_val = 1.23'\n\n# F-string格式\nIn [7]: s3 = f'{key:<10} = {value:.2f}'\n\nIn [8]: s3\nOut[8]: 'my_val = 1.23'\n```\n可以看出F-string和前两种方法最大的区别就是前两种方法对变量没有直接访问权,需要在格式化字符串中设置占位符,然后通过位置参数(也支持键值对参数)将变量值传递进去。而F-string对同作用域的变量有直接访问权。\n\n以下示例可能更能说明这一点。\n``` python\n# 自定义字符串处理函数,大小写相间。\nIn [24]: def personality(s):\n ...: new_s = ''\n ...: for i in range(len(s)):\n ...: if i % 2:\n ...: new_s += s[i].upper()\n ...: else:\n ...: new_s += s[i].lower()\n ...: return new_s\n \nIn [25]: s = 'hello'\n\nIn [26]: s1 = '%s world' % personality(s)\n\nIn [27]: s1\nOut[27]: 'hElLo world'\n\nIn [28]: s2 = '{} world'.format(personality(s))\n\nIn [29]: s2\nOut[29]: 'hElLo world'\n\nIn [32]: s3 = f'{personality(s)} world'\n \nIn [33]: s3\nOut[33]: 'hElLo world'\n```\nF-string可以直接在格式化字符串中执行我的自定义函数。\n\n另外,如果你最终在三种方法中选择了F-string,千万别忘了F-string的 ``f``前缀。\n\n### (5)使用辅助函数代替复杂的表达式\n\n如果发现某条表达式变得复杂难懂或者重复多次时(DRY:Don't repeat youself),就应该将该处逻辑分离出来编写为小函数。这样做的好处有:\n\n1. 代码更清晰易懂。\n2. 代码可复用。\n\n### (6)使用序列解包完成多变量赋值\n\n先看一下python实现的冒泡排序。\n``` python\ndef bubble_sort(lst):\n for _ in range(len(lst)):\n for i in range(1, len(lst)):\n if lst[i] < lst[i-1]:\n # 数据交换\n lst[i], lst[i-1] = lst[i-1], lst[i]\n```\n如果采用C风格方式编写,则是如下代码:\n``` python\ndef bubble_sort(lst):\n for _ in range(len(lst)):\n for i in range(1, len(lst)):\n if lst[i] < lst[i-1]:\n # 数据交换\n tmp = lst[i]\n lst[i] = lst[i-1]\n lst[i-1] = tmp\n```\n它们的区别就在于数据交换部分。C语言风格的语法需要一个临时变量``tmp``来保存中间结果以完成交换。而python则使用 **序列解包** 省掉了这个临时变量。使代码量更少且可读性高。\n\n原理: **其实序列解包也用到了临时变量,具体说是临时元组。序列解包先计算赋值号右侧,将计算结果保存到一个临时元组中,然后将这个临时元组再赋值给赋值号左侧。这就是``a, b = b, a``能正常工作的原因。**\n\n序列解包除了用于多变量赋值,也常用于``for``循环中。例:\n``` python\npersons = [('taylor', 29), ('hans', 25), ('bob', 12)]\n\n# 序列解包\nfor name, age in persons:\n print(f'{name} is {age} years old')\n```\n直接对列表``persons``里的元素进行解包,赋予它们更有意义的变量名,可以让程序更易读。避免写成下面这样:\n``` python\nfor item in persons:\n name = item[0]\n age = item[1]\n print(f'{name} is {age} years old')\n```\n\n### (7)多使用 enumerate 而不是 range\n\n如果你同时需要可迭代序列(如list)的索引和元素值,那么可以用``enumerate``代替``range``来提高可读性。\n``` python\n# 使用range\nfor i in range(len(lst)):\n print(f'{i + 1} item is {lst[i]}')\n \n# 使用enumerate\nfor i, item in enumerate(lst, start=1):\n print(f'{i} item is {item}')\n```\n``enumerate``可以指定索引的起始值(``start``参数,默认为0),如果需要从1开始计数,后续就省掉了加1的操作。\n\n### (8)使用zip同步处理多个可迭代序列(如list)\n\n对于两个(或多个)有相关性的可迭代序列(它们的序列长度是相同的)。我们可以用某一个序列的长度来做``for``循环的``range``参数,这样不会出错,但可读性差。使用``zip``函数可以提高可读性。如下例所示:\n\n``` python\nIn [5]: names = ['Cecilia', 'Lise', 'Marie']\n\nIn [6]: counts = [len(item) for item in name]\n\nIn [7]: for i in range(len(names)):\n ...: print(f'{names[i]}: {counts[i]}')\n ...:\nCecilia: 7\nLise: 4\nMarie: 5\n\nIn [8]: for name, count in zip(names, counts):\n ...: print(f'{name}: {count}')\n ...:\nCecilia: 7\nLise: 4\nMarie: 5\n```\n``zip``函数以两个或多个可迭代对象作为参数,返回一个生成器,该生成器每次生成以参数中每一个可迭代对象的下一个值组成的元组。\n\n值得注意的是,如果``zip``函数的参数序列长度不相同,则``zip``函数返回元组项的个数和参数中最短的序列元素个数相同。如果需要元组项个数和参数中最长的序列元素个数相同,则可以使用``itertools.zip_longest``函数。如下例所示:\n```python\nIn [33]: names.append('Taylor swift')\n \nIn [34]: for name, count in zip(names, counts):\n ...: print(f'{name}: {count}')\n ...:\nCecilia: 7\nLise: 4\nMarie: 5\n# 输出没有 Taylor swift\n\nIn [35]: import itertools\n\nIn [36]: for name, count in itertools.zip_longest(names, counts):\n ...: print(f'{name}: {count}')\n ...:\nCecilia: 7\nLise: 4\nMarie: 5\nTaylor swift: None\n```\n当参数中较短的可迭代对象耗尽时,将使用``fillvalue``关键字参数的提供的值(默认为``None``)作为它们的填充值。\n\n### (9)避免在``for/while``循环后直接使用``else``代码块\n\n先说一句,这个语法我还是蛮常用的。并不觉得会产生什么歧义。当循环正常结束时会执行``else``代码块,否则不执行(比如循环中途``break``出来)。\n\n当你需要在循环中寻找某个东西,只有当整个循环都没有找到时才执行某些操作。就很符合这个应用场景。这种场景下一般``for``循环里会有``if``代码块,``if``代码块里会有``break``语句,当执行了``if``代码块(``if``的条件为真)程序就会``break``出循环。和普通的``if/else``语法一样,当执行了``if``块,就不会执行``else``块。只不过这块是多个``if``对应一个``else``,只有当所有循环都没有执行``if``块时,才会执行``else``块。举个简单的例子,假如你想在姓名列表中找到第一个姓名长度大于5的姓名并打印输出,如果找不到则打印``Not found``。你可以这样写:\n```python\nfor name in names:\n if len(name) > 5:\n print(name)\n break\nelse:\n print('Not Found')\n```\n作者提供了两种替换写法。\n\n第一种:(作者在这里耍了小心机,替换了需求,把打印输出改成了直接作为返回值返回。)\n```python\nfor name in names:\n if len(name) > 5:\n return name\nreturn 'Not Found'\n```\n\n第二种还是可以接受的,在``for``循环之前为变量设置默认值来省掉``else``子句:\n```python\nrst_output = 'Not found'\nfor name in names:\n if len(name) > 5:\n rst_output = name\n break\nprint(rst_output)\n```\n你可以根据自己喜好选择``for/else``或作者提供的第二种替代写法。\n\n### (10)海象运算符(:=)的使用场景\n\n这是我想要很久的语法了!终于在python3.8加了进来!它可以减少很多重复代码或重复计算。话不多说,先看第一个应用场景。\n```python\n# 最接近的三数之和 leetcode 16.\n# 题目中需要维护一个所有三元组之和与target值的最小距离(绝对值最小),最后返回这个距离最小的三元组之和\n# diff是维护的最小距离\n\n# 方法一(重复计算)\nif abs(three_sum - target) < diff:\n diff = abs(three_sum - target)\n \n# 方法二(可读性差,distance只会在if代码块中用到,定义在if代码块上面感觉是个更大作用域的变量)\ndistance = abs(three_sum - target)\nif distance < diff:\n diff = distance\n \n# 海象运算符(:=)\nif (distance := abs(three_sum - target)) < diff:\n diff = distance\n```\n一般大家写代码的时候都会直接把计算写进条件语句,而不是提前想到之后可能会用到计算结果,然后先计算把结果保留,再用结果做条件判断(大多数人是懒得做这个预判的)。而且能这样写就说明有很大可能计算结果除了做条件判断在其他地方不会用到。所以我一般是先写成普通条件语句,后面发现会用到计算结果再把其改为海象运算符格式。\n\n海象运算符(:=)先执行赋值操作,把右侧表达式计算结果赋值给左侧变量,然后以左侧变量计算条件语句真假。因为海象运算符的优先级低于比较运算符,所以如果左侧变量是条件语句的一部分,则需要给海象运算符的操作加上括号以得到预期的结果。\n\n海象运算符还可用于实现C语言中``do/while``功能。这也是它的第二个应用场景。直接贴作者的例子吧。\n```python\nfresh_fruit = pick_fruit() \nwhile fresh_fruit: \n for fruit, count in fresh_fruit.items(): \n batch = make_juice(fruit, count) \n fresh_fruit = pick_fruit()\n```\n上面的代码在进入循环之前需要先进行一次计算。使用海象运算符可以这样写:\n```python\nwhile fresh_fruit := pick_fruit(): \n for fruit, count in fresh_fruit.items(): \n batch = make_juice(fruit, count)\n```\n把计算本身放到条件语句中,而不是只把计算结果放到条件语句中。\n\n## 列表和字典\n\n### (11)Know How to Slice Sequences\npython列表切片方法很多,使用时记住以下要点:\n1. ``a[start: end]``包含``start``,不含``end``,也就是``[start, end)``左闭右开区间。\n2. ``need = lst[:4]``好于``need = lst[0:4]``,``need = lst[4:]``好于``need = lst[4:len(lst)]``。即如果从开头开始取元素或者取到最后一个元素,则可以省略掉相应的``0``或者``len(lst)``。\n3. 可以使用``b = a[:]``来获得数组``a``的一份拷贝。\n\n### (12)Avoid Striding and Slicing in a Single Expression\n``lst[start:end:stride]``在区间``[start, end)``中每隔``stride``个元素取一个元素,结果是一个列表。\n这条建议不要同时使用这三个参数,并且``stride``尽量不要取负值。以提高代码的可读性。\n\n### (13)Prefer Catch-All Unpacking Over Slicing\n\n使用``*expression``表达式来获取序列所有剩余值。而不要使用下标硬编码。使用示例:\n```python\nIn [1]: lst = [1,2,3,4,5,6,7,8,9]\n\nIn [2]: one, two, *other = lst\n\nIn [3]: print(one, two, other)\n1 2 [3, 4, 5, 6, 7, 8, 9]\n# starred expression 可以放在任意位置。\nIn [4]: one, *other, nine = lst\n\nIn [5]: print(one, nine, other)\n1 9 [2, 3, 4, 5, 6, 7, 8]\n```\n\n### (14)Sort by Complex Criteria Using the key Parameter\n\n这个平时已经用的非常熟练了,就放两个例子:\n```python\nitems = [(34, 'taylor'),\n (43, 'bob'),\n (23, 'hans'),\n (43, 'will')]\n\n# 按姓名升序,按年龄逆序\nitems.sort(key=lambda a: (a[1], -a[0]))\n\n# 按姓名逆序,按年龄升序\nitems.sort(key=lambda a: a[0])\nitems.sort(key=lambda a: a[1], reverse=True)\n\n```\n对于多标准排序,如果可以用元组直接实现,就直接实现。实在不行再用多个``sort``。因为``sort``是稳定的,因此可以这样干。但要记住:``sort``调用的顺序和排序标准的顺序相反。\n\n### (15)Be Cautious When Relying on dict Insertion Ordering\n\n从python3.7之后,字典会保持元素的插入顺序(和 ``collections.OrderedDict`` 功能类似)。但为了兼容性,如果你需要保持元素的插入顺序,还是应该先考虑 ``OrderedDict``。\n\n这节知道了 ``mypy`` 静态类型检查器(需pip安装),可以强制进行类型检查。例子:\n```python\n# hello.py\ndef hello(name: str) -> None:\n print(f\"hello {name}\")\n \nhello(23)\n\n# terminal\n> python3 -m mypy --strict hello.py\nhello.py:6: error: Argument 1 to \"hello\" has incompatible type \"int\"; expected \"str\"\nFound 1 error in 1 file (checked 1 source file)\n```\n\n强制做类型检查的话,有类型错误会直接报错,而不会运行程序。\n\n### (16)Prefer get Over in and KeyError to Handle Missing Dictionary Keys\n用 ``get`` 处理键不存在的情况,不要用 ``setdefault`` 。如果一定要用 ``setdefault`` 的功能,请用 ``defaultdict`` 代替。\n\n### (17)Prefer defaultdict Over setdefault to Handle Missing Items in Internal State\n看一下 ``defaultdict`` 和 ``setdefault`` 的区别:\n```python\n# setdefault\nclass Visits1:\n def __init__(self):\n self.data = {}\n\n def add(self, country, city):\n self.data.setdefault(country, set()).add(city)\n \n# defaultdict\nfrom collections import defaultdict\nclass Visits2:\n def __init__(self):\n self.data = defaultdict(set)\n\n def add(self, country, city):\n self.data[country].add(city)\n```\n看出来了吗?对于 ``set`` 的使用,一个是函数(``defaultdict``),一个是函数调用(``setdefault``),这也就是说,对于``Visits1``,每一次调用``add``都会生成一个``set``对象,而``Visits2``则只有在需要时才会创建对象。所以一般情况下 ``defaultdict`` 会比 ``setdefault`` 快一些。如果你是字典的创建者,遇到它们符合的应用场景,请选择 ``defaultdict`` 。\n\n### (18)Know How to Construct Key-Dependent Default Values with ``__missing__``\n根据特定的 key 生成特定的 value,这一点 defaultdict 无法做到。因为它只能接受无参数函数。想要完成这个功能,你可以定义 dict 的实现 ``__missing__`` 方法的子类,该方法接收 key 作为参数,生成一个特定的 value, 然后把该项插入字典, 最后返回 value。\n\n```python\nclass Pictures(dict):\n def __missing__(self, key):\n value = generate_value(key) # 该函数根据 key 生成特定 value\n self[key] = value # 该项存入字典\n return value\n```\n\n## 函数\n\n### (19)Never Unpack More Than Three Variables When Functions Return Multiple Values\n\n当函数返回多个值(元组)时,函数调用方(自己或他人)可以直接对返回值进行序列解包。但如果元组项超过三个,就不要直接返回元组了,定义一个结果类或者 ``namedtuple`` 进行返回,调用方会更清晰,避免产生难找的 bug 。\n\n### (20)Prefer Raising Exceptions to Returning None\n\n当 None 有特殊含义时,就不要默默的返回 None 了,这时应该写好文档(任何时候都该写好文档),报异常给调用方,让调用方来处理。下例是一个定义完好的函数该有的长相。\n```python\ndef careful_divide(a: float, b: float) -> float:\n \"\"\"Divides a by b\n\n Raises:\n ValueError: When the input cannot be divided.\n \"\"\"\n try:\n return a / b\n except ZeroDivisionError as e:\n raise ValueError(\"Invalid inputs\")\n```\n\n### (21)Know How Closures Interact with Variable Scope\n\n函数A内部构建了函数B,函数B加上函数B内部使用的函数A的局部变量就构成了一个闭包。这是从函数式编程来的概念。比如下面的 Haskell 函数,``genIfEven`` 函数的参数 ``f`` 被 lambda 表达式捕获,此时这个 lambda 就是一个闭包,即 ``genIfEven`` 函数返回一个闭包。\n```haskell\ngenIfEven f = (\\x -> ifEven f x)\n```\n到了python中,用法也是一样的,请看下例:\n```python\ndef sort_priority(values, group):\n found = False\n\n def helper(x):\n nonlocal found\n if x in group:\n found = True\n return 0, x\n return 1, x\n values.sort(key=helper)\n return found\n\nnumbers = [5, 4, 32, 7, 6, 1, 2]\ngroup = {7, 5}\nsort_priority(numbers, group)\n\n```\n\n``helper`` 函数和 ``found``,``group`` 变量一起就构成了一个闭包。``helper`` 函数可以直接访问 ``sort_priority`` 函数的变量,但如果要赋值(改变变量的值),就需要给被赋值的变量做 ``nonlocal`` 声明(因为作用域原因,如果不声明,python 会把其解释为下定义,即新定义了一个局部变量)。\n\n其实闭包更多是上面 Haskell 例子中的那种用法,即作为返回值使用。把上面的 python 例子修改一下如下:\n```python\ndef sort_priority(group):\n def helper(x):\n if x in group:\n return 0, x\n return 1, x\n return helper\n\nnumbers = [5, 4, 32, 7, 6, 1, 2]\ngroup = {7, 5}\nrule = sort_priority(group) # rule 即是一个闭包\nnumbers.sort(key=rule)\n```\n为了程序的可读性,闭包还是少用为妙。\n\n### (22)Reduce Visual Noise with Variable Positional Arguments\n\n对于多个可选参数,使用可变位置参数(\\*args),以减少视觉污染。一个可选参数的话,还是直接用默认值吧(args=None)。需要说明的是,可选位置参数在传入函数之前会被转化为元组,所以不要传入生成器!\n\n带可变位置参数的函数定义大概长这个样子:\n```python\ndef func(name, *values):\n if not values:\n print(f\"Hello {name}\")\n else:\n val_str = ' '.join(str(item) for item in values)\n print(f\"hello {val_str}\")\n```\n\n### (23)Provide Optional Behavior with Keyword Arguments\n当你需要为已有函数添加新功能的时候,可以添加关键字参数,这样不会影响原来使用该函数的代码。简单的修改可以这么干,如果修改很多,我建议还是不要动原函数,重新封装一个函数为妙。\n\n### (24)Use None and Docstrings to Specify Dynamic Default Arguments\n\n函数的默认参数只会在模块加载时计算一次。所以不要使用动态值做函数的默认值(例如 ``[], {}, datetime.now()``)!应该使用 ``None`` 代替!\n\n这个其实没什么说的,编程时养成良好的习惯即可。\n\n### (25)Enforce Clarity with Keyword-Only and Positional-Only Arguments\n\n强制使用位置参数和关键字参数来降低程序耦合性。以下面函数签名示例:\n```python\ndef safe_division_e(numerator, denominator, /, ndigits=10, *, \n ignore_overflow=False, ignore_zero_division=False):\n pass\n```\n对 ``/`` 前的参数,调用方只能以位置参数提供。``*`` 之后的参数调用方只能以关键字参数的形式提供。``/`` 与 ``*`` 之间的参数和普通函数一样,既可以以位置参数也可以以关键字参数给出。\n\n\n### (26)Define Function Decorators with functools.wraps\n\n什么是装饰器?装饰器本质上就是一次函数调用,它在模块加载时执行。可以用来实现参数检查,函数注册,添加日志等等功能。如果需要根据不同场景实现不同功能,可以使用带参数的装饰器(或使用装饰器内部变量),返回的函数中使用了这个参数,即可根据不同参数实现不同的功能。这实际上就是返回了一个闭包(见item21)。而闭包就是一个带状态的函数。\n```python\nimport functools\n\ndef trace(func):\n i = 0\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n nonlocal i\n result = func(*args, **kwargs)\n i += 1\n print(f\"{' '*i}{func.__name__}({args!r}, {kwargs!r}) -> {result!r}\")\n return result\n return wrapper\n\n@trace\ndef fibonacci(n):\n if n in (0, 1):\n return n\n return fibonacci(n - 1) + fibonacci(n - 2)\n```\n使用 ``functools.wraps`` 定义装饰器,能把原函数的元数据(``metadata``)保留。而你确实应该这么做。\n\n## 推导式与生成器\n\n### (27)Use Comprehensions Instead of map and filter\n列表推导式,太常用就不多费笔墨了。\n\n### (28)Avoid More Than Two Control Subexpressions in Comprehensions\n同上。当列表推导式变得复杂(超过两个 ``for/if`` 表达式),应该用普通的 ``for/if`` 进行替换,以提高程序的可读性。\n\n### (29)Avoid Repeated Work in Comprehensions by Using Assignment Expressions\n\n把海象运算符用到推导式里,也是为了避免重复计算。但是要尽量避免将其用到条件语句外的其他语句,这样会引起变量名泄露(和 for 语句一样)。见下例:\n```python\nIn [1]: doubled = [(half := item * 2) for item in range(5)]\n# half 变量泄漏到外层作用域\nIn [2]: half\nOut[2]: 8\nIn [4]: for item in range(5):\n ...: print(item)\n ...:\n0\n1\n2\n3\n4\n# item 变量泄漏到 for 循环外部\nIn [5]: item\nOut[5]: 4\n```\n\n### (30)Consider Generators Instead of Returning Lists\n\n生成器有很多好处:1. 对于大的输入输出而言,节省内存。2. 通常需要更少的行数来完成普通函数相同的功能。但缺点也很明显:生成器是有状态的,不能重用。这点有时会导致 bug。而且如果调用者需要整个列表才能开始工作,这时使用生成器也是没有意义的,还是得调用者把生成器显示转化为列表才能进行下一步。\n\n建议:对于可以构造成 pipeline 的函数组(类似生产者-消费者模型),使用生成器函数,否则使用普通函数。\n\n### (31)Be Defensive When Iterating Over Arguments\n\n(30)说了,生成器是有状态的,不能重用。所以当把生成器作为参数传入函数时,如果函数体内需要多次迭代该参数,就会导致错误。这里使用生成器,主要是为了节省内存,对于数据不大的情况,还是直接使用列表语义更清晰。但如果到了非省内存不可的情况,也还是有解决办法的。就是不使用简单的生成器,而是实现自己的可迭代容器类型(实现了迭代器协议的容器类就是可迭代容器。list 就是一种可迭代容器类型)。如下例:\n```python\nclass ReadVisits:\n def __init__(self, data_path):\n self.data_path = data_path\n \n def __iter__(self):\n with open(self.data_path) as f:\n for line in f:\n yield int(line)\n```\n上面说的复杂,其实,把类的 ``__iter__``方法实现为生成器即实现了迭代器协议。此时该类就是一个可迭代容器类。容器类的使用方法如下例所示:\n```python\nfrom collections.abc import Iterator\n\ndef nomalize(numbers):\n if isinstance(numbers, Iterator):\n raise TypeError('Must supply a container!')\n total = sum(numbers)\n result = []\n for value in numbers:\n percent = 100 * value / total\n result.append(percent)\n return result\n\nvisits = ReadVisits(file_path)\npercentages = nomalize(visits)\nassert sum(percentages) == 100.0\n```\n上面 ``normalize`` 函数保证传入的参数必须是容器类型,如果传入了普通的迭代器,就会引发异常。\n\n### (32)Consider Generator Expressions for Large List Comprehensions\n如题,对于大的列表推导式,可以用生成器表达式替代。只需把 ``[]`` 换成 ``()`` 就行。这样可以节省内存。但要记住,生成器是有状态的!\n\n### (33)Compose Multiple Generators with yield from\n如果需要组合多个生成器,请使用 ``yield from`` 。\n\n### (34)Avoid Injecting Data into Generators with send\n函数中如果需要动态值,不要使用 ``send`` 和 ``yield`` 实现,用迭代器来实现。**迭代器是有状态的,这一点有时也能为我们所用!** \n\n### (35)Avoid Causing State Transitions in Generators with throw\n```python\nclass Timer: \n def __init__(self, period): \n self.current = period \n self.period = period\n \n def reset(self): \n self.current = self.period\n\n def __iter__(self): \n while self.current: \n self.current -= 1 \n yield self.current\n```\n如上例,不要用``throw``做状态转换,通过把``__iter__``方法实现成闭包,以及提供一个状态转换方法(``reset``)来实现状态转换。\n\n### (36)Consider itertools for Working with Iterators and Generators\n``itertools``里的函数按功能主要分为三类:\n1. Linking Iterators Together: ``chain, repeat, cycle, tee, zip_longest``\n2. Filtering Items from an Iterator: ``islice, takewhile, dropwhile, filterfalse``\n3. Producing Combinations of Items from Iterators: ``accumulate, product, permutations, combinations, combinations_with_replacement``\n\n使用示例:\n```python\nIn [5]: import itertools\n\nIn [6]: it = itertools.chain([1,2,3], [4,5,6])\n\nIn [7]: print(list(it))\n[1, 2, 3, 4, 5, 6]\n\nIn [8]: it = itertools.repeat('hello', 3)\n\nIn [9]: print(list(it))\n['hello', 'hello', 'hello']\n\nIn [10]: it = itertools.cycle([1, 2])\n\nIn [11]: result = [next(it) for _ in range(10)]\n\nIn [12]: result\nOut[12]: [1, 2, 1, 2, 1, 2, 1, 2, 1, 2]\n\nIn [13]: it1, it2 = itertools.tee(['first', 'second'], 2)\n\nIn [14]: print(list(it1))\n['first', 'second']\n\nIn [15]: print(list(it2))\n['first', 'second']\n\nIn [16]: keys = ['one', 'two', 'three']\n\nIn [17]: values = [1, 2]\n\nIn [18]: it = itertools.zip_longest(keys, values, fillvalue='nope')\n\nIn [19]: print(list(it))\n[('one', 1), ('two', 2), ('three', 'nope')]\n```\n其它例子就不贴了,主要是看个眼熟,多用就记住了。\n\n## 类和接口\n\n### (37)Compose Classes Instead of Nesting Many Levels of Built-in Types\n当你的程序中出现内置数据类型的嵌套,比如,字典里套字典。就应该考虑用多个自定义类(或 namedtuple)来实现了。\n\n用类虽然代码行数可能增加了,但可读性也得到了明显的提升。\n\n### (38)Accept Functions Instead of Classes for Simple Interfaces\n\n用函数做接口,如果想顺便完成其他功能,可以利用函数的副作用来实现。建议使用实现了 ``__call__`` 方法的类(可调用对象),而不要使用闭包。\n示例见 [count_missing](https://github.com/hangxuu/Notes-and-Blog/tree/master/codes/effective_python/item38/item38.py) 。当然,也是为了可读性。\n\n### (39)Use @classmethod Polymorphism to Construct Objects\n使用 ``@classmethod`` 定义类的替代构造函数。(构造函数多态,C++中一个类可以有多个构造函数,但python只有一个 ``__init__``,可以通过类方法定义多个构造函数。)\n\n示例见 [map_reduce](https://github.com/hangxuu/Notes-and-Blog/tree/master/codes/effective_python/item39/item39.py) 。\n\n### (40)Initialize Parent Classes with super\n使用 ``super`` 初始化父类。\n\n不使用 super ,显式调用父类构造函数时,父类初始化顺序与父类构造函数调用顺序保持一致,而与继承顺序无关。对于菱形继承,公共父类构造函数会被调用2次。\n\n理解 python MRO(方法解析顺序)。\n\n\n\n## 并发与并行\n\n### (52)使用``subprocess``模块管理子进程\n\n如果需要在python脚本中执行系统命令,可以用``os``模块,比如执行``os.system('cd /; ls')``。现在推荐使用``subprocess``模块来完成这些功能。\n```python\nIn [35]: import subprocess\n\nIn [36]: result = subprocess.run(['echo', 'hello word'], capture_output=True, encoding='utf-8')\n\nIn [37]: print(result.stdout)\nhello word\n\n```\n等有需求再来具体学习这个模块吧。\n\n### (53)Use Threads for Blocking I/O, Avoid for Parallelism\n\nGIL:全局解释器锁。\n\nCpython执行python程序分为两步:1,把源程序翻译成字节码;2,使用基于堆栈的解释器运行字节码(字节码解释器的状态必须在python程序运行时保持一致)。GIL是互斥锁,以防止Cpython受到抢占式多线程的影响。\n\nGIL带来了很大的副作用,它让并行计算变的不可能。因为Cpython解释器只能用一个CPU核心。(可以用``concurrent.futures``实现真并行)\n\n那么为什么python还要支持多线程呢?1,至少Cpython可以保证公平地运行你的各个线程。2,多线程可以处理阻塞I/O(比如读写文件)。这是因为当陷入系统调用时,python解释器会释放GIL,当系统调用返回时它再重新获得GIL。\n\n### (54)Use Lock to Prevent Data Races in Threads\n\n虽然python有GIL,但如果你在程序中使用多个线程访问同一个数据变量,还是可能会发生数据争用(Cpython保证公平运行你的各个线程,它可能在任意时候执行线程切换)。\n\n使用``Lock``类(互斥锁)来保证各个线程对共享数据对象访问/修改的原子性。\n\n示例:\n```python\nclass Counter:\n def __init__(self):\n self.count = 0\n\n def increment(self, offset):\n self.count += offset\n\nfrom threading import Lock\n\nclass LockingCounter:\n def __init__(self):\n self.lock = Lock()\n self.count = 0\n\n def increment(self, offset):\n with self.lock:\n self.count += offset\n```\n在``Counter``类中,``self.count += offset``不是原子操作。``LockingCounter``类中,使用``with self.lock``对``with``语句代码块上锁后,``self.count += offset``就有原子性了,此时可以保证多线程中数据的一致性。\n\n### (55)Use Queue to Coordinate Work Between Threads\n\n上一节(item 54)强调原子性,多个线程访问同一数据对象,要保证一个线程对数据的修改不会被另一个线程所破坏。该节不仅要求原子性,还增加了顺序性。比如必须线程A先把数据写入共享数据对象,线程B才能正常工作。这样的一系列线程就构成了一条``pipeline``。你可以用锁``Lock``和忙等待来保证原子性和顺序性。但会有几个问题:\n\n1. 忙等待浪费CPU运算。比如生产者-消费者问题,如果生产者速度很慢,那么消费者就要等待生产者生产数据,这里的等待一般是忙等待。\n2. 内存溢出风险。还是生产者-消费者问题,如果生产者速度很快,那么消费者来不及消耗。生产者生产的数据就会随着时间推移越来越多,直至耗尽内存。\n\n使用``Queue``可以解决上述问题。当``Queue``为空时,它的``get``方法会被阻塞----解决忙等待;可以初始化``Queue``时指定缓冲区大小----解决内存溢出。\n\n使用``Queue``实现生产者-消费者问题:\n```python\nfrom queue import Queue\nfrom threading import Thread\n\n# 缓冲区大小为10,当my_queue.qsize() == 10时,阻塞put方法\nmy_queue = Queue(10)\n\ndef consumer():\n i = 0\n while True:\n my_queue.get()\n print(f\"Consuming item {i}.\")\n my_queue.task_done() # 对每一个item调用task_done()\n i += 1\n if i == 100:\n break\n\ndef producer():\n i = 0\n while True:\n print(f\"Producing item {i}\")\n my_queue.put(i)\n i += 1\n if i == 100:\n # 假设只生产100个元素,则 i == 100时任务完成\n print('Producer done')\n break\n\nthread_consumer = Thread(target=consumer)\nthread_consumer.start()\nthread_producer = Thread(target=producer)\nthread_producer.start()\n\nmy_queue.join() # 只有消费者消费每个item后都调用了task_done(),这里join才会解除阻塞。也就是说,一旦my_queue.join()执行,任务就一定完成了。下面的 thread_consumer.join() 甚至是多余的。\nthread_consumer.join()\nthread_producer.join()\nprint(f\"my_queue size: {my_queue.qsize()}\")\n```\n\n### (56)Know How to Recognize When Concurrency Is Necessary\n以下5节(56 - 60)说的是一个主题。\n- **fan-out** 生成新的并发单元。\n- **fan-in** 等待现有的并发单元执行完成。\n\n### (57)Avoid Creating New Thread Instances for On-demand Fan-out\n\n- 线程的缺点。频繁的创建浪费时间,大量的线程浪费内存。\n- 多线程难于调试。\n\n### (58)Understand How Using Queue for Concurrency Requires Refactoring\n\n使用``Queue``能解决一些问题。比如可以控制总的线程数量(避免无限``fan-out``,但也降低了并发的灵活性)。但同时需要做大量的代码重构。\n\n### (59)Consider ThreadPoolExecutor When Threads Are Necessary for Concurrency\n\n使用``ThreadPoolExecutor``(线程池)可以只做少量代码重构就能完成``Queue``的功能。但同时存在``Queue``的缺点--提前限制了线程总数,降低了并发的灵活性。\n\n### (60)Achieve Highly Concurrent I/O with Coroutines\n\n协程是以上四节的解决方案。协程使用``async/await``关键字定义。支持同时运行成千上万个并发单元,却没有线程的时间和空间开销。\n\n### (61)Know How to Port Threaded I/O to asyncio\n\n这节作者举了个例子把一个多线程阻塞IO程序修改成了协程异步IO版本。主要说明``with``,``for`` 等一些语言特性都有对应的异步版本。两个脚本见[number_guess.py](https://github.com/hangxuu/Notes-and-Blog/tree/master/codes/effective_python/item61/number_guess.py) 和 [asnyc_number_guess.py](https://github.com/hangxuu/Notes-and-Blog/tree/master/codes/effective_python/item61/asnyc_number_guess.py),对比两个脚本,理解每处``async/await``的使用方法。\n\n### (62)Mix Threads and Coroutines to Ease the Transition to asyncio\n\n通过混合使用线程和协程来一步步把多线程阻塞IO代码重构为协程异步IO代码。\n\n通过例子学习:\n- 多线程版本 [item62.py](https://github.com/hangxuu/Notes-and-Blog/blob/master/codes/effective_python/item62/item62.py)\n- 多线程协程混合版本 [item62_mixed.py](https://github.com/hangxuu/Notes-and-Blog/blob/master/codes/effective_python/item62/item62_mixed.py)\n- 协程版本 [item62_asyncio.py](https://github.com/hangxuu/Notes-and-Blog/blob/master/codes/effective_python/item62/item62_asyncio.py)\n\n### (63)Avoid Blocking the asyncio Event Loop to Maximize Responsiveness\n\n避免阻塞客户代码与 asyncio 事件循环共用的唯一线程。在 item62 的例子中,与输出文件相关的操作在主线程的事件循环中调用。而这些操作都是阻塞型的(访问本地文件系统会阻塞)。所以,当执行这些系统调用时,整个程序都会被阻塞,浪费不必要的CPU算力。\n```python\nasync def run_tasks(handles, interval, output_path):\n with open(output_path, 'wb') as output:\n\n async def write_async(data):\n output.write(data)\n ......\n```\n解决方法:``asyncio`` 的事件循环在背后维护着一个`` ThreadPoolExecutor`` 对象,我们可以调用 ``run_in_executor`` 方法,把可调用的对象发给它执行。对于简单的情形,这种做法已经够用。如果情形复杂(如本例,``open`` ,`` write``等操作并未封装在某个函数内,而使分散在各处),则可以按该节作者示例:定义自己的``Thread``子类,在自己的线程中完成所有这些耗时的系统调用,以不影响主线程的正常运行。\n\n书中示例代码见: [item63.py](https://github.com/hangxuu/Notes-and-Blog/blob/master/codes/effective_python/item63/item63.py)\n\n\n### (64)Consider concurrent.futures for True Parallelism\n\n多线程或者协程都只是对IO密集型应用的优化。它们仍受制于GIL,只能使用一个CPU核心。对于CPU密集型应用,我们需要同时使用多个CPU核心,实现真并行。\n\n有以下三个选择,使用优先级由高至低:\n1. ``concurrent.futures`` 的 ``ProcessPoolExecutor`` 类。\n2. ``multiprocessing`` 模块。\n3. 编写C扩展实现计算部分。\n\n当进程间需要交互的数据越少,以及每个进程的计算量都比较大的时候,多进程才能带来比较大的性能提升(毕竟进程间数据传输也是需要时间的)。\n\n示例代码见:[item64.py](https://github.com/hangxuu/Notes-and-Blog/blob/master/codes/effective_python/item64/item64.py)\n\n## 鲁棒性与性能\n\n### (65)Take Advantage of Each Block in try/except/else/finally\n每个功能块的作用如下:\n- ``try``: 执行可能会发生异常的语句(一般是自己能想到的异常)。\n- ``except``: ``try`` 中发生异常时执行。捕捉 ``try`` 中发生的异常,处理掉或者传到上游函数。\n- ``else``: ``try`` 中没有异常发生时执行。把不会引起异常的代码和 ``try/except`` 分开,程序功能更清晰,也更好排查是 ``try`` 中哪一句引发了异常。\n- finally:无论如何都会执行。一般做最后的清理工作。\n\n### (66)Consider contextlib and with Statements for Reusable try/finally Behavior\n\n``with``语句可以方便简洁地实现``try/finally``的功能。如下例:\n```python\nfrom threading import Lock\n\nlock = Lock()\n\n# with statement\nwith lock:\n # do something\n \n \n# try/finally statement\n\nlock.acquire()\ntry:\n # do something\nfinally:\n lock.release()\n```\n使用``with``语句程序更清晰,``with lock``通俗点说就是:在我得到锁的语境下,干接下来的一系列事情。除了内置支持 ``with`` 的函数和类外,我们也可以自定义支持 ``with`` 的函数和类。类的话我们是在类中实现``__enter__``, ``__exit__``这两个魔法方法。对于函数,我们可以使用 ``contextlib``模块的``contextmanager``装饰器。\n\n示例如下:\n```python\nfrom contextlib import contextmanager\n\n@contextmanager \ndef debug_logging(level): \n logger = logging.getLogger() \n old_level = logger.getEffectiveLevel() \n logger.setLevel(level) \n try:\n yield \n finally: \n logger.setLevel(old_level)\n```\n这里 ``yield`` 没有返回值。所以我们只能这样使用它:\n```python\nwith debug_logging(logging.DEBUG):\n # do something\n```\n就是说我们只能在这个上下文语境中做一些事,而不能直接与这个上下文交互。其实我们更常这样使用 ``with``:\n```python\nwith open(filename, 'w', encoding='utf-8') as f:\n f.write('something')\n```\n我们不止需要打开文件,更主要的是我们需要对文件进行操作。这就需要我们定义的函数在 ``yield`` 处返回值,而返回的值就赋给了 ``as`` 后面的变量。 \n```python\n@contextmanager \ndef log_level(level, name): \n logger = logging.getLogger(name) \n old_level = logger.getEffectiveLevel() \n logger.setLevel(level) \n try:\n yield logger \n finally: \n logger.setLevel(old_level)\n```\n这里 ``yield`` 处返回了我们设置了安全级别的 ``logger`` 对象,这样我们在该语境下就可以使用它来写日志而不影响整体日志的安全等级,而上面那个函数则修改的是整体日志的安全等级。有了返回值,我们就可以这样写了:\n```python\nwith log_level(logging.DEBUG, 'my_log') as mylogger:\n mylogger.debug(\"debug info, this will print\") # 只修改 mylogger 的安全等级\n logging.debug(\"This will not print\") # 全局 logging 不受影响\n```\n\n### (67)Use datetime Instead of time for Local Clocks\n\n" }, { "alpha_fraction": 0.5824176073074341, "alphanum_fraction": 0.5994005799293518, "avg_line_length": 19.040000915527344, "blob_id": "8451b01ddfdacdee14dc0d5ed5828088e89089c6", "content_id": "aee8f75e4d43883bea02dd7b8b2c75b453b8fa04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1001, "license_type": "no_license", "max_line_length": 50, "num_lines": 50, "path": "/codes/effective_python/item38/item38.py", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "from collections import defaultdict\n\ncurrent = {'green': 12, 'blue': 3}\nincrements = [('red', 3),\n ('blue', 17),\n ('orange', 9)\n ]\n\n\n# closure\ndef count_missing(current, increments):\n added_count = 0\n\n def missing():\n nonlocal added_count\n added_count += 1\n return 0\n\n result = defaultdict(missing, current)\n for key, amount in increments:\n result[key] += amount\n\n return result, added_count\n\n\nresult, count = count_missing(current, increments)\nassert count == 2\n\n\n# class with __call__\nclass CountMissing:\n def __init__(self):\n self.count = 0\n\n def __call__(self, *args, **kwargs):\n self.count += 1\n return 0\n\n\ndef count_missing_2(current, increments):\n counter = CountMissing()\n result = defaultdict(counter, current)\n for key, amount in increments:\n result[key] += amount\n\n return result, counter.count\n\n\n_, count = count_missing_2(current, increments)\nassert count == 2" }, { "alpha_fraction": 0.5803667902946472, "alphanum_fraction": 0.6051779985427856, "avg_line_length": 21.609756469726562, "blob_id": "ee3977b9bf25b7c3b0033601fc2925c3f0dbd7de", "content_id": "605c272f7895c229aeba66accddd0e84b377fb0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1089, "license_type": "no_license", "max_line_length": 101, "num_lines": 41, "path": "/codes/effective_python/item55/producer_and_consumer.py", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "from queue import Queue\nfrom threading import Thread\nimport time\n# 缓冲区大小为10,当my_queue.qsize() == 10时,阻塞put方法\nmy_queue = Queue(10)\n\n\ndef consumer():\n i = 0\n while True:\n my_queue.get()\n print(f\"Consuming item {i}.\")\n my_queue.task_done() # 对每一个item调用task_done()\n i += 1\n if i == 100:\n break\n\n\ndef producer():\n i = 0\n while True:\n print(f\"Producing item {i}\")\n my_queue.put(i)\n i += 1\n if i == 100:\n # 假设只生产100个元素,则 i == 100时任务完成\n print('Producer done')\n break\n\n\nthread_consumer = Thread(target=consumer)\nthread_consumer.start()\nthread_producer = Thread(target=producer)\nthread_producer.start()\n\n\nmy_queue.join() # 只有所有item都调用了task_done(),join才会解除阻塞。也就是说,一旦my_queue.join()执行,任务就一定完成了。下面两句甚至是多余的。\n# thread_consumer.join()\n# thread_producer.join()\ntime.sleep(1)\nprint(f\"my_queue size: {my_queue.qsize()}\")\n" }, { "alpha_fraction": 0.4735126197338104, "alphanum_fraction": 0.596576988697052, "avg_line_length": 24.020408630371094, "blob_id": "f2d413489356b3892524653fdbd61936f0c4e463", "content_id": "b0d7d8c2bd9306f616df24ea23e30bd9d50e5577", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1231, "license_type": "no_license", "max_line_length": 71, "num_lines": 49, "path": "/codes/effective_python/item64/item64.py", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "import time\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\n\nNUMBERS = [ (1963309, 2265973), (2030677, 3814172), (1551645, 2229620),\n (2039045, 2020802), (1823712, 1924928), (2293129, 1020491),\n (1281238, 2273782), (3823812, 4237281), (3812741, 4729139),\n (1292391, 2123811),\n] * 10\n\n\n# 暴力GCD\ndef gcd(pair):\n a, b = pair\n low = min(a, b)\n for i in range(low, 0, -1):\n if a % i == 0 and b % i == 0:\n return i\n\n\ndef main():\n start = time.time()\n results = list(map(gcd, NUMBERS))\n end = time.time()\n delta = end - start\n print(f\"Token {delta:.3f} seconds\")\n\n\ndef main_thread():\n start = time.time()\n with ThreadPoolExecutor(max_workers=8) as executor:\n results = list(executor.map(gcd, NUMBERS))\n end = time.time()\n delta = end - start\n print(f\"Thread token {delta:.3f} seconds\")\n\n\ndef main_process():\n start = time.time()\n with ProcessPoolExecutor(max_workers=8) as executor:\n results = list(executor.map(gcd, NUMBERS))\n end = time.time()\n delta = end - start\n print(f\"Processing token {delta:.3f} seconds\")\n\n\nif __name__ == \"__main__\":\n main()\n main_thread()\n main_process()\n\n" }, { "alpha_fraction": 0.55708909034729, "alphanum_fraction": 0.5621079206466675, "avg_line_length": 17.113636016845703, "blob_id": "a14123738bb3c4af2bcc014f2f52cbd33bbc9a9b", "content_id": "9a841efceef9f02f673eb5fdf8b2f1b4b5e10df8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 827, "license_type": "no_license", "max_line_length": 71, "num_lines": 44, "path": "/codes/concurrency/spinner_thread.py", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "import threading\nimport itertools\nimport time\n\n\nclass Signal:\n go = True\n\n\ndef spin(msg, signal):\n for ch in itertools.cycle('|/-\\\\'):\n status = ch + ' ' + msg\n # \\r:将光标回退到本行的开头位置\n print(status, flush=True, end='\\r')\n time.sleep(.1)\n if not signal.go:\n print(' ' * len(status), end='\\r')\n break\n\n\ndef slow_function():\n # 模拟IO\n time.sleep(3)\n return 42\n\n\ndef supervisor():\n signal = Signal()\n spinner = threading.Thread(target=spin, args=(\"Thinking!\", signal))\n print(f\"Spinner object: {spinner}\")\n spinner.start()\n result = slow_function()\n signal.go = False\n spinner.join()\n return result\n\n\ndef main():\n result = supervisor()\n print(f\"Answer: {result}\")\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6214740872383118, "alphanum_fraction": 0.6305732727050781, "avg_line_length": 19.370370864868164, "blob_id": "58b1b56656fee5f27c01585db574bcd88988efc3", "content_id": "15b5e0005dfebaef1cd9d53c4b62194bd1fe16a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1099, "license_type": "no_license", "max_line_length": 63, "num_lines": 54, "path": "/codes/effective_python/item54/lock_usage.py", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "from threading import Thread, Lock\n\nclass Counter:\n def __init__(self):\n self.count = 0\n\n def increment(self, offset):\n self.count += offset\n\n\nclass LockingCounter:\n def __init__(self):\n self.lock = Lock()\n self.count = 0\n\n def increment(self, offset):\n with self.lock:\n self.count += offset\n\n\ndef worker(sensor_index, how_many, counter):\n for _ in range(how_many):\n counter.increment(1)\n\n\nhow_many = 10**5\ncounter = Counter()\nthreads = []\nfor i in range(5): \n thread = Thread(target=worker, args=(i, how_many, counter))\n threads.append(thread) \n thread.start()\n\nfor thread in threads: \n thread.join()\n\nexpected = how_many * 5 \nfound = counter.count \nprint(f'Counter should be {expected}, got {found}')\n\n\ncounter = LockingCounter()\nthreads = []\nfor i in range(5): \n thread = Thread(target=worker, args=(i, how_many, counter))\n threads.append(thread) \n thread.start()\n\nfor thread in threads: \n thread.join()\n\nexpected = how_many * 5 \nfound = counter.count \nprint(f'Counter should be {expected}, got {found}')" }, { "alpha_fraction": 0.6197771430015564, "alphanum_fraction": 0.6281337141990662, "avg_line_length": 20.117647171020508, "blob_id": "6495c5f1a98aee102af0a23cbba084c720a0a612", "content_id": "728ff421dba5acc2cbfdcaa92134342513579cb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1466, "license_type": "no_license", "max_line_length": 71, "num_lines": 68, "path": "/codes/concurrency/download_asyncio.py", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "\"\"\"\nauthor: hangxuu@qq.com\n\n\"\"\"\n\nimport os\nimport time\nimport asyncio\nimport aiohttp\n\nimport atexit\nimport gc\nimport io\n\n\n# Make sure Windows processes exit cleanly\ndef close_open_files():\n everything = gc.get_objects()\n for obj in everything:\n if isinstance(obj, io.IOBase):\n obj.close()\n\n\natexit.register(close_open_files)\n\n\nBASE_DIR = r'C:\\Downloads\\test'\nBASE_URL = f'https://www.example.com'\n\n\ndef save_fig(image, filename):\n if not os.path.exists(BASE_DIR):\n os.mkdir(BASE_DIR)\n path = os.path.join(BASE_DIR, filename)\n with open(path, 'wb') as f:\n f.write(image)\n print(f\"{filename} downloaded!\")\n\n\nasync def get_image_asy(alnum, num):\n url = f'{BASE_URL}{alnum}/{num}.jpg'\n async with aiohttp.request('GET', url) as resp:\n assert resp.status == 200\n image = await resp.read()\n return image\n\n\nasync def download_one_asy(alnum, num):\n image = await get_image_asy(alnum, num)\n save_fig(image, f'{alnum}_{num}.jpg')\n return num\n\n\nasync def download_many_asy(alnum, total):\n start = time.time()\n to_do = [download_one_asy(alnum, cc) for cc in range(1, total + 1)]\n await asyncio.gather(*to_do)\n end = time.time()\n print(f'Single thread uses {end - start} seconds')\n print('Job done')\n return total\n\n\nif __name__ == \"__main__\":\n # 为了示例多参数传递(两个参数)\n alnum = '13052'\n num = 64\n asyncio.run(download_many_asy(alnum, num))\n" }, { "alpha_fraction": 0.5955811738967896, "alphanum_fraction": 0.6051872968673706, "avg_line_length": 19.431371688842773, "blob_id": "4ba850a94b1486ff118d537adb3e53fec892921a", "content_id": "b778d0db1d2497c94aff1d0a99a84fed833ddabd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1041, "license_type": "no_license", "max_line_length": 49, "num_lines": 51, "path": "/codes/concurrency/download_normal.py", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "\"\"\"\nauthor: hangxuu@qq.com\n\n\"\"\"\n\nimport requests\nimport os\nimport time\n\nBASE_DIR = r'C:\\Downloads\\test'\nBASE_URL = f'https://www.example.com'\n\n\ndef save_fig(image, filename):\n if not os.path.exists(BASE_DIR):\n os.mkdir(BASE_DIR)\n path = os.path.join(BASE_DIR, filename)\n with open(path, 'wb') as f:\n f.write(image)\n print(f\"{filename} downloaded!\")\n\n\ndef get_image(alnum, num):\n url = f'{BASE_URL}{alnum}/{num}.jpg'\n resp = requests.get(url)\n return resp.content\n\n\ndef download_one(alnum, num):\n filename = f'{alnum}_{num}.jpg'\n image = get_image(alnum, num)\n save_fig(image, filename)\n return filename\n\n\ndef download_many(alnum, total):\n results = []\n for i in range(1, total + 1):\n filename = download_one(alnum, i)\n results.append(filename)\n return results\n\n\nif __name__ == \"__main__\":\n alnum = '13052'\n num = 64\n start = time.time()\n res = download_many(alnum, num)\n print(list(res))\n end = time.time()\n print(f\"Total use {end - start:.2f} seconds\")" }, { "alpha_fraction": 0.6942317485809326, "alphanum_fraction": 0.7049515247344971, "avg_line_length": 30.85365867614746, "blob_id": "4a051eef03bdce5e9f57d12afe5c360d0b303b75", "content_id": "62c02aa5f27a851ddb24e4ea86b4e7ed33fb5242", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4048, "license_type": "no_license", "max_line_length": 420, "num_lines": 123, "path": "/notes/6_null.md", "repo_name": "hangxuu/Notes-and-Blog", "src_encoding": "UTF-8", "text": "# 6.NULL - The Missing Semester of Your CS Education\n[课程主页](https://missing.csail.mit.edu/)\n\n## The Shell\n注:没按官方题号组织。\n### Exercises\n2. Create a new directory called missing under /tmp.\n```bash\nmkdir /tmp/missing\n```\n\n\n3. Use touch to create a new file called semester in missing.\n```bash\ncd /tmp/missing\ntouch semester\n```\n\n\n4. write \n\n```bash\n#!/bin/sh\ncurl --head --silent https://missing.csail.mit.edu\n```\n\ninto the file and try to execute the file.\n\n```bash\nsh semester # ok\n./semester # permission denied 需给该文件执行权限\nchmod 777 semester # 给了所有权限\n./semester # ok\n```\n\nshebang 的作用,shell 通过它寻找执行该脚本程序的位置。\n\n\n5. Use | and > to write the “last modified” date output by semester into a file called last-modified.txt in your home directory.\n\n```bash\n./semester | grep --ignore-case last-modified | cut --delimiter=' ' -f2- > /home/last-modified.txt\n```\n\n6. Write a command that reads out your laptop battery’s power level or your desktop machine’s CPU temperature from /sys\n\n```bash\n# linux on winsows. battery's power\ncat /sys/class/power_supply//battery/capacity\n# 没找到 CPU 温度\n```\n\n## Shell Tools\n- In general, in shell scripts the space character will perform argument splitting. \n- trings delimited with ' are literal strings and will not substitute variable values whereas \" delimited strings will.\n- ``$0``: Name of the script\n- ``$1 - $9``: Arguments to the script. ``$1`` is the first argument and so on.\n- ``$@``: All the arguments\n- ``$#``: Number of arguments\n- ``$?``: Return code of the previous command\n- ``$$``: Process identification number (PID) for the current script\n- ``!!``: Entire last command, including arguments. A common pattern is to execute a command only for it to fail due to missing permissions; you can quickly re-execute the command with sudo by doing sudo !!\n- ``$_``: Last argument from the last command.\n- The return code or exit status is the way scripts/commands have to communicate how execution went. A value of 0 usually means everything went OK; anything different from 0 means an error occurred.\n- command substitution. ``for file in $(ls)``\n- process substitution, ``<( CMD )``, This is useful when commands expect values to be passed by file instead of by STDIN. ``diff <(ls foo) <(ls bar)``\n\n### Exercises\n1. Read man ls and write an ls command that lists files in the following manner\n- Includes all files, including hidden files.\n- Sizes are listed in human readable format (e.g. 454M instead of 454279954)\n- Files are ordered by recency\n- Output is colorized\n\n```bash\nls -lath --color=auto\n```\n\n2. Write bash functions marco and polo that do the following. Whenever you execute marco the current working directory should be saved in some manner, then when you execute polo, no matter what directory you are in, polo should cd you back to the directory where you executed marco. For ease of debugging you can write the code in a file marco.sh and (re)load the definitions to your shell by executing source marco.sh.\n\n```bash\n\nmarco(){\n export MARCO=$(pwd)\n}\n\npolo(){\n cd \"$MARCO\"\n}\n\n```\n\n3. Say you have a command that fails rarely. In order to debug it you need to capture its output but it can be time consuming to get a failure run. Write a bash script that runs the following script until it fails and captures its standard output and error streams to files and prints everything at the end. Bonus points if you can also report how many runs it took for the script to fail.\n\n```bash\n# random.sh\nn=\"$(( RANDOM % 100 ))\"\nif [[ n -eq 42 ]]; then\n echo \"Something went wrong\"\n >&2 echo \"The error was using magic numbers\"\n exit 1\nfi\necho \"Everything went according to plan\"\n\n```\ncount.sh 为本题答案。\n\n```bash\n# count.sh\ncount=0\nwhile true; do\n ./random.sh &> out.txt\n if [[ \"$?\" -eq 1 ]]; then\n break\n fi\n #echo \"$count\"\n count=$(( count + 1))\ndone\necho \"$count runs before it fails\"\ncat out.txt\n```\n\n4. " } ]
25
YilinWphysics/Assignments
https://github.com/YilinWphysics/Assignments
3b4b812bc0b2e023dec7072f807680693dbb53f8
8940bb2d40f0831543dd1e3ce4bc26481b2cd0e3
5d0a94411b0cc14b4dbed468fb97840b8bf48c51
refs/heads/master
2022-03-28T23:55:07.429737
2019-12-10T01:28:47
2019-12-10T01:28:47
208,935,577
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5795454382896423, "alphanum_fraction": 0.6148989796638489, "avg_line_length": 28.037036895751953, "blob_id": "31fb46fd6c842df525656bbe79e293abd7691bae", "content_id": "6c32ff0e4693a52aab369b72063934b3e76514a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 792, "license_type": "no_license", "max_line_length": 93, "num_lines": 27, "path": "/Nbody_project/SecondPart.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "from functions import * \n\n\nsummary = open(\"Summary.txt\", \"a\")\n\n\n################### Question 1 ####################\nn=int(2) # numbers of particle \ngrid_size = 500 \nsoften = 10 \nmass = 5\nv_x = [0,0] # initial v in x-direction \nv_y = [0.1,-0.1] # initial v in y-direction \n\nsystem = Particles(mass, v_x, v_y, n, grid_size, soften, orbit=True)\ndt = 5\nfig = plt.figure()\nax = fig.add_subplot(111, autoscale_on = False, xlim = (0, grid_size), ylim = (0, grid_size))\nparticles_plot , = ax.plot([], [], \"*\")\ndef animation_plot(i):\n\tglobal system, ax, fig, dt\n\tsystem.evolve(dt)\n\tparticles_plot.set_data(system.loc[:,0], system.loc[:,1])\n\treturn particles_plot, \n\ngif = anmt.FuncAnimation(fig, animation_plot, frames = 500, interval = 10) \ngif.save(\"Question2.gif\", writer = \"imagemagick\")\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6859338283538818, "alphanum_fraction": 0.6959572434425354, "avg_line_length": 45.06153869628906, "blob_id": "f5ba453887b7981d16b9ed70022a244e61241820", "content_id": "3b08dc1d41180b4856c5a7501ff7807ff14ee4fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2993, "license_type": "no_license", "max_line_length": 197, "num_lines": 65, "path": "/Assignment1/Question3.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "import numpy as np \n\ndef simpsons_rule(func, a, func_a, b, func_b): \n\t# evaluating integral between x=a and x=b using Simpson's rule\n\t# h is the midpoint between a and b \n\th = (a+b)/2\n\tfunc_h=func(h)\n\tsimpson_integral=(np.abs(b-a)/6) * (func_a+4*func_h+func_b)\n\treturn h, func_h, simpson_integral\n\ndef recursive_simpson(func, a, func_a, b, func_b, err, total_int, h, func_h, count=0): \n\t# Evaluating the left part (from a to h) of the integral using Simpson's rule: \n\tleft_h, left_func_h, left_int=simpsons_rule(func, a, func_a, h, func_h)\n\t# Evaluating the right part (from h to b) of the integral using Simpson's rule: \n\tright_h, right_func_h, right_int=simpsons_rule(func, h, func_h, b, func_b)\n\tdelta=left_int+right_int-total_int\n\t# criterion for determining when to stop subdividing an interval - when delta < 15*err \n\tif np.abs(delta)<=15*err:\n\t\treturn total_int, count\n\telse: \n\t\treturn recursive_simpson(func, a, func_a, h, func_h, err/2, left_int, left_h, left_func_h, count+1)+recursive_simpson(func, h, func_h, b, func_b, err/2, right_int, right_h, right_func_h, count+1)\n\ndef adaptive_simpsons(func, a, b, err):\n\tfunc_a, func_b = func(a), func(b)\n\th, func_h, total_int = simpsons_rule(func, a, func_a, b, func_b)\n\tintegral = recursive_simpson(func, a, func_a, b, func_b, err, total_int, h, func_h)\n\tcount = np.sum(integral[1::2])\n\tintegral = np.sum(integral[0::2])\n\treturn integral, count\n\n# testing the adaptive Simpson's rule with a few typical examples: \ntest_err = 1e-8\nlower_bound=-3\nupper_bound=5\nexp_integral, exp_count = adaptive_simpsons(np.exp, lower_bound, upper_bound, test_err)\n\nsin_integral, sin_count = adaptive_simpsons(np.sin, lower_bound, upper_bound, test_err)\n\ncos_integral, cos_count = adaptive_simpsons(np.cos, lower_bound, upper_bound, test_err)\n\ndef slope2(x):\n\treturn 2*x\n\ny_2x_integral, y_2x_count = adaptive_simpsons(slope2, lower_bound, upper_bound, test_err)\n\nprint(f\"Testing for an exponential function, the integral between x={lower_bound} and \"\n + f\"x={upper_bound}, with an error tolerance of {test_err} gives a value of \"\n + f\"{exp_integral}, in {exp_count} iterations.\")\n\nprint(f\"Testing for a sine function, the integral between x={lower_bound} and \"\n + f\"x={upper_bound}, with an error tolerance of {test_err} gives a value of \"\n + f\"{sin_integral}, in {sin_count} iterations.\")\n\nprint(f\"Testing for a cosine function, the integral between x={lower_bound} and \"\n + f\"x={upper_bound}, with an error tolerance of {test_err} gives a value of \"\n + f\"{cos_integral}, in {cos_count} iterations.\")\n\nprint(f\"Testing for y=2x, the integral between x={lower_bound} and \"\n + f\"x={upper_bound}, with an error tolerance of {test_err} gives a value of \"\n + f\"{y_2x_integral}, in {y_2x_count} iterations.\")\n\n\n\"\"\" This methods calls upon the input function twice, whereas the in-class method \ncalls upon the input function three times. Therefore, this method reduces calling upon \nthe input function by a raito of 5/2 \"\"\"" }, { "alpha_fraction": 0.593805730342865, "alphanum_fraction": 0.627452552318573, "avg_line_length": 28.854721069335938, "blob_id": "b87d509092c9a9e3b81b8579f35a29b479e918d1", "content_id": "8792dbdb85bbd107ea6d0999688ced5de3ac5512", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12334, "license_type": "no_license", "max_line_length": 199, "num_lines": 413, "path": "/Assignment5/Assignment5.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nimport scipy.interpolate\n\nsummary=open(\"Summary.txt\", \"w\")\n#Q1_saveprint=open(\"Q1_saveprint.txt\", \"w\")\n#Q2_saveprint=open(\"Q2_saveprint.txt\", \"w\")\n\n\n#################### Question 1 #############################\n\nn=400#arbitrary, grid size is n*n\nconv_criterion=1e-2 #convergence criteria \nite=int(1e6) # maximum number of iterations \n\nx = np.arange(n)\ny = np.arange(n)\nxx, yy = np.meshgrid(x, y)\ncx, cy, r = n//2, n//2, 40 # defining centre of circle to be at the centre of the grid; radius 10\ncondition = (xx-cx)**2+(yy-cy)**2 <=r**2\n\n\nV=np.zeros([n,n])\nbc=0*V\n\nmask=np.zeros([n,n],dtype='bool')\nmask[:,0]=True\nmask[:,-1]=True\nmask[0,:]=True\nmask[-1,:]=True\nmask[condition]=True \nbc[condition]=1 #arbitrarily defined potential of the cylinder \n\nV=bc.copy()\n\n# one relaxation step taken on the boundary condition\nb=-(bc[1:-1,0:-2]+bc[1:-1,2:]+bc[:-2,1:-1]+bc[2:,1:-1])/4.0 \n\n\n# evolving the relaxation technique by one iteration: \ndef relaxation_one_step(V, bc, mask):\n V[1:-1,1:-1]=(V[1:-1,0:-2]+V[1:-1,2:]+V[:-2,1:-1]+V[2:,1:-1])/4.0\n V[mask]=bc[mask]\n return V \n\ndef Ax(V,mask):\n #Vuse=np.zeros([V.shape[0]+2,V.shape[1]+2])\n #Vuse[1:-1,1:-1]=V\n Vuse=V.copy()\n Vuse[mask]=0\n ans=(Vuse[1:-1,:-2]+Vuse[1:-1,2:]+Vuse[2:,1:-1]+Vuse[:-2,1:-1])/4.0\n ans=ans-V[1:-1,1:-1]\n return ans\n\ndef pad(A):\n AA=np.zeros([A.shape[0]+2,A.shape[1]+2])\n AA[1:-1,1:-1]=A\n return AA\n\ndef evolve(V, bc, mask, b, conv_criterion, ite): \n count=0\n res=b-Ax(V,mask) #residuals \n for i in range(ite):\n relaxation_one_step(V, bc, mask)\n res_squared=np.sum(res*res)\n res=b-Ax(V,mask)\n count=count+1\n print(f\"Residual squared {res_squared}, count {count}\")\n #Q1_saveprint.write(f\"Residual squared {res_squared}, count {count} \\n\")\n if res_squared<conv_criterion: break \n return V, count\n\n# charge density \nrho=V[1:-1,1:-1]-(V[1:-1,0:-2]+V[1:-1,2:]+V[:-2,1:-1]+V[2:,1:-1])/4.0 \n\n\n\n# numerically solved potential V: \nV, count = evolve(V,bc,mask,b,conv_criterion,ite) \nE = np.gradient(V[::10,::10])\n\n# analytically solved potential V: \ndef V_anl(xx, cx, yy, cy, r): \n normalization=np.sqrt((xx.ravel()-cx)**2+(yy.ravel()-cy)**2)-r\n V=np.log(normalization)\n V=V.reshape(xx.shape)\n slope=1/V[cx, -1]\n V=-slope*V+1 \n V[condition]=1\n return V \n\nV_analytical=V_anl(xx, cx, yy, cy, r)\nE_analytical=np.gradient(V_analytical[::10,::10])\n\n\n\nplt.pcolormesh(V)\nplt.colorbar()\nplt.xlabel(\"x coordinate\")\nplt.ylabel(\"y coordinate\")\nplt.quiver(xx[::10,::10].ravel(),yy[::10,::10].ravel(),-E[1],-E[0])\nplt.title(\"Potential in contour, E field in arrows - Numerical\")\nplt.savefig(\"Q1_numerical.png\")\nplt.show()\n\n\nplt.pcolormesh(rho)\nplt.colorbar()\nplt.xlabel(\"x coordinate\")\nplt.ylabel(\"y coordinate\")\nplt.title(\"Charge density, rho\")\nplt.savefig(\"Q1_rho.png\")\nplt.show()\n\nplt.pcolormesh(V_analytical)\nplt.colorbar()\nplt.xlabel(\"x coordinate\")\nplt.ylabel(\"y coordinate\")\nplt.quiver(xx[::10,::10].ravel(),yy[::10,::10].ravel(),-E_analytical[1],-E_analytical[0])\nplt.title(\"Potential in contour, E field in arrows - Analytical\")\nplt.savefig(\"Q1_analytical.png\")\nplt.show()\n\nlamb=np.sum(rho)/(2*np.pi*r)\n\nsummary.write(\"###############Question 1################## \\n\")\nsummary.write(f\"The numerical method with the relaxation technique takes {count} number of iterations to converge. \\n\")\nsummary.write(f\"The line charge density lambda on the ring is {lamb}. \\n\")\nsummary.write(\"The numerical and analytical method yield similar results. But it should be bear in mind that the analytical method should be taken \\n\")\nsummary.write(\"with a grain of salt as the grid box is square and the source is circular, therefore the boundary condition of 0 cannot be properly met. \")\n\n\n\n\n\n#################### Question 2 #############################\n\ndef evolve_conjugate_grad(V, mask, b, conv_criterion, ite, start=0): \n count=start\n res=b-Ax(V,mask) #residuals \n p=res.copy()\n for k in range(ite):\n Ap=(Ax(pad(p),mask))\n rtr=np.sum(res*res) # note that \"rtr\" here is the same concept as \"res_squared\" prior\n print('on iteration ' + repr(count) + ' residual is ' + repr(rtr))\n #Q2_saveprint.write(f\"Residual squared {rtr}, count {count} \\n\")\n if rtr<conv_criterion: \n break \n count=count+1\n alpha=rtr/np.sum(Ap*p)\n V=V+pad(alpha*p)\n rnew=res-alpha*Ap\n beta=np.sum(rnew*rnew)/rtr\n p=rnew+beta*p\n res=rnew\n return V, count\n\n# re-initialize: \nx = np.arange(n)\ny = np.arange(n)\nxx, yy = np.meshgrid(x, y)\ncx, cy, r = n//2, n//2, 40 # defining centre of circle to be at the centre of the grid; radius 10\ncondition = (xx-cx)**2+(yy-cy)**2 <=r**2\n\n\nV=np.zeros([n,n])\nbc=0*V\n\nmask=np.zeros([n,n],dtype='bool')\nmask[:,0]=True\nmask[:,-1]=True\nmask[0,:]=True\nmask[-1,:]=True\n\nmask[condition]=True \nbc[condition]=1 #arbitrarily defined potential of the cylinder \n\nV=0*bc\n\n\n# one relaxation step taken on the boundary condition\nb=-(bc[1:-1,0:-2]+bc[1:-1,2:]+bc[:-2,1:-1]+bc[2:,1:-1])/4.0 \n\nV, count = evolve_conjugate_grad(V,mask,b,conv_criterion,ite) \nE = np.gradient(V[::10,::10])\n\nplt.pcolormesh(V)\nplt.colorbar()\nplt.xlabel(\"x coordinate\")\nplt.ylabel(\"y coordinate\")\nplt.quiver(xx[::10,::10].ravel(),yy[::10,::10].ravel(),-E[1],-E[0])\nplt.title(\"Potential in contour, E field in arrows - Numerical \\n (conjugate gradient method)\")\nplt.savefig(\"Q2_numerical.png\")\nplt.show()\n\n\nplt.pcolormesh(rho)\nplt.colorbar()\nplt.xlabel(\"x coordinate\")\nplt.ylabel(\"y coordinate\")\nplt.title(\"Charge density, rho\")\nplt.savefig(\"Q2_rho.png\")\nplt.show()\n\nplt.pcolormesh(V_analytical)\nplt.colorbar()\nplt.xlabel(\"x coordinate\")\nplt.ylabel(\"y coordinate\")\nplt.quiver(xx[::10,::10].ravel(),yy[::10,::10].ravel(),-E_analytical[1],-E_analytical[0])\nplt.title(\"Potential in contour, E field in arrows - Analytical\")\nplt.savefig(\"Q2_analytical.png\")\nplt.show()\n\nsummary.write(\"###############Question 2################## \\n\")\nsummary.write(f\"The numerical method with the analytical technique takes {count} number of iterations to converge. \\n\")\nsummary.write(\"It is obvious that the conjugate gradient method is much faster than the relaxation method in Q1 - \\n this new method takes a lot fewer steps to reach the same convergence criterion.\")\n\n\n\n#################### Question 3 #############################\n\ndef grid_interpolate (n, resolution, V, r): \n size=np.linspace(0, n, n)\n xx, yy =np.meshgrid(size, size) # old grid\n size=np.linspace(0, n, resolution)\n xxx, yyy=np.meshgrid(size, size) # new grid (with the input resolution)\n points=np.array([xx.ravel(), yy.ravel()]).transpose()\n V=V.ravel()\n bc=np.zeros(xxx.shape)\n cx, cy, r=n//2, n//2, r\n condition=(xxx-cx)**2+(yyy-cy)**2 <=r**2\n mask=condition.copy()\n mask[:,0]=True\n mask[:,-1]=True\n mask[0,:]=True\n mask[-1,:]=True\n mask[condition]=True \n bc[condition]=1\n V_new = scipy.interpolate.griddata(points, V, (xxx, yyy))\n return V_new, mask, bc \n\ndef evolve_low_resolution(V, mask, b, resolution, r, n, conv_criterion, ite, multiplication_factor):\n\n V, count = evolve_conjugate_grad(V, mask, b, conv_criterion, ite)\n while n < resolution: \n if n*multiplication_factor<resolution: nn=n*multiplication_factor\n else: nn = resolution # nn is the updated n \n V, mask, bc = grid_interpolate(n, nn, V, r)\n b=-(bc[1:-1,0:-2]+bc[1:-1,2:]+bc[:-2,1:-1]+bc[2:,1:-1])/4.0\n V, count_add = evolve_conjugate_grad(V, mask, b, conv_criterion, ite,start=count)\n n = nn \n count = count + count_add\n size = np.linspace(0, resolution, resolution)\n xxx, yyy = np.meshgrid(size, size)\n return V, xxx, yyy, count \n\n\n\n\n# creating a smaller resolution n and consequently defining a circle of smaller radius: \nn_low=100\nr_small=10\nmultiplication_factor = 2\n\n# re-initialization: \nx = np.arange(n_low)\ny = np.arange(n_low)\nxx, yy = np.meshgrid(x, y)\ncx, cy, r = n_low//2, n_low//2, r_small # defining centre of circle to be at the centre of the grid; radius 10\ncondition = (xx-cx)**2+(yy-cy)**2 <=r_small**2\n\n\nV=np.zeros([n_low,n_low])\nbc=0*V\n\nmask=np.zeros([n_low,n_low],dtype='bool')\nmask[:,0]=True\nmask[:,-1]=True\nmask[0,:]=True\nmask[-1,:]=True\n\nmask[condition]=True \nbc[condition]=1 #arbitrarily defined potential of the cylinder \n\n\n\nV=0*bc\n\nb=-(bc[1:-1,0:-2]+bc[1:-1,2:]+bc[:-2,1:-1]+bc[2:,1:-1])/4.0 \n\nV, xxx, yyy, count = evolve_low_resolution(V, mask, b, n, r_small, n_low, conv_criterion, ite, multiplication_factor)\n\n\nE=np.gradient(V[::10, ::10])\n\n\nplt.pcolormesh(V)\nplt.colorbar()\nplt.xlabel(\"x coordinate\")\nplt.ylabel(\"y coordinate\")\nplt.quiver(xxx[::10,::10].ravel(),yyy[::10,::10].ravel(),-E[1],-E[0])\nplt.title(\"Potential in contour, E field in arrows\")\nplt.savefig(\"Q3_increasing_resolution.png\")\nplt.show()\n\nsummary.write(\"\\n ###############Question 3################## \\n\")\nsummary.write(f\"A total steps of {count} is taken to reach the same convergence criterion. \\n\")\n\n\n\n#################### Question 4 #############################\n \n# creating a smaller resolution n and consequently defining a circle of smaller radius: \nn_low=100\nr_small=10\nmultiplication_factor = 2\n\n# re-initialization: \nx = np.arange(n_low)\ny = np.arange(n_low)\nxx, yy = np.meshgrid(x, y)\ncx, cy, r = n_low//2, n_low//2, r_small # defining centre of circle to be at the centre of the grid; radius 10\ncondition = (xx-cx)**2+(yy-cy)**2 <=r_small**2\n\ncx_bump, cy_bump, r_bump = n_low//2+r_small, n_low//2, 2*r_small//10\ncondition_bump = (xx-cx_bump)**2+(yy-cy_bump)**2 <=r_bump**2\n\n\n\nV=np.zeros([n_low,n_low])\nbc=0*V\n\nmask=np.zeros([n_low,n_low],dtype='bool')\nmask[:,0]=True\nmask[:,-1]=True\nmask[0,:]=True\nmask[-1,:]=True\n\nmask[condition]=True \nbc[condition]=1 #arbitrarily defined potential of the cylinder \nmask[condition_bump]=True \nbc[condition_bump]=1 #bump on the cylinder\n\n\nV=0*bc\n\n\nb=-(bc[1:-1,0:-2]+bc[1:-1,2:]+bc[:-2,1:-1]+bc[2:,1:-1])/4.0 \n\nV, xxx, yyy, count = evolve_low_resolution(V, mask, b, n, r_small, n_low, conv_criterion, ite, multiplication_factor)\n\n\nE=np.gradient(V[::10, ::10])\n\n\nplt.pcolormesh(V)\nplt.colorbar()\nplt.xlabel(\"x coordinate\")\nplt.ylabel(\"y coordinate\")\nplt.quiver(xxx[::10,::10].ravel(),yyy[::10,::10].ravel(),-E[1],-E[0])\nplt.title(\"Potential in contour, E field in arrows\")\nplt.savefig(\"Q4_10percent_bump.png\")\nplt.show()\n\nsummary.write(\"\\n ###############Question 4################## \\n\")\nsummary.write(f\"A total steps of {count} is taken to reach the same convergence criterion. \\n\")\nsummary.write(\"There should be disturbance in the field after the addition of the bump, 10 percent of the wire diameter. \\n\")\nsummary.write(\"However, the disturbance is not that obvious just by a quick observation with the naked eyes.\\n\")\n\n\n\n#################### Question 5 #############################\ndef Neumann_1D(dt, dx, t_max, x_max, k, C):\n s = k*dt/dx**2\n if s > 1/2:\n print('Error - Exit')\n exit(1)\n x = np.arange(0,x_max+dx,dx) \n t = np.arange(0,t_max+dt,dt)\n r = len(t)\n c = len(x)\n T = np.zeros([r,c])\n for n in range(0,r-1):\n for j in range(1,c-1):\n T[n,0] = t[n]*C\n T[n+1,j] = T[n,j] + s*(T[n,j-1] - 2*T[n,j] + T[n,j+1]) \n return x,T\n\ndt=1e-3\ndx=1e-3\n# to make sure the residuals don't diverge, k * dt / (dx**2) must satisfy <=0.5\nk_max=0.5*dx**2/dt\nk=k_max / 2 #arbitarily making sure that the chosen value of k is smaller than the maximally allowed k value \nx_max=0.01\nt_max=1\nC=100 \nx, T=Neumann_1D(dt, dx, t_max, x_max, k, C)\ntime_ticks=np.arange(0, t_max/2, 0.05)\n\nfor i in time_ticks: \n index=int(i/dt)\n plt.plot(x, T[index, :], label=f\"t={i}\")\nplt.xlabel(\"Position, x\")\nplt.ylabel(\"Temperature, T\")\nplt.legend()\nplt.savefig(\"Q5_heat_curves_Newmann_Robin.png\")\nplt.show()\n\nsummary.write(\"\\n ###############Question 5################## \\n\")\nsummary.write(\"Using the 1D Neumann for heat transfer, the heat curves are plotted shown in the saved figure for Q5. \\n\")\nsummary.write(\"There are indeed constants that need to be set. \\n\")\nsummary.write(f\"In order to make the solution converge properly, it must be that k * dt / (dx**2) <= 0.5 \\n\")\nsummary.write(f\"For this calculation, these values are chosen as dt={dt}, dx={dx}, and k={k} to satisfy the aforementioned inequality.\")\n\n\n\n\n" }, { "alpha_fraction": 0.6385964751243591, "alphanum_fraction": 0.6680701971054077, "avg_line_length": 26.764705657958984, "blob_id": "09b9e4fb2ca32e3cf46445d3813b60a4b148d89e", "content_id": "aa26cfc41a32908aa79b40678adced98ade4d494", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1425, "license_type": "no_license", "max_line_length": 142, "num_lines": 51, "path": "/Nbody_project/FourthPart.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "from functions import * \nimport matplotlib.colors as colors\n\n\n############## Periodic B.C's ##################\n\nsummary = open(\"Summary.txt\", \"a\")\n\n\nn=int(2e5) # now use hundreds of thousands of particles \ngrid_size = 500\nsoften = 10\nmass = 10000\nv_x = 0 # initial v in x-direction \nv_y = 0 # initial v in y-direction \n\n\n\nsystem = Particles(mass, v_x, v_y, n, grid_size, soften, early_uni = True)\ngrid = system.grid.copy()\ngrid[grid==0] = grid[grid!=0].min()*1e-3\ndt = 100\nfig = plt.figure()\nax = fig.add_subplot(111, autoscale_on = False, xlim = (0, grid_size), ylim = (0, grid_size))\nparticles_plot = ax.imshow(system.grid, origin='lower', cmap=plt.get_cmap('cividis'), norm = colors.LogNorm(vmin=grid.min(), vmax=grid.max()))\nplt.colorbar(particles_plot)\n\ncount = 0\ndef animation_plot(i):\n\tglobal system, ax, fig, dt, count\n\t\n\tprint(count)\n\tfor i in range(5): \n\t\tsystem.evolve(dt)\n\t\tprint(f'step = {i}')\n\n\tcount+=1\n\tgrid = system.grid.copy()\n\tgrid[grid==0] = grid[grid!=0].min()*1e-3\n\tprint(system.v[0])\n\tprint(system.a[0])\n\tprint(system.loc[0])\n\tparticles_plot.set_data(system.grid)\n\tparticles_plot.set_norm(colors.LogNorm(vmin=grid.min(), vmax=grid.max()))\n\tparticles_plot.set_cmap(plt.get_cmap(\"cividis\"))\n\n\treturn particles_plot,\n\nanimation_periodic = anmt.FuncAnimation(fig, animation_plot, frames = 100, interval = 10) \nanimation_periodic.save(\"Question4_periodic.gif\", writer = \"imagemagick\")\n# plt.show()\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6359338164329529, "alphanum_fraction": 0.6832151412963867, "avg_line_length": 28.543859481811523, "blob_id": "24cc741612f9c644c5775c71480600c9a6763cdb", "content_id": "b16f880bfef61f42893d1897cc02a034fe0cca28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1692, "license_type": "no_license", "max_line_length": 139, "num_lines": 57, "path": "/Assignment3/Question1.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "### the following is copied from the code Prof. Sievers wrote and provided for this question: \n### the txt file is calling the date found and saved from https://lambda.gsfc.nasa.gov/data/map/dr5/dcp/spectra/wmap_tt_spectrum_9yr_v5.txt\n\n\nimport numpy as np\nimport camb\nfrom matplotlib import pyplot as plt\nimport time\n\n\ndef get_spectrum(pars,lmax=2000):\n #print('pars are ',pars)\n H0=pars[0]\n ombh2=pars[1]\n omch2=pars[2]\n tau=pars[3]\n As=pars[4]\n ns=pars[5]\n pars=camb.CAMBparams()\n pars.set_cosmology(H0=H0,ombh2=ombh2,omch2=omch2,mnu=0.06,omk=0,tau=tau)\n pars.InitPower.set_params(As=As,ns=ns,r=0)\n pars.set_for_lmax(lmax,lens_potential_accuracy=0)\n results=camb.get_results(pars)\n powers=results.get_cmb_power_spectra(pars,CMB_unit='muK')\n cmb=powers['total']\n tt=cmb[:,0] #you could return the full power spectrum here if you wanted to do say EE\n return tt\n\n\npars=np.asarray([65,0.02,0.1,0.05,2e-9,0.96])\nwmap=np.loadtxt('wmap_tt_spectrum_9yr_v5.txt')\n\n#plt.clf();\n#plt.errorbar(wmap[:,0],wmap[:,1],wmap[:,2],fmt='*')\n#plt.plot(wmap[:,0],wmap[:,1],'.')\ncmb=get_spectrum(pars)\n#plt.plot(cmb)\n#plt.show()\n\n\n\n###### end of Prof. Sievers' code ######\n\n\ndef chi_squared(empiracal_data, fit_data, err):\n # defining chi-squared formula, equation taken from Lecture 4 notes \n numerator=(empiracal_data-fit_data)**2\n denominator=err**2\n return numerator/denominator\n\n\ncmb_data=cmb[2:len(wmap[:,0])+2] # removing the first two points in the cmb data\nwmap_chi_squared=np.sum(chi_squared(wmap[:,1], cmb_data, wmap[:,2])) \nprint(wmap_chi_squared) \n# this prints the value of 1588.2376465826746\n\n# this is the expected value, around 1588 \n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5714285969734192, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 18, "blob_id": "8bc70951fa508c8dc7c83179a8b4eba206c5b2d5", "content_id": "60cde5782e814ec5886b18eb4bfac45f4fab6ad6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 56, "license_type": "no_license", "max_line_length": 21, "num_lines": 3, "path": "/README.md", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "PHYS 512 Assignments\nName: Yilin Wang \nStudent ID: 260720347" }, { "alpha_fraction": 0.4458353519439697, "alphanum_fraction": 0.6610496044158936, "avg_line_length": 31.4375, "blob_id": "7727337789b66c6a74d26fd6e032e8c08dafe9cf", "content_id": "24d7da5f0259933196366df7679e5ec1f24e4dc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2077, "license_type": "no_license", "max_line_length": 87, "num_lines": 64, "path": "/Assignment3/Question4.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "import numpy as np \nimport matplotlib.pyplot as plt \nimport camb \nfrom wmap_camb_example import wmap, get_spectrum\n\n\npcov = np.array([[ 1.34599766e+01, 2.27429191e-03, -2.33134798e-02, 3.88034261e-01,\n 1.41048208e-09, 8.08997413e-02],\n [ 2.27429191e-03, 6.54401598e-07, -3.01065452e-06, 8.64332826e-05,\n 3.33455835e-13, 1.88420375e-05],\n [-2.33134798e-02, -3.01065452e-06, 4.62480360e-05, -6.32838818e-04,\n -2.21981708e-12, -1.24799929e-04],\n [ 3.88034261e-01, 8.64332826e-05, -6.32838818e-04, 2.08038516e-02,\n 7.93466765e-11, 3.08761209e-03],\n [ 1.41048208e-09, 3.33455835e-13, -2.21981708e-12, 7.93466765e-11,\n 3.04274290e-19, 1.17274721e-11],\n [ 8.08997413e-02, 1.88420375e-05, -1.24799929e-04, 3.08761209e-03,\n 1.17274721e-11, 6.45825601e-04]]\n)\n\n# write MCMC to fit the basic 6 parameters\n\n\nlength=len(wmap[:,0])\n\ndef take_step_cov(covmat):\n mychol=np.linalg.cholesky(covmat)\n return np.dot(mychol,np.random.randn(covmat.shape[0]))\n\ntau_value=0.0544\ntau_sigma=0.0073\n\nnoise = wmap[:,2]\ndata = wmap[:,1]\nparams=np.asarray([65,0.02,0.1,2e-9,0.96])\nparams=np.insert(params, 3, 0.05)\nnstep=5000\nnpar=len(params)\nchains=np.zeros([nstep,npar])\nchisq=np.sum((data-get_spectrum(params)[2:length+2])**2/noise**2)\nscale_fac=0.5\nchisqvec=np.zeros(nstep)\nfile=open('Question4_datafile.txt', 'w') # \"w\" for write \n# as Prof. Sievers suggested, writing each step's results to a data file (in case of crashing)\nfor i in range(nstep):\n new_params=params+take_step_cov(pcov)*scale_fac\n if new_params[3]>tau_value-tau_sigma and new_params[3]<tau_value+tau_sigma:\n new_model=get_spectrum(new_params)[2:length+2]\n new_chisq=np.sum((data-new_model)**2/noise**2)\n \n delta_chisq=new_chisq-chisq\n prob=np.exp(-0.5*delta_chisq)\n accept=np.random.rand(1)<prob\n if accept:\n params=new_params\n model=new_model\n chisq=new_chisq\n chains[i,:]=params\n chisqvec[i]=chisq\n for ii in params: \n file.write(f\"{ii}, \")\n file.write(f\"{chisq} \\n\")\n file.flush()\nfile.close()\n\n" }, { "alpha_fraction": 0.6441322565078735, "alphanum_fraction": 0.6698858737945557, "avg_line_length": 25.184616088867188, "blob_id": "b776d7d0e7d53e22c5b2cdf567764b05815a016b", "content_id": "e815957de9bf53fc2647f1e5cbe248d372d7bd5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3417, "license_type": "no_license", "max_line_length": 98, "num_lines": 130, "path": "/Assignment2/Question2.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "import numpy as np \nimport matplotlib.pyplot as plt \n\n\n# part (a)\n\nfulldata = np.loadtxt('229614158_PDCSAP_SC6.txt', delimiter=',')\n\ntime_fulldata=fulldata[:,0]\nflux_fulldata=fulldata[:,1]\n\n# the region to which an exponential decay will be fitted \ntime_flare=time_fulldata[3200:3400]\nflux_flare=flux_fulldata[3200:3400]\n\n# defining a general exponential function (decaying one) \ndef exponential_func(x, x0, b, C):\n\treturn np.exp(-b*(x-x0))+C \n\n\n\"\"\"\nBy observing the plot: \n- The base line is approximately 1 instead of 0 -> C=1 \n- teh amplitude is the nax flux value - the base line\n\"\"\"\nA=np.max(flux_flare)-1 # this gives the amplitude \nC=1 # the shift upwards by 1 due to base line being at 1 \n\n# converting between the amplitude of an exponential function and the x0 factor \n\"\"\"\nf(x)=a*np.exp(-b*(x-x0_old))+C=np.exp(-b*(x-(x0_old+ln(a)/b)))+C, where x0_new=x0_old+ln(a)/b\n\"\"\"\nx0_old=time_flare[0]\nb=65 # vary this value by guessing and observing the behaviour of the prediction graph \nx0_new=x0_old+np.log(A)/b\nflux_prediction=exponential_func(time_flare, x0_new, b, C)\n\n\n\nplt.plot(time_flare, flux_flare, '.k', label=\"Original data\")\nplt.plot(time_flare, flux_prediction, \".r\", label=\"Prediction\")\nplt.xlabel(\"Time\")\nplt.ylabel(\"Flux\")\nplt.legend()\nplt.savefig(\"Question2a_Flux_vs_time_at_flare.png\")\nplt.show()\n\n# note that when b=65 it is somewhat of a good prediction \n\nprint(f\"The initial guess values are x0={x0_new}, b=65, C=1\")\nprint(\"The model exponentially decays and is not linear.\")\n\n\n\n\n\n################################\n\n\n# part (b)\n\n# partial derivatives of the exponential function w/ respect to x0, C, b: \ndef gradient_exponential_func(x, x0, b, C):\n\texponential_function=np.exp(-b*(x-x0))+C \n\tdf_dx0=b*np.exp(-b*(x-x0))\n\tdf_db=-(x-x0)*np.exp(-b*(x-x0))\n\tdf_dC=1\n\tgrad=np.zeros([x.size, 3]) # defining a zero matrix of the required size \n\tgrad[:, 0]=df_dx0\n\tgrad[:, 1]=df_db\n\tgrad[:, 2]=df_dC\n\treturn exponential_function, grad \n\n# taking the code from lecture for Newton's method: \n\nfor j in range(5):\n prediction,grad=gradient_exponential_func(time_flare, x0_new, b, C)\n r=flux_flare-prediction\n err=(r**2).sum()\n r=np.matrix(r).transpose()\n grad=np.matrix(grad)\n\n lhs=grad.transpose()*grad\n rhs=grad.transpose()*r\n dp=np.linalg.inv(lhs)*(rhs)\n x0_new=float(x0_new+dp[0])\n b=float(b+dp[1])\n C=float(C+dp[2])\n\n\n\nplt.plot(time_flare, flux_flare, '.k', label=\"Original data\")\nplt.plot(time_flare, flux_prediction, \".r\", label=\"Prediction\")\nplt.plot(time_flare, exponential_func(time_flare, x0_new, b, C), label=\"Newton's method\")\nplt.xlabel(\"Time\")\nplt.ylabel(\"Flux\")\nplt.legend()\nplt.savefig(\"Question2b_Flux_vs_time_at_flare_exponential_fit.png\")\nplt.show()\n\n# comment: the guess is reasonable \n\n\nprint(f\"The parameters for Newton's method are x0={x0_new}, b={b}, C={C}\")\n\n\n\n\n################## \n# Part (c) \nnoise_matrix=np.diag(1/((flux_flare-prediction)**2))\n\n\n# find errors on fit parameters \n\n\ncovariance=np.linalg.inv(np.transpose(grad)@noise_matrix@grad)\nerror_on_fit=np.sqrt(np.diag(covariance))\n\nprint(f\"The errors on the Newton's method parameters are error of {error_on_fit[0]} on {x0_new},\")\nprint(f\" error of {error_on_fit[1]} on {b},\")\nprint(f\" error of {error_on_fit[2]} on {C}. \")\n\n# the errors are reasonably small \n\n##########################\n\n# part (d)\n\n# Definitely not. This is only limited to this one, most significant peak. \n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5760171413421631, "alphanum_fraction": 0.6006423830986023, "avg_line_length": 28, "blob_id": "48544b9c4690d16d692c6732ae5ed2bb03d9c679", "content_id": "adf1eee39761398cc8f25d1d93e4c8b8390a1467", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 934, "license_type": "no_license", "max_line_length": 93, "num_lines": 32, "path": "/Nbody_project/FirstPart.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "from functions import * \n\n\n# summary = open(\"Summary.txt\", \"w\")\n\n\n################### Question 1 ####################\nn=int(1) # numbers of particle \ngrid_size = 500 \nsoften = 10 \nmass = 1/n \nv_x = 0 # initial v in x-direction \nv_y = 0 # initial v in y-direction \n\nsystem = Particles(mass, v_x, v_y, n, grid_size, soften)\ndt = 1 \nfig = plt.figure()\nax = fig.add_subplot(111, autoscale_on = False, xlim = (0, grid_size), ylim = (0, grid_size))\nparticles_plot , = ax.plot([], [], \"*\")\ndef animation_plot(i):\n\tglobal system, ax, fig, dt\n\tsystem.evolve(dt)\n\tparticles_plot.set_data(system.loc[:,0], system.loc[:,1])\n\treturn particles_plot, \n\ngif = anmt.FuncAnimation(fig, animation_plot, frames = 50, interval = 5) \ngif.save(\"Question1.gif\", writer = \"imagemagick\")\n\n\n\n# summary.write(\"################### Question 1 ##################### \\n\")\n# summary.write(\"As shown in the animation, the particle behaviour is stationary. \\n\")\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6512500047683716, "alphanum_fraction": 0.675178587436676, "avg_line_length": 41.05263137817383, "blob_id": "6c9f888dcacadc06050e8f3e0955d36fd5ebaa9d", "content_id": "55a6dcdb6da09ef61db2c81279ce86d9a559c6be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5602, "license_type": "no_license", "max_line_length": 177, "num_lines": 133, "path": "/Assignment3/Question2.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "# once again start with Prof. Sievers' code: \n\nimport numpy as np\nimport camb\nfrom matplotlib import pyplot as plt\nfrom wmap_camb_example import wmap, get_spectrum\nimport time\n\n\ndef get_spectrum_fixed_tau(pars,lmax=1500):\n #print('pars are ',pars)\n H0=pars[0]\n ombh2=pars[1]\n omch2=pars[2]\n tau=0.05 \n As=pars[3] \n ns=pars[4]\n pars=camb.CAMBparams()\n pars.set_cosmology(H0=H0,ombh2=ombh2,omch2=omch2,mnu=0.06,omk=0,tau=tau)\n pars.InitPower.set_params(As=As,ns=ns,r=0)\n pars.set_for_lmax(lmax,lens_potential_accuracy=0)\n results=camb.get_results(pars)\n powers=results.get_cmb_power_spectra(pars,CMB_unit='muK')\n cmb=powers['total']\n tt=cmb[:,0] #you could return the full power spectrum here if you wanted to do say EE\n return tt\n\n\npars=np.asarray([65,0.02,0.1,2e-9,0.96])\nwmap=np.loadtxt('wmap_tt_spectrum_9yr_v5.txt')\n\n#plt.clf();\n#plt.errorbar(wmap[:,0],wmap[:,1],wmap[:,2],fmt='*')\n#plt.plot(wmap[:,0],wmap[:,1],'.')\n#cmb=get_spectrum(pars)\n#plt.plot(cmb)\n#plt.show()\n\n\n\n##### end of Prof. Sievers' code #####\n\n# optical depth fixed at 0.05 \n# Newton's method / Levenberg-Marquardt minimizer \n# find best-fit values for the other parameters and their errors \n\nlength=len(wmap[:,0]) # length of wmap data (any column will do)\n\ndef Newton_gradient(func, parameter):\n # defining gradient with respect to a speicific parameter for a given function; \n gradient=np.zeros([length, len(parameter)]) # create zerio matrix\n for i in range(len(parameter)):\n parameter_update=parameter.copy()\n dx=parameter_update[i]*0.01\n parameter_update[i]=parameter_update[i]+dx\n func_left=func(parameter_update)[2:length+2]\n parameter_update[i]=parameter_update[i]-2*dx\n func_right=func(parameter_update)[2:length+2]\n gradient[:,i]=(func_left-func_right)/(2*dx)\n return gradient\n\n\nconvergence_criterion=1e-3 # common convergence criterion in ANSYS Fluent \nlambda_increase_factor=1000\nlambda_decrease_factor=500\n\n# defining Newton's method for when the residuals are already close to a minimum, i.e. already converging\n# and when the residuals are large and are diverging, the Levenberg–Marquardt algorithm is employed for steep descend \ndef Newton_Levenberg_Marquardt(empirical_data, fit_data, parameter, err, max_ite=100):\n lamb=0.001 #arbitrarily small \n chi_squared=5000 #arbitrarily large\n gradient=Newton_gradient(fit_data, parameter)\n parameter_new=parameter.copy()\n for i in range(max_ite):\n guess=fit_data(parameter_new)[2:len(empirical_data)+2] # because in the data, same reason as Q1, the first two data points are to be discarded \n residual=empirical_data-guess \n chi_squared_new=np.sum((residual**2)/(err**2))\n # when chi_squared is already small enough and reducing: \n if chi_squared_new < chi_squared and np.abs(chi_squared_new-chi_squared) < convergence_criterion: \n parameter=parameter_new.copy()\n parameter = np.insert(parameter, 3, 0.05)\n print(\"The residuals are converging and meeting the convergence criterion of \" + str(convergence_criterion) + r\", with $\\chi^{2}$ of \" + str(chi_squared_new) + \"\\n\")\n gradient=Newton_gradient(get_spectrum, parameter)\n noise=np.diag(1/(err**2))\n pcov=np.linalg.inv(np.dot(np.dot(gradient.transpose(), noise), gradient)) # definition of a covariance matrix \n perr=np.sqrt(np.diag(pcov))\n break \n\n # when chi_squared is diverging, increase lambda for steepest descend (Levenberg-Marquardt method)\n elif chi_squared_new > chi_squared: \n print(r\"$\\chi^{2}$ diverging. Increase $\\lambda$ by a factor of \" + str(lambda_increase_factor) + \"\\n\")\n lamb=lamb*lambda_increase_factor\n parameter_new=parameter.copy()\n\n else: \n parameter=parameter_new.copy()\n lamb=lamb*lambda_decrease_factor\n gradient=Newton_gradient(fit_data, parameter)\n chi_squared=chi_squared_new\n residual=np.matrix(residual).transpose()\n gradient=np.matrix(gradient)\n Newton_lhs=gradient.transpose()@np.diag(1/(err**2))@gradient \n lhs=Newton_lhs+np.diag(np.diag(Newton_lhs))*lamb\n rhs=gradient.transpose()@np.diag(1/(err**2))@residual\n dp=np.linalg.inv(lhs)@(rhs)\n for jj in range(parameter.size):\n parameter_new[jj]=parameter_new[jj]+dp[jj] # copied from class example Newton.py \n print (\"At iteration \" + str({i}), r\"the $\\chi^{2}$ is \" + str(chi_squared) + \"\\n\")\n return parameter, pcov, perr \n\n\n# input initial values as given in Q1, in the following order: \n# Hubble constant, physixal baryon density, cold DM density, primordial amplitude of fluctuations, slope of primordial amplitude of fluctuations\nH0=65 #km/s\nwb_h2=0.02\nwc_h2=0.1\nAs=2e-9\nslope_ppl=0.96\n\n\n\npars=np.asarray([H0, wb_h2, wc_h2, As, slope_ppl])\npars,pcov,perr=Newton_Levenberg_Marquardt(wmap[:,1], get_spectrum_fixed_tau, pars, wmap[:,2])\n\nprint(\"The optimized parameters are the following: \\n\")\nprint(f\"Hubble constant, H0, is {pars[0]} with an error of {perr[0]}\")\nprint(f\"Physical baryon density, wb_h2, is {pars[1]} with an error of {perr[1]}\")\nprint(f\"Cold DM density, wc_h2, is {pars[2]} with an error of {perr[2]}\")\nprint(f\"Optical depth, tau, is {pars[3]} with an error of {perr[3]}\")\nprint(f\"Primordial amplitude of fluctuations, As, is {pars[4]} with an error of {perr[4]}\")\nprint(f\"Slope of primordial amplitude of fluctuations, slope_ppl, is {pars[5]} with an error of {perr[5]}\")\n\nprint(pcov)\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6678813099861145, "alphanum_fraction": 0.7048412561416626, "avg_line_length": 24.600000381469727, "blob_id": "bd500c6858aacbb638415366f5b2fc5a7cfbdefc", "content_id": "75f39ce4b1d5aa971a6bb8185b2f0829bd588e56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1921, "license_type": "no_license", "max_line_length": 114, "num_lines": 75, "path": "/Assignment1/Question1(b)_plots.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "import numpy as np \nimport matplotlib.pyplot as plt\n###### Based on the numerical derivative as shown in Question1(a) ######\n\ndef derivative(func, x, dx): \n\tNewton_dx=func(x+dx)-func(x-dx)\n\tNewton_2dx=func(x+2*dx)-func(x-2*dx)\n\tnumerator=8*Newton_dx-Newton_2dx\n\tdenominator=12*dx\n\treturn numerator/denominator\n\ndx=np.logspace(-14, 1, 100)\n\n##### test for e(x)\n\ndef exponential_func(x):\n\treturn np.exp(x)\n\ndef exponential01_func(x):\n\treturn np.exp(0.01*x)\n\n\n# randomly define an x-value:\nx=0\n\nerr_exp=[]\nfor i in dx:\n\tnumerical_direv_exp=derivative(exponential_func, x, i)\n\treal_direv_exp=np.exp(x)\n\tdifference_exp=np.abs(numerical_direv_exp-real_direv_exp)\n\terr_exp.append(difference_exp)\n\nerr_exp01=[]\nfor i in dx:\n\tnumerical_direv_exp=derivative(exponential01_func, x, i)\n\treal_direv_exp=(0.01)*np.exp(0.01*x)\n\tdifference_exp=np.abs(numerical_direv_exp-real_direv_exp)\n\terr_exp01.append(difference_exp)\n\n\nplt.plot(dx, err_exp, '-k')\nplt.xlabel(\"dx\")\nplt.ylabel(\"Error\")\nplt.title(\"Error size for varying step size, dx, for function f(x)=exp(x)\")\nplt.xscale(\"log\")\nplt.yscale(\"log\")\nplt.show()\n\nplt.plot(dx, err_exp01, '-k')\nplt.xlabel(\"dx\")\nplt.ylabel(\"Error\")\nplt.title(\"Error size for varying step size, dx, for function f(x)=exp(0.01x)\")\nplt.xscale(\"log\")\nplt.yscale(\"log\")\nplt.show()\n\n\n\t\noptimized_dx_exp=(45*(1e-16)/4)**(1/5)\n\noptimized_dx_exp01=(45*(1e-6)/4)**(1/5)\n\n\n\n\n\n\n\nprint(f\"For an exponential function f(x)=exp(x), the optimized dx to minimize error is {optimized_dx_exp}. \"\n\t+ \"As observed from the previous graph, the value of dx at which the error is a minimum is around 0.00115.\"\n\t+ \"These two results are roughly consistent.\")\n\nprint(f\"For an exponential function f(x)=exp(0.01x), the optimized dx to minimize error is {optimized_dx_exp01}. \"\n\t+ \"As observed from the previous graph, the value of dx at which the error is a minimum is around 0.10729.\"\n\t+ \"These two results are roughly consistent.\")\n\n" }, { "alpha_fraction": 0.5500507354736328, "alphanum_fraction": 0.5644233822822571, "avg_line_length": 37.64052200317383, "blob_id": "2658889dbdb6272ec61283f99edbc1158bec6b3c", "content_id": "b9003cb757825b8cc52e9bc8ba7994631486f05e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5914, "license_type": "no_license", "max_line_length": 193, "num_lines": 153, "path": "/Nbody_project/functions.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "import numpy as np \nimport matplotlib.pyplot as plt \nimport matplotlib.animation as anmt \n\n\n\n\n\n\"\"\"\nLeapfrog method for higher order intergration \nnotes taken from: https://rein.utsc.utoronto.ca/teaching/PSCB57_notes_lecture10.pdf\n- Basic idea: stagger the updates of position and velocity in time, making the method symmetric \n\"\"\"\n\n\n\n\n\n\n\nclass Particles(): \n def __init__(self, mass, v_x, v_y, nparticles, grid_size, soften, orbit = False, bc_periodic = True, early_uni = False): \n \"\"\"\n mass (array): mass of particle\n p_x (array): x-component of the particle's velocity \n p_y (array): y-component of the particle's velocity \n nparticles (int): numberof particles in the list \n initial_condition (array): array containing initial ppsition and mass of the particles; lengths equal as nparticles \n grid_size (int): the size of the lenght of one side of the square grid \n soften (float): a restraint on the radius (distance of grid from origin) such that any radius smaller than soften is defined \n to be soften, to avoid infinity when divided by in the Green function calculation \n a (array): acceleration, [0] in x and [1] in y \n \"\"\"\n self.mass = np.ones(nparticles)*mass \n self.v_x = np.ones(nparticles) * v_x\n self.v_y = np.ones(nparticles) * v_y\n self.v = np.array([v_x, v_y]).transpose()\n self.nparticles = nparticles \n self.grid_size = grid_size\n self.soften = soften\n self.bc = bc_periodic\n if orbit ==False:\n self.initial_loc()\n else:\n self.initial_orbit()\n if early_uni == True: \n self.mass_early_uni()\n self.hist_2d()\n self.Green_func()\n self.a = np.zeros([nparticles, 2])\n\n def initial_loc(self):\n self.loc = np.random.rand(self.nparticles,2) * (self.grid_size-1)\n # self.loc_y = np.random.rand(self.nparticles) * (self.grid_size-1)\n\n def initial_orbit(self):\n n = self.grid_size\n self.loc = np.array([[n//2+10,n//2],[n//2-10,n//2]])\n\n def take_one_step(self,dt):\n \"\"\"\"\n dt (float): size of time step \n \"\"\"\n self.loc = self.loc + self.v * dt \n self.loc = self.loc%(self.grid_size-1)\n self.v = self.v + self.a * dt \n\n\n def hist_2d(self):\n \"\"\"\n i_loc (int): x- and y-location of particle, rounded off to nearest integer \n grid (array): density of particle on grid of size grid_size * grid_size \n \"\"\"\n if self.bc == True:\n self.grid = np.zeros([self.grid_size,self.grid_size])\n else:\n self.grid = np.zeros([2*self.grid_size,2*self.grid_size])\n self.i_loc=np.asarray(np.round(self.loc),dtype='int')\n n=self.loc.shape[0]\n for i in range(n):\n self.grid[self.i_loc[i,0],self.i_loc[i,1]]+=self.mass[i]\n\n def Green_func(self): \n \"\"\"\n Motivation - calculate Green function at each grid point, 1/(4*np.pi*r) \n where r is the distance from the origin (defined as the bottom left grid point)\n radius (float): distance from a grid point to the origin \n Green (array): calculate Green function at each grid point \n \"\"\"\n if self.bc == True:\n size = self.grid_size\n else:\n size = 2*self.grid_size\n self.Green = np.zeros([size, size])\n for x in range(len(self.Green[0])):\n for y in range(len(self.Green[1])):\n radius = np.sqrt(x**2 + y**2) \n if radius < self.soften: \n radius = self.soften\n self.Green[x, y]=1/(4 * np.pi * radius)\n if self.grid_size%2 == 0: \n self.Green[: size//2, size//2 : ] = np.flip(self.Green[: size//2, : size//2], axis = 1) # an intermittent step - the original grid has only been flipped once (2 x the original size)\n self.Green[ size//2 : , :] = np.flip(self.Green[: size//2, :], axis = 0)\n else: \n print(\"Exiting - Grid size is currently odd. Pleaset set to an even value.\")\n\n def potential(self): \n \"\"\"\n phi (array): potential obtained from the convolution, inverse Fourier transform (ifft) of Green function * ifft grid (i.e. density)\n \"\"\"\n self.phi = np.real(np.fft.ifft2(np.fft.fft2(self.Green)*np.fft.fft2(self.grid)))\n self.phi = 0.5 * (np.roll(self.phi, 1, axis = 1) + self.phi)\n self.phi = 0.5 * (np.roll(self.phi, 1, axis = 0) +self.phi)\n\n\n def force(self):\n \"\"\"\n force_x (array): force on each grid point in x-direction \n force_y (array): force on each grid point in y-direction \n \"\"\"\n\n\n self.potential()\n self.force_x = -0.5 * (np.roll(self.phi, 1, axis = 0) - np.roll(self.phi, -1, axis = 0)) * self.grid\n self.force_y = -0.5 * (np.roll(self.phi, 1, axis = 1) - np.roll(self.phi, -1, axis = 1)) * self.grid\n\n def evolve(self, dt): \n \"\"\"\n dt: time step size from function take_one_step \n \"\"\"\n\n self.force()\n self.take_one_step(dt)\n for i in range(self.nparticles):\n self.a[i]= np.array([self.force_x[self.i_loc[i,0],self.i_loc[i,1]] / self.mass[i], self.force_y[self.i_loc[i,0],self.i_loc[i,1]]/self.mass[i]])\n self.hist_2d()\n\n def energy(self): \n \"\"\"\n Recall that energy is potential energy (-GMm/r, which is - phi) + kinetic energy (mv**2/2)\n \"\"\"\n self.E = - np.sum(self.phi) + 0.5 * self.mass * np.sqrt((self.v_x ** 2 + self.v_y **2))\n\n def mass_early_uni(self): \n \"\"\"\n k (array): Fourier transform of x \n \"\"\"\n x = self.loc[:,0]\n y = self.loc[:,1]\n fft_x_sq = (np.real(np.fft.fft(x)))**2\n fft_y_sq = (np.real(np.fft.fft(y)))**2\n self.k = np.sqrt(fft_x_sq + fft_y_sq)\n self.mass = self.mass * (self.k**(-3))\n\n\n" }, { "alpha_fraction": 0.6610313057899475, "alphanum_fraction": 0.7075232267379761, "avg_line_length": 29.714284896850586, "blob_id": "333d3b19d9864c988fe2d3dab03e24181000a355", "content_id": "f9bbbf9cca4a253211b0eeee2729ba45f61458d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2366, "license_type": "no_license", "max_line_length": 107, "num_lines": 77, "path": "/Assignment3/Question3_readdata.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "import numpy as np \nimport matplotlib.pyplot as plt \n\nparameters=np.loadtxt(\"Question3_datafile.txt\", delimiter=\",\")\nH0=parameters[:,0]\nwb_h2=parameters[:,1]\nwc_h2=parameters[:,2]\ntau=parameters[:,3]\nAs=parameters[:,4]\nslope_ppl=parameters[:,5]\nchisq=parameters[:,6]\n\nfigure, (ax1, ax2, ax3, ax4, ax5, ax6, ax7)=plt.subplots(7, 1, sharex=True) \nax1.plot(H0)\nax1.set_ylabel(\"H0\")\nax2.plot(wb_h2)\nax2.set_ylabel(\"wb_h2\")\nax3.plot(wc_h2)\nax3.set_ylabel(\"wc_h2\")\nax4.plot(tau)\nax4.set_ylabel(\"tau\")\nax5.plot(As)\nax5.set_ylabel(\"As\")\nax6.plot(slope_ppl)\nax6.set_ylabel(\"slope_ppl\")\nax7.plot(chisq)\nax7.set_ylabel(\"chisq\")\nax7.set_xlabel(\"Steps\")\nplt.show()\nfigure.savefig(\"Question3_MCMC_chain.png\")\n\nburn_in_region_steps=500 # read off from the plots, should be ~ 190; but remove a bit more just in case \nparams_selected_region=parameters[burn_in_region_steps:,]\npars=np.mean(params_selected_region,axis=0)\nperr=np.std(params_selected_region,axis=0)\n\nprint(\"The optimized parameters are the following: \\n\")\nprint(f\"Hubble constant, H0, is {pars[0]} with an error of {perr[0]}\")\nprint(f\"Physical baryon density, wb_h2, is {pars[1]} with an error of {perr[1]}\")\nprint(f\"Cold DM density, wc_h2, is {pars[2]} with an error of {perr[2]}\")\nprint(f\"Optical depth, tau, is {pars[3]} with an error of {perr[3]}\")\nprint(f\"Primordial amplitude of fluctuations, As, is {pars[4]} with an error of {perr[4]}\")\nprint(f\"Slope of primordial amplitude of fluctuations, slope_ppl, is {pars[5]} with an error of {perr[5]}\")\n\n\nfigure, (ax1, ax2, ax3, ax4, ax5, ax6, ax7)=plt.subplots(nrows=7, ncols=1, sharex=True) \nax1.plot(np.fft.rfft(H0))\nax1.set_xscale('log')\nax1.set_yscale('symlog')\nax1.set_ylabel(\"H0\")\nax2.plot(np.fft.rfft(wb_h2))\nax2.set_xscale('log')\nax2.set_yscale('symlog')\nax2.set_ylabel(\"wb_h2\")\nax3.plot(np.fft.rfft(wc_h2))\nax3.set_xscale('log')\nax3.set_yscale('symlog')\nax3.set_ylabel(\"wc_h2\")\nax4.plot(np.fft.rfft(tau))\nax4.set_xscale('log')\nax4.set_yscale('symlog')\nax4.set_ylabel(\"tau\")\nax5.plot(np.fft.rfft(As))\nax5.set_xscale('log')\nax5.set_yscale('symlog')\nax5.set_ylabel(\"As\")\nax6.plot(np.fft.rfft(slope_ppl))\nax6.set_xscale('log')\nax6.set_yscale('symlog')\nax6.set_ylabel(\"slope_ppl\")\nax7.plot(np.fft.rfft(chisq))\nax7.set_xscale('log')\nax7.set_yscale('symlog')\nax7.set_ylabel(\"chi_squared\")\nax7.set_xlabel(\"Steps\")\nplt.show()\nfigure.savefig(\"Question3_MCMC_FFT.png\")\n\n" }, { "alpha_fraction": 0.6502024531364441, "alphanum_fraction": 0.6753036379814148, "avg_line_length": 30.512821197509766, "blob_id": "e396ecdd25e23b59be46310bf8220793f6a2f5da", "content_id": "904919cf42ea797b1578ee2ff201c4e74563f62b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1235, "license_type": "no_license", "max_line_length": 133, "num_lines": 39, "path": "/Nbody_project/ThirdPart_Periodic.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "from functions import * \n\n############## Periodic B.C's ##################\n\nsummary = open(\"Summary.txt\", \"a\")\nQ3_periodic_E = open(\"Q3_periodic_E.txt\", \"w\")\n\n\nn=int(2e5) # now use hundreds of thousands of particles \ngrid_size = 500\nsoften = 10 \nmass = 1/n\nv_x = 0 # initial v in x-direction \nv_y = 0 # initial v in y-direction \n\nsystem = Particles(mass, v_x, v_y, n, grid_size, soften)\ndt = 80\nfig = plt.figure()\nax = fig.add_subplot(111, autoscale_on = False, xlim = (0, grid_size), ylim = (0, grid_size))\nparticles_plot = ax.imshow(system.grid, origin='lower', vmin=system.grid.min(), vmax=system.grid.max(), cmap=plt.get_cmap('cividis'))\nplt.colorbar(particles_plot)\n\ncount = 0\ndef animation_plot(i):\n\tglobal system, ax, fig, dt, Q3_periodic_E, count\n\tprint(count)\n\tfor i in range(10): \n\t\tsystem.evolve(dt)\n\t\tsystem.energy()\n\t\tQ3_periodic_E.write(f\"{system.E}\")\n\tcount+=1\n\tparticles_plot.set_data(system.grid)\n\tparticles_plot.set_clim(system.grid.min(), system.grid.max())\n\tparticles_plot.set_cmap(plt.get_cmap(\"cividis\"))\n\treturn particles_plot,\n\nanimation_periodic = anmt.FuncAnimation(fig, animation_plot, frames = 200, interval = 10) \nanimation_periodic.save(\"Question3_periodic.gif\", writer = \"imagemagick\")\n#plt.show()\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6627988815307617, "alphanum_fraction": 0.7056962251663208, "avg_line_length": 34.97468185424805, "blob_id": "fa9af328ac343d7573c154f1d3928ecb53b1fa37", "content_id": "c0916bf84232e9f4d73ae0c3e3d464615de712ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2844, "license_type": "no_license", "max_line_length": 164, "num_lines": 79, "path": "/Assignment3/Question4_readdata.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "import numpy as np \nimport matplotlib.pyplot as plt \n\nparameters=np.loadtxt(\"Question4_datafile.txt\", delimiter=\",\")\nH0=parameters[:,0]\nwb_h2=parameters[:,1]\nwc_h2=parameters[:,2]\ntau=parameters[:,3]\nAs=parameters[:,4]\nslope_ppl=parameters[:,5]\nchisq=parameters[:,6]\n\n\ndef gaussian(x, mu, sigma, N):\n return 1/(sigma*np.sqrt(2*np.pi*N))*np.exp(-0.5*(((x-mu)/sigma)**2/N))\n\n\ntau_value=0.0544\ntau_sigma=0.0073\n\n\nfigure, (ax1, ax2, ax3, ax4, ax5, ax6, ax7)=plt.subplots(7, 1, sharex=True) \nax1.plot(H0)\nax1.set_ylabel(\"H0\")\nax2.plot(wb_h2)\nax2.set_ylabel(\"wb_h2\")\nax3.plot(wc_h2)\nax3.set_ylabel(\"wc_h2\")\nax4.plot(tau)\nax4.set_ylabel(\"tau\")\nax5.plot(As)\nax5.set_ylabel(\"As\")\nax6.plot(slope_ppl)\nax6.set_ylabel(\"slope_ppl\")\nax7.plot(chisq)\nax7.set_ylabel(\"chisq\")\nax7.set_xlabel(\"Steps\")\n#plt.show()\nfigure.savefig(\"Question4_MCMC_chain.png\")\n\n\nburn_in_region_steps=1000 # read off from the plots, should be ~ 190; but remove a bit more just in case \nparams_selected_region=parameters[burn_in_region_steps:,]\npars=np.mean(params_selected_region,axis=0)\nperr=np.std(params_selected_region,axis=0)\n\n\nprint(\"The optimized parameters are the following: \\n\")\nprint(f\"Hubble constant, H0, is {pars[0]} with an error of {perr[0]}\")\nprint(f\"Physical baryon density, wb_h2, is {pars[1]} with an error of {perr[1]}\")\nprint(f\"Cold DM density, wc_h2, is {pars[2]} with an error of {perr[2]}\")\nprint(f\"Optical depth, tau, is {pars[3]} with an error of {perr[3]}\")\nprint(f\"Primordial amplitude of fluctuations, As, is {pars[4]} with an error of {perr[4]}\")\nprint(f\"Slope of primordial amplitude of fluctuations, slope_ppl, is {pars[5]} with an error of {perr[5]} \\n \\n \\n\")\n\n\n\nparams_Q3=np.loadtxt(\"Question3_datafile.txt\", delimiter=\",\")\n\n\n\n\n\n\nburn_in_region_steps=500 # read off from the plots, should be ~ 800; but remove a bit more just in case \nparams_Q3=params_Q3[burn_in_region_steps:,]\n\nfor i in range(6):\n\tpars[i]=np.average(params_Q3[burn_in_region_steps:,i], weights=gaussian(params_Q3[burn_in_region_steps:,3], tau_value, tau_sigma, 5000-burn_in_region_steps))\n\tperr[i]=np.sqrt(np.cov(params_Q3[burn_in_region_steps:,i], aweights=gaussian(params_Q3[burn_in_region_steps:,3], tau_value, tau_sigma, 5000-burn_in_region_steps)))\n\n\nprint(\"The optimized parameters with the data from Q3 and weighting with a Gaussian distribution are the following: \\n\")\nprint(f\"Hubble constant, H0, is {pars[0]} with an error of {perr[0]}\")\nprint(f\"Physical baryon density, wb_h2, is {pars[1]} with an error of {perr[1]}\")\nprint(f\"Cold DM density, wc_h2, is {pars[2]} with an error of {perr[2]}\")\nprint(f\"Optical depth, tau, is {pars[3]} with an error of {perr[3]}\")\nprint(f\"Primordial amplitude of fluctuations, As, is {pars[4]} with an error of {perr[4]}\")\nprint(f\"Slope of primordial amplitude of fluctuations, slope_ppl, is {pars[5]} with an error of {perr[5]}\")\n\n\n" }, { "alpha_fraction": 0.6553359627723694, "alphanum_fraction": 0.6837944388389587, "avg_line_length": 29.878047943115234, "blob_id": "b64b52685c6e25e162b687b731ac84862045e3e5", "content_id": "b93f242427de471dcff6d5336641f737eb3af812", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1265, "license_type": "no_license", "max_line_length": 138, "num_lines": 41, "path": "/Assignment1/Question2.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "from scipy.interpolate import interp1d\nfrom scipy.misc import derivative \nimport numpy as np \nimport matplotlib.pyplot as plt \n\nlakeshore=np.genfromtxt(\"lakeshore.csv\")\nT_data=lakeshore[:,0] #K \nV_data=lakeshore[:,1] #V\ndV_dT_data=lakeshore[:,2] #mV/K\n\n#reverse the arrays such that data is in increasing order, to suit interp1d \nT=T_data[::-1] \nV=V_data[::-1]\ndV_dT=dV_dT_data[::-1]\n\nf = interp1d(V, T, kind=\"cubic\")\n\nticks=np.linspace(V[0], V[-1], 10000)\n\nplt.plot(ticks, f(ticks), '-r', label=\"Interpolated data\")\nplt.plot(V, T, '.k', label=\"Empirical data\")\nplt.xlabel(\"Voltage, V (V)\")\nplt.ylabel(\"Temperature, T (K)\")\nplt.title(\"Interolation of Lakeshore diode temperature versus voltage data\")\nplt.legend()\nplt.show()\n\n# Estimate error: \n# based on the results from 1(a) \ndef first_direv(func, x, dx):\n\treturn (4/3)*(func(x+dx)-func(x-dx))/(2*dx)-(1/3)*(func(x+2*dx)-func(x-2*dx))/(4*dx)\n\nerr_diff=first_direv(f, V[1:-1], 1e-4) - 1/(dV_dT[1:-1]*0.001)\nabs_err_diff=np.abs(err_diff)\nmax_abs_err_diff=np.max(abs_err_diff)\nmin_abs_err_diff=np.min(abs_err_diff)\n\n# This is the error on my derivatives: \nprint(abs_err_diff)\n\nprint (\"The range of error on the derivative is from a minimum of \" + str(min_abs_err_diff) + \" to a maximum of \" + str(max_abs_err_diff))" }, { "alpha_fraction": 0.6044907569885254, "alphanum_fraction": 0.646756649017334, "avg_line_length": 29.28444480895996, "blob_id": "853f44dec848bd8f9684c7b61fe26d5f941a374b", "content_id": "dcf749819a4f2c3f2a3f27fc7bdcb5892eeeb894", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6814, "license_type": "no_license", "max_line_length": 153, "num_lines": 225, "path": "/Assignment4/Question1.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "import numpy as np \nfrom matplotlib import pyplot as plt\nfrom scipy.ndimage import gaussian_filter\nfrom scipy.optimize import curve_fit\nimport h5py\nimport glob\nimport os \nfrom scipy.constants import c \n\n# read file (copied frmo Prof. Siever's \"simple_read_ligo.py\")\n\n\n\n\ndef read_template(filename):\n dataFile=h5py.File(filename,'r')\n template=dataFile['template']\n th=template[0]\n tl=template[1]\n return th,tl\ndef read_file(filename):\n dataFile=h5py.File(filename,'r')\n dqInfo = dataFile['quality']['simple']\n qmask=dqInfo['DQmask'][...]\n\n meta=dataFile['meta']\n gpsStart=meta['GPSstart'].value\n #print meta.keys()\n utc=meta['UTCstart'].value\n duration=meta['Duration'].value\n strain=dataFile['strain']['Strain'].value\n dt=(1.0*duration)/len(strain)\n\n dataFile.close()\n return strain,dt,utc\n\n\n\n\ndirectory = \"LOSC_Event_tutorial\"\n\n\n#################### Reading the file ####################\n\n\nfn_H=[\"H-H1_LOSC_4_V2-1126259446-32.hdf5\", \"H-H1_LOSC_4_V2-1128678884-32.hdf5\", \"H-H1_LOSC_4_V2-1135136334-32.hdf5\", \"H-H1_LOSC_4_V1-1167559920-32.hdf5\"]\nfn_L=[\"L-L1_LOSC_4_V2-1126259446-32.hdf5\", \"L-L1_LOSC_4_V2-1128678884-32.hdf5\", \"L-L1_LOSC_4_V2-1135136334-32.hdf5\", \"L-L1_LOSC_4_V1-1167559920-32.hdf5\"]\n\nfn_length=len(fn_H) # this is also the same length as len(fn_template) with fn_template assigned later \n\n\nstrain_H=np.zeros([fn_length, 131072])\nstrain_L=np.zeros([fn_length, 131072])\n# dt: time step between each data point \ndt=np.zeros([fn_length])\n# utc: starting time \nutc=[]\n\nfn_template=np.array([\"GW150914_4_template.hdf5\", \"LVT151012_4_template.hdf5\", \"GW151226_4_template.hdf5\", \"GW170104_4_template.hdf5\"])\n# creating placeholder empty arrays: \nth=np.zeros([fn_length, 131072]) \ntl=np.zeros([fn_length, 131072]) \n\nname=[\"GW150914\", \"LVT151012\", \"GW151226\", \"GW170104\"]\n\nfor i in range(fn_length): \n\tstrain_H[i,:], dt[i], _ = read_file(f'{directory}/{fn_H[i]}')\n\tstrain_L[i,:], dt[i], _ = read_file(f'{directory}/{fn_L[i]}')\n\tth[i:,], tl[i:,] = read_template(f'{directory}/{fn_template[i]}')\n\n#################### End of - Reading the file ####################\n\n\ndef noise_model(strain, window): # for part (a)\n\t\tnormalization=np.sqrt(np.mean(window**2))\n\t\tnoise=gaussian_filter(np.abs(np.fft.rfft(strain*window)/normalization)**2, 1)\n\t\treturn noise, normalization\n\nx=np.arange(len(strain_H[0]))\nx=x-1.0*x.mean()\nwindow=0.5*(1+np.cos(x*np.pi/np.max(x))) # use the cosine window to taper data such that the start and end are 0, compatible with fft.rfft() later \n\n\n\ndef match_filter(template, noise, strain, window, normalization): # for part (b)\n\twA = np.fft.rfft(window*template)/(np.sqrt(noise)*normalization)\n\twd = np.fft.rfft(window*strain)/(np.sqrt(noise)*normalization)\n\treturn np.fft.fftshift(np.fft.irfft(np.conj(wA)*wd))\n\ndef SNR(match_filter, template, noise, window, normalization, freq): # for part (c)\n\twA = np.fft.rfft(window*template)/(np.sqrt(noise)*normalization)\n\tSNR = np.abs(match_filter*np.fft.fftshift(np.fft.irfft(np.sqrt(np.conj(wA)*wA)))) # for (c)\n\tanalytic_SNR=np.abs(np.fft.irfft(wA)) # for (d)\n\tsum_power_spectra = np.cumsum(np.abs(wA**2)) # for (e)\n\tfreq_half=freq[np.argmin(np.abs(sum_power_spectra-(np.amax(sum_power_spectra)/2)))]\n\treturn SNR, analytic_SNR, freq_half\n\ndef HL_combined_SNR(SNR_H, SNR_L):\n\treturn np.sqrt(SNR_H**2+SNR_L**2)\n\ndef gaus(x, A, sigma, mu):\n\treturn A*np.exp(-(x-mu)**2/sigma**2)\n\ndef time_of_arrival(SNR, x):\n\tA=np.max(SNR)\n\tindex=np.argmax(SNR)\n\tmu=x[index]\n\tsigma=0.0005\n\tparams, cov = curve_fit(gaus, x[index-10:index+10], SNR[index-10:index+10], p0=[A, sigma, mu])\n\treturn params[2], params[1]\n\n\n\n\n\n\n\nfor i in range(len(strain_H)):\n\n\t#################### Part (a) ####################\n\ttime=np.linspace(0, len(strain_H[i])/4096, len(strain_H[i]))\n\tfreq=np.fft.rfftfreq(len(strain_H[i]), dt[i])\n\n\n\t# noise model in Hanford: \n\tnoise_H, normalization_H=noise_model(strain_H[i], window)\n\n\t# noise model in Livingston: \n\tnoise_L, normalization_L=noise_model(strain_L[i], window)\n\n\n\n\tplt.subplot(2, 1, 1)\n\tplt.semilogy(freq, noise_H)\n\tplt.ylabel(\"Power spectrum in Hanford\")\n\tplt.title(f'Noise model of {name[i]}')\n\n\tplt.subplot(2, 1, 2)\n\tplt.semilogy(freq, noise_L)\n\tplt.ylabel(\"Power spectrum in Livingston\")\n\tplt.xlabel(\"Frequency (Hz)\")\n\tplt.savefig(f\"Q1a_noise_model_{name[i]}.png\")\n\tplt.clf()\n\n\n\n\t#################### Part (b) ####################\n\tm_H=match_filter(th[i], noise_H, strain_H[i], window, normalization_H) # match filter for H\n\tm_L=match_filter(tl[i], noise_L, strain_L[i], window, normalization_L) # match filter for L\n\n\n\tplt.subplot(2, 1, 1)\n\tplt.plot(time, m_H)\n\tplt.ylabel(\"Match filter signal for Hanford\")\n\tplt.title(f'Match filter of {name[i]}')\n\n\tplt.subplot(2, 1, 2)\n\tplt.plot(time, m_L)\n\tplt.ylabel(\"Match filter signal for \\n Livingston\")\n\tplt.xlabel(\"Time (sec)\")\n\tplt.savefig(f\"Q1b_match_filter_signal_{name[i]}.png\")\n\tplt.clf()\n\n\n\t#################### Part (c) ####################\n\tSNR_H, analytic_SNR_H, freq_H=SNR(m_H, th[i], noise_H, window, normalization_H, freq)\n\tSNR_L, analytic_SNR_L, freq_L=SNR(m_L, tl[i], noise_L, window, normalization_L, freq)\n\tSNR_combined=HL_combined_SNR(SNR_H, SNR_L)\n\n\n\tplt.subplot(3, 1, 1)\n\tplt.plot(time, SNR_H)\n\tplt.ylabel(\"Signal-to-noise \\n in Hanford\")\n\tplt.title(f'Signal-to-noise of {name[i]}')\n\n\tplt.subplot(3, 1, 2)\n\tplt.plot(time, SNR_L)\n\tplt.ylabel(\"Signal-to-noise \\n in Livingston\")\n\n\tplt.subplot(3, 1, 3)\n\tplt.plot(time, SNR_combined)\n\tplt.ylabel(\"Signal-to-noise \\n combined\")\n\tplt.xlabel(\"Time (sec)\")\n\tplt.savefig(f\"Q1c_signal_to_noise_{name[i]}.png\")\n\tplt.clf()\n\n\t#################### Part (d) ####################\n\tanalytic_SNR_combined=HL_combined_SNR(SNR_H, SNR_L)\n\n\n\tplt.subplot(3, 1, 1)\n\tplt.plot(time, analytic_SNR_H)\n\tplt.ylabel(\"Analytic signal-to-noise \\n in Hanford\")\n\tplt.title(f'Analytic signal-to-noise of {name[i]}')\n\n\tplt.subplot(3, 1, 2)\n\tplt.plot(time, analytic_SNR_L)\n\tplt.ylabel(\"Analytic signal-to-noise \\n in Livingston\")\n\n\n\tplt.subplot(3, 1, 3)\n\tplt.plot(time, analytic_SNR_combined)\n\tplt.ylabel(\"Analytic_signal-to-noise \\n combined\")\n\tplt.xlabel(\"Time (sec)\")\n\tplt.savefig(f\"Q1d_analytic_signal_to_noise_{name[i]}.png\")\n\tplt.clf()\n\t\n\t#################### Part (e) ####################\n\tprint(name[i])\n\tprint(\"------------\")\n\tprint(f\"freq_H:{freq_H}\")\n\tprint(f\"freq_L:{freq_L}\") # this is saved in textfile \"part_e_f_print_results.txt\"\n\n\t#################### Part (f) ####################\n\ttime_H, err_H=time_of_arrival(SNR_H, time)\n\ttime_L, err_L=time_of_arrival(SNR_L, time)\n\tdelta_time=np.abs(time_H-time_L)\n\tdistance=1e6 # unit: m\n\terror_total=delta_time*c/distance \n\tprint(f\"time_H:{time_H}\")\n\tprint(f\"error_H:{err_H}\")\n\tprint(f\"time_L:{time_L}\")\n\tprint(f\"error_L:{err_L}\")\n\tprint(f\"error_total:{error_total}\")\n\tprint('') # this is saved in textfile \"part_e_f_print_results.txt\"\n" }, { "alpha_fraction": 0.6992322206497192, "alphanum_fraction": 0.7191938757896423, "avg_line_length": 36.70289993286133, "blob_id": "c7b3563054d13930129c80c4789a3b31f688af34", "content_id": "60bb2c322786a2a3462950fdaee0e863e9bacfa5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5210, "license_type": "no_license", "max_line_length": 190, "num_lines": 138, "path": "/Assignment2/Question1.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "import numpy as np \nimport os\n\nfrom matplotlib import pyplot as plt \n\nx=np.linspace(-1, 1, 10000)\n\ndef chebyshev_matrix(x, n): \n\t# note that n is the index of the polynomials, starting from n=0 \n\tmatrix=np.zeros([len(x), n+1]) # creating a zero matrix of dimensions length(x) times order+1\n\t\n\tmatrix[:, 0]=1 # First order of Chebyshev polynomials: T0=1\n\t\n\tif n>=1: \n\t\t# Second order of Cheb poly: T1=x\n\t\tmatrix[:,1]=x\n\tif n>=2: \n\t\t# third order of Cheb poly: use recursive relation for T(n+1) by recalling T(n) and T(n-1)\n\t\t# Recall recursive relation: Tn+1(x)=2*x*Tn(x)-Tn-1(x)\n\t\tfor i in range(1, n): \n\t\t\tmatrix[:, i+1]=2*x*matrix[:,i]-matrix[:,i-1]\n\treturn matrix\n\n\n\nmatrix_order_30=chebyshev_matrix(x, 30)\n\n\n\n\n#### mapping the interval in question, i.e. 0.5 < x < 1, to the interval accepted in the Cheb poly, i.e. -1 < x < 1: \n# simple method adapted from Stackoverflow: https://stackoverflow.com/questions/1969240/mapping-a-range-of-values-to-another\n\ndef mapfromto(x, a, b, c, d): \n\t\"\"\" \n\tx - input value \n\ta, b - input range \n\tc, d - output range \n\ty - retunr value\n\t\"\"\"\n\ty=(x-a)/(b-a)*(d-c)+c\n\treturn y \n# note that the old interval is a = -1, 1\nx_new_interval=mapfromto(x, -1, 1, 0.5, 1)\n\n\n# Compute the chebyshev polynomials for the array of x (from -1 to 1) as previously assigned, to order of 30 (arbitrary)\n\n\n\n\n\n# The function in questoin is the log base 2 of x\n# input x as the new interval as mapped onto the range of from 0.5 to 1 \nfunc=np.log2(x_new_interval)\n\n\n\n\n\n# Coefficients to the Cheb poly (note that this is an array of len(x): \ndef chebyshev_coeffs_leastsq(matrix, func): \n\tlhs=np.dot(matrix.transpose(), matrix)\n\trhs=np.dot(matrix.transpose(), func)\n\tcoeffs = np.dot(np.linalg.inv(lhs), rhs)\n\treturn coeffs\n# find the coefficients to the matrix and function in question: \ncoeffs_30=chebyshev_coeffs_leastsq(matrix_order_30, func)\n\n\ndef truncated_cheb(x, func, n, tolerance):\n\n\tmatrix = chebyshev_matrix(x,n)\n\tcoeffs = chebyshev_coeffs_leastsq(matrix, func)\n\tdef error_tolerance(coeffs, tolerance): \n\t\tmax_order=len(coeffs)\n\t\tfor i in range(len(coeffs)): \n\t\t\tif np.abs(coeffs[i]) <= tolerance: \n\t\t\t\tmax_order=i\n\t\t\t\tbreak \n\t\treturn max_order\n\tmax_index = error_tolerance(coeffs, tolerance)\n\tfit_func = np.dot(matrix[:,:max_index], coeffs[:max_index])\n\treturn fit_func, max_index\n\n\nfit_func, max_index=truncated_cheb(x, func, 30, 1e-6) \n# note that n=30 is an arbitrarily large value; the maximum index is later truncated using error_tolerance, as determined by the size of the tolenrance, here is 1e-6\nplt.plot(x_new_interval, fit_func, '.r', label=\"Chebyshev fit\")\nplt.plot(x_new_interval, func, '-k', label=\"Original function\")\nplt.xlabel(\"x interval\")\nplt.ylabel(\"Functions\")\nplt.title(\"Comparison of the original function of log base 2 of x and \\n the truncated Chebyshev polynomial expression of the function\")\nplt.legend()\nplt.savefig(\"Question1a_compare_original_func_and_truncated_Cheb_poly.png\")\nplt.show()\n\nprint(\"The number of terms needed for an error tolerance of 1e-6 is \" + str(max_index)) # prints the number of terms needed to achieve an input error tolerance \n\n\n\n\n########### This is the linear combination of the polyfit method using the numpy.polyfit method;\n# the residuals are compared to that of the truncated Cheb poly method that I previously coded \n\n\nfit_linear = np.polyfit(x_new_interval, func, max_index-1)\nfit_linear = np.polyval(fit_linear, x_new_interval)\n\nplt.plot(x_new_interval, fit_func-func, '.b', label=\"Chebyshev method\") # residuals from the Chebyshev polynomial expression \nplt.plot(x_new_interval, fit_linear-func, '.g', label=\"Numpy.polyfit method\") # residuals from the numpy.polyfit method \nplt.xlabel(\"x interval\")\nplt.ylabel(\"Residuals\")\nplt.title(\"Comparison of residuals from the truncated Chebyshev method and \\n numpy.polyfit method\")\nplt.legend()\nplt.savefig(\"Question1a_compare_truncated_Cheb_poly_and_numpy_polyfit_methods.png\")\nplt.show()\n\nprint('rms error for numpy.polyfit method is ',np.sqrt(np.mean((fit_linear-func)**2)),' with max error ',np.max(np.abs(fit_linear-func)))\nprint('rms error for truncated Chebyshev method is ',np.sqrt(np.mean((fit_func-func)**2)),' with max error ',np.max(np.abs(fit_func-func)))\n\nprint(\"Comment on the comparisons on residuals: The truncated Cherbyshev method has a higher root mean square (as indicated by the larger average error), but has a smaller maximum error;\")\nprint(\"whereas the numpy.polyfit method has a smaller root mean square (as indicated by the smaller average error), but has a much larger maximum error.\")\n\n\n\n\n\n\n'''\n# Part (b): \nThe way the functions are coded answers for part b already. To extend the function to take the log base 2 of any positive numnber, simply alter the x_new_interval:\nCurrent the x range takes the value between 0.5 and 1 as asked in part (a) - this is achieved by mapping the range of -1 to 1 of the Chebyshev to the specific range of 0.5 to 1 for part (a).\nTo change the mapped x region, sipmly change the last two parameters in mapfromto. \nFor example, to take the positive values from 3 to 10 instead of from 0.5 to 1, replace the current x_new_interval=mapfromto(x, -1, 1, 0.5, 1) with x_new_interval=mapfromto(x, -1, 1, 3, 10)\n\n\n'''\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6752721667289734, "alphanum_fraction": 0.6867806911468506, "avg_line_length": 36.764705657958984, "blob_id": "4919a3800b5989c917588d61a7866f246ad7d02f", "content_id": "bef6f620c60f345a6028bf537c1b2ed1d5b3caf2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3215, "license_type": "no_license", "max_line_length": 197, "num_lines": 85, "path": "/Assignment1/Question4.py", "repo_name": "YilinWphysics/Assignments", "src_encoding": "UTF-8", "text": "import numpy as np \nfrom scipy import integrate \nimport matplotlib.pyplot as plt\n\ndef integrand(z, R, u): \n\tnumerator=z-R*u\n\tdenominator=(R**2+z**2-2*R*z*u)**(3/2)\n\treturn numerator/denominator\n\n###### This is the adaptive Simpson's rule from Question 3 ######\ndef simpsons_rule(func, a, func_a, b, func_b): \n\t# evaluating integral between x=a and x=b using Simpson's rule\n\t# h is the midpoint between a and b \n\th = (a+b)/2\n\tfunc_h=func(h)\n\tsimpson_integral=(np.abs(b-a)/6) * (func_a+4*func_h+func_b)\n\treturn h, func_h, simpson_integral\n\ndef recursive_simpson(func, a, func_a, b, func_b, err, total_int, h, func_h, count=0): \n\t# Evaluating the left part (from a to h) of the integral using Simpson's rule: \n\tleft_h, left_func_h, left_int=simpsons_rule(func, a, func_a, h, func_h)\n\t# Evaluating the right part (from h to b) of the integral using Simpson's rule: \n\tright_h, right_func_h, right_int=simpsons_rule(func, h, func_h, b, func_b)\n\tdelta=left_int+right_int-total_int\n\t# criterion for determining when to stop subdividing an interval - when delta < 15*err \n\tif np.abs(delta)<=15*err:\n\t\treturn total_int, count\n\telse: \n\t\treturn recursive_simpson(func, a, func_a, h, func_h, err/2, left_int, left_h, left_func_h, count+1)+recursive_simpson(func, h, func_h, b, func_b, err/2, right_int, right_h, right_func_h, count+1)\n\ndef adaptive_simpsons(func, a, b, err):\n\tfunc_a, func_b = func(a), func(b)\n\th, func_h, total_int = simpsons_rule(func, a, func_a, b, func_b)\n\tintegral = recursive_simpson(func, a, func_a, b, func_b, err, total_int, h, func_h)\n\tcount = np.sum(integral[1::2])\n\tintegral = np.sum(integral[0::2])\n\treturn integral, count\n\n\t##########################################\n\nz_ticks=np.linspace(0,10,101)\n\n\n########## Integrating using the quad method ##########\n\n# Assign an arbitrary value of radius of sphere, r=1\nR=1\n# Lower bound of integration: \na=-1\n# Upper bound of integration: \nb=1\n\n# Creating integral_list as an empty array for now to save values into it for plotting purpose later \nintegral_quad_list=[]\n\nfor i in z_ticks:\n\tfunc = lambda x: integrand(i, R, x)\n\t# scipy.integrate.quad: input func (function); a (float) - lower bound; b (float) - upper bound\n\t# returns: y (float) - integral from a to b; abserr (float) - an estimate of the absolute error \n\tintegral, error = integrate.quad(func, a, b)\n\tintegral_quad_list.append(integral)\n\n# Plot integral_list again z_ticks: \nplt.plot(z_ticks, integral_quad_list, '-k')\nplt.xlabel(\"z-axis\")\nplt.ylabel(\"Electric field\")\nplt.title(\"Electric field as calculated using quad integration\")\nplt.show()\n\n# Comment on the plot previously plotted: Z<R is the region of E=0, and Z>R is the region where E decays as z increases; \n# There IS singularity - at z=R. However, the quad integration method does not care about the singularity. \n\n########## Integrating using the adaptive Simpson's rule as written in Question 3 ##########\n\n# randomly define a tolerance level: \nerr=1e-8\n\nintegral_AS_list=[] # AS: adaptive Simpson's \n\nfor i in z_ticks: \n\tfunc = lambda x: integrand(i, R, x)\n\tintegral, count = adaptive_simpsons(func, a, b, err)\n\tintegral_AS_list.append(integral)\n\n# Note that the adaptive Simpson's rule crashes due to divergence at z=1 \n\n\n\n\n" } ]
19
oemss/test_ldap
https://github.com/oemss/test_ldap
1d281d0e584e5c539911b4bf98ab7cf87c8228cc
a2d8be5e7613242495f5103d4ded13664bd22da0
7b2b332c3a994261616ca1eb5fbbf2fd46472d98
refs/heads/master
2020-03-30T11:11:58.521503
2018-10-11T13:30:54
2018-10-11T13:30:54
151,158,570
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7066929340362549, "alphanum_fraction": 0.7086614370346069, "avg_line_length": 32.93333435058594, "blob_id": "18fabca7414cf5470550394055e37c5ea31a5bb3", "content_id": "6ab8f5e8b14f0ec7255ba95f36c00fd113333b1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 508, "license_type": "no_license", "max_line_length": 104, "num_lines": 15, "path": "/auth_test/ldap_test/views.py", "repo_name": "oemss/test_ldap", "src_encoding": "UTF-8", "text": "# # -*- coding: utf-8 -*-\n# from __future__ import unicode_literals\n#\n# from django.http import request\n# from django.shortcuts import render\n# from django_auth_ldap.backend import LDAPBackend\n#\n# # Create your views here.\n# # from django.contrib.auth import authenticate, login\n# # user = authenticate(username=request.REQUEST.get('email'), password=request.REQUEST.get('password'))\n# # # handle error cases, inactive users, ...\n# # login(request, user)\n#\n# def mainp(request):\n# print(get_user_model())" }, { "alpha_fraction": 0.5785365700721741, "alphanum_fraction": 0.5853658318519592, "avg_line_length": 27.47222137451172, "blob_id": "d6d1e06d9cf607cbc855e3910f98367564f5d641", "content_id": "c8afd8e46da1643344661eabbfbc601a6a226cae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1025, "license_type": "no_license", "max_line_length": 77, "num_lines": 36, "path": "/auth_test/ldap_test/test_auth.py", "repo_name": "oemss/test_ldap", "src_encoding": "UTF-8", "text": "import ldap\n\n\ndef check_ldap(userUid):\n connect = init()\n \n # try:\n # connect.start_tls_s()\n # except ldap.OPERATIONS_ERROR as e:\n # e_msg = e[0]['info']\n # if e_msg == 'TLS already started':\n # pass\n # else:\n # raise\n try:\n # if authentication successful, get the full user data\n connect.bind_s(user_dn, password)\n result = connect.search_s(base_dn, ldap.SCOPE_SUBTREE, search_filter)\n # return all user data results\n connect.unbind_s()\n print(result)\n print(\"Success\")\n except ldap.LDAPError:\n connect.unbind_s()\n print(\"authentication error\")\n\n\ndef init():\n ldap_server = \"ldap://127.0.0.1\"\n username = \"Manager\"\n password = \"secret\"\n # the following is the user_dn format provided by the ldap server\n user_dn = \"cn=\" + username + \",dc=maxcrc,dc=com\"\n # adjust this to your base dn for searching\n base_dn = \"dc=maxcrc,dc=com\"\n return ldap.initialize(ldap_server)\n" }, { "alpha_fraction": 0.6942675113677979, "alphanum_fraction": 0.7006369233131409, "avg_line_length": 18.625, "blob_id": "e1d275eac6aa424e13850363cca27eacec464cee", "content_id": "5a0d0a0e92ae0ad937542e912531b61b6f5bc740", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 157, "license_type": "no_license", "max_line_length": 39, "num_lines": 8, "path": "/auth_test/ldap_test/apps.py", "repo_name": "oemss/test_ldap", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.apps import AppConfig\n\n\nclass LdapTestConfig(AppConfig):\n name = 'ldap_test'\n" } ]
3
emiliogozo/subset_raster
https://github.com/emiliogozo/subset_raster
1bed33f1927f59fa17fb2e153df74a0e69cb8454
c9bf5f161d972be0d7cab5f71a72bcb28fa88c55
e7da1ac121e9aedf9b9708e50a60cc124e94b2f5
refs/heads/main
2023-04-13T15:38:49.352395
2021-04-22T10:30:47
2021-04-22T10:30:47
360,480,435
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6272189617156982, "alphanum_fraction": 0.7120315432548523, "avg_line_length": 27.16666603088379, "blob_id": "a9e1584c29943d7924c377d9f3123b335d922be5", "content_id": "696bbfe41b89c21baedb61779ef98700b1291cf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 507, "license_type": "no_license", "max_line_length": 87, "num_lines": 18, "path": "/usage.py", "repo_name": "emiliogozo/subset_raster", "src_encoding": "UTF-8", "text": "from pathlib import Path\nfrom salem import wgs84\n\nfrom subset import subset\n\n\nin_nc = Path(\"/home/egozo/Research/workdir/data/nc/rcm/CNRM_RCP45_precip_2006_2099.nc\")\n\n# subset using shapefile, specify date\n\ndate_range = slice(\"2006\", \"2065\")\nshp_file = \"../../../ipif2/input/shp/basins/abra/basin.shp\"\nsubset_ds1 = subset(in_nc, date_range=date_range, shape=shp_file)\n\n\n# subset using corners\nsubset_opt = dict(corners=((120.25, 16.75), (121.25, 18.25)), crs=wgs84)\nsubset_ds2 = subset(in_nc, **subset_opt)\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 15, "blob_id": "a681f8cd26d3a0c8de477603db35b5ec2ccc3ae2", "content_id": "3d697cf10af02690cb8f261708b7fc6eac06e33b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 16, "license_type": "no_license", "max_line_length": 15, "num_lines": 1, "path": "/README.md", "repo_name": "emiliogozo/subset_raster", "src_encoding": "UTF-8", "text": "# Raster subset\n" }, { "alpha_fraction": 0.6220238208770752, "alphanum_fraction": 0.6235119104385376, "avg_line_length": 22.172412872314453, "blob_id": "e7d9e8cc9e16eabad997ec7eb68c4286df7dcc7e", "content_id": "a14b43575edbd6819599a31d42be05a988f934e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 672, "license_type": "no_license", "max_line_length": 71, "num_lines": 29, "path": "/subset.py", "repo_name": "emiliogozo/subset_raster", "src_encoding": "UTF-8", "text": "from pathlib import Path\nimport salem\n\n\ndef subset(raster, date_range=None, **kwargs):\n \"\"\"Returns the subset of a raster file\n\n Args:\n raster (str): Full path of the raster file\n date_range (list-like, optional): Date range. Defaults to None.\n\n Returns:\n an xarray Dataset\n \"\"\"\n if isinstance(raster, str):\n raster = Path(raster)\n\n if not raster.is_file():\n return None\n\n in_ds = salem.open_xr_dataset(raster)\n\n if date_range is not None:\n in_ds = in_ds.sel(time=date_range)\n\n out_ds = in_ds.salem.subset(margin=1, **kwargs)\n out_ds = out_ds.salem.roi(all_touched=True, **kwargs)\n\n return out_ds\n" } ]
3
PaulWichser/adventofcode
https://github.com/PaulWichser/adventofcode
43bb62f6da5fd7b03178293f4cdd5ddaca288b87
628d962a65188310af136c8b88acbdbd5dc94352
f878c9b3b2c7cec7a7b1c16129e4ff26d71460b7
refs/heads/master
2021-07-12T03:09:20.972130
2020-12-06T15:31:57
2020-12-06T15:31:57
226,439,135
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49837133288383484, "alphanum_fraction": 0.5276873111724854, "avg_line_length": 30.144927978515625, "blob_id": "67848163195f232f3c447d37c846e096a494e1ae", "content_id": "ffbce70d20dd27440556de52c27b6bddb686b2df", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2149, "license_type": "permissive", "max_line_length": 82, "num_lines": 69, "path": "/2019/day3-1.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "#Solution for https://adventofcode.com/2019/day/3\ndef wireimp(filename):\n with open(filename,'r') as file:\n wires = {}\n x=1\n for line in file:\n line = line.rstrip('\\n')\n list = line.split(',')\n wires['wire%i' % x] = list\n # print(len(wires))\n x += 1\n print(\"Imported wire dictionary of length %i\" % len(wires))\n return wires\n\ndef cartwire(list):\n outlist = []\n coords = [0,0]\n for x in range(len(list)):\n #convert strings to cartesian coords\n dir = list[x][0]\n list[x] = int(list[x].replace(dir,''))\n for i in range(list[x]):\n if dir == 'R':\n coords[0] = coords[0]+1\n elif dir == 'L':\n coords[0] = coords[0]-1\n elif dir == 'U':\n coords[1] = coords[1]+1\n elif dir == 'D':\n coords[1] = coords[1]-1\n else:\n print('Unexpected direction of %s' % dir)\n quit()\n # print(coords)\n outlist.append(coords.copy())\n # print(outlist)\n # print(outlist)\n return outlist\n\ndef closecross(list1,list2):\n crosses = []\n length = len(list1)*len(list2)\n counter = 0\n print('Checking %i possibilities for crossed wires' % length)\n for i in range(len(list1)):\n for j in range(len(list2)):\n if list1[i] == list2[j]:\n crosses.append(list1[i])\n counter +=1\n if not (counter%10000000):\n print('%i' % ((counter/length)*100))\n for i in range(len(crosses)):\n crosses[i] = abs(crosses[i][0]) + abs(crosses[i][1])\n print(crosses)\n return min(crosses)\n\ndef test(filename,ans):\n testdict = wireimp(filename)\n if closecross(cartwire(testdict['wire1']),cartwire(testdict['wire2'])) == ans:\n print('Test cross check successful!')\n else:\n print('Test cross check failure!')\n quit()\n\ntest('day3-1test2.txt',159)\ntest('day3-1test.txt',135)\n\nwiredict = wireimp('day3-1input.txt')\nprint(closecross(cartwire(wiredict['wire1']),cartwire(wiredict['wire2'])))\n" }, { "alpha_fraction": 0.3487088978290558, "alphanum_fraction": 0.4449349045753479, "avg_line_length": 30.685314178466797, "blob_id": "386e99351931e109a14d79d440ea09a761b0948d", "content_id": "bb135db5a119c4158ad3f9b365e446713228725c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4531, "license_type": "permissive", "max_line_length": 324, "num_lines": 143, "path": "/2019/day5-2.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n#Solution for https://adventofcode.com/2019/day/5\ntestdata = [3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31,1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104,999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99]\n# inputdata = [1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,10,19,1,6,19,23,2,23,6,27,2,6,27,31,2,13,31,35,1,10,35,39,2,39,13,43,1,43,13,47,1,6,47,51,1,10,51,55,2,55,6,59,1,5,59,63,2,9,63,67,1,6,67,71,2,9,71,75,1,6,75,79,2,79,13,83,1,83,10,87,1,13,87,91,1,91,10,95,2,9,95,99,1,5,99,103,2,10,103,107,1,107,2,111,1,111,5,0,99,2,14,0,0]\n\ndef getcode(intnum):\n strnum = str(intnum)\n code = []\n for i in range(len(strnum)):\n code.insert(i,int(strnum[i]))\n while len(code) < 5:\n code.insert(0,0)\n print('code:')\n print(code)\n return code\n\ndef getvalue(listdata,mode,loc):\n print('mode: %i, loc: %i' % (mode,loc))\n try:\n if mode == 0:\n # print(listdata[loc])\n return listdata[loc]\n elif mode == 1:\n # print(loc)\n return loc\n else:\n print('Unrecognized mode: %i' % mode)\n quit()\n except:\n listdata.append(-1)\n return -1\n\n\n\ndef intcomp(listdata):\n x = 0\n while x < len(listdata):\n print('x = %i' % x)\n code = getcode(listdata[x])\n op = code[-1] + (code[-2] * 10)\n mode1 = code[-3]\n mode2 = code[-4]\n mode3 = code[-5]\n ploc1 = x+1\n ploc2 = x+2\n ploc3 = x+3\n pval1 = getvalue(listdata,mode1,ploc1)\n listd1 = listdata[pval1]\n\n if op == 99:\n break\n\n elif op == 3:\n listdata[listdata[x+1]] = int(input('Enter intcomp value: '))\n x += 2\n\n elif op == 4:\n print('Intcomp value output: %i' % listdata[listdata[x+1]])\n if listd1 != 0:\n if listdata[x+2] == 99:\n print('Diagnostic code: %i' % listd1)\n quit()\n else:\n print('Unexpected value %i at location %i' % (listd1,listdata[x+1]))\n quit()\n x += 2\n\n else:\n pval2 = getvalue(listdata,mode2,ploc2)\n listd2 = listdata[pval2]\n\n if op == 5:\n if listd1 != 0:\n x += listd2\n else:\n x += 3\n\n elif op == 6:\n if listd1 == 0:\n x += listd2\n else:\n x += 3\n\n else:\n pval3 = getvalue(listdata,mode3,ploc3)\n listd3 = listdata[pval3]\n\n if op == 1:\n listdata[pval3] = listd2 + listd1\n print('%i at listdata[%i]' % (listd3,pval3))\n x += 4\n # print(listdata)\n\n elif op == 2:\n listdata[pval3] = listd2 * listd1\n print('%i at listdata[%i]' % (listd3,pval3))\n x += 4\n # print(listdata)\n\n elif op == 7:\n if listd1 < listd2:\n listdata[pval3] = 1\n print('1 at listdata[%i]' % pval3)\n else:\n listdata[pval3] = 0\n print('0 at listdata[%i]' % pval3)\n x += 4\n\n elif op == 8:\n if listd1 == listd2:\n listdata[pval3] = 1\n print('1 at listdata[%i]' % pval3)\n else:\n print('0 at listdata[%i]' % pval3)\n listdata[pval3] = 0\n x += 4\n\n else:\n print('Unexpected opcode: %i at %i' % (listdata[x], x))\n x += 4\n break\n\n print(listdata)\n print('Intcode computer position 0 = %i' % listdata[0])\n return listdata[0]\n\nprint('If input < 8, output should be 999. If input = 8, output should be 1000. If input > 8, output should be 1001')\nintcomp(testdata)\n\nfilename = input('Enter data file name: ')\nlistdata = fileimp.intimp(filename)\nintcomp(listdata)\n\n# for noun in range(100):\n# for verb in range(100):\n# indat = inputdata.copy()\n# indat[1] = noun\n# indat[2] = verb\n# if intcomp(indat) == 19690720:\n# print('Final intcode: %s' % indat)\n# print('noun=%i' % noun)\n# print('verb=%i' % verb)\n# quit()\n" }, { "alpha_fraction": 0.6533505320549011, "alphanum_fraction": 0.6675257682800293, "avg_line_length": 27.740739822387695, "blob_id": "8bb7110de0b6b25375eb7e179564a200e6d6a70d", "content_id": "5453e549ee5fcc20338d7eac1f4fa7bb509d4665", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 776, "license_type": "permissive", "max_line_length": 65, "num_lines": 27, "path": "/2020/d06_1.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\nimport string\n\n# import file as list, clean list\n# for each list item, scrub through string, noting unique answers\n# string.find() != -1\n# add uniques from each string to total\n\ndef groupuniques(stringlist,findlist):\n total = 0\n for i in stringlist:\n group = 0\n for j in findlist:\n if i.find(j) != -1:\n group = group + 1\n total = total + group\n print(total)\n return total\n\ntestlist = fileimp.cleanlist(fileimp.listimp('d06_test.txt'))\nif groupuniques(testlist,list(string.ascii_lowercase)) != 11:\n print(\"Test Failed!\")\n quit()\n\ngrouplist = fileimp.cleanlist(fileimp.listimp('d06_input.txt'))\ntotal = groupuniques(grouplist,list(string.ascii_lowercase))\nprint(\"Total added by groups =\", total)\n" }, { "alpha_fraction": 0.5801281929016113, "alphanum_fraction": 0.6538461446762085, "avg_line_length": 19.799999237060547, "blob_id": "0870796547bfa819d037c25e6b089cfc7e47ba72", "content_id": "5b88483c6fef7bbe2314b4443c05de6d067039e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 312, "license_type": "permissive", "max_line_length": 54, "num_lines": 15, "path": "/2019/day1-1.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n\ndef fuelcalc(mass):\n fuel = int(mass/3-2)\n return fuel\n\nif fuelcalc(1969) != 654 or fuelcalc(100756) != 33583:\n print('Fuel calculation failed')\n quit()\n\nmasses = fileimp.listimp('day1-1input.txt')\nfuel = 0\nfor m in masses:\n fuel += fuelcalc(m)\nprint (\"Fuel required = %i\" % fuel)\n" }, { "alpha_fraction": 0.533462643623352, "alphanum_fraction": 0.5480116605758667, "avg_line_length": 25.435897827148438, "blob_id": "f1c4e1a5f3af9c9dd9a4c318b7fabc8acfbbdfff", "content_id": "76a56df299de5a60d5ea0dbc743cf5ca00fd1b6e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1031, "license_type": "permissive", "max_line_length": 81, "num_lines": 39, "path": "/2020/d04.1.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n\n# listimp data as list\n# iterate through list of strings, concatenating into larger string\n# if list entry is blank '', end string, start over\n# search strings for byr, iyr, eyr, hgt, hcl, ecl, pid, cid (optional)\n# if all but cid, valid, iterate count\n\ndef cleanlist(list):\n returnlist = []\n string = \"\"\n for i in list:\n if i == '':\n returnlist.append(string)\n string = \"\"\n else:\n string = string + \" \" + i\n return returnlist\n\ndef validate(list):\n valid = 0\n for i in list:\n if \\\n i.find(\"byr\") != -1 and\\\n i.find(\"iyr\") != -1 and\\\n i.find(\"eyr\") != -1 and\\\n i.find(\"hgt\") != -1 and\\\n i.find(\"hcl\") != -1 and\\\n i.find(\"ecl\") != -1 and\\\n i.find(\"pid\") != -1:\n valid = valid + 1\n return valid\n\n\nif validate(cleanlist(fileimp.listimp('d04.1.test.txt'))) != 2:\n print(\"Test Failed!\")\n quit()\n\nprint(\"valid passports =\", validate(cleanlist(fileimp.listimp('d04.input.txt'))))\n" }, { "alpha_fraction": 0.481575608253479, "alphanum_fraction": 0.5021600723266602, "avg_line_length": 23.59375, "blob_id": "93fd2f44f818b0325f6c1ae2c4a9472c4e128b28", "content_id": "89e51db8224968805326f7b052ea3c540cc0dd4a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3935, "license_type": "permissive", "max_line_length": 104, "num_lines": 160, "path": "/2020/d04.2.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n\n# listimp data as list\n# iterate through list of strings, concatenating into larger string\n# if list entry is blank '', end string, start over\n# search strings for byr, iyr, eyr, hgt, hcl, ecl, pid, cid (optional)\n# if all but cid, valid, return list of valid by number of entries\n# convert valid list of strings to list of dicts\n# pass dict values by name to entry validators, return 1 for valid\n# count if all entries valid, count\n\ndef cleanlist(list):\n returnlist = []\n string = \"\"\n for i in list:\n if i == '':\n returnlist.append(string.lstrip(\" \"))\n string = \"\"\n else:\n string = string + \" \" + i\n returnlist.append(string.lstrip(\" \"))\n print(returnlist)\n return returnlist\n\ndef dictlist(list): #converts list of strings to dicts\n returnlist = []\n for x in list:\n print(x)\n Dict = dict((x.strip(), y.strip()) for x, y in (element.split(':') for element in x.split(' ')))\n returnlist.append(Dict)\n return returnlist\n\ndef valbyr(string):\n if string.isdigit():\n if 1920 <= int(string) <= 2002:\n return 0\n else:\n print(\"bad byr\")\n return 1\n\ndef valiyr(string):\n if string.isdigit():\n if 2010 <= int(string) <= 2020:\n return 0\n else:\n print(\"bad iyr\")\n return 1\n\ndef valeyr(string):\n if string.isdigit():\n if 2020 <= int(string) <= 2030:\n return 0\n else:\n print(\"bad eyr\")\n return 1\n\ndef valhgt(string):\n if string.find(\"cm\") != -1:\n c = string.rstrip(\"cm\")\n if string.find(\"in\") != -1:\n i = string.rstrip(\"in\")\n if c.isdigit():\n if 150 <= int(c) <= 193:\n return 0\n if i.isdigit():\n if 59 <= int(i) <= 76:\n return 0\n else:\n print(\"bad hgt\")\n return 1\n\ndef valhcl(string):\n if string.find(\"#\") != -1:\n h = string.lstrip('#')\n if len(h) == 6:\n try:\n int(h, 16)\n except:\n print(\"bad hcl\")\n return 1\n return 0\n else:\n print(\"bad hcl\")\n return 1\n\ndef valecl(string):\n colors = ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']\n for c in colors:\n if string == c:\n return 0\n print(\"bad ecl\")\n return 1\n\ndef valpid(string):\n if len(string) == 9 and string.isdigit():\n return 0\n else:\n print(\"bad pid\")\n return 1\n\ndef validate(dlist):\n validcount = 0\n for l in dlist:\n print(l)\n i = 0\n try:\n i = i + valbyr(l['byr'])\n except:\n print(\"no byr\")\n i = i +1\n try:\n i = i + valiyr(l['iyr'])\n except:\n print(\"no iyr\")\n i = i +1\n try:\n i = i + valeyr(l['eyr'])\n except:\n print(\"no eyr\")\n i = i +1\n try:\n i = i + valhgt(l['hgt'])\n except:\n print(\"no hgt\")\n i = i +1\n try:\n i = i + valhcl(l['hcl'])\n except:\n print(\"no hcl\")\n i = i +1\n try:\n i = i + valecl(l['ecl'])\n except:\n print(\"no ecl\")\n i = i +1\n try:\n i = i + valpid(l['pid'])\n except:\n print(\"no pid\")\n i = i +1\n print(\"bad count =\", i)\n if i == 0:\n validcount = validcount +1\n return validcount\n\ntestclean = cleanlist(fileimp.listimp('d04.2.test.txt'))\ntestdict = dictlist(testclean)\nif validate(testdict) != 4:\n print(\"Test failed!\")\n quit()\n\nclean = cleanlist(fileimp.listimp('d04.input.txt'))\nDict = dictlist(clean)\nprint(\"Number of valid passports =\", validate(Dict))\n\n# if validate(cleanlist(fileimp.listimp('d04.1.test.txt'))) != 2:\n# print(\"Test Failed!\")\n# quit()\n#\n# print(\"valid passports =\", validate(cleanlist(fileimp.listimp('d04.input.txt'))))\n" }, { "alpha_fraction": 0.5236363410949707, "alphanum_fraction": 0.5552726984024048, "avg_line_length": 32.132530212402344, "blob_id": "43a5e5954b2cfa66cf8851524da891d3a8ebbd7e", "content_id": "e349815fd4684ce7e22f95306b331d4706e5aa43", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2750, "license_type": "permissive", "max_line_length": 78, "num_lines": 83, "path": "/2019/day3-2.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "#Solution for https://adventofcode.com/2019/day/3\ndef wireimp(filename):\n with open(filename,'r') as file:\n wires = {}\n x=1\n for line in file:\n line = line.rstrip('\\n')\n list = line.split(',')\n wires['wire%i' % x] = list\n # print(len(wires))\n x += 1\n print(\"Imported wire dictionary of length %i\" % len(wires))\n return wires\n\ndef cartwire(list):\n outlist = []\n coords = [0,0,0]\n for x in range(len(list)):\n #convert strings to cartesian coords\n dir = list[x][0]\n list[x] = int(list[x].replace(dir,''))\n for i in range(list[x]):\n if dir == 'R':\n coords[0] = coords[0]+1\n elif dir == 'L':\n coords[0] = coords[0]-1\n elif dir == 'U':\n coords[1] = coords[1]+1\n elif dir == 'D':\n coords[1] = coords[1]-1\n else:\n print('Unexpected direction of %s' % dir)\n quit()\n # print(coords)\n coords[2] = coords[2]+1\n outlist.append(coords.copy())\n # print(outlist)\n # print(outlist)\n return outlist\n\ndef cross(list1,list2):\n crosslist = []\n length = len(list1)*len(list2)\n counter = 0\n print('Checking %i possibilities for crossed wires' % length)\n for i in range(len(list1)):\n for j in range(len(list2)):\n if list1[i][0] == list2[j][0] and list1[i][1] == list2[j][1]:\n totdist = list1[i][2]+list2[j][2]\n crosslist.append([list1[i][0],list1[i][1],totdist])\n counter +=1\n if not (counter%10000000):\n print('%i' % ((counter/length)*100))\n return crosslist\n\ndef closecross(inlist): #returns min Manhattan distance of cross list\n crosslist = inlist.copy()\n for i in range(len(crosslist)):\n crosslist[i] = abs(crosslist[i][0]) + abs(crosslist[i][1])\n print(crosslist)\n return min(crosslist)\n\ndef wirelen(inlist): #returns total added wire length from origin\n crosslist = inlist.copy()\n for i in range(len(crosslist)):\n crosslist[i] = crosslist[i][2]\n print(crosslist)\n return min(crosslist)\n\ndef test(filename,closeans,lenans):\n testdict = wireimp(filename)\n crosslist = cross(cartwire(testdict['wire1']),cartwire(testdict['wire2']))\n if closecross(crosslist) == closeans and wirelen(crosslist) == lenans:\n print('Test cross check successful!')\n else:\n print('Test cross check failure!')\n quit()\n\ntest('day3-1test2.txt',159,610)\ntest('day3-1test.txt',135,410)\n\nwiredict = wireimp('day3-1input.txt')\nprint(wirelen(cross(cartwire(wiredict['wire1']),cartwire(wiredict['wire2']))))\n" }, { "alpha_fraction": 0.5703324675559998, "alphanum_fraction": 0.6317135691642761, "avg_line_length": 20.72222137451172, "blob_id": "3156ab92dd74843aeaba6795cb40cc57c847eafa", "content_id": "6fc9734b63e84d5e8a4105ded3855b33dc4ac3fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 391, "license_type": "permissive", "max_line_length": 54, "num_lines": 18, "path": "/2019/day1-2.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n\ndef fuelcalc(mass):\n fuel = int(mass/3-2)\n return fuel\n\nif fuelcalc(1969) != 654 or fuelcalc(100756) != 33583:\n print('Fuel calculation failed')\n quit()\n\nmasses = fileimp.listimp('day1-1input.txt')\nfueltot = 0\nfor m in masses:\n fuel = fuelcalc(m)\n while fuel > 0:\n fueltot += fuel\n fuel = fuelcalc(fuel)\nprint (\"Fuel required = %i\" % fueltot)\n" }, { "alpha_fraction": 0.3814432919025421, "alphanum_fraction": 0.5841924548149109, "avg_line_length": 37.79999923706055, "blob_id": "e310c92cfd18755acf5802ef9f0f643fdeb140bb", "content_id": "df598ca0b56d41931aa3307fada4f96cce063432", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1164, "license_type": "permissive", "max_line_length": 322, "num_lines": 30, "path": "/2019/day2-1.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "#Solution for https://adventofcode.com/2019/day/2\ntestdata = [1,9,10,3,2,3,11,0,99,30,40,50]\ninputdata = [1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,10,19,1,6,19,23,2,23,6,27,2,6,27,31,2,13,31,35,1,10,35,39,2,39,13,43,1,43,13,47,1,6,47,51,1,10,51,55,2,55,6,59,1,5,59,63,2,9,63,67,1,6,67,71,2,9,71,75,1,6,75,79,2,79,13,83,1,83,10,87,1,13,87,91,1,91,10,95,2,9,95,99,1,5,99,103,2,10,103,107,1,107,2,111,1,111,5,0,99,2,14,0,0]\ninputdata[1] = 12\ninputdata[2] = 2\ndef intcomp(listdata):\n x = 0\n while listdata[x] != 99:\n if listdata[x] == 1:\n listdata[listdata[x+3]] = listdata[listdata[x+1]] + listdata[listdata[x+2]]\n x += 4\n print(listdata)\n elif listdata[x] == 2:\n listdata[listdata[x+3]] = listdata[listdata[x+1]] * listdata[listdata[x+2]]\n x += 4\n print(listdata)\n else:\n print('Unexpected opcode: %i' % x)\n quit()\n\n print('Intcode computer position 0 = %i' % listdata[0])\n return listdata[0]\n\nif intcomp(testdata) == 3500:\n print('Intcode computer test successful')\nelse:\n print('Intcode computer test failure')\n quit()\n\nintcomp(inputdata)\n" }, { "alpha_fraction": 0.4155290126800537, "alphanum_fraction": 0.4744027256965637, "avg_line_length": 42.407405853271484, "blob_id": "96ef0b8753d0eba4bf22606b43e2e19cb827e26f", "content_id": "02456212681924dcfb9e1de4d3d3dd994564c75f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2344, "license_type": "permissive", "max_line_length": 190, "num_lines": 54, "path": "/2019/day10_2.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\nimport math\n\ndef bestaster(asters):\n maxloc = [0,0,0]\n for y0 in range(len(asters)):\n for x0 in range(len(asters[y0])):\n slopes = {}\n if asters[y0][x0] == 1:\n for y1 in range(len(asters)):\n for x1 in range(len(asters[y1])):\n if asters[y1][x1] == 1:\n if y1-y0 >= 0 and x1-x0 >= 0: q = 1\n elif y1-y0 <= 0 and x1-x0 > 0: q = 2\n elif y1-y0 <= 0 and x1-x0 <= 0: q = 3\n else: q = 4\n if q == 1 and x1-x0 == 0: slope = 999999999\n elif q == 3 and x1-x0 == 0: slope = -999999999\n else:\n slope = (y1-y0)/(x1-x0)\n slopes.setdefault(q, {})\n slopes[q].setdefault(slope, {})\n distance = math.sqrt(((x1-x0)**2)+((y1-y0)**2))\n slopes[q][slope].setdefault(distance, [])\n slopes[q][slope][distance].append([x1,y1])\n slopescount = 0\n for i in slopes:\n for j in slopes[i]:\n # for k in slopes[i][j]:\n # for l in slopes[i][j][k]:\n slopescount += 1\n if slopescount > maxloc[0]:\n maxloc = [slopescount,x0,y0]\n maxslopes = slopes.copy()\n # print(slopes)\n print('The best asteroid is at (%i,%i), with %i others visible.' % (maxloc[1],maxloc[2],maxloc[0]))\n return maxloc, maxslopes\n\n\n\nif bestaster(fileimp.asterimp('day10-1test1.txt'))[0][0] != 35 or bestaster(fileimp.asterimp('day10-1test2.txt'))[0][0] != 41 or bestaster(fileimp.asterimp('day10-1test3.txt'))[0][0] != 210:\n print('Tests failed!')\n quit()\n\ndef laser(filename):\n loc, slopes = bestaster(fileimp.asterimp(filename))\n for q in slopes:\n for slope in slopes[q]:\n \n#find best asteroid (23,19) (loc[1],loc[2])\n#find distance to each other asteroid (sqrt((x1-x0)^2+(y1-y0)^2)) slopes[q][slope][distance]\n#starting straight up (slope 999999999) in q1, shoot closest min(slopes[q][slope])\n#increment smaller slopes, shoot closest\n#keep counter, @ 199: x1*100 + y1\n" }, { "alpha_fraction": 0.5784946084022522, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 26.352941513061523, "blob_id": "88f8473eb14c007ee150b6fe5788e2384da06a38", "content_id": "278f84b14daf3e2cc1b5ad9950d6658827232a93", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 465, "license_type": "permissive", "max_line_length": 73, "num_lines": 17, "path": "/2019/day8-1.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n\ndef countint(imglist,num):\n count = 0\n for i in range(len(imglist)):\n for j in range(len(imglist[i])):\n if imglist[i][j] == num:\n count += 1\n return count\n\nimage = fileimp.sifimp('day8-1input.txt',25,6)\nzeros = []\nfor i in range(len(image)):\n zeros.append(countint(image['L%i' % i],0))\nmindex = zeros.index(min(zeros))\nans = countint(image['L%i' % mindex],1)*countint(image['L%i' % mindex],2)\nprint(ans)\n" }, { "alpha_fraction": 0.5985915660858154, "alphanum_fraction": 0.6161971688270569, "avg_line_length": 28.128204345703125, "blob_id": "716b1ad49ce4dc6c8a3f5b2e315fe83351245cfb", "content_id": "9b697ed6903c889b42152565c4ce2702645b516b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1136, "license_type": "permissive", "max_line_length": 69, "num_lines": 39, "path": "/2020/d02.1.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n\n# import list of strings\n# split strings into min, max, letter, and password\n #string.split('')\n# count letter in password\n# check within min max\n# iterate count\n\ndef parsepasslist(list):\n returnlist = []\n for i in range(len(list)):\n onepasslist = []\n temp = list[i].split(' ')\n onepasslist.append(int(temp[0].split('-')[0]))\n onepasslist.append(int(temp[0].split('-')[1]))\n onepasslist.append(temp[1].split(':')[0])\n onepasslist.append(temp[2])\n returnlist.append(onepasslist)\n# print(returnlist)\n return returnlist\n\ndef countletters(list):\n passwordcount = 0\n for i in range(len(list)):\n lettercount = 0\n for j in list[i][3]:\n if j == list[i][2]:\n lettercount = lettercount + 1\n if list[i][0] <= lettercount <= list[i][1]:\n passwordcount = passwordcount + 1\n return passwordcount\n\nif countletters(parsepasslist(fileimp.listimp('d02.test.txt'))) != 2:\n print(\"Test Failed!\")\n quit()\n\nx = countletters(parsepasslist(fileimp.listimp('d02.input.txt')))\nprint(x,'successful passwords')\n" }, { "alpha_fraction": 0.592903196811676, "alphanum_fraction": 0.6348387002944946, "avg_line_length": 26.678571701049805, "blob_id": "c90d42884dcf15b223078b20fac44c4241f32da9", "content_id": "358e4e38f448ebeb56814860c4ad683864af5a6c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1550, "license_type": "permissive", "max_line_length": 115, "num_lines": 56, "path": "/2019/day16-1.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n\npatt = [0,1,0,-1]\n\n# import input list\n# generate pattern list\n# pattern list repeats through patt until list is input+1 long\n# pattern list generates based on number of times through so that each patt member gets i+1 entries per iteration\n# lose first pattern list item\n# multiply input list item to corresponding patt list item\n# add each multiplied item and abs(modal 10)\n# build new input list as long as input and repeat for required steps\n\ndef pattlistgen(patt,step,inlength):\n list = []\n while len(list) <= inlength:\n for i in patt:\n j = 0\n while j <= step:\n list.append(i)\n j+=1\n\n list.pop(0)\n return list\n\ndef listcalc(inlist):\n outlist = []\n for i in range(len(inlist)):\n pattlist = pattlistgen(patt,i,len(inlist))\n linetot = 0\n for j in range(len(inlist)):\n linetot += (inlist[j] * pattlist[j])\n outlist.append(abs(linetot) % 10)\n # print(outlist)\n return outlist\n\ndef firsteight(inlist,steps):\n for i in range(steps):\n inlist = listcalc(inlist)\n output = 0\n for i in range(8):\n output += inlist[8 - (i+1)]*(10**i)\n return output\n\ndef testfile(filename,ans):\n test = firsteight(fileimp.fftimp(filename),100)\n if test != ans:\n print(test)\n print('Test failed')\n quit()\n\ntestfile('day16-1test1.txt',24176176)\ntestfile('day16-1test2.txt',73745418)\ntestfile('day16-1test3.txt',52432133)\n\nprint(firsteight(fileimp.fftimp('day16-1input.txt'),100))\n" }, { "alpha_fraction": 0.49866971373558044, "alphanum_fraction": 0.5264158248901367, "avg_line_length": 30.321428298950195, "blob_id": "9fceebca5c4f57762e357ff9b4b51e0036057e1d", "content_id": "b2e23b1422c2774de9a9c4498ecc607fb22ae1ab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2631, "license_type": "permissive", "max_line_length": 132, "num_lines": 84, "path": "/2019/day12-2nohash.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\nimport hashlib\nimport time\n\ndef moonimp(filename):\n inlist = fileimp.intimp(filename)\n moons = {}\n i = 0\n m = 0\n while i < len(inlist):\n moons.setdefault('moon%i' % m,[inlist[i],inlist[i+1],inlist[i+2],0,0,0])\n m += 1\n i += 3\n return moons\n\ndef moonpos(moons):\n\n for m in range(len(moons)):\n for i in range(3):\n moons['moon%i' % m][i] += moons['moon%i' % m][i+3]\n # print(moons)\n\ndef moonvel(moons):\n for m in range(len(moons)):\n n = m+1\n while n < len(moons):\n dvelx = moons['moon%i' % m][0] - moons['moon%i' % n][0]\n dvely = moons['moon%i' % m][1] - moons['moon%i' % n][1]\n dvelz = moons['moon%i' % m][2] - moons['moon%i' % n][2]\n if dvelx != 0:\n moons['moon%i' % m][3] -= round(dvelx/abs(dvelx))\n moons['moon%i' % n][3] += round(dvelx/abs(dvelx))\n if dvely != 0:\n moons['moon%i' % m][4] -= round(dvely/abs(dvely))\n moons['moon%i' % n][4] += round(dvely/abs(dvely))\n if dvelz != 0:\n moons['moon%i' % m][5] -= round(dvelz/abs(dvelz))\n moons['moon%i' % n][5] += round(dvelz/abs(dvelz))\n n += 1\n # print(moons)\n\ndef moonergy(moons):\n energy = 0\n for m in range(len(moons)):\n pot1 = abs(moons['moon%i' % m][0]) + abs(moons['moon%i' % m][1]) + abs(moons['moon%i' % m][2])\n kin1 = abs(moons['moon%i' % m][3]) + abs(moons['moon%i' % m][4]) + abs(moons['moon%i' % m][5])\n energy += (pot1 * kin1)\n print('System energy: %i' % energy)\n return energy\n\ndef mooncalc(filename,steps):\n moons = moonimp(filename)\n for i in range(steps):\n # print('Step %i' % i)\n # print('Calculating velocity...')\n moonvel(moons)\n # print('Calculating position...')\n moonpos(moons)\n # print(moons)\n print('Calculating energy...')\n return moonergy(moons)\n\ndef moonreturn(filename):\n moons = moonimp(filename)\n hash = str(moons)\n hashes = []\n while hash not in hashes:\n hashes.append(hash)\n moonvel(moons)\n moonpos(moons)\n hash = str(moons)\n # print(hash)\n # print(hashes)\n print('It took %i steps to return the system to repeat a position' % (len(hashes)))\n\n\nif mooncalc('day12-1test1.txt',10) != 179 or mooncalc('day12-1test2.txt',100) != 1940 or mooncalc('day12-1input.txt', 1000) != 9441:\n print('Test failed!')\n quit()\n\nt = time.time()\nprint('%i seconds' % (time.time()-t))\nmoonreturn('day12-1input.txt')\nprint('%i seconds' % (time.time()-t))\n" }, { "alpha_fraction": 0.4817170202732086, "alphanum_fraction": 0.5166931748390198, "avg_line_length": 23.19230842590332, "blob_id": "8e3b89859dec7f9591d1c6c7af8ddee47ce9b036", "content_id": "e60f0823d6ea577411e403839cacc349d26e84c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 629, "license_type": "permissive", "max_line_length": 58, "num_lines": 26, "path": "/2020/d01.1.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n\n# import data as list\n# find pair that adds up to 2020\n# multiply pair\n\ndef paircalc(intlist):\n for i in range(len(intlist)-1):\n for j in range(i+1,len(intlist)):\n x = intlist[i]\n y = intlist[j]\n #print(i,' ',j)\n if x + y == 2020:\n print('2020 sum found at i=', x, ' j=', y)\n ans = x * y\n return ans\n else:\n pass\n\ntestint = paircalc(fileimp.intimp('d1.test.txt'))\n#print(testint)\nif testint != 514579:\n print('Test failed!')\n quit()\n\nprint(paircalc(fileimp.intimp('d1.input.txt')))\n" }, { "alpha_fraction": 0.6674242615699768, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 22.157894134521484, "blob_id": "2c548a9f4423e3fec8a00d9fe5ff79398d4c4c87", "content_id": "26b2172aec5934ea3abb5faf936b2391217664ce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1320, "license_type": "permissive", "max_line_length": 78, "num_lines": 57, "path": "/2019/day6-1.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "#Solution for https://adventofcode.com/2019/day/6\n\nimport sys\n\nclass Orb(object):\t\t\t#Orbit object that has a name and a single parent\n\tdef __init__(self):\n\t\tself.name = None\n\t\tself.parent = None\n\tdef count(self): \t\t#count all of the parents and grandparents this object has\n\t\t#iterate through all parents and increment by 1 for each until None\n#\t\tprint('count method initiated')\n\t\tcnt = 0\n\t\tX = self\n\t\twhile X.parent != None:\n#\t\t\tprint(X.name)\n#\t\t\tprint(X.parent)\n\t\t\tcnt +=1\n\t\t\tX = X.parent\n#\t\t\tprint(cnt)\n\t\treturn cnt\n\n#build orbits from file function\ndef orbuild(filename):\n\tfile = open(filename,'r')\n\t#readline\n\torbs = {}\n\tfor x in file:\n#\t\tprint(x)\n\t\tz = x.rstrip('\\n')\n\t\ty = z.split(')')\n#\t\tprint(y)\n\t\torbs.setdefault(y[0],Orb())\n\t\torbs.setdefault(y[1],Orb())\n\t\torbs[y[1]].parent = orbs[y[0]]\n\treturn orbs\n\t#parse line with separator\n\t#check if parent exists, create if not\n\t#create child Orb\n\n#count all orbits in file\ndef orbitcount(orbdict):\n\tc = 0\n\tfor x in orbdict:\n\t\tc += orbdict[x].count()\n\treturn c\n\n#test section\norbitest = orbuild('day6-1test.txt')\norbitestcount = orbitcount(orbitest)\nif orbitestcount != 42:\n\tprint('orbitest failure')\n\tquit()\nelse: print('orbitest success')\n\nloadfile = 'day6-1input.txt'\norbits = orbuild(loadfile)\nprint('The total orbits of %s are %i' % (loadfile,orbitcount(orbits)))\n" }, { "alpha_fraction": 0.45781466364860535, "alphanum_fraction": 0.4951590597629547, "avg_line_length": 23.100000381469727, "blob_id": "a761514b66491c0782431a7b63e540b9a4e1c3fa", "content_id": "3aaa6ca3daad7ffd29e27e347713a2d8a4f47cca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 723, "license_type": "permissive", "max_line_length": 72, "num_lines": 30, "path": "/2020/d01.2.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n\n# import data as list\n# find pair that adds up to 2020\n# multiply pair\n\ndef tripcalc(intlist):\n for i in range(len(intlist)-2):\n x = intlist[i]\n\n for j in range(i+1,len(intlist)-1):\n y = intlist[j]\n\n for k in range(j+1,len(intlist)):\n z = intlist[k]\n\n if x + y + z == 2020:\n print('2020 sum found at i=', x, ' j=', y, ' k=', z)\n ans = x * y *z\n return ans\n else:\n pass\n\ntestint = tripcalc(fileimp.intimp('d1.test.txt'))\n#print(testint)\nif testint != 241861950:\n print('Test failed!')\n quit()\n\nprint(tripcalc(fileimp.intimp('d1.input.txt')))\n" }, { "alpha_fraction": 0.42563024163246155, "alphanum_fraction": 0.4323529303073883, "avg_line_length": 25.153846740722656, "blob_id": "ecf653dbaef4a5b9a583c5cef8266399d3eacd0f", "content_id": "de814306cadbf0e574c1fa4c893e63b55536e8f7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2380, "license_type": "permissive", "max_line_length": 66, "num_lines": 91, "path": "/2019/fileimp.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "def listimp(filename):\n with open(filename,'r') as file:\n list = []\n for line in file:\n line = line.rstrip('\\n')\n list.append(int(line))\n return list\n\ndef intimp(filename):\n list=[]\n with open(filename,'r') as file:\n for line in file:\n line = line.rstrip('\\n')\n inlist = line.split(',')\n # print(len(list))\n for x in range(len(inlist)):\n list.append(int(inlist[x]))\n print(\"Imported int list of length %i\" % len(list))\n return list\n\ndef wireimp(filename):\n with open(filename,'r') as file:\n wires = {}\n x=1\n for line in file:\n line = line.rstrip('\\n')\n list = line.split(',')\n wires['wire%i' % x] = list\n print(len(wires))\n x += 1\n print(\"Imported wire dictionary of length %i\" % len(wires))\n return wires\n\ndef sifimp(filename,w,h):\n list = []\n with open(filename,'r') as file:\n for line in file:\n line = line.rstrip('\\n')\n for ch in line:\n list.append(int(ch))\n image = {}\n line = []\n i = 0\n j = 0\n k = 0\n l = 0\n while i < len(list):\n image['L%i' % l] = []\n j = 0\n while j < h:\n # image['L%i' % l][j] = []\n line = []\n k = 0\n while k < w:\n line.append(list[i])\n print(line)\n i += 1\n k += 1\n image['L%i' % l].append(line.copy())\n print(image)\n j += 1\n l += 1\n return image\n\ndef asterimp(filename):\n asterlist = []\n with open(filename,'r') as file:\n i = 0\n for line in file:\n line = line.rstrip('\\n')\n j = 0\n linelist = []\n for ch in line:\n if ch == '.':\n linelist.append(0)\n elif ch == '#':\n linelist.append(1)\n else:\n print('Unexpected character at %i,%i' % (i,j))\n quit()\n asterlist.append(linelist)\n return asterlist\n\ndef fftimp(filename):\n list = []\n with open(filename,'r') as file:\n for line in file:\n line = line.rstrip('\\n')\n for ch in line:\n list.append(int(ch))\n return list\n" }, { "alpha_fraction": 0.5864115953445435, "alphanum_fraction": 0.6233509182929993, "avg_line_length": 35.095237731933594, "blob_id": "e1fa56bde3e820149e62adce360ba70873c8bdf3", "content_id": "abc963ae501f75387b1f2034f0f14831fa06eb05", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1516, "license_type": "permissive", "max_line_length": 102, "num_lines": 42, "path": "/2020/d03.2.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n\n# import grid as list of lists\n# traverse grid input(filename, dx, dy)\n# increment x and y by dx and dy\n# check if new x pos is outside of grid\n# reset grid position for repeating grid\n# count 1s as trees, do not count 0s\n\ndef counttrees(treelist, dx, dy):\n# print('treelist: max Y =', len(treelist)-1, ', max X =', len(treelist[0])-1)\n x = 0\n y = 0\n treecount = 0\n while y < len(treelist):\n# print('line =', y, ', column =', x, ', value = ', treelist[y][x], ', treecount =', treecount)\n treecount = treecount + treelist[y][x]\n if (x + dx) > len(treelist[y])-1: #grids repeat, expect x > width\n x = dx - (len(treelist[y]) - (x)) #reset grid position for repeating grid\n else:\n x = x + dx\n y = y + dy\n return treecount\n\nif(\\\ncounttrees(fileimp.gridimp('d03.test.txt'),1,1) *\\\ncounttrees(fileimp.gridimp('d03.test.txt'),3,1) *\\\ncounttrees(fileimp.gridimp('d03.test.txt'),5,1) *\\\ncounttrees(fileimp.gridimp('d03.test.txt'),7,1) *\\\ncounttrees(fileimp.gridimp('d03.test.txt'),1,2))\\\n!= 336:\n print(\"Test Failed!\")\n quit()\n\n#print('number of trees =', counttrees(fileimp.gridimp('d03.input.txt'),3,1))\ntrees =\\\ncounttrees(fileimp.gridimp('d03.input.txt'),1,1) *\\\ncounttrees(fileimp.gridimp('d03.input.txt'),3,1) *\\\ncounttrees(fileimp.gridimp('d03.input.txt'),5,1) *\\\ncounttrees(fileimp.gridimp('d03.input.txt'),7,1) *\\\ncounttrees(fileimp.gridimp('d03.input.txt'),1,2)\nprint('number of trees =', trees)\n" }, { "alpha_fraction": 0.43041473627090454, "alphanum_fraction": 0.4516128897666931, "avg_line_length": 22.085105895996094, "blob_id": "2502fb983c22eb585d82aa8b8c88044b7b9e3bf1", "content_id": "77592dd99f28334c1a356341edde3b576368b416", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1085, "license_type": "permissive", "max_line_length": 60, "num_lines": 47, "path": "/2020/d05_1.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n\n# divide rows 0-127\n# F = lower half\n# B = upper half\n# divide columns 0-7\n# R = upper half\n# L = lower half\n# seat ID = row * 8 + col\n# list of IDs\n# max list\n\ndef idcalc(list):\n seats = []\n for i in list:\n row = ''\n col = ''\n for j in i:\n if j == 'F':\n row = row + '0'\n elif j == 'B':\n row = row + '1'\n elif j == 'R':\n col = col + '1'\n elif j == 'L':\n col = col + '0'\n else:\n print(\"something went wrong in rows & cols\")\n quit()\n print(row, col)\n # row = row[::-1]\n # col = col[::-1]\n print(row, col)\n row = int(row, 2)\n col = int(col, 2)\n print(row, col)\n seats.append((row * 8) + col)\n print(seats)\n return seats\n\ntestlist = fileimp.listimp(\"d05_test.txt\")\nif max(idcalc(testlist)) != 820:\n print(\"Test Failed!\")\n quit()\n\nseatlist = fileimp.listimp(\"d05_input.txt\")\nprint(\"Largest seat ID = \", max(idcalc(seatlist)))\n" }, { "alpha_fraction": 0.6372212767601013, "alphanum_fraction": 0.6475128531455994, "avg_line_length": 33.29411697387695, "blob_id": "e5014f05769a8997d0b06bbe03fabf0f0da6a6f6", "content_id": "afb007e562dd9d8b7f1bb2ad9fcade2884cd68dd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1166, "license_type": "permissive", "max_line_length": 66, "num_lines": 34, "path": "/2020/d06_2.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\nimport string\n\n# import file as list, clean list\n# for each list item, scrub through string, noting unique answers\n# string.find() != -1\n# groupanslist = 0 list of len(findlist)\n# answers = list of individual answers per group\n# if findlist[x] exists in answers[i], increment groupanslist[x]\n# if groupanslist[x] = len(answers), increment group total\n\ndef groupagrees(stringlist,findlist):\n total = 0\n for i in stringlist:\n groupanslist = [0] * len(findlist)\n answers = i.split()\n for j in answers:\n for k in range(len(findlist)):\n if j.find(findlist[k]) != -1:\n groupanslist[k] = groupanslist[k] + 1\n for j in groupanslist:\n if j == len(answers):\n total = total + 1\n print(total)\n return total\n\ntestlist = fileimp.cleanlist(fileimp.listimp('d06_test.txt'))\nif groupagrees(testlist,list(string.ascii_lowercase)) != 6:\n print(\"Test Failed!\")\n quit()\n\ngrouplist = fileimp.cleanlist(fileimp.listimp('d06_input.txt'))\ntotal = groupagrees(grouplist,list(string.ascii_lowercase))\nprint(\"Total added of agreed per group =\", total)\n" }, { "alpha_fraction": 0.587135374546051, "alphanum_fraction": 0.6073298454284668, "avg_line_length": 30.83333396911621, "blob_id": "7b66bf3b5b2243439c437075674b3e8be0d79604", "content_id": "b425e51196a2a20036ddcc53f201fba86b01acd1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1337, "license_type": "permissive", "max_line_length": 100, "num_lines": 42, "path": "/2020/d02.2.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n\n# import list of strings\n# split strings into min, max, letter, and password\n #string.split('')\n# count letter in password\n# check within min max\n# iterate count\n\ndef parsepasslist(list):\n returnlist = []\n for i in range(len(list)):\n onepasslist = []\n temp = list[i].split(' ')\n onepasslist.append(int(temp[0].split('-')[0]))\n onepasslist.append(int(temp[0].split('-')[1]))\n onepasslist.append(temp[1].split(':')[0])\n onepasslist.append(temp[2])\n returnlist.append(onepasslist)\n# print(returnlist)\n return returnlist\n\ndef positletters(list):\n passwordcount = 0\n for i in range(len(list)):\n lettercount = 0\n success = 0\n for j in list[i][3]:\n lettercount = lettercount + 1\n if ((j == list[i][2]) and ((lettercount == list[i][0]) or (lettercount == list[i][1]))):\n success = success + 1\n if success == 1:\n print(i,list[i][0],list[i][1],lettercount,j,list[i][2],passwordcount+1)\n passwordcount = passwordcount + 1\n print(passwordcount,'successful passwords')\n return passwordcount\n\nif positletters(parsepasslist(fileimp.listimp('d02.test.txt'))) != 1:\n print(\"Test Failed!\")\n quit()\n\nx = positletters(parsepasslist(fileimp.listimp('d02.input.txt')))\n" }, { "alpha_fraction": 0.6706507205963135, "alphanum_fraction": 0.6799468994140625, "avg_line_length": 23.03191566467285, "blob_id": "f5591a707a8bbc4a1ac7399d02926d441ce49e4d", "content_id": "8c3c9dbdb3caa18cf63f3fd669dd64bab4826233", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2259, "license_type": "permissive", "max_line_length": 79, "num_lines": 94, "path": "/2019/day6-2.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "#Solution for https://adventofcode.com/2019/day/6\n\nimport sys\n\nclass Orb(object):\t\t\t#Orbit object that has a name and a single parent\n\tdef __init__(self):\n\t\tself.name = None\n\t\tself.parent = None\n\tdef count(self): \t\t#count all of the parents and grandparents this object has\n#\t\titerate through all parents and increment by 1 for each until None\n#\t\tprint('count method initiated')\n\t\tcnt = 0\n\t\tX = self\n\t\twhile X.parent != None:\n#\t\t\tprint(X.name)\n#\t\t\tprint(X.parent)\n\t\t\tcnt +=1\n\t\t\tX = X.parent\n#\t\t\tprint(cnt)\n\t\treturn cnt\n\n#build orbits from file function. returns dict\ndef orbuild(filename):\n\tfile = open(filename,'r')\n\t#readline\n\torbs = {}\n\tfor x in file:\n#\t\tprint(x)\n\t\tz = x.rstrip('\\n')\n\t\ty = z.split(')')\n#\t\tprint(y)\n\t\torbs.setdefault(y[0],Orb())\n\t\torbs.setdefault(y[1],Orb())\n\t\torbs[y[1]].parent = orbs[y[0]]\n\t\torbs[y[1]].name = y[1]\n\treturn orbs\n\n#count all orbits in file. returns int\ndef orbitcount(orbdict):\n\tc = 0\n\tfor x in orbdict:\n\t\tc += orbdict[x].count()\n\treturn c\n\n#find the shortest route between two orbits, returns int\ndef orbitmeet(orbdict,one,two):\n\tmeetdict = {}\n\t#make a sub-dict for one to root path\n\tX = orbdict[one]\n\twhile X.name in orbdict:\n#\t\tNull()\n\t\tprint('Adding %s' % X.name)\n\t\tmeetdict.setdefault(X.name,X)\n\t\tX = X.parent\n\tprint('After %s, meetdict is:' % one)\n\tprint(meetdict)\n\t#make a sub-dict for two to first shared node\n\tX = orbdict[two]\n\tY = Orb()\n\twhile X.name in orbdict:\n\t\tif X.name not in meetdict:\n\t\t\tprint('Adding %s' % X.name)\n\t\t\tmeetdict.setdefault(X.name,X)\n\t\t\tX = X.parent\n\t\telse: break\n\tprint('After %s, meetdict is:' % two)\n\tprint(meetdict)\n\n\tY = X.parent\n\tX.parent = None\n\twhile Y.name in meetdict:\n\t\tprint('Removing %s' % Y.name)\n\t\tmeetdict.pop(Y.name)\n\t\tY = Y.parent\n\tprint(\"After cleanup, meetdict is:\")\n\tprint(meetdict)\n\n\treturn len(meetdict)-3\t#minus start, end, and one stop (counting jumps)\n\n\n#test section\norbitest = orbuild('day6-2test.txt')\nprint(orbitest)\norbitestcount = orbitmeet(orbitest,'YOU','SAN')\nprint(orbitestcount)\nif orbitestcount != 4:\n\tprint('orbitest failure')\n\tquit()\nelse: print('orbitest success')\n\nloadfile = 'day6-1input.txt'\norbits = orbuild(loadfile)\norbitmeetcount = orbitmeet(orbits,'YOU','SAN')\nprint('The shortest distance between YOU and SAN is %i jumps' % orbitmeetcount)\n" }, { "alpha_fraction": 0.5143918395042419, "alphanum_fraction": 0.5264623761177063, "avg_line_length": 25.268293380737305, "blob_id": "4a0192f76628dd3514dfe613f2e7a6745df74329", "content_id": "ac2ea9a8a3f88872ca7bea6bf7234786d71861b9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1077, "license_type": "permissive", "max_line_length": 73, "num_lines": 41, "path": "/2019/day8_2.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n\ndef countint(imglist,num):\n count = 0\n for i in range(len(imglist)):\n for j in range(len(imglist[i])):\n if imglist[i][j] == num:\n count += 1\n return count\n\ndef imgbuild(imgdict):\n imglist = imgdict['L0']\n for i in range(len(imgdict)):\n for j in range(len(imgdict['L%i' % i])):\n for k in range(len(imgdict['L%i' % i][j])):\n if imglist[j][k] == 2:\n imglist[j][k] = imgdict['L%i' % i][j][k]\n return imglist\n\ndef imgdisplay(imglist):\n img = []\n for i in range(len(imglist)):\n list = []\n for j in range(len(imglist[i])):\n if imglist[i][j] == 1:\n list.append('#')\n else:\n list.append('.')\n print(list)\n\n\nimage = fileimp.sifimp('day8-1input.txt',25,6)\n\nzeros = []\nfor i in range(len(image)):\n zeros.append(countint(image['L%i' % i],0))\nmindex = zeros.index(min(zeros))\nans = countint(image['L%i' % mindex],1)*countint(image['L%i' % mindex],2)\nprint(ans)\n\nimgdisplay(imgbuild(image))\n" }, { "alpha_fraction": 0.4172293245792389, "alphanum_fraction": 0.44889405369758606, "avg_line_length": 28.0202693939209, "blob_id": "197b6ca810f19e9c3b8588dd610d9063b74491a0", "content_id": "16263b30e30617c8b585236216b48740c07cd625", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4295, "license_type": "permissive", "max_line_length": 117, "num_lines": 148, "path": "/2019/intcomp.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "def getcode(intnum):\n strnum = str(intnum)\n code = []\n for i in range(len(strnum)):\n code.insert(i,int(strnum[i]))\n while len(code) < 5:\n code.insert(0,0)\n print('code:')\n print(code)\n return code\n\ndef getvalue(listdata,mode,loc):\n print('mode: %i, loc: %i' % (mode,loc))\n try:\n if mode == 0:\n # print(listdata[loc])\n return listdata[loc]\n elif mode == 1:\n # print(loc)\n return loc\n else:\n print('Unrecognized mode: %i' % mode)\n quit()\n except:\n listdata.append(-1)\n return -1\n\ndef getvals(listdata,code,loc,params):\n mode = [code[2],code[1],code[0]]\n ploc = [loc+1,loc+2,loc+3]\n for i in range(params):\n vals[i] = getvalue(listdata,mode[i],ploc[i])\n return vals\n\ndef intop3(listdata,code,loc,params):\n listd = getvals(listdata,code,loc,params)\n listdata[listdata[loc+1]] = int(input('Enter intcomp value: '))\n\ndef intop4(listdata,code,loc,params):\n print('Intcomp value output: %i' % listdata[listdata[loc+1]])\n listd = getvals(listdata,code,loc,params)\n if listd[0] != 0:\n if listdata[x+2] == 99:\n print('Diagnostic code: %i' % listd[0])\n quit()\n else:\n print('Unexpected value %i at location %i' % (listd[0],listdata[x+1]))\n quit()\n\n\ndef intcomp(listdata):\n x = 0\n while x < len(listdata):\n print('x = %i' % x)\n code = getcode(listdata[x])\n op = code[-1] + (code[-2] * 10)\n pval1 = getvalue(listdata,mode1,ploc1)\n listd1 = listdata[pval1]\n params = 1\n\n if op == 99:\n break\n\n elif op == 3:\n listop3(listdata,code,x,params)\n x += \n\n elif op == 4:\n listop4(listdata,code,x,params)\n x += 2\n\n else:\n params = 2\n pval2 = getvalue(listdata,mode2,ploc2)\n listd2 = listdata[pval2]\n\n if op == 5:\n if listd1 != 0:\n x += listd2\n else:\n x +=\n\n elif op == 6:\n if listd1 == 0:\n x += listd2\n else:\n x += 3\n\n else:\n pval3 = getvalue(listdata,mode3,ploc3)\n listd3 = listdata[pval3]\n\n if op == 1:\n listdata[pval3] = listd2 + listd1\n print('%i at listdata[%i]' % (listd3,pval3))\n x += 4\n # print(listdata)\n\n elif op == 2:\n listdata[pval3] = listd2 * listd1\n print('%i at listdata[%i]' % (listd3,pval3))\n x += 4\n # print(listdata)\n\n elif op == 7:\n if listd1 < listd2:\n listdata[pval3] = 1\n print('1 at listdata[%i]' % pval3)\n else:\n listdata[pval3] = 0\n print('0 at listdata[%i]' % pval3)\n x += 4\n\n elif op == 8:\n if listd1 == listd2:\n listdata[pval3] = 1\n print('1 at listdata[%i]' % pval3)\n else:\n print('0 at listdata[%i]' % pval3)\n listdata[pval3] = 0\n x += 4\n\n else:\n print('Unexpected opcode: %i at %i' % (listdata[x], x))\n x += 4\n break\n x += params+1\n print(listdata)\n print('Intcode computer position 0 = %i' % listdata[0])\n return listdata[0]\n\nprint('If input < 8, output should be 999. If input = 8, output should be 1000. If input > 8, output should be 1001')\nintcomp(testdata)\n\nfilename = input('Enter data file name: ')\nlistdata = fileimp.intimp(filename)\nintcomp(listdata)\n\n# for noun in range(100):\n# for verb in range(100):\n# indat = inputdata.copy()\n# indat[1] = noun\n# indat[2] = verb\n# if intcomp(indat) == 19690720:\n# print('Final intcode: %s' % indat)\n# print('noun=%i' % noun)\n# print('verb=%i' % verb)\n# quit()\n" }, { "alpha_fraction": 0.38187703490257263, "alphanum_fraction": 0.5443365573883057, "avg_line_length": 35.78571319580078, "blob_id": "d43f0759d06414b8dbd63c8daee0aa8431c0f074", "content_id": "8f2021aef17715129edb1e0d012649f528e1fd1f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1545, "license_type": "permissive", "max_line_length": 322, "num_lines": 42, "path": "/2019/day2-2.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "#Solution for https://adventofcode.com/2019/day/2\ntestdata = [1,9,10,3,2,3,11,0,99,30,40,50]\ninputdata = [1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,10,19,1,6,19,23,2,23,6,27,2,6,27,31,2,13,31,35,1,10,35,39,2,39,13,43,1,43,13,47,1,6,47,51,1,10,51,55,2,55,6,59,1,5,59,63,2,9,63,67,1,6,67,71,2,9,71,75,1,6,75,79,2,79,13,83,1,83,10,87,1,13,87,91,1,91,10,95,2,9,95,99,1,5,99,103,2,10,103,107,1,107,2,111,1,111,5,0,99,2,14,0,0]\n\ndef intcomp(listdata):\n x = 0\n while inputdata[x] != 99:\n if listdata[x] == 1:\n listdata[listdata[x+3]] = listdata[listdata[x+1]] + listdata[listdata[x+2]]\n x += 4\n# print(listdata)\n elif listdata[x] == 2:\n listdata[listdata[x+3]] = listdata[listdata[x+1]] * listdata[listdata[x+2]]\n x += 4\n# print(listdata)\n elif listdata[x] == 99:\n return listdata[0]\n break\n\n else:\n print('Unexpected opcode: %i at %i' % (listdata[x], x))\n x += 4\n break\n\n# print('Intcode computer position 0 = %i' % listdata[0])\n return listdata[0]\n\nif intcomp(testdata) == 3500:\n print('Intcode computer test successful')\nelse:\n print('Intcode computer test failure')\n quit()\nfor noun in range(100):\n for verb in range(100):\n indat = inputdata.copy()\n indat[1] = noun\n indat[2] = verb\n if intcomp(indat) == 19690720:\n print('Final intcode: %s' % indat)\n print('noun=%i' % noun)\n print('verb=%i' % verb)\n quit()\n" }, { "alpha_fraction": 0.5690486431121826, "alphanum_fraction": 0.6128891110420227, "avg_line_length": 24.920454025268555, "blob_id": "f0b1485e55151887007fcdb72e96221d16aeb859", "content_id": "6309aa37526ef1a78c8c17d5e7b192cad4b3f677", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2281, "license_type": "permissive", "max_line_length": 115, "num_lines": 88, "path": "/2019/day16_2.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n\npatt = [0,1,0,-1]\n\n# import input list\n# generate pattern list\n# pattern list repeats through patt until list is input+1 long\n# pattern list generates based on number of times through so that each patt member gets i+1 entries per iteration\n# lose first pattern list item\n# multiply input list item to corresponding patt list item\n# add each multiplied item and abs(modal 10)\n# build new input list as long as input and repeat for required steps\n\ndef pattlistgen(patt,step,inlength):\n list = []\n while len(list) <= inlength:\n for i in patt:\n j = 0\n while j <= step:\n list.append(i)\n j+=1\n\n list.pop(0)\n # print(len(list))\n return list\n\ndef listcalc(inlist):\n outlist = []\n p = 0\n for i in range(len(inlist)):\n pattlist = pattlistgen(patt,i,len(inlist))\n linetot = 0\n for j in range(len(inlist)):\n linetot += (inlist[j] * pattlist[j])\n outlist.append(abs(linetot) % 10)\n p2 = p\n p = int(i/len(inlist))\n if p2 != p:\n print(p)\n # print(outlist)\n return outlist\n\ndef firsteight(inlist,steps):\n for i in range(steps):\n inlist = listcalc(inlist)\n output = 0\n for i in range(8):\n output += inlist[8 - (i+1)]*(10**i)\n return output\n\ndef whicheight(inlist,steps):\n for i in range(steps):\n inlist = listcalc(inlist)\n print(i)\n output = 0\n for i in range(8):\n index = offset + 8 - i + 1\n print(len(inlist))\n print(index)\n output += inlist[index]*(10**i)\n return output\n\ndef newlist(inlist,repeats):\n outlist = []\n for i in range(repeats):\n for j in inlist:\n outlist.append(j)\n print(len(outlist))\n return outlist\n\ndef testfile(filename,ans,repeats):\n test = whicheight(newlist(fileimp.fftimp(filename),repeats),100)\n if test != ans:\n print(test)\n print('Test failed')\n quit()\n\ntestfile('day16-1test1.txt',84462026,10000)\ntestfile('day16-1test2.txt',78725270,10000)\ntestfile('day16-1test3.txt',53553731,10000)\n\n\n\nthislist = newlist(fileimp.fftimp('day16-1input.txt'),10000)\n\nprint(whicheight(thislist,100,offset))\n\n# print(firsteight(fileimp.fftimp('day16-1input.txt'),100))\n" }, { "alpha_fraction": 0.4501303732395172, "alphanum_fraction": 0.5413950681686401, "avg_line_length": 32.71428680419922, "blob_id": "8edb0e90a29a5bf0bafaa20a7ff39f126f01be9a", "content_id": "222dda4f2e6c476d35914f1d1c498fddf7343cf6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3068, "license_type": "permissive", "max_line_length": 324, "num_lines": 91, "path": "/2019/day5-1.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n#Solution for https://adventofcode.com/2019/day/5\ntestdata = [1,9,10,3,2,3,11,0,99,30,40,50]\n# inputdata = [1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,10,19,1,6,19,23,2,23,6,27,2,6,27,31,2,13,31,35,1,10,35,39,2,39,13,43,1,43,13,47,1,6,47,51,1,10,51,55,2,55,6,59,1,5,59,63,2,9,63,67,1,6,67,71,2,9,71,75,1,6,75,79,2,79,13,83,1,83,10,87,1,13,87,91,1,91,10,95,2,9,95,99,1,5,99,103,2,10,103,107,1,107,2,111,1,111,5,0,99,2,14,0,0]\n\ndef getcode(intnum):\n strnum = str(intnum)\n code = []\n for i in range(len(strnum)):\n code.insert(i,int(strnum[i]))\n while len(code) < 5:\n code.insert(0,0)\n print('code:')\n print(code)\n return code\n\ndef getvalue(listdata,mode,loc):\n print('mode: %i, loc: %i' % (mode,loc))\n if mode == 0:\n print(listdata[loc])\n return listdata[loc]\n elif mode == 1:\n print(loc)\n return loc\n else:\n print('Unrecognized mode: %i' % mode)\n quit()\n\ndef intcomp(listdata):\n x = 0\n while x < len(listdata):\n print('x = %i' % x)\n code = getcode(listdata[x])\n op = code[len(code)-1] + (code[len(code)-2] * 10)\n\n if op == 1:\n listdata[getvalue(listdata,code[len(code)-5],x+3)] = listdata[getvalue(listdata,code[len(code)-4],x+2)] + listdata[getvalue(listdata,code[len(code)-3],x+1)]\n x += 4\n print(listdata)\n\n elif op == 2:\n listdata[getvalue(listdata,code[len(code)-5],x+3)] = listdata[getvalue(listdata,code[len(code)-4],x+2)] * listdata[getvalue(listdata,code[len(code)-3],x+1)]\n x += 4\n print(listdata)\n\n elif op == 3:\n listdata[listdata[x+1]] = int(input('Enter intcomp value: '))\n x += 2\n\n elif op == 4:\n print('Intcomp value output: %i' % listdata[listdata[x+1]])\n if listdata[getvalue(listdata,code[len(code)-3],x+1)] != 0:\n if listdata[x+2] == 99:\n print('Diagnostic code: %i' % listdata[getvalue(listdata,code[len(code)-3],x+1)])\n quit()\n print('Unexpected value %i at location %i' % (listdata[getvalue(listdata,code[len(code)-3],x+1)],listdata[x+1]))\n quit()\n x += 2\n\n elif op == 99:\n break\n\n else:\n print('Unexpected opcode: %i at %i' % (listdata[x], x))\n x += 4\n break\n\n print(listdata)\n print('Intcode computer position 0 = %i' % listdata[0])\n return listdata[0]\n\nif intcomp(testdata) == 3500:\n print('Intcode computer test successful')\nelse:\n print('Intcode computer test failure')\n quit()\n\nfilename = input('Enter data file name: ')\nlistdata = fileimp.intimp(filename)\nintcomp(listdata)\n\n# for noun in range(100):\n# for verb in range(100):\n# indat = inputdata.copy()\n# indat[1] = noun\n# indat[2] = verb\n# if intcomp(indat) == 19690720:\n# print('Final intcode: %s' % indat)\n# print('noun=%i' % noun)\n# print('verb=%i' % verb)\n# quit()\n" }, { "alpha_fraction": 0.38973647356033325, "alphanum_fraction": 0.45145630836486816, "avg_line_length": 40.20000076293945, "blob_id": "ca7faa420599d867ef76216937ebc7b6c1907176", "content_id": "3ac439a9ceb50eeb5a9ec2ef7f529abcfd72516f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1442, "license_type": "permissive", "max_line_length": 190, "num_lines": 35, "path": "/2019/day10-1.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n\n\ndef bestaster(asters):\n maxloc = [0,0,0]\n for y0 in range(len(asters)):\n for x0 in range(len(asters[y0])):\n slopes = {}\n if asters[y0][x0] == 1:\n for y1 in range(len(asters)):\n for x1 in range(len(asters[y1])):\n if asters[y1][x1] == 1:\n if y1-y0 >= 0 and x1-x0 >= 0: q = 1\n elif y1-y0 <= 0 and x1-x0 > 0: q = 2\n elif y1-y0 <= 0 and x1-x0 < 0: q = 3\n else: q = 4\n if x1-x0 == 0: slope = 999999999\n else:\n slope = (y1-y0)/(x1-x0)\n slopes.setdefault('%i,%f' % (q,slope), [])\n slopes['%i,%f' % (q,slope)].append([x1,y1])\n if len(slopes) > maxloc[0]:\n maxloc = [len(slopes),x0,y0]\n maxslopes = slopes.copy()\n # print(slopes)\n print('The best asteroid is at (%i,%i), with %i others visible.' % (maxloc[1],maxloc[2],maxloc[0]))\n return maxloc, maxslopes\n\n\n\nif bestaster(fileimp.asterimp('day10-1test1.txt'))[0][0] != 35 or bestaster(fileimp.asterimp('day10-1test2.txt'))[0][0] != 41 or bestaster(fileimp.asterimp('day10-1test3.txt'))[0][0] != 210:\n print('Tests failed!')\n quit()\n\nbestaster(fileimp.asterimp('day10-1input.txt'))\n" }, { "alpha_fraction": 0.448223739862442, "alphanum_fraction": 0.4731670320034027, "avg_line_length": 23.5, "blob_id": "21f9f3f0ba0930ccb4d8c1e5a60a5aab003519ef", "content_id": "bd5ca05c9c4a78108d9b5065335ce2787457b6f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1323, "license_type": "permissive", "max_line_length": 63, "num_lines": 54, "path": "/2020/d05_2.py", "repo_name": "PaulWichser/adventofcode", "src_encoding": "UTF-8", "text": "import fileimp\n\n# divide rows 0-127\n# F = lower half\n# B = upper half\n# divide columns 0-7\n# R = upper half\n# L = lower half\n# seat ID = row * 8 + col\n# list of IDs\n# find range of all seat IDs\n# if seat id doesn't exist in list, look for -1 and +1\n\ndef idcalc(list):\n seats = []\n for i in list:\n row = ''\n col = ''\n for j in i:\n if j == 'F':\n row = row + '0'\n elif j == 'B':\n row = row + '1'\n elif j == 'R':\n col = col + '1'\n elif j == 'L':\n col = col + '0'\n else:\n print(\"something went wrong in rows & cols\")\n quit()\n # print(row, col)\n # # row = row[::-1]\n # # col = col[::-1]\n # print(row, col)\n row = int(row, 2)\n col = int(col, 2)\n # print(row, col)\n seats.append((row * 8) + col)\n # print(seats)\n return seats\n\ndef findempty(list):\n for i in range(1,(127*8)+6):\n if (i not in list) and (i-1 in list) and (i+1 in list):\n print(\"your seat ID is \", i)\n\ntestlist = fileimp.listimp(\"d05_test.txt\")\nif max(idcalc(testlist)) != 820:\n print(\"Test Failed!\")\n quit()\n\nseatlist = fileimp.listimp(\"d05_input.txt\")\nidlist = idcalc(seatlist)\nfindempty(idlist)\n" } ]
30
dev9318/SOC
https://github.com/dev9318/SOC
84aea963788683dd68a16a970f9352cd95511de0
ea02d2cae176a4808bb33c0c75966fba28945b82
5d976da6dfd7b4da1b0c8b84efbd8ad58f4965f1
refs/heads/main
2022-12-27T14:00:07.505083
2020-10-17T10:10:51
2020-10-17T10:10:51
304,849,327
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4653465449810028, "alphanum_fraction": 0.5391539335250854, "avg_line_length": 17.491228103637695, "blob_id": "e02ec4a627df7a36bf6397250981bc37947e84d3", "content_id": "f8f5a075e361b06b7e24ac847f6200bdcd1a989c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1111, "license_type": "no_license", "max_line_length": 39, "num_lines": 57, "path": "/IA/Pandemic and array stimulations/DevM.Desai_ASS2 - Copy.py", "repo_name": "dev9318/SOC", "src_encoding": "UTF-8", "text": "from random import seed\r\nfrom random import randint\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.signal import savgol_filter \r\n\r\n# seed random number generator\r\nseed(1)\r\n\r\na=[0]\r\nno_of_1=[1] #y axis variable\r\nn=0\r\ndx=[0]\r\n\r\nfor i in range(19999):\r\n a.append(0)\r\n \r\n\r\n#my random 1\r\na[7010]=1\r\n\r\nwhile(1):\r\n #the magic basically adding 1s\r\n for i in range(20000):\r\n if(a[i]==1):\r\n if(randint(0,1)==0):\r\n a[i-1]=1\r\n else:\r\n a[(i+1)%20000]=1\r\n #swapping\r\n x=randint(0,19999)\r\n y=randint(0,19999)\r\n a[x]=a[y]+a[x]\r\n a[y]=a[x]-a[y]\r\n a[x]=a[x]-a[y]\r\n n=n+1\r\n #caz lists go out of range\r\n no_of_1.append(0)\r\n #counting 1s\r\n for i in range(20000):\r\n if(a[i]==1):\r\n no_of_1[n]=no_of_1[n] + 1\r\n dx.append(no_of_1[n]-no_of_1[n-1])\r\n if((int)(no_of_1[n])==20000):\r\n break\r\n\r\n\r\nx1=[1] #x axis variable\r\nfor i in range(n):\r\n x1.append(i+2)\r\nyhat=savgol_filter(dx, 51, 1)\r\n\r\n#plotting\r\nplt.plot(x1,dx)\r\nplt.plot(x1,yhat,color='red')\r\nplt.xlabel('no of repetitions')\r\nplt.ylabel('no of 1s')\r\nplt.show()\r\n" }, { "alpha_fraction": 0.3937210440635681, "alphanum_fraction": 0.46114256978034973, "avg_line_length": 22.56962013244629, "blob_id": "5057e5ebc9f94d620a08895d8f135993335664f0", "content_id": "f2633cd3a61eae834f0efd4fd2eb7b396cb3952d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1943, "license_type": "no_license", "max_line_length": 55, "num_lines": 79, "path": "/IA/Pandemic and array stimulations/SOC-TASK-3-DevM.Desai.py", "repo_name": "dev9318/SOC", "src_encoding": "UTF-8", "text": "from random import seed\r\nfrom random import randint\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.signal import savgol_filter \r\n\r\n# seed random number generator\r\nseed(1)\r\n\r\ndx=[0]\r\nn1=[]\r\na1=[] #y axis variable\r\n\r\n\r\nfor i1 in range(500):\r\n a1.append(i1)\r\n n1.append(0)\r\n no_of_1=[1]\r\n a=[0]\r\n for i in range(9999):\r\n a.append(0)\r\n a[5000]=1\r\n while(1):\r\n #swapping\r\n for j in range(5):\r\n x=randint(0,9999)\r\n y=randint(0,9999)\r\n a[x]=a[y]+a[x]\r\n a[y]=a[x]-a[y]\r\n a[x]=a[x]-a[y]\r\n #the magic basically adding 1s\r\n for i in range(10000):\r\n if(a[i]==1):\r\n if(randint(0,19)<7):\r\n a[i-1]=1\r\n elif(randint(0,19)<7):\r\n a[(i+1)%10000]=1\r\n n1[i1]=n1[i1]+1\r\n #caz lists go out of range\r\n no_of_1.append(0)\r\n #counting 1s\r\n for i in range(10000):\r\n if(a[i]==1):\r\n no_of_1[n1[i1]]=no_of_1[n1[i1]] + 1\r\n if(a1[-1]==0):\r\n dx.append(no_of_1[n1[i1]]-no_of_1[n1[i1]-1])\r\n if((int)(no_of_1[n1[i1]])==10000):\r\n break\r\n if(a1[-1]==0):\r\n x1=[1] #x axis variable\r\n for i in range(n1[0]):\r\n x1.append(i+2)\r\n plt.plot(x1,no_of_1,)\r\n plt.xlabel('no of repetitions')\r\n plt.ylabel('no of 1s')\r\n plt.show()\r\n plt.plot(x1,dx,color='yellow')\r\n plt.xlabel('x')\r\n yhat=savgol_filter(dx, 51, 1)\r\n plt.ylabel('dx')\r\n plt.plot(x1,yhat,color='red')\r\n plt.show()\r\n maxi=0\r\n maxy=0\r\n for i in range(n1[0]):\r\n if(dx[i]>maxi):\r\n maxi=dx[i]\r\n maxy=yhat[i]\r\n print(maxy)\r\n\r\n#plotting\r\nplt.plot(a1,n1)\r\nplt.ylabel('no of repetitions')\r\nplt.xlabel('no of iterations')\r\nplt.show()\r\n\r\nsum=0\r\nfor i in range(500):\r\n sum=sum+n1[i]/500\r\nprint(sum)\r\n\r\n" }, { "alpha_fraction": 0.27981752157211304, "alphanum_fraction": 0.3988702893257141, "avg_line_length": 35.30894470214844, "blob_id": "554871c77c22e9960dedd65384115b87f5165aff", "content_id": "b74c536dc0481dd097d3bc61609356bb07257c52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4603, "license_type": "no_license", "max_line_length": 278, "num_lines": 123, "path": "/IA/Pandemic and array stimulations/ASS3.py", "repo_name": "dev9318/SOC", "src_encoding": "UTF-8", "text": "from random import seed, randint, random\r\nimport copy\r\nimport matplotlib.pyplot as plt\r\n\r\nseed(1)\r\n\r\na=[]\r\n\r\n\r\nlens=[[330,500],[232,400],[215,400],[377,200],[300,200],[298,200],[283,200],[252,200],[249,200],[204,200],[173,200],[144,200],[138,200],[136,200],[129,200],[183,125],[168,125],[167,125],[83,100],[57,100],[60,50],[50,50],[42,50],[32,50],[48,25],[44,25],[36,25],[20,25],[139,100]]\r\nab=[]\r\nfor i1 in range(29):\r\n ab.append([[]])\r\n ab[i1] = [[0 for i in range(lens[i1][1])] for j in range(lens[i1][0])]\r\n for i2 in range(10):\r\n ab[i1][10+i2][i2*2]=1\r\ntotal=0\r\n\r\nno_in=[]\r\nn=-1\r\nprob=[0.0828,0.0365,0.1102,0.1029,0.0236,0.0555,0.0201,0.0319,0.0303,0.0201,0.0319,0.0308,0.0303,0.0269,0.0307,0.0859,0.0414,0.0397,0.0556,0.0189,0.0573,0.0189,0.0123,0.0350,0.0132,0.0122,0.0122,0.0119,0.0394,0.0017,0.0052,0.0086,1]\r\nno_in_t=290\r\nno_hos=0\r\n\r\nwhile(1):\r\n a.append(copy.deepcopy(ab))\r\n no_in=0\r\n n=n+1\r\n no_hos=0\r\n print(n)\r\n if(n<5):\r\n for i in range(1280000):\r\n x= randint(0,28)\r\n b= randint(0,lens[x][0]-1)\r\n c= randint(0,lens[x][1]-1)\r\n x1= randint(0,28)\r\n b1= randint(0,lens[x1][0]-1)\r\n c1= randint(0,lens[x1][1]-1)\r\n if((ab[x][b][c] or ab[x1][b1][c1])and n>0):\r\n for i in range(n):\r\n a[n-i][x][b][c]= a[n-i][x][b][c]+a[n-i][x1][b1][c1]\r\n a[n-i][x1][b1][c1]= a[n-i][x][b][c]-a[n-i][x1][b1][c1]\r\n a[n-i][x][b][c]= a[n-i][x][b][c]-a[n-i][x1][b1][c1]\r\n ab[x][b][c]= ab[x][b][c]+ab[x1][b1][c1]\r\n ab[x1][b1][c1]= ab[x][b][c]-ab[x1][b1][c1]\r\n ab[x][b][c]= ab[x][b][c]-ab[x1][b1][c1]\r\n else:\r\n for i in range(3200):\r\n x= randint(0,28)\r\n b= randint(0,lens[x][0]-1)\r\n c= randint(0,lens[x][1]-1)\r\n x1= randint(0,28)\r\n b1= randint(0,lens[x1][0]-1)\r\n c1= randint(0,lens[x1][1]-1)\r\n if((ab[x][b][c] or ab[x1][b1][c1])and n>0):\r\n for i in range(n):\r\n a[n-i][x][b][c]= a[n-i][x][b][c]+a[n-i][x1][b1][c1]\r\n a[n-i][x1][b1][c1]= a[n-i][x][b][c]-a[n-i][x1][b1][c1]\r\n a[n-i][x][b][c]= a[n-i][x][b][c]-a[n-i][x1][b1][c1]\r\n ab[x][b][c]= ab[x][b][c]+ab[x1][b1][c1]\r\n ab[x1][b1][c1]= ab[x][b][c]-ab[x1][b1][c1]\r\n ab[x][b][c]= ab[x][b][c]-ab[x1][b1][c1]\r\n for x in range(29):\r\n for i in range(lens[x][0]):\r\n for j in range(lens[x][1]):\r\n if(ab[x][i][j]==1 or ab[x][i][j]==2 or ab[x][i][j]==3):\r\n for i1 in range(3):\r\n for j1 in range(3):\r\n if((ab[x][(i-1+i1)%lens[x][0]][(j-1+j1)%lens[x][1]]==0) and random()<prob[x]*1.2):\r\n ab[x][(i-1+i1)%lens[x][0]][(j-1+j1)%lens[x][1]]=1\r\n for x in range(29):\r\n for i in range(lens[x][0]):\r\n for j in range(lens[x][1]):\r\n if(ab[x][i][j]==3):\r\n no_hos = no_hos +1\r\n if(n>=0):\r\n for x in range(29):\r\n for i in range(lens[x][0]):\r\n for j in range(lens[x][1]):\r\n if(ab[x][i][j]==1):\r\n if(no_hos>=12000):\r\n ab[x][i][j]=2 #not hospitalized\r\n else:\r\n ab[x][i][j]= 3 # hospitalized\r\n if(n>5):\r\n for x in range(29):\r\n for i in range(lens[x][0]):\r\n for j in range(lens[x][1]):\r\n if(a[n-6][x][i][j]==2 or a[n-6][x][i][j]==3):\r\n if(0.05>random()):\r\n ab[x][i][j]= 5 #dead\r\n else:\r\n ab[x][i][j]= 4\r\n \r\n \r\n for x in range(29):\r\n for i in range(lens[x][0]):\r\n for j in range(lens[x][1]):\r\n if(ab[x][i][j]==3 or ab[x][i][j]==2):\r\n no_in=no_in+1\r\n print(no_in) \r\n if( n>150):\r\n break\r\n\r\nfor x in range(28):\r\n nodead=[]\r\n abc=0\r\n x1=[]\r\n for y in range(n):\r\n x1.append(y)\r\n for i in range(lens[x][0]):\r\n for j in range(lens[x][1]):\r\n if(a[y][x][i][j]==5):\r\n abc=abc+1\r\n \r\n nodead.append(abc)\r\n if(x==0 or x==2 or x==3 or x==28 or x==15):\r\n plt.plot(x1,nodead)\r\n plt.title(x)\r\n plt.ylabel('no of deaths')\r\n plt.xlabel('no of days')\r\n\r\n plt.show()\r\n \r\n\r\n \r\n" }, { "alpha_fraction": 0.45342886447906494, "alphanum_fraction": 0.5209826231002808, "avg_line_length": 16.433961868286133, "blob_id": "3f23107acfed0501d1bece58b4a73dce9d8b5e2a", "content_id": "303315844b2a21680045756a739dbcf4a2abd0f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 977, "license_type": "no_license", "max_line_length": 37, "num_lines": 53, "path": "/IA/Pandemic and array stimulations/DevM.Desai_ASS2.py", "repo_name": "dev9318/SOC", "src_encoding": "UTF-8", "text": "from random import seed\r\nfrom random import randint\r\nimport matplotlib.pyplot as plt \r\n\r\n# seed random number generator\r\nseed(1)\r\n\r\na=[0]\r\nno_of_1=[1] #y axis variable\r\nn=0\r\n\r\nfor i in range(999):\r\n a.append(0)\r\n\r\n#my random 1\r\na[201]=1\r\n\r\nwhile(1):\r\n #the magic basically adding 1s\r\n for i in range(1000):\r\n if(a[i]==1):\r\n if(randint(0,1)==0):\r\n a[i-1]=1\r\n else:\r\n a[(i+1)%1000]=1\r\n #swapping\r\n x=randint(0,999)\r\n y=randint(0,999)\r\n a[x]=a[y]+a[x]\r\n a[y]=a[x]-a[y]\r\n a[x]=a[x]-a[y]\r\n n=n+1\r\n #caz lists go out of range\r\n no_of_1.append(0)\r\n #counting 1s\r\n for i in range(1000):\r\n if(a[i]==1):\r\n no_of_1[n]=no_of_1[n] + 1\r\n if((int)(no_of_1[n])==1000):\r\n break\r\n\r\n\r\nx1=[1] #x axis variable\r\nfor i in range(n):\r\n x1.append(i+2)\r\n\r\nprint(no_of_1)\r\nprint(x1)\r\n#plotting\r\nplt.plot(x1,no_of_1)\r\nplt.xlabel('no of repetitions')\r\nplt.ylabel('no of 1s')\r\nplt.show()\r\n" }, { "alpha_fraction": 0.33005669713020325, "alphanum_fraction": 0.4166351556777954, "avg_line_length": 26.877777099609375, "blob_id": "ad06ca85c4aec528ac74d3ca02c3282447f3f0aa", "content_id": "1e12650021b8b6398f127bb701d45f7290ae0252", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2645, "license_type": "no_license", "max_line_length": 94, "num_lines": 90, "path": "/IA/Pandemic and array stimulations/DevM.Desai_ASS2(100) - Copy.py", "repo_name": "dev9318/SOC", "src_encoding": "UTF-8", "text": "from random import seed\r\nfrom random import randint\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.signal import savgol_filter \r\n\r\n# seed random number generator\r\nseed(1)\r\n\r\na = [[0 for i in range(150)] for j in range(100)]\r\na__ = [[0 for i in range(150)] for j in range(100)]\r\ndx=[0]\r\na[50][75]=1\r\na__[50][75]=1\r\nx2=[]\r\nn1=[]\r\nfor i in range(100):\r\n n1.append(0)\r\n x2.append(i)\r\n no_1=[]\r\n print(a)\r\n while(1):\r\n no_1.append(0)\r\n for i1 in range(8):\r\n a1=randint(0,99)\r\n b=randint(0,99)\r\n a11=randint(0,149)\r\n b1=randint(0,149)\r\n a[a1][a11]=a[a1][a11]+a[b][b1]\r\n a[b][b1]=a[a1][a11]-a[b][b1]\r\n a[a1][a11]=a[a1][a11]-a[b][b1]\r\n for i1 in range(100):\r\n for j in range(150):\r\n if(a[i1][j]==1):\r\n for i2 in range(5):\r\n for j1 in range(5):\r\n if((i2>0 and i2<4 and j1>0 and j1<4) and (randint(0,3)<1)):\r\n a__[(i1+i2-2)%100][(j+j1-2)%150]=1\r\n elif(not (i2>0 and i2<4 and j1>0 and j1<4) and (randint(0,24)<2)):\r\n a__[(i1+i2-2)%100][(j+j1-2)%150]=1\r\n for i1 in range(100):\r\n for j in range(150):\r\n a[i1][j]=a__[i1][j]\r\n for i1 in range(100):\r\n for j in range(150):\r\n if(a[i1][j]==1):\r\n no_1[n1[i]]=no_1[n1[i]] + 1\r\n if(i==0):\r\n dx.append(no_1[n1[i]]-no_1[n1[i]-1])\r\n if(no_1[n1[i]]==15000):\r\n for i1 in range(100):\r\n for j in range(150):\r\n a[i1][j]=0\r\n a__[i1][j]=0\r\n a[50][75]=1\r\n a__[50][75]=1\r\n break\r\n n1[i]=n1[i]+1\r\n if(i==0):\r\n x1=[]\r\n for i1 in range(n1[i]+1):\r\n x1.append(i1)\r\n plt.plot(x1,no_1)\r\n plt.xlabel('no of repetitions')\r\n plt.ylabel('no of 1s')\r\n plt.show()\r\n x1.append(n1[i]+1)\r\n plt.plot(x1,dx,color='yellow')\r\n plt.xlabel('x')\r\n #yhat=savgol_filter(dx, 51, 3)\r\n plt.ylabel('dx')\r\n #plt.plot(x1,yhat,color='red')\r\n plt.show()\r\n maxi=0\r\n #maxy=0\r\n for i in range(n1[0]):\r\n if(dx[i]>maxi):\r\n maxi=dx[i]\r\n #maxy=yhat[i]\r\n print(maxi)\r\n\r\n#plotting\r\nplt.plot(x2,n1)\r\nplt.ylabel('no of repetitions')\r\nplt.xlabel('no of iterations')\r\nplt.show()\r\n\r\nsum=0\r\nfor i in range(100):\r\n sum=sum+n1[i]/100\r\nprint(sum)\r\n\r\n \r\n \r\n\r\n\r\n" }, { "alpha_fraction": 0.3907342553138733, "alphanum_fraction": 0.4711538553237915, "avg_line_length": 19.58490562438965, "blob_id": "20f343c4d0db4d34d861831326f0a58b73789fec", "content_id": "05261e50af2ba91ce1050c95b1e17c1b1d5235b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1144, "license_type": "no_license", "max_line_length": 49, "num_lines": 53, "path": "/IA/Pandemic and array stimulations/DevM.Desai_ASS2(100).py", "repo_name": "dev9318/SOC", "src_encoding": "UTF-8", "text": "from random import seed\r\nfrom random import randint\r\nimport matplotlib.pyplot as plt \r\n\r\n# seed random number generator\r\nseed(1)\r\n\r\n\r\nn1=[]\r\na1=[] #y axis variable\r\n\r\n\r\nfor i1 in range(10000):\r\n a1.append(i1)\r\n n1.append(0)\r\n no_of_1=[1]\r\n a=[0]\r\n for i in range(999):\r\n a.append(0)\r\n a[217]=1\r\n while(1):\r\n #the magic basically adding 1s\r\n for i in range(1000):\r\n if(a[i]==1):\r\n if(randint(0,1)==0):\r\n a[i-1]=1\r\n else:\r\n a[(i+1)%1000]=1\r\n #swapping\r\n x=randint(0,999)\r\n y=randint(0,999)\r\n a[x]=a[y]+a[x]\r\n a[y]=a[x]-a[y]\r\n a[x]=a[x]-a[y]\r\n n1[i1]=n1[i1]+1\r\n #caz lists go out of range\r\n no_of_1.append(0)\r\n #counting 1s\r\n for i in range(1000):\r\n if(a[i]==1):\r\n no_of_1[n1[i1]]=no_of_1[n1[i1]] + 1\r\n if((int)(no_of_1[n1[i1]])==1000):\r\n break\r\n\r\n#plotting\r\nplt.plot(a1,n1)\r\nplt.ylabel('no of repetitions')\r\nplt.xlabel('no of iterations')\r\n\r\nsum=0.0\r\nfor i in range(10000):\r\n sum=sum+n1[i]/10000\r\nprint(sum)\r\n" }, { "alpha_fraction": 0.6469265222549438, "alphanum_fraction": 0.6622938513755798, "avg_line_length": 29.36470603942871, "blob_id": "bb1e730c16691d5e38cf9b78a2cbb3648caf322d", "content_id": "b94a5801508dfbb839fb97058afe7ebce3b55633", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2668, "license_type": "no_license", "max_line_length": 91, "num_lines": 85, "path": "/IA/neural Networks/Neural Networks(part 2)_Xor_gate - Copy.py", "repo_name": "dev9318/SOC", "src_encoding": "UTF-8", "text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n#required to predit a numbert between 0 and 1\r\ndef sigmoid (x):\r\n return 1/(1 + np.exp(-x))\r\n\r\n#required for back propagation\r\ndef sigmoid_derivative(x):\r\n return x * (1 - x)\r\n\r\ndatai=[]\r\ndatao=[]\r\nfor i in range(10):\r\n for j in range(10):\r\n datai.append([i,j])\r\n datao.append((i+1)*(j+1))\r\n\r\n#making data for training it\r\ninputs = (datai)\r\nexpected_output = (datao)\r\n\r\n\r\nepochs = 4000\r\nlr = 0.\r\n\r\n#making random weights and bias\r\n\r\nhidden_weights = np.random.uniform(size=(2,2))\r\nhidden_bias =np.random.uniform(size=(1,2))\r\noutput_weights = np.random.uniform(size=(2,1))\r\noutput_bias = np.random.uniform(size=(1,1))\r\n\r\nerrors=[]\r\nx=[]\r\ny=[]\r\nx1=[]\r\n\r\n \r\n#Training algorithm executing the algorithm 10000 times\r\nfor i in range(epochs):\r\n \r\n \r\n for i in range(len(expected_output)):\r\n #Forward Propagation\r\n #1st layer\r\n hidden_layer_activation = np.dot(np.array(inputs[i]),hidden_weights)\r\n hidden_layer_activation = hidden_layer_activation + hidden_bias\r\n hidden_layer_output = sigmoid(hidden_layer_activation)\r\n\r\n # 2nd layer (using the output of the previous layer as input)\r\n output_layer_activation = np.dot(hidden_layer_output,output_weights)\r\n output_layer_activation = output_layer_activation + output_bias\r\n predicted_output = sigmoid(output_layer_activation)\r\n\r\n\r\n #Backpropagation\r\n #2nd layer\r\n error = np.array(expected_output[i]) - predicted_output\r\n d_predicted_output = error * sigmoid_derivative(predicted_output)\r\n\r\n #1st layer\r\n error_hidden_layer = d_predicted_output.dot(output_weights.T)\r\n d_hidden_layer = error_hidden_layer * sigmoid_derivative(hidden_layer_output)\r\n\t\r\n\r\n #Updating Weights and Biases\r\n output_weights =output_weights + hidden_layer_output.T.dot(d_predicted_output) * lr\r\n output_bias = output_bias + np.sum(d_predicted_output,axis=0,keepdims=True) * lr\r\n hidden_weights = hidden_weights + np.array(inputs[i]).T.dot(d_hidden_layer.T) * lr\r\n hidden_bias = hidden_bias + np.sum(d_hidden_layer,axis=0,keepdims=True) * lr\r\n \r\n\r\nhidden_layer_activation = np.dot([10,10],hidden_weights)\r\nhidden_layer_activation = hidden_layer_activation + hidden_bias\r\nhidden_layer_output = (hidden_layer_activation)\r\n\r\n # 2nd layer (using the output of the previous layer as input)\r\noutput_layer_activation = np.dot(hidden_layer_output,output_weights)\r\noutput_layer_activation = output_layer_activation + output_bias\r\npredicted_output = (output_layer_activation)\r\n\r\n\r\nprint(predicted_output)\r\n\r\n" }, { "alpha_fraction": 0.5934426188468933, "alphanum_fraction": 0.6557376980781555, "avg_line_length": 25.909090042114258, "blob_id": "4536429425976c0e076dc0b0496f38e38a30e3cf", "content_id": "cee59ee04feac005c0f7b25b42d2bb78b4ed8cb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 305, "license_type": "no_license", "max_line_length": 78, "num_lines": 11, "path": "/IA/Pandemic and array stimulations/Rass1.R", "repo_name": "dev9318/SOC", "src_encoding": "UTF-8", "text": "three.dice<-function(){\r\n random.dice<-sample(1:6,3,replace=FALSE)\r\n sum(random.dice) \r\n}\r\n\r\nsim<-replicate(50,three.dice())\r\nplot(table(sim), xlab='Sum', ylab='Frequency', main='50 Rolls of 3 fair dice')\r\n\r\nsims<-replicate(500,three.dice())\r\nprobabili<-(sum((sims>=14) & (sims<=16) ))/5000\r\nprobabili" }, { "alpha_fraction": 0.5636083483695984, "alphanum_fraction": 0.5983037948608398, "avg_line_length": 30.424999237060547, "blob_id": "2855f49c936cbb3b59706ed4ab0a35083e7a4d04", "content_id": "5a368f4bb93b5f89d54ac8a87d1ce3ebe8510a7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1297, "license_type": "no_license", "max_line_length": 73, "num_lines": 40, "path": "/IA/neural Networks/Neural Networks(part 1)_perceptron - Copy.py", "repo_name": "dev9318/SOC", "src_encoding": "UTF-8", "text": "from random import random\r\n\r\n\r\n# Make a prediction with weights\r\ndef predict_train(row, weights):\r\n activation = weights[0]\r\n for i in range(len(row)-1):\r\n \tactivation += weights[i + 1] * row[i]\r\n return 1.0 if activation >= 0.0 else 0.0\r\n\r\n\r\ndef predict_test(row, weights):\r\n activation = weights[0]\r\n for i in range(len(row)):\r\n \tactivation += weights[i + 1] * row[i]\r\n return 1.0 if activation >= 0.0 else 0.0\r\n\r\n# Estimate Perceptron weights using stochastic gradient descent\r\ndef train_weights(train, l_rate, n_epoch):\r\n weights = [random() for i in range(len(train[0]))]\r\n for epoch in range(n_epoch):\r\n for row in train:\r\n prediction = predict_train(row, weights)\r\n error = row[-1] - prediction\r\n weights[0] = weights[0] + l_rate * error\r\n for i in range(len(row)-1):\r\n weights[i + 1] = weights[i + 1] + l_rate * error * row[i]\r\n return weights\r\n\r\n#training data\r\ndataset = [[1,0,1,1],[0,0,1,0],[1,1,0,1],[1,1,1,1]]\r\nl_rate = 0.05\r\nn_epoch = 10\r\nweights = train_weights(dataset, l_rate, n_epoch)\r\n\r\n#input\r\nn = int(input(\"How many predictions would you like to make\\n\"))\r\nfor _ in range(n):\r\n data_column = [int(x) for x in input().split()]\r\n print(predict_test(data_column,weights))\r\n" }, { "alpha_fraction": 0.6050899624824524, "alphanum_fraction": 0.6305397152900696, "avg_line_length": 27.571428298950195, "blob_id": "c463da2b18c81668b0b3e0c41c990c1ea8ec79eb", "content_id": "a6b33756eb1aff58ac6bd2f77ab7eda493b7e56a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2279, "license_type": "no_license", "max_line_length": 88, "num_lines": 77, "path": "/IA/neural Networks/Neural Networks(part 2)_Xor_gate.py", "repo_name": "dev9318/SOC", "src_encoding": "UTF-8", "text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n#required to predit a numbert between 0 and 1\r\ndef sigmoid (x):\r\n return 1/(1 + np.exp(-x))\r\n\r\n#required for back propagation\r\ndef sigmoid_derivative(x):\r\n return x * (1 - x)\r\n\r\n#making data for training it\r\ninputs = np.array([[0,0],[0,1],[1,0],[1,1]])\r\nexpected_output = np.array([[0],[1],[1],[0]])\r\n\r\n\r\nepochs = 10000\r\nlr = 0.1\r\n\r\n#making random weights and bias\r\n\r\n\r\n\r\nerrors=[]\r\nx=[]\r\ny=[]\r\nx1=[]\r\n\r\nfor i1 in range(100):\r\n x1.append(i1+1)\r\n hidden_weights = np.random.uniform(size=(2,2))\r\n hidden_bias =np.random.uniform(size=(1,2))\r\n output_weights = np.random.uniform(size=(2,1))\r\n output_bias = np.random.uniform(size=(1,1))\r\n #Training algorithm executing the algorithm 10000 times\r\n for i in range(epochs):\r\n \r\n x.append(i)\r\n \r\n #Forward Propagation\r\n #1st layer\r\n hidden_layer_activation = np.dot(inputs,hidden_weights)\r\n hidden_layer_activation += hidden_bias\r\n hidden_layer_output = sigmoid(hidden_layer_activation)\r\n\r\n # 2nd layer (using the output of the previous layer as input)\r\n output_layer_activation = np.dot(hidden_layer_output,output_weights)\r\n output_layer_activation += output_bias\r\n predicted_output = sigmoid(output_layer_activation)\r\n\r\n\r\n #Backpropagation\r\n #2nd layer\r\n error = expected_output - predicted_output\r\n errors.append(error[0])\r\n d_predicted_output = error * sigmoid_derivative(predicted_output)\r\n\r\n #1st layer\r\n error_hidden_layer = d_predicted_output.dot(output_weights.T)\r\n d_hidden_layer = error_hidden_layer * sigmoid_derivative(hidden_layer_output)\r\n\t\r\n\r\n #Updating Weights and Biases\r\n output_weights += hidden_layer_output.T.dot(d_predicted_output) * lr\r\n output_bias += np.sum(d_predicted_output,axis=0,keepdims=True) * lr\r\n hidden_weights += inputs.T.dot(d_hidden_layer) * lr\r\n hidden_bias += np.sum(d_hidden_layer,axis=0,keepdims=True) * lr\r\n y.append(errors[-1])\r\n\r\n\r\n#ploting a graph of error(for input (0,0)) vs no. of iterations (beacuase it looks cool)\r\n\r\nplt.plot(x1,y)\r\nplt.xlabel(\"ith run\")\r\nplt.ylabel(\"Final Error in that run(for input (0,0))\")\r\nplt.show()\r\n\r\n" }, { "alpha_fraction": 0.4609375, "alphanum_fraction": 0.546875, "avg_line_length": 30, "blob_id": "56871121c9e83570995f1f254ceec3f48903b77b", "content_id": "243ceffaa16ca5492c58cd22fe4c8a2f98035a2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "no_license", "max_line_length": 54, "num_lines": 8, "path": "/IA/MusicPatterPredictor/update function.py", "repo_name": "dev9318/SOC", "src_encoding": "UTF-8", "text": "def update(Song1 ,Song2):\r\n alpha= 0.01\r\n for i in range(1,5): \r\n Song2[i] =Song2[i] + alpha*(Song2[i]-Song1[i])\r\ndef onsearch(Song1, Song2):\r\n alpha= 0.01\r\n for i in range(1,5): \r\n Song2[i] =Song2[i] - alpha*(Song2[i]-Song1[i])\r\n" }, { "alpha_fraction": 0.7214699983596802, "alphanum_fraction": 0.7214699983596802, "avg_line_length": 34.92856979370117, "blob_id": "24fa6f2c3e1210ea331d652dd3101b1113907fef", "content_id": "c96a90cb727de53651a5d49af649971137e96a95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 517, "license_type": "no_license", "max_line_length": 106, "num_lines": 14, "path": "/IA/admission predictor/ass4.py", "repo_name": "dev9318/SOC", "src_encoding": "UTF-8", "text": "import pandas as pd \r\nimport numpy as np \r\nimport matplotlib.pyplot as plt \r\nfrom sklearn.model_selection import train_test_split \r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn import metrics\r\n\r\ndataset = pd.read_csv('/Users/Dev/Desktop/IA/Admission_Predict.csv')\r\nX = dataset[['GRE Score' ,'TOEFL Score'\t,'University Rating'\t,'SOP'\t,'LOR' ,'CGPA'\t,'Research']].values\r\nY = dataset['Chance of Admit'].values\r\nregressor = LinearRegression() \r\nregressor.fit(X, Y)\r\n \r\nprint(regressor.coef_)\r\n" } ]
12
Kanibel/Assignment_5
https://github.com/Kanibel/Assignment_5
b5dc5c7509b351ca60a22d674d567a0693e93bef
7dc539ec0daee404c032b204b4faef18a71ebfa9
59a7cf87ecfd785d67baebae78a5934fcf83ff6f
refs/heads/master
2015-08-09T07:22:49.910343
2013-10-25T00:45:27
2013-10-25T00:45:27
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6973294019699097, "alphanum_fraction": 0.7127596735954285, "avg_line_length": 18.823530197143555, "blob_id": "6b45bc7929cf72d9f775fbb01e68ff78608f0038", "content_id": "c21f633ff49e56ad4c5b65c9fcf2f335c63578bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1685, "license_type": "no_license", "max_line_length": 119, "num_lines": 85, "path": "/JackKnobel_ScriptingAssignment/resources/scripts/game.py", "repo_name": "Kanibel/Assignment_5", "src_encoding": "UTF-8", "text": "#Python Includes\nimport random\n\n#Custom Includes\nimport TSU\nimport JKDefs\nimport pathfinding\nimport mapsheet\nimport Boid\nimport Vector \n\n#Globals\nglobal LevelMap\nglobal AI\n\nLevelMap = None\nAI = None \nAIList = list()\ngameSize = {'width':1600, 'height': 900}\ntileSize = {'width': 64, 'height': 64}\n\nglobal buttonPressed\nbuttonPressed = False\nglobal Flock\nFlock = True\n\ndef GameInit():\n\t\n\tTSU.Initialise(\"AI - Python Scripting Assignment\", gameSize['width'], gameSize['height'], False)\n\n\treload(JKDefs)\n\t\n\tMapInit()\n\ndef MapInit():\n\tglobal buttonPressed\n\tglobal Flock\n\tprint \"MapInit\"\n\treload(mapsheet)\n\treload(pathfinding) \n\treload(Boid)\n\n\tglobal LevelMap\n\tLevelMap = mapsheet.LevelMap(gameSize, tileSize)\n\tLevelMap.loadSprites()\n\n\tif(Flock == True):\n\t\tglobal AI\n\t\tAI = Boid.Flock(6)\n\tif(Flock == False):\n\t\tfor i in range (10):\n\t\t\tAIPos = Vector.Vector(gameSize['width'] * random.uniform(0.4, 0.6), (gameSize['height'] * random.uniform(0.4, 0.6)))\n\t\t\tAIList.append(Boid.Boid(AIPos))\n\t\t\tAIList[i].loadSprites()\n\t\t\n\ndef GameUpdate():\n\tglobal LevelMap\n\tLevelMap.Update(TSU.GetDeltaTime())\n\tLevelMap.draw()\n\tglobal buttonPressed\n\tglobal Flock\n\tif(TSU.IsKeyDown(JKDefs.KEY_1) and (buttonPressed is False) and (Flock is False)):\n\t\tFlock = True\n\t\tMapInit()\n\t\tbuttonPressed = True\n\t\t\n\tif(TSU.IsKeyDown(JKDefs.KEY_2) and (buttonPressed is False) and (Flock is True)):\n\t\tFlock = False\n\t\tdel AIList[:]\n\t\tMapInit()\n\t\tbuttonPressed = True\n\t\t\n\n\tbuttonPressed = TSU.IsKeyDown(JKDefs.KEY_1) or TSU.IsKeyDown(JKDefs.KEY_2)\n\tif(Flock):\n\t\tAI.Update(LevelMap)\n\telse:\n\t\tfor i in range (len(AIList)):\n\t\t\tAIList[i].Update(LevelMap)\n\t\t\tAIList[i].Draw()\n\ndef GameShutdown():\n\tglobal LevelMap\n\tLevelMap.cleanUp()\n" }, { "alpha_fraction": 0.6420692205429077, "alphanum_fraction": 0.6472042798995972, "avg_line_length": 30.29166603088379, "blob_id": "20dcbb58b7a300116c1625aed5b269ee91c3350d", "content_id": "5e28e261688db65c884d9ee2bc587a8c88351cf6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5258, "license_type": "no_license", "max_line_length": 186, "num_lines": 168, "path": "/JackKnobel_ScriptingAssignment/resources/scripts/pathfinding.py", "repo_name": "Kanibel/Assignment_5", "src_encoding": "UTF-8", "text": "#Python Includes\nimport math\n#from operator import attrgetter\nimport heapq\n#=========================================\n#Custom Includes\nimport TSU\nimport mapsheet\nimport JKDefs\nimport game\nimport Vector\n#=========================================\n\nclass AStar:\n\tdef __init__(self, levelSize, levelTiles, tileSize, Start, End, PathSprite):\n\t\tself.Start = Start\n\t\tself.Start.g = 0\n\t\tself.End = End\n\t\tself.openList = []\n\t\theapq.heapify(self.openList)\n\t\tself.closedList = set()\n\t\tself.levelSize = levelSize\n\t\tself.levelTiles = levelTiles\n\t\tself.tileSize = tileSize \n\t\tfor x in range(len(levelTiles)):\n\t\t\tfor y in range(len(levelTiles[x])):\n\t\t\t\tlevelTiles[x][y].h = self.getHeuristic(levelTiles[x][y], self.End)\n\t\tself.PathSprite = PathSprite\n\tdef getHeuristic(self, Tile, End):\n\t\treturn (abs(Tile.position.x/self.tileSize['width'] - End.position.x/self.tileSize['width']) + abs(Tile.position.y/self.tileSize['height'] - End.position.y/self.tileSize['height']))\n\tdef getAdjTiles(self, Tile, levelTiles):\n\t\tcells = []\n\t\tfor i in range(-1, 2):\n\t\t\tfor j in range(-1, 2):\n\t\t\t\tif (i or j):\n\t\t\t\t\tgridX=Tile.position.x/self.tileSize['width'] + i\n\t\t\t\t\tgridY=Tile.position.y/self.tileSize['height'] + j\n\t\t\t\t\tif(gridX < 0):\n\t\t\t\t\t\tgridX = 0\n\t\t\t\t\tif(gridY < 0):\n\t\t\t\t\t\tgridY = 0\n\t\t\t\t\tif(gridX > self.levelSize['Width']-1):\n\t\t\t\t\t\tgridX = self.levelSize['Width']-1\n\t\t\t\t\tif(gridY > self.levelSize['Height']-1):\n\t\t\t\t\t\tgridY = self.levelSize['Height']-1\n\t\t\t\t\tcells.append(levelTiles[gridX][gridY])\n\t\t\t\t\t#print cells\n\t\treturn cells\n\n\tdef dispPath(self):\n\t\tpath = list()\n\t\tTile = self.End.parent \n\t\twhile Tile.parent is not None:\n\t\t\tTile.setSpriteID(self.PathSprite)\n\t\t\tpath.append(Tile)\n\t\t\tTile = Tile.parent\n\t\treturn path\n\n\tdef calcScores(self, Tile, Adj):\t\n\t\tAdj.g = Tile.g + Tile.position.Distance(Adj.position)\n\t\tAdj.parent = Tile \n\t\tAdj.f = Adj.h + Adj.g \t\t\n\n\tdef findPath(self):\n\t\tprint \"A* Begin\"\n\t\theapq.heappush(self.openList, (self.Start.f, self.Start))\n\t\twhile (self.openList):\n\t\t\tf, Tile = heapq.heappop(self.openList)\t\n\t\t\tself.closedList.add(Tile)\n\t\t\t#print Tile \n\t\t\tif Tile is self.End:\n\t\t\t\treturn self.dispPath()\n\t\t\tAdjTiles = self.getAdjTiles(Tile, self.levelTiles)\n\t\t\tfor cAdj in AdjTiles:\n\t\t\t\t#print self.closedList\n\t\t\t\tif(cAdj.reachable):\n\t\t\t\t\ttg = Tile.g + Tile.position.Distance(cAdj.position)\n\t\t\t\t\tif((cAdj.f, cAdj) in self.closedList and tg >= cAdj.g):\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif (cAdj not in self.closedList) or (tg < cAdj.g):\n\t\t\t\t\t\tself.calcScores(Tile, cAdj)\n\t\t\t\t\t\tif((cAdj.f, cAdj) not in self.openList):\n\t\t\t\t\t\t\theapq.heappush(self.openList, (cAdj.f, cAdj))\n\t\t\t\telif(not cAdj.reachable):\n\t\t\t\t\t#self.closedList.add(cAdj)\n\t\t\t\t\tprint \"Can't find end\"\n\n\t\tprint \"A* End\"\n\nclass Dijkstra:\n\tdef __init__(self, levelSize, levelTiles, tileSize, Start, End, PathSprite):\n\t\tself.Start = Start\n\t\tself.Start.g = 0\n\t\tself.End = End\n\t\tself.openList = []\n\t\theapq.heapify(self.openList)\n\t\tself.closedList = set()\n\t\tself.levelSize = levelSize\n\t\tself.levelTiles = levelTiles\n\t\tself.tileSize = tileSize \n\t\tfor x in range(len(levelTiles)):\n\t\t\tfor y in range(len(levelTiles[x])):\n\t\t\t\tlevelTiles[x][y].h = self.getHeuristic(levelTiles[x][y], self.End)\n\t\tself.PathSprite = PathSprite\n\tdef getHeuristic(self, Tile, End):\n\t\treturn 0 * (abs(Tile.position.x/self.tileSize['width'] - End.position.x/self.tileSize['width']) + abs(Tile.position.y/self.tileSize['height'] - End.position.y/self.tileSize['height']))\n\tdef getAdjTiles(self, Tile, levelTiles):\n\t\tcells = []\n\t\tfor i in range(-1, 2):\n\t\t\tfor j in range(-1, 2):\n\t\t\t\tif (i or j):\n\t\t\t\t\tgridX=Tile.position.x/self.tileSize['width'] + i\n\t\t\t\t\tgridY=Tile.position.y/self.tileSize['height'] + j\n\t\t\t\t\tif(gridX < 0):\n\t\t\t\t\t\tgridX = 0\n\t\t\t\t\tif(gridY < 0):\n\t\t\t\t\t\tgridY = 0\n\t\t\t\t\tif(gridX > self.levelSize['Width']-1):\n\t\t\t\t\t\tgridX = self.levelSize['Width']-1\n\t\t\t\t\tif(gridY > self.levelSize['Height']-1):\n\t\t\t\t\t\tgridY = self.levelSize['Height']-1\n\t\t\t\t\tcells.append(levelTiles[gridX][gridY])\n\t\t\t\t\t#print cells\n\t\treturn cells\n\n\tdef dispPath(self):\n\t\tpath = list()\n\t\tTile = self.End.parent \n\t\twhile Tile.parent is not None:\n\t\t\tTile.setSpriteID(self.PathSprite)\n\t\t\tpath.append(Tile)\n\t\t\tTile = Tile.parent\n\t\t\t#print Tile\n\t\t\t#print 'Tile: %d, %d' % (Tile.x, Tile.y)\n\t\treturn path\n\n\tdef calcScores(self, Tile, Adj):\t\n\t\tAdj.g = Tile.g + Tile.position.Distance(Adj.position)\n\t\t#Adj.h = self.getHeuristic(Tile, Adj)\n\t\tAdj.parent = Tile \n\t\t#print \"adj h, \", Adj.h\n\t\tAdj.f = Adj.h + Adj.g \t\t\n\t\t#print Adj.g, Adj.h, Adj.f\n\n\tdef findPath(self):\n\t\tprint \"Dijkstra Begin\"\n\t\theapq.heappush(self.openList, (self.Start.f, self.Start))\n\t\twhile (self.openList):\n\t\t\tf, Tile = heapq.heappop(self.openList)\t\n\t\t\tself.closedList.add(Tile)\n\t\t\t#print Tile \n\t\t\tif Tile is self.End:\n\t\t\t\treturn self.dispPath()\n\t\t\tAdjTiles = self.getAdjTiles(Tile, self.levelTiles)\n\t\t\tfor cAdj in AdjTiles:\n\t\t\t\t#print self.closedList\n\t\t\t\tif(cAdj.reachable):\n\t\t\t\t\ttg = Tile.g + Tile.position.Distance(cAdj.position)\n\t\t\t\t\tif((cAdj.f, cAdj) in self.closedList and tg >= cAdj.g):\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif (cAdj not in self.closedList) or (tg < cAdj.g):\n\t\t\t\t\t\tself.calcScores(Tile, cAdj)\n\t\t\t\t\t\tif((cAdj.f, cAdj) not in self.openList):\n\t\t\t\t\t\t\theapq.heappush(self.openList, (cAdj.f, cAdj))\n\t\t\t\telif(not cAdj.reachable):\n\t\t\t\t\t#self.closedList.add(cAdj)\n\t\t\t\t\tprint \"Can't find end\"\n\t\tprint \"Dijkstra End\"\n\n" }, { "alpha_fraction": 0.6493108868598938, "alphanum_fraction": 0.6539050340652466, "avg_line_length": 18.205883026123047, "blob_id": "ce33f0e70b07dc59c8a7ae8748c7e48b32fa5c70", "content_id": "59714de93d55499291481d7fa5ccba03e5143574", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 653, "license_type": "no_license", "max_line_length": 53, "num_lines": 34, "path": "/JackKnobel_ScriptingAssignment/main.cpp", "repo_name": "Kanibel/Assignment_5", "src_encoding": "UTF-8", "text": "#include <Python.h>\n#include \"include\\TSU_Py.h\"\n#include \"include\\TSU.h\"\nchar* g_pWindowTitle;\n\nint main(int argc, char *argv[])\n{\n\tTSUPyInitialise(argc, argv);\n\n\tPyObject* pModule = TSUImportPythonModule( \"game\" );\n\t\n\tif (pModule != NULL) \n\t{\n\t\t\tTSUCallPythonFunction(pModule, \"GameInit\");\n\n\t\t\tdo \n\t\t\t{\t\n\t\t\t\tClearScreen();\n\n\t\t\t\tTSUCallPythonFunction(pModule, \"GameUpdate\");\n\t\t\t\tif(IsKeyDown(32))\n\t\t\t\t{\n\t\t\t\t\tTSUReloadPythonModule(pModule);\n\t\t\t\t\tTSUCallPythonFunction(pModule, \"MapInit\");\n\t\t\t\t}\n\t\t\t}while( EngineRunning() );\n\n\t\t\tTSUCallPythonFunction( pModule, \"GameShutdown\" );\n\t\tPy_DECREF(pModule);\n }\n Py_Finalize();\n\tTurnOff();\n return 0;\n}\n" }, { "alpha_fraction": 0.6189062595367432, "alphanum_fraction": 0.6221442818641663, "avg_line_length": 29.886110305786133, "blob_id": "5651110a601c5c15814c63d1c7034042a45c760f", "content_id": "d0f392bd524f012d3fab29acfae0a6f389b48028", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11118, "license_type": "no_license", "max_line_length": 114, "num_lines": 360, "path": "/JackKnobel_ScriptingAssignment/source/TSU_Py.cpp", "repo_name": "Kanibel/Assignment_5", "src_encoding": "UTF-8", "text": "#include \"TSU_Py.h\"\n#include \"TSU.h\"\nvoid ParsePyTupleError(const char* a_pFunction, int a_Line )\n{\n\tstd::cout << \"___Error Parsing Tuple___\\nFunction: \" << a_pFunction << \"\\nLine# : \" << a_Line << std::endl;\n\tPyErr_Print();\n}\nPyObject* GetHandleToPythonFunction( PyObject* a_pModule, const char* a_pFunctionName )\n{\n\tPyObject* pFunction = PyObject_GetAttrString(a_pModule, a_pFunctionName);\n //pFunc is a new reference\n if( !(pFunction && PyCallable_Check(pFunction)) ) \n\t{\n if (PyErr_Occurred()){\n\t\t\tPyErr_Print();\n\t\t}\n std::cout << stderr << \"Cannot find function \\\"\" << a_pFunctionName << \"\\\"\" << std::endl;\n }\n\treturn pFunction;\n}\nPyObject* CallPythonFunction( PyObject* a_pyFunction, PyObject* a_pyFuncArguments)\n{\n\tPyObject* pReturnValue = PyObject_CallObject( a_pyFunction, a_pyFuncArguments );\n if (pReturnValue == nullptr)\n\t{\n\t\tPyErr_Print();\n\t\tfprintf(stderr,\"Call failed\\n\");\n }\n\treturn pReturnValue;\n}\n//=============================================================================================\n//Python Engine Functionality \n//=============================================================================================\nPyObject* TSU_Initialise(PyObject *self, PyObject *args)\n{\n\tconst char* p_WindowName; unsigned int fWidth; unsigned int fHeight; bool b_Fullscreen;\n\tif (!PyArg_ParseTuple(args, \"siib\", &p_WindowName, &fWidth, &fHeight, &b_Fullscreen))\n\t{\n\t\tParsePyTupleError( __func__, __LINE__ );\n\t\treturn nullptr;\n\t}\n\tInitialise(fWidth, fHeight, b_Fullscreen, p_WindowName);\n\tPy_RETURN_NONE;\n}\nPyObject* TSU_EngineRunning(PyObject *self, PyObject *args)\n{\n\tbool bGameRunning = EngineRunning();\n\tif(bGameRunning)\n\t\tPy_RETURN_TRUE;\n\telse \n\t\tPy_RETURN_FALSE;\n}\nPyObject* TSU_ClearScreen(PyObject *self, PyObject *args)\n{\n\tClearScreen();\n\tPy_RETURN_NONE;\n}\nPyObject* TSU_SetBackgroundColour(PyObject *self, PyObject *args)\n{\n\tfloat fRed; float fGreen; float fBlue; float fAlpha;\n\tif (!PyArg_ParseTuple(args, \"ffff\", &fRed, &fGreen, &fBlue, &fAlpha))\n\t{\n\t\tParsePyTupleError( __func__, __LINE__ );\n\t\treturn nullptr;\n\t}\n\tSetBackGroundColour(fRed, fGreen, fBlue, fAlpha);\n\tPy_RETURN_NONE;\n}\nPyObject* TSU_TurnOff(PyObject *self, PyObject *args)\n{\n\tTurnOff();\n\tPy_RETURN_NONE;\n}\n//=============================================================================================\n//Python Sprite Functionality \n//=============================================================================================\nPyObject* TSU_CreateSprite(PyObject *self, PyObject *args)\n{\n\tconst char* pTextureName; float fWidth; float fHeight; bool bDrawFromCenter;\n\tif (!PyArg_ParseTuple(args, \"sffb\", &pTextureName, &fWidth, &fHeight, &bDrawFromCenter)) \n\t{\n\t\tParsePyTupleError( __func__, __LINE__ );\n\t\treturn nullptr;\n\t}\n\tunsigned int uiSpriteID = CreateSprite(pTextureName, fWidth, fHeight, bDrawFromCenter);\n\treturn Py_BuildValue(\"i\", uiSpriteID);\n}\nPyObject* TSU_DrawSprite(PyObject *self, PyObject *args)\n{\n\tunsigned int uiSpriteID;\n\tif (!PyArg_ParseTuple(args, \"i\", &uiSpriteID))\n\t{\n\t\tParsePyTupleError( __func__, __LINE__ );\n\t\treturn nullptr;\n\t}\n\tDrawSprite(uiSpriteID);\n\tPy_RETURN_NONE;\n}\nPyObject* TSU_DestroySprite(PyObject *self, PyObject *args)\n{\n\tunsigned int uiSpriteID;\n\tif (!PyArg_ParseTuple(args, \"i\", &uiSpriteID))\n\t{\n\t\tParsePyTupleError( __func__, __LINE__ );\n\t\treturn nullptr;\n\t}\n\tDestroySprite(uiSpriteID);\n\tPy_RETURN_NONE;\n}\nPyObject* TSU_MoveSprite(PyObject *self, PyObject *args)\n{\n\tunsigned int uiSpriteID; float fXPos; float fYPos;\n\tif (!PyArg_ParseTuple(args, \"iff\", &uiSpriteID, &fXPos, &fYPos)) \n\t{\n\t\tParsePyTupleError( __func__, __LINE__ );\n\t\treturn nullptr;\n\t}\n\tMoveSprite(uiSpriteID, fXPos, fYPos);\n\tPy_RETURN_NONE;\n}\nPyObject* TSU_RotateSprite(PyObject *self, PyObject *args)\n{\n\tunsigned int uiSpriteID; float fRotation;\n\tif (!PyArg_ParseTuple(args, \"if\", &uiSpriteID, &fRotation))\n\t{\n\t\tParsePyTupleError( __func__, __LINE__ );\n\t\treturn nullptr;\n\t}\n\tRotateSprite(uiSpriteID, fRotation);\n\tPy_RETURN_NONE;\n}\nPyObject* TSU_UpdateSprite(PyObject *self, PyObject *args)\n{\n\tunsigned int uiSpriteID;\n\tif (!PyArg_ParseTuple(args, \"i\", &uiSpriteID))\n\t{\n\t\tParsePyTupleError( __func__, __LINE__ );\n\t\treturn nullptr;\n\t}\n\tUpdateSprite(uiSpriteID);\n\tPy_RETURN_NONE;\n}\n//=============================================================================================\n//Python Input Functionality \n//=============================================================================================\nPyObject* TSU_IsKeyDown(PyObject *self, PyObject *args)\n{\n\tunsigned int uiKey;\n\tif (!PyArg_ParseTuple(args, \"i\", &uiKey))\n\t{\n\t\tParsePyTupleError( __func__, __LINE__ );\n\t\treturn nullptr;\n\t}\n\tbool KeyisDown = IsKeyDown(uiKey);\n\tif (KeyisDown)\n\t\tPy_RETURN_TRUE;\n\telse\n\t\tPy_RETURN_FALSE;\n}\nPyObject* TSU_IsKeyReleased(PyObject *self, PyObject *args)\n{\n\tunsigned int uiKey;\n\tif (!PyArg_ParseTuple(args, \"i\", &uiKey))\n\t{\n\t\tParsePyTupleError( __func__, __LINE__ );\n\t\treturn nullptr;\n\t}\n\tbool KeyisPressed = IsKeyReleased(uiKey);\n\tif (KeyisPressed)\n\t\tPy_RETURN_TRUE;\n\telse\n\t\tPy_RETURN_FALSE;\n}\nPyObject* TSU_GetMouseButtonDown(PyObject *self, PyObject *args)\n{\n\tunsigned int uiMouseButton;\n\tif (!PyArg_ParseTuple(args, \"i\", &uiMouseButton))\n\t{\n\t\tParsePyTupleError( __func__, __LINE__ );\n\t\treturn nullptr;\n\t}\n\tbool MouseButtonDown = GetMouseButtonDown(uiMouseButton);\n\tif (MouseButtonDown)\n\t\tPy_RETURN_TRUE;\n\telse\n\t\tPy_RETURN_FALSE;\n}\nPyObject* TSU_GetMouseLocation(PyObject *self, PyObject *args)\n{\n\tint iXPos; int iYPos;\n\tGetMousePos(iXPos, iYPos);\n\treturn Py_BuildValue(\"ii\", iXPos, iYPos );\n\t/*if (!PyArg_ParseTuple(args, \"ii\", &iXPos, &iYPos))\n\t{\n\t\tParsePyTupleError( __func__, __LINE__ );\n\t\treturn nullptr;\n\t}\n\tGetMousePos(iXPos,iYPos);\n\tPy_RETURN_NONE;*/\n}\nPyObject* TSU_GetMouseButtonReleased(PyObject *self, PyObject *args)\n{\n\tunsigned int uiMouseButton;\n\tif (!PyArg_ParseTuple(args, \"i\", &uiMouseButton))\n\t{\n\t\tParsePyTupleError( __func__, __LINE__ );\n\t\treturn nullptr;\n\t}\n\tbool MouseButtonReleased = GetMouseButtonReleased(uiMouseButton);\n\tif (MouseButtonReleased)\n\t\tPy_RETURN_TRUE;\n\telse\n\t\tPy_RETURN_FALSE;\n}\n//=============================================================================================\n//Python DeltaTime \n//=============================================================================================\nPyObject* TSU_GetDeltaTime(PyObject *self, PyObject *args)\n{\n\tdouble DeltaTime = GetDeltaTime();\n\treturn Py_BuildValue(\"d\", DeltaTime);\n}\nPyMethodDef TSU_Functions[] = \n{\n\t{\"Initialise\",\t\t\t\tTSU_Initialise,\t\t\t\t\tMETH_VARARGS,\t\t\"Initialise TSU Engine\"\t\t\t\t\t\t\t\t\t},\n\t{\"EngineRunning\",\t\t\tTSU_EngineRunning,\t\t\t\tMETH_VARARGS,\t\t\"While the TSU Framework running update.\"\t\t\t\t},\n\t{\"ClearScreen\",\t\t\t\tTSU_ClearScreen,\t\t\t\tMETH_VARARGS,\t\t\"Clear the OpenGL Render scene.\"\t\t\t\t\t\t},\n\t{\"SetBackgroundColour\",\t\tTSU_SetBackgroundColour,\t\tMETH_VARARGS,\t\t\"Sets the background Colour of the Scene\"\t\t\t\t},\n\t{\"TurnOff\",\t\t\t\t\tTSU_TurnOff,\t\t\t\t\tMETH_VARARGS,\t\t\"Turnoff\"\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t{\"CreateSprite\",\t\t\tTSU_CreateSprite,\t\t\t\tMETH_VARARGS,\t\t\"Create a sprite object\"\t\t\t\t\t\t\t\t},\n\t{\"DestroySprite\",\t\t\tTSU_DestroySprite,\t\t\t\tMETH_VARARGS,\t\t\"Destroy a sprite object\"\t\t\t\t\t\t\t\t},\n\t{\"MoveSprite\",\t\t\t\tTSU_MoveSprite,\t\t\t\t\tMETH_VARARGS,\t\t\"Move Sprite\"\t\t\t\t\t\t\t\t\t\t\t},\n\t{\"DrawSprite\",\t\t\t\tTSU_DrawSprite,\t\t\t\t\tMETH_VARARGS,\t\t\"Draw Sprite\"\t\t\t\t\t\t\t\t\t\t\t},\n\t{\"RotateSprite\",\t\t\tTSU_RotateSprite,\t\t\t\tMETH_VARARGS,\t\t\"Draw Sprite\"\t\t\t\t\t\t\t\t\t\t\t},\n\t{\"UpdateSprite\",\t\t\tTSU_UpdateSprite,\t\t\t\tMETH_VARARGS,\t\t\"Update Sprite\"\t\t\t\t\t\t\t\t\t\t\t},\n\n\t{\"IsKeyDown\",\t\t\t\tTSU_IsKeyDown,\t\t\t\t\tMETH_VARARGS,\t\t\"IsKeyDown\"\t\t\t\t\t\t\t\t\t\t\t\t},\n\t{\"IsKeyPressed\",\t\t\tTSU_IsKeyReleased,\t\t\t\tMETH_VARARGS,\t\t\"IsKeyPressed\"\t\t\t\t\t\t\t\t\t\t\t},\n\t{\"GetMouseLocation\",\t\tTSU_GetMouseLocation,\t\t\tMETH_VARARGS,\t\t\"Where is the Mouse?\"\t\t\t\t\t\t\t\t\t},\n\t{\"GetMouseButton\",\t\t\tTSU_GetMouseButtonDown,\t\t\tMETH_VARARGS,\t\t\"Mouse Button Pressed?\"\t\t\t\t\t\t\t\t\t},\n\t{\"GetMouseButtonRelease\",\tTSU_GetMouseButtonReleased,\t\tMETH_VARARGS,\t\t\"Mouse Button Let Go?\"\t\t\t\t\t\t\t\t\t},\n\n\t{\"GetDeltaTime\",\t\t\tTSU_GetDeltaTime,\t\t\t\tMETH_VARARGS,\t\t\"GetDeltaTime\"\t\t\t\t\t\t\t\t\t\t\t},\n\t{NULL, NULL, 0, NULL}\n};\n\nbool TSUPyInitialise()\n{\n\tbool returnb = false;\n\tPy_Initialize();\n\tif (Py_IsInitialized())\n\t{\n\t\tPyObject* sysPath = PySys_GetObject((char*)\"path\");\n\t\tPyList_Append(sysPath, PyString_FromString(\"./Scripts\"));\n\t\tPy_InitModule(\"TSU\",TSU_Functions);\n\t\treturnb = true;\n\t}else\n\t{\n\t\tprintf(\"Something broke with python...\\n\");\n\t}\n\treturn returnb;\n}\nbool TSUPyInitialise(int argc, char* argv[])\n{\n\tbool returnb = false;\n\tif (TSUPyInitialise())\n\t{\n\t\tPySys_SetArgv(argc, argv);\n\t\treturnb = true;\n\t}\n\treturn returnb;\n}\nPyObject* TSUImportPythonModule( const char* a_pyModuleName )\n{\n\tPyObject* pObjName= PyString_FromString(a_pyModuleName);\n\tPyObject* pModule = PyImport_Import(pObjName);\n\tif (!pModule)\n\t{\n PyErr_Print();\n std::cout << stderr << \"Failed to load \\\"\" << a_pyModuleName << \"\\\"\\n\" << std::endl;\n }\n Py_DECREF(pObjName);\n\treturn pModule;\n}\nvoid TSUReloadPythonModule(PyObject* a_pModule)\n{\n\tPyObject* pModule = PyImport_ReloadModule(a_pModule);\n\tif (pModule == NULL)\n\t{\n\t\tstd::cout << stderr << \"Failed to reload, Python returned NULL.\\n\" << std::endl;\n\t\treturn;\n\t}\n\ta_pModule = pModule;\n}\nbool TSUCallPythonFunction(PyObject* a_pModule, char* cs_FunctionName){\n\tbool bSuccess = false;\n\tPyObject* pFunction = GetHandleToPythonFunction( a_pModule, cs_FunctionName);\n\tif( pFunction ){\n\t\tPyObject* pReturnValue = CallPythonFunction( pFunction, nullptr );\n\t\tif( pReturnValue ){\n\t\t\tbSuccess = true;\n\t\t}\n\t\tPy_XDECREF(pFunction);\t\n\t}\n\treturn bSuccess;\n}\n//\\=============================================================================== My own overloaded python passer\nbool TSUCallPythonFunction(PyObject* a_pModule, char* cs_FunctionName,char* VarTypes,...)\n{\n\tbool bSuccess = false;\n\t//This takes the arguments and converts to python args to pass\n\tint stringLength = strlen(VarTypes);\n\tva_list vaItems;\n\tva_start(vaItems,VarTypes);\n\tPyObject* pArgs;\n\n\tif (stringLength > 0)\n\t{\n\t\tpArgs = PyTuple_New(stringLength);\n\t\tfor (int i = 0; i < stringLength; i++)\n\t\t{\n\t\t\tint iChar = VarTypes[i];\n\t\t\tswitch (iChar){\n\t\t\tcase 98: case 66://b B\n\t\t\t\tPyTuple_SetItem( pArgs, i, PyBool_FromLong( va_arg(vaItems,bool) ) );\n\t\t\t\tbreak;\n\t\t\tcase 105: case 73://i I\n\t\t\t\tPyTuple_SetItem( pArgs, i, PyInt_FromLong( va_arg(vaItems,int) ) );\n\t\t\t\tbreak;\n\t\t\tcase 108: case 76://l L\n\t\t\t\tPyTuple_SetItem( pArgs, i, PyLong_FromLong( va_arg(vaItems,long) ) );\n\t\t\t\tbreak;\n\t\t\tcase 102: case 70://f F\n\t\t\tcase 100: case 68://d D\n\t\t\t\tPyTuple_SetItem( pArgs, i, PyFloat_FromDouble(va_arg(vaItems,double) ) );\n\t\t\t\tbreak;\n\t\t\tcase 99: case 67://c C\n\t\t\t\tPyTuple_SetItem( pArgs, i, Py_BuildValue(\"c\",va_arg(vaItems,char) ) );\n\t\t\t\tbreak;\n\t\t\tcase 115: case 83://s S\n\t\t\t\tPyTuple_SetItem( pArgs, i, PyString_FromString( va_arg(vaItems,char*) ) );\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tva_end(vaItems);\n\t//End of passer\n\tPyObject* pFunction = GetHandleToPythonFunction( a_pModule, cs_FunctionName);\n\tif( pFunction )\n\t{\n\t\tPyObject* pReturnValue = CallPythonFunction( pFunction, pArgs );\n\t\tif( pReturnValue ){\n\t\t\tbSuccess = true;\n\t\t}\n\t\tPy_XDECREF(pFunction);\t\n\t}\n\treturn bSuccess;\n}\n//\\=============================================================================== EOF" }, { "alpha_fraction": 0.6821079850196838, "alphanum_fraction": 0.6875731945037842, "avg_line_length": 34.90654373168945, "blob_id": "cc83e6885658b37b03c1d50eddbbb5ff3a3ba7a9", "content_id": "d891ff1ab91c961b6d98e6494b36418cafd566cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7685, "license_type": "no_license", "max_line_length": 127, "num_lines": 214, "path": "/JackKnobel_ScriptingAssignment/resources/scripts/mapsheet.py", "repo_name": "Kanibel/Assignment_5", "src_encoding": "UTF-8", "text": "#Python Includes\nimport math\nimport random\n\n#Custom Includes\nimport TSU\nimport game\nimport JKDefs\nimport pathfinding\nimport Vector\n\n#Global Sprites\nglobal GrassSprite\nglobal WallSprite\nglobal StartSprite\nglobal EndSprite\nglobal PathSprite\n\n#Global Class\nglobal AStar\nAStar = None\nglobal Dijkstra\nDijkstra = None\n\nclass LevelMap:\n\t\"\"\"docstring for LevelMap\"\"\"\n\tdef __init__(self, gameSize, tileSize):\n\t\treload(pathfinding)\n\t\tself.tileSize = tileSize\n\t\tself.buttonPressed = [False]*5\n\t\tself.levelSize = {'Width':gameSize['width']/tileSize['width'], 'Height':gameSize['height']/tileSize['height']}\n\t\tself.levelTiles = [[None]*self.levelSize['Height'] for i in range(self.levelSize['Width'] )]\n\t\tself.wallList = []\n\n\t\tfor x in range(len(self.levelTiles)):\n\t\t\tfor y in range(len(self.levelTiles[x])):\n\t\t\t\tt = Tile()\n\t\t\t\tif (x == 0 and y):\n\t\t\t\t\tt.position.x = (self.tileSize['height']) * (x%gameSize['height'] ) - (self.tileSize['height'])\n\t\t\t\t\tt.position.y = (self.tileSize['width']) * (y%gameSize['width'] ) + 2 \n\t\t\t\tif (y == 0 and x):\n\t\t\t\t\tt.position.x = (self.tileSize['height']) * (x%gameSize['height'] ) \n\t\t\t\t\tt.position.y = (self.tileSize['width']) * (y%gameSize['width'] ) + 2 - (self.tileSize['width'])\n\n\t\t\t\tif(x == self.levelSize['Width'] - 1):\n\t\t\t\t\tt.position.x = (self.tileSize['height']) * (x%gameSize['height'] ) + (self.tileSize['height'])\n\t\t\t\t\tt.position.y = (self.tileSize['width']) * (y%gameSize['width'] ) + 2 \n\t\t\t\tif(y == self.levelSize['Height'] - 1):\n\t\t\t\t\tt.position.x = (self.tileSize['height']) * (x%gameSize['height'] ) \n\t\t\t\t\tt.position.y = (self.tileSize['width']) * (y%gameSize['width'] ) + 2 + (self.tileSize['width'])\n\t\t\t\t\n\t\t\t\tself.wallList.append(t)\n\n\t\tfor x in range(len(self.levelTiles)):\n\t\t\tfor y in range(len(self.levelTiles[x])):\n\t\t\t\tself.levelTiles[x][y] = Tile()\n\t\t\t\tself.levelTiles[x][y].position.x = (self.tileSize['height']) * (x%gameSize['height'] ) \n\t\t\t\tself.levelTiles[x][y].position.y = (self.tileSize['width']) * (y%gameSize['width'] ) + 2\n\tdef getWallList(self):\n\t\treturn self.wallList\n\tdef loadSprites(self):\n\t\tglobal GrassSprite\n\t\tGrassSprite = TSU.CreateSprite(self.levelTiles[0][0].getImageName(), self.tileSize['width'] , self.tileSize['height'], False)\n\t\tglobal WallSprite\n\t\tWallSprite = TSU.CreateSprite(\"./images/wall.png\", self.tileSize['width'] , self.tileSize['height'], False)\n\t\tglobal StartSprite\n\t\tStartSprite = TSU.CreateSprite(\"./images/seamGrass.jpg\", self.tileSize['width'] , self.tileSize['height'], False)\n\t\tglobal EndSprite\n\t\tEndSprite = TSU.CreateSprite(\"./images/crate_sideup - Copy.png\", self.tileSize['width'] , self.tileSize['height'], False)\n\t\tglobal PathSprite\n\t\tPathSprite = TSU.CreateSprite(\"./images/pathSprite.png\", self.tileSize['width'] , self.tileSize['height'], False) \n\n\t\tfor x in range(len(self.levelTiles)):\n\t\t\tfor y in range(len(self.levelTiles[x])):\n\t\t\t\tself.levelTiles[x][y].setSpriteID(GrassSprite)\n\n\tdef Update(self, fDeltaTime):\n\t\tglobal AStar\n\t\tglobal Dijkstra\n\n\t\tmouseX, mouseY = TSU.GetMouseLocation()\n\t\ttx = mouseX/self.tileSize['width']\n\t\tty = mouseY/self.tileSize['height']\n\n\t\tif(TSU.GetMouseButton(JKDefs.MOUSE_BUTTON_1) and (self.buttonPressed[0] is False)):\n\t\t\tself.buttonPressed[0] = True\n\t\t\t#If Sprite is Grass sprite change to Start Sprite\n\t\t\tif(self.levelTiles[tx][ty].getSpriteID() == GrassSprite):\n\t\t\t\tself.levelTiles[tx][ty].setSpriteID(StartSprite)\n\t\t\t\tself.levelTiles[tx][ty].reachable = 1\n\t\t\t\treturn\n\t\t\t#If Sprite is Start Sprite change to End Sprite\n\t\t\tif(self.levelTiles[tx][ty].getSpriteID() == StartSprite):\n\t\t\t\tself.levelTiles[tx][ty].setSpriteID(EndSprite) \n\t\t\t\tself.levelTiles[tx][ty].reachable = 1\n\t\t\t\treturn\n\t\t\t#If Sprite is End Sprite change to Start Sprite\n\t\t\tif(self.levelTiles[tx][ty].getSpriteID() == EndSprite):\n\t\t\t\tself.levelTiles[tx][ty].setSpriteID(StartSprite) \n\t\t\t\tself.levelTiles[tx][ty].reachable = 1\n\t\t\t\treturn\n\t\t#On right click set's any tile to Wall Sprite\n\t\tif(TSU.GetMouseButton(JKDefs.MOUSE_BUTTON_2)):\n\t\t\tself.levelTiles[tx][ty].setSpriteID(WallSprite) \n\t\t\tself.levelTiles[tx][ty].reachable = 0\n\t\t\tif(self.levelTiles[tx][ty] not in self.wallList):\n\t\t\t\tself.wallList.append(self.levelTiles[tx][ty])\n\n\t\tif(TSU.GetMouseButton(JKDefs.MOUSE_BUTTON_3) and (self.buttonPressed[1] is False)):\n\t\t\tif(self.levelTiles[tx][ty].getSpriteID() == WallSprite):\n\t\t\t\tself.wallList.remove(self.levelTiles[tx][ty])\n\t\t\tself.buttonPressed[1] = True\n\t\t\tself.levelTiles[tx][ty].setSpriteID(GrassSprite)\n\n\t\tself.buttonPressed[0] = not TSU.GetMouseButtonRelease(JKDefs.MOUSE_BUTTON_1)\n\t\tself.buttonPressed[1] = not TSU.GetMouseButtonRelease(JKDefs.MOUSE_BUTTON_3)\n\n\t\tif(TSU.IsKeyDown(JKDefs.KEY_LCTRL) and TSU.IsKeyDown(JKDefs.KEY_LSHIFT )):\n\t\t\tprint \"Path Finding Reset\"\n\t\t\tfor x in range(len(self.levelTiles)):\n\t\t\t\tfor y in range(len(self.levelTiles[x])):\n\t\t\t\t\tif(self.levelTiles[x][y].getSpriteID() == PathSprite):\n\t\t\t\t\t\tself.levelTiles[x][y].setSpriteID(GrassSprite)\n\t\t\t\t\t\tself.levelTiles[x][y].reachable = 1\n\t\t\t\t\t\treturn\n\n\t\tif(TSU.IsKeyDown(JKDefs.LETTER_A) and (self.buttonPressed[3] is False)):\n\t\t\tself.buttonPressed[3] = True\n\t\t\tstart = None\n\t\t\tend = None\n\t\t\tfor x in range(len(self.levelTiles)):\n\t\t\t\tfor y in range(len(self.levelTiles[x])):\n\t\t\t\t\tif (self.levelTiles[x][y].getSpriteID() == StartSprite):\n\t\t\t\t\t\tstart = self.levelTiles[x][y]\n\t\t\t\t\telif(self.levelTiles[x][y].getSpriteID() == EndSprite):\n\t\t\t\t\t\tend = self.levelTiles[x][y]\n\t\t\tif(start is not None and end is not None):\n\t\t\t\tAStar = pathfinding.AStar(self.levelSize, self.levelTiles, self.tileSize, start, end, PathSprite)\n\n\t\t\tif (AStar is not None):\n\t\t\t\tp = AStar.findPath()\n\t\t\t\tAStar = None\n\t\t\t\t#print AStar\n\t\t\t\t#print p\n\n\t\tself.buttonPressed[3] = TSU.IsKeyDown(JKDefs.LETTER_A)\n\n\t\tif(TSU.IsKeyDown(JKDefs.LETTER_D) and (self.buttonPressed[3] is False)):\n\t\t\tself.buttonPressed[3] = True\n\t\t\tstart = None\n\t\t\tend = None\n\t\t\tfor x in range(len(self.levelTiles)):\n\t\t\t\tfor y in range(len(self.levelTiles[x])):\n\t\t\t\t\tif (self.levelTiles[x][y].getSpriteID() == StartSprite):\n\t\t\t\t\t\tstart = self.levelTiles[x][y]\n\t\t\t\t\telif(self.levelTiles[x][y].getSpriteID() == EndSprite):\n\t\t\t\t\t\tend = self.levelTiles[x][y]\n\t\t\tif(start is not None and end is not None):\n\t\t\t\tDijkstra = pathfinding.Dijkstra(self.levelSize, self.levelTiles, self.tileSize, start, end, PathSprite)\n\n\t\t\tif (Dijkstra is not None):\n\t\t\t\tp = Dijkstra.findPath()\n\t\t\t\tDijkstra = None\n\t\t\t\t#print AStar\n\t\t\t\t#print p\n\n\t\tself.buttonPressed[3] = TSU.IsKeyDown(JKDefs.LETTER_D)\n\n\tdef isReachable(self, objectPosition):\n\t\tobjPosX = objectPosition.x / self.tileSize['width']\n\t\tobjPosY = objectPosition.y / self.tileSize['height']\n\t\tif(self.levelTiles[objPosX][objPosY].getSpriteID() == WallSprite):\n\t\t\treturn True\n\t\treturn False\n\n\tdef draw(self):\n\t\tfor x in range(len(self.levelTiles)):\n\t\t\tfor y in range(len(self.levelTiles[x])):\t\n\t\t\t\tTSU.MoveSprite(self.levelTiles[x][y].getSpriteID(),self.levelTiles[x][y].position.x,self.levelTiles[x][y].position.y)\n\t\t\t\tTSU.UpdateSprite(self.levelTiles[x][y].getSpriteID())\t\n\t\t\t\tTSU.DrawSprite(self.levelTiles[x][y].getSpriteID())\n\n\tdef cleanUp(self):\n\t\tTSU.DestroySprite(GrassSprite)\n\t\tTSU.DestroySprite(WallSprite)\n\t\tTSU.DestroySprite(StartSprite)\n\t\tTSU.DestroySprite(EndSprite)\n\t\tTSU.DestroySprite(PathSprite)\n\nclass Tile:\n\tdef __init__(self):\n\t\tself.imageName = \"./images/grassTile.png\"\n\t\tself.spriteID = -1\n\t\tself.state = 0\n\t\tself.position = Vector.Vector(0,0)\n\t\tself.reachable = 1\n\t\tself.parent = None\n\t\tself.g = 0\n\t\tself.h = 0\n\t\tself.f = 0\n\tdef __repr__(self):\n\t\treturn 't : %d %d' % (self.position.x,self.position.y)\n\n\tdef getImageName(self):\n\t\treturn self.imageName\n\n\tdef getState(self):\n\t\treturn self.state \n\n\tdef getSpriteID(self):\n\t\treturn self.spriteID\n\n\tdef setSpriteID(self, a_spriteID):\n\t\tself.spriteID = a_spriteID\n\n" }, { "alpha_fraction": 0.4588659405708313, "alphanum_fraction": 0.46607670187950134, "avg_line_length": 47.44444274902344, "blob_id": "bfb6d8d3546eb6fa59efd9dac13b7dbd301c1240", "content_id": "53a29f367b22a7eb365ad7106d54ae61fe33fba9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3051, "license_type": "no_license", "max_line_length": 123, "num_lines": 63, "path": "/JackKnobel_ScriptingAssignment/include/TSU.h", "repo_name": "Kanibel/Assignment_5", "src_encoding": "UTF-8", "text": "#ifndef _TSU_\n#define _TSU_\n#include \"JKMath.h\"\n//=============================================================================================\n//Engine Functionality \n//=============================================================================================\nvoid Initialise(unsigned int ui_Width, unsigned int ui_Height, bool b_Fullscreen, const char* p_WindowName);\n\nvoid ClearScreen();\n\nvoid SetBackGroundColour(Vector4 vec4_Colour);\n\nvoid SetBackGroundColour(float f_red, float f_green, float f_blue, float f_alpha);\n\nvoid TurnOff();\n\nbool EngineRunning();\n//=============================================================================================\n//Sprite Functionality \n//=============================================================================================\nunsigned int CreateSprite(const char* p_TextureName, unsigned int ui_Width, unsigned int ui_Height, bool b_DrawFromCenter);\n\nvoid DrawSprite(unsigned int ui_SpriteID);\n\nvoid MoveSprite(unsigned int ui_SpriteID, float f_XPos, float f_YPos);\n\nvoid RotateSprite(unsigned int ui_SpriteID, float f_Rotation);\n\nvoid DestroySprite(unsigned int ui_SpriteID);\n//=============================================================================================\n//Sprite Physics\n//=============================================================================================\nvoid UpdateSprite(unsigned int ui_SpriteID); // Used to update World Physics\n\nvoid ChangeVelocity(unsigned int ui_SpriteID, Vector3 vec3_Vel);\n\nvoid ChangeForce(unsigned int ui_SpriteID, Vector3 vec3_For);\n\nvoid ChangeGravity(unsigned int ui_SpriteID, Vector3 vec3_Grav);\n\nvoid ChangeDamping(unsigned int ui_SpriteID, float f_Damping);\n//=============================================================================================\n// String Functionality\n//=============================================================================================\nvoid DrawString(const char* cp_TextToDisplay, Vector4 vec4_Position, Vector4 vec4_Colour);\nvoid DrawString(const char* cp_TextToDisplay, float f_x, float f_y, Vector4 vec4_Colour);\n//=============================================================================================\n// Line Functionality\n//=============================================================================================\nvoid DrawLine(float f_StartX,float f_StartY, float f_EndX,float f_EndY, Vector4 vec4_LineColour); \nvoid DrawLine(Vector2 vec2_Start, Vector2 vec2_End, Vector4 vec4_LineColour); \n//=============================================================================================\n//Input Functionality \n//=============================================================================================\nbool IsKeyDown(unsigned int ui_Key);\nbool IsKeyReleased(unsigned int ui_Key);\nbool GetMouseButtonDown(unsigned int ui_MouseButton);\nvoid GetMousePos(int &iMousePosX, int &iMousePosY );\nbool GetMouseButtonReleased(unsigned int ui_MouseButton);\n\ndouble GetDeltaTime();\n//=============================================================================================\n#endif" }, { "alpha_fraction": 0.38461539149284363, "alphanum_fraction": 0.42307692766189575, "avg_line_length": 12, "blob_id": "5b49585734a3f90d31e6fe4ee854237a90781bbb", "content_id": "49ef3cf5dfe1cf8ba5952658e9b42049b7b0afea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 26, "license_type": "no_license", "max_line_length": 12, "num_lines": 2, "path": "/README.md", "repo_name": "Kanibel/Assignment_5", "src_encoding": "UTF-8", "text": "Assignment_5\n============\n" }, { "alpha_fraction": 0.5530726313591003, "alphanum_fraction": 0.5558659434318542, "avg_line_length": 34.79999923706055, "blob_id": "a8e15ed08ab43edfc87598a14785d4e10b06c627", "content_id": "21bb0ef551131fc5b23ce1b1edf7518e12b9302d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 716, "license_type": "no_license", "max_line_length": 95, "num_lines": 20, "path": "/JackKnobel_ScriptingAssignment/include/TSU_Py.h", "repo_name": "Kanibel/Assignment_5", "src_encoding": "UTF-8", "text": "#ifndef _TSU_PY_H\n#define _TSU_PY_H\n\n#include <Python.h>\n\n#if defined (_WIN32)\n#define __func__ __FUNCTION__\n#endif\n//=============================================================================================\n//TSU_PY Functions\n//=============================================================================================\nextern PyMethodDef TSU_Functions[];\n\nbool TSUPyInitialise();\nbool TSUPyInitialise(int argc, char* argv[]);\nPyObject* TSUImportPythonModule( const char* a_pyModuleName );\nvoid TSUReloadPythonModule(PyObject* a_pModule);\nbool TSUCallPythonFunction(PyObject* a_pModule, char* cs_FunctionName);\nbool TSUCallPythonFunction(PyObject* a_pModule, char* cs_FunctionName,char* VarTypes,...);\n#endif " }, { "alpha_fraction": 0.3867248594760895, "alphanum_fraction": 0.40116408467292786, "avg_line_length": 48.08241653442383, "blob_id": "fe341fa18d5ea6538005a7c772c841b61f547b86", "content_id": "6d388e653bc0f442b2251490d2ebc5364f00562b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8934, "license_type": "no_license", "max_line_length": 148, "num_lines": 182, "path": "/JackKnobel_ScriptingAssignment/include/JKMath.h", "repo_name": "Kanibel/Assignment_5", "src_encoding": "UTF-8", "text": "//==============================================================================\n// Used for defining useful math functions and some constant variables.\n// With the help of @Pete Keys for some of the Bitwise Operations & Conversions\n//==============================================================================\n#ifndef _JKMATH_H\n#define _JKMATH_H\n#pragma region Includes\n//------------------------------------------\n// Built in Includes \n//------------------------------------------\n#include <math.h>\n#include <istream>\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <algorithm>\n//------------------------------------------\n// User Made Includes \n//------------------------------------------\n#include \"Vector2.h\"\n#include \"Vector3.h\"\n#include \"Vector4.h\"\n#include \"Matrix3.h\"\n#include \"Matrix4.h\"\n//------------------------------------------\n#pragma endregion\n#pragma region Common Math Functionality\n//=====================================================================================\n// Constant Variables\n//=====================================================================================\nconst float PI\t\t\t= 3.1415926f;\nconst float TWOPI\t\t= 6.2831853f;\nconst float HALFPI\t\t= 1.5707963f;\n\nconst float DEG2RAD = 0.0174532f;\nconst float RAD2DEG\t\t= 57.295779f;\n//=====================================================================================\n// Reciprocal Function - used for finding the multiplicative inverse \n// e.g Reciprocal of 5 is one fifth (1/5 or 0.2), Reciprocal of 0.25 is 1/0.25 or 4\n//=====================================================================================\ninline float Reciprocal(float x) { return (1.0f / x); }\n//=====================================================================================\n// Trigonometry Functions\n//=====================================================================================\ninline float Acosf( float x ) { return acosf( x ); }\ninline float Asinf( float x ) { return asinf( x ); }\ninline float Atanf( float x ) { return atanf( x ); }\ninline float Atan2f( float y, float x ) { return atan2f( y, x ); }\ninline float Cosf( float x ) { return cosf( x ); }\ninline float Sinf( float x ) { return sinf( x ); }\ninline float Tanf( float x ) { return tanf( x ); }\n//=====================================================================================\n// Exponential & Logarithmic Functions\n//=====================================================================================\ninline float Expon (float x) { return expf(x); }\ninline float Logar (float x) { return logf(x); }\ninline float Logar10 (float x) { return log10f(x); }\n//=====================================================================================\n// Power , SquareRoot and Inverse of Squareroot\n//=====================================================================================\ninline float PowTo (float x, float y) { return powf(x, y); }\ninline float SqRoot (float x) { return sqrtf(x); }\ninline float InvSqRoot (float x) { return 1.0f/sqrtf(x); }\n//=====================================================================================\n// Nearest integer, absolute value and finding the remainder\n//=====================================================================================\ninline float SmallVal (float x) { return ceilf(x); }\t\t\t\t\t// Rounds down to the smallest possible value greater then or equal to x\ninline float AbsoVal (float x) { return fabsf(x); }\t\t\t\t\t\t// Finds the Absolute value\ninline float LargVal (float x) { return floorf(x); }\t\t\t\t\t// Rounds up to the largest Value less then or equal to x\ninline float Modular (float x, float y) { return fmodf( x, y); } // Returns true value and fractional value. 31415.9265 = 31415.0000 + 0.9265\n#pragma endregion\n#pragma region Math Min and Max Values\n//=====================================================================================\n// Sign Function change between -x and x\n//=====================================================================================\ninline float Sign (float x) { return (x >= 0.0f) ? 1.0f : -1.0f; }\n//=====================================================================================\n// Min and Max Functions - Return Largest or negative values both Int and Float \n//=====================================================================================\ninline int Max (int x, int y) {return (x > y) ? x : y; }\ninline int Min (int x, int y) {return (x < y) ? x : y; }\ninline float Maxf (float x, float y) { return (x > y) ? x : y; }\ninline float MinF (float x, float y) { return (x < y) ? x : y; }\n//=====================================================================================\n// Clamp a value to a range - Between 0.0f and 1.0f \n//=====================================================================================\ninline float Clampf(float x)\n{\n\treturn (x > 1.0f) ? 1.0f : ((x < 0.0f) ? 0.0f : x);\n}\n//=====================================================================================\n// Clamp a value to a range - Between Min and Max\n//=====================================================================================\ninline float Clampf (float x, float min_x, float max_x ) \n{\n\treturn (x > max_x) ? max_x : ((x < min_x) ? min_x : x);\n}\ninline int Clamp (int x, int min_x, int max_x)\n{\n\treturn (x > max_x) ? max_x : (( x < min_x) ? min_x : x);\n}\n#pragma endregion\n#pragma region Linear Interpolation for scalar values\n//=====================================================================================\n// Linearly interpolate a float - Find a position on a line drawn between two points\n//=====================================================================================\ninline float Lerp(float fA, float fB, float fT)\n{\n\treturn (fB - fA) * fT + fA;\n}\n//=====================================================================================\n// Interpolation - Cosine , SmoothStep, SmootherStep, Acceleration and Deceleration http://vidyadev.com/wiki/Interpolation\n//=====================================================================================\n// Cosine - Provides smooth acceleration and deceleration \ninline float CosineInterpolate (float fA, float fB, float t)\n{\n\tfloat c = ( 1 - cos(t * PI)) / 2;\n\treturn fA *(1 - c) + fB * c;\n}\n// SmoothStep - Similar to cosines smoothness however does not require complex trig functions. \n//More useful on mobile or fixed platforms. Only modifies t in linear interpolation\ninline float SmoothStep (float fA, float fB, float t) \n{ \n\treturn fA + (pow(t, 2) * (3 - 2 * t)) * (fB - fA); \n}\n//Acceleration - Useful for moving a menu item into view or having a weapon change at an inclining rate\ninline float Acceleration(float fA, float fB, float t)\n{\n\treturn fA + (pow(t,2)) * (fB - fA);\n}\n //Deceleration\ninline float Deceleration (float fA, float fB, float t)\n{\n\treturn fA + (1.f - pow((1.f - t), 2)) * (fB - fA);\n}\n#pragma endregion\n#pragma region Testing scalar value for power of two\n//=====================================================================================\n// Nearest Power of 2\n//=====================================================================================\nint nearestpower2(int value);\n\n#pragma endregion\n#pragma region Bitwise Operations\n//=====================================================================================\n//\tHexadecimal to Decimal\n//=====================================================================================\ninline unsigned long long HEX2DEC(std::string HEX)\n{\n\t unsigned long long r;\n\t std::istringstream(HEX) >> std::hex >> r;\n\t return r;\n}\n//=====================================================================================\n// Hexadecimal to Binary\n//=====================================================================================\nstd::string HEX2BIN (std::string HEX);\n\n//=====================================================================================\n// Decimal to Hexadecimal\n//=====================================================================================\ninline std::string DEC2HEX(unsigned long long DEC)\n{\n\t std::string r = static_cast<std::ostringstream*>( &(std::ostringstream() << std::hex << DEC) )->str();\n\t return r;\n}\n//=====================================================================================\n// Decimal to Binary\n//=====================================================================================\nstd::string DEC2BIN(unsigned long long DEC);\n//=====================================================================================\n// Binary to Hexadecimal\n//=====================================================================================\nstd::string BIN2HEX(std::string BIN);\n//=====================================================================================\n// Binary to Decimal\n//=====================================================================================\nunsigned long BIN2DEC(std::string BIN);\n\n#pragma endregion\n\n#endif\n\n" }, { "alpha_fraction": 0.5153980255126953, "alphanum_fraction": 0.5183033347129822, "avg_line_length": 21.946666717529297, "blob_id": "38d352241e83e8f654e96fd13ecae0565d02aec2", "content_id": "a5fbc69af7475e113e45f01bc3747b742bcd8203", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1721, "license_type": "no_license", "max_line_length": 57, "num_lines": 75, "path": "/JackKnobel_ScriptingAssignment/resources/scripts/Vector.py", "repo_name": "Kanibel/Assignment_5", "src_encoding": "UTF-8", "text": "#Python Includes\nimport math\n#=========================================\n#Includes\nimport TSU\n#=========================================\n\nclass Vector:\n\tdef __init__(self, x, y):\n\t\tself.x = float(x)\n\t\tself.y = float(y)\n\n\tdef __repr__(self):\n\t\treturn '%s %s' % (self.x,self.y)\n\n\tdef Magnitude(self): \n\t\treturn math.sqrt((self.x * self.x) + (self.y * self.y))\n\n\tdef Norm(self):\n\t\tMag = self.Magnitude()\n\t\tif Mag < 1:\n\t\t\tMag = 1\n\t\tself.x /= Mag\n\t\tself.y /= Mag\n\n\tdef Distance(self, Vector):\n\t\treturn((self - Vector).Magnitude())\n\n\t#======================================================\n\t#Operator Overloads \n\t#======================================================\n\tdef __add__(self, other):\n\t\tif(isinstance(other, Vector)):\n\t\t\tnx = self.x + other.x\n\t\t\tny = self.y + other.y\n\t\telif(isinstance(other, (int, float, long))):\n\t\t\tnx = self.x + other \n\t\t\tny = self.y + other\n\t\treturn Vector(nx, ny)\n\n\tdef __sub__(self, other):\n\t\tif(isinstance(other, Vector)):\n\t\t\tnx = self.x - other.x\n\t\t\tny = self.y - other.y\n\t\telif(isinstance(other, (int, float, long))):\n\t\t\tnx = self.x - other \n\t\t\tny = self.y - other\n\t\treturn Vector(nx, ny)\n\n\tdef __mul__(self, other):\n\t\tif(isinstance(other, Vector)):\n\t\t\tnx = self.x * other.x\n\t\t\tny = self.y * other.y\n\t\telif(isinstance(other, (int, float, long))):\n\t\t\tnx = self.x * other \n\t\t\tny = self.y * other\n\t\treturn Vector(nx, ny)\n\n\tdef __div__(self, other):\n\t\tnx = self.x\n\t\tny = self.y\n\t\tif(isinstance(other, Vector)):\n\t\t\tif(other.x!=0):\n\t\t\t\tnx = self.x / other.x\n\t\t\tif(other.y!=0):\n\t\t\t\tny = self.y / other.y\n\t\telif isinstance(other, (int, float, long)):\n\t\t\tif(other!=0):\n\t\t\t\tnx = self.x / other\n\t\t\t\tny = self.y / other\n\t\treturn Vector(nx,ny)\n\t\n\tdef __neg__(self):\n\t\tself.x = -self.x\n\t\tself.y = -self.y\n" }, { "alpha_fraction": 0.6697141528129578, "alphanum_fraction": 0.6852948665618896, "avg_line_length": 26.507143020629883, "blob_id": "d1472e1a57e42530f186746a8d4853c2557b57e4", "content_id": "4d29fa1119e096ed0d4cfe80a67ccde16433286a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7766, "license_type": "no_license", "max_line_length": 143, "num_lines": 280, "path": "/JackKnobel_ScriptingAssignment/resources/scripts/Boid.py", "repo_name": "Kanibel/Assignment_5", "src_encoding": "UTF-8", "text": "#Python Includes\nimport math\nimport random\n#Custom Includes\nimport TSU\nimport mapsheet\nimport Vector\nimport pathfinding\nimport JKDefs\nimport game\n#Global Sprites\nglobal AISprite\nclass Boid:\n\tdef __init__(self, Position):\n\t\tself.imageName = \"./images/AISprite.png\"\n\n\t\tself.Mass = 32\n\t\tself.MaxForce = 0.6\n\t\tself.MaxSpeed = 1\n\t\tself.MaxVelocity = 10\n\n\t\tself.MaxAvoid = 32\n\t\tself.AvoidForce = 5\n\n\t\tself.Force = 0\n\t\tself.Rotation = 0\n\n\t\tself.CircleDistance = 8\n\t\tself.CircleRadius = 16\n\t\tself.angleChange = 0.95\n\t\tself.wanderAngle = random.randint(-5,5)\n\t\t\n\t\t\n\t\tif(isinstance(Position, Vector.Vector)):\n\t\t\tself.Position = Position\n\t\telse:\n\t\t\tself.Position = Vector.Vector(400,400)\n\n\t\tself.Velocity = Vector.Vector(0, 0)\n\t\tself.Desired = Vector.Vector(0,0)\n\t\tself.Steering = Vector.Vector(0,0)\n\t\tself.Target = Vector.Vector(0,0)\n\t\tself.Avoid = Vector.Vector(0,0)\n\n\tdef __repr__(self):\n\t\treturn '%s %s' % (self.x,self.y)\n\n\tdef Seek(self,Target):\n\n\t\tself.Target = Target\n\t\tself.Rotation = math.atan2((self.Position.x - Target.x),(self.Position.y - Target.y))\n\n\t\tself.Desired = (self.Target - self.Position)\n\t\tself.Desired.Norm()\n\n\t\tself.Desired = self.Desired * self.MaxVelocity\n\t\tself.Steering = self.Desired - self.Velocity \n\n\tdef Flee(self, Target):\n\n\t\tself.Target = Target \n\t\tself.Rotation = math.atan2((Target.x - self.Position.x),(Target.y - self.Position.y))\n\n\t\tself.Desired = (self.Position - self.Target)\n\t\tself.Desired.Norm()\n\n\t\tself.Desired = self.Desired * self.MaxVelocity\n\t\tself.Steering = self.Desired - self.Velocity \n\n\tdef Wander(self):\n\n\t\twanderTarget = self.Velocity\n\t\twanderTarget.Norm()\n\t\tself.Target = self.Position + wanderTarget \n\t\tself.Rotation = math.atan2((self.Position.x - self.Target.x),(self.Position.y - self.Target.y))\n\n\t\tcircCenter = self.Velocity \n\t\t#print self.Velocity\n\t\tcircCenter.Norm()\n\t\tcircCenter = circCenter * self.CircleDistance\n\n\t\tcircleDisplace = Vector.Vector(1,1)\n\t\tcircleDisplace = circleDisplace * self.CircleRadius\n\n\t\t#Set The Angle \n\t\tlen = circleDisplace.Magnitude()\n\t\tcircleDisplace.x = math.cos(self.wanderAngle) * len * 0.1\n\t\tcircleDisplace.y = math.sin(self.wanderAngle) * len * 0.1\n\t\t\n\t\trandomNum = random.random() \n\t\n\t\tself.wanderAngle = self.wanderAngle + randomNum * self.angleChange - self.angleChange * 0.5\n\t\tself.Steering = circCenter + circleDisplace\n\n\tdef Arrive(self, Target):\n\t\tTarget = self.Target \n\t\tslowArea = 256\n\n\t\tself.Desired = (Target - self.Position)\n\n\t\tDistance = self.Desired.Magnitude()\n\t\tif (Distance <= slowArea):\n\t\t\tself.Desired.Norm() \n\t\t\tself.Desired = self.Desired * self.MaxVelocity * Distance / slowArea\n\t\telse:\n\t\t\tself.Desired.Norm() \n\t\t\tself.Desired = self.Desired * self.MaxVelocity\n\n\t\tself.Steering = self.Desired - self.Velocity\n\n\tdef Update(self, LevelMap):\n\t\tmouseX, mouseY = TSU.GetMouseLocation()\n\t\t\n\t\t#self.Seek(Vector.Vector(mouseX, mouseY))\n\t\t#self.Flee(Vector.Vector(mouseX, mouseY))\n\t\tself.obstacleAvoidance(LevelMap.getWallList())\n\n\t\tself.Steering = MaxTruncate(self.Steering + self.Avoid, self.MaxForce)\n\t\tself.Steering = self.Steering / self.Mass \n\t\tself.Velocity = MinTruncate(self.Velocity + self.Steering, self.MaxSpeed)\n\t\tself.Position = self.Position + self.Velocity \n\n\t\t#if(self.Position.x < 0):\n\t\t#\t-self.Velocity \n\t\t#\t-self.Steering \n\t\t#if(self.Position.x > game.gameSize['width']):\n\t\t#\t-self.Velocity\n\t\t#\t-self.Steering \n\t\t#if(self.Position.y < 0):\n\t\t#\t-self.Velocity\n\t\t#\t-self.Steering \n\t\t#if(self.Position.y > game.gameSize['height']):\n\t\t#\t-self.Velocity\n\t\t#\t-self.Steering \n\n\n\tdef loadSprites(self):\n\t\tglobal AISprite\n\t\tAISprite = TSU.CreateSprite(self.imageName, 32 , 32, True) \n\t\t\n\tdef Draw(self): \n\t\tTSU.MoveSprite(AISprite,self.Position.x,self.Position.y)\n\t\tTSU.RotateSprite(AISprite,self.Rotation)\n\t\tTSU.UpdateSprite(AISprite)\n\t\tTSU.DrawSprite(AISprite)\n\n\tdef cleanUp(self):\n\t\tTSU.DestroySprite(AISprite)\n\n\tdef obstacleAvoidance(self, Obstacles):\n\t\t\n\t\t#print Obstacles\n\n\t\ttempVec = self.Velocity \n\t\ttempVec.Norm()\n\t\ttempVec = tempVec * self.MaxAvoid\n\n\t\tdistanceAhead = self.Position + tempVec\n\t\tmostThreatening = None\n\n\t\tfor i in range(len(Obstacles)):\n\t\t\tobstacle = Obstacles[i]\n\t\t\tif(self.Position.Distance(obstacle.position) < 128 ):\n\t\t\t\tcoll = self.lineIntersection(self.Position, distanceAhead, obstacle)\n\t\t\t\tif(coll and ((mostThreatening is None) or (self.Position.Distance(obstacle.position) < self.Position.Distance(mostThreatening.position)))):\n\t\t\t\t\tmostThreatening = obstacle\n\t\tif (mostThreatening is not None):\n\t\t\tself.Avoid = distanceAhead - mostThreatening.position\n\t\t\tself.Avoid.Norm()\n\t\t\tself.Avoid = self.Avoid * self.AvoidForce\n\t\telse:\n\t\t\tself.Wander()\n\n\n\tdef lineIntersection(self, position, ahead, Obstacle):\n\t\ttempVec = self.Velocity\n\t\ttempVec.Norm()\n\t\ttempVec = tempVec * self.MaxAvoid * 0.75\n\n\t\tahead2 = self.Position + tempVec\n\t\tnum = 64\n\t\tfor t in range(num)[::3]:\n\t\t\tpie1 = 2 * math.pi * t/num\n\t\t\tpie2 = 2 * math.pi * (t+1)/num\n\t\t\tVec1 = Vector.Vector(num * math.cos(pie1), num * math.sin(pie1))\n\t\t\tVec2 = Vector.Vector(num * math.cos(pie2), num * math.sin(pie2))\n\t\treturn (Obstacle.position.Distance(ahead) <= num) or (Obstacle.position.Distance(ahead2) <= num)\n\n\ndef MaxTruncate(aVector, Max):\n\t\n\ti = Max / aVector.Magnitude()\n\tif (i<1.0):\n\t\ti=1.0 \n\telse:\n\t\ti=1/i\n\taVector = aVector * i \n\treturn aVector\n\ndef MinTruncate(aVector, Min):\n\ti = aVector.Magnitude() / Min\n\tif(i<1.0):\n\t\ti=1.0 \n\taVector = aVector * i \n\treturn aVector\n\n\nclass Flock:\n\tdef __init__(self, boidCount):\n\t\tself.Boids = []\n\t\tfor i in range (boidCount):\n\t\t\txPos = game.gameSize['width'] * random.uniform(0.4, 0.6)\n\t\t\tyPos = game.gameSize['height'] * random.uniform(0.4, 0.6)\n\t\t\tself.Boids.append(Boid(Vector.Vector(xPos, yPos)))\n\t\t\tself.Boids[i].loadSprites()\n\tdef Update(self, LevelMap): \n\t\tfor i in range(len(self.Boids)):\n\t\t\taliBoid = self.Alignment(self.Boids[i])\n\t\t\tcohBoid = self.Cohesion(self.Boids[i])\n\t\t\tsepBoid = self.Seperation(self.Boids[i])\n\t\t\tself.Boids[i].Velocity = Vector.Vector(0,0)\n\t\t\tself.Boids[i].Velocity = self.Boids[i].Velocity + aliBoid + cohBoid + sepBoid\n\n\t\t\tif(self.Boids[i].Velocity.Magnitude() > self.Boids[i].MaxVelocity):\n\t\t\t\tself.Boids[i].Velocity.Norm()\n\n\t\t\t#print \"sepBoid\", cohBoid\n\t\t\tself.Boids[i].Update(LevelMap)\n\t\t\tself.Boids[i].Draw()\n\t\t\t\n\tdef Alignment(self, Boid):\n\t\tneighbourCount = 0\n\t\ttempVec = Vector.Vector(0,0)\n\t\tfor i in range (len(self.Boids)):\n\t\t\tif self.Boids[i] != Boid:\n\t\t\t\tif ((self.Boids[i].Position - Boid.Position).Magnitude() < 300):\n\t\t\t\t\ttempVec = tempVec + self.Boids[i].Velocity\n\t\t\t\t\tneighbourCount += 1\n\n\t\tif neighbourCount == 0:\n\t\t\treturn tempVec\n\t\t#print \"Ali - neighbourCount\", neighbourCount\n\t\ttempVec = tempVec / neighbourCount\n\t\ttempVec.Norm()\n\t\treturn tempVec\n\t \n\tdef Cohesion(self, Boid):\n\t\ttempVec = Vector.Vector(0,0)\n\t\tneighbourCount = 0\n\t\tfor i in range (len(self.Boids)):\n\t\t\tif self.Boids[i] != Boid:\n\t\t\t\tif ((self.Boids[i].Position - Boid.Position).Magnitude() < 300):\n\t\t\t\t\ttempVec = tempVec + self.Boids[i].Position\n\t\t\t\t\tneighbourCount += 1\n\n\t\tif neighbourCount == 0:\n\t\t\treturn tempVec\n\t\t#print \"Cho - neighbourCount\", neighbourCount\n\t\ttempVec = tempVec / neighbourCount\n\t\ttempVec = Vector.Vector(tempVec.x - Boid.Position.x, tempVec.y - Boid.Position.y)\n\t\ttempVec.Norm()\n\t\treturn tempVec\n\n\tdef Seperation(self, Boid):\n\t\ttempVec = Vector.Vector(0,0)\n\t\tneighbourCount = 0\n\t\tfor i in range (len(self.Boids)):\n\t\t\tif self.Boids[i] != Boid:\n\t\t\t\tif ((self.Boids[i].Position - Boid.Position).Magnitude() < 500):\n\t\t\t\t\ttempVec = tempVec + self.Boids[i].Position - Boid.Position\n\t\t\t\t\tneighbourCount += 1\n\n\t\tif neighbourCount == 0:\n\t\t\treturn tempVec\n\t\t#print \"Sep - neighbourCount\", neighbourCount\n\t\ttempVec = tempVec / neighbourCount\n\t\t-tempVec \n\t\ttempVec.Norm()\n\t\t#print \"Velocity\", tempVec\n\t\treturn tempVec\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" } ]
11
SBelkaid/webApp
https://github.com/SBelkaid/webApp
7faa01b6891bbb425f1a55afc0242369a91a8d6d
d08d0855fea6c5125cd25a4f275c8b635ffc1a86
33d839719d47b404fbf2aef37359e8891346f0c5
refs/heads/master
2021-01-21T16:45:04.839353
2017-05-20T17:06:13
2017-05-20T17:06:13
91,903,883
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7552447319030762, "alphanum_fraction": 0.7552447319030762, "avg_line_length": 21.076923370361328, "blob_id": "19059633594c100fb83c72a7def0c29b9c7e7d7b", "content_id": "8117dd5ceb2105767727f866af4a4381deb10081", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 286, "license_type": "no_license", "max_line_length": 39, "num_lines": 13, "path": "/user_shema.sql", "repo_name": "SBelkaid/webApp", "src_encoding": "UTF-8", "text": "drop table if exists entries;\ncreate table User (\n id integer primary key autoincrement,\n username text not null,\n password float not null\n);\n\ndrop table if exists entries;\ncreate table Role (\n id integer primary key autoincrement,\n username text not null,\n role float not null\n);" }, { "alpha_fraction": 0.7415730357170105, "alphanum_fraction": 0.7415730357170105, "avg_line_length": 20.238094329833984, "blob_id": "0ab7cb2ab88f1c153748b6b504e4285f6b840478", "content_id": "80904333f99a0fb1d67d5fe226715055d5d486c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 445, "license_type": "no_license", "max_line_length": 39, "num_lines": 21, "path": "/webApp/schema.sql", "repo_name": "SBelkaid/webApp", "src_encoding": "UTF-8", "text": "drop table if exists Entries;\ncreate table entries (\n id integer primary key autoincrement,\n title text not null,\n price float not null,\n 'text' text not null\n);\n\ndrop table if exists User;\ncreate table user (\n id integer primary key autoincrement,\n username text not null,\n password text not null\n);\n\ndrop table if exists Role;\ncreate table role (\n id integer primary key autoincrement,\n username text not null,\n role text not null\n);" }, { "alpha_fraction": 0.7170731425285339, "alphanum_fraction": 0.7170731425285339, "avg_line_length": 24.625, "blob_id": "efc1a51cf4fad6d7b41ea1b7ec3818c00a3df814", "content_id": "b6307e1e6e3c5bcc8a5ff6d068c4cdbfbfb6ffe0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 205, "license_type": "no_license", "max_line_length": 48, "num_lines": 8, "path": "/webApp/views/profile.py", "repo_name": "SBelkaid/webApp", "src_encoding": "UTF-8", "text": "from flask import Blueprint, render_template\n\nprofile = Blueprint('profile', __name__)\n\n@profile.route('profile/hello')\ndef timeline():\n # Do some stuff\n return render_template('profile/hello.html')\n" }, { "alpha_fraction": 0.6284342408180237, "alphanum_fraction": 0.6316351294517517, "avg_line_length": 24.678081512451172, "blob_id": "9c4c51f6ddb6a98db8b2aea34c83a0bb87083ae5", "content_id": "ef574498d88bb5e4be3e6549a09e95a5411e9b9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3749, "license_type": "no_license", "max_line_length": 98, "num_lines": 146, "path": "/webApp/app.py", "repo_name": "SBelkaid/webApp", "src_encoding": "UTF-8", "text": "from flask import Flask\nfrom flask import request\nfrom flask import redirect\nfrom flask import render_template\nfrom flask import session\nfrom flask import g, url_for, abort, flash\nfrom werkzeug.security import generate_password_hash, check_password_hash\nimport sqlite3, os, click\n\napp = Flask(__name__, instance_path='/Users/johndoe/Programming/Python/flask-web/webApp/instance')\napp.config.from_object(__name__) # load config from this file , flaskr.py\n\n# Load default config and override config from an environment variable\napp.config.update(dict(\n DATABASE=os.path.join(app.root_path, 'app.db'),\n SECRET_KEY='Meikah5aiyai2iez1Uw0',\n USERNAME='admin',\n PASSWORD='default'\n))\napp.config.from_envvar('FLASKR_SETTINGS', silent=True)\n\n\n\nclass User(object):\n def __init__(self, username, password):\n self.username = username\n self.password = self.hash_pass(password)\n\n\n def hash_pass(self, passw):\n return generate_password_hash(passw, method='pbkdf2:sha1', salt_length=8)\n\n\n def check_pass(self, passw):\n return check_password_hash(self.password, passw)\n\n\n def store_user(self):\n conn = get_db()\n c = conn.cursor()\n query = 'INSERT INTO user (username, password) VALUES (?,?)'\n c.execute(query, [self.username, self.password])\n conn.commit()\n\n\ndef connect_db():\n \"\"\"Connecting DB\"\"\"\n conn = sqlite3.connect(app.config['DATABASE'])\n conn.row_factory = sqlite3.Row\n return conn\n\n\ndef get_db():\n \"\"\"Opens a new databse connection if there's none\n yet for the current application app_context\n \"\"\"\n if not hasattr(g,'sqlite_db'):\n g.sqlite_db=connect_db()\n return g.sqlite_db\n\n\ndef init_db():\n db = get_db()\n with app.open_resource('schema.sql', mode='r') as f:\n db.cursor().executescript(f.read())\n db.commit()\n\n\n@app.cli.command('showentries')\ndef show_all():\n \"\"\"\n Show all entries in db\n \"\"\"\n command = 'select * from entries'\n c = get_db()\n print c.execute(command).fetchall()\n\n\n@app.cli.command('initdb')\ndef initdb_command():\n \"\"\"Initilize db\"\"\"\n init_db()\n print 'Initialized db'\n\n\n@app.teardown_appcontext\ndef close_db(error):\n \"\"\"Close db connection at end of request\"\"\"\n if hasattr(g, 'sqlite_db'):\n g.sqlite_db.close()\n\n\n@app.route('/')\ndef show_entries():\n db = get_db()\n cur = db.execute('select * from entries')\n entries = cur.fetchall()\n return render_template('show_entries.html', entries=entries)\n\n\n@app.route('/user/<name>')\ndef user(name):\n return 'Hello %s' % name\n\n\n@app.route('/logout')\ndef logout():\n session.pop('logged_in', None)\n flash('You were logged out')\n return redirect(url_for('show_entries'))\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n error = None\n if request.method == 'POST':\n if request.form['username'] != app.config['USERNAME']:\n error = 'Invalid username'\n elif request.form['password'] != app.config['PASSWORD']:\n error = 'Invalid password'\n else:\n session['logged_in'] = True\n flash('You were logged in')\n return redirect(url_for('show_entries'))\n return render_template('login.html', error=error)\n\n\n@app.route('/add', methods=['POST'])\ndef add_entry():\n if not session.get('logged_in'):\n abort(401)\n db = get_db()\n db.execute('insert into entries (title, text, price) values (?, ?, ?)',\n [request.form['title'], request.form['text'], int(100)])\n db.commit()\n flash('New entry was successfully posted')\n return redirect(url_for('show_entries'))\n\n\n@app.route('/redirect')\ndef redirect_me():\n return redirect('http://www.example.com')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n" } ]
4
Balu-Varanasi/minimal-django-tutorial
https://github.com/Balu-Varanasi/minimal-django-tutorial
5d41207cdc6b78e2b26cbc8c565084cbcbccd17d
b523d862fa0f2bc139802ed0ad97c9db1e084519
3ec52e3d8dd02ba3b7e1aa822574e36610ff8c89
refs/heads/master
2021-01-13T03:55:07.705586
2017-01-06T11:25:30
2017-01-06T11:25:30
78,200,257
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6543437838554382, "alphanum_fraction": 0.6580406427383423, "avg_line_length": 19.037036895751953, "blob_id": "ada6f598832d9c2fe765a51aa98b5f6349befa54", "content_id": "ed31e36b956e504bd1e8d37c5794b4168c677200", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 541, "license_type": "no_license", "max_line_length": 60, "num_lines": 27, "path": "/minimal.py", "repo_name": "Balu-Varanasi/minimal-django-tutorial", "src_encoding": "UTF-8", "text": "import sys\n\nfrom django.conf import settings\nfrom django.conf.urls import url\nfrom django.core.management import execute_from_command_line\n\nfrom django.http import HttpResponse\n\nsettings.configure(\n DATABASES={\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'mydatabase.sqlite3',\n }\n },\n DEBUG=True,\n ROOT_URLCONF=sys.modules[__name__],\n)\n\n\ndef index(request):\n return HttpResponse(\"Hello, World!\")\n\n\nurlpatterns = [url('^$', index), ]\n\nexecute_from_command_line(sys.argv)\n" } ]
1
gulbing/HacktoberFest2018
https://github.com/gulbing/HacktoberFest2018
0e6ed1216e1c0b7af1fb02162e6fb3b384a35046
ae5d52d1748a3cb5e22e60ac1a743e531e57d1ee
8947d35296589091aba8ac6c9e0467d6ceccb12b
refs/heads/master
2020-08-26T13:04:30.528446
2019-10-23T09:39:38
2019-10-23T09:39:38
154,817,351
0
0
null
2018-10-26T10:24:40
2018-10-28T14:25:49
2019-10-23T09:25:26
Java
[ { "alpha_fraction": 0.7159624695777893, "alphanum_fraction": 0.7605633735656738, "avg_line_length": 29.35714340209961, "blob_id": "d78ba980d7d5185a80474ed042af81c4e6a3317c", "content_id": "b8d3d9a44998533c597ccf807b9e283f4597205e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 445, "license_type": "no_license", "max_line_length": 49, "num_lines": 14, "path": "/Python/Litre Dönüştürücü.py", "repo_name": "gulbing/HacktoberFest2018", "src_encoding": "UTF-8", "text": "\n#GÖREV: Baş bırakılan yerleri doldurunuz:\n#Girdileri alıyoruz:\nkenar1 = int(input(\"1.kenarı\"1.kenarı giriniz:\"))\nkenar2 = int(input(\"2.kenarı\"2.kenarı giriniz:\"))\nkenar3 = int(input(\"3.kenarı\"3.kenarı giriniz:\"))\n\n#Prizmanın hacmini cm^3 cinsinden giriniz:\nhacimCM3 = kenar1*kenar2*kenar3\n\n#Prizmanın hacmini litre cinsinden heaplıyoruz:\nhacimL = hacimCM3*1000\n\n#Çıktıyı alıyoruz:\nprint(\"Litre cinsinden hacmimiz: \", hacimL)\n" } ]
1
hjian42/Geo-Twitter2019
https://github.com/hjian42/Geo-Twitter2019
88f7731752bfda55fef1c0c447c246949dfd2bf2
9d99e9294e68f39006ff0cd4d9bd2beb9cd808ec
b525ddfe6327ef2f8336c9bbe2ba3985c8da99b8
refs/heads/master
2020-05-15T11:17:54.357459
2019-10-03T09:42:27
2019-10-03T09:42:27
182,220,595
2
2
null
null
null
null
null
[ { "alpha_fraction": 0.6055966019630432, "alphanum_fraction": 0.6393875479698181, "avg_line_length": 27.378787994384766, "blob_id": "b000be6997101217c58f52484afb30e207a73b2b", "content_id": "e71688c3f3d9d624465a85f7b1a7914a39fcb5aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1894, "license_type": "no_license", "max_line_length": 67, "num_lines": 66, "path": "/preprocessing/merge_files.py", "repo_name": "hjian42/Geo-Twitter2019", "src_encoding": "UTF-8", "text": "import json\n\ncountries = ['UK', 'USA']\n\ndef merge_jsons():\n\tfor c in countries:\n\t\ti = 0\n\t\tfile_main = '../tweets2019/{}-no-filter.json'.format(c)\n\t\tfile_added = '../tweets2019/{}.json'.format(c)\n\t\twith open(file_main, 'a') as f_main, open(file_added) as f_added:\n\t\t\tfor line in f_added:\n\t\t\t\tf_main.write(line)\n\t\t\t\ti += 1\n\t\t\tprint(\"{}:\\tNum of Tweets Appended:\\t\".format(c), str(i))\n\n# Append Statistics\n# AUS:\tNum of Tweets Appended:\t 7140\n# UK:\tNum of Tweets Appended:\t 143800\n# USA:\tNum of Tweets Appended:\t 572500\n\ndef merge_txts():\n\tf_main = open('../tweets2019/dialects3.txt', 'w')\n\ti = 0\n\tfor c in countries:\n\t\tfile_added = '../tweets2019/{}.txt'.format(c)\n\t\twith open(file_added) as f_added:\n\t\t\tfor line in f_added:\n\t\t\t\tf_main.write(line)\n\t\t\t\ti += 1\n\t\tprint(\"{} added new tweets, in total:\\t\".format(c), str(i))\n\tf_main.close()\n\n# merge_txts()\n# merging txt files\n# AUS added new tweets, in total:\t 58108\n# UK added new tweets, in total:\t 616166\n# USA added new tweets, in total:\t 2827618\n\ndef count_stats():\n\tmain_tweet_count = 0\n\tmain_token_count = 0\n\tmain_term_set = set()\n\tfor c in countries:\n\t\ttweet_count = 0\n\t\ttoken_count = 0\n\t\tterm_set = set()\n\t\tfile_added = '../tweets2019/{}_tokenized.txt'.format(c)\n\t\twith open(file_added) as f_added:\n\t\t\tfor line in f_added:\n\t\t\t\ttokens = line.split()\n\t\t\t\ttweet_count += 1\n\t\t\t\ttoken_count += len(tokens)\n\t\t\t\t[term_set.add(token) for token in tokens]\n\t\t\t\t[main_term_set.add(token) for token in tokens]\n\t\tprint(\"{} added new tweets\".format(c))\n\t\tprint(\"{} tweets\".format(tweet_count))\n\t\tprint(\"{} tokens\".format(token_count))\n\t\tprint(\"{} terms\".format(len(term_set)))\n\t\tmain_tweet_count += tweet_count\n\t\tmain_token_count += token_count\n\tprint('\\n')\n\tprint(\"TOTAL\\t {} tweets\".format(main_tweet_count))\n\tprint(\"TOTAL\\t {} tokens\".format(main_token_count))\n\tprint(\"TOTAL\\t {} terms\".format(len(main_term_set)))\n\ncount_stats()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5141700506210327, "alphanum_fraction": 0.6497975587844849, "avg_line_length": 27.941177368164062, "blob_id": "c46939208ca84f6dcc85bffa34a4acd4fab9d9cc", "content_id": "861ae7f488f2929a5278014cb416e1beae543da7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 988, "license_type": "no_license", "max_line_length": 83, "num_lines": 34, "path": "/preprocessing/remove_duplicate.py", "repo_name": "hjian42/Geo-Twitter2019", "src_encoding": "UTF-8", "text": "\n\ncountry = \"UK\"\ndatafile = \"../tweets2019/{}_tokenized.txt\".format(country)\noutputfile = \"../tweets2019/{}_uniq_tokenized.txt\".format(country)\n\ntext_set = set()\ntext_num = 0\nwith open(datafile, encoding = \"utf-8\") as f, open(outputfile, 'w') as out:\n for line in f:\n parts = line.split(\"\\t\")\n if len(parts) != 6:\n print('Invalid tweets')\n continue\n username, dt, _xy, x, y, text = parts\n # hash_str = username + text\n if text not in text_set:\n\t out.write('\\t'.join([username, dt, _xy, x, y, text]))\n\t out.write('\\n')\n\n text_set.add(text)\n text_num += 1\n\nprint(len(text_set), 'out of', text_num, 'unique %:', len(text_set)/text_num * 100)\n\n# for UK.txt and USA.txt\n# UK unique percentage\n# 1008723 1088232 92.69374545133758%\n# USA unique percentage\n# 2025164 2075394 97.57973666686904%\n\n# for UK_tokenized.txt and USA_tokenized.txt\n# USA\n# 1883153 out of 2075394 unique %: 90.73713232282641\n# UK\n# 941472 out of 1088232 unique %: 86.51390512317226\n\n\n" }, { "alpha_fraction": 0.5706357359886169, "alphanum_fraction": 0.6069626808166504, "avg_line_length": 32.423728942871094, "blob_id": "d3e27c9786817fa89d3f6fa5fc7cf7288917f2a4", "content_id": "e9fcdbd8c8fa657e2a76d539563d3d84296a6912", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1982, "license_type": "no_license", "max_line_length": 164, "num_lines": 59, "path": "/preprocessing/preprocess_tokenize.py", "repo_name": "hjian42/Geo-Twitter2019", "src_encoding": "UTF-8", "text": "from __future__ import with_statement\nfrom collections import defaultdict\nimport os,sys\nimport twokenize\nimport nltk\nimport re\n\ncountry = 'USA'\nword_count = defaultdict(int)\n\ndef clean_tweets(text):\n text = re.sub(r'&[a-z]{3};', ' <sym> ', text) # '&amp;'\n text = re.sub(r'&gt;', '>', text)\n text = re.sub(r'&lt;', '<', text) \n text = re.sub(r'@\\w+', ' <user> ', text)\n ENCODE_EMOJI = re.compile(u'([\\U00010000-\\U0010ffff])|([\\U00002600-\\U000027BF])|([\\U0001f300-\\U0001f64F])|([\\U0001f680-\\U0001f6FF])', flags=re.UNICODE) # emoji\n text = ENCODE_EMOJI.sub(r'', text)\n text = re.sub(' +', ' ', text)\n \n return text.strip().lower()\n\ndef get_tokens(text):\n toks = twokenize.tokenize(text.lower())\n toks = [t for t in toks if not t.startswith('@') and t != 'rt' ]\n # toks = [t.replace(\"#\",\"\") for t in toks]\n return toks\n\ndef get_pos_tokens(text):\n pos_tokens = nltk.pos_tag(nltk.word_tokenize(text))\n return [\"_\".join(pair) for pair in pos_tokens]\n\n\ndatafile = \"../tweets2019/{}.txt\".format(country)\noutputfile = \"../tweets2019/{}_tokenized.txt\".format(country)\npos_outputfile = \"../tweets2019/{}_tok_pos.txt\".format(country)\n\nwith open(datafile, encoding = \"utf-8\") as f, open(outputfile, 'w') as out, open(pos_outputfile, 'w') as out1:\n for line in f:\n parts = line.split(\"\\t\")\n if len(parts) != 6:\n print('Invalid tweets')\n continue\n username, dt, _xy, x, y, text = parts\n tok_text = \" \".join(get_tokens(text))\n clean_text = clean_tweets(tok_text)\n out.write('\\t'.join([username, dt, _xy, x, y, clean_text]))\n out.write('\\n')\n\n\nwith open(outputfile, encoding = \"utf-8\") as f, open(pos_outputfile, 'w') as out1:\n for line in f:\n parts = line.split(\"\\t\")\n if len(parts) != 6:\n print('Invalid tweets')\n continue\n username, dt, _xy, x, y, text = parts\n tok_pos_text = \" \".join(get_pos_tokens(text))\n out1.write('\\t'.join([username, dt, _xy, x, y, tok_pos_text]))\n out1.write('\\n')\n\n\n\n\n\n\n\n\n " }, { "alpha_fraction": 0.5680271983146667, "alphanum_fraction": 0.5782312750816345, "avg_line_length": 25.81818199157715, "blob_id": "e206cd09350cc81edd18b618fb5d14586a38d034", "content_id": "44ad4fc27e67221ef033b95ff6db9098fa93cce7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 294, "license_type": "no_license", "max_line_length": 66, "num_lines": 11, "path": "/data_collection/test.py", "repo_name": "hjian42/Geo-Twitter2019", "src_encoding": "UTF-8", "text": "from crawl import *\nimport json\ni = 0\nwith open('UK.json') as f:\n\tprint('------------------')\n\tfor line in f:\n\t\t# data = json.loads(line)\n\t\t# if not has_url(data['text']) and is_normal_user(data['user']):\n\t\t# \tprint(json.dumps(data['text'], indent=4))\n\t\ti += 1\nprint(\"Num of Tweets:\\t\", str(i))" }, { "alpha_fraction": 0.6861667633056641, "alphanum_fraction": 0.7365869283676147, "avg_line_length": 57.1698112487793, "blob_id": "a50016b5aad18faaead8829d28a4b6f589595eb2", "content_id": "ffd95686870a9108ea172d3904f96d7e3cf09799", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3094, "license_type": "no_license", "max_line_length": 326, "num_lines": 53, "path": "/README.md", "repo_name": "hjian42/Geo-Twitter2019", "src_encoding": "UTF-8", "text": "# Geo-Twitter2019\n\n## Description\n\nIn this project, we use a novel non-parametric skip-gram model to capture the dialectal changes of English on multiple resolutions. This repository contains the tweets ids we used for training the model. You are free to crawl the data using these ids and preprocess the data using our tools to replicate our research results. \n\n## Dataset\n\n| Number \t| USA \t| UK \t| Total \t|\n|--------\t|------------\t|------------\t|------------\t|\n| tweet \t| 2,075,394 \t| 1,088,232 \t| 3,163,626 \t|\n| token \t| 41,637,107 \t| 22,012,953 \t| 63,650,060 \t|\n| term \t| 865,784 \t| 469,570 \t| 1,167,790 \t|\n\nnote: CMU geo data only contain 378K tweets\n\n### Model\n\nTo use our model implementation, you should visit the github page [DialectGram](https://github.com/yuxingch/DialectGram). There are four models in the github repository:\n - baseline models: frequency model and syntactic model\n - GEODIST model: region-specific embeddings\n - DialectGram model: a novel approach to compose dialect-sensitive word embeddings, based on Adaptive Skip-gram.\n\n### Demo\n\nYou can play with our demo on the website: [demo](https://hjian42.github.io/Geo-Twitter2019/demo/main.html)\n\n \n### Acknowledgement\n\nWe would like to acknowledge the following resources when we implement our models:\n\n1. [Eisenstein, Jacob, et al. \"A latent variable model for geographic lexical variation.\" Proceedings of the 2010 conference on empirical methods in natural language processing. Association for Computational Linguistics, 2010.](http://www.cs.cmu.edu/~nasmith/papers/eisenstein+oconnor+smith+xing.emnlp10.pdf)\n2. [Bartunov, Sergey, et al. \"Breaking sticks and ambiguities with adaptive skip-gram.\" Artificial Intelligence and Statistics. 2016.](https://arxiv.org/pdf/1502.07257.pdf)\n3. [Bamman, David, Chris Dyer, and Noah A. Smith. \"Distributed representations of geographically situated language.\" Proceedings of the 52nd Annual Meeting of the Association for Computational Linguistics (Volume 2: Short Papers). 2014.](http://acl2014.org/acl2014/P14-2/pdf/P14-2134.pdf)\n4. [Kulkarni, Vivek, Bryan Perozzi, and Steven Skiena. \"Freshman or fresher? quantifying the geographic variation of internet language.\" arXiv preprint arXiv:1510.06786 (2015).](https://arxiv.org/pdf/1510.06786.pdf)\n5. [Python Implementation of AdaGram](https://github.com/lopuhin/python-adagram)\n6. [Julia Implementation of AdaGram](https://github.com/sbos/AdaGram.jl)\n\n\n## Citation\nJiang, Hang*; Haoshen Hong*; Yuxing Chen*; and Vivek Kulkarni. 2019. DialectGram: Automatic Detection of Dialectal Changes with Multi-geographic Resolution Analysis. To appear in *Proceedings of the Society for Computation in Linguistics*. New Orleans: Linguistic Society of America. \n\n```\n@inproceedings{Jiang:Hong:Chen:2020:SCiL,\n Author = {Jiang, Hang and Hong, Haoshen and Chen, Yuxing and Kulkarni, Vivek},\n Title = {DialectGram: Automatic Detection of Dialectal Changes with Multi-geographic Resolution Analysis},\n Booktitle = {Proceedings of the Society for Computation in Linguistics},\n Location = {New Orleans},\n Publisher = {Linguistic Society of America},\n Address = {Washington, D.C.},\n Year = {2020}}\n```\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5299500823020935, "alphanum_fraction": 0.5632279515266418, "avg_line_length": 28.268293380737305, "blob_id": "796ba03a37285a4a4f1180643582ef762aed5437", "content_id": "6bef5373c20c2d84c3fe49d2d420d5e624ccaa47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2404, "license_type": "no_license", "max_line_length": 91, "num_lines": 82, "path": "/data_collection/crawl.py", "repo_name": "hjian42/Geo-Twitter2019", "src_encoding": "UTF-8", "text": "import tweepy\nfrom tweepy import Stream\nfrom tweepy.streaming import StreamListener \nfrom tweepy import OAuthHandler\nimport json\nimport re\n\nLOCATION_UK = [-11.22,49.96,1.69,59.37]\nLOCATION_USA = [-130.16,25.58,-62.93,49.34] # no alaska\nLOCATION_AUS = [112.467, -55.05, 168, -9.133]\nLOCATION_INDIA = [67.93,7.82,89.2,35.66]\n\n@classmethod\ndef parse(cls, api, raw):\n status = cls.first_parse(api, raw)\n setattr(status, 'json', json.dumps(raw))\n return status\n\ndef has_url(text):\n if re.search(r'http', text):\n return True\n else:\n return False\n\ndef is_normal_user(user):\n\n if user['followers_count'] and user['followers_count'] < 1000:\n if user['friends_count'] and user['friends_count'] < 1000:\n return True\n\n return False\n\nclass MyListener(StreamListener):\n \n def on_data(self, data):\n global data_list\n try:\n if len(data_list) == 20:\n if data_list:\n with open('UK-no-filter.json', 'a') as f:\n print('Write ', NUM_OF_TWEETS['count'], 'tweets')\n for data in data_list:\n f.write(data)\n data_list = []\n else:\n data_json = json.loads(data)\n if not has_url(data_json['text']):\n data_list.append(data)\n NUM_OF_TWEETS['count'] += 1\n NUM_OF_TWEETS['seen'] += 1\n if NUM_OF_TWEETS['seen'] % 20 == 0:\n print('seen:\\t', NUM_OF_TWEETS['seen'], 'count:\\t', NUM_OF_TWEETS['count'])\n return True\n except BaseException as e:\n print(\"Error on_data: %s\" % str(e))\n return True\n \n def on_error(self, status):\n print(status)\n return True\n \n#filter the tweets\nif __name__ == '__main__':\n\n data_list = []\n NUM_OF_TWEETS = {'count': 0, 'seen': 0}\n\n access_token = \"\"\n access_secret = \"\"\n consumer_key = \"\"\n consumer_secret = \"\"\n\n auth = OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_secret)\n\n api = tweepy.API(auth)\n\n # Status() is the data model for a tweet\n tweepy.models.Status.first_parse = tweepy.models.Status.parse\n tweepy.models.Status.parse = parse\n twitter_stream = Stream(auth, MyListener())\n twitter_stream.filter(locations=LOCATION_UK, languages=[\"en\"])\n\n\n\n\n" }, { "alpha_fraction": 0.5899485945701599, "alphanum_fraction": 0.6230725049972534, "avg_line_length": 30.836362838745117, "blob_id": "f5ad25c44a862a084732185feae17ef95e2189aa", "content_id": "87725e2ec16867db92f88b76d34a56af572f9d70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1751, "license_type": "no_license", "max_line_length": 91, "num_lines": 55, "path": "/preprocessing/json2txt.py", "repo_name": "hjian42/Geo-Twitter2019", "src_encoding": "UTF-8", "text": "import json\n\ncountries = ['UK', 'USA']\n# countries = ['UK']\n\nfor c in countries:\n\ti = 0\n\tfile_main = '../tweets2019/{}-no-filter.json'.format(c)\n\tfile_out = '../tweets2019/{}.txt'.format(c)\n\twith open(file_main) as f_main, open(file_out, 'w') as f_out:\n\t\tfor line in f_main:\n\t\t\ttry:\n\t\t\t\ttweet_json = json.loads(line)\n\t\t\texcept ValueError:\n\t\t\t\tprint('Decoding JSON has failed')\n\t\t\t\tcontinue\n\t\t\ttweet_user = 'USER_' + tweet_json['user']['id_str']\n\t\t\ttweet_date = tweet_json['created_at']\n\t\t\tif tweet_json['place']:\n\t\t\t\ttweet_x = tweet_json['place']['bounding_box']['coordinates'][0][0][0]\n\t\t\t\ttweet_y = tweet_json['place']['bounding_box']['coordinates'][0][0][1]\n\t\t\t\ttweet_x, tweet_y = str(tweet_x), str(tweet_y)\n\t\t\telif tweet_json[\"coordinates\"]:\n\t\t\t\t# print(tweet_json[\"coordinates\"]['coordinates'])\n\t\t\t\ttweet_x = tweet_json['coordinates']['coordinates'][0]\n\t\t\t\ttweet_y = tweet_json['coordinates']['coordinates'][1]\n\t\t\t\ttweet_x, tweet_y = str(tweet_x), str(tweet_y)\n\t\t\telse:\n\t\t\t\t# print(tweet_json['user']['location'])\n\t\t\t\tprint('coordinates are NULL')\n\t\t\t\tcontinue\n\t\t\t# print(tweet_x, tweet_y)\n\t\t\ttweet_xy = ','.join([tweet_x, tweet_y])\n\t\t\ttweet_text = tweet_json['text'].strip()\n\t\t\ttweet_text = \" \".join(tweet_text.split())\n\t\t\tf_out.write('\\t'.join([tweet_user, tweet_date, tweet_xy, tweet_x, tweet_y, tweet_text]))\n\t\t\tf_out.write('\\n')\n\t\t\t# print(tweet_text)\n\t\t\ti += 1\n\t\t\t# if i == 5:\n\t\t\t# \tbreak\n\t\tprint(\"{}:\\tNum of Tweets in Total:\\t\".format(c), str(i))\n\t\t\n\n\n\n# raw: total statistics vs. CMU: 378K tweets\n# AUS:\tNum of Tweets Total:\t 52420\n# UK:\tNum of Tweets Total:\t 507920\n# USA:\tNum of Tweets Total:\t 2075395\n\n# after parsing\n# AUS:\tNum of Tweets in Total:\t 52420\n# UK:\tNum of Tweets in Total:\t 507792\n# USA:\tNum of Tweets in Total:\t 2075394\n" }, { "alpha_fraction": 0.4913013279438019, "alphanum_fraction": 0.5379262566566467, "avg_line_length": 34.07316970825195, "blob_id": "f7e46257c9da8d97d8e70e2c6caa68fec42caa57", "content_id": "aced50f96d57062a8cf8e8094cc458823def60de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1437, "license_type": "no_license", "max_line_length": 164, "num_lines": 41, "path": "/preprocessing/prepare_data_adagram.py", "repo_name": "hjian42/Geo-Twitter2019", "src_encoding": "UTF-8", "text": "import re\nfrom collections import defaultdict\n\ncountries = ['USA', 'UK']\n# concatenation of usa tweets + uk tweets\nout = open('../tweets2019/usa_uk.txt', 'w') \nword_count = defaultdict(int)\n\ndef clean_tweets(text):\n text = re.sub(r'&[a-z]{3};', ' <sym> ', text) # '&amp;'\n text = re.sub(r'&gt;', '>', text)\n text = re.sub(r'&lt;', '<', text) \n text = re.sub(r'@\\w+', ' <user> ', text)\n ENCODE_EMOJI = re.compile(u'([\\U00010000-\\U0010ffff])|([\\U00002600-\\U000027BF])|([\\U0001f300-\\U0001f64F])|([\\U0001f680-\\U0001f6FF])', flags=re.UNICODE) # emoji\n text = ENCODE_EMOJI.sub(r'', text)\n text = re.sub(' +', ' ', text)\n \n return text.strip().lower()\n\nfor country in countries:\n datafile = \"../tweets2019/{}_tokenized.txt\".format(country)\n with open(datafile, encoding = \"utf-8\") as f:\n for line in f:\n parts = line.split(\"\\t\")\n if len(parts) != 6:\n print('Invalid tweets')\n continue\n username, dt, _xy, x, y, text = parts\n clean_text = clean_tweets(text)\n for w in clean_text.split():\n if w:\n word_count[w] += 1\n # print(clean_text)\n out.write(clean_text)\n out.write('\\n')\nout.close()\n\nwith open(\"../tweets2019/usa_uk.dict\", 'w') as out:\n for w in word_count:\n print(w, word_count[w])\n out.write(\"\".join([w, '\\t', str(word_count[w]), '\\n']))" } ]
8
hbredin/pyannote-db-plumcot
https://github.com/hbredin/pyannote-db-plumcot
b9bacf62f79aa10af376ff9a5054fe5e469a414b
760fc88583e63b9c35ac2e055a9fe1cb47ef1bae
3bb35164e925159bd6b3a5ac0fa15184d10ccafb
refs/heads/develop
2023-01-03T02:25:00.920441
2019-03-14T08:11:12
2019-03-14T08:11:12
161,605,539
2
5
NOASSERTION
2018-12-13T08:11:24
2019-11-27T11:23:25
2020-06-21T05:05:53
Python
[ { "alpha_fraction": 0.5442314147949219, "alphanum_fraction": 0.5479313731193542, "avg_line_length": 27.586538314819336, "blob_id": "0b939e48ae00d46b978d181432c23ed1cbe597c4", "content_id": "4b1a459a9a5af8d61c6ec91521c4c61bf2bd6b4d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5946, "license_type": "permissive", "max_line_length": 79, "num_lines": 208, "path": "/scripts/characters.py", "repo_name": "hbredin/pyannote-db-plumcot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"Usage: characters.py SOURCEFILE [SERIES] [-v FILE]\n\nArguments:\n SOURCEFILE input series list file\n SERIES optionnal normalized name of a series\n\nOptions:\n -v FILE creates normalization verification for names in FILE\n\n\"\"\"\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport codecs # for encoding the data as utf-8\nimport unidecode\nimport re\nfrom docopt import docopt\n\n\ndef normalizeName(fullName):\n \"\"\"Normalizes characters and actors names.\n\n Removes parenthesis, commas, diacritics and non-alphanumerics characters,\n except _.\n\n Parameters\n ----------\n fullName : `str`\n Full name (of a character or a person).\n\n Returns\n -------\n normName : `str`\n Normalized name.\n \"\"\"\n\n fullName = fullName.lower()\n\n fullName = fullName.split('\\n')[0].strip()\n fullName = re.sub(r'\\([^()]*\\)', '', fullName) # Remove parenthesis\n fullName = re.sub(r\"\\'[^'']*\\'\", '', fullName) # Remove commas\n fullName = unidecode.unidecode(fullName) # Remove diacritics\n fullName = fullName.replace(' ', '_')\n # Remove all non-alphanumerics characters (except _)\n fullName = re.sub(r'\\W+', '', fullName)\n fullName = re.sub(r\"[_]+\", '_', fullName)\n return fullName\n\n\ndef scrapPage(pageIMDB):\n \"\"\"Extracts characters list of a series.\n\n Given an IMDB page, extracts characters information in this format:\n actor's normalized name, character's full name, actor's full name,\n IMDB.com character page.\n\n Parameters\n ----------\n pageIMDB : `str`\n IMDB page with the list of characters.\n\n Returns\n -------\n cast : `list`\n List with one tuple per character.\n \"\"\"\n urlIDMB = requests.get(pageIMDB).text\n soup = BeautifulSoup(urlIDMB, 'lxml')\n seriesTable = soup.find('table', {'class': 'cast_list'}).find_all('tr')\n\n cast = []\n\n for char in seriesTable:\n charInfo = char.find_all('td')\n if len(charInfo) == 4:\n actorName = charInfo[1].text.strip()\n\n charNorm = charInfo[3].find('a')\n charLink = \"\"\n if not charNorm:\n charName = charInfo[3].text.strip().split('\\n')[0].strip()\n elif charNorm.get('href') != \"#\":\n charName = charNorm.text.strip()\n charLink = \"https://www.imdb.com\" \\\n + charNorm.get('href').strip().split('?')[0]\n else:\n charName = charNorm.previous_sibling.strip()\\\n .split('\\n')[0].strip()\n\n normActorName = normalizeName(actorName)\n normCharName = normalizeName(charName)\n if normCharName and normActorName:\n cast.append((normCharName, normActorName, charName,\n actorName, charLink))\n\n return cast\n\n\ndef getData(pageIDMB):\n \"\"\"Extracts characters list of a series.\n\n Given an IMDB page, extracts characters information in this format:\n actor's normalized name, character's full name, actor's full name,\n IMDB.com character page, separated with commas.\n\n Parameters\n ----------\n pageIMDB : `str`\n IMDB page with the list of characters.\n\n Returns\n -------\n cast : `list`\n List with one string per character.\n \"\"\"\n\n textFile = []\n cast = scrapPage(pageIDMB)\n\n for normCharName, normActorName, charName, actorName, charLink in cast:\n text = normCharName + ',' + normActorName + ',' + charName + ',' + \\\n actorName + ',' + charLink + '\\n'\n text = text.encode('utf-8')\n textWrite = text.decode('utf-8')\n textFile.append(textWrite)\n\n return textFile\n\n\ndef writeData(series, data):\n \"\"\"Writes characters information in `characters.txt`.\n\n Parameters\n ----------\n series : `str`\n Folder of the series.\n data : `str`\n Data to write.\n \"\"\"\n\n with codecs.open(\"data/\"+series+\"/characters.txt\", \"w\", \"utf-8\") as chars:\n chars.write(data)\n\n\ndef verifNorm(idSeries, fileName, data):\n \"\"\"Creates the normalization verification file.\n\n Parameters\n ----------\n idSeries : `str`\n Folder of the series.\n fileName : `str`\n Wanted file name.\n data : `str`\n Data to write.\n \"\"\"\n\n file = \"data/\" + idSeries + \"/\" + fileName\n with open(file, mode=\"w\", encoding=\"utf-8\") as f:\n for char in data:\n charSp = char.split(',')\n normName = charSp[0]\n name = charSp[2]\n\n f.write(normName + \";\" + name + \"\\n\")\n\n\ndef main(args):\n sourceFile = args[\"SOURCEFILE\"]\n onlyOne = args[\"SERIES\"]\n if onlyOne:\n series = args[\"SERIES\"]\n\n with open(sourceFile, 'r') as f:\n for line in f:\n sp = line.split(',')\n idSeries = sp[0]\n isMovie = int(sp[4])\n\n if not onlyOne or idSeries == series:\n if not isMovie:\n link = sp[2]\n data = getData(link + \"fullcredits/\")\n if args[\"-v\"]:\n verifNorm(idSeries, args[\"-v\"], data)\n finalText = \"\".join(data)\n writeData(idSeries, finalText)\n\n else:\n sagaChars = []\n with open(\"data/\"+idSeries+\"/episodes.txt\", 'r') as fMovie:\n for lineMovie in fMovie:\n link = lineMovie.split(',')[2]\n movieChars = getData(link + \"fullcredits/\")\n sagaChars.extend(movieChars)\n # sagaChars = list(set(sagaChars)) to remove duplicates\n if args[\"-v\"]:\n verifNorm(idSeries, args[\"-v\"], sagaChars)\n finalText = \"\".join(sagaChars)\n writeData(idSeries, finalText)\n\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n main(args)\n" }, { "alpha_fraction": 0.7371695041656494, "alphanum_fraction": 0.7371695041656494, "avg_line_length": 24.719999313354492, "blob_id": "3cea92feb7eac3847af556784dcde93b5a0eab5b", "content_id": "2f231cf0e95dcd71203ac6ee88ce58d36d184751", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 643, "license_type": "permissive", "max_line_length": 89, "num_lines": 25, "path": "/README.md", "repo_name": "hbredin/pyannote-db-plumcot", "src_encoding": "UTF-8", "text": "# PLUMCOT corpus (not ready for prime time)\n\nThis repository provides a Python API to access the PLUMCOT corpus programmatically.\n\n## Installation\n\nUntil the package has been published on PyPI, one has to run the following commands:\n\n```bash\n$ git clone https://github.com/hbredin/pyannote-db-plumcot.git\n$ pip install pyannote-db-plumcot\n```\n\n## API\n\n```python\n>>> from pyannote.database import get_protocol\n>>> buffy = get_protocol('Plumcot.Collection.BuffyTheVampireSlayer')\n>>> for episode in buffy.files():\n... print(episode)\n```\n\n## Raw data\n\nIf needs be, one can also find the raw data as text file in `Plumcot/data` sub-directory.\n" }, { "alpha_fraction": 0.5107913613319397, "alphanum_fraction": 0.7122302055358887, "avg_line_length": 16.375, "blob_id": "674e117fee2a8a78b2b143025324d31d8504725c", "content_id": "56ee9970b632646e0c416be6203acd21a6df4322", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 139, "license_type": "permissive", "max_line_length": 24, "num_lines": 8, "path": "/scripts/requirements.txt", "repo_name": "hbredin/pyannote-db-plumcot", "src_encoding": "UTF-8", "text": "pyannote.database==1.5.5\nUnidecode==1.0.23\ndocopt==0.6.2\naffinegap==1.10\nscipy==1.1.0\nrequests==2.18.4\nnumpy==1.15.4\nbeautifulsoup4==4.7.1\n" }, { "alpha_fraction": 0.5567460656166077, "alphanum_fraction": 0.5604116916656494, "avg_line_length": 27.83333396911621, "blob_id": "6a97387ff017e009fd15c0d9a1aa6356fd456cb0", "content_id": "c28fd7a5e04a4552a3802184ca8b0429c0d60629", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7093, "license_type": "permissive", "max_line_length": 78, "num_lines": 246, "path": "/scripts/episodes.py", "repo_name": "hbredin/pyannote-db-plumcot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"Usage: episodes.py SOURCEFILE [SERIES] [-c]\n\nArguments:\n SOURCEFILE input series list file\n SERIES optionnal normalized name of a series\n\nOptions:\n -c creates credits.txt file (needs characters.txt)\n\n\"\"\"\n\nfrom docopt import docopt\nimport codecs # for encoding the data as utf-8\nimport requests\nfrom bs4 import BeautifulSoup\nfrom collections import OrderedDict\nimport unidecode\nimport re\n\n\ndef normalizeName(fullName):\n \"\"\"Normalizes characters and actors names.\n\n Removes parenthesis, commas, diacritics and non-alphanumerics characters,\n except _.\n\n Parameters\n ----------\n fullName : `str`\n Full name (of a character or a person).\n\n Returns\n -------\n normName : `str`\n Normalized name.\n \"\"\"\n\n fullName = fullName.lower()\n\n fullName = fullName.split('\\n')[0].strip()\n fullName = re.sub(r'\\([^()]*\\)', '', fullName) # Remove parenthesis\n fullName = re.sub(r\"\\'[^'']*\\'\", '', fullName) # Remove commas\n fullName = unidecode.unidecode(fullName) # Remove diacritics\n fullName = fullName.replace(' ', '_')\n # Remove all non-alphanumerics characters (except _)\n fullName = re.sub(r'\\W+', '', fullName)\n fullName = re.sub(r\"[_]+\", '_', fullName)\n return fullName\n\n\ndef scrapPage(idSeries, pageIMDB, credit=False, dicChars=None):\n \"\"\"Extracts episodes list of a series.\n\n Given an IMDB page, extracts episodes information in this format:\n unique episode identifier, name of the episode, IMDB.com episode page,\n TV.com episode page.\n\n Parameters\n ----------\n idSeries : `str`\n Folder of the series.\n pageIMDB : `str`\n IMDB page with the list of episodes.\n credit : `bool`\n Set to True to create credits.txt.\n dicChars : `OrderedDict`\n Ordered dictionnary generated from characters.txt.\n\n Returns\n -------\n seriesData : `str`\n String with the correct format, one line per episode.\n creditsData : `str`\n String with the correct format for credits.txt\n \"\"\"\n\n urlIDMB = requests.get(pageIMDB).text\n soup = BeautifulSoup(urlIDMB, 'lxml')\n seriesData = \"\"\n creditsData = \"\"\n\n nbSeasons = len(soup.find(id=\"bySeason\").find_all('option')) + 1\n\n for season in range(1, nbSeasons):\n linkSeason = pageIMDB + \"?season=\" + str(season)\n urlIDMB = requests.get(linkSeason).text\n soup = BeautifulSoup(urlIDMB, 'lxml')\n\n table = soup.find('div', {'class': 'eplist'})\n episodesTable = table.find_all('div', class_=\"list_item\")\n\n for episode in episodesTable:\n infos = episode.find('div', {'class': 'info'})\n nbEpisode = int(infos.find('meta').get('content'))\n link = infos.find('a')\n title = link.get('title')\n\n if \"Episode #\" not in title:\n link = link.get('href').split('?')[0]\n imdbLink = \"https://www.imdb.com\" + link\n seasonStr = f\"{season:02d}\"\n epStr = f\"{nbEpisode:02d}\"\n\n epNorm = idSeries + '.Season' + seasonStr + '.Episode' + epStr\n\n epString = epNorm + ',' + title + ',' + imdbLink + ','\n\n if credit:\n epCast = getEpCast(imdbLink, dicChars)\n creditsData += epNorm + ',' + epCast + '\\n'\n\n seriesData += epString + '\\n'\n\n return seriesData, creditsData\n\n\ndef getEpCast(imdbLink, dicChars):\n \"\"\"Extracts cast of an episode.\n\n Given the episode cast IMDB page and the series characters dictionnary set\n to zeros, sets ones if the character appears in the episode.\n\n\n Parameters\n ----------\n pageIMDB : `str`\n IMDB episode cast link.\n dicChars : `OrderedDict`\n Ordered dictionnary generated from characters.txt.\n\n Returns\n -------\n creditsData : `str`\n String with one if the character is in the episode and zero if not,\n separated with commas.\n \"\"\"\n\n dicEpCast = dicChars.copy()\n\n urlIDMB = requests.get(imdbLink + \"fullcredits\").text\n soup = BeautifulSoup(urlIDMB, 'lxml')\n seriesTable = soup.find('table', {'class': 'cast_list'}).find_all('tr')\n\n for char in seriesTable:\n charInfo = char.find_all('td')\n if len(charInfo) == 4:\n actorName = charInfo[1].text.strip()\n\n key = normalizeName(actorName)\n\n if key in dicEpCast:\n dicEpCast[key] = '1'\n\n return \",\".join(x for x in dicEpCast.values())\n\n\ndef writeData(series, data, file):\n \"\"\"Writes characters information in `characters.txt`.\n\n Parameters\n ----------\n series : `str`\n Folder of the series.\n data : `str`\n Data to write.\n \"\"\"\n\n with codecs.open(\"data/\"+series+\"/\" + file, \"w\", \"utf-8\") as chars:\n chars.write(data)\n\n\ndef initDicChars(idSeries):\n \"\"\"Creates a dictionnary in the format (idCharacter, 0)\n\n Creates an OrderedDict dictionnary in the format (idCharacter, 0) from\n characters.txt.\n\n\n Parameters\n ----------\n idSeries : `str`\n Id of the series.\n\n Returns\n -------\n dicChars : `OrderedDict`\n OrderedDict in the format (idCharacter, 0).\n \"\"\"\n dicChars = OrderedDict()\n\n with open(\"data/\"+idSeries+\"/characters.txt\", 'r') as chars:\n for charLine in chars:\n charSp = charLine.split(',')\n key = charSp[1]\n\n dicChars[key] = '0'\n\n return dicChars\n\n\ndef main(args):\n sourceFile = args[\"SOURCEFILE\"]\n onlyOne = args[\"SERIES\"]\n if onlyOne:\n series = args[\"SERIES\"]\n credit = True if args['-c'] else False\n\n with open(sourceFile, 'r') as f:\n for line in f:\n sp = line.split(',')\n idSeries = sp[0]\n isMovie = int(sp[4])\n\n if not isMovie and (not onlyOne or idSeries == series):\n if args['-c']:\n dicChars = initDicChars(idSeries)\n link = sp[2]\n dataSeries, dataCredits = scrapPage(idSeries,\n link + \"episodes\",\n credit, dicChars)\n finalText = \"\".join(dataSeries)\n writeData(idSeries, finalText, \"episodes.txt\")\n if credit:\n writeData(idSeries, dataCredits, \"credits.txt\")\n\n if credit and isMovie and (not onlyOne or idSeries == series):\n with open(\"data/\"+idSeries+\"/episodes.txt\", 'r') as movies:\n dataMovie = \"\"\n for movie in movies:\n movieSp = movie.split(',')\n normName = movieSp[0]\n linkIMDB = movieSp[2]\n dic = initDicChars(idSeries)\n\n epCast = getEpCast(linkIMDB, dic)\n dataMovie += (f\"{normName},{epCast}\\n\")\n\n writeData(idSeries, dataMovie, \"credits.txt\")\n\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n main(args)\n" }, { "alpha_fraction": 0.5812636613845825, "alphanum_fraction": 0.5840947031974792, "avg_line_length": 35.829383850097656, "blob_id": "d760bd8a1fe585f830b30cd19709ef198407d8a6", "content_id": "2280c0d21bab0eb63057d99dcb0b7c70ce14199e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7771, "license_type": "permissive", "max_line_length": 79, "num_lines": 211, "path": "/Plumcot/__init__.py", "repo_name": "hbredin/pyannote-db-plumcot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# encoding: utf-8\n\n# The MIT License (MIT)\n\n# Copyright (c) 2019 CNRS\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# AUTHORS\n# Hervé BREDIN - http://herve.niderb.fr\n\n\nfrom ._version import get_versions\n__version__ = get_versions()['version']\ndel get_versions\n\nfrom pyannote.database import Database\nfrom pyannote.database.protocol import CollectionProtocol\nfrom pathlib import Path\nimport pandas as pd\nimport glob\n\n\nclass BaseEpisodes(CollectionProtocol):\n \"\"\"Base class of collection protocols\"\"\"\n\n def files_iter(self):\n \"\"\"Iterate over all episodes of a series\"\"\"\n path = Path(__file__).parent / f'data/{self.SERIES}/episodes.txt'\n with open(path, mode='r') as fp:\n lines = fp.readlines()\n for line in lines:\n uri = line.split(',')[0]\n yield {'uri': uri, 'database': 'Plumcot'}\n\n\nclass Plumcot(Database):\n \"\"\"Plumcot database\"\"\"\n\n def get_characters(self, id_series, season_number=None,\n episode_number=None, full_name=False):\n \"\"\"Get IMDB character's names list.\n\n Parameters\n ----------\n id_series : `str`\n Id of the series.\n season_number : `str`\n The desired season number. If None, all seasons are processed.\n episode_number : `str`\n The desired episodeNumber. If None, all episodes are processed.\n full_name : `bool`\n Return id names if False, real names if True.\n\n Returns\n -------\n namesDict : `dict`\n Dictionnary with episodeId as key and list of IMDB names as value.\n \"\"\"\n\n # Template for processed episodes\n ep_name = id_series\n if season_number:\n ep_name += f\".Season{season_number}\"\n if episode_number:\n ep_name += f\".Episode{episode_number}\"\n\n parent = Path(__file__).parent\n credits_file = parent / f'data/{id_series}/credits.txt'\n characters_file = parent / f'data/{id_series}/characters.txt'\n\n # Get credits as list\n characters_list_credits = []\n with open(credits_file, mode='r', encoding=\"utf8\") as f:\n for line in f:\n line_split = line.split(',')\n if ep_name in line_split[0]:\n characters_list_credits.append(line_split)\n\n # Get character names as list\n characters_list = []\n id_name = 1 if full_name else 0\n with open(characters_file, mode='r', encoding=\"utf8\") as f:\n for line in f:\n characters_list.append(line.split(',')[id_name])\n\n # Create character's list by episode\n characters_dict = {}\n for episode in characters_list_credits:\n episode_name = episode[0]\n characters_name_list = []\n\n for id_character, character in enumerate(episode[1:]):\n if int(character):\n characters_name_list.append(characters_list[id_character])\n\n characters_dict[episode_name] = characters_name_list\n\n return characters_dict\n\n def get_transcript_characters(self, id_series, season_number=None,\n episode_number=None):\n \"\"\"Get transcripts character's names list from .temp transcripts files.\n\n Parameters\n ----------\n id_series : `str`\n Id of the series.\n season_number : `str`\n The desired season number. If None, all seasons are processed.\n episode_number : `str`\n The desired episodeNumber. If None, all episodes are processed.\n\n Returns\n -------\n namesDict : `dict`\n Dictionnary with episodeId as key and dictionnary as value with\n transcripts as key and number of speech turns as value\n \"\"\"\n\n # Template for processed episodes\n ep_template = id_series\n if season_number:\n ep_template += f\".Season{season_number}\"\n if episode_number:\n ep_template += f\".Episode{episode_number}\"\n\n parent = Path(__file__).parent\n temp_transcripts = glob.glob(f\"{parent}/data/{id_series}/transcripts/\"\n f\"{ep_template}*.temp\")\n\n # Get transcript character names list by episode\n characters_dict = {}\n for file in temp_transcripts:\n with open(file, mode='r', encoding=\"utf8\") as ep_file:\n characters = {}\n for line in ep_file:\n charac = line.split()[0]\n if charac not in characters:\n characters[charac] = 1\n else:\n characters[charac] += 1\n # Get episode name\n ep_name = file.split(\"/\")[-1].replace('.temp', '')\n characters_dict[ep_name] = characters\n\n return characters_dict\n\n def save_normalized_names(self, id_series, id_ep, dic_names):\n \"\"\"Saves new transcripts files as .txt with normalized names.\n\n Parameters\n ----------\n id_series : `str`\n Id of the series.\n id_ep : `str`\n Id of the episode.\n dic_names : `dict`\n Dictionnary with matching names (transcript -> normalized).\n \"\"\"\n\n parent = Path(__file__).parent\n trans_folder = f\"{parent}/data/{id_series}/transcripts/\"\n\n # Read .temp file and replace speaker names\n file_text = \"\"\n with open(trans_folder + id_ep + '.temp', mode='r',\n encoding=\"utf8\") as ep_file:\n for line in ep_file:\n line_split = line.split()\n line_split[0] = dic_names[line_split[0]]\n file_text += \" \".join(line_split) + '\\n'\n\n # Write changes\n with open(trans_folder + id_ep + '.txt', mode='w',\n encoding=\"utf8\") as ep_file:\n ep_file.write(file_text)\n\n def __init__(self, preprocessors={}, **kwargs):\n super().__init__(preprocessors=preprocessors, **kwargs)\n\n # load list of series\n path = Path(__file__).parent / 'data/series.txt'\n names = ['short_name', 'human_readable', 'imdb', 'tv', 'movies']\n with open(path, mode='r') as fp:\n data = pd.read_csv(fp, sep=',', header=None,\n names=names, converters={'movies': bool})\n\n # for each series, create and register a collection protocol\n # used to iterate over all episodes in chronological order\n for series in data.itertuples():\n Klass = type(series.short_name, (BaseEpisodes, ),\n {'SERIES': series.short_name})\n self.register_protocol('Collection', series.short_name, Klass)\n" }, { "alpha_fraction": 0.7156170010566711, "alphanum_fraction": 0.7410138249397278, "avg_line_length": 40.730770111083984, "blob_id": "1d9e37c86902b12136a2f5b984199540854d1bfa", "content_id": "e4b8b9ce186a6c2118e931ec2b7ceb029af05135", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9767, "license_type": "permissive", "max_line_length": 357, "num_lines": 234, "path": "/CONTRIBUTING.md", "repo_name": "hbredin/pyannote-db-plumcot", "src_encoding": "UTF-8", "text": "# How to contribute\n\n1. Clone the repository.\n2. Make changes.\n3. Open a pull request.\n\nMake sure all files are UTF8.\n\nMake sure to follow conventions and file formats described in this document.\n\nOpen an issue if something is not clear -- we will decide on a solution and update this document accordingly.\n\n# series.txt\n\n`series.txt` contains one line per TV (or movie) series.\nEach line provides a (CamelCase) identifier, a full name, a link to its IMDB.com page, a link to its TV.com page, and a boolean set to 1 if the line corresponds to a movie.\n\n```\n$ cat series.txt\nTheBigBangTheory,The Big Bang Theory,https://www.imdb.com/title/tt0898266/,http://www.tv.com/shows/the-big-bang-theory/,0\n```\n\n## One sub-directory per series / movies\n\nFor each entries in `series.txt`, there is a corresponding sub-directory called after its CamelCase identifier into the scripts folder and into the data folder.\n\n# Scripts\n\nAll the scripts need to put on the `scripts` folder into the corresponding serie's name.\nWe assume that we launch all the script from this root directory where README is stored.\n\n```\ncharacters.py\ncredits.py\nalignment.py\n(entities.py)\nTheBigBangTheory/\n transcripts.py\n```\n\n# Data\n\nAll the clean data with be put at the root directory of the serie into a `.txt` file.\nWe also download all the webpages where we extract the informations into the `html_pages` folder into the corresponding task folder.\n\n```\nTheBigBangTheory/\n characters.txt\n credits.txt\n transcripts/\n\tTheBigBangTheory.Season01.Episode01.temp\n\tTheBigBangTheory.Season01.Episode01.txt\n alignment.txt\n entities.txt\n html_pages/\n characters/\n credits/\n transcripts/\n season01.episode01.html\n season01.episode02.html\n season01.episode03.html\n alignment/\n entities/\n```\n\n### `characters.txt`\n\nThis file provides the list of characters (gathered from TV.com or IMDB.com). It contains one line per character with the following information: underscore-separated identifier, actor's normalized name, character's full name, actor's full name, IMDB.com character page.\n\n```\nleonard_hofstadter,johnny_galecki,Leonard Hofstadter,Johnny Galecki,https://www.imdb.com/title/tt0898266/characters/nm0301959\n```\n\nThe creation of this file should be automated as much as possible. Ideally, a script would take `series.txt` as input and generate all `characters.txt` file at once (or just one if an optional series identifier is provided)\n`-v fileName` creates a file with `characters.txt` to easily verify the characters normalization.\n\n```bash\npython characters.py series.txt TheBigBangTheory -v normVerif.txt\n```\n\nNote: Leo is in charge of creating this script.\n\n### `episodes.txt`\n\nThis file provides the list of episodes (gathered from TV.com or IMDB.com). It contains one line per episode with the following information: unique episode identifier, name of the episode, IMDB.com episode page, TV.com episode page.\n\n```\nTheBigBangTheory.Season01.Episode01,Pilot,https://www.imdb.com/title/tt0775431/,http://www.tv.com/shows/the-big-bang-theory/pilot-939386/\n```\n\nThe creation of this file should be automated as much as possible. Ideally, a script would take `series.txt` as input and generate all `episodes.txt` file at once (or just one if an optional series identifier is provided)\n\n```bash\npython episodes.py series.txt TheBigBangTheory\n```\n\nFor movies, we can use something like `HarryPotter.Episode01` as \"episode\" unique identifier.\n\nNote: Leo can probably do this script.\n\n### `credits.txt`\n\nThis file provides the list of characters credited in each episode. It contains one line per episode. Each episode is denoted by its normalized identifier (e.g. `TheBigBangTheory.Season01.Episode01`).\n\nThe line starts with one field for the episode and then one boolean for each character of the series/movie, with 1 if the character appears in the episode, 0 otherwise.\n\nFor instance, the line below tells that 3 characters appear in episode 1 of season 1 of The Big Bang Theory\n\n```\nTheBigBangTheory.Season01.Episode01,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0...\n```\n\nThe ith binary column corresponds to the ith line in characters.txt\n\nThe creation of this file should be automated as much as possible. Ideally, a script would take `series.txt` as input and generate all `credits.txt` at once (or just one if an optional series identifier is provided)\n\n```bash\npython episodes.py series.txt TheBigBangTheory -c\n```\n\nNote: Leo is in charge of creating this script\n\n### `transcripts/ folder`\n\nThe transcripts folder contains 2 files for all episodes in `episodes.txt`:\n\n#### `{idEpisode}.temp`\n\nThis file provides the manual transcript of the {idEpisode} episode without normalized names. It contains one line per speech turn.\n\nThe expected file format is the following: character identifier, followed by the actual transcription.\n\n```\nSheldon How are you, Leonard?\nLeonard Good, and you?\n```\n\nIt is unlikely that we will be able to code *one script to rule them all* generic enough to process all series. It will most likely need a lot of manual cleaning.\n\nThis is why we will start by focusing on a sub-sample of the (eventually bigger) corpus.\n\nNote: here is a \"who is doing what\" split\n\n* Harry Potter : Ruiqing\n* The Big Bang Theory : Leo\n* Friends : Leo\n* Lost : Benjamin\n* Game of Thrones : Aman\n* Buffy the Vampire Slayer : Hervé\n* Battlestar Galactica : Benjamin\n* The Good Wife : Claude\n\n#### `{idEpisode}.txt`\n\nThis file is the same as {idEpisode}.temp file but with normalized names.\n\n```\nsheldon_cooper How are you, Leonard?\nleonard_hofstadter Good, and you?\n```\n\nAll normalized names should appear in the IMDB credits except for few cases:\n\nWhen a character from the transcript doesn't have an equivalent in IMDB, we name it as *{transcriptName}#unknown#{idEpisode}*.\n\nWhen several characters speak at the same time, we concatenate normalized names in alphabetical order with \"@\" as separator like *penny@sheldon_cooper*. \n\n*all@* is used as the \"all\" tag.\n\nTo normalize names, you can use the script normalizeTranscriptsNames.py like that: *python normalizeTranscriptsNames.py TheBigBangTheory*.\n\nYou can precise a season with -s option and an episode with -e option.\n\nFor a given episode, the script presents normalized names from IMDB for this episode.\n\nThen, the script show the result of the automatic alignment as *{transcriptName} -> {predictedIMDBName}*.\n\nYou can then select a {transcriptName} you want to change, and the script asks for the normalized name. If you can't find a matching, just type\n*unk* or leave the field blank and the script automatically asigns the right unknown format to the {transcriptName}.\n\nYou can finally save the changes and create the appropriate `{idEpisode}.txt` file with *end*.\n\n### `alignment.stm`\n\nThis file provides the forced-aligned transcripts of all episodes in episodes.txt. It contains one line per word using the [`stm`](http://www1.icsi.berkeley.edu/Speech/docs/sctk-1.2/infmts.htm#stm_fmt_name_0) or [`ctm`](https://web.archive.org/web/20170119114252/http://www.itl.nist.gov/iad/mig/tests/rt/2009/docs/rt09-meeting-eval-plan-v2.pdf) file format.\n\n```\nTheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> How\nTheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> are\nTheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> you\nTheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> ,\nTheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> Leonard\nTheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> ?\n```\n\nNote : Benjamin and Hervé will take care of it.\n\n### `entities.txt`\n\nThis file contains named entities annotation of `alignment.stm`.\n\nThe proposed file format is the following:\n\n```\nword_id file_id channel_id speaker_id start_time end_time <> word named_entity_type normalized_name coreference_id\n```\n\n```\n1 TheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> How <> <> <>\n2 TheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> are <> <> <>\n3 TheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> you <> <> 5/6\n4 TheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> , <> <> <>\n5 TheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> Leonard PERSON leonard_hofstadter <>\n6 TheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> Hofstadter PERSON leonard_hofstadter <>\n7 TheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> ? <> <> <>\n```\n\n```\n1 TheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> How <> <> <>\n2 TheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> are <> <> <>\n3 TheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> you <> <> 5/7\n4 TheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> , <> <> <>\n5 TheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> Sheldon PERSON sheldon_cooper <>\n6 TheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> and <> <> <>\n7 TheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> Leonard PERSON leonard_hofstadter <>\n8 TheBigBangTheory.Season01.Episode01 1 sheldon_cooper start_time end_time <> ? <> <> <>\n```\n\nNote: Leo has a script to do that, though the (automatic) output will need a manual correction pass.\n\n\n### scene / narrative stuff\n\nAman will come up with a file format and data.\n" }, { "alpha_fraction": 0.5641739368438721, "alphanum_fraction": 0.5656324625015259, "avg_line_length": 31.649351119995117, "blob_id": "59d232cd30f045685ede85861cf4cea616de2ffa", "content_id": "4e1ae6fbcefeb71033600fa0e0784f113f0c23ff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7542, "license_type": "permissive", "max_line_length": 79, "num_lines": 231, "path": "/scripts/normalizeTranscriptsNames.py", "repo_name": "hbredin/pyannote-db-plumcot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"Usage: normalizeTranscriptsNames.py <id_series> [-s SEASON] [-e EPISODE]\n\nArguments:\n id_series Id of the series\n\nOptions:\n -s SEASON Season number to iterate on (all seasons if not specified)\n -e EPISODE Episode number (all episodes of the season if not specified)\n\n\"\"\"\n\nimport pyannote.database\nfrom docopt import docopt\nfrom Plumcot import Plumcot\nimport affinegap\nimport numpy as np\nfrom scipy.optimize import linear_sum_assignment\nimport os.path\nfrom pathlib import Path\nimport Plumcot as PC\nimport json\n\n\ndef automatic_alignment(id_series, id_ep, refsT, hypsT):\n \"\"\"Aligns IMDB character's names with transcripts characters names.\n\n Parameters\n ----------\n id_series : `str`\n Id of the series.\n id_ep : `str`\n Id of the episode.\n refsT : `dict`\n Dictionnary of character's names from transcripts as key and number of\n speech turns as value.\n hypsT : `list`\n List of character's names from IMDB.\n\n Returns\n -------\n names_dict : `dict`\n Dictionnary with character's names as key and normalized name as value.\n \"\"\"\n\n names_dict = {}\n save_dict = {}\n\n hyps = hypsT[:]\n refs = refsT.copy()\n\n # Loading user previous matching names\n savePath = Path(__file__).parent / f\"{id_series}.json\"\n if os.path.isfile(savePath):\n with open(savePath, 'r') as f:\n save_dict = json.load(f)\n\n # Process data to take user matching names in account\n for trans_name in refs.copy():\n if trans_name in save_dict:\n if ('@' in save_dict[trans_name] or\n save_dict[trans_name] in hyps):\n\n names_dict[trans_name] = save_dict[trans_name]\n refs.pop(trans_name)\n if save_dict[trans_name] in hyps:\n hyps.remove(save_dict[trans_name])\n\n size = max(len(refs), len(hyps))\n min_size = min(len(refs), len(hyps))\n dists = np.ones([size, size])\n for i, ref in enumerate(refs):\n for j, hyp in enumerate(hyps):\n # Affine gap distance is configured to penalize gap openings,\n # regardless of the gap length to maximize matching between\n # firstName_lastName and firstName for example.\n dists[i, j] = affinegap.normalizedAffineGapDistance(\n ref, hyp, matchWeight=0, mismatchWeight=1, gapWeight=0,\n spaceWeight=1)\n # We use Hungarian algorithm which solves the \"assignment problem\" in a\n # polynomial time.\n row_ind, col_ind = linear_sum_assignment(dists)\n\n # Add names ignored by Hungarian algorithm when sizes are not equal\n for i, ref in enumerate(refs):\n if col_ind[i] < min_size:\n names_dict[ref] = hyps[col_ind[i]]\n else:\n names_dict[ref] = unknown_char(ref, id_ep)\n\n return names_dict\n\n\ndef normalize_names(id_series, season_number, episode_number):\n \"\"\"Manual normalization.\n\n Parameters\n ----------\n id_series : `str`\n Id of the series.\n season_number : `str`\n The desired season number. If None, all seasons are processed.\n episode_number : `str`\n The desired episode_number. If None, all episodes are processed.\n\n Returns\n -------\n names_dict : `dict`\n Dictionnary with character's names as key and normalized name as value.\n \"\"\"\n\n # Plumcot database object\n db = Plumcot()\n\n # Retrieve IMDB normalized character names\n imdb_chars_series = db.get_characters(id_series, season_number,\n episode_number)\n # Retrieve transcripts normalized character names\n trans_chars_series = db.get_transcript_characters(id_series, season_number,\n episode_number)\n\n # Iterate over episode IMDB character names\n for id_ep, imdb_chars in imdb_chars_series.items():\n if id_ep not in trans_chars_series:\n continue\n trans_chars = trans_chars_series[id_ep]\n\n link = Path(PC.__file__).parent / 'data' / f'{id_series}'\\\n / 'transcripts' / f'{id_ep}.txt'\n # If episode has already been processed\n if os.path.isfile(link):\n exists = f\"{id_ep} already processed. [y] to processe, n to skip: \"\n co = input(exists)\n if co == 'n':\n continue\n\n # Get automatic alignment as a dictionnary\n dic_names = automatic_alignment(id_series, id_ep, trans_chars,\n imdb_chars)\n save = True\n\n # User input loop\n while True:\n print(f\"----------------------------\\n{id_ep}. Here is the list \"\n \"of normalized names from IMDB: \")\n names = \"\"\n for name in imdb_chars:\n names += name + ', '\n print(names[:-2], '\\n')\n\n print(\"Automatic alignment:\")\n for name, norm_name in dic_names.items():\n # Get number of speech turns of the character for this episode\n appearence = trans_chars[name]\n print(f\"{name} ({appearence}) -> {norm_name}\")\n\n request = input(\"\\nType the name of the character which you want \"\n \"to change normalized name (end to save, stop \"\n \"to skip): \")\n # Stop and save\n if request == \"end\":\n break\n # Stop without saving\n if request == \"stop\" or request == \"skip\":\n save = False\n break\n # Wrong name\n if request not in dic_names:\n print(\"This name doesn't match with any characters.\\n\")\n else:\n new_name = input(\"\\nType the new character's name \"\n \"(unk for unknown character): \")\n # Unknown character\n if new_name == \"unk\" or not new_name:\n new_name = unknown_char(request, id_ep)\n dic_names[request] = new_name\n\n # Save changes and create .txt file\n if save:\n save_matching(id_series, dic_names)\n db.save_normalized_names(id_series, id_ep, dic_names)\n\n\ndef unknown_char(char_name, id_ep):\n \"\"\"Transforms character name into unknown version.\"\"\"\n\n return f\"{char_name}#unknown#{id_ep}\"\n\n\ndef save_matching(id_series, dic_names):\n \"\"\"Saves user matching names\n\n Parameters\n ----------\n id_series : `str`\n Id of the series.\n dic_names : `dict`\n Dictionnary with matching names (transcript -> normalized).\n \"\"\"\n\n save_dict = {}\n savePath = Path(__file__).parent / f\"{id_series}.json\"\n if os.path.isfile(savePath):\n with open(savePath, 'r') as f:\n save_dict = json.load(f)\n\n for name_trans, name_norm in dic_names.items():\n if \"#unknown\" not in name_norm:\n save_dict[name_trans] = name_norm\n\n with open(Path(__file__).parent / f\"{id_series}.json\", 'w') as f:\n json.dump(save_dict, f)\n\n\ndef main(args):\n id_series = args[\"<id_series>\"]\n season_number = args['-s']\n if season_number:\n season_number = f\"{int(season_number):02d}\"\n episode_number = args['-e']\n if episode_number:\n episode_number = f\"{int(episode_number):02d}\"\n\n normalize_names(id_series, season_number, episode_number)\n\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n main(args)\n" } ]
7
znsoftm/chinese_ocr-1
https://github.com/znsoftm/chinese_ocr-1
92796c6ec0cb2ed0763b2f026377687087764867
d5b70457079e9ae5c965588c940020da742ea9c1
e1bb967ae710c64188d08da0b1c6b38cf5be49b7
refs/heads/master
2022-03-21T03:11:19.795622
2019-12-20T06:42:18
2019-12-20T06:42:18
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6093457937240601, "alphanum_fraction": 0.6396676898002625, "avg_line_length": 29.865385055541992, "blob_id": "0112c8e48b12046f21bdea1d20369f4a9d766c3f", "content_id": "ce5f563bc4fdf1d507d97bd7e8c7465e5a53cd13", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4917, "license_type": "permissive", "max_line_length": 112, "num_lines": 156, "path": "/chinese_ocr/7476_model_eval.py", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "# -- coding:utf-8 --\n\"\"\"\n\n计算单字准确率\n\"\"\"\nfrom keras import backend as K\nimport os\nimport shutil\nfrom imp import reload\nimport tensorflow as tf\nimport cv2\nfrom PIL import Image\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nfrom keras.layers import Input\nfrom keras.models import Model\nfrom keras.utils import multi_gpu_model\n\nfrom chinese_ocr.train.train import random_uniform_num, get_session, get_model\nfrom chinese_ocr.densenet_common import densenet\nfrom chinese_ocr.densenet_common.densenet_model import data_generator\nfrom chinese_ocr.train.synthtext_config import SynthtextConfig\nfrom chinese_ocr.densenet_common.dataset_format import DataSetSynthtext\nfrom predict_tf_tool import DensenetOcr\n\nreload(densenet)\nK.set_learning_phase(0)\n\ndataset_path = \"/media/chenhao/study/code/other/out\"\n\nclass_id_file = \"char_7476.txt\"\ntrain_label_name = \"label_train.txt\"\nval_label_name = \"label_val.txt\"\ntest_label_name = \"label_test.txt\"\ndataset_format = 0\nsub_img_folder = \"default\"\n\ndata_test = DataSetSynthtext()\ndata_test.load_data(class_id_file, dataset_path, test_label_name, subset=sub_img_folder)\n# label_list = data.load_instance(33)\n# print(label_list)\ndata_test.prepare()\n\nnclass = data_test.num_classes\nchar_set_line = data_test.char_set_line\nprint(\"class num:\", nclass)\nprint(\"char_set_line:\", char_set_line)\n#\n# input = Input(shape=(32, None, 1), name='the_input')\n# # input = Input(tensor=resize_image)\n# y_pred= densenet.dense_cnn(input, nclass)\n# basemodel = Model(inputs=input, outputs=y_pred)\n#\n# modelPath = '/media/chenhao/study/code/work/github/chinese_ocr/chinese_ocr/models/weights_densenet-12-0.98.h5'\n# # basemodel = multi_gpu_model(basemodel, gpus=8)\n# print(modelPath)\n# w = basemodel.get_weights()[2]\n# print(w)\n# print(\"loading weights..............\")\n# basemodel.load_weights(modelPath)\n# w = basemodel.get_weights()[2]\n# print(w)\n\nconfig = SynthtextConfig()\nconfig.display()\n''''''\ntest_gen = data_generator(data_test, config=config)\n\nprint(\"test num_images\", data_test.num_images)\n# predict\n\nocr_predict_7476 = DensenetOcr(\"./train/char_7476.txt\", model_name=\"7476_model\")\n\n\ndef eva_batch():\n aaa = next(test_gen)\n # print(aaa)\n input_tuple = aaa[0]\n # print(input_tuple[\"the_input\"].shape)\n batch_lines_img = input_tuple[\"the_input\"]\n y_true = input_tuple[\"the_labels\"]\n img_paths = input_tuple[\"img_paths\"]\n\n batch_img_result = ocr_predict_7476.run_func(batch_lines_img)\n print(batch_img_result.shape)\n\n accs = []\n for i in range(config.BATCH_SIZE):\n one_line = batch_img_result[i, :, :]\n line_label = y_true[i, :]\n line_label = np.array(line_label).astype(int)\n one_line = np.expand_dims(one_line, axis=0)\n line_result = ocr_predict_7476.decode_to_id(one_line)\n\n print(\"y_pres \", line_result)\n print(\"line_label \", line_label)\n print(\"img_path \", img_paths[i])\n print(\"id_to_char \", ocr_predict_7476.id_to_char(line_result))\n\n \"\"\"\n y_pres [1, 360, 21, 5, 5, 175, 16, 36, 26, 258, 264]\n line_label [ 1 360 21 5 175 16 36 26 258 264]\n img_path train/images/20459843_2752426851.jpg\n 的近20名大学生保安\n id_to_char 的近200名大学生保安\n 有重复 [1, 360, 21, 5, 5, 175, 16, 36, 26, 258, 264]\n acc 0.4\n \"\"\"\n # if len(line_result) > len(line_label):\n # aaa = line_result.copy()\n # # if remove_duplicates(aaa) == len(line_label):\n # print(\"-------------->有重复\", aaa)\n # # line_result = aaa[:len(line_label)]\n # line_result = line_result[:len(line_label)]\n pre_arr = np.array(line_result)\n result = calculate_char_equal(line_label, pre_arr)\n totalRight = np.sum(result)\n acc = totalRight / len(result)\n print('acc', acc)\n accs.append(acc)\n print(\"batch mean acc\", np.mean(acc))\n return accs\n\n\ndef calculate_char_equal(line_label, predict_arr):\n label_len = len(line_label)\n predict_len = predict_arr.shape[0]\n print(\"predict_len \", predict_len)\n # 长度不足的补字符\n if predict_len < label_len:\n print(\"predict shorter than true label\")\n supplement = label_len - predict_len\n p_ = -1 # 补-1\n for i in range(supplement):\n predict_arr = np.append(predict_arr, p_) # 直接向p_arr里添加p_\n # 过长的直接截取\n elif predict_len > label_len:\n print(\"predict longer than true label\")\n predict_arr = predict_arr[:label_len]\n else:\n pass\n return np.equal(line_label, predict_arr)\n\n\naccs = []\n# epoch = data_test.num_images // config.BATCH_SIZE\nepoch = 50\nfor i in range(epoch):\n print(\"---------------- eval epoch ----------\", i)\n acc = eva_batch()\n accs += acc\n\nprint(accs)\nprec = np.mean(accs)\nprint(\"total mean acc \", prec)\n" }, { "alpha_fraction": 0.4104938209056854, "alphanum_fraction": 0.43300652503967285, "avg_line_length": 31.585798263549805, "blob_id": "4d870fabefe1321902284d072421a8b5c3b28519", "content_id": "49f9fe8a4e22c7102a03e8afb5f40dc08322bf1f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6096, "license_type": "permissive", "max_line_length": 109, "num_lines": 169, "path": "/chinese_ocr/demo.py", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\nimport sys\nimport os\nimport time\n\nfrom PIL import Image\nimport cv2\n\nimport model\nfrom utils.image import union_rbox, adjust_box_to_origin\nfrom utils.image import get_boxes, letterbox_image\nfrom global_obj import ocr_predict, ocr_predict_7476\nfrom config.config import opencvFlag, GPU, IMGSIZE, ocrFlag\n\n\ndef test_img1():\n detectAngle = True\n path = \"test_images/shi.png\"\n\n img = cv2.imread(path) ##GBR\n H, W = img.shape[:2]\n timeTake = time.time()\n\n # 多行识别 multi line\n _, result, angle = model.model(img,\n detectAngle=detectAngle, ##是否进行文字方向检测,通过web传参控制\n config=dict(MAX_HORIZONTAL_GAP=50, ##字符之间的最大间隔,用于文本行的合并\n MIN_V_OVERLAPS=0.6,\n MIN_SIZE_SIM=0.6,\n TEXT_PROPOSALS_MIN_SCORE=0.1,\n TEXT_PROPOSALS_NMS_THRESH=0.3,\n TEXT_LINE_NMS_THRESH=0.7, ##文本行之间测iou值\n ),\n leftAdjust=True, ##对检测的文本行进行向左延伸\n rightAdjust=True, ##对检测的文本行进行向右延伸\n alph=0.2, ##对检测的文本行进行向右、左延伸的倍数\n )\n\n print(result, angle)\n result = union_rbox(result, 0.2)\n print(result, angle)\n\n res = [{'text': x['text'],\n 'name': str(i),\n 'box': {'cx': x['cx'],\n 'cy': x['cy'],\n 'w': x['w'],\n 'h': x['h'],\n 'angle': x['degree']\n\n }\n } for i, x in enumerate(result)]\n res = adjust_box_to_origin(img, angle, res) ##修正box\n print(\"res \\n\")\n print(res)\n\n print(\"result str: \\n\", )\n for x in result:\n print(x['text'])\n\n print(\"done\")\n\n\ndef test_img2():\n \"\"\"\n single line img test\n :return:\n \"\"\"\n # detectAngle = False\n path = \"test_images/line.jpg\"\n\n img = cv2.imread(path) ##GBR\n # 单行识别 one line\n partImg = Image.fromarray(img)\n text2 = ocr_predict.recognize(partImg.convert('L'))\n print(text2)\n # 客店遒劲摊婕有力\n\n\ndef test_img3():\n \"\"\"\n single line need resize img, set alph to 0.2 to adjust anchor\n :return:\n \"\"\"\n detectAngle = False\n path = \"test_images/line.jpg\"\n\n img = cv2.imread(path) ##GBR\n img2, f = letterbox_image(Image.fromarray(img), IMGSIZE)\n\n _, result, angle = model.model(img2,\n detectAngle=detectAngle, ##是否进行文字方向检测,通过web传参控制\n config=dict(MAX_HORIZONTAL_GAP=50, ##字符之间的最大间隔,用于文本行的合并\n MIN_V_OVERLAPS=0.6,\n MIN_SIZE_SIM=0.6,\n TEXT_PROPOSALS_MIN_SCORE=0.1,\n TEXT_PROPOSALS_NMS_THRESH=0.3,\n TEXT_LINE_NMS_THRESH=0.7, ##文本行之间测iou值\n ),\n leftAdjust=True, ##对检测的文本行进行向左延伸\n rightAdjust=True, ##对检测的文本行进行向右延伸\n alph=0.2, ##对检测的文本行进行向右、左延伸的倍数\n )\n #\n print(result, angle)\n # [{'cx': 280.5, 'cy': 26.5, 'text': '客店遒劲摊婕有力', 'w': 606.0, 'h': 50.0, 'degree': 0.10314419109384157}] 0\n\n\n\ndef test_img4():\n detectAngle = True\n path = \"test_images/fp.jpg\"\n\n img = cv2.imread(path) ##GBR\n H, W = img.shape[:2]\n timeTake = time.time()\n\n # 多行识别 multi line\n _, result, angle = model.model(img,\n detectAngle=detectAngle, ##是否进行文字方向检测,通过web传参控制\n config=dict(MAX_HORIZONTAL_GAP=50, ##字符之间的最大间隔,用于文本行的合并\n MIN_V_OVERLAPS=0.6,\n MIN_SIZE_SIM=0.6,\n TEXT_PROPOSALS_MIN_SCORE=0.1,\n TEXT_PROPOSALS_NMS_THRESH=0.3,\n TEXT_LINE_NMS_THRESH=0.7, ##文本行之间测iou值\n ),\n leftAdjust=True, ##对检测的文本行进行向左延伸\n rightAdjust=True, ##对检测的文本行进行向右延伸\n alph=0.2, ##对检测的文本行进行向右、左延伸的倍数\n )\n\n print(result, angle)\n result = union_rbox(result, 0.2)\n print(result, angle)\n\n res = [{'text': x['text'],\n 'name': str(i),\n 'box': {'cx': x['cx'],\n 'cy': x['cy'],\n 'w': x['w'],\n 'h': x['h'],\n 'angle': x['degree']\n\n }\n } for i, x in enumerate(result)]\n res = adjust_box_to_origin(img, angle, res) ##修正box\n print(\"res \\n\")\n print(res)\n\n print(\"result str: \\n\", )\n for x in result:\n print(x['text'])\n\n print(\"done\")\n\n\ndef test_7476_model():\n # detectAngle = False\n path = \"test_images/00000000.jpg\"\n\n img = cv2.imread(path) ##GBR\n # 单行识别 one line\n partImg = Image.fromarray(img)\n text2 = ocr_predict_7476.recognize(partImg.convert('L'))\n print(text2)\n\ntest_7476_model()\n\n" }, { "alpha_fraction": 0.7586206793785095, "alphanum_fraction": 0.7793103456497192, "avg_line_length": 28, "blob_id": "dcc28281d93cdf7c0ecb0c561c702394d2ecd467", "content_id": "c969444c0d27b888313734cbf4e836b801c6deaf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 145, "license_type": "permissive", "max_line_length": 55, "num_lines": 5, "path": "/chinese_ocr/train/synthtext_config.py", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "\nfrom chinese_ocr.config.train_config import TrainConfig\n\nclass SynthtextConfig(TrainConfig):\n DATASET_SOURCE1 = \"Synthtext\"\n BATCH_SIZE=20" }, { "alpha_fraction": 0.6249240040779114, "alphanum_fraction": 0.6376899480819702, "avg_line_length": 31.899999618530273, "blob_id": "9e5abd229915a64d121dedd89c8f007bf9155505", "content_id": "e72ca02702e9e531dacbc1241c934ec4229588bb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3324, "license_type": "permissive", "max_line_length": 114, "num_lines": 100, "path": "/chinese_ocr/tools/tmp_label_to_id_label.py", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n# bing1 \n\n# 2019/8/21 \n\n# 11:11 \n\"\"\"\nMIT License\n\nCopyright (c) 2019 Hyman Chen\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\nimport sys\nimport os\nimport argparse\n\n\n# dataset_url = \"/media/chenhao/study/code/other/out\"\n# dict_file_name = \"char_7476.txt\"\n# tmp_label_path = \"/media/chenhao/study/code/other/out/default/tmp_labels.txt\"\n\ndef main(dataset_url, dict_file_name, tmp_label_path):\n \"\"\"\n 把使用text_renderer 生成的label文件,转化为需要的格式\n\n :param dataset_url:\n :param dict_file_name:\n :param tmp_label_path:\n :return:\n \"\"\"\n dict_file_path = os.path.join(dataset_url, dict_file_name)\n\n out_file_name = \"my_dataset_label.txt\"\n\n char_set = open(dict_file_path, 'r', encoding='utf-8').readlines()\n char_set = ''.join([ch.strip('\\n') for ch in char_set][1:] + ['卍'])\n\n d = {' ': '0'}\n for i, c in enumerate(char_set):\n d[c] = str(i + 1)\n\n g = open(os.path.join(dataset_url, out_file_name), \"w\", encoding=\"utf-8\")\n s = 0\n with open(tmp_label_path, \"r\", encoding=\"utf-8\") as f:\n for line in f:\n line = line.strip()\n # label = line.split(\" \")\n (img_name, *line_text) = line.split(\" \")\n words = \" \".join(line_text)\n print(words)\n label_list = []\n if img_name ==\"00003580\":\n print(\"dddd\")\n for w in words:\n if w == ' ':\n print(\"aaaa \", d[w])\n label_list.append(d[w])\n\n label_str = \" \".join(label_list)\n print(label_str)\n g.write(img_name + \".jpg \" + label_str + \"\\n\")\n s += 1\n\n g.close()\n print(\"wirte \", s)\n\n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n\n parser.add_argument('dataset_url', type=str, help='text generate dataset url')\n parser.add_argument('dict_file_name', type=str, help='file name.')\n parser.add_argument('tmp_label_path', type=str, help='tmp_labels.txt path ')\n\n return parser.parse_args(argv)\n\n\nif __name__ == '__main__':\n ### F:/code/other/text_renderer/output char_7473.txt F:/code/other/text_renderer/output/default/tmp_labels.txt\n a = sys.argv[1:]\n print(\"args:\", a)\n args = parse_arguments(a)\n main(args.dataset_url, args.dict_file_name, args.tmp_label_path)\n" }, { "alpha_fraction": 0.6292585134506226, "alphanum_fraction": 0.6753507256507874, "avg_line_length": 18.230770111083984, "blob_id": "aea2214907cb740640e9522e9cd909aa18eb9876", "content_id": "9710a3aced91c186a793d527a5d78f5d15115775", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 499, "license_type": "permissive", "max_line_length": 70, "num_lines": 26, "path": "/chinese_ocr/config/use_model_config.py", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport os\n\n\"\"\"\nmode config \n\"\"\"\n\n\nclass InferenceConfig:\n # the mode path to use in demo\n DENSENET_MODEL_DIR = os.getcwd() + \"/models/densenet_base_model/1\"\n\n\nclass Dict1Config(InferenceConfig):\n print(\"config 5990 chars model path \")\n\n\nclass Dict2Config(InferenceConfig):\n print(\"config 7476 chars model\")\n DENSENET_MODEL_DIR = os.getcwd() + \"/models/densenet_base_model/2\"\n\ninference_config = {\n '5990_model': Dict1Config,\n '7476_model': Dict2Config\n}" }, { "alpha_fraction": 0.7140012979507446, "alphanum_fraction": 0.7412077188491821, "avg_line_length": 27.433961868286133, "blob_id": "84a1ecdb6b201a1322f483118d9def922105f1df", "content_id": "b5b81ff96aa19a011b1183179e67f7e4180c4f1c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3206, "license_type": "permissive", "max_line_length": 155, "num_lines": 106, "path": "/README.md", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "# chinese_ocr\nyolo3 + densenet + ctc ocr\n\n# setup \nsee setup\n\n# dowon model \n* densenet model used for 5990 chars \nurl:https://pan.baidu.com/s/1gm0Uq_sLe00En-IbUPiQUg \npassword :qcco \nput the model file in project_root/chinese_ocr/models/densenet_base_model/1\n\n* densenet model used for 7476 chars \nurl:https://pan.baidu.com/s/1_eGdF9odvzziJn35wOzQlA \npassword :jve5 \nput the model file in project_root/chinese_ocr/models/densenet_base_model/2\n\n\n* other model\nurl: https://pan.baidu.com/s/10t5BYHm-YJXb9NpT7OnIOg \npassword: 8zbx \nput the model file in project_root/chinese_ocr/models/\n\n#### 模型效果\n目前提供的模型只适合学习使用,只用当前代码在生成的数据集上训练了很多轮保存的最好的一个版本,但不足以商用,\n你可以自己用代码训练更好的模型,参考白翔老师的crnn也是个不错的选择\n\n# test\n`python demo.py`\n\nyou can also see [understand_detect](https://github.com/bing1zhi2/chinese_ocr/blob/master/chinese_ocr/understand_detect.ipynb)\n\n![result](https://github.com/bing1zhi2/chinese_ocr/blob/master/chinese_ocr/test_result/result.png \"result\")\n# train\n`cd train`\n\n`python train.py`\nor you can use [train_with_param](https://github.com/bing1zhi2/chinese_ocr/blob/master/chinese_ocr/train_use_new_dataset.py) to deal with different dataset\n\n## dataset format\n\n\n&ensp;---dataset \n&ensp;&ensp;&ensp;&ensp;--images \n&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;--xxx.jpg \n&ensp;&ensp;&ensp;&ensp;--data_train.txt \n&ensp;&ensp;&ensp;&ensp;--data_test.txt \n\n\n\n## dataset\nthis dataset is generate by code.\n\nlink:https://pan.baidu.com/s/1JgS1gSRcfnjWF_epU-E2vA \npassword:wigu \n \nThe dataset contains 800,000 pictures \n300,000 from chinese novel \n100,000 from random number 0-9 \n100,000 from random code \n300,000 random selected by it's frequency \n\n* Random char space\n* Random font size \n* 10 different fonts\n* Blur\n* noise(gauss,uniform,salt_pepper,poisson)\n* ...\n\nfor more detial see [train_with_param](https://github.com/bing1zhi2/chinese_ocr/blob/master/chinese_ocr/train_use_new_dataset.py) \n\n\nOr you can use YCG09's dataset to train,url:\n\nurl:https://pan.baidu.com/s/1QkI7kjah8SPHwOQ40rS1Pw (passwd:lu7m)\n\n\nput your dataset into train/images and change the label file data_test.txt data_train.txt\n\n\n## generate you own dataset\nor you can generate your own dataset:\n* text location: \n[SynthText](https://github.com/JarveeLee/SynthText_Chinese_version) \n* text recognition \n[TextRecognitionDataGenerator](https://github.com/Belval/TextRecognitionDataGenerator) \n[text_renderer](https://github.com/Sanster/text_renderer) (which one I used ) \nyou can use tools/tmp_label_to_id_label.py to change label file format to what we need here\n\n\n# update\n1. use pretrain model to detect word\n * add demo &radic;\n * add densenet training code &radic;\n * test gpu nms &radic;\n * generate my own dataset &radic;\n \n2. add framework to easy train on your own dataset\n * add yolo3 train code\n * make the code can be easy use on other dataset\n \n \n \n# Reference\nhttps://github.com/chineseocr/chineseocr\nhttps://github.com/YCG09/chinese_ocr\n" }, { "alpha_fraction": 0.6953210234642029, "alphanum_fraction": 0.7080159783363342, "avg_line_length": 37.83098602294922, "blob_id": "2652d93d6807f7bad4d7dd32cd6c3004284e41e3", "content_id": "a4da1c4fbb4c38147693808fc0634ef2f650d91a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2757, "license_type": "permissive", "max_line_length": 97, "num_lines": 71, "path": "/chinese_ocr/train/train_with_param.py", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\n# from importlib import reload\nimport tensorflow as tf\nfrom keras import losses\nfrom keras import backend as K\nfrom keras.utils import plot_model\nfrom keras.preprocessing import image\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Input, Dense, Flatten\nfrom keras.layers.core import Reshape, Masking, Lambda, Permute\nfrom keras.layers.recurrent import GRU, LSTM\nfrom keras.layers.wrappers import Bidirectional, TimeDistributed\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D, ZeroPadding2D\nfrom keras.optimizers import SGD, Adam\nfrom keras.models import Model\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, LearningRateScheduler, TensorBoard\n\nfrom chinese_ocr.densenet_common.dataset_format import DataSetSynthtext\nfrom chinese_ocr.train.synthtext_config import SynthtextConfig\nfrom chinese_ocr.config.train_config import TrainConfig\nfrom chinese_ocr.densenet_common.densenet_model import DensenetModel\n\n\n#\n# IMG_H = 32\n# IMG_W = 280\n# BATCH_SIZE = 50\n# MAX_LABEL_LENGTH = 10\n#\ndef train_with_param(dataset_path, epochs, batch_size, dataset_format=0,\n class_id_file=\"char_std_5990.txt\", train_label_name=\"data_train.txt\",\n val_label_name=\"data_test.txt\",sub_img_folder=\"images\", max_label_length=10,\n img_height=32, img_weight=280):\n config = TrainConfig()\n if dataset_format == 0:\n config = SynthtextConfig()\n config.BATCH_SIZE = batch_size\n config.MAX_LABEL_LENGTH = max_label_length\n config.IMG_H = img_height\n config.IMG_W = img_weight\n\n config.display()\n\n # class_id_file = \"char_std_5990.txt\"\n # train_label_name = \"data_train.txt\"\n # val_label_name = \"data_test.txt\"\n # sub_img_folder = \"images\"\n\n data = DataSetSynthtext()\n data.load_data(class_id_file, dataset_path, train_label_name, subset=sub_img_folder)\n # label_list = data.load_instance(33)\n # print(label_list)\n data.prepare()\n\n data_val = DataSetSynthtext()\n data_val.load_data(class_id_file, dataset_path, val_label_name, subset=sub_img_folder)\n data_val.prepare()\n\n print(\"Train Image Count: {}\".format(len(data.image_ids)), data.num_images)\n print(\"Train Class Count: {}\".format(data.num_classes))\n\n print(\"Val Image Count: {}\".format(len(data_val.image_ids)), data_val.num_images)\n print(\"Val Class Count: {}\".format(data_val.num_classes))\n\n # for i, info in enumerate(data.class_info):\n # print(\"{:3}. {:50}\".format(i, info['name']))\n\n model = DensenetModel(config=config, model_dir=\"./models\")\n model.train(train_dataset=data, val_dataset=data_val, epochs=epochs)\n" }, { "alpha_fraction": 0.5306122303009033, "alphanum_fraction": 0.5368916988372803, "avg_line_length": 23.5, "blob_id": "5ba411f54314fdd2fca555d478c5d82093e1fb45", "content_id": "bdbb41e10f625fafc802d25501f30d17518ec52f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 687, "license_type": "permissive", "max_line_length": 58, "num_lines": 26, "path": "/chinese_ocr/utils/file_read.py", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\ndef read_line(file_path, encoding='utf-8'):\n char_list=[]\n try:\n with open(file_path, 'r', encoding=encoding) as f:\n char_list= f.readlines()\n except FileNotFoundError:\n print('找不到指定的文件!')\n except LookupError:\n print('指定了未知的编码!')\n except UnicodeDecodeError:\n print('读取文件时解码错误!')\n return char_list\n\ndef read_file(filename):\n res = []\n with open(filename, 'r') as f:\n lines = f.readlines()\n for i in lines:\n res.append(i.strip())\n dic = {}\n for i in res:\n p = i.split(' ')\n dic[p[0]] = p[1:]\n return dic\n" }, { "alpha_fraction": 0.6997900605201721, "alphanum_fraction": 0.714835524559021, "avg_line_length": 29.74193572998047, "blob_id": "e6e3eb06514cef8bccd6b56190563f7c27937173", "content_id": "ffc468d8e217a1def4a26d8bfb71dfb9428f6036", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2882, "license_type": "permissive", "max_line_length": 120, "num_lines": 93, "path": "/chinese_ocr/densenet_common/change_h52tensorflow.py", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "#-- coding:utf-8 --\n\nfrom keras import backend as K\nimport os\nimport shutil\nfrom imp import reload\nimport tensorflow as tf\nfrom . import keys\nfrom . import densenet\nfrom keras.layers import Input\nfrom keras.models import Model\n\nfrom keras.utils import multi_gpu_model\n\n\nK.set_learning_phase(0)\n\ndef preprocess_image(im):\n #等比例将图像高度缩放到32\n # im=tf.image.rgb_to_grayscale(im)\n im_shape = tf.shape(im)\n h=im_shape[1]\n w=im_shape[2]\n height=tf.constant(32,tf.int32)\n scale = tf.divide(tf.cast(h,tf.float32),32)\n width = tf.divide(tf.cast(w,tf.float32),scale)\n width =tf.cast(width,tf.int32)\n resize_image = tf.image.resize_images(im, [height,width], method=tf.image.ResizeMethod.BILINEAR, align_corners=True)\n resize_image = tf.cast(resize_image, tf.float32) / 255 - 0.5\n width = tf.reshape(width, [1])\n height = tf.reshape(height, [1])\n im_info = tf.concat([height, width], 0)\n im_info = tf.concat([im_info, [1]], 0)\n im_info = tf.reshape(im_info, [1, 3])\n im_info = tf.cast(im_info, tf.float32)\n return resize_image,im_info\n\n\nreload(densenet)\n\ncharacters = keys.alphabet[:]\ncharacters = characters[1:] + u'卍'\nnclass = len(characters)\ninput = Input(shape=(32, None, 1), name='the_input')\n\n# input = Input(tensor=resize_image)\n\n\ny_pred= densenet.dense_cnn(input, nclass)\nbasemodel = Model(inputs=input, outputs=y_pred)\nmodelPath = os.path.join(os.getcwd(), './models/weights_densenet.h5')\n\n# basemodel = multi_gpu_model(basemodel, gpus=8)\n\nbasemodel.load_weights(modelPath)\n#model model_mulit_gpu\nexport_path = './model/1/'\nif os.path.exists(export_path):\n shutil.rmtree(export_path)\nversion = 1\npath='model'\nK.set_learning_phase(0)\nif not os.path.exists(path):\n os.mkdir(path)\nexport_path = os.path.join(tf.compat.as_bytes(path),tf.compat.as_bytes(str(version)))\nbuilder = tf.saved_model.builder.SavedModelBuilder(export_path)\nprint('input info:', basemodel.input_names, '---', basemodel.input)\nprint('output info:', basemodel.output_names, '---', basemodel.output)\ninput_tensor = basemodel.input\noutput_tensor=basemodel.output\n\n# tensor_info_input = tf.saved_model.utils.build_tensor_info(raw_image)\n\nmodel_input = tf.saved_model.utils.build_tensor_info(input_tensor)\nmodel_output = tf.saved_model.utils.build_tensor_info(output_tensor)\n\n# im_info_output = tf.saved_model.utils.build_tensor_info(im_info)\n# print('im_info_input tensor shape', im_info.shape)\n\n\nprediction_signature = (\ntf.saved_model.signature_def_utils.build_signature_def(\ninputs={'images': model_input},\noutputs={'prediction': model_output},\nmethod_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME))\n\n\nwith K.get_session() as sess:\n builder.add_meta_graph_and_variables(\n sess=sess, tags=[tf.saved_model.tag_constants.SERVING],\n signature_def_map={'predict_images':prediction_signature,}\n )\n builder.save()" }, { "alpha_fraction": 0.6421350836753845, "alphanum_fraction": 0.646583080291748, "avg_line_length": 27.113636016845703, "blob_id": "1337e878a67d0c4975421592aae7f1f341b5c7f9", "content_id": "d5e5ee49f39f20b6beb369acb26803782c9b04bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2473, "license_type": "permissive", "max_line_length": 102, "num_lines": 88, "path": "/chinese_ocr/tools/ocr_dataset_divide.py", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nimport sys\nimport os\nimport random\nimport argparse\n\nimport numpy as np\n\n\"\"\"\ndataset divide :\ntrain val test\n\"\"\"\n\ndef divide_arr(data, train_percent, val_percent):\n \"\"\"\n divide dataset to train set,val set, test set,\n test_percent = 1 - train_percent - val_percent\n :param data: numpy arr to divide\n :param train_percent: train set percent\n :param val_percent:\n :return: train set,val set, test set\n \"\"\"\n data_size = len(data)\n data = np.array(data)\n\n divide_index_train = int(round(data_size * train_percent))\n print(\"train divide index\", divide_index_train)\n divide_index_val = int(divide_index_train + round(data_size * val_percent))\n print(\"val divide index\", divide_index_val)\n\n indexes = np.array(range(0, data_size))\n\n random.shuffle(indexes)\n\n label_train = indexes[:divide_index_train]\n label_val = indexes[divide_index_train:divide_index_val]\n label_test = indexes[divide_index_val:data_size]\n\n return data[label_train], data[label_val], data[label_test]\n\n\ndef write_arr_to_file(data, dest_file_dir, dest_file_name=\"result.txt\"):\n if os.path.isdir(dest_file_dir):\n with open(os.path.join(dest_file_dir, dest_file_name), \"w\", encoding=\"utf-8\") as f:\n for i in data:\n f.write(i + \"\\n\")\n else:\n print(\"dest dir is not dir\")\n\n\n\n\ndef main(args):\n # lable_dir = \"F:\\\\code\\\\other\\\\TextRecognitionDataGenerator\\\\TextRecognitionDataGenerator\\\\dicts\"\n # input_file_name = \"label_id.txt\"\n\n lable_dir = args.lable_dir\n input_file_name = args.input_file_name\n\n data_list = []\n with open(os.path.join(lable_dir, input_file_name), \"r\", encoding=\"utf-8\") as f:\n for line in f:\n line = line.strip()\n data_list.append(line)\n\n data_list = np.array(data_list)\n\n print(data_list)\n\n label_train, label_val, label_test = divide_arr(data_list, 0.8, 0.1)\n\n write_arr_to_file(label_train, lable_dir, \"label_train.txt\")\n write_arr_to_file(label_val, lable_dir, \"label_val.txt\")\n write_arr_to_file(label_test, lable_dir, \"label_test.txt\")\n\n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n\n parser.add_argument('lable_dir', type=str, help='Directory with label file.')\n parser.add_argument('input_file_name', type=str, help='file name.')\n\n return parser.parse_args(argv)\n\n\nif __name__ == '__main__':\n print(\"args:\",sys.argv[1:])\n main(parse_arguments(sys.argv[1:]))" }, { "alpha_fraction": 0.5748772621154785, "alphanum_fraction": 0.5906301140785217, "avg_line_length": 36.599998474121094, "blob_id": "5810727d9372ed93947e080adfb963c09b6212de", "content_id": "68d9ac99c9a7060803217aa0d03ab663417f8c5f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4888, "license_type": "permissive", "max_line_length": 172, "num_lines": 130, "path": "/chinese_ocr/densenet_common/densenet_model.py", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "import multiprocessing\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport keras\nimport keras.backend as K\nimport keras.layers as KL\nimport keras.engine as KE\nimport keras.models as KM\nfrom keras.layers.core import Lambda\nfrom keras.models import Model\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, LearningRateScheduler, TensorBoard\nfrom PIL import Image\n\nfrom chinese_ocr.train.train import random_uniform_num, get_session, get_model\n\n\n\n# from config.train_config import DATASET_SOURCE1\n\ndef data_generator(dataset, config, maxlabellength=10):\n # batch_size=128,\n # imagesize=(32, 280)\n batch_size = config.BATCH_SIZE\n imagesize = (config.IMG_H, config.IMG_W)\n\n _imagefile = [info[\"id\"] for info in dataset.image_info]\n x = np.zeros((batch_size, imagesize[0], imagesize[1], 1), dtype=np.float)\n labels = np.ones([batch_size, maxlabellength]) * 10000\n input_length = np.zeros([batch_size, 1])\n label_length = np.zeros([batch_size, 1])\n\n r_n = random_uniform_num(dataset.num_images)\n _imagefile = np.array(_imagefile)\n while 1:\n shufimagefile = dataset._image_ids[r_n.get(batch_size)]\n\n # print('shufimagefile:', shufimagefile)\n image_paths =[]\n for i, j in enumerate(shufimagefile):\n # image_id = dataset.map_source_image_id(\"Synthtext\" + '.' + j)\n image_id = j\n\n image_path = dataset.image_info[image_id][\"path\"]\n image_paths.append(image_path)\n img1 = Image.open(image_path).convert('L')\n img = np.array(img1, 'f') / 255.0 - 0.5\n\n x[i] = np.expand_dims(img, axis=2)\n # print('imag:shape', img.shape)\n str = dataset.image_info[image_id][\"label_list\"]\n label_length[i] = len(str)\n\n if (len(str) <= 0):\n print(\"len < 0\", j)\n input_length[i] = imagesize[1] // 8\n labels[i, :len(str)] = [int(k) - 1 for k in str]\n\n inputs = {'the_input': x,\n 'the_labels': labels,\n 'input_length': input_length,\n 'label_length': label_length,\n 'img_paths': image_paths,\n }\n outputs = {'ctc': np.zeros([batch_size])}\n yield (inputs, outputs)\n\n\nclass DensenetModel:\n def __init__(self, config, model_dir):\n \"\"\"\n config: A Sub-class of the Config class\n model_dir: Directory to save training logs and trained weights\n \"\"\"\n self.config = config\n self.model_dir = model_dir\n\n\n\n def train(self, train_dataset, val_dataset, epochs, learning_rate=None,\n pre_train_path=None, checkpoint_path=None, no_augmentation_sources=None):\n assert train_dataset.num_classes == val_dataset.num_classes\n\n batch_size = self.config.BATCH_SIZE\n img_h = self.config.IMG_H\n\n nclass = train_dataset.num_classes\n\n K.set_session(get_session())\n # reload(densenet)\n basemodel, model = get_model(img_h, nclass)\n\n modelPath = './models/pretrain_model/keras.h5'\n if os.path.exists(modelPath):\n print(\"Loading model weights...\")\n basemodel.load_weights(modelPath)\n print('done!')\n train_loader = data_generator(train_dataset, config=self.config)\n\n test_loader = data_generator(val_dataset, config=self.config)\n\n # checkpoint = ModelCheckpoint(filepath='./models/weights_densenet-{epoch:02d}-{val_loss:.2f}.h5', monitor='val_loss', save_best_only=False, save_weights_only=True)\n checkpoint = ModelCheckpoint(filepath='./models/weights_densenet-{epoch:02d}-{val_loss:.2f}.h5',\n monitor='val_loss', save_best_only=False)\n\n # lr_schedule = lambda epoch: 0.0005 * 0.4 ** epoch\n # learning_rate = np.array([lr_schedule(i) for i in range(10)])\n # changelr = LearningRateScheduler(lambda epoch: float(learning_rate[epoch]))\n\n changelr = LearningRateScheduler(lambda epoch: 0.001 * 0.4 ** (epoch // 2))\n\n earlystop = EarlyStopping(monitor='val_loss', patience=10, verbose=1)\n tensorboard = TensorBoard(log_dir='./models/logs', write_graph=True)\n\n\n\n\n\n print('-----------Start training-----------')\n history = model.fit_generator(train_loader,\n # steps_per_epoch = 3607567 // batch_size,\n steps_per_epoch=train_dataset.num_images // batch_size,\n epochs=epochs,\n initial_epoch=0,\n validation_data=test_loader,\n # validation_steps = 36440 // batch_size,\n validation_steps=val_dataset.num_images // batch_size,\n callbacks=[checkpoint, earlystop, changelr, tensorboard])\n\n print(history)\n" }, { "alpha_fraction": 0.5749129056930542, "alphanum_fraction": 0.5897212624549866, "avg_line_length": 27.700000762939453, "blob_id": "de544a633069139b1af2a37f77327b40b1a74c42", "content_id": "0a7045aa512c52b637000e7a0b95cba2ad3d0f5a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1172, "license_type": "permissive", "max_line_length": 102, "num_lines": 40, "path": "/chinese_ocr/densenet_common/key_common.py", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\n把dict 文件转化成 一行字典\n\"\"\"\nimport os\n\nfrom chinese_ocr.utils.file_read import read_line\nfrom densenet_common import keys\n\n\nclass DictKey:\n def __init__(self, dict_file_path=None):\n self.keys = self.init_key(dict_file_path)\n\n def init_key(self, dict_path):\n if dict_path:\n char_set = read_line(dict_path, encoding='utf-8')\n assert len(char_set) > 0\n char_set_temp = []\n for i, ch in enumerate(char_set):\n one_word = ch.strip('\\n')\n char_set_temp.append(one_word)\n\n char_set_line = ''.join(char_set_temp[1:] + ['卍'])\n return char_set_line\n else:\n characters = keys.alphabet[:]\n characters = characters[1:] + u'卍'\n return characters\n\n# a = DictKey(\"/media/chenhao/study/code/work/github/chinese_ocr/chinese_ocr/train/char_std_5990.txt\")\n# print(a.keys)\n#\n# b = DictKey()\n# print(b.keys)\n#\n# c = DictKey(\"/media/chenhao/study/code/work/github/chinese_ocr/chinese_ocr/train/char_7476.txt\")\n# c = DictKey(\"chinese_ocr/train/char_7476.txt\")\n# print(os.getcwd())\n# print(c.keys)\n" }, { "alpha_fraction": 0.6832203269004822, "alphanum_fraction": 0.7042372822761536, "avg_line_length": 25.554054260253906, "blob_id": "cfa73fc5da7fd90096b61bc413625cfa60b4fc95", "content_id": "4744278bf1eabd9cfdb1aa6853bb4f2a7cfe493d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5944, "license_type": "permissive", "max_line_length": 116, "num_lines": 222, "path": "/chinese_ocr/7476h5_modelfile_to_pb.py", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n# bing1 \n\n# 2019/8/26 \n\n# 13:52 \n\"\"\"\nMIT License\n\nCopyright (c) 2019 Hyman Chen\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n\n\n把用7476字典数据集训练的模型使用saved_model存成pb文件\n\"\"\"\n\n\n\nfrom keras import backend as K\nimport os\nimport shutil\nfrom imp import reload\nimport tensorflow as tf\nimport cv2\nfrom PIL import Image\nimport numpy as np\n\n\nimport matplotlib.pyplot as plt\nfrom keras.layers import Input\nfrom keras.models import Model\nfrom keras.utils import multi_gpu_model\n\nfrom chinese_ocr.train.train import random_uniform_num, get_session, get_model\nfrom chinese_ocr.densenet_common import densenet\nfrom chinese_ocr.densenet_common.dataset_format import DataSetSynthtext\n\n\ndef run_func(model,img):\n return model.predict(img)\n\ndef deal_img(img):\n width, height = img.size[0], img.size[1]\n print(width, height)\n scale = height * 1.0 / 32\n width = int(width / scale)\n print(width, 32)\n\n img = img.resize([width, 32], Image.ANTIALIAS)\n\n plt.imshow(img)\n plt.show()\n\n img = np.array(img).astype(np.float32) / 255.0 - 0.5\n\n X = img.reshape([1, 32, width, 1])\n\n return X\n\n # y_pred = self.run_func(X)\n # y_pred = y_pred[:, :, :]\n #\n # return y_pred\n\ndef decode(pred, characters):\n char_list = []\n pred_text = pred.argmax(axis=2)[0]\n for i in range(len(pred_text)):\n if pred_text[i] != nclass - 1 and (\n (not (i > 0 and pred_text[i] == pred_text[i - 1])) or (i > 1 and pred_text[i] == pred_text[i - 2])):\n print(pred_text[i])\n char_list.append(characters[pred_text[i]])\n return u''.join(char_list)\n\ndef predict(img):\n \"\"\"\n the method which to use\n :param img:\n :return: chinese character that in the image\n \"\"\"\n\n y_pred = deal_img(img)\n\n y_pred = y_pred[:, :, :]\n\n # out = K.get_value(K.ctc_decode(y_pred, input_length=np.ones(y_pred.shape[0]) * y_pred.shape[1])[0][0])[:, :]\n # out = u''.join([characters[x] for x in out[0]])\n\n # out = decode(y_pred)\n # return out\n\n\n\nreload(densenet)\nK.set_learning_phase(0)\n\n\ndataset_path=\"/media/chenhao/study/code/other/out\"\n\nclass_id_file=\"char_7476.txt\"\ntrain_label_name=\"label_train.txt\"\nval_label_name=\"label_val.txt\"\ndataset_format= 0\nsub_img_folder=\"default\"\n\ndata = DataSetSynthtext()\ndata.load_data(class_id_file, dataset_path, train_label_name, subset=sub_img_folder)\n# label_list = data.load_instance(33)\n# print(label_list)\ndata.prepare()\n\n\nnclass = data.num_classes\nchar_set_line = data.char_set_line\nprint(\"class num:\",nclass)\nprint(\"char_set_line:\", char_set_line)\n\ninput = Input(shape=(32, None, 1), name='the_input')\n# input = Input(tensor=resize_image)\ny_pred= densenet.dense_cnn(input, nclass)\nbasemodel = Model(inputs=input, outputs=y_pred)\n\nmodelPath = '/media/chenhao/study/code/work/github/chinese_ocr/chinese_ocr/models/weights_densenet-12-0.98.h5'\n# basemodel = multi_gpu_model(basemodel, gpus=8)\nprint(modelPath)\nw = basemodel.get_weights()[2]\nprint(w)\n\nbasemodel.load_weights(modelPath)\nw = basemodel.get_weights()[2]\nprint(w)\n\n\n''''''\n\n# predict \npath = \"test_images/line.jpg\"\n\npath = \"test_images/line.jpg\"\npath = \"test_images/20456062_1743140291.jpg\"\npath = \"test_images/aaa.png\"\npath = \"test_images/00582036.jpg\"\n# path = \"test_images/00000028.jpg\"\n# path = \"test_images/00349227.jpg\"\n\nimg = cv2.imread(path) ##GBR\n# 单行识别 one line\npartImg = Image.fromarray(img)\n# text2 = recognize(partImg.convert('L'))\n\n# text2 = recognize()\n\nX = deal_img(partImg.convert('L'))\ny_pred = basemodel.predict(X)\n\ny_pred = y_pred[:, :, :]\n\nresult = decode(y_pred, char_set_line)\n\nprint(result)\n\n\n\n\n\n# output\n\nexport_path = './model/2/'\nif os.path.exists(export_path):\n shutil.rmtree(export_path)\nversion = 2\npath='model'\nK.set_learning_phase(0)\nif not os.path.exists(path):\n os.mkdir(path)\nexport_path = os.path.join(tf.compat.as_bytes(path),tf.compat.as_bytes(str(version)))\nbuilder = tf.saved_model.builder.SavedModelBuilder(export_path)\nprint('input info:', basemodel.input_names, '---', basemodel.input)\nprint('output info:', basemodel.output_names, '---', basemodel.output)\ninput_tensor = basemodel.input\noutput_tensor=basemodel.output\n\n# tensor_info_input = tf.saved_model.utils.build_tensor_info(raw_image)\n\nmodel_input = tf.saved_model.utils.build_tensor_info(input_tensor)\nmodel_output = tf.saved_model.utils.build_tensor_info(output_tensor)\n\n# im_info_output = tf.saved_model.utils.build_tensor_info(im_info)\n# print('im_info_input tensor shape', im_info.shape)\n\n\nprediction_signature = (\ntf.saved_model.signature_def_utils.build_signature_def(\ninputs={'images': model_input},\noutputs={'prediction': model_output},\nmethod_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME))\n\n\nwith K.get_session() as sess:\n builder.add_meta_graph_and_variables(\n sess=sess, tags=[tf.saved_model.tag_constants.SERVING],\n signature_def_map={'predict_images':prediction_signature,}\n )\n builder.save()\n \n" }, { "alpha_fraction": 0.6845637559890747, "alphanum_fraction": 0.7651006579399109, "avg_line_length": 28.799999237060547, "blob_id": "eb88e8f0882d7db85ba9505ffdc436c7db0a85a9", "content_id": "579d6a3170579141cf1afc8e13c2ffc04dc7f473", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 149, "license_type": "permissive", "max_line_length": 78, "num_lines": 5, "path": "/chinese_ocr/global_obj.py", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "from predict_tf_tool import DensenetOcr\n\n\nocr_predict = DensenetOcr()\nocr_predict_7476= DensenetOcr(\"./train/char_7476.txt\",model_name=\"7476_model\")\n" }, { "alpha_fraction": 0.5665102005004883, "alphanum_fraction": 0.59272301197052, "avg_line_length": 29.795181274414062, "blob_id": "1ad863ea44f0ac9e679e74597311f23e459cdf46", "content_id": "cdeadc183be4b885f9149114789af83735b1af03", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2690, "license_type": "permissive", "max_line_length": 89, "num_lines": 83, "path": "/chinese_ocr/densenet_common/dataset_format.py", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "# -*-coding:utf-8 -*-\n\"\"\"\n此模块用于预定义 若干 数据集格式及对应的处理方式\n\n继承 DataSet 类,按格式解析加载数据\n\"\"\"\nimport os\n\nfrom chinese_ocr.densenet_common.model_utils import Dataset\nfrom chinese_ocr.utils.file_read import read_file\n\n# from config.train_config import DATASET_SOURCE1\nfrom chinese_ocr.utils.file_read import read_line\n\nsource = \"Synthtext\"\n\n\nclass DataSetSynthtext(Dataset):\n \"\"\"\n 格式 0 ,\n 一个定义所有字符集的文件\n char_std_5990.txt\n 数据集路径 一个标签文件,默认文件名\n 20456062_1743140291.jpg 153 432 950 150 65 899 115 7 97 49\n \"\"\"\n\n def load_data(self, class_file_name, data_set_dir, label_file_name, subset=\"images\"):\n # 'char_std_5990.txt' class_id_file, \"./\", \"data_train.txt\"\n class_file_path = os.path.join(data_set_dir, class_file_name)\n char_set = read_line(class_file_path, encoding='utf-8')\n char_set_temp = []\n for i, ch in enumerate(char_set):\n one_word = ch.strip('\\n')\n self.add_class(source, i, one_word)\n char_set_temp.append(one_word)\n\n char_set_line = ''.join(char_set_temp[1:] + ['卍'])\n self.char_set_line = char_set_line\n\n # char_set = ''.join([ch.strip('\\n') for ch in char_set][1:] + ['卍'])\n # print(char_set)\n print(char_set_line)\n nclass = len(char_set_line)\n print(nclass)\n\n #\n\n annotions_file = os.path.join(data_set_dir, label_file_name)\n\n\n images_path = os.path.join(data_set_dir, subset)\n\n image_label = read_file(annotions_file)\n\n for key in image_label:\n self.add_image(source,\n key,\n os.path.join(images_path, key),\n nclass=nclass,\n label_list=image_label[key])\n\n def load_instance(self, image_id):\n\n # If not a DATASET_SOURCE1 dataset image, delegate to parent class.\n image_info = self.image_info[image_id]\n if image_info[\"source\"] != source:\n return super(self.__class__, self).load_instance(image_id)\n\n info = self.image_info[image_id]\n print(info)\n return info['label_list']\n\n# data = DataSetSynthtext()\n# data.load_data(\"../train/char_std_5990.txt\", \"../train\", \"data_train.txt\")\n# print(\"done\")\n# label_list = data.load_instance(33)\n# print(label_list)\n# data.prepare()\n#\n# print(\"Train Image Count: {}\".format(len(data.image_ids)), data.num_images)\n# print(\"Train Class Count: {}\".format(data.num_classes))\n# # for i, info in enumerate(data.class_info):\n# # print(\"{:3}. {:50}\".format(i, info['name']))\n" }, { "alpha_fraction": 0.5351729393005371, "alphanum_fraction": 0.5534395575523376, "avg_line_length": 26.089473724365234, "blob_id": "55f22a4d0481fe0d2aff3879369923d0ec178072", "content_id": "6528bd48c464154b900dd3a9362c9dff481d7f3f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5146, "license_type": "permissive", "max_line_length": 98, "num_lines": 190, "path": "/chinese_ocr/utils/visualize.py", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport random\nimport itertools\nimport colorsys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import patches, lines\nfrom matplotlib.patches import Polygon\nimport IPython.display\n\n\n\ndef random_colors(N, bright=True):\n \"\"\"\n Generate random colors.\n To get visually distinct colors, generate them in HSV space then\n convert to RGB.\n \"\"\"\n brightness = 1.0 if bright else 0.7\n hsv = [(i / N, 1, brightness) for i in range(N)]\n colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))\n random.shuffle(colors)\n return colors\n\n\ndef drow_boxes(image, title='', boxes=None, ax=None, visibilities=None):\n\n assert boxes is not None\n N = boxes.shape[0]\n\n # Matplotlib Axis\n if not ax:\n _, ax = plt.subplots(1, figsize=(12, 12))\n\n # Generate random colors\n colors = random_colors(N)\n\n # Show area outside image boundaries.\n margin = image.shape[0] // 10\n ax.set_ylim(image.shape[0] + margin, -margin)\n ax.set_xlim(-margin, image.shape[1] + margin)\n ax.axis('off')\n\n ax.set_title(title)\n\n masked_image = image.astype(np.uint32).copy()\n\n for i in range(N):\n # Box visibility\n visibility = visibilities[i] if visibilities is not None else 1\n if visibility == 0:\n color = \"gray\"\n style = \"dotted\"\n alpha = 0.5\n elif visibility == 1:\n color = colors[i]\n style = \"dotted\"\n alpha = 1\n elif visibility == 2:\n color = colors[i]\n style = \"solid\"\n alpha = 1\n\n # Boxes\n if boxes is not None:\n if not np.any(boxes[i]):\n # Skip this instance. Has no bbox. Likely lost in cropping.\n continue\n y1, x1, y2, x2 = boxes[i]\n p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2,\n alpha=alpha, linestyle=style,\n edgecolor=color, facecolor='none')\n\n\n ax.add_patch(p)\n\n ax.imshow(masked_image.astype(np.uint8))\n\n\ndef drow_boxes_degree(image, title='', boxes=None, ax=None, visibilities=None,degree=0.0):\n\n assert boxes is not None\n N = boxes.shape[0]\n\n # Matplotlib Axis\n if not ax:\n _, ax = plt.subplots(1, figsize=(12, 12))\n\n # Generate random colors\n colors = random_colors(N)\n\n # Show area outside image boundaries.\n margin = image.shape[0] // 10\n ax.set_ylim(image.shape[0] + margin, -margin)\n ax.set_xlim(-margin, image.shape[1] + margin)\n ax.axis('off')\n\n ax.set_title(title)\n\n masked_image = image.astype(np.uint32).copy()\n\n for i in range(N):\n # Box visibility\n visibility = visibilities[i] if visibilities is not None else 1\n if visibility == 0:\n color = \"gray\"\n style = \"dotted\"\n alpha = 0.5\n elif visibility == 1:\n color = colors[i]\n style = \"dotted\"\n alpha = 1\n elif visibility == 2:\n color = colors[i]\n style = \"solid\"\n alpha = 1\n\n # Boxes\n if boxes is not None:\n if not np.any(boxes[i]):\n # Skip this instance. Has no bbox. Likely lost in cropping.\n continue\n y1, x1, y2, x2 = boxes[i]\n p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2,\n alpha=degree, linestyle=style,\n edgecolor=color, facecolor='none')\n\n\n ax.add_patch(p)\n\n ax.imshow(masked_image.astype(np.uint8))\n\n\ndef drow_polygon(image, title='', boxes=None, ax=None, visibilities=None):\n \"\"\"\n\n :param image:\n :param title:\n :param boxes: (M,N,2) the line number,N is the number of dot, (x,y)\n :param ax:\n :param visibilities: int array,\n :return:\n \"\"\"\n assert boxes is not None\n N = boxes.shape[0]\n\n # Matplotlib Axis\n if not ax:\n _, ax = plt.subplots(1, figsize=(12, 12))\n\n # Generate random colors\n colors = random_colors(N)\n\n # Show area outside image boundaries.\n margin = image.shape[0] // 10\n ax.set_ylim(image.shape[0] + margin, -margin)\n ax.set_xlim(-margin, image.shape[1] + margin)\n ax.axis('off')\n\n ax.set_title(title)\n\n masked_image = image.astype(np.uint32).copy()\n\n for i in range(N):\n # Box visibility\n visibility = visibilities[i] if visibilities is not None else 1\n if visibility == 0:\n color = \"gray\"\n style = \"dotted\"\n elif visibility == 1:\n color = colors[i]\n style = \"dotted\"\n elif visibility == 2:\n color = colors[i]\n style = \"solid\"\n\n # Boxes\n if boxes is not None:\n if not np.any(boxes[i]):\n # Skip this instance. Has no bbox. Likely lost in cropping.\n continue\n xy = boxes[i] # xy shape Nx2.\n\n p = patches.Polygon(xy, linewidth=2,linestyle=style,edgecolor=color, facecolor='none')\n\n ax.add_patch(p)\n\n ax.imshow(masked_image.astype(np.uint8))" }, { "alpha_fraction": 0.5043859481811523, "alphanum_fraction": 0.5328947305679321, "avg_line_length": 20.761905670166016, "blob_id": "8a50cd797def2bf1eab6c331b6758ebd78c9074e", "content_id": "b86661c9380b65e69f37b7f8401bb6cca7d90f06", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 470, "license_type": "permissive", "max_line_length": 73, "num_lines": 21, "path": "/chinese_ocr/config/train_config.py", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\n\nclass TrainConfig:\n # 训练图片的宽高\n IMG_H = 32\n IMG_W = 280\n BATCH_SIZE = 50\n MAX_LABEL_LENGTH = 10\n\n\n DATASET_SOURCE1=\"Synthtext\"\n\n\n def display(self):\n \"\"\"Display Configuration values.\"\"\"\n print(\"\\nConfigurations:\")\n for a in dir(self):\n if not a.startswith(\"__\") and not callable(getattr(self, a)):\n print(\"{:30} {}\".format(a, getattr(self, a)))\n print(\"\\n\")" }, { "alpha_fraction": 0.5610010623931885, "alphanum_fraction": 0.5753910541534424, "avg_line_length": 28.788820266723633, "blob_id": "d95d8e2560762bbb5a3718b55c31b067ba08cf6d", "content_id": "8e79539b32b469ed770f8053b81465235e129bbe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4829, "license_type": "permissive", "max_line_length": 120, "num_lines": 161, "path": "/chinese_ocr/predict_tf_tool.py", "repo_name": "znsoftm/chinese_ocr-1", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport argparse\nfrom imp import reload\nfrom PIL import Image\nimport numpy as np\nimport tensorflow as tf\n\n# from densenet_common import keys\nfrom densenet_common import densenet\nfrom densenet_common.key_common import DictKey\nfrom config.use_model_config import inference_config\n\n# model_dir = DENSENET_MODEL_DIR\n\nreload(densenet)\n\n# characters = keys.alphabet[:]\n# characters = characters[1:] + u'卍'\n# nclass = len(characters)\n\n\n\"\"\"\nsignature_def['predict_images']:\nThe given SavedModel SignatureDef contains the following input(s):\ninputs['images'] tensor_info:\n dtype: DT_FLOAT\n shape: (-1, 32, -1, 1)\n name: the_input_2:0\nThe given SavedModel SignatureDef contains the following output(s):\noutputs['prediction'] tensor_info:\n dtype: DT_FLOAT\n shape: (-1, -1, 5990)\n name: out_2/truediv:0\nMethod name is: tensorflow/serving/predict\n\n\"\"\"\n\n\nclass DensenetOcr:\n def __init__(self, class_file_path=None, model_name=\"5990_model\"):\n dk = DictKey(class_file_path)\n self.chars = dk.keys\n self.class_num = len(self.chars)\n self.config = inference_config[model_name]\n\n self.run_func = self.loadmodel()\n\n def loadmodel(self):\n with tf.Graph().as_default():\n sess = tf.Session()\n with sess.as_default():\n return self.run_lamada(sess)\n\n def run_lamada(self, sess):\n print(\"loading ocr model from \" + self.config.DENSENET_MODEL_DIR + \"...............\")\n metagraph_def = tf.saved_model.loader.load(\n sess, [tf.saved_model.tag_constants.SERVING], self.config.DENSENET_MODEL_DIR)\n # print(metagraph_def)\n\n signature_def = metagraph_def.signature_def[\n \"predict_images\"]\n input_tensor = sess.graph.get_tensor_by_name(\n signature_def.inputs['images'].name)\n output_tensor = sess.graph.get_tensor_by_name(\n signature_def.outputs['prediction'].name)\n\n s1, s2, s3 = output_tensor.shape\n assert s3 == self.class_num, \"model classnum isn't equal dict class num\"\n\n run_func = lambda images: output_tensor.eval(session=sess, feed_dict={input_tensor: images})\n\n return run_func\n\n def runimg(self, img):\n width, height = img.size[0], img.size[1]\n scale = height * 1.0 / 32\n width = int(width / scale)\n\n img = img.resize([width, 32], Image.ANTIALIAS)\n img = np.array(img).astype(np.float32) / 255.0 - 0.5\n\n X = img.reshape([1, 32, width, 1])\n\n y_pred = self.run_func(X)\n y_pred = y_pred[:, :, :]\n\n return y_pred\n\n def recognize(self, img):\n\n \"\"\"\n the method which to use\n :param img:\n :return: chinese character that in the image\n \"\"\"\n\n y_pred = self.runimg(img)\n y_pred = y_pred[:, :, :]\n\n # out = K.get_value(K.ctc_decode(y_pred, input_length=np.ones(y_pred.shape[0]) * y_pred.shape[1])[0][0])[:, :]\n # out = u''.join([characters[x] for x in out[0]])\n out = self.decode(y_pred)\n\n return out\n\n def decode(self, pred):\n char_list = []\n pred_text = pred.argmax(axis=2)[0]\n for i in range(len(pred_text)):\n if pred_text[i] != self.class_num - 1 and (\n (not (i > 0 and pred_text[i] == pred_text[i - 1])) or (i > 1 and pred_text[i] == pred_text[i - 2])):\n print(pred_text[i])\n char_list.append(self.chars[pred_text[i]])\n return u''.join(char_list)\n\n def img_2_id(self, img):\n \"\"\"\n 把图片文字运算成字符id,方便计算acc 使用\n :param img:\n :return:\n \"\"\"\n y_pred = self.runimg(img)\n y_pred = y_pred[:, :, :]\n\n out = self.decode_to_id(y_pred)\n return out\n\n def decode_to_id(self, pred):\n \"\"\"\n first decode to id ,then to char ,\n only to calculate acc ....you can directly use recognize\n :param pred:\n :return:\n \"\"\"\n id_list = []\n pred_text = pred.argmax(axis=2)[0]\n for i in range(len(pred_text)):\n if pred_text[i] != self.class_num - 1 and (\n (not (i > 0 and pred_text[i] == pred_text[i - 1])) or (i > 1 and pred_text[i] == pred_text[i - 2])):\n id_list.append(pred_text[i])\n return id_list\n\n def id_to_char(self, id_list):\n \"\"\"\n id to char\n :param id_list:\n :return:\n \"\"\"\n char_list = []\n for i in range(len(id_list)):\n char_list.append(self.chars[id_list[i]])\n return u''.join(char_list)\n\n\n\n# a = DensenetOcr(\"/media/chenhao/study/code/work/github/chinese_ocr/chinese_ocr/train/char_7476.txt\")" } ]
18
Tanmoy-Sarkar/NewspaperApp
https://github.com/Tanmoy-Sarkar/NewspaperApp
5dbe2dd209b877f6b0c3e2c5ca5f402455229f24
35f455d6128df959b2eb2543ada8d7844a711295
22e78415f5553289ed3cec38567cbe4964861cac
refs/heads/master
2022-09-11T17:43:39.856907
2020-05-26T17:49:16
2020-05-26T17:49:16
266,339,722
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7199074029922485, "alphanum_fraction": 0.7199074029922485, "avg_line_length": 27.866666793823242, "blob_id": "e36430f41b9f0bb942e94df7d09346c376c2e753", "content_id": "5b137727739ce57ecee8686383bb9448e1f585a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 432, "license_type": "no_license", "max_line_length": 78, "num_lines": 15, "path": "/articles/urls.py", "repo_name": "Tanmoy-Sarkar/NewspaperApp", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom .views import (\n\tArticleListView,\n\tArticleUpdateView,\n\tArticleDeleteView,\n\tArticleDetailView,\n\t)\n\nurlpatterns = [\n\tpath('',ArticleListView.as_view(),name='article_list'),\n\tpath('<int:pk>/edit/',ArticleUpdateView.as_view(),name = 'article_edit'),\n\tpath('<int:pk>/',ArticleDetailView.as_view(),name='article_detail'),\n\tpath('<int:pk>/delete/',ArticleDeleteView.as_view(),name = 'article_delete'),\n\t\n]" }, { "alpha_fraction": 0.781931459903717, "alphanum_fraction": 0.781931459903717, "avg_line_length": 28.227272033691406, "blob_id": "15b2e5825aa12d3b9663b47f5d1cd6d15e8799ba", "content_id": "9f38d28cd8604e9c9c7dcbebd76aab24a4533a1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 642, "license_type": "no_license", "max_line_length": 59, "num_lines": 22, "path": "/articles/views.py", "repo_name": "Tanmoy-Sarkar/NewspaperApp", "src_encoding": "UTF-8", "text": "from django.views.generic import ListView,DetailView\nfrom django.views.generic.edit import UpdateView,DeleteView\nfrom django.urls import reverse_lazy\nfrom .models import Article\n# Create your views here.\nclass ArticleListView(ListView):\n\tmodel = Article\n\ttemplate_name = 'article_list.html'\n\nclass ArticleDetailView(DetailView):\n\tmodel = Article\n\ttemplate_name = 'article_detail.html'\n\nclass ArticleUpdateView(UpdateView):\n\tmodel = Article\n\tfields = ('title','body',)\n\ttemplate_name = 'article_edit.html'\n\nclass ArticleDeleteView(DeleteView):\n\tmodel = Article\n\ttemplate_name = 'article_delete.html'\n\tsuccess_url = reverse_lazy('article_list')" } ]
2
LeeCheer00/Keras
https://github.com/LeeCheer00/Keras
a63f82eb8840aaff56c03f1ff6c930e827066f51
249115989f400b1697c6ef1a274d705f8e7f7512
2c71c8906505e13ce5cf739509b0e0a5174e65e5
refs/heads/master
2020-03-25T13:58:35.028713
2018-09-04T22:16:28
2018-09-04T22:16:28
143,849,786
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49539169669151306, "alphanum_fraction": 0.5351382493972778, "avg_line_length": 34.38775634765625, "blob_id": "7d151ec58384282e8a8476edefbf31144b2544f8", "content_id": "54bc0ee51d303d8dd9a27d422c641a82936b341f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1736, "license_type": "no_license", "max_line_length": 113, "num_lines": 49, "path": "/3Dataface.py", "repo_name": "LeeCheer00/Keras", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding=utf-8\nimport cv2\nimport sys\n\nfrom PIL import Image\n\ndef CatchPICFromVideo(window_name, camera_idx, catch_pic_num, path_name):\n cv2.nameWindow(window_name)\n cap =cv2.VideoCapture(camera_idx)\n classifier = cv2.CascadeClassifier(\"/usr/local/share/OpenCV/haarcascades/haarcascades_frontalface_alt2.xml\")\n color = (0, 255, 0)\n num = 0\n while cap.isOpened():\n ok, frame = cap.read()\n if not ok:\n break\n grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faceRects = classifier.detectMultiScale(grey, scaleFactor = 1.2, minNeighbors = 3, minSize = (32, 32))\n if len(faceRects) > 0:\n for faceRect in faceRects:\n x, y, w, h = faceRect \n img_name = '%s/%d.jpg'%(path_name, num)\n image = frame[y - 10: y + h + 10, x - 10: x + w + 10]\n cv2.imwrite(img_name, image) \n num += 1 \n if num > (catch_pic_num):\n break\n cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2)\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(frame, 'num:%d' % (num), (x + 30, y + 30), font, 1, (255, 0, 255), 4)\n\n\n if num > (catch_pic_num):break\n cv2.imshow(window_name, frame)\n c = cv2.waitKey(10)\n if c & 0xFF == ord('q'):\n break\n\n\n cap.release()\n cv2.destroyAllWindows()\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 4:\n print(\"Usage:%s camera_id face_num_max path_name\\r\\n\" % (sys.argv[0]))\n else:\n CatchPICFromVideo(\"Screen shot for the face Collection\", int(sys.argv[1], int(sys.argv[2], sys.argv[3])))\n\n\n" }, { "alpha_fraction": 0.6008272767066956, "alphanum_fraction": 0.6308169364929199, "avg_line_length": 37.68000030517578, "blob_id": "1862e12611240d695dd94e9402be37ea4ca3c620", "content_id": "f063daff100727d6ff63bcab70f1473a77819f14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 967, "license_type": "no_license", "max_line_length": 183, "num_lines": 25, "path": "/README.md", "repo_name": "LeeCheer00/Keras", "src_encoding": "UTF-8", "text": "Two persons recognition use keras, train model and deploy.\n==========================================================\nTwo folders.\n-----------\n![dataset](2.png)\nOne model.\n-----------\n![model](3.png)\nAccuracy.\n--------------------\n![screenshot](1.png)\nTest Window.\n-----------------------\n![upload](kerastest.png)\n\n\nRun it!\n-------\n* File1: `python 1realtimev.py 0 `#opencv open the webcam and show it in the window, Para 0 is camera's id.\n* File2: `python 2facezone.py 0 `#Recognize the face zone.\n* File3: `python 3dataface.py 0 1000 /path/to/your/data/folder/ `# 0 1000 is the number of picture we cut from webcam, /path/to/you/data/folder/ is the directory we store our photoes.\n* File4: `python load_face_dataset.py `#load the dataset to memoery.\n* File5: `python 5facetrainusekears.py `#save the model to model directory.\n* File6: `python evaluate.py `# Use the model we saved, and output the accuracy.\n* File7: `python 7recognition.py 0 `# The final product.\n" } ]
2
subayadhav/ns
https://github.com/subayadhav/ns
897e01ce6bd8d2b3a48c5e78f0aa86454591612e
3d4d512c7ff09db3aeb327cc2e13ee3fff27f23d
151cf3ff61058c9bbb18923fedcae93d094eca1e
refs/heads/master
2020-05-31T10:24:05.394378
2019-06-04T16:39:21
2019-06-04T16:39:21
190,239,922
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5180723071098328, "alphanum_fraction": 0.5421686768531799, "avg_line_length": 10.857142448425293, "blob_id": "4c6174f6adbfb950c134acb71ec728b29ae2da92", "content_id": "db9310775235a4c32ea88e9f37d070a79b491a83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 83, "license_type": "no_license", "max_line_length": 20, "num_lines": 7, "path": "/fiboo.py", "repo_name": "subayadhav/ns", "src_encoding": "UTF-8", "text": "num=int(input())\na=0\nb=1\nfor i in range(num):\n print(b,end=' ')\n c=b+a\n a,b=b,c\n" } ]
1
hajix/speaker-embedding-service
https://github.com/hajix/speaker-embedding-service
07735ffb32ba6e1c47681203a0e3b3a431f17bbd
c78d62dd4420ea13748e6b2c9adb0c1e37cc3a6b
e41cba8c41164eae3ed0f22498b07d96610fff69
refs/heads/main
2023-04-09T16:08:29.243049
2023-02-14T11:13:52
2023-02-14T11:13:52
328,502,464
0
2
null
2021-01-10T23:41:32
2021-04-25T19:55:21
2023-02-14T11:13:53
Python
[ { "alpha_fraction": 0.7361477613449097, "alphanum_fraction": 0.7440633177757263, "avg_line_length": 41.11111068725586, "blob_id": "5b3d28c4bc31a0496bda514e964f36b6af41c1ce", "content_id": "e15c77a6b46042421c03ab98d306c2c21ae0110d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 379, "license_type": "no_license", "max_line_length": 119, "num_lines": 9, "path": "/create_docker_GPU.sh", "repo_name": "hajix/speaker-embedding-service", "src_encoding": "UTF-8", "text": "# check if model exists\n[ ! -d \"speaker_embedding/resources\" ] && mkdir speaker_embedding/resources\nif [ -f \"speaker_embedding/resources/baseline_v2_ap.model\" ]; then\n echo \"speaker embedding model exists.\"\nelse\n wget http://www.robots.ox.ac.uk/~joon/data/baseline_v2_ap.model -O speaker_embedding/resources/baseline_v2_ap.model\nfi\n\ndocker build -t speaker-embedding-gpu .\n" }, { "alpha_fraction": 0.5823529362678528, "alphanum_fraction": 0.6764705777168274, "avg_line_length": 27.33333396911621, "blob_id": "5701809a34d0d3b704568a702ed1a3c164237a1f", "content_id": "65c8610b889095779be776819d4e0de041c837d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 170, "license_type": "no_license", "max_line_length": 42, "num_lines": 6, "path": "/run_docker_GPU.sh", "repo_name": "hajix/speaker-embedding-service", "src_encoding": "UTF-8", "text": "# run speaker embedding service\ndocker run -d \\\n --name speaker-embedding-service-gpu \\\n --gpus all \\\n -p 8080-8082:8080-8082 \\\n speaker-embedding-gpu:latest\n" }, { "alpha_fraction": 0.6572580933570862, "alphanum_fraction": 0.6962365508079529, "avg_line_length": 19.66666603088379, "blob_id": "95b0a527b09859785d8232d98a9952be49104cab", "content_id": "79f1071be06bba297050b364cde7a1b3673fbafb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 744, "license_type": "no_license", "max_line_length": 76, "num_lines": 36, "path": "/faiss_index/snippet.py", "repo_name": "hajix/speaker-embedding-service", "src_encoding": "UTF-8", "text": "import base64\nimport json\n\nimport faiss\nimport numpy as np\nfrom tqdm import tqdm\n\nwith open('representation.json') as f:\n data = json.load(f)\n\nids = [i[0].split('/')[1] for i in data]\ndata = np.array(\n [\n np.frombuffer(base64.b64decode(i[1]), dtype=np.float32)\n for i in tqdm(data)\n ]\n)\n\n# embedding dimension\nd = 512\n# for example the number of speakers\nn_list = 1125\n\nquantizer = faiss.IndexFlatIP(d)\nindex = faiss.IndexIVFFlat(quantizer, d, n_list, faiss.METRIC_INNER_PRODUCT)\n\nindex.train(data)\nindex.add(data)\n\n# get top 50 speakers\nsrc_speaker_index = 100\nindex.search(data[src_speaker_index].reshape(-1, 512), 50)\n\n# write and read index\nfaiss.write_index(index, 'index.bin')\nindex = faiss.read_index('index.bin')\n" }, { "alpha_fraction": 0.5746594667434692, "alphanum_fraction": 0.5859676003456116, "avg_line_length": 34.37272644042969, "blob_id": "ae20d07b60f5c98867fe0960a52d0f498f889a89", "content_id": "900fb400448a9d84057495f29637e73648949e80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3891, "license_type": "no_license", "max_line_length": 91, "num_lines": 110, "path": "/speaker_embedding/handler.py", "repo_name": "hajix/speaker-embedding-service", "src_encoding": "UTF-8", "text": "import base64\nimport io\nimport json\nimport os\nimport subprocess\nimport sys\n\nimport ffmpeg\nimport numpy as np\nimport soundfile as sf\nimport torch\nimport torch.nn.functional as F\nfrom ts.torch_handler.base_handler import BaseHandler\n\nsys.path.append('/home/model-server/services/speaker_embedding/voxceleb_trainer')\nfrom SpeakerNet import SpeakerNet\n\nMODEL_PATH = '/home/model-server/services/speaker_embedding/resources/baseline_v2_ap.model'\nCONFIG_PATH = '/home/model-server/services/speaker_embedding/resources/config.json'\n\n\nclass SpeakerEmbeddingHandler(BaseHandler):\n def __init__(self):\n self._context = None\n self.initialized = False\n self.sample_rate = 16000\n\n def initialize(self, context):\n self._context = context\n properties = context.system_properties\n if properties.get(\"gpu_id\") is not None:\n self.device = torch.device(\"cuda:\" + str(properties.get(\"gpu_id\")))\n else:\n self.device = torch.device('cpu')\n with open(CONFIG_PATH) as f:\n kwargs = json.load(f)\n self.model = SpeakerNet(**kwargs)\n self.model.load_state_dict(torch.load(MODEL_PATH, map_location='cpu'))\n self.model.__S__.to(self.device)\n self.model.__L__.to(self.device)\n self.model.eval()\n self.initialized = True\n\n def convert_audio_to_wav(self, audio_content):\n args = (\n ffmpeg\n .input('pipe:')\n .output(\n 'pipe:',\n format='wav',\n acodec='pcm_s16le',\n ac=1,\n ar=self.sample_rate\n )\n .get_args()\n )\n ffmpeg_process = subprocess.Popen(\n ['ffmpeg'] + args,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.DEVNULL\n )\n wav_content = ffmpeg_process.communicate(input=audio_content)[0]\n wav_content = io.BytesIO(wav_content)\n ffmpeg_process.kill()\n return wav_content\n \n def load_wav(self, filename, max_frames=400):\n wav_content = self.convert_audio_to_wav(filename)\n audio, _ = sf.read(wav_content)\n segment_size = max_frames * 160 + 240\n print(f'segment_size: {segment_size}')\n audio_size = audio.shape[0]\n print(f'audio_size-before: {audio_size}')\n if audio_size <= segment_size:\n print('shortage')\n shortage = segment_size - audio_size\n audio = np.pad(audio, (0, shortage), 'wrap')\n audio_size = audio.shape[0]\n print(f'audio_size-after: {audio_size}')\n num_eval = min(16, (audio_size - segment_size) // 4000 + 1)\n print(f'num_eval: {num_eval}')\n startframe = np.linspace(0, audio_size-segment_size, num_eval)\n print(f'startframe: {startframe}')\n feats = []\n print('chunks')\n for asf in startframe:\n print(f'{int(asf)}:{int(asf)+segment_size}')\n feats.append(audio[int(asf):int(asf)+segment_size])\n feat = np.stack(feats, axis=0).astype(np.float)\n print(f'feat size: {feat.shape}')\n return torch.FloatTensor(feat)\n\n def inference_batch(self, batch):\n length = np.cumsum([0] + [len(i) for i in batch])\n batch = torch.cat(batch).to(self.device)\n with torch.no_grad():\n out = self.model(batch)\n if self.model.__L__.test_normalize:\n out = F.normalize(out, p=2, dim=1)\n out = [\n F.normalize(out[start:end].mean(dim=0), dim=0).cpu().numpy()\n for start, end in zip(length[:-1], length[1:])\n ]\n return out\n\n def handle(self, batch, context):\n batch = [self.load_wav(i.get('body')) for i in batch]\n result = self.inference_batch(batch)\n return [base64.b64encode(embedding.tobytes()) for embedding in result]\n" }, { "alpha_fraction": 0.601307213306427, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 29.600000381469727, "blob_id": "18202c0fab16aa27e4f03f5846bf90da2c8da3ed", "content_id": "c83c7733464897fbdfacec28c5c00d100304ba48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 153, "license_type": "no_license", "max_line_length": 42, "num_lines": 5, "path": "/run_docker.sh", "repo_name": "hajix/speaker-embedding-service", "src_encoding": "UTF-8", "text": "# run speaker embedding service\ndocker run -d \\\n --name speaker-embedding-service-cpu \\\n -p 8080-8082:8080-8082 \\\n speaker-embedding-cpu:latest\n" }, { "alpha_fraction": 0.7027832865715027, "alphanum_fraction": 0.737574577331543, "avg_line_length": 24.149999618530273, "blob_id": "d9677c56fd51b7c81e602b3fbca8dc1f3f59883c", "content_id": "9ac4f8ec7c1c3134831b2e6e20b79d7c7656911d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 1006, "license_type": "no_license", "max_line_length": 118, "num_lines": 40, "path": "/Dockerfile", "repo_name": "hajix/speaker-embedding-service", "src_encoding": "UTF-8", "text": "FROM pytorch/torchserve:0.3.0-cpu\n\nUSER root\n\nRUN apt-get update && apt-get upgrade -y\n\nRUN apt-get install python3-distutils python3-dev git nano curl python3-pip libsndfile1 build-essential ffmpeg -y && \\\n pip3 install -U pip && \\\n pip3 install ffmpeg-python\n\nUSER model-server\n\nRUN mkdir -p /home/model-server/services/speaker_embedding\n\nWORKDIR /home/model-server/services/speaker_embedding\n\nCOPY speaker_embedding .\n\nRUN git clone https://github.com/clovaai/voxceleb_trainer.git && \\\n cd voxceleb_trainer && \\\n git checkout 3bfd557fab5a3e6cd59d717f5029b3a20d22a281 && \\\n pip3 install -r requirements.txt\n\nRUN cd voxceleb_trainer && \\\n ls && \\\n patch -p1 < ../diff.patch\n\nUSER root\n\nRUN pip install -r requirements.txt\n\nCOPY resources/dockerd-entrypoint.sh /usr/local/bin/dockerd-entrypoint.sh\n\nRUN chmod +x /usr/local/bin/dockerd-entrypoint.sh && \\\n chown -R model-server /home/model-server\n\nUSER model-server\n\nENTRYPOINT [\"/usr/local/bin/dockerd-entrypoint.sh\"]\nCMD [\"serve\"]\n" }, { "alpha_fraction": 0.6695652008056641, "alphanum_fraction": 0.7242236137390137, "avg_line_length": 21.36111068725586, "blob_id": "dc45ba45563c7e346cded11e93102566bf5c7817", "content_id": "8d5c96705a717e79154a9c84dfa48a5c47e1484c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 805, "license_type": "no_license", "max_line_length": 109, "num_lines": 36, "path": "/README.md", "repo_name": "hajix/speaker-embedding-service", "src_encoding": "UTF-8", "text": "# speaker embedding service\n\n## How to run service:\n\nBuild docker image: `./create_docker.sh`\n\nRun and create container: `./run_docker.sh`\n\n\n## How to use service:\n\n1- Curl client:\n```bash\ncurl 127.0.0.1:8080/predictions/speaker_embedding -T resources/shah.wav\n```\n\n2- Python client:\n```python\nimport base64\nimport requests\n\nimport numpy as np\n\nwith open('resources/shah.wav', 'rb') as f:\n data = f.read()\n\nresponse = requests.put('http://127.0.0.1:8080/predictions/speaker_embedding', data=data)\nspeaker_embedding = np.frombuffer(base64.b64decode(response.text), dtype=np.float32)\n```\n\nYou could send multiple requests concurrently:\n```python\nimport grequests\nreqs = (grequests.put('http://127.0.0.1:8080/predictions/speaker_embedding', data=data) for _ in range(1000))\nreps = grequests.map(reqs)\n```\n" } ]
7
jobergum/vespa-tools
https://github.com/jobergum/vespa-tools
f6c4ba9e6ae3eb5b18a8e0c6380165b786d164fe
173c8eb1e934c95ebc08bbb2e9e2d8e5c911b2f0
515c6c30c6c2cef14049bd5008ab90fb5c6f543b
refs/heads/master
2021-01-23T10:23:23.604928
2017-12-11T11:59:43
2017-12-11T11:59:43
102,613,717
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6238678693771362, "alphanum_fraction": 0.7437400221824646, "avg_line_length": 39.80434799194336, "blob_id": "5cc3963b45e3089f3d4cf488df1bd384869aad35", "content_id": "3d83ae8f3abf326ebd983b367718e182b90f57aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1885, "license_type": "no_license", "max_line_length": 231, "num_lines": 46, "path": "/talk-demo/README.md", "repo_name": "jobergum/vespa-tools", "src_encoding": "UTF-8", "text": "Add s.dwitter.com to /etc/hosts and point to IP address of search container\n\ncat doc.json\n{\n \"fields\": {\n\t \"user\": \"jobergum”\n \"tweet\": \"Vespa meetup going down right no”,\n \"hashtags\": [“vespa.ai”],\n \"timestamp\": 1512084275\n }\n}\n\nPOST IT \ncurl -X POST --data-binary @doc.json http://s.dwitter.com:8080/document/v1/twitter/tweet/docid/1 -s |python -m json.tool\n\n\nSimple GET\nhttp://s.dwitter.com:8080/document/v1/twitter/tweet/docid/1\n\nStart stream of updates. \n\nNeed to install https://github.com/bear/python-twitter\n\nsudo pip install python-twitter\n\npython twitter-api-get-sample.py | vespa-feeder -v \n\n\nQuery Examples \n\nWeightedset query: \nhttp://s.dwitter.com:8080/search/?yql=select%20*%20from%20sources%20*%20where%20weightedSet(user,%20%7B%22divaradiodisco%22:1,%20%22Wally_Callahan%22:1%7D)%3B\n\nRegular expression:\nhttp://s.dwitter.com:8080/search/?yql=select%20*%20from%20sources%20*%20where%20hashtags%20contains%20%22trump%22%3B&select=all(group(fixedwidth(timestamp,60))%20order(-max(timestamp))each(output(count())))&hits=0\n\nRange search:\nhttp://s.dwitter.com:8080/search/?yql=select%20*%20from%20sources%20*%20where%20range(timestamp,1512408240,1512408300)%3B&\n\nGrouping examples\n\nhttp://s.dwitter.com:8080/search/?yql=select%20*%20from%20sources%20*%20where%20hashtags%20matches%20%22%5Etrum%22%3B&select=all(group(hashtags)%20max(10)%20order(-count())%20each(output(count())))&hits=0\n\nhttp://s.dwitter.com:8080/search/?yql=select%20*%20from%20sources%20*%20where%20hashtags%20contains%20%22trump%22%3B&select=all(group(fixedwidth(timestamp,60))%20order(-max(timestamp))each(output(count())))&hits=0\n\nhttp://s.dwitter.com:8080/search/?yql=select%20*%20from%20sources%20*%20where%20hashtags%20contains%20%22trump%22%3B&select=all(group(hashtags)%20max(10)%20order(-count())%20each(output(count())%20max(2)%20each(output(summary()))))\n" }, { "alpha_fraction": 0.6046326160430908, "alphanum_fraction": 0.610223650932312, "avg_line_length": 29.512195587158203, "blob_id": "2f04c47fcfe52ef6f9e57d50e1e1ecb691868a32", "content_id": "a8513c5f09d35d57e1e04caa94f60508d171acbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1252, "license_type": "no_license", "max_line_length": 97, "num_lines": 41, "path": "/talk-demo/bin/twitter-api-get-sample.py", "repo_name": "jobergum/vespa-tools", "src_encoding": "UTF-8", "text": "import twitter,time,calendar,json,unicodedata\n\ndef remove_control_characters(s):\n return \"\".join(ch for ch in s if unicodedata.category(ch)[0]!=\"C\")\n\napi = twitter.Api(consumer_key='xx',\n consumer_secret='xx',\n access_token_key='xx',\n access_token_secret='xx'\n\napi.VerifyCredentials()\n\n#replace with topics of interest\nsample = api.GetStreamFilter(track=[\"donald\",\"trump\"])\n\nprint \"[\"\nfor s in sample:\n\tif s.has_key(\"text\"):\n\t\ttext = s[\"text\"]\n\t\ttext = remove_control_characters(text)\n\t\t#text = text.encode('utf-8')\n\t\tid = s[\"id\"]\n\t\thashtags = []\n\t\tif s.has_key(\"entities\"):\n\t\t\thashtags = s[\"entities\"][\"hashtags\"]\n\t\t\ttags = []\n\t\t\tfor tag in hashtags:\n\t\t\t\tt = tag[\"text\"]\n\t\t\t\tt = remove_control_characters(t)\n\t\t\t\t#t = t.encode('utf-8')\n\t\t\t\ttags.append(t)\n\t\t\thashtags = tags\n\t\tts = time.strptime(s['created_at'],'%a %b %d %H:%M:%S +0000 %Y')\n\t\tin_reply_to_screen_name = s[\"in_reply_to_screen_name\"]\n\t\tuser_name = s['user']['screen_name']\n\t\tif not text.startswith(\"RT\") and in_reply_to_screen_name is None:\n\n\t\t\tprint json.dumps({\"put\":\"id:twitter:tweet::%s\" %(id),\n\t\t\t\t\"fields\":{\"text\":text,\"hashtags\":hashtags,\"timestamp\":calendar.timegm(ts),\"user\":user_name}})\n\t\t \tprint \",\"\nprint \"]\"\t\n" }, { "alpha_fraction": 0.6985645890235901, "alphanum_fraction": 0.7081339955329895, "avg_line_length": 51.25, "blob_id": "553a7c9717da3cfe7d3d750ef8569072cbadda35", "content_id": "ec6f0b1cd99627a95489e76ab55b7f54e2c28dae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 209, "license_type": "no_license", "max_line_length": 93, "num_lines": 4, "path": "/talk-demo/bin/check-indexed-documents-per-node.sh", "repo_name": "jobergum/vespa-tools", "src_encoding": "UTF-8", "text": "for host in $(vespa-model-inspect -u service searchnode |grep JSON | awk '{print $1}'); do \n\techo -n $host\" \"\n\tcurl -s $host\"state/v1/custom/component/documentdb/tweet\" |python -m json.tool |grep indexed\ndone\n" }, { "alpha_fraction": 0.761904776096344, "alphanum_fraction": 0.761904776096344, "avg_line_length": 19, "blob_id": "33898884b164aa7da898655f4e6a22453c314544", "content_id": "fbabb6e5b7b89dc2d79d81cbf755af470bde7ef0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 21, "license_type": "no_license", "max_line_length": 19, "num_lines": 1, "path": "/README.md", "repo_name": "jobergum/vespa-tools", "src_encoding": "UTF-8", "text": "#Random Vespa Stuff \n" } ]
4
patricia-777/proxy-TD
https://github.com/patricia-777/proxy-TD
dc966591fc6d91b317c70514bb82149c092c3845
9950435f7420ab9789aa431e37c746f31baffa81
cc150e934a3c787d5177178519df6e2b66cac549
refs/heads/master
2021-01-22T06:19:13.435761
2017-06-27T00:30:14
2017-06-27T00:30:14
92,541,814
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49391627311706543, "alphanum_fraction": 0.5013405084609985, "avg_line_length": 29.471698760986328, "blob_id": "21537abdd0debdc14a349c4aede9c44beb9c4f12", "content_id": "7c4df305ac48a81711a9b397d1863be63b005710", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4849, "license_type": "no_license", "max_line_length": 112, "num_lines": 159, "path": "/modulo_proxy.py", "repo_name": "patricia-777/proxy-TD", "src_encoding": "UTF-8", "text": "'''\nTD - 2/2017\n@author: Gibson e Lais\n'''\n\n# IMPORTANDO MODULOS E BIBLIOTECAS\nimport socket, thread, sys, time\n\nfrom modulo_cache import *\nfrom modulo_permissao import *\nfrom modulo_log import *\nfrom modulo_proxy import *\n\n# VARIAVEIS CONSTANTES\nMAX_RECV=2097152\nhttpport=80\nTIME_OUT=10\n\n\n# FUNCAO DO PROXY \ndef webproxy(cliente,address):\n \n # FLAGS PARA VERIFICACAO DE TERMOS\n reqdeny=0\n reqdeny1=0 \n \n # MENSAGEM DE REQUISICAO HTTP \n msg=cliente.recv(MAX_RECV)\n \n\n # VERIFICACAO SE A MENSAGEM NAO EH VAZIA\n indice_final = msg.find('\\n')\n if indice_final != -1:\n\n # OBTENCAO DO SITE QUE O USUARIO QUER ACESSAR\n msglist=msg.split('\\n')\n website=(msglist[1].split())[1] \n\n # MOSTRANDO AO CLIENTE A REQUISICAO\n print \"requisicao: \",website\n\n \n # VERIFICAR SE EXISTE CACHE PARA ESSE SITE\n existe_cache = verificar_cache(website)\n\n #SE EXISTIR CACHE, USA AS INFORMACOES SALVAS, SE NAO CONECTA NORMALMENTE \n if existe_cache != \"\":\n\n for msg_cache in existe_cache:\n cliente.send(msg_cache)\n\n # GERANDO LOG PARA A REQUISICAO\n log(address, website, \"PERMITIDO\")\n\n\n else:\n \n #FLAG DE VERIFICACAO SE O SITE PODE SER ACESSADO\n proxyflag=permission(website)\n \n if proxyflag == 0 or proxyflag == 2:\n \n #SE O SITE NAO ESTIVER NA WHITE LIST, OS SEUS TERMOS DEVEM SER VERIFICADOS\n if proxyflag == 0:\n #VERIFICACAO DOS TERMOS DA MENSAGEM DE REQUISICAO\n reqdeny=permission_terms(msg)\n\n\n # CRIACAO DE CONEXAO ENTRE O SERVIDOR E O SITE QUE O USUARIO DESEJA ACESSAR \n try:\n start=time.clock()\n # ESTABELECENDO A CONEXAO ENTRE O CLIENTE E O SERVIDOR HTTP\n tcp = estabelecedo_conexao(website, msg, httpport)\n \n # LACO PARA OBTENCAO DA RESPOSTA DO SITE\n while True:\n \n # TIMEOUT\n if time.clock()-start > TIME_OUT:\n log(address,website,\"TIMEOUT\")\n break\n \n #RECEBE AS MENSAGEM DE RESPOSTA DO SITE\n msgr=tcp.recv(MAX_RECV)\n\n \n #SE O SITE NAO ESTIVER NA WHITE LIST, OS SEUS TERMOS DEVEM SER VERIFICADOS\n if proxyflag == 0:\n #VERIFICACAO DOS TERMOS DA MENSAGEM DE RESPOSTA\n reqdeny1=permission_terms(msgr)\n \n \n # SE A MENSAGEM DE RESPOSTA FOR VAZIA, OU UMA FLAG DE TERMOS FOR ATIVA, A CONEXAO ACABOU\n if (len(msgr)>0 and reqdeny == 0 and reqdeny1 == 0):\n\n cliente.send(msgr)\n start=time.clock()\n\n # SALVAR NA CACHE DADOS DO SITE\n criar_cache(website, msgr)\n\n # GERANDO LOG PARA A REQUISICAO\n log(address, website, \"PERMITIDO\")\n\n print \"conectado\"\n\n else:\n break\n\n tcp.close()\n \n # MENSAGEM DE ERROS NO SOCKET \n except socket.error, (value, message):\n print message\n \n # SE A FLAG DE BLACKLIST FOR ATIVA \n if proxyflag == 1:\n \n #MENSAGEM HTML DE ACESSO NEGADO PARA O USUARIO\n cliente.send(str.encode(blmsg))\n\n # GERANDO LOG PARA A REQUISICAO\n log(address, website, \"NEGADO\")\n\n \n else: \n\n # SE ALGUMA FLAG DE TERMOS PROIBIDOS FOR ATIVA\n if (reqdeny == 1 or reqdeny1 == 1):\n \n #MENSAGEM HTML DE ACESSO NEGADO PARA O USUARIO\n cliente.send(str.encode(denymsg))\n blacklist_add(website)\n\n # GERANDO LOG PARA A REQUISICAO\n log(address, website, \"NEGADO\")\n\n\n # FECHANDO CONEXAO\n cliente.close()\n \n \n\n\ndef estabelecedo_conexao(website, msg, httpport):\n # OBTENCAO DO IP PELO NOME DO SITE\n webaddress2=socket.gethostbyname(website)\n webaddress=website\n DEST=webaddress,httpport\n tcp=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\n\n #CONEXAO ENTRE SERVIDOR E SITE\n tcp.connect(DEST)\n \n #ENVIO DA MENSAGEM DE REQUISICAO FEITA PELO USUARIO PARA O SITE\n tcp.sendall(msg)\n\n return tcp\n\n\n\n\n" }, { "alpha_fraction": 0.5815602540969849, "alphanum_fraction": 0.5957446694374084, "avg_line_length": 21.965517044067383, "blob_id": "933addaebe431729cdfe2b89b133fd865853ce24", "content_id": "5226da37dc05a0245854b51d5a8e179f9ceaf917", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1410, "license_type": "no_license", "max_line_length": 77, "num_lines": 58, "path": "/modulo_servidor.py", "repo_name": "patricia-777/proxy-TD", "src_encoding": "UTF-8", "text": "'''\r\nTD - 2/2017\r\n@author: Gibson e Lais\r\n'''\r\n\r\n# IMPORTANDO MODULOS E BIBLIOTECAS\r\nimport socket, thread, sys, time\r\n\r\nfrom modulo_cache import *\r\nfrom modulo_log import *\r\nfrom modulo_proxy import *\r\n\r\n\r\n\r\n# VARIAVEIS CONSTANTES\r\nServerPort=8080\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n \r\n # NOME DO SERVIDOR E PORTA #\r\n ServerName='127.0.0.1'\r\n ServerAddress=ServerName,ServerPort\r\n \r\n # CRIACAO DO SOCKET DO SERVIDOR #\r\n try:\r\n ServerSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n ServerSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n\r\n ServerSocket.bind(ServerAddress)\r\n ServerSocket.listen(10)\r\n\r\n print \"Aguardando conexao\\n\"\r\n\r\n # APAGANDO A CACHE ANTERIOR\r\n reiniciando_cache()\r\n\r\n # APAGANDO OS LOGS ANTERIORES\r\n reiniciando_log()\r\n\r\n # CONEXAO ENTRE SERVIDOR PROXY E USUARIO\r\n while True:\r\n\r\n cliente,address=ServerSocket.accept()\r\n\r\n # MOSTRANDO O CLIENTE QUE FEZ A REQUISICAO\r\n print \"\\nusuario: \",address[0],address[1]\r\n \r\n # AO ESCUTAR UM CLIENTE, GERA UMA NOVA THREAD PARA AQUELE USUARIO\r\n thread.start_new_thread(webproxy,(cliente,address))\r\n \r\n ServerSocket.close()\r\n \r\n # MENSAGENS DE ERROR NO SOCKET \r\n except socket.error, (value, message):\r\n print message\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.6423034071922302, "alphanum_fraction": 0.6489479541778564, "avg_line_length": 22.153846740722656, "blob_id": "e85991f2c4169c5611968723486ef3d7a582e6de", "content_id": "a3885f56fba38b474901bd1e0ef881dfabe2a98c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 903, "license_type": "no_license", "max_line_length": 195, "num_lines": 39, "path": "/modulo_log.py", "repo_name": "patricia-777/proxy-TD", "src_encoding": "UTF-8", "text": "'''\nTD - 2/2017\n@author: Gibson e Lais\n'''\n\n# IMPORTANDO BIBLIOTECAS\nimport os\nfrom datetime import datetime\n\n# SALVANDO NO ARQUIVO LOG.TXT AS INFORMACOES DE REQUISICAO\ndef log(address, website, status):\n\n\tnow = datetime.now()\n\tmensagem_log = str(now.day) + \"/\" + str(now.month) + \"/\" + str(now.year) + \" - \" + str(now.hour) + \":\" + str(now.minute) + \" --> \" + address[0] + \" requisitou \" + website + \" (\" + status + \")\\n\"\n\n\ttry:\n\t\t\n\t\tarquivo_log = open(\"log.txt\", \"r\")\n\t\tconteudo_log = arquivo_log.readlines()\n\n\t\tconteudo_log.append(mensagem_log)\n\n\t\tarquivo_log = open(\"log.txt\", \"w\")\n\t\tarquivo_log.writelines(conteudo_log)\n\t\tpass\n\texcept Exception, e:\n\n\t\tarquivo_log = open(\"log.txt\", \"w\")\n\t\tarquivo_log.write(mensagem_log)\n\t\n\tarquivo_log.close()\n\t\n\n# DELETANDO O ARQUIVO DE LOG NO COMECO DA EXECUCAO\ndef reiniciando_log():\n\tarquivo_log = 'log.txt'\n\n\tif os.path.isfile(arquivo_log):\n\t\tos.remove(arquivo_log)\n" }, { "alpha_fraction": 0.6353928446769714, "alphanum_fraction": 0.6414950489997864, "avg_line_length": 24.41176414489746, "blob_id": "2c55f7db69f27c8985ecd8e685054241b9d63eae", "content_id": "48b109f79c2ab2341ec782867c3c91dc06c6f7ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1311, "license_type": "no_license", "max_line_length": 137, "num_lines": 51, "path": "/modulo_cache.py", "repo_name": "patricia-777/proxy-TD", "src_encoding": "UTF-8", "text": "'''\nTD - 2/2017\n@author: Gibson e Lais\n'''\n\n# IMPORTANDO BIBLIOTECAS\nimport os, shutil\n\n# VARIAVEIS CONSTANTES\nFILE_EXIST = \"False\"\n\n\n# FUNCAO QUE VERIFICA SE O SITE JA ESTA SALVO EM CACHE\ndef verificar_cache(website):\n # TENTA ABRIR O ARQUIVO COM REFERENTE AO SITE, SE CONSEGUIR ELE LE O ARQUIVO, RETORNA OS DADOS E MUDA O STATUS DA VARIAVEL FILE_EXIST\n # SE NAO EXISTIR O ARQUIVO ELE RETORNA VAZIO\n try:\n arquivo_cache = open(\"./cache/\"+ website + \".txt\", \"r\")\n dados_cache = arquivo_cache.readlines()\n\n arquivo_cache.close()\n\n FILE_EXIST = \"True\"\n\n return dados_cache\n\n except Exception, e:\n return \"\"\n\n\n# FUNCAO QUE GRAVA NO CACHE OS DADOS DO SITE, CRIANDO UM ARQUIVO TXT COM O NOME SO SITE\n# CASO O ARQUIVO EXISTA MAS NAO TENHA SIDO ENCONTRADO, GERA UM ERRO\ndef criar_cache(website, msg):\n if FILE_EXIST == \"False\":\n arquivo_cache = open(\"./cache/\"+ website + \".txt\", \"w\")\n arquivo_cache.write(msg)\n\n arquivo_cache.close()\n else:\n print \"404: File Not Found\"\n\n\n# FUNCAO QUE DELETA A CACHE ATUAL DEIXANDO A PASTA VAZIA\ndef reiniciando_cache():\n diretorio = './cache' \n\n if os.path.exists(diretorio):\n shutil.rmtree(diretorio)\n os.makedirs(diretorio)\n else:\n os.makedirs(diretorio)\n \n \n \n" }, { "alpha_fraction": 0.6024909019470215, "alphanum_fraction": 0.615464448928833, "avg_line_length": 30.064516067504883, "blob_id": "f14e15ef99436367bf5be9982d538093d1884901", "content_id": "d103ae8c89527935f1418dd645428e6414d5c719", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1927, "license_type": "no_license", "max_line_length": 229, "num_lines": 62, "path": "/modulo_permissao.py", "repo_name": "patricia-777/proxy-TD", "src_encoding": "UTF-8", "text": "'''\nTD - 2/2017\n@author: Gibson e Lais\n'''\n\n# VARIAVEIS CONSTANTES\nblmsg='HTTP/1.1 200 OK\\nContent-Type: text/html\\n\\n<html><header><title>ERROR</title></header><body><div align=\"center\" style=\"border:1px solid red\"><p>Acesso negado.</br>Site na blacklist.</p></div></body></html>\\n'\ndenymsg='HTTP/1.1 200 OK\\nContent-Type: text/html\\n\\n<html><header><title>ERROR</title></header><body><div align=\"center\" style=\"border:1px solid red\"><p>Acesso negado.</br>Site contem termos proibidos.</p></div></body></html>\\n'\n\n\n\n#FUNCAO PARA VERIFICAR SE O SITE PODE SER ACESSADO \ndef permission(website): \n \n wl=open('whitelist.txt','r')\n bl=open('blacklist.txt','r')\n flag=0\n \n # SE O SITE ESTIVER NO ARQUIVO DE WHITELIST, FLAG=2\n # CADA LINHA DO ARQUIVO CONTEM UM SITE\n for line in wl:\n if website == line.rstrip('\\n'):\n flag=2 \n \n #SE O SITE ESTIVER NO ARQUIVO DE BLACKLIST, FLAG=1\n # CADA LINHA DO ARQUIVO CONTEM UM SITE\n for line in bl:\n if website == line.rstrip('\\n'):\n flag=1\n \n #SE O SITE NAO ESTIVER EM NENHUM DOS ARQUIVOS, FLAG=0\n \n wl.close()\n bl.close()\n \n return flag \n\n#FUNCAO PARA VERIFICAR SE A MENSAGEM CONTEM TERMOS PROIBIDOS \ndef permission_terms(msg): \n \n denyterms=open('denyterms.txt','r')\n \n flag=0\n \n #PERCORRE O ARQUIVO DENY_TERMS PARA VER SE A MENSAGEM CONTEM ALGUMA PALAVRA QUE ESTA NO ARQUIVO\n #CADA LINHA DO ARQUIVO CONTEM UMA PALAVRA PROIBIDA\n #A MENSAGEM EH QUEBRADA PALAVRA POR PALAVRA \n for line in denyterms:\n for element in msg.split():\n if element == line.rstrip():\n flag=1\n \n denyterms.close()\n \n return flag \n\n#FUNCAO PARA ADICIONAR O SITE PARA O ARQUIVO DE BLACKLIST\ndef blacklist_add(website):\n \n bl=open('blacklist.txt','a')\n bl.write('\\n'+website)\n bl.close()\n\n" }, { "alpha_fraction": 0.5031043887138367, "alphanum_fraction": 0.5126115679740906, "avg_line_length": 28.742515563964844, "blob_id": "8a61884e2a70088e6315375b1fefca5bdb046f8d", "content_id": "b92c0d669def1b6687399d5384c8b822bf0d9dab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5154, "license_type": "no_license", "max_line_length": 112, "num_lines": 167, "path": "/Server_com_permissions_comentado.py", "repo_name": "patricia-777/proxy-TD", "src_encoding": "UTF-8", "text": "'''\r\nCreated on 30 de mai de 2017\r\n@author: Gibson e Lais\r\n'''\r\n\r\n# IMPORTANDO MODULOS E BIBLIOTECAS\r\nimport socket,thread,sys\r\n\r\nfrom modulo_cache import *\r\nfrom modulo_permissao import *\r\n\r\n\r\n\r\n# VARIAVEIS CONSTANTES\r\nMAX_RECV=2097152\r\nhttpport=80\r\nServerPort=8080\r\n\r\n\r\n\r\n \r\n# FUNCAO DO PROXY \r\ndef webproxy(cliente,address):\r\n \r\n # FLAGS PARA VERIFICACAO DE TERMOS\r\n reqdeny=0\r\n reqdeny1=0 \r\n print \"\\nusuario: \",address[0],address[1]\r\n \r\n # MENSAGEM DE REQUISICAO HTTP \r\n msg=cliente.recv(MAX_RECV)\r\n \r\n # VERIFICACAO SE A MENSAGEM NAO EH VAZIA\r\n indice_final = msg.find('\\n')\r\n if indice_final != -1:\r\n\r\n # OBTENCAO DO SITE QUE O USUARIO QUER ACESSAR\r\n msglist=msg.split('\\n')\r\n website=(msglist[1].split())[1] \r\n print \"WEBSITE: \",website \r\n\r\n \r\n # VERIFICAR SE EXISTE CACHE PARA ESSE SITE\r\n existe_cache = verificar_cache(website)\r\n\r\n #SE EXISTIR CACHE, USA AS INFORMACOES SALVAS, SE NAO CONECTA NORMALMENTE \r\n if existe_cache != \"\":\r\n\r\n for msg_cache in existe_cache:\r\n cliente.send(msg_cache)\r\n else:\r\n \r\n #FLAG DE VERIFICACAO SE O SITE PODE SER ACESSADO\r\n proxyflag=permission(website)\r\n \r\n if proxyflag == 0 or proxyflag == 2:\r\n \r\n #SE O SITE NAO ESTIVER NA WHITE LIST, OS SEUS TERMOS DEVEM SER VERIFICADOS\r\n if proxyflag == 0:\r\n #VERIFICACAO DOS TERMOS DA MENSAGEM DE REQUISICAO\r\n reqdeny=permission_terms(msg)\r\n\r\n\r\n # CRIACAO DE CONEXAO ENTRE O SERVIDOR E O SITE QUE O USUARIO DESEJA ACESSAR \r\n try:\r\n \r\n # ESTABELECENDO A CONEXAO ENTRE O CLIENTE E O SERVIDOR HTTP\r\n tcp = estabelecedo_conexao(website, msg, httpport)\r\n \r\n # LACO PARA OBTENCAO DA RESPOSTA DO SITE\r\n while True:\r\n \r\n #RECEBE AS MENSAGEM DE RESPOSTA DO SITE\r\n msgr=tcp.recv(MAX_RECV)\r\n \r\n #SE O SITE NAO ESTIVER NA WHITE LIST, OS SEUS TERMOS DEVEM SER VERIFICADOS\r\n if proxyflag == 0:\r\n #VERIFICACAO DOS TERMOS DA MENSAGEM DE RESPOSTA\r\n reqdeny1=permission_terms(msgr)\r\n \r\n \r\n # SE A MENSAGEM DE RESPOSTA FOR VAZIA, OU UMA FLAG DE TERMOS FOR ATIVA, A CONEXAO ACABOU\r\n if (len(msgr)>0 and reqdeny == 0 and reqdeny1 == 0):\r\n\r\n cliente.send(msgr)\r\n\r\n # SALVAR NA CACHE DADOS DO SITE\r\n recuperar_cache(website, msgr)\r\n\r\n print \"connected\"\r\n else:\r\n break\r\n\r\n tcp.close()\r\n \r\n # MENSAGEM DE ERROS NO SOCKET \r\n except socket.error, (value, message):\r\n print message\r\n \r\n # SE A FLAG DE BLACKLIST FOR ATIVA \r\n if proxyflag == 1:\r\n \r\n #MENSAGEM HTML DE ACESSO NEGADO PARA O USUARIO\r\n cliente.send(str.encode(blmsg))\r\n\r\n \r\n else: \r\n\r\n # SE ALGUMA FLAG DE TERMOS PROIBIDOS FOR ATIVA\r\n if (reqdeny == 1 or reqdeny1 == 1):\r\n \r\n #MENSAGEM HTML DE ACESSO NEGADO PARA O USUARIO\r\n cliente.send(str.encode(denymsg))\r\n blacklist_add(website)\r\n\r\n # FECHANDO CONEXAO\r\n cliente.close()\r\n \r\n\r\n\r\ndef estabelecedo_conexao(website, msg, httpport):\r\n # OBTENCAO DO IP PELO NOME DO SITE\r\n webaddress2=socket.gethostbyname(website)\r\n print webaddress2\r\n webaddress=website\r\n DEST=webaddress,httpport\r\n tcp=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n \r\n #CONEXAO ENTRE SERVIDOR E SITE\r\n tcp.connect(DEST)\r\n print \"conectado a: \\n\",website\r\n #ENVIO DA MENSAGEM DE REQUISICAO FEITA PELO USUARIO PARA O SITE\r\n tcp.sendall(msg)\r\n\r\n return tcp\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n \r\n # NOME DO SERVIDOR E PORTA #\r\n ServerName='127.0.0.1'\r\n ServerAddress=ServerName,ServerPort\r\n \r\n # CRIACAO DO SOCKET DO SERVIDOR #\r\n try:\r\n ServerSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n\r\n ServerSocket.bind(ServerAddress)\r\n ServerSocket.listen(1)\r\n\r\n print \"Aguardando conexao\\n\"\r\n\r\n # CONEXAO ENTRE SERVIDOR PROXY E USUARIO\r\n while True:\r\n cliente,address=ServerSocket.accept()\r\n \r\n # AO ESCUTAR UM CLIENTE, GERA UMA NOVA THREAD PARA AQUELE USUARIO\r\n thread.start_new_thread(webproxy,(cliente,address))\r\n \r\n ServerSocket.close()\r\n \r\n # MENSAGENS DE ERROR NO SOCKET \r\n except socket.error, (value, message):\r\n print message\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.48212379217147827, "alphanum_fraction": 0.49973317980766296, "avg_line_length": 26.846153259277344, "blob_id": "7be0854c0bf3644f9e624f5e165f19d986c0f0a5", "content_id": "1fd660a5232d9206f70bbbe6f3fffdfd5444f534", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3748, "license_type": "no_license", "max_line_length": 229, "num_lines": 130, "path": "/versoes/Server_com_permissions.py", "repo_name": "patricia-777/proxy-TD", "src_encoding": "UTF-8", "text": "'''\r\nCreated on 30 de mai de 2017\r\n@author: Gibson\r\n'''\r\nimport socket,thread,sys\r\n\r\nMAX_RECV=2097152\r\nhttpport=80\r\nServerPort=8080\r\nblmsg='HTTP/1.1 200 OK\\nContent-Type: text/html\\n\\n<html><header><title>ERROR</title></header><body><div align=\"center\" style=\"border:1px solid red\"><p>Acesso negado.</br>Site na blacklist.</p></div></body></html>\\n'\r\ndenymsg='HTTP/1.1 200 OK\\nContent-Type: text/html\\n\\n<html><header><title>ERROR</title></header><body><div align=\"center\" style=\"border:1px solid red\"><p>Acesso negado.</br>Site contem termos proibidos.</p></div></body></html>\\n'\r\n\r\ndef main():\r\n\r\n\r\n ServerName='127.0.0.1'\r\n ServerAddress=ServerName,ServerPort\r\n \r\n try:\r\n ServerSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n\r\n ServerSocket.bind(ServerAddress)\r\n ServerSocket.listen(1)\r\n\r\n print \"Aguardando conexao\\n\"\r\n\r\n while True:\r\n cliente,address=ServerSocket.accept()\r\n thread.start_new_thread(webproxy,(cliente,address))\r\n \r\n ServerSocket.close()\r\n \r\n except socket.error, (value, message):\r\n print message\r\n \r\ndef webproxy(cliente,address):\r\n reqdeny=0\r\n reqdeny1=0 \r\n print \"\\nusuario: \",address[0],address[1]\r\n msg=cliente.recv(MAX_RECV)\r\n indice_final = msg.find('\\n')\r\n if indice_final != -1:\r\n\r\n msglist=msg.split('\\n')\r\n website=(msglist[1].split())[1] \r\n \r\n proxyflag=permission(website)\r\n \r\n if proxyflag == 0 or proxyflag == 2:\r\n \r\n if proxyflag == 0:\r\n reqdeny=permission_terms(msg)\r\n try:\r\n webaddress2=socket.gethostbyname(website)\r\n print webaddress2\r\n webaddress=website\r\n DEST=webaddress,httpport\r\n tcp=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n \r\n tcp.connect(DEST)\r\n print \"conectado a: \\n\",website\r\n tcp.sendall(msg)\r\n \r\n while True:\r\n msgr=tcp.recv(MAX_RECV)\r\n if proxyflag == 0:\r\n reqdeny1=permission_terms(msgr)\r\n #print msgr\r\n if (len(msgr)>0 and reqdeny == 0 and reqdeny1 == 0):\r\n cliente.send(msgr)\r\n print \"connected\"\r\n else:\r\n break\r\n tcp.close()\r\n except socket.error, (value, message):\r\n print message\r\n \r\n if proxyflag == 1:\r\n # print \"blacklist\"\r\n cliente.send(str.encode(blmsg))\r\n\r\n \r\n else: \r\n if (reqdeny == 1 or reqdeny1 == 1):\r\n # print \"denied\"\r\n cliente.send(str.encode(denymsg))\r\n blacklist_add(website)\r\n\r\n cliente.close()\r\n \r\ndef permission(website): \r\n \r\n wl=open('whitelist.txt','r')\r\n bl=open('blacklist.txt','r')\r\n flag=0\r\n \r\n for line in wl:\r\n if website == line.rstrip('\\n'):\r\n flag=2 \r\n for line in bl:\r\n if website == line.rstrip('\\n'):\r\n flag=1\r\n \r\n wl.close()\r\n bl.close()\r\n \r\n return flag \r\n \r\ndef permission_terms(msg): \r\n \r\n denyterms=open('denyterms.txt','r')\r\n \r\n flag=0\r\n \r\n for line in denyterms:\r\n for element in msg.split():\r\n if element == line.rstrip():\r\n flag=1\r\n \r\n denyterms.close()\r\n \r\n return flag \r\n\r\ndef blacklist_add(website):\r\n \r\n bl=open('blacklist.txt','a')\r\n bl.write('\\n'+website)\r\n bl.close()\r\n \r\nmain()" }, { "alpha_fraction": 0.7817258834838867, "alphanum_fraction": 0.7817258834838867, "avg_line_length": 27.14285659790039, "blob_id": "0a49101ae3f41015976538f7227a99ab235ede0a", "content_id": "c8b6fea6e5e1e5e2d1e72ba354e34636576e394d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 200, "license_type": "no_license", "max_line_length": 100, "num_lines": 7, "path": "/README.md", "repo_name": "patricia-777/proxy-TD", "src_encoding": "UTF-8", "text": "# proxy-TD\n\nPara executar, baixe o projeto e escreva no terminal/cmd\n\n** python servidor_proxy\n\nPara o perfeito funcionamento do programa, é necessário ter uma pasta chamada \"cache\", pré-existente\n" }, { "alpha_fraction": 0.557865560054779, "alphanum_fraction": 0.5793485641479492, "avg_line_length": 21.177419662475586, "blob_id": "09e3726e65dd77b123a319a3b8c5ea411b1fa3dd", "content_id": "de0381fa866348f259958452550f57077b00b715", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1443, "license_type": "no_license", "max_line_length": 65, "num_lines": 62, "path": "/versoes/Server.py", "repo_name": "patricia-777/proxy-TD", "src_encoding": "UTF-8", "text": "'''\r\nCreated on 30 de mai de 2017\r\n\r\n@author: Gibson\r\n'''\r\nimport socket,thread,sys\r\n\r\nMAX_RECV=2097152\r\nhttpport=80\r\nServerPort=8080\r\n \r\ndef main():\r\n\r\n\r\n ServerName='127.0.0.1'\r\n ServerAddress=ServerName,ServerPort\r\n ServerSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n\r\n ServerSocket.bind(ServerAddress)\r\n ServerSocket.listen(1)\r\n\r\n print \"Aguardando conexao\\n\"\r\n\r\n while True:\r\n cliente,address=ServerSocket.accept()\r\n thread.start_new_thread(webproxy,(cliente,address))\r\n \r\n ServerSocket.close()\r\n \r\n\r\ndef webproxy(cliente,address): \r\n print \"\\nusuario: \",address[0],address[1]\r\n msg=cliente.recv(MAX_RECV)\r\n # print msg\r\n msglist=msg.split('\\n')\r\n print \"LISTA: \",msglist\r\n if msglist:\r\n website=(msglist[1].split())[1]\r\n # print website\r\n webaddress=socket.gethostbyname(website)\r\n #print \"conectando a: \",webaddress\r\n # print \"\\n\"\r\n DEST=webaddress,httpport\r\n tcp=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n\r\n tcp.connect(DEST)\r\n print \"conectado a: \\n\",website\r\n tcp.sendall(msg)\r\n \r\n while True:\r\n msgr=tcp.recv(MAX_RECV)\r\n #print msgr\r\n if (len(msgr)>0):\r\n cliente.send(msgr)\r\n else:\r\n tcp.close()\r\n break\r\n cliente.close()\r\n #print \"\\n Conexao finalizada\"\r\n return\r\n\r\nmain()\r\n\r\n\r\n\r\n" } ]
9
paulfurley/python-windows-packager
https://github.com/paulfurley/python-windows-packager
8d0b71ca29f2b87be87433c989e9926acb23b9f4
565c2696ff1c2406ec69e622e9bb72b6b5dd0be3
fa9716682ecc2b7bcc4e467cfe0ca40aef9ef26e
refs/heads/master
2020-06-08T05:11:36.926378
2016-12-08T09:06:46
2016-12-08T09:06:46
15,207,244
31
6
null
2013-12-15T17:03:23
2017-05-29T16:01:54
2016-12-08T09:06:46
Shell
[ { "alpha_fraction": 0.6566593647003174, "alphanum_fraction": 0.6648471355438232, "avg_line_length": 26.74242401123047, "blob_id": "bd8ab3eb0b509ed888a61d57a11b92981effc04a", "content_id": "42da5d7f96379480d5beeb1f51a0755235f7e94c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1832, "license_type": "permissive", "max_line_length": 83, "num_lines": 66, "path": "/package.sh", "repo_name": "paulfurley/python-windows-packager", "src_encoding": "UTF-8", "text": "#!/bin/bash -e\n\nif [ $# -ne 2 ]; then\n echo \"Usage: $0 /path/to/main.py ProjectName\"\n exit 1\nelse\n FULL_PY_PATH=`readlink -f $1`\n SOURCE_DIR_LINUX=`dirname ${FULL_PY_PATH}`\n MAIN_PY=`basename ${FULL_PY_PATH}`\n PROJECT_NAME=\"$2\"\nfi\n\nTHIS_SCRIPT_PATH=`readlink -f $0`\nTHIS_SCRIPT_DIR=`dirname ${THIS_SCRIPT_PATH}`\n\nPYINSTALLER_ZIP=${THIS_SCRIPT_DIR}/installers/PyInstaller-2.1.zip\n\n\nPYTHON_EXE_WIN=\"C:\\\\Python27\\\\python.exe\"\n\nWINE_TARBALL=${THIS_SCRIPT_DIR}/build_environment/wine.tar.gz\n\nif [ ! -e \"${WINE_TARBALL}\" ]; then\n echo \"ERROR: You don't have a frozen wine environment at\"\n echo \"${WINE_TARBALL}\"\n echo\n echo \"Option 1:\"\n echo \" Create a new wine environment by running build_environment/create.sh\"\n echo \" and following the instructions.\"\n echo \"Option 2:\"\n echo \" Use an existing wine environment (with Python installed) by doing:\"\n echo \" $ export WINEPREFIX=~/.wine # path to your existing wine env\"\n echo \" $ build_environment/freeze.sh\"\n\n exit 2\nelse\n export WINEPREFIX=`mktemp -d --suffix=_wine`\n\n # Unpack wine environment\n tar \"--directory=${WINEPREFIX}\" -xzf ${WINE_TARBALL}\n\nfi\n\nBUILD_DIR_LINUX=${WINEPREFIX}/drive_c/build\nBUILD_DIR_WIN=\"C:\\\\build\"\nmkdir -p ${BUILD_DIR_LINUX}\n\n\n# Unpack PyInstaller\nunzip ${PYINSTALLER_ZIP} -d ${BUILD_DIR_LINUX} > /dev/null\nPYINSTALLER_DIR_WIN=${BUILD_DIR_WIN}/pyinstaller-2.1\n\n# Create symbolic link to source directory so Windows can access it\nln -s ${SOURCE_DIR_LINUX} ${BUILD_DIR_LINUX}/src_symlink\nSOURCE_DIR_WIN=${BUILD_DIR_WIN}\\\\src_symlink\n\n\nwine \"${PYTHON_EXE_WIN}\" \"${PYINSTALLER_DIR_WIN}\\\\pyinstaller.py\" \\\n \"--name=${PROJECT_NAME}\" \\\n --onefile \\\n --noconsole \\\n \"${SOURCE_DIR_WIN}\\\\${MAIN_PY}\"\n\nrm -rf ${WINEPREFIX}\n\necho \"Executable available at dist/${PROJECT_NAME}.exe\"\n\n" }, { "alpha_fraction": 0.7317073345184326, "alphanum_fraction": 0.7317073345184326, "avg_line_length": 24.375, "blob_id": "35e1aed2808468e9feabc92172fa618c8bab9313", "content_id": "8e19b603c8845d922009b5cbbd04a44c5afd7093", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 205, "license_type": "permissive", "max_line_length": 70, "num_lines": 8, "path": "/sample-application/src/gui.py", "repo_name": "paulfurley/python-windows-packager", "src_encoding": "UTF-8", "text": "from Tkinter import Tk\nimport tkMessageBox\n\ndef show_message(message, title=\"message\"):\n window = Tk()\n window.wm_withdraw()\n\n tkMessageBox.showinfo(title=title, message=message, parent=window)\n\n\n" }, { "alpha_fraction": 0.6054421663284302, "alphanum_fraction": 0.6054421663284302, "avg_line_length": 15.333333015441895, "blob_id": "1d06f23a72522a6d8f401d8d7339f9ff9e722911", "content_id": "97c083b30dd6c98dd0cf94d6bea2331ae04c48ba", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 147, "license_type": "permissive", "max_line_length": 46, "num_lines": 9, "path": "/sample-application/src/main.py", "repo_name": "paulfurley/python-windows-packager", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nfrom gui import show_message\n\ndef main():\n show_message(\"Here's an example message.\")\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.7183513045310974, "alphanum_fraction": 0.7536800503730774, "avg_line_length": 34.10344696044922, "blob_id": "e58c0488879e970f10722e3a63025dad499e56a1", "content_id": "25c3cdd47c900049d9cbaf1b1b74a9055c291259", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1019, "license_type": "permissive", "max_line_length": 107, "num_lines": 29, "path": "/README.md", "repo_name": "paulfurley/python-windows-packager", "src_encoding": "UTF-8", "text": "# Python Packager\n## Overview\n\nDevelop Python on Linux, deploy on Windows.\n\nUses Pyinstaller and Wine to \"freeze\" Python programs to a standalone Windows\nexecutable, all from your Linux box.\n\n## Quick start\n\nTo quickly build your Wine environment, then create a standalone EXE,\nrun the following commands:\n\n $ wget \"http://www.python.org/ftp/python/2.7.3/python-2.7.3.msi\" \n $ wget \"http://nchc.dl.sourceforge.net/project/pywin32/pywin32/Build%20218/pywin32-218.win32-py2.7.exe\"\n $ build_environment/create.sh\n $ export WINEPREFIX=/tmp/path-outputted-from-create\n $ wine start python-2.7.3.msi\n $ wine pywin32-218.win32-py2.7.exe\n $ build_environment/freeze.sh\n $ ./package sample-application/src/main.py MySampleProgram\n\nThis will create a Wine environment in a tarball at \n./build_environment/wine.tar.gz.\n\n## Modifying the Python Windows environment\n\nIf you want to use a different Python version or add additional Python\nmodules, just do the above with different Windows Python installers.\n\n" }, { "alpha_fraction": 0.66847825050354, "alphanum_fraction": 0.6739130616188049, "avg_line_length": 21.9375, "blob_id": "85b6ed4e1fb560b7578dfca7e020868c4f11cf56", "content_id": "6884bf02f3a5555af08b0b238455e336644b58ba", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 368, "license_type": "permissive", "max_line_length": 83, "num_lines": 16, "path": "/build_environment/freeze.sh", "repo_name": "paulfurley/python-windows-packager", "src_encoding": "UTF-8", "text": "#!/bin/bash -e\n\nTHIS_SCRIPT_PATH=`readlink -f $0`\nTHIS_SCRIPT_DIR=`dirname ${THIS_SCRIPT_PATH}`\n\nWINE_TARBALL=${THIS_SCRIPT_DIR}/wine.tar.gz\n\nif [ \"$WINEPREFIX\" = \"\" ]; then\n echo \"WINEPREFIX is not set. This script freezes WINEPREFIX to ${WINE_TARBALL}\"\n exit 1\nfi\n\necho \"Freezing $WINEPREFIX to ${WINE_TARBALL}\"\n\ncd ${WINEPREFIX}\ntar -czf \"${WINE_TARBALL}\" .\n\n" }, { "alpha_fraction": 0.6486860513687134, "alphanum_fraction": 0.6721991896629333, "avg_line_length": 27.84000015258789, "blob_id": "32172b7a89d1bc264814beb59dd1a9ded67a11a3", "content_id": "fa3fed2a73145e4c6d251a0585e19b1fad09eda5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 723, "license_type": "permissive", "max_line_length": 66, "num_lines": 25, "path": "/build_environment/create.sh", "repo_name": "paulfurley/python-windows-packager", "src_encoding": "UTF-8", "text": "#!/bin/bash -e\n\nTHIS_SCRIPT_PATH=`readlink -f $0`\nTHIS_SCRIPT_DIR=`dirname ${THIS_SCRIPT_PATH}`\n\nWINE_TARBALL=${THIS_SCRIPT_DIR}/wine.tar.gz\n\nexport WINEPREFIX=`mktemp -d --suffix=_wine`\necho \"Created wine environment at $WINEPREFIX\"\n\nif [ \"$1\" = \"--update\" ]; then\n echo \"Update option given. Starting from existing wine.tar.gz\"\n tar --directory=${WINEPREFIX} -xzf ${WINE_TARBALL}\nfi\n\necho \"# STEP 1 #\"\necho \" $ export WINEPREFIX=${WINEPREFIX}\"\necho\necho \"# STEP 2 #\"\necho \" Run your python installers with wine, eg:\"\necho \" $ wine start installers/python-2.7.3.msi\"\necho \" $ wine installers/pywin32-218.win32-py2.7.exe\"\necho\necho \"# STEP 3 #\"\necho \" Run ./freeze.sh to save back to {WINE_TARBALL}\"\n\n\n" } ]
6
koumakpet/PyGame
https://github.com/koumakpet/PyGame
88f2f1e0bcc600a7624ab3b7c9219cc6cc5f3ca4
b78a9c0a876ae8a6d3f5e730c1b9c0d9a67ad521
d1db0f7e2ead9dd71ce39f06ca5a917f4198cdeb
refs/heads/master
2020-06-23T13:39:46.620440
2019-07-25T15:12:37
2019-07-25T15:12:37
198,526,261
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5169100165367126, "alphanum_fraction": 0.5345592498779297, "avg_line_length": 31.30447769165039, "blob_id": "8d124be4f5f07f39888bb68ef170677dc872dc0c", "content_id": "1d1b8303bb942cd29e2ce572e819f54d37bf6048", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10822, "license_type": "no_license", "max_line_length": 148, "num_lines": 335, "path": "/entities.py", "repo_name": "koumakpet/PyGame", "src_encoding": "UTF-8", "text": "import pygame\n\npygame.font.init()\n\n\ndef get_anim(anim_count=9, type='player'):\n '''Images for object animation\n\n Keyword Arguments:\n anim_count {int} -- [Amount of images for animation] (default: {9})\n type {str} -- [What class is the animation for] (default: {'player'})\n\n Returns:\n dict -- Images for ['left'] and ['right'] rotations\n '''\n anim = {}\n\n anim['left'] = []\n anim['right'] = []\n\n for n in range(1, anim_count + 1):\n if type == 'player':\n anim['right'].append(pygame.image.load(f'resources/R{n}.png'))\n anim['left'].append(pygame.image.load(f'resources/L{n}.png'))\n elif type == 'enemy':\n anim['right'].append(pygame.image.load(f'resources/R{n}E.png'))\n anim['left'].append(pygame.image.load(f'resources/L{n}E.png'))\n\n return anim\n\n\nclass Player(object):\n def __init__(self, x, y, max_health=500, width=64, height=64, vel=5, max_jump_count=8, rotation=1, anim_count=9, display_hitbox=False):\n self.x = x\n self.y = y\n self.max_health = max_health\n self.width = width\n self.height = height\n self.vel = vel\n self.max_jump_count = max_jump_count\n self.rotation = rotation\n self.anim_count = anim_count\n self.display_hitbox = display_hitbox\n\n self.health = self.max_health\n self.jump_count = self.max_jump_count\n self.is_jump = False\n self.walk_count = 0\n self.standing = True\n self.anim = get_anim(anim_count=self.anim_count, type='player')\n self.godmode = False\n\n @property\n def hitbox(self):\n # return (self.x + 17, self.y, 28, 60)\n return (self.x + 17, self.y + 11, 29, 52)\n\n def draw(self, win):\n '''Draw Player to the game window\n\n Arguments:\n win {window} -- Game window\n '''\n\n # Walk counter overflow reset\n if self.walk_count + 1 >= self.anim_count * 3:\n self.walk_count = 0\n\n # Moving\n if not self.standing:\n # Left rotation\n if self.rotation == -1:\n win.blit(self.anim['left'][self.walk_count // 3],\n (self.x, self.y))\n self.walk_count += 1\n # Right rotation\n else:\n win.blit(self.anim['right'][self.walk_count // 3],\n (self.x, self.y))\n self.walk_count += 1\n # Not moving\n else:\n # Left rotation\n if self.rotation == -1:\n win.blit(self.anim['left'][0], (self.x, self.y))\n # Right rotation\n else:\n win.blit(self.anim['right'][0], (self.x, self.y))\n\n if self.display_hitbox:\n pygame.draw.rect(win, (0, 0, 255), self.hitbox, 2)\n\n # Health bar\n pygame.draw.rect(win, (255, 0, 0), (340, 20, 130, 30), 2)\n healthbar_len = (125 / self.max_health) * self.health\n pygame.draw.rect(win, (255, 0, 0), (343, 23, healthbar_len, 25), 0)\n\n # Health text TODO: Handle text overflow\n font = pygame.font.SysFont('Roboto', 45)\n text = font.render(str(self.health), False, (119, 0, 0))\n win.blit(text, (380, 22))\n\n def check_damage(self, enemies):\n '''Check if Player will get damaged by Enemies\n\n Arguments:\n enemies {list} -- List of Enemy class instances\n '''\n for enemy in enemies:\n # Check y coord\n if enemy.hitbox[1] < self.hitbox[1] + self.hitbox[3] and enemy.hitbox[1] + enemy.hitbox[3] > self.hitbox[1]:\n # Check x coord\n if enemy.hitbox[0] < self.hitbox[0] + self.hitbox[2] and enemy.hitbox[0] + enemy.hitbox[2] > self.hitbox[0]:\n if not self.godmode:\n self.health -= enemy.damage\n else:\n self.health += enemy.damage\n\n def can_exist(self):\n '''Check weather Player can exists\n\n Returns:\n bool -- True - Player can exist / False - Player can't exist\n '''\n if self.health < 0:\n return False\n elif self.health > self.max_health:\n self.health = self.max_health\n return True\n else:\n return True\n\n @staticmethod\n def update_all(players, enemies):\n '''Update all players\n\n Arguments:\n players {list} -- List of Player class instances\n enemies {list} -- List of Enemy class instances\n\n Returns:\n list -- (Updated) List of Player class instances\n '''\n # Loop through every player\n for player in players:\n # Player is alive (check if damage was received)\n if player.can_exist():\n player.check_damage(enemies=enemies)\n # Player is dead\n else:\n players.pop(players.index(player))\n\n return players\n\n\nclass Projectile(object):\n def __init__(self, x, y, rotation, damage=5, radius=6, color=(0, 0, 0)):\n self.x = x\n self.y = y\n self.rotation = rotation\n self.damage = damage\n self.radius = radius\n self.color = color\n self.vel = 8 * rotation\n\n def draw(self, win):\n '''Draw Projectile to the game window\n\n Arguments:\n win {window} -- Game window\n '''\n pygame.draw.circle(win, self.color, (self.x, self.y), self.radius)\n\n def move(self):\n '''Movement of Projectile'''\n self.x += self.vel\n\n def can_exist(self, screen_width):\n '''Check weather projectile should be removed (out of screen)\n\n Arguments:\n screen_width {int} -- Width of the screen\n\n Returns:\n bool -- True - projectile can exist / False - projectile can't exist\n '''\n # Projectile out of screen (can't exist)\n if self.x + self.vel > screen_width or self.x + self.vel < 0:\n return False\n # Projectile on screen (can exist)\n else:\n return True\n\n @staticmethod\n def update_all(projectiles, screen_width):\n '''Update all Projectiles\n\n Arguments:\n projectiles {list} -- List of Projectile class instances\n screen_width {int} -- Width of the screen\n\n Returns:\n list -- (Updated) List of Projectile class instances\n '''\n # Loop through every projectile\n for projectile in projectiles:\n # Projectile is on screen (move it)\n if projectile.can_exist(screen_width):\n projectile.move()\n # Projectile is out of screen\n else:\n projectiles.pop(projectiles.index(projectile))\n\n return projectiles\n\n\nclass Enemy(object):\n def __init__(self, x, y, start_x, end_x, max_health=100, damage=5, width=64, height=64, vel=3, rotation=1, anim_count=11, display_hitbox=False):\n self.x = x\n self.y = y\n self.end_x = end_x\n self.start_x = start_x\n self.max_health = max_health\n self.damage = damage\n self.width = width\n self.height = height\n self.vel = vel\n self.rotation = rotation\n self.anim_count = anim_count\n self.display_hitbox = display_hitbox\n\n self.health = self.max_health\n self.path = [self.start_x, self.end_x]\n self.walk_count = 0\n self.anim = get_anim(anim_count=self.anim_count, type='enemy')\n\n @property\n def hitbox(self):\n # Right\n if self.rotation == 1:\n return (self.x + 13, self.y + 2, 32, 57)\n # Left\n else:\n return (self.x + 25, self.y + 2, 32, 57)\n\n def draw(self, win):\n '''Draw Enemy to the game window\n\n Arguments:\n win {window} -- Game window\n '''\n\n # Walk counter overflow reset\n if self.walk_count + 1 >= self.anim_count * 3:\n self.walk_count = 0\n\n # Left rotation:\n if self.rotation == -1:\n win.blit(self.anim['left'][self.walk_count // 3],\n (self.x, self.y))\n self.walk_count += 1\n # Right rotation\n else:\n win.blit(self.anim['right'][self.walk_count // 3],\n (self.x, self.y))\n self.walk_count += 1\n\n # Display hitbox\n if self.display_hitbox:\n pygame.draw.rect(win, (0, 0, 255), self.hitbox, 2)\n\n # Health bar\n pygame.draw.rect(win, (255, 0, 0),\n (self.hitbox[0], self.y - 10, 29, 10), 2)\n healthbar_len = (29 / self.max_health) * self.health\n pygame.draw.rect(win, (255, 0, 0),\n (self.hitbox[0], self.y - 10, healthbar_len, 10), 0)\n\n def move(self):\n '''Movement of Enemy'''\n if self.x + self.vel + self.width >= self.path[1] or self.x + self.vel <= self.path[0]:\n self.rotation *= -1\n self.x += self.vel * self.rotation\n\n def check_damage(self, projectiles):\n '''Check if Enemy will get damaged by projectiles\n\n Arguments:\n projectiles {list} -- List of Projectile class instances\n '''\n # Loop through every projectile\n for projectile in projectiles:\n # Check if projectile hit enemy\n # Check y coord\n if projectile.y - projectile.radius < self.hitbox[1] + self.hitbox[3] and projectile.y + projectile.radius > self.hitbox[1]:\n # Check x coord\n if projectile.x + projectile.radius > self.hitbox[0] and projectile.x - projectile.radius < self.hitbox[0] + self.hitbox[2]:\n projectiles.pop(projectiles.index(projectile))\n self.health -= projectile.damage\n\n def can_exist(self):\n '''Check weather Enemy can exists\n\n Returns:\n bool -- True - Enemy can exist / False - Enemy can't exist\n '''\n if self.health < 0:\n return False\n else:\n return True\n\n @staticmethod\n def update_all(enemies, projectiles):\n '''Update all Enemies\n\n Arguments:\n enemies {list} -- List of Enemy class instances\n projectiles {list} -- List of Projectile class instances\n\n Returns:\n list -- (Updated) List of Enemy class instances\n '''\n # Loop through every enemy\n kills = 0\n for enemy in enemies:\n # Enemy is alive (check if damage was received and move the enemy)\n if enemy.can_exist():\n enemy.check_damage(projectiles=projectiles)\n enemy.move()\n # Enemy is dead\n else:\n enemies.pop(enemies.index(enemy))\n kills += 1\n\n return enemies, kills\n" }, { "alpha_fraction": 0.57109135389328, "alphanum_fraction": 0.5881699323654175, "avg_line_length": 28.760330200195312, "blob_id": "d24cc1f70239b4dda310b86ffe6c0f2ffcef5a4a", "content_id": "8ac6452171edbdebd92a4d33dfb8e1fcca5935e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7202, "license_type": "no_license", "max_line_length": 136, "num_lines": 242, "path": "/main.py", "repo_name": "koumakpet/PyGame", "src_encoding": "UTF-8", "text": "import pygame\n\nfrom random import randint\n\nfrom entities import Player, Enemy, Projectile\n\nSCREEN_WIDTH = 500\nSCREEN_HEIGHT = 480\nFRAMERATE = 27\nBACKGROUND = pygame.image.load('resources/bg.jpg')\n\n\ndef setup(screen_width, screen_height):\n '''Basic setup of pygame\n\n Arguments:\n screen_width {int} -- Width of the game window\n screen_height {int} -- Height of the game window\n\n Returns:\n window -- Game window\n '''\n pygame.init()\n pygame.font.init()\n win = pygame.display.set_mode((screen_width, screen_height))\n pygame.display.set_caption('First Game')\n return win\n\n\ndef check_events():\n '''Checking for events\n\n Returns:\n bool -- Game Exit\n '''\n for event in pygame.event.get():\n # Check for quit\n if event.type == pygame.QUIT:\n pygame.quit()\n return False\n else:\n return True\n\n\ndef controls(player, projectiles, screen_width, shoot_cooldown, max_shoot_cooldown):\n '''Controls for the game\n\n Arguments:\n player {Player} -- Instance of Player class\n projectiles {list} -- List of Projectile class instances\n screen_width {int} -- Width of the game window\n shoot_cooldown {int} -- Cooldown for shooting\n\n Returns:\n int -- (Updated) Cooldown for shooting\n '''\n\n keys = pygame.key.get_pressed()\n\n # Moving left\n if keys[pygame.K_LEFT] and player.x >= player.vel:\n player.rotation = -1\n player.standing = False\n player.x += player.vel * player.rotation\n # Moving right\n elif keys[pygame.K_RIGHT] and player.x <= screen_width - player.width - player.vel:\n player.rotation = 1\n player.standing = False\n player.x += player.vel * player.rotation\n # Not moving\n else:\n player.standing = True\n player.walk_count = 0\n\n # In jump\n if player.is_jump:\n if player.jump_count >= -player.max_jump_count:\n neg = 1\n if player.jump_count < 0:\n neg = -1\n player.y -= (player.jump_count ** 2) * 0.5 * neg\n player.jump_count -= 1\n else:\n player.is_jump = False\n player.jump_count = player.max_jump_count\n # Not in jump\n else:\n if keys[pygame.K_UP]:\n player.is_jump = True\n player.standing = False\n player.walk_count = 0\n\n # Shooting\n if keys[pygame.K_SPACE] and shoot_cooldown == 0:\n # Maximum of 4 projectiles at the time\n if len(projectiles) < 5:\n # Create new projectile and add it into projectiles list\n projectiles.append(Projectile(\n round(player.x + player.width / 2),\n round(player.y + player.height / 2),\n player.rotation))\n shoot_cooldown = 1\n\n # Godmode\n if keys[pygame.K_x]:\n if player.godmode:\n player.godmode = False\n else:\n player.godmode = True\n\n # Manage cooldown for shooting\n if shoot_cooldown > max_shoot_cooldown:\n shoot_cooldown = 0\n elif shoot_cooldown > 0:\n shoot_cooldown += 1\n\n return shoot_cooldown\n\n\ndef redraw_game_window(win, background, score, wave, deaths, player, enemies, projectiles):\n '''Redraw the window (used for next frame)\n\n Arguments:\n win {window} -- Game window\n background {pygame image} -- Background image for game\n player {Player} -- Instance of Player class\n enemies {list} -- List of Enemy class instances\n projectiles {list} -- List of Projectile class instances\n '''\n # Draw background\n win.blit(background, (0, 0))\n # Score text\n roboto45 = pygame.font.SysFont('Roboto', 45)\n roboto30 = pygame.font.SysFont('Roboto', 30)\n\n wave_text = roboto45.render(f'Wave: {wave}', False, (0, 0, 0))\n score_text = roboto30.render(f'Score: {score}', False, (0, 0, 0))\n deaths_text = roboto30.render(f'Deaths: {deaths}', False, (0, 0, 0))\n enemies_text = roboto30.render(\n f'Enemies: {len(enemies)}', False, (0, 0, 0))\n\n win.blit(wave_text, (10, 10))\n win.blit(score_text, (10, 40))\n win.blit(deaths_text, (350, 60))\n win.blit(enemies_text, (350, 90))\n # Draw player\n if player:\n player.draw(win=win)\n # Draw every enemy\n for enemy in enemies:\n enemy.draw(win=win)\n # Draw every projectile\n for projectile in projectiles:\n projectile.draw(win=win)\n # Update display\n pygame.display.update()\n\n\ndef main():\n global SCREEN_WIDTH, SCREEN_HEIGHT, FRAMERATE, BACKGROUND\n\n # Set win to current window and setup pygame\n win = setup(SCREEN_WIDTH, SCREEN_HEIGHT)\n\n # Setup pygame clock for framerate\n clock = pygame.time.Clock()\n\n # Define music\n pygame.mixer.music.load('resources/music.mp3')\n pygame.mixer.music.play(-1)\n\n # Score counter\n score = 0\n # Wave counter\n wave = 1\n # Deaths counter\n deaths = 0\n\n # Create an empty list for projectiles\n projectiles = []\n # Create an empty list for enemies\n enemies = []\n # Create an empty list for players\n players = []\n\n # Setup cooldown for shooting\n shoot_cooldown = 0\n\n # Create an instance of Player (multiple instances are respawns)\n players.append(Player(x=randint(0, SCREEN_WIDTH - 70), y=410))\n # Create an instance of Enemy\n enemies.append(Enemy(x=randint(0, SCREEN_WIDTH - 70),\n y=410, start_x=0, end_x=SCREEN_WIDTH))\n\n while True:\n # Framerate\n clock.tick(FRAMERATE)\n\n if not check_events():\n break\n\n # Define player as 0th element from array\n try:\n player = players[0]\n except IndexError:\n deaths += 1\n players.append(Player(x=randint(0, SCREEN_WIDTH - 70), y=410))\n player = players[0]\n\n # Controls\n if player:\n shoot_cooldown = controls(player=player, projectiles=projectiles,\n screen_width=SCREEN_WIDTH - 70, shoot_cooldown=shoot_cooldown, max_shoot_cooldown=8 - (wave // 2))\n\n # Update entities\n enemies, kills = Enemy.update_all(\n enemies=enemies, projectiles=projectiles)\n projectiles = Projectile.update_all(projectiles=projectiles,\n screen_width=SCREEN_WIDTH)\n players = Player.update_all(players=players, enemies=enemies)\n\n # Update score\n score += kills\n\n # Spawn new enemies\n if len(enemies) == 0:\n wave += 1\n for n in range(0, randint(wave, round(wave * 1.5))):\n enemies.append(Enemy(x=randint(0, SCREEN_WIDTH - 70),\n y=410, start_x=0, end_x=SCREEN_WIDTH))\n # Health increse\n increase = randint(score, score + score * wave // 2)\n player.max_health += increase\n player.health += player.max_health // 2\n\n # Draw next frame\n redraw_game_window(win=win, background=BACKGROUND, score=score, wave=wave, deaths=deaths, player=player,\n enemies=enemies, projectiles=projectiles)\n\n\nif __name__ == '__main__':\n main()\n" } ]
2
hargunsinghgrover/CVL757_2021
https://github.com/hargunsinghgrover/CVL757_2021
5d9b48489ff052524a14480a66727cd827cca748
77ba9459176f26dd40689b6866a8247a52f5c1b4
cac39a205c4a0b795c58ea6e4f1b15cbd674a57d
refs/heads/main
2023-08-25T01:24:18.492643
2021-10-28T15:27:31
2021-10-28T15:27:31
403,611,546
0
0
null
2021-09-06T12:18:41
2021-08-31T15:20:17
2021-08-31T15:20:14
null
[ { "alpha_fraction": 0.5069789886474609, "alphanum_fraction": 0.5709931254386902, "avg_line_length": 21.650909423828125, "blob_id": "ba38c4cd9cb0ef696650313f8157f687595d1150", "content_id": "008a05e3be53b5d188d1bc88ae865a4db40ed75d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6233, "license_type": "no_license", "max_line_length": 113, "num_lines": 275, "path": "/2021AIZ8326_A4/2021AIZ8326_A4_Q2/2021AIZ8326_A4_Q2.py", "repo_name": "hargunsinghgrover/CVL757_2021", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[24]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# In[25]:\n\n\ndef PlaneFrameElementLength(x1,y1,x2,y2):\n \"\"\"This function returns the length of the plane frame element whose first node has coordinates (x1,y1) \n and second node has coordinates (x2,y2).\"\"\"\n \n return np.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1))\n\n\n# In[26]:\n\n\ndef PlaneFrameElementStiffness(E,A,I,L,theta):\n \"\"\"This function returns the element stiffness matrix for a plane frame element with modulus of elasticity E,\n cross-sectional area A, moment of inertia I, length L, and angle theta (in degrees). The size of the \n element stiffness matrix is 6 x 6.\"\"\"\n x = theta*np.pi/180\n C = np.cos(x)\n S = np.sin(x)\n w1 = A*C*C + 12*I*S*S/(L*L)\n w2 = A*S*S + 12*I*C*C/(L*L)\n w3 = (A-12*I/(L*L))*C*S\n w4 = 6*I*S/L\n w5 = 6*I*C/L\n y = E/L * np.array([[w1, w3, -w4, -w1, -w3, -w4], [w3, w2, w5, -w3, -w2, w5],\n [-w4, w5, 4*I, w4, -w5, 2*I], [-w1, -w3, w4, w1, w3, w4],\n [-w3, -w2, -w5, w3, w2, -w5], [-w4, w5, 2*I, w4, -w5, 4*I]])\n return y\n\n\n# In[27]:\n\n\ndef PlaneFrameAssemble(K,k,i,j):\n \"\"\"\"This function assembles the element stiffness matrix k of the plane frame element with nodes i and j \n into the global stiffness matrix K. This function returns the global stiffness matrix K after the \n element stiffness matrix k is assembled.\"\"\"\n temp = [3*i-3, 3*i-2, 3*i-1, 3*j-3, 3*j-2, 3*j-1]\n for i in range(len(temp)):\n for j in range(len(temp)):\n K[temp[i], temp[j]] += k[i, j]\n \n return K\n\n\n# In[28]:\n\n\ndef PlaneFrameElementForces(E,A,I,L,theta,u):\n \"\"\"This function returns the element force vector given the modulus of elasticity E, \n the cross-sectional area A, the moment of inertia I, the length L, the angle theta \n (in degrees), and the element nodal displacement vector u.\"\"\"\n \n x = theta * np.pi/180\n C = np.cos(x)\n S = np.sin(x)\n w1 = E*A/L\n w2 = 12*E*I/(L*L*L)\n w3 = 6*E*I/(L*L)\n w4 = 4*E*I/L\n w5 = 2*E*I/L\n kprime = np.array([[w1, 0, 0, -w1, 0, 0], [0, w2, w3, 0, -w2, w3], \n [0, w3, w4, 0, -w3, w5], [-w1, 0, 0, w1, 0, 0],\n [0, -w2, -w3, 0, w2, -w3], [0, w3, w5, 0, -w3, w4]])\n\n T = np.array([[C, S, 0, 0, 0, 0], [-S, C, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0],\n [0, 0, 0, C, S, 0], [0, 0, 0, -S, C, 0], [0, 0, 0, 0, 0, 1]])\n y = np.dot(kprime,np.dot(T,u))\n \n return y\n\n\n# In[29]:\n\n\ndef PlaneFrameElementAxialDiagram(f, L):\n \"\"\"\"This function plots the axial force diagram for the plane frame element with nodal \n force vector f and length L.\"\"\"\n \n x = [0, L]\n z = [-f[0,0] , f[3,0]]\n plt.plot(x,z)\n plt.ylabel('Axial Force (kN)')\n plt.show()\n\n\n# In[30]:\n\n\ndef PlaneFrameElementShearDiagram(f, L):\n \"\"\"\"This function plots the shear force diagram for the plane frame element with nodal \n force vector f and length L.\"\"\"\n \n x = [0, L]\n z = [f[1,0] , -f[4,0]]\n plt.plot(x,z)\n plt.ylabel('Shear Force (kN)')\n plt.show()\n\n\n# In[31]:\n\n\ndef PlaneFrameElementMomentDiagram(f, L):\n \"\"\"\"This function plots the bending moment diagram for the plane frame element with nodal \n force vector f and length L.\"\"\"\n \n x = [0, L]\n z = [-f[2,0] , f[5,0]]\n plt.plot(x,z)\n plt.ylabel('Shear Force (kN)')\n plt.show()\n\n\n# In[32]:\n\n\ndef PlaneFrameInclinedSupport(T,i,alpha):\n \"\"\"This function calculates the tranformation matrix T of the inclined \n support at node i with angle of inclination alpha (in degrees).\"\"\"\n x = alpha*pi/180\n T[3*i-3,3*i-3] = np.cos(x)\n T[3*i-3,3*i-2] = np.sin(x)\n T[3*i-3,3*i-1] = 0\n T[3*i-2,3*i-3] = -np.sin(x)\n T[3*i-2,3*i-2] = np.cos(x)\n T[3*i-2,3*i-1] = 0\n T[3*i-1,3*i-3] = 0\n T[3*i-1,3*i-2] = 0\n T[3*i-1,3*i-1] = 1\n return T\n\n\n# In[33]:\n\n\n##Step 1 : Initializing the problem\n\nE = 200e6\nI = 1e-6\nA = 4e-2\nL1 = PlaneFrameElementLength(0,3,2,0)\nL2 = 4\nnodes = [1,2,3]\nnode_connections = [(1,2), (2,3)]\nlength = [L1, L2]\ntheta = [360-np.arctan(3/2)*180/np.pi, 0]\n\n\n# In[34]:\n\n\n## Step 2 : Element Stiffness Matrices\n\nk = []\n\nfor node in range(len(node_connections)):\n k1 = PlaneFrameElementStiffness(E,A,I,length[node],theta[node])\n k.append(k1)\n\n\n# In[35]:\n\n\n## Step 3 : Global Stiffness Matrix\n\nK = np.zeros((3*len(nodes), 3*len(nodes)))\nfor node in range(len(node_connections)):\n K=PlaneFrameAssemble(K,k[node],node_connections[node][0],node_connections[node][1])\n\nK\n\n\n# In[36]:\n\n\n## Step 4 : Applying Boundary Conditions\n\nU=np.zeros((len(nodes)*3,1)) \nF=np.zeros((len(nodes)*3,1)) \n\nU[0,0] = 0\nU[1,0] = 0\nU[2,0] = 0\nU[6,0] = 0\nU[7,0] = 0\nU[8,0] = 0\n\nF[3,0] = 0\nF[4,0] = -16\nF[5,0] = -10.667\n\n\n# In[37]:\n\n\n## Step 5 : Solving the Equations\n\nbound = [3, 4, 5]\n\nUp=U[bound]\nFp=F[bound]\nKpp=K[bound]\nKpp=Kpp[:,bound]\n\n\nUp=np.dot(np.linalg.inv(Kpp),Fp)\nprint(\"Displacements and Rotations at Node 2 [U2x U2y Phi2]\")\nprint(Up)\n\n\n# In[38]:\n\n\n## Post - processing\n\nU[bound]=Up\n\nforce = []\nfor i in range(3*len(nodes)):\n if i not in bound:\n force.append(i)\n\nF=np.dot(K,U)\nprint(\"Reactions at Node 1, and 3 are [F1x, F21y, M1, F3x, F3y, M3]\")\nprint(F[force,0])\n\n\n# In[39]:\n\n\n## Axial Force, Shear Force and Bending Moment\n\nu = [] \nf = []\nfor node in node_connections:\n u1 = np.asarray([U[node[0]*3-3], U[node[0]*3-2], U[node[0]*3-1], \n U[node[1]*3-3], U[node[1]*3-2], U[node[1]*3-1]])\n u.append(u1)\n\nfor i in range(len(node_connections)):\n f1 = PlaneFrameElementForces(E,A,I,length[i],theta[i],u[i])\n if i == 1:\n f1 = f1 - np.array([[0, -16, -10.667, 0, -16, 10.667]]).reshape((6,1))\n f.append(f1)\n print(\"The Axial Force, Shear Force and Bending Moment in Element \" + str(i+1) + \" is\" + '\\n', f1)\n\n\n# In[43]:\n\n\n## AFD, SFD and BMD\n\nfor i in range(len(f)):\n print(\"Axial Force Diagram for Element \"+ str(i+1))\n PlaneFrameElementAxialDiagram(f[i],length[i])\n print(\"Shear Force Diagram for Element \"+ str(i+1))\n PlaneFrameElementShearDiagram(f[i],length[i])\n print(\"Bending Moment Diagram for Element \"+ str(i+1))\n PlaneFrameElementMomentDiagram(f[i],length[i])\n \n\n\n# In[ ]:\n\n\n\n\n" }, { "alpha_fraction": 0.5672025680541992, "alphanum_fraction": 0.610075056552887, "avg_line_length": 18.340248107910156, "blob_id": "1e41ae8042bbb66f7f8eba0e084ffd5f57ac1ea6", "content_id": "86b1446fd7f086bcfe2d80fc0163984dc74760ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4665, "license_type": "no_license", "max_line_length": 107, "num_lines": 241, "path": "/2021AIZ8326_A2/2021AIZ8326_A2_Q3/2021AIZ8326_A2_Q3.py", "repo_name": "hargunsinghgrover/CVL757_2021", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[36]:\n\n\ndef BeamElementStiffness(E,I,L):\n \"\"\"This function returns the element stiffness matrix for a beam element with modulus of elasticity E, \n moment of inertia I, and length L. The size of the element stiffness matrix is 4 x 4.\"\"\"\n\n y = E*I/(L*L*L) * np.array([[12, 6*L, -12, 6*L], [6*L, 4*L*L, -6*L, 2*L*L,],\n [-12, -6*L, 12, -6*L], [6*L, 2*L*L, -6*L, 4*L*L,]])\n\n return y\n\n\n# In[37]:\n\n\ndef BeamAssemble(K,k,i,j):\n \"\"\"\"This function assembles the element stiffness matrix k of the beam element with nodes i and j \n into the global stiffness matrix K. This function returns the global stiffness matrix K after the \n element stiffness matrix k is assembled.\"\"\"\n temp = [2*i-2, 2*i-1, 2*j-2, 2*j-1]\n for i in range(len(temp)):\n for j in range(len(temp)):\n K[temp[i], temp[j]] += k[i, j]\n \n return K\n\n\n# In[38]:\n\n\ndef BeamElementForces(k,u):\n \"\"\"\"This function returns the element nodal force vector given the element stiffness matrix k \n and the element nodal displacement vector u.\"\"\" \n return np.dot(k, u)\n\n\n# In[39]:\n\n\ndef BeamElementShearDiagram(f, L):\n \"\"\"\"This function plots the shear force diagram for the beam element with nodal \n force vector f and length L.\"\"\"\n \n x = [0, L]\n z = [f[0,0] , -f[2,0]]\n plt.plot(x,z)\n plt.ylabel('Shear Force (kN)')\n plt.show()\n\n\n# In[40]:\n\n\ndef BeamElementMomentDiagram(f, L):\n \"\"\"\"This function plots the shear force diagram for the beam element with nodal \n force vector f and length L.\"\"\"\n \n x = [0, L]\n z = [-f[1,0] , f[3,0]]\n plt.plot(x,z)\n plt.ylabel('Bending Moment (kN.m)')\n plt.show()\n\n\n# In[41]:\n\n\ndef SpringElementStiffness(k):\n \"\"\"This function returns the element stiffness matrix for a spring with stiffness k.\n The size of the element stiffness matrix is 2 x 2.\"\"\"\n \n y = np.array([[k, -k], [-k, k]])\n return y\n\n\n# In[42]:\n\n\ndef SpringAssemble(K,k,i,j):\n \"\"\"This function assembles the element stiffness matrix k of the spring \n with nodes i and j into the global stiffness matrix K. This function returns \n the global stiffness matrix K after the element stiffness matrix k is assembled.\"\"\"\n \n K[i,i] += k[0,0]\n K[i,j] += k[0,1]\n\n K[j,i] += k[1,0]\n K[j,j] += k[1,1]\n \n return K\n\n\n# In[43]:\n\n\ndef SpringElementForces(k,u):\n \"\"\"This function returns the element nodal force vector given the element \n stiffness matrix k and the element nodal displacement vector u.\"\"\"\n \n y = np.dot(k, u)\n \n return y\n\n\n# In[44]:\n\n\n##Step 1 : Initializing the problem\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nE = 70e6\nI = 40e-6\nL = 3\nnodes = [1,2,3]\nnode_connections = [(1,2), (2,3)]\nlength = [L, L]\n\n\n# In[45]:\n\n\n## Step 2 : Element Stiffness Matrices\n\nk1 = BeamElementStiffness(E,I,L)\nk2 = BeamElementStiffness(E,I,L)\nk3 = SpringElementStiffness(5000)\n\nelement_stiffness = [k1, k2, k3]\n\n\n# In[46]:\n\n\n## Step 3 : Global Stiffness Matrix\n\nK = np.zeros((2*len(nodes)+1, 2*len(nodes)+1))\nK = BeamAssemble(K,k1,1,2)\nK = BeamAssemble(K,k2,2,3)\nK = SpringAssemble(K,k3,2,6)\n\nK\n\n\n# In[47]:\n\n\n## Step 4 : Applying Boundary Conditions\n\nU=np.zeros((len(nodes)*2+1,1)) \nF=np.zeros((len(nodes)*2+1,1)) \n\nU[0,0] = 0\nU[1,0] = 0\nU[4,0] = 0\nU[6,0] = 0\n\nF[2,0] = -10\nF[3,0] = 0\nF[5,0] = 0\n\n\n# In[48]:\n\n\n## Step 5 : Solving the Equations\n\nbound = [2,3,5]\n\nUp=U[bound]\nFp=F[bound]\nKpp=K[bound]\nKpp=Kpp[:,bound]\n\n\nUp=np.dot(np.linalg.inv(Kpp),Fp)\nprint(\"Deflection of Node 2 and Rotations of Node 2 and 3 are [U2 Phi2 Phi3]\")\nprint(Up)\n\n\n# In[49]:\n\n\n## Post - processing\n\nU[bound]=Up\n\nforce = []\nfor i in range(2*len(nodes)+1):\n if i not in bound:\n force.append(i)\n\nF=np.dot(K,U)\nprint(\"Reactions at Node 1, 3, 4 are [F1y, M1, F3y, F4y]\")\nprint(F[force,0])\n\n\n# In[50]:\n\n\n## Shear Force and Bending Moment\n\nu = [] \nf = []\nfor node in node_connections:\n u1 = np.asarray([U[node[0]*2-2],U[node[0]*2-1],U[node[1]*2-2],U[node[1]*2-1]])\n u.append(u1)\n\nu.append([U[2],U[6]])\n\nfor i in range(len(node_connections)):\n f1 = BeamElementForces(element_stiffness[i], u[i])\n f.append(f1)\n print(\"The shear Force and Bending Moment in Element \" + str(i+1) + \" is\" + '\\n', f1)\n\n\n# In[51]:\n\n\nf3 = SpringElementForces(element_stiffness[2], u[2])\nprint(\"The Spring Element Force is \" + '\\n', f3)\n\n\n# In[52]:\n\n\n## SFD and BMD\n\nfor i in range(len(f)):\n print(\"Shear Force Diagram for Element \"+ str(i+1))\n BeamElementShearDiagram(f[i],length[i])\n print(\"Bending Moment Diagram for Element \"+ str(i+1))\n BeamElementMomentDiagram(f[i],length[i])\n \n\n\n# In[ ]:\n\n\n\n\n" }, { "alpha_fraction": 0.5582468509674072, "alphanum_fraction": 0.6058247089385986, "avg_line_length": 17.72432518005371, "blob_id": "bab043ca440e095b7361bb91877b036aae1c324a", "content_id": "526ea4ef3dfe90fdda55f3277f7b105dd0d55097", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3468, "license_type": "no_license", "max_line_length": 107, "num_lines": 185, "path": "/2021AIZ8326_A2/2021AIZ8326_A2_Q1/2021AIZ8326_A2_Q1.py", "repo_name": "hargunsinghgrover/CVL757_2021", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[67]:\n\n\ndef BeamElementStiffness(E,I,L):\n \"\"\"This function returns the element stiffness matrix for a beam element with modulus of elasticity E, \n moment of inertia I, and length L. The size of the element stiffness matrix is 4 x 4.\"\"\"\n\n y = E*I/(L*L*L) * np.array([[12, 6*L, -12, 6*L], [6*L, 4*L*L, -6*L, 2*L*L,],\n [-12, -6*L, 12, -6*L], [6*L, 2*L*L, -6*L, 4*L*L,]])\n\n return y\n\n\n# In[68]:\n\n\ndef BeamAssemble(K,k,i,j):\n \"\"\"\"This function assembles the element stiffness matrix k of the beam element with nodes i and j \n into the global stiffness matrix K. This function returns the global stiffness matrix K after the \n element stiffness matrix k is assembled.\"\"\"\n temp = [2*i-2, 2*i-1, 2*j-2, 2*j-1]\n for i in range(len(temp)):\n for j in range(len(temp)):\n K[temp[i], temp[j]] += k[i, j]\n \n return K\n\n\n# In[69]:\n\n\ndef BeamElementForces(k,u):\n \"\"\"\"This function returns the element nodal force vector given the element stiffness matrix k \n and the element nodal displacement vector u.\"\"\" \n return np.dot(k, u)\n\n\n# In[70]:\n\n\ndef BeamElementShearDiagram(f, L):\n \"\"\"\"This function plots the shear force diagram for the beam element with nodal \n force vector f and length L.\"\"\"\n \n x = [0, L]\n z = [f[0,0] , -f[2,0]]\n plt.plot(x,z)\n plt.ylabel('Shear Force (kN)')\n plt.show()\n\n\n# In[71]:\n\n\ndef BeamElementMomentDiagram(f, L):\n \"\"\"\"This function plots the shear force diagram for the beam element with nodal \n force vector f and length L.\"\"\"\n \n x = [0, L]\n z = [-f[1,0] , f[3,0]]\n plt.plot(x,z)\n plt.ylabel('Bending Moment (kN.m)')\n plt.show()\n\n\n# In[72]:\n\n\n##Step 1 : Initializing the problem\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nE = 210e6\nI = 60e-6\nL1 = 2\nL2 = 2\nnodes = [1,2,3]\nnode_connections = [(1,2), (2,3)]\nlength = [L1, L2]\n\n\n# In[73]:\n\n\n## Step 2 : Element Stiffness Matrices\n\nk1 = BeamElementStiffness(E,I,L1)\nk2 = BeamElementStiffness(E,I,L2)\n\nelement_stiffness = [k1,k2]\n\n\n# In[74]:\n\n\n## Step 3 : Global Stiffness Matrix\n\nK = np.zeros((2*len(nodes), 2*len(nodes)))\nK = BeamAssemble(K,k1,1,2)\nK = BeamAssemble(K,k2,2,3)\n\nK\n\n\n# In[75]:\n\n\n## Step 4 : Applying Boundary Conditions\n\nU=np.zeros((len(nodes)*2,1)) \nF=np.zeros((len(nodes)*2,1)) \n\nU[0,0] = 0\nU[1,0] = 0\nU[4,0] = 0\n\nF[2,0] = -20\nF[3,0] = 0\nF[5,0] = 0\n\n\n# In[76]:\n\n\n## Step 5 : Solving the Equations\n\nbound = [2,3,5]\n\nUp=U[bound]\nFp=F[bound]\nKpp=K[bound]\nKpp=Kpp[:,bound]\n\n\nUp=np.dot(np.linalg.inv(Kpp),Fp)\nprint(\"Nodal Displacements and rotations of Node 2 and Node 3[U2y Phi2 Phi3]\")\nprint(Up)\n\n\n# In[77]:\n\n\n## Post - processing\n\nU[bound]=Up\n\nF=np.dot(K,U)\nprint(\"Reactions at Node 1 and 3 [F1y, M1, F3y]\")\nprint(F[[0,1,4]])\n\n\n# In[78]:\n\n\n## Shear Force and Bending Moment\n\nu = [] \nf = []\nfor node in node_connections:\n u1 = np.asarray([U[node[0]*2-2],U[node[0]*2-1],U[node[1]*2-2],U[node[1]*2-1]])\n u.append(u1)\n\nfor i in range(len(node_connections)):\n f1 = BeamElementForces(element_stiffness[i], u[i])\n f.append(f1)\n print(\"The shear Force and Bending Moment in Element \" + str(i+1) + \" is\" + '\\n', f1)\n\n\n# In[79]:\n\n\n## SFD and BMD\n\nfor i in range(len(f)):\n print(\"Shear Force Diagram for Element \"+ str(i+1))\n BeamElementShearDiagram(f[i],length[i])\n print(\"Bending Moment Diagram for Element \"+ str(i+1))\n BeamElementMomentDiagram(f[i],length[i])\n \n\n\n# In[ ]:\n\n\n\n\n" }, { "alpha_fraction": 0.5433680415153503, "alphanum_fraction": 0.5967440605163574, "avg_line_length": 18, "blob_id": "f7d0f7a780dcbc86852838d534116899ed99f44a", "content_id": "09fd6a800a278ea9bcadc2b473b91aab7943332b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3747, "license_type": "no_license", "max_line_length": 107, "num_lines": 197, "path": "/2021AIZ8326_A2/2021AIZ8326_A2_Q2/2021AIZ8326_A2_Q2.py", "repo_name": "hargunsinghgrover/CVL757_2021", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\ndef BeamElementStiffness(E,I,L):\n \"\"\"This function returns the element stiffness matrix for a beam element with modulus of elasticity E, \n moment of inertia I, and length L. The size of the element stiffness matrix is 4 x 4.\"\"\"\n\n y = E*I/(L*L*L) * np.array([[12, 6*L, -12, 6*L], [6*L, 4*L*L, -6*L, 2*L*L,],\n [-12, -6*L, 12, -6*L], [6*L, 2*L*L, -6*L, 4*L*L,]])\n\n return y\n\n\n# In[2]:\n\n\ndef BeamAssemble(K,k,i,j):\n \"\"\"\"This function assembles the element stiffness matrix k of the beam element with nodes i and j \n into the global stiffness matrix K. This function returns the global stiffness matrix K after the \n element stiffness matrix k is assembled.\"\"\"\n temp = [2*i-2, 2*i-1, 2*j-2, 2*j-1]\n for i in range(len(temp)):\n for j in range(len(temp)):\n K[temp[i], temp[j]] += k[i, j]\n \n return K\n\n\n# In[3]:\n\n\ndef BeamElementForces(k,u):\n \"\"\"\"This function returns the element nodal force vector given the element stiffness matrix k \n and the element nodal displacement vector u.\"\"\" \n return np.dot(k, u)\n\n\n# In[4]:\n\n\ndef BeamElementShearDiagram(f, L):\n \"\"\"\"This function plots the shear force diagram for the beam element with nodal \n force vector f and length L.\"\"\"\n \n x = [0, L]\n z = [f[0,0] , -f[2,0]]\n plt.plot(x,z)\n plt.ylabel('Shear Force (kN)')\n plt.show()\n\n\n# In[5]:\n\n\ndef BeamElementMomentDiagram(f, L):\n \"\"\"\"This function plots the shear force diagram for the beam element with nodal \n force vector f and length L.\"\"\"\n \n x = [0, L]\n z = [-f[1,0] , f[3,0]]\n plt.plot(x,z)\n plt.ylabel('Bending Moment (kN.m)')\n plt.show()\n\n\n# In[6]:\n\n\n##Step 1 : Initializing the problem\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nE = 210e6\nI = 5e-6\nL1 = 3\nL2 = 4\nL3 = 2\nnodes = [1,2,3,4]\nnode_connections = [(1,2), (2,3), (3,4)]\nlength = [L1, L2, L3]\n\n\n# In[8]:\n\n\n## Step 2 : Element Stiffness Matrices\n\nk1 = BeamElementStiffness(E,I,L1)\nk2 = BeamElementStiffness(E,I,L2)\nk3 = BeamElementStiffness(E,I,L3)\n\nelement_stiffness = [k1, k2, k3]\n\n\n# In[9]:\n\n\n## Step 3 : Global Stiffness Matrix\n\nK = np.zeros((2*len(nodes), 2*len(nodes)))\nK = BeamAssemble(K,k1,1,2)\nK = BeamAssemble(K,k2,2,3)\nK = BeamAssemble(K,k3,3,4)\n\nK\n\n\n# In[10]:\n\n\n## Step 4 : Applying Boundary Conditions\n\nU=np.zeros((len(nodes)*2,1)) \nF=np.zeros((len(nodes)*2,1)) \n\nU[0,0] = 0\nU[2,0] = 0\nU[4,0] = 0\nU[6,0] = 0\nU[7,0] = 0\n\nF[1,0] = 0\nF[3,0] = -9.333\nF[5,0] = 9.333\n\n\n# In[12]:\n\n\n## Step 5 : Solving the Equations\n\nbound = [1,3,5]\n\nUp=U[bound]\nFp=F[bound]\nKpp=K[bound]\nKpp=Kpp[:,bound]\n\n\nUp=np.dot(np.linalg.inv(Kpp),Fp)\nprint(\"Rotations of Node 1, 2 and 3 are [Phi1 Phi2 Phi3]\")\nprint(Up)\n\n\n# In[14]:\n\n\n## Post - processing\n\nU[bound]=Up\n\nforce = []\nfor i in range(2*len(nodes)):\n if i not in bound:\n force.append(i)\n\nF=np.dot(K,U)\nprint(\"Reactions at Node 1, 2, 3, 4 are [F1y, F2y, F3y, F4y, M4]\")\nprint(F[force,0])\n\n\n# In[23]:\n\n\n## Shear Force and Bending Moment\n\nu = [] \nf = []\nfor node in node_connections:\n u1 = np.asarray([U[node[0]*2-2],U[node[0]*2-1],U[node[1]*2-2],U[node[1]*2-1]])\n u.append(u1)\n\nfor i in range(len(node_connections)):\n f1 = BeamElementForces(element_stiffness[i], u[i])\n if i == 1:\n f1 = f1 - np.array([[-14, -9.333, -14, 9.333]]).reshape((4,1))\n f.append(f1)\n print(\"The shear Force and Bending Moment in Element \" + str(i+1) + \" is\" + '\\n', f1)\n\n\n# In[24]:\n\n\n## SFD and BMD\n\nfor i in range(len(f)):\n print(\"Shear Force Diagram for Element \"+ str(i+1))\n BeamElementShearDiagram(f[i],length[i])\n print(\"Bending Moment Diagram for Element \"+ str(i+1))\n BeamElementMomentDiagram(f[i],length[i])\n \n\n\n# In[ ]:\n\n\n\n\n" } ]
4
shaojinding/speech
https://github.com/shaojinding/speech
698c6ce59bcb3f5d1391cee9a8e17225abfe8f98
3a19c2a025844913caf4c5190448d5af0e8059ea
fd8437551db90899fabaecc5e9e9be55e20ab93f
refs/heads/master
2021-06-05T06:18:11.093099
2016-09-01T18:50:56
2016-09-01T18:50:56
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7137573957443237, "alphanum_fraction": 0.7167159914970398, "avg_line_length": 35.5405387878418, "blob_id": "5513bb892d7a4a751124c53949cbd08a25b4f90f", "content_id": "c142050f9aa9885c7020186f3f255f5dd9b5f4ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1352, "license_type": "no_license", "max_line_length": 211, "num_lines": 37, "path": "/speech/views.py", "repo_name": "shaojinding/speech", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse\n\n#from django_auth0.auth_backend import Auth0Backend\n#from django_auth0.auth_helpers import process_login\n\ndef index(request):\n #process_login(request)\n #authback = Auth0Backend()\n #if authback.authenticate():\n # context_dict = {'boldmessage': \"Authenticate!\"}\n #else:\n # context_dict = {'boldmessage': \"I am bold font from the context\"}\n if 'profile' in request.session:\n user = request.session['profile']\n context_dict = {'boldmessage': user['name']}\n else:\n context_dict = {'boldmessage': \"Hello\"}\n return render(request, 'speech/index.html', context_dict)\n\n@login_required()\ndef record(request):\n infotext = \"The voiced dental fricative is pronounced with the tip of the tongue against the teeth, while your glottis vibrates. This is a rare sound that does not exist in most European and Asian languages\"\n context_dict = {'infotext': infotext}\n return render(request, 'speech/record.html', context_dict)\n\ndef annotate(request):\n return render(request, 'speech/annotate.html')\n\ndef build(request):\n return render(request, 'speech/build.html')\n\ndef synthesize(request):\n return render(request, 'speech/synthesize.html')\n\n# Create your views here.\n" }, { "alpha_fraction": 0.6038251519203186, "alphanum_fraction": 0.6038251519203186, "avg_line_length": 31.454545974731445, "blob_id": "090b0acd80e4ceb3a51033357d0b65d1368a68a0", "content_id": "76df8130e5e1c0b7c29e5cb878cb5ff9e7852dff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 366, "license_type": "no_license", "max_line_length": 65, "num_lines": 11, "path": "/speech/urls.py", "repo_name": "shaojinding/speech", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\r\nfrom speech import views\r\n\r\nurlpatterns = [\r\n url(r'^$', views.index, name='index'),\r\n url(r'^record', views.record, name='record'),\r\n url(r'^annotate', views.annotate, name='annotate'),\r\n url(r'^build', views.build, name='build'),\r\n url(r'^synthesize', views.synthesize, name='synthesize'),\r\n\r\n]" }, { "alpha_fraction": 0.7037037014961243, "alphanum_fraction": 0.7469135522842407, "avg_line_length": 42.20000076293945, "blob_id": "0124c22d577183105f8fd3d8321c95b05fb14f5b", "content_id": "d8b25ef08a2bf70dbbf7f93b339900d60fa9851c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 648, "license_type": "no_license", "max_line_length": 235, "num_lines": 15, "path": "/django_auth0/views.py", "repo_name": "shaojinding/speech", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom .auth_helpers import process_login\nfrom django.shortcuts import redirect\n\n\ndef auth_callback(request):\n return process_login(request)\n\ndef log_out(request):\n user = request.session.pop('profile')\n client_id = user['clientID']\n return redirect('https://shjd.auth0.com/v2/logout?returnTo=http://127.0.0.1:8000/speech/&client_id={}'.format(client_id))\n\ndef log_in(request):\n return redirect('https://shjd.auth0.com/authorize?response_type=code&scope=openid%20profile&client_id=GfnvKP8rFiGCaBXauuNEulqY8EapxJmp&redirect_uri=http://127.0.0.1:8000/auth/callback/?&connection=Username-Password-Authentication')\n" } ]
3
Enforcer/zeromq-plays
https://github.com/Enforcer/zeromq-plays
a2495465420b411e3293c07dd15410eb886f4f02
2fd1babfeb91e1998bfe2704bfcb28f4dbb4544f
ad212c719b8315f96675b1a8d0c2561a1455abc2
refs/heads/master
2022-11-07T13:05:18.406381
2020-06-25T14:35:57
2020-06-25T14:35:57
274,939,582
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6442952752113342, "alphanum_fraction": 0.6523489952087402, "avg_line_length": 19.135135650634766, "blob_id": "90770cf56fc2c21c345ffd8858dbcfca05f05672", "content_id": "fcf5dab05ff9e5e3e825550dcf99ece460aa59f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 745, "license_type": "no_license", "max_line_length": 75, "num_lines": 37, "path": "/api.py", "repo_name": "Enforcer/zeromq-plays", "src_encoding": "UTF-8", "text": "import uuid\nimport random\n\nimport fastapi\nimport zmq\nimport zmq.asyncio\n\nctx = zmq.asyncio.Context()\n\napp = fastapi.FastAPI()\n\n\norder_ids = iter(range(10000))\n\n@app.get(\"/status\")\ndef status():\n return {\"status\": \"ok\"}\n\n@app.get(\"/orders\")\nasync def post_order():\n order = {\"id\": next(order_ids), \"side\": random.choice([\"BUY\", \"SELL\"])}\n\n report = await send_order_and_get_execution_report(order)\n\n return report\n\n\nasync def send_order_and_get_execution_report(order):\n socket = ctx.socket(zmq.DEALER)\n try:\n socket.setsockopt(zmq.IDENTITY, str(uuid.uuid4()).encode())\n socket.connect(\"ipc://ms.ipc\")\n\n await socket.send_json(order)\n return await socket.recv_json()\n finally:\n \tsocket.close()\n" }, { "alpha_fraction": 0.5908163189888, "alphanum_fraction": 0.5928571224212646, "avg_line_length": 22.878047943115234, "blob_id": "c32b97415e9fcf378f1ec77d2924ea7789f2014b", "content_id": "50c2aa6828b8f1c5f8171016f23b3869c9ac5b94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 980, "license_type": "no_license", "max_line_length": 86, "num_lines": 41, "path": "/ms.py", "repo_name": "Enforcer/zeromq-plays", "src_encoding": "UTF-8", "text": "import asyncio\nimport json\n\nimport zmq\nimport zmq.asyncio\n\nctx = zmq.asyncio.Context()\n\nsocket = ctx.socket(zmq.ROUTER)\nsocket.bind(\"ipc://ms.ipc\")\n\n\norders = {\"BUY\": [], \"SELL\": []}\n\n\nasync def main():\n while True:\n data = await socket.recv_multipart()\n print('Got', data)\n identity = data[0]\n order = json.loads(data[1])\n\n other_side = \"BUY\" if order[\"side\"] == \"SELL\" else \"SELL\"\n execution_report = {\"status\": None}\n if orders[other_side]:\n orders[other_side].pop()\n execution_report[\"status\"] = \"MATCHED\"\n else:\n orders[order[\"side\"]].append(order)\n execution_report[\"status\"] = \"NEW\"\n\n #input('enter by kontynuowac')\n await socket.send_multipart([identity, json.dumps(execution_report).encode()])\n print('Orders now', orders)\n\n\ntry:\n asyncio.get_event_loop().run_until_complete(main())\nexcept KeyboardInterrupt:\n socket.close()\n ctx.term()\n\n" } ]
2
nextgis/rekod_storage
https://github.com/nextgis/rekod_storage
7d74f19eb570209500c91eab965042a29d905b72
fed88e83647006add646010c0f16ec2a6aef689b
af04fbb531461d4c3e5014daa5b9a39f5caf6334
refs/heads/master
2015-08-12T13:52:04.497827
2015-06-03T15:15:37
2015-06-03T15:15:37
22,059,772
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6347268223762512, "alphanum_fraction": 0.6473509669303894, "avg_line_length": 39.63793182373047, "blob_id": "5a81b188e547652942cb8a044888ef9e88d3062a", "content_id": "b2e7c866847627e4ecd8624da223cf1c00600cd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 4832, "license_type": "no_license", "max_line_length": 131, "num_lines": 116, "path": "/geosync/CMakeLists.txt", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "# **************************************************************************** \r\n# * Project: geosync\r\n# * Purpose: cmake script\r\n# * Author: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru\r\n# ****************************************************************************\r\n# * Copyright (C) 2014 Bishop\r\n# * Copyright (C) 2014 NextGIS\r\n# *\r\n# * This program is free software: you can redistribute it and/or modify\r\n# * it under the terms of the GNU General Public License as published by\r\n# * the Free Software Foundation, either version 3 of the License, or\r\n# * (at your option) any later version.\r\n# *\r\n# * This program is distributed in the hope that it will be useful,\r\n# * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# * GNU General Public License for more details.\r\n# *\r\n# * You should have received a copy of the GNU General Public License\r\n# * along with this program. If not, see <http://www.gnu.org/licenses/>.\r\n# ****************************************************************************\r\ncmake_minimum_required (VERSION 2.8)\r\nproject (geosync)\r\n\r\nset(CMAKE_CONFIGURATION_TYPES \"Debug;Release\" CACHE STRING \"Configs\" FORCE)\r\nset(CMAKE_COLOR_MAKEFILE ON)\r\n\r\nfile(READ ${CMAKE_CURRENT_SOURCE_DIR}/include/version.h GEOSYNC_VERSION_H_CONTENTS)\r\nstring(REGEX MATCH \"GEOSYNC_MAJOR_VERSION[ \\t]+([0-9]+)\"\r\n GEOSYNC_MAJOR_VERSION ${GEOSYNC_VERSION_H_CONTENTS})\r\nstring (REGEX MATCH \"([0-9]+)\"\r\n GEOSYNC_MAJOR_VERSION ${GEOSYNC_MAJOR_VERSION})\r\nstring(REGEX MATCH \"GEOSYNC_MINOR_VERSION[ \\t]+([0-9]+)\"\r\n GEOSYNC_MINOR_VERSION ${GEOSYNC_VERSION_H_CONTENTS})\r\nstring (REGEX MATCH \"([0-9]+)\"\r\n GEOSYNC_MINOR_VERSION ${GEOSYNC_MINOR_VERSION})\r\nstring(REGEX MATCH \"GEOSYNC_RELEASE_NUMBER[ \\t]+([0-9]+)\"\r\n GEOSYNC_RELEASE_NUMBER ${GEOSYNC_VERSION_H_CONTENTS}) \r\nstring (REGEX MATCH \"([0-9]+)\"\r\n GEOSYNC_RELEASE_NUMBER ${GEOSYNC_RELEASE_NUMBER})\r\n\r\n# Setup package meta-data\r\nmessage(STATUS \"c++ compiler ... \" ${CMAKE_CXX_COMPILER})\r\n\r\ninclude_directories(${CMAKE_CURRENT_SOURCE_DIR})\r\ninclude_directories(${CMAKE_CURRENT_BINARY_DIR})\r\ninclude_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)\r\n\r\nset(GEOSYNC_CURRENT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})\r\nset(GEOSYNC_CURRENT_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR})\r\n\r\n# set path to additional CMake modules\r\nset(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake ${CMAKE_MODULE_PATH})\r\n\r\n# uninstall target\r\nconfigure_file(\r\n \"${CMAKE_MODULE_PATH}/cmake_uninstall.cmake.in\"\r\n \"${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake\"\r\n IMMEDIATE @ONLY)\r\n\r\n# For windows, do not allow the compiler to use default target (Vista).\r\nif(WIN32)\r\n add_definitions(-D_WIN32_WINNT=0x0501)\r\nendif(WIN32)\r\n\r\nadd_definitions(-DSTRICT)\r\n\r\nif(MSVC OR MSVC_IDE)\r\n #string(REPLACE \"/W4\" \"/W0\" CMAKE_C_FLAGS \"${CMAKE_C_FLAGS}\")\r\n #string(REPLACE \"/W4\" \"/W0\" CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS}\")\r\n # string(REPLACE \"/Gm\" CMAKE_CXX_FLAGS_DEBUG \"${CMAKE_CXX_FLAGS_DEBUG}\")\r\n #set(CMAKE_CXX_FLAGS_DEBUG \"/Gm /ZI /W3 /Od\")\r\n # add_definitions(-DDISABLE_SOME_FLOATING_POINT)\r\n # set_target_properties( ${the_target} PROPERTIES COMPILE_FLAGS \"/Gm\" )\r\n if(CMAKE_CL_64)\r\n set_target_properties(${the_target} PROPERTIES STATIC_LIBRARY_FLAGS \"/machine:x64\")\r\n add_definitions(-D_WIN64)\r\n endif()\r\n \r\n if( MSVC_VERSION GREATER 1600 )\r\n set(CMAKE_GENERATOR_TOOLSET \"v120_xp\" CACHE STRING \"Platform Toolset\" FORCE) \r\n add_definitions(-D_USING_V120_SDK71_)\r\n endif() \r\n\r\nendif()\r\n\r\nif(UNIX)\r\n if(CMAKE_COMPILER_IS_GNUCXX OR CV_ICC)\r\n set(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -fPIC -fno-strict-aliasing\")#-Wextra -Wall -W -pthread -O2 -fno-strict-aliasing -pthrea\r\n set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -fPIC -fno-strict-aliasing\")\r\n endif()\r\n # Select flags.\r\n# set(CMAKE_CXX_FLAGS_RELWITHDEBINFO \"-O0 -g\")\r\n# set(CMAKE_CXX_FLAGS_RELEASE \"-O\")\r\n# set(CMAKE_CXX_FLAGS_DEBUG \"-Wall -g -O\")\r\n# set(CMAKE_C_FLAGS_RELWITHDEBINFO \"-O0 -g\")\r\n# set(CMAKE_C_FLAGS_RELEASE \"-O\")\r\n# set(CMAKE_C_FLAGS_DEBUG \"-Wall -g -O2\")\r\nendif()\r\n\r\noption(GEOSYNC_SERVICE_TASK \"Set ON to build geosync service task\" ON)\r\nif(GEOSYNC_SERVICE_TASK)\r\n add_subdirectory(${GEOSYNC_CURRENT_SOURCE_DIR}/src/task/)\r\nendif(GEOSYNC_SERVICE_TASK)\r\n\r\noption(GEOSYNC_APP \"Set ON to build geosync application\" ON)\r\nif(GEOSYNC_APP)\r\n add_subdirectory(${GEOSYNC_CURRENT_SOURCE_DIR}/src/app/)\r\nendif(GEOSYNC_APP)\r\n\r\noption(wxGIS_BUILD_TRANSLATION \"Set ON to build translation\" ON)\r\nif(wxGIS_BUILD_TRANSLATION)\r\n add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/opt/)\r\nendif(wxGIS_BUILD_TRANSLATION)\r\n\r\nadd_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake)\r\n\r\n" }, { "alpha_fraction": 0.7062937021255493, "alphanum_fraction": 0.7104895114898682, "avg_line_length": 37.55555725097656, "blob_id": "0c2a96dd79b1a6f44b4ac69c1b68ec3000e1ea71", "content_id": "1a038b1415cfe278d3b903e70b7afa052591605a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 715, "license_type": "no_license", "max_line_length": 107, "num_lines": 18, "path": "/geosync/cmake/installapp.cmake", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "set_target_properties(${APP_NAME}\r\n\tPROPERTIES PROJECT_LABEL ${PROJECT_NAME}\r\n VERSION ${WXGISMON_VERSION}\r\n SOVERSION 1\r\n\tARCHIVE_OUTPUT_DIRECTORY ${WXGISMON_CURRENT_BINARY_DIR}\r\n LIBRARY_OUTPUT_DIRECTORY ${WXGISMON_CURRENT_BINARY_DIR}\r\n RUNTIME_OUTPUT_DIRECTORY ${WXGISMON_CURRENT_BINARY_DIR} \r\n )\r\n\r\nif(WIN32)\r\n install(TARGETS ${APP_NAME} DESTINATION ${WXGISMON_CURRENT_BINARY_DIR}/Debug/ CONFIGURATIONS Debug)\r\n install(TARGETS ${APP_NAME} DESTINATION ${WXGISMON_CURRENT_BINARY_DIR}/Release/ CONFIGURATIONS Release)\r\nelse()\r\n install(TARGETS ${APP_NAME}\r\n RUNTIME DESTINATION bin/wxgis\r\n ARCHIVE DESTINATION lib/wxgis\r\n LIBRARY DESTINATION lib/wxgis )\r\nendif() \r\n\r\n" }, { "alpha_fraction": 0.5478068590164185, "alphanum_fraction": 0.5579078197479248, "avg_line_length": 27.456693649291992, "blob_id": "a843026ea2142e93a1e0e02455a6c973efc2751e", "content_id": "608886d71af8af7606ed1a41312f13f8dbfa6b95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7227, "license_type": "no_license", "max_line_length": 121, "num_lines": 254, "path": "/geosync/src/app/tskmngr.cpp", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "/******************************************************************************\n * Project: geosync\n * Purpose: sync spatial data with NGW\n * Author: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru\n ******************************************************************************\n* Copyright (C) 2014-2015 NextGIS\n*\n* This program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n ****************************************************************************/\n\n#include \"app/tskmngr.h\"\n#include \"wxgis/core/config.h\"\n\n#include \"../../art/geosync.xpm\"\n#include \"../art/state.xpm\" //path relative to ngm sources/include\n\n#define TIMER_UPDATE_PERIOD 1050\n\n//-----------------------------------------------------------------------------\n// GeoSyncTaskManager\n//-----------------------------------------------------------------------------\n\nIMPLEMENT_CLASS(GeoSyncTaskManager, wxTaskBarIcon)\n\n\nBEGIN_EVENT_TABLE(GeoSyncTaskManager, wxTaskBarIcon)\n EVT_MENU(wxID_EXIT, GeoSyncTaskManager::OnExit)\n EVT_TASKBAR_LEFT_UP(GeoSyncTaskManager::OnLeftUp)\n EVT_MENU(ID_MANAGE, GeoSyncTaskManager::OnManage)\n EVT_MENU(ID_START_SYNC, GeoSyncTaskManager::OnStartAllSyncTasks)\n EVT_TIMER(ID_TIMER, GeoSyncTaskManager::OnTimer)\nEND_EVENT_TABLE()\n\nGeoSyncTaskManager::GeoSyncTaskManager(wxTaskBarIconType iconType) : wxTaskBarIcon(iconType)\n{\n wxInitAllImageHandlers();\n m_pTaskManager = GetTaskManager();\n m_timer.SetOwner(this, ID_TIMER);\n\n unsigned nCount = 0;\n while (!m_pTaskManager->IsValid() && nCount < 254)\n {\n wxTheApp->Yield(true);\n wxMilliSleep(150);\n nCount++;\n }\n\n m_pGeoSyncCat = NULL;\n if (m_pTaskManager)\n {\n m_pGeoSyncCat = m_pTaskManager->GetCategory(GEOSYNCCAT);\n if (!m_pGeoSyncCat)\n {\n //create the new category\n if (m_pTaskManager->CreateCategory(GEOSYNCCAT))\n m_pGeoSyncCat = m_pTaskManager->GetCategory(GEOSYNCCAT);\n }\n }\n\n m_TaskCategoryCookie = wxNOT_FOUND;\n m_ImageList.Create(16, 16);\n //0 - info, 1 - complete, 2 - error, 3 - warning, 4 - work, 5 - queued, 6 - done, 7 - paused, 8 - deleted\n m_ImageList.Add(wxBitmap(state_xpm));\n m_ImageList.Add(wxIcon(geosync_xpm));\n if (!m_pGeoSyncCat)\n { \n m_nLastIcon = 2;\n SetIcon(m_ImageList.GetIcon(m_nLastIcon), m_pTaskManager->GetLastError());\n }\n else\n {\n m_TaskCategoryCookie = m_pGeoSyncCat->Advise(this);\n\n int nRunCount = m_pGeoSyncCat->GetRunTaskCount();\n if (nRunCount > 0)\n {\n m_nLastIcon = 4;\n SetIcon(m_ImageList.GetIcon(m_nLastIcon), wxString::Format(_(\"%d task(s) run\"), nRunCount));\n }\n else\n {\n m_nLastIcon = 9;\n SetIcon(m_ImageList.GetIcon(m_nLastIcon), _(\"All tasks finished\"));\n }\n }\n\n m_nExtraTime = 0;\n m_timer.Start(TIMER_UPDATE_PERIOD);\n\n m_pGeoSyncTaskDlg = new GeoSyncTaskDlg(NULL);\n}\n\nGeoSyncTaskManager::~GeoSyncTaskManager(void)\n{ \n wxDELETE(m_pGeoSyncTaskDlg);\n m_timer.Stop();\n if (NULL != m_pGeoSyncCat && m_TaskCategoryCookie != wxNOT_FOUND)\n {\n m_pGeoSyncCat->Unadvise(m_TaskCategoryCookie);\n m_pGeoSyncCat = NULL; \n }\n \n\twsDELETE(m_pTaskManager);\n}\n\nvoid GeoSyncTaskManager::OnExit(wxCommandEvent& event)\n{\n if (m_pGeoSyncTaskDlg)\n {\n m_pGeoSyncTaskDlg->Destroy();\n }\n\twxExit();\n}\n\nwxMenu *GeoSyncTaskManager::CreatePopupMenu()\n{\n\twxMenu* pMenu = new wxMenu(); \n pMenu->Append(ID_MANAGE, _(\"Manage sync tasks\"));\n pMenu->Append(ID_START_SYNC, _(\"Start all sync tasks\"));\n //pMenu->Append(wxID_PREFERENCES, _(\"Properties\"));\n pMenu->AppendSeparator();\n\tpMenu->Append(wxID_EXIT, _(\"Exit\"));\n\t\n\treturn pMenu;\n}\n\nvoid GeoSyncTaskManager::OnLeftUp(wxTaskBarIconEvent& event)\n{\n //show tasks dialog\n ShowTasksDialog();\n}\n\nvoid GeoSyncTaskManager::OnManage(wxCommandEvent& event)\n{\n //show tasks dialog\n ShowTasksDialog();\n}\n\nvoid GeoSyncTaskManager::OnStartAllSyncTasks(wxCommandEvent& event)\n{\n if (m_pGeoSyncCat)\n {\n for (size_t i = 0; i < m_pGeoSyncCat->GetSubTaskCount(); ++i)\n {\n wxGISTask* pTask = wxDynamicCast(m_pGeoSyncCat->GetSubTask(i), wxGISTask);\n if (pTask)\n pTask->StartTask();\n }\n }\n}\n\nvoid GeoSyncTaskManager::OnTimer(wxTimerEvent & event)\n{\n if (!m_pGeoSyncCat)\n return;\n\n wxString sMsg;\n int nWork = 0;\n int nQuered = 0;\n int nDone = 0;\n int nError = 0;\n for (size_t i = 0; i < m_pGeoSyncCat->GetSubTaskCount(); ++i)\n {\n wxGISTask* pTask = wxDynamicCast(m_pGeoSyncCat->GetSubTask(i), wxGISTask);\n if (pTask)\n {\n switch (pTask->GetState())\n {\n case enumGISTaskWork:\n nWork++;\n break;\n case enumGISTaskDone:\n nDone++;\n break;\n case enumGISTaskQuered:\n nQuered++;\n break;\n case enumGISTaskPaused:\n nDone++;\n break;\n case enumGISTaskError:\n nError++;\n break;\n }\n }\n }\n\n //0 - info, 1 - complete, 2 - error, 3 - warning, 4 - work, 5 - queued, 6 - done, 7 - paused, 8 - deleted, 9 - normal\n if (nError > 0)\n {\n SetIcon(m_ImageList.GetIcon(2), wxString::Format(_(\"%d task(s) have errors\"), nError));\n m_nLastIcon = 2;\n }\n else if (nWork > 0)\n {\n if (m_nLastIcon == 4)\n m_nLastIcon = 9;\n else\n m_nLastIcon = 4;\n SetIcon(m_ImageList.GetIcon(m_nLastIcon), wxString::Format(_(\"%d task(s) run\"), nWork));\n }\n else if (nQuered > 0)\n {\n if (m_nLastIcon == 5)\n m_nLastIcon = 9;\n else\n m_nLastIcon = 5;\n SetIcon(m_ImageList.GetIcon(m_nLastIcon), wxString::Format(_(\"%d task(s) quered\"), nQuered));\n }\n else if (nDone > 0)\n {\n if (m_nLastIcon == 9)\n {\n }\n else if (m_nLastIcon == 6 && m_nExtraTime > 3)\n {\n m_nLastIcon = 9;\n m_nExtraTime = 0;\n }\n else\n {\n m_nLastIcon = 6;\n m_nExtraTime++;\n }\n SetIcon(m_ImageList.GetIcon(m_nLastIcon), _(\"All tasks finished\"));\n }\n else\n {\n m_nLastIcon = 9;\n SetIcon(m_ImageList.GetIcon(m_nLastIcon), _(\"All tasks finished\"));\n }\n}\n\nvoid GeoSyncTaskManager::ShowTasksDialog()\n{\n if (!m_pGeoSyncTaskDlg)\n return;\n\n if (m_pGeoSyncTaskDlg->IsShown())\n return;\n\n m_pGeoSyncTaskDlg->Show();\n}" }, { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.5616631507873535, "avg_line_length": 39.735294342041016, "blob_id": "d32114701f7ab2845b024d35ad1457b60d1a34c8", "content_id": "70c317588b215f903e0e8eec0dca28af01ec8183", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1419, "license_type": "no_license", "max_line_length": 79, "num_lines": 34, "path": "/geosync/include/resource.h", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "//{{NO_DEPENDENCIES}}\r\n/******************************************************************************\r\n * Project: geosync\r\n * Purpose: resources def\r\n * Author: Baryshnikov Dmitry (aka Bishop), polimax@mail.ru\r\n ******************************************************************************\r\n* Copyright (C) 2014 NextGIS\r\n*\r\n* This program is free software: you can redistribute it and/or modify\r\n* it under the terms of the GNU General Public License as published by\r\n* the Free Software Foundation, either version 3 of the License, or\r\n* (at your option) any later version.\r\n*\r\n* This program is distributed in the hope that it will be useful,\r\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n* GNU General Public License for more details.\r\n*\r\n* You should have received a copy of the GNU General Public License\r\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\r\n ****************************************************************************/\r\n//\r\n#define archive \t\t101\r\n\r\n// Next default values for new objects\r\n// \r\n#ifdef APSTUDIO_INVOKED\r\n#ifndef APSTUDIO_READONLY_SYMBOLS\r\n#define _APS_NEXT_RESOURCE_VALUE 102\r\n#define _APS_NEXT_COMMAND_VALUE 40001\r\n#define _APS_NEXT_CONTROL_VALUE 1001\r\n#define _APS_NEXT_SYMED_VALUE 101\r\n#endif\r\n#endif\r\n" }, { "alpha_fraction": 0.7108433842658997, "alphanum_fraction": 0.7108433842658997, "avg_line_length": 19.25, "blob_id": "b06c79aa6e745271db21d090c36335b768a1d119", "content_id": "1295d3e45bd28786ff0e2c5a9adffdeee6f2ea4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 83, "license_type": "no_license", "max_line_length": 29, "num_lines": 4, "path": "/qgis-installer/src/TMSforRES/pluggins.conf.ini", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "[additionalhelp]\r\nurl = d:\\builds\\plugins\\\r\n[Tester]\r\nurl = d:\\Development\\NextGIS\\" }, { "alpha_fraction": 0.5581395626068115, "alphanum_fraction": 0.5581395626068115, "avg_line_length": 9.75, "blob_id": "d7b788e0883c1206e29d8fc75148f2fbe300d2e4", "content_id": "94834b0d13f0047d7699c34a29d78b68e4a6c890", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 43, "license_type": "no_license", "max_line_length": 13, "num_lines": 4, "path": "/README.md", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "rekod-storage\n=============\n\nRekod-storage\n" }, { "alpha_fraction": 0.7172995805740356, "alphanum_fraction": 0.7291139364242554, "avg_line_length": 51.681819915771484, "blob_id": "224b022d0a372da220f38a2d7c0d037180c98c8c", "content_id": "df7d66484e045480792d67b90ba00c729d190844", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1185, "license_type": "no_license", "max_line_length": 254, "num_lines": 22, "path": "/geosync/cmake/app.cmake", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "project (geosync${PROJECT_NAME})\r\n\r\nmessage(STATUS \"${PROJECT_NAME} app name ${APP_NAME}\")\r\n\r\nset(CMAKE_CONFIGURATION_TYPES \"Debug;Release\" CACHE STRING \"Configs\" FORCE)\r\n\r\ninclude_directories(${CMAKE_CURRENT_BINARY_DIR})\r\nfile(WRITE ${CMAKE_CURRENT_BINARY_DIR}/version_app.h \"//Copyright (C) 2014 NextGIS\\n//Copyright (C) 2014 Baryshnikov Dmitry (aka Bishop), polimax@mail.ru\\n#pragma once\\n#define GEOSYNC_FILENAME \\\"${APP_NAME}\\\"\\n#define GEOSYNC_MAINFAMEICON \\\"${GEOSYNC_MAINFAMEICON}\\\"\\n\\n\" )\r\n\r\nif(MSVC)\r\n set(CMAKE_DEBUG_POSTFIX \"d\")\r\n set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${GEOSYNC_CURRENT_BINARY_DIR}/Debug/)\r\n set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${GEOSYNC_CURRENT_BINARY_DIR}/Release/)\r\n add_definitions(-D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE)\r\n add_definitions(-D_UNICODE -DUNICODE -D_USRDLL)\r\n set(PROJECT_CSOURCES ${PROJECT_CSOURCES} ${GEOSYNC_CURRENT_SOURCE_DIR}/src/version_app.rc ${GEOSYNC_MAINFAMEICON} ${GEOSYNC_MAINFAMEICON_X})\r\n source_group(\"Resource Files\" FILES ${GEOSYNC_CURRENT_SOURCE_DIR}/src/version_app.rc ${GEOSYNC_MAINFAMEICON} ${GEOSYNC_MAINFAMEICON_X}) \r\nendif(MSVC)\r\n\r\nif(WIN32)\r\n add_definitions(-DWIN32 -D__WXMSW__)\r\nendif(WIN32)\r\n\r\n\r\n" }, { "alpha_fraction": 0.6150850057601929, "alphanum_fraction": 0.6255311369895935, "avg_line_length": 27.88359832763672, "blob_id": "f8a66dfcfbb3a2b281c45b3d0407df25619315a5", "content_id": "c1947e1723a3595e6af47318b50518144a6f2ffa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 5648, "license_type": "no_license", "max_line_length": 136, "num_lines": 189, "path": "/geosync/cmake/FindGDAL.cmake", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "# - Try to find the GDAL encryption library\r\n# Once done this will define\r\n#\r\n# GDAL_ROOT_DIR - Set this variable to the root installation of GDAL\r\n#\r\n# Read-Only variables:\r\n# GDAL_FOUND - system has the GDAL library\r\n# GDAL_INCLUDE_DIR - the GDAL include directory\r\n# GDAL_LIBRARIES - The libraries needed to use GDAL\r\n# GDAL_VERSION - This is set to $major.$minor.$revision (eg. 0.9.8)\r\n\r\n#=============================================================================\r\n# Copyright 2012 Dmitry Baryshnikov <polimax at mail dot ru>\r\n#\r\n# Distributed under the OSI-approved BSD License (the \"License\");\r\n# see accompanying file Copyright.txt for details.\r\n#\r\n# This software is distributed WITHOUT ANY WARRANTY; without even the\r\n# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\r\n# See the License for more information.\r\n#=============================================================================\r\n# (To distribute this file outside of CMake, substitute the full\r\n# License text for the above reference.)\r\nMACRO(DBG_MSG _MSG)\r\n MESSAGE(STATUS\r\n \"${CMAKE_CURRENT_LIST_FILE}(${CMAKE_CURRENT_LIST_LINE}): ${_MSG}\")\r\nENDMACRO(DBG_MSG)\r\n\r\n\r\nif (UNIX)\r\n find_package(PkgConfig)\r\n if (PKG_CONFIG_FOUND)\r\n pkg_check_modules(_GDAL gdal)\r\n endif (PKG_CONFIG_FOUND)\r\nendif (UNIX)\r\n\r\nset(_GDAL_ROOT_HINTS\r\n\t$ENV{GDAL}\r\n\t$ENV{GDAL_ROOT}\r\n\t$ENV{LIB}\r\n\t$ENV{LIB_HOME}/gdal\r\n\t${GDAL_ROOT_DIR}\r\n\t/usr/lib\r\n\t/usr/local/lib\r\n)\r\n \r\nset(_GDAL_ROOT_PATHS\r\n\t$ENV{GDAL}\r\n\t$ENV{GDAL_ROOT}\r\n\t$ENV{LIB}\r\n\t$ENV{LIB_HOME}/gdal\r\n\t/usr/lib\r\n\t/usr/local/lib\r\n)\r\n\r\nif(MSVC)\r\n set(P_SUFF \"lib\" \"lib/Release\" \"lib/Debug\")\r\n if(CMAKE_CL_64)\r\n\t\tset(P_SUFF ${P_SUFF} \"lib/x64\")\r\n\t\tset(_GDAL_ROOT_HINTS ${_GDAL_ROOT_HINTS}\r\n\t\t\t$ENV{GDAL}/lib/x64\r\n\t\t\t$ENV{GDAL_ROOT}/lib/x64\r\n\t\t\t${GDAL_ROOT_DIR}/lib/x64\r\n\t\t)\r\n\t\t\r\n\t\tset(_GDAL_ROOT_PATHS ${_GDAL_ROOT_PATHS}\r\n\t\t\t$ENV{GDAL}/lib/x64\r\n\t\t\t$ENV{GDAL_ROOT}/lib/x64\r\n\t\t\t${GDAL_ROOT_DIR}/lib/x64\r\n\t\t)\r\n\telse(CMAKE_CL_64)\r\n set(P_SUFF ${P_SUFF} \"lib/x86\")\r\n\t\tset(_GDAL_ROOT_HINTS ${_GDAL_ROOT_HINTS}\r\n\t\t\t$ENV{GDAL}/lib/x86\r\n\t\t\t$ENV{GDAL_ROOT}/lib/x86\r\n\t\t\t${GDAL_ROOT_DIR}/lib/x86\r\n\t\t)\r\n\t\t\r\n\t\tset(_GDAL_ROOT_PATHS ${_GDAL_ROOT_PATHS}\r\n\t\t\t$ENV{GDAL}/lib/x86\r\n\t\t\t$ENV{GDAL_ROOT}/lib/x86\t\t\t\r\n\t\t\t${GDAL_ROOT_DIR}/lib/x86\r\n\t\t) \r\n\tendif(CMAKE_CL_64)\r\nendif()\r\n\r\nfind_path(GDAL_INCLUDE_DIR\r\n NAMES\r\n gdal.h\r\n gcore/gdal.h\r\n HINTS\r\n ${_GDAL_INCLUDE_DIR}\r\n ${_GDAL_ROOT_HINTS_AND_PATHS}\r\n PATH_SUFFIXES\r\n \"include\"\r\n \"include/gdal\"\r\n \"local/include/gdal\"\r\n)\r\n\r\nmessage(STATUS \"GDAL_INCLUDE_DIR=[${GDAL_INCLUDE_DIR}]\")\r\n\r\nif (GDAL_INCLUDE_DIR)\r\n\r\n find_path(GDAL_VERSION_DIR gdal_version.h HINTS ${GDAL_INCLUDE_DIR} PATH_SUFFIXES \"gcore\")\r\n if(GDAL_VERSION_DIR)\r\n file(READ \"${GDAL_VERSION_DIR}/gdal_version.h\" _gdal_VERSION_H_CONTENTS)\r\n \r\n# if(WIN32)\r\n# file(READ \"${GDAL_INCLUDE_DIR}/gcore/gdal_version.h\" _gdal_VERSION_H_CONTENTS)\r\n# else(WIN32)\r\n# file(READ \"${GDAL_INCLUDE_DIR}/gdal_version.h\" _gdal_VERSION_H_CONTENTS)\r\n# endif(WIN32)\r\n\r\n string(REGEX MATCH \"GDAL_VERSION_MAJOR[ \\t]+([0-9]+)\" GDAL_MAJOR_VERSION ${_gdal_VERSION_H_CONTENTS})\r\n string(REGEX MATCH \"([0-9]+)\" GDAL_MAJOR_VERSION ${GDAL_MAJOR_VERSION})\r\n string(REGEX MATCH \"GDAL_VERSION_MINOR[ \\t]+([0-9]+)\" GDAL_MINOR_VERSION ${_gdal_VERSION_H_CONTENTS})\r\n string(REGEX MATCH \"([0-9]+)\" GDAL_MINOR_VERSION ${GDAL_MINOR_VERSION})\r\n string(REGEX MATCH \"GDAL_VERSION_REV[ \\t]+([0-9]+)\" GDAL_RELEASE_NUMBER ${_gdal_VERSION_H_CONTENTS}) \r\n string(REGEX MATCH \"([0-9]+)\" GDAL_RELEASE_NUMBER ${GDAL_RELEASE_NUMBER})\r\n \r\n # Setup package meta-data\r\n set(GDAL_VERSION ${GDAL_MAJOR_VERSION}.${GDAL_MINOR_VERSION} CACHE INTERNAL \"The version number for wxgis libraries\")\r\n DBG_MSG(\"GDAL_VERSION : ${GDAL_VERSION}\") \r\n\r\n endif()\r\nendif (GDAL_INCLUDE_DIR)\r\n\r\nfind_library(GDAL_RELEASE\r\n NAMES\r\n gdal${GDAL_MAJOR_VERSION}${GDAL_MINOR_VERSION}.lib\r\n gdal${GDAL_MAJOR_VERSION}${GDAL_MINOR_VERSION}.so\r\n gdal${GDAL_MAJOR_VERSION}${GDAL_MINOR_VERSION}.a\r\n libgdal.so\r\n PATHS \r\n\t\t${_GDAL_ROOT_PATHS}\r\n\t\t${GDAL_INCLUDE_DIR}\r\n\tPATH_SUFFIXES\r\n\t\t${P_SUFF}\r\n NO_DEFAULT_PATH\r\n)\t\r\nfind_library(GDAL_DEBUG\r\n NAMES\r\n gdal${GDAL_MAJOR_VERSION}${GDAL_MINOR_VERSION}d.lib \r\n gdal${GDAL_MAJOR_VERSION}${GDAL_MINOR_VERSION}d.so \r\n gdal${GDAL_MAJOR_VERSION}${GDAL_MINOR_VERSION}d.a \r\n libgdald.so\r\n PATHS\r\n\t\t${_GDAL_ROOT_PATHS}\r\n\t\t${GDAL_INCLUDE_DIR}\r\n\tPATH_SUFFIXES\r\n\t\t${P_SUFF}\r\n\tNO_DEFAULT_PATH\r\n)\r\n\t\r\nif(NOT GDAL_RELEASE AND GDAL_DEBUG)\r\n\tset(GDAL_RELEASE ${GDAL_DEBUG})\r\nendif(NOT GDAL_RELEASE AND GDAL_DEBUG)\r\n\t\r\nif(NOT GDAL_DEBUG AND GDAL_RELEASE)\r\n set(GDAL_DEBUG ${GDAL_RELEASE})\r\nendif(NOT GDAL_DEBUG AND GDAL_RELEASE)\r\n\r\nLIST(APPEND GDAL_LIBRARIES\r\n debug ${GDAL_DEBUG} optimized ${GDAL_RELEASE}\r\n )\r\n\t\t\r\nDBG_MSG(\"GDAL_LIBRARIES : ${GDAL_LIBRARIES}\") \r\n\t\t\r\ninclude(FindPackageHandleStandardArgs)\r\n\r\nif (GDAL_VERSION)\r\n find_package_handle_standard_args(GDAL\r\n REQUIRED_VARS\r\n GDAL_LIBRARIES\r\n GDAL_INCLUDE_DIR\r\n VERSION_VAR\r\n GDAL_VERSION\r\n FAIL_MESSAGE\r\n \"Could NOT find GDAL, try to set the path to GDAL root folder in the system variable GDAL_ROOT\"\r\n )\r\nelse (GDAL_VERSION)\r\n find_package_handle_standard_args(GDAL \"Could NOT find GDAL, try to set the path to GDAL root folder in the system variable GDAL_ROOT\"\r\n GDAL_LIBRARIES\r\n GDAL_INCLUDE_DIR\r\n )\r\nendif (GDAL_VERSION)\r\n\r\nmessage(STATUS \"gdal libs=[${GDAL_LIBRARIES}] headers=[${GDAL_INCLUDE_DIR}]\")\r\nMARK_AS_ADVANCED(GDAL_INCLUDE_DIR GDAL_LIBRARIES)\r\n" }, { "alpha_fraction": 0.7878788113594055, "alphanum_fraction": 0.7878788113594055, "avg_line_length": 15.5, "blob_id": "2807686902efb2ee6c9b3df27942da8494bf19dc", "content_id": "0b689c53179c21360f74b8452e0789683a4d4e76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 33, "license_type": "no_license", "max_line_length": 22, "num_lines": 2, "path": "/qgis-installer/Installer-Files/nextgis_qgis.ini", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "[RunInfo]\r\nwhether_first_run=true" }, { "alpha_fraction": 0.6638417840003967, "alphanum_fraction": 0.665859580039978, "avg_line_length": 33.43055725097656, "blob_id": "7726113a39e0429faa85d91a223e4b9e134bde8e", "content_id": "686feb90a6b3d18c0e8bd569d8d568a3fe855cca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2478, "license_type": "no_license", "max_line_length": 106, "num_lines": 72, "path": "/geosync/include/app/app.h", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "/******************************************************************************\n * Project: geosync\n * Purpose: sync spatial data with NGW\n * Author: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru\n ******************************************************************************\n* Copyright (C) 2014 NextGIS\n*\n* This program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n ****************************************************************************/\n\n#pragma once\n\n#include \"wxgis/base.h\"\n#include \"wxgis/core/init.h\"\n#include \"wxgis/geoprocessing/tskmngr.h\"\n#include \"app/tskmngr.h\"\n#include \"version.h\"\n\n#include <wx/app.h>\n#include <wx/snglinst.h>\n#include <wx/cmdline.h>\n#include <wx/taskbar.h>\n\n/** @class GeoSyncApp\n\n Main spatial data syncronization application.\n\n*/\nclass GeoSyncApp :\n\tpublic wxApp,\n public wxGISInitializer\n{\npublic:\n\tGeoSyncApp(void);\n\tvirtual ~GeoSyncApp(void);\n // wxAppConsole\n virtual bool OnInit();\n virtual int OnExit();\n // wxGISInitializer\n\tvirtual bool Initialize(const wxString &sAppName, const wxString &sLogFilePrefix);\n // IApplication\n virtual bool SetupSys(const wxString &sSysPath);\n virtual wxString GetAppName(void) const {return m_appName;};\n\tvirtual wxString GetAppDisplayName(void) const{return m_appDisplayName;};\n virtual wxString GetAppDisplayNameShort(void) const {return wxString(_(\"Geo Sync\"));};\n virtual wxString GetAppVersionString(void) const {return wxString(GEOSYNC_VERSION_NUM_DOT_STRING_T);};\n virtual void OnAppAbout(void);\n virtual void OnAppOptions(void);\n\t//\n\tvirtual void OnUnhandledException();\n\tvirtual void OnFatalException();\n\tvirtual bool OnExceptionInMainLoop();\n virtual void OnEventLoopEnter(wxEventLoopBase* loop);\nprotected:\n#ifdef wxUSE_SNGLINST_CHECKER\n wxSingleInstanceChecker *m_pChecker;\n#endif\n GeoSyncTaskManager* m_pTaskManager;\n};\n\nDECLARE_APP(GeoSyncApp)" }, { "alpha_fraction": 0.6127574443817139, "alphanum_fraction": 0.6147572994232178, "avg_line_length": 39.657867431640625, "blob_id": "7a6e37a5b130e486d124ea459c1b8637e061c642", "content_id": "e1473d21dbe624bfbe3ab5ba866e91d4dbf13745", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 38503, "license_type": "no_license", "max_line_length": 262, "num_lines": 947, "path": "/geosync/src/task/task.cpp", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "/******************************************************************************\n* Project: geosync\n* Purpose: sync spatial data with NGW\n* Author: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru\n******************************************************************************\n* Copyright (C) 2014 NextGIS\n*\n* This program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n****************************************************************************/\n\n#include \"task/task.h\"\n#include \"wxgis/core/json/jsonval.h\"\n#include \"wxgis/core/json/jsonreader.h\"\n#include \"wxgis/core/json/jsonwriter.h\"\n#include \"wxgis/datasource/sysop.h\"\n#include \"wxgis/catalog/gxarchfolder.h\"\n#include \"wxgis/carto/mapbitmap.h\"\n#include \"wxgis/datasource/sysop.h\"\n\n#include \"gdal_priv.h\"\n\n#define TEMP_DIR \".geosync\"\n#define REMOTE_LIST \"remote.json\"\n#define TEMP_NAME_PREFIX wxT(\"~ngwtemp_\")\n\n//-----------------------------------------------------------------------------\n// GeoSyncTask\n//-----------------------------------------------------------------------------\n\nGeoSyncTask::GeoSyncTask(const wxString &sLocalPath, const wxString& sURL, const wxString& sUser, const wxString& sPasswd, long nRemoteId, geoSyncDirection eDirection)\n{\n m_sLocalPath = sLocalPath;\n m_sURL = sURL;\n m_sUser = sUser;\n m_sPasswd = sPasswd;\n m_nRemoteId = nRemoteId;\n m_eDirection = eDirection;\n}\n\nGeoSyncTask::~GeoSyncTask(void)\n{ \n\n}\n\nbool GeoSyncTask::Execute(ITrackCancel * const pTrackCancel)\n{\n wxLogMessage(_(\"Start task\"));\n wxSetWorkingDirectory(m_sLocalPath);\n\n wxGISAppConfig oConfig = GetConfig();\n if (oConfig.IsOk())\n oConfig.ReportPaths();\n\n wxGxCatalog *pCatalog = new wxGxCatalog();\n SetGxCatalog(pCatalog);\n\n if (!pCatalog->Init())\n {\n wxDELETE(pCatalog);\n wxGISLogError(_(\"Init catalog failed\"), wxEmptyString, wxEmptyString, pTrackCancel);\n return false;\n }\n\n pCatalog->SetShowHidden(true);\n\n pCatalog->Refresh();\n\n //1. load remote list\n wxGxNGWService* pService = new wxGxNGWService(m_sURL, m_sUser, m_sPasswd, pCatalog, wxT(\"remote\"));\n if (!pService->Connect())\n {\n wxGISLogError(_(\"Remote host unreachable\"), wxEmptyString, wxEmptyString, pTrackCancel);\n SetGxCatalog(NULL);\n return false;\n }\n\n wxJSONValue JSONResource;\n JSONResource[\"resource\"][\"children\"] = true;\n JSONResource[\"resource\"][\"display_name\"] = wxString(wxT(\"remote\"));\n JSONResource[\"resource\"][\"id\"] = m_nRemoteId;\n\n wxGxNGWResourceGroup* pRemoteDir = new wxGxNGWResourceGroup(pService, JSONResource, pService);\n \n //2. load local files list\n wxGxFolder* pLocalDir = wxDynamicCast(pCatalog->FindGxObjectByPath(CPLString(m_sLocalPath.ToUTF8())), wxGxFolder);\n \n bool bRet = SyncSources(pLocalDir, pRemoteDir, m_eDirection, pTrackCancel);\n\n SetGxCatalog(NULL);\n\n wxGISLogMessage(wxString::Format(_(\"Task %s\"), bRet ? _(\"succeeded\") : _(\"failed\")), pTrackCancel);\n\n /*//yield\n wxDateTime dtBeg = wxDateTime::Now();\n wxTimeSpan Elapsed = wxDateTime::Now() - dtBeg;\n //wxFprintf(stdout, wxString(_(\"Exiting\\n\")));\n int nSec = 2;\n while (Elapsed.GetSeconds() < nSec)\n {\n wxTheApp->Yield(true);\n Elapsed = wxDateTime::Now() - dtBeg;\n int nTest = nSec - Elapsed.GetSeconds().ToLong();\n if (nSec != nTest)\n {\n //wxFprintf(stdout, wxString::Format(wxT(\"%d sec.\\r\"), nTest));\n nSec = nTest;\n }\n\n }*/\n\n return bRet;\n}\n\nbool GeoSyncTask::SyncSources(wxGxFolder* const pLocalDir, wxGxNGWResourceGroup* const pRemoteDir, geoSyncDirection eDirection, ITrackCancel * const pTrackCancel)\n{\n if (NULL == pLocalDir || NULL == pRemoteDir)\n {\n wxGISLogError(_(\"SyncSources failed\"), _(\"pLocalDir and/or pRemoteDir is null\"), wxEmptyString, pTrackCancel);\n return false;\n }\n\n //if (wxGISEQUALN(pLocalDir->GetPath(), \"/vsi\", 4))\n // return true;\n\n pRemoteDir->Refresh(); //to load children without update thread\n pLocalDir->Refresh();\n\n //3. load remote cached list\n\n std::map<wxString, enumSyncType> mstCachedDir;\n wxString sRemoteCachedList = wxString::FromUTF8(pLocalDir->GetPath()) + wxFileName::GetPathSeparator() + wxString(wxT(TEMP_DIR)) + wxFileName::GetPathSeparator() + wxString(wxT(REMOTE_LIST));\n if (wxFileName::FileExists(sRemoteCachedList))\n {\n wxFileInputStream StorageInputStream(sRemoteCachedList);\n wxJSONReader reader;\n wxJSONValue oRoot;\n //try to load connections json file\n int numErrorsStorage = reader.Parse(StorageInputStream, &oRoot);\n if (numErrorsStorage == 0)\n {\n //load last remote groupe file backet list\n for (size_t i = 0; i < oRoot.Size(); ++i)\n {\n wxString sName = oRoot[i][\"name\"].AsString();\n enumSyncType eType = (enumSyncType)oRoot[i][\"type\"].AsInt();\n mstCachedDir[sName] = eType;\n } \n }\n }\n \n wxGxObjectList ObjectList = pRemoteDir->GetChildren();\n wxGxObjectList::iterator iter;\n int nCounter = 0;\n IProgressor* pProgressor = NULL;\n if (pTrackCancel)\n {\n pProgressor = pTrackCancel->GetProgressor();\n if (pProgressor)\n pProgressor->SetRange(ObjectList.GetCount());\n }\n\n for (iter = ObjectList.begin(); iter != ObjectList.end(); ++iter)\n {\n if (pProgressor)\n pProgressor->SetValue(nCounter++);\n\n wxGxObject *pRemoteCurrent = *iter;\n //1. find local object\n wxGxObject* pLocalCurrent = pLocalDir->FindGxObject(pLocalDir->GetFullName() + wxFileName::GetPathSeparator() + pRemoteCurrent->GetName());\n if (NULL == pLocalCurrent)\n {\n //create local or delete remote\n bool wasExist = mstCachedDir.find(pRemoteCurrent->GetName()) != mstCachedDir.end();\n if (pRemoteCurrent->IsKindOf(wxCLASSINFO(wxGxNGWResourceGroup)))\n {\n if (!SyncFolderCreateOrDeleteR2L(pLocalDir, wxDynamicCast(pRemoteCurrent, wxGxNGWResourceGroup), wasExist, eDirection, pTrackCancel))\n return false;\n }\n else if (pRemoteCurrent->IsKindOf(wxCLASSINFO(wxGxNGWFileSet)))\n {\n if (!SyncFileCreateOrDelete(pLocalDir, wxDynamicCast(pRemoteCurrent, wxGxNGWFileSet), wasExist, eDirection, pTrackCancel))\n return false; \n }\n }\n else\n {\n m_paInspectedItems.Add((long)pLocalCurrent);\n \n //check if type was changed\n bool wasTypeChanged = !((pRemoteCurrent->IsKindOf(wxCLASSINFO(wxGxNGWResourceGroup)) && pLocalCurrent->IsKindOf(wxCLASSINFO(wxGxFolder))) || (pRemoteCurrent->IsKindOf(wxCLASSINFO(wxGxNGWFileSet)) && NULL != dynamic_cast<IGxDataset*>(pLocalCurrent)));\n\n if (wasTypeChanged)\n {\n //1. remote type changed\n if (mstCachedDir[pRemoteCurrent->GetName()] == enumSyncFolder && pLocalCurrent->IsKindOf(wxCLASSINFO(wxGxFolder)))\n {\n if (!SyncFile(wxDynamicCast(pLocalCurrent, wxGxFolder), wxDynamicCast(pRemoteCurrent, wxGxNGWFileSet), eDirection, pTrackCancel))\n return false; \n }\n //2. local type changed\n if (mstCachedDir[pRemoteCurrent->GetName()] == enumSyncFolder && pRemoteCurrent->IsKindOf(wxCLASSINFO(wxGxNGWResourceGroup)))\n {\n if (!SyncFile(dynamic_cast<IGxDataset*>(pLocalCurrent), wxDynamicCast(pRemoteCurrent, wxGxNGWResourceGroup), eDirection, pTrackCancel))\n return false;\n } \n }\n else\n {\n if (pRemoteCurrent->IsKindOf(wxCLASSINFO(wxGxNGWResourceGroup))) //if remote and local are catalogs - sync them\n {\n if (pLocalCurrent->IsKindOf(wxCLASSINFO(wxGxFolder)))\n {\n if (!SyncSources(wxDynamicCast(pLocalCurrent, wxGxFolder), wxDynamicCast(pRemoteCurrent, wxGxNGWResourceGroup), eDirection, pTrackCancel))\n return false;\n }\n } \n else if (pRemoteCurrent->IsKindOf(wxCLASSINFO(wxGxNGWFileSet))) //if remote and local are files - check timestamp and sync them\n {\n wxGxNGWFileSet* pRemoteFileSet = wxDynamicCast(pRemoteCurrent, wxGxNGWFileSet);\n IGxDataset* pLocalFile = dynamic_cast<IGxDataset*>(pLocalCurrent);\n if (!SyncFile(pLocalFile, pRemoteFileSet, eDirection, pTrackCancel))\n return false;\n }\n //else skip\n } \n }\n }\n\n //now iterate throw the local files and delete or create in remote folder\n ObjectList = pLocalDir->GetChildren();\n if (pProgressor)\n pProgressor->SetRange(ObjectList.GetCount());\n nCounter = 0;\n\n for (iter = ObjectList.begin(); iter != ObjectList.end(); ++iter)\n {\n if (pProgressor)\n pProgressor->SetValue(nCounter++);\n\n wxGxObject *pLocalCurrent = *iter;\n if (pLocalCurrent->GetName().IsSameAs(wxT(TEMP_DIR)))\n continue;\n if (m_paInspectedItems.Index((long)pLocalCurrent) == wxNOT_FOUND)\n {\n bool wasExist = mstCachedDir.find(pLocalCurrent->GetName()) != mstCachedDir.end();\n IGxDataset* pLocalFile = dynamic_cast<IGxDataset*>(pLocalCurrent);\n if (pLocalCurrent->IsKindOf(wxCLASSINFO(wxGxFolder)))\n {\n if (!SyncFolderCreateOrDeleteL2R(wxDynamicCast(pLocalCurrent, wxGxFolder), pRemoteDir, wasExist, eDirection, pTrackCancel))\n return false;\n }\n else if (pLocalFile)\n {\n //create remote or delete local \n if (!SyncFileCreateOrDelete(pLocalFile, pRemoteDir, wasExist, eDirection, pTrackCancel))\n return false;\n }\n }\n }\n\n // create last sync state in json\n StoreSyncState(pLocalDir);\n return true;\n}\n\nvoid GeoSyncTask::StoreSyncState(wxGxFolder* const pFolder)\n{\n if (!pFolder)\n {\n wxGISLogError(_(\"StoreSyncState failed\"), _(\"pFolder is null\"), wxEmptyString, NULL);\n return;\n }\n\n CPLString sTempDirName = CPLFormFilename(pFolder->GetPath(), TEMP_DIR, NULL);\n if (!wxDir::Exists(wxString::FromUTF8(sTempDirName)))\n {\n if(!CreateDir(sTempDirName))\n return;\n }\n\n wxJSONValue JSONResource;\n int nCounter = 0;\n\n pFolder->Refresh();\n wxGxObjectList ObjectList = pFolder->GetChildren();\n wxGxObjectList::iterator iter;\n for (iter = ObjectList.begin(); iter != ObjectList.end(); ++iter)\n {\n wxGxObject *pLocalCurrent = *iter;\n if (pLocalCurrent->GetName().IsSameAs(wxT(TEMP_DIR)))\n continue;\n if (wxGISEQUALN(pLocalCurrent->GetPath(), \"/vsi\", 4))\n continue;\n\n\n if (pLocalCurrent->IsKindOf(wxCLASSINFO(wxGxFolder)))\n {\n JSONResource[nCounter][\"name\"] = pLocalCurrent->GetName();\n JSONResource[nCounter][\"type\"] = (int)enumSyncFolder;\n nCounter++;\n\n StoreSyncState(wxDynamicCast(pLocalCurrent, wxGxFolder));\n }\n else if (NULL != dynamic_cast<IGxDataset*>(pLocalCurrent))\n {\n JSONResource[nCounter][\"name\"] = pLocalCurrent->GetName();\n JSONResource[nCounter][\"type\"] = (int)enumSyncFile;\n nCounter++;\n }\n }\n\n wxJSONWriter writer(wxJSONWRITER_STYLED | wxJSONWRITER_WRITE_COMMENTS);\n wxString sJSONText;\n\n writer.Write(JSONResource, sJSONText);\n wxFile oStorageFile(wxString::FromUTF8(CPLFormFilename(sTempDirName, REMOTE_LIST, NULL)), wxFile::write);\n oStorageFile.Write(sJSONText);\n oStorageFile.Close(); \n}\n\nbool GeoSyncTask::SyncFile(IGxDataset* const pLocalFile, wxGxNGWFileSet* const pRemoteFileSet, geoSyncDirection eDirection, ITrackCancel * const pTrackCancel)\n{\n if (NULL == pLocalFile || NULL == pRemoteFileSet)\n {\n wxGISLogError(_(\"SyncFile failed\"), _(\"pLocalDir and/or pRemoteFileSet is null\"), wxEmptyString, pTrackCancel);\n return false;\n }\n\n //4. check time of each file\n pLocalFile->FillMetadata(true);\n if (eDirection == geoSyncBoth)\n {\n if (pLocalFile->GetModificationDate() > pRemoteFileSet->GetModificationDate())\n return Upload(wxDynamicCast(pRemoteFileSet->GetParent(), wxGxNGWResourceGroup), pLocalFile, pTrackCancel);\n if (pLocalFile->GetModificationDate() < pRemoteFileSet->GetModificationDate())\n {\n wxGxObject* pLocalFileObj = dynamic_cast<wxGxObject*>(pLocalFile);\n if (!pLocalFileObj)\n return false;\n return Download(wxDynamicCast(pLocalFileObj->GetParent(), wxGxFolder), pRemoteFileSet, pTrackCancel);\n }\n }\n else if (eDirection == geoSyncLocal2Remote)\n {\n if (pLocalFile->GetModificationDate() > pRemoteFileSet->GetModificationDate())\n return Upload(wxDynamicCast(pRemoteFileSet->GetParent(), wxGxNGWResourceGroup), pLocalFile, pTrackCancel);\n }\n else if (eDirection == geoSyncRemote2Local)\n {\n if (pLocalFile->GetModificationDate() < pRemoteFileSet->GetModificationDate())\n {\n wxGxObject* pLocalFileObj = dynamic_cast<wxGxObject*>(pLocalFile);\n if (!pLocalFileObj)\n return false;\n return Download(wxDynamicCast(pLocalFileObj->GetParent(), wxGxFolder), pRemoteFileSet, pTrackCancel);\n }\n }\n else\n {\n wxGISLogError(_(\"Wrong sync direction\"), wxEmptyString, wxEmptyString, pTrackCancel);\n return false;\n }\n return true;\n}\n\nbool GeoSyncTask::SyncFolderCreateOrDeleteR2L(wxGxFolder* const pLocalDir, wxGxNGWResourceGroup* const pRemoteDir, bool wasExist, geoSyncDirection eDirection, ITrackCancel * const pTrackCancel)\n{\n // pLocalDir - parent dir\n // pRemoteDir - sync dir\n if (NULL == pLocalDir || NULL == pRemoteDir)\n {\n wxGISLogError(_(\"SyncFolderCreateOrDeleteR2L failed\"), _(\"pLocalDir and/or pRemoteDir is null\"), wxEmptyString, pTrackCancel);\n return false;\n }\n\n //create remote or delete local\n if (eDirection == geoSyncLocal2Remote && wasExist) //if deleted in remote source\n {\n return pRemoteDir->Delete();\n }\n else if (eDirection == geoSyncRemote2Local)\n {\n wxGxFolder *pNewFolder = GetOrCreateFolder(pLocalDir, pRemoteDir->GetName(), pTrackCancel);\n return Download(pNewFolder, pRemoteDir, pTrackCancel);\n }\n else if (eDirection == geoSyncBoth)\n {\n if (wasExist)\n {\n return pRemoteDir->Delete();\n }\n else\n {\n wxGxFolder *pNewFolder = GetOrCreateFolder(pLocalDir, pRemoteDir->GetName(), pTrackCancel);\n return Download(pNewFolder, pRemoteDir, pTrackCancel);\n }\n }\n else\n {\n wxGISLogError(_(\"Wrong sync direction\"), wxEmptyString, wxEmptyString, pTrackCancel);\n }\n return false;\n}\n\nbool GeoSyncTask::SyncFolderCreateOrDeleteL2R(wxGxFolder* const pLocalDir, wxGxNGWResourceGroup* const pRemoteDir, bool wasExist, geoSyncDirection eDirection, ITrackCancel * const pTrackCancel)\n{\n // pRemoteDir - parent dir\n // pLocalDir - sync dir\n\n if (NULL == pLocalDir || NULL == pRemoteDir)\n {\n wxGISLogError(_(\"SyncFolderCreateOrDeleteL2R failed\"), _(\"pLocalDir and/or pRemoteDir is null\"), wxEmptyString, pTrackCancel);\n return false;\n }\n\n //create remote or delete local\n if (eDirection == geoSyncRemote2Local && wasExist) //if deleted in remote source\n {\n return pLocalDir->Delete();\n }\n else if (eDirection == geoSyncLocal2Remote)\n {\n if (!pRemoteDir->CreateResource(pLocalDir->GetName(), enumNGWResourceTypeResourceGroup))\n {\n wxGISLogError(wxString::Format(_(\"CreateResource '%s' failed\"), pLocalDir->GetName().c_str()), wxEmptyString, wxEmptyString, pTrackCancel);\n return false;\n }\n pRemoteDir->Refresh();\n wxGxNGWResourceGroup* pChildDir = wxDynamicCast(pRemoteDir->FindGxObject(pRemoteDir->GetFullName() + wxFileName::GetPathSeparator() + pLocalDir->GetName()), wxGxNGWResourceGroup);\n return SyncSources(pLocalDir, pChildDir, eDirection, pTrackCancel);\n }\n else if (eDirection == geoSyncBoth)\n {\n if (wasExist)\n { \n return pLocalDir->Delete();\n }\n else\n {\n if (!pRemoteDir->CreateResource(pLocalDir->GetName(), enumNGWResourceTypeResourceGroup))\n {\n wxGISLogError(wxString::Format(_(\"CreateResource '%s' failed\"), pLocalDir->GetName().c_str()), wxEmptyString, wxEmptyString, pTrackCancel);\n return false;\n }\n pRemoteDir->Refresh();\n wxGxNGWResourceGroup* pChildDir = wxDynamicCast(pRemoteDir->FindGxObject(pRemoteDir->GetFullName() + wxFileName::GetPathSeparator() + pLocalDir->GetName()), wxGxNGWResourceGroup);\n return SyncSources(pLocalDir, pChildDir, eDirection, pTrackCancel);\n }\n }\n else\n {\n wxGISLogError(_(\"Wrong sync direction\"), wxEmptyString, wxEmptyString, pTrackCancel);\n }\n return false;\n}\n\nbool GeoSyncTask::SyncFileCreateOrDelete(IGxDataset* const pGxDataset, wxGxNGWResourceGroup* const pRemoteDir, bool wasExist, geoSyncDirection eDirection, ITrackCancel * const pTrackCancel)\n{\n if (NULL == pGxDataset || NULL == pRemoteDir)\n {\n wxGISLogError(_(\"SyncFileCreateOrDelete failed\"), _(\"pGxDataset and/or pRemoteDir is null\"), wxEmptyString, pTrackCancel);\n return false;\n }\n\n //create remote or delete local\n if (eDirection == geoSyncRemote2Local && wasExist) //if deleted in remote source\n {\n IGxObjectEdit* pObjectEdit = dynamic_cast<IGxObjectEdit*>(pGxDataset);\n if (!pObjectEdit)\n {\n wxGISLogError(_(\"SyncFileCreateOrDelete failed\"), _(\"cast from IGxDataset to IGxObjectEdit failed\"), wxEmptyString, pTrackCancel);\n return false;\n }\n return pObjectEdit->Delete();\n }\n else if (eDirection == geoSyncLocal2Remote)\n return Upload(pRemoteDir, pGxDataset, pTrackCancel);\n else if (eDirection == geoSyncBoth)\n {\n if (wasExist)\n {\n IGxObjectEdit* pObjectEdit = dynamic_cast<IGxObjectEdit*>(pGxDataset);\n if (!pObjectEdit)\n {\n wxGISLogError(_(\"SyncFileCreateOrDelete failed\"), _(\"cast from IGxDataset to IGxObjectEdit failed\"), wxEmptyString, pTrackCancel);\n return false;\n }\n return pObjectEdit->Delete();\n }\n else\n return Upload(pRemoteDir, pGxDataset, pTrackCancel);\n }\n else\n {\n wxGISLogError(_(\"Wrong sync direction\"), wxEmptyString, wxEmptyString, pTrackCancel);\n }\n return false;\n}\n\nbool GeoSyncTask::SyncFileCreateOrDelete(wxGxFolder* const pLocalDir, wxGxNGWFileSet *pRemoteFileSet, bool wasExist, geoSyncDirection eDirection, ITrackCancel * const pTrackCancel)\n{\n if (NULL == pLocalDir || NULL == pRemoteFileSet)\n {\n wxGISLogError(_(\"SyncFileCreateOrDelete failed\"), _(\"pLocalDir and/or pRemoteFileSet is null\"), wxEmptyString, pTrackCancel);\n return false;\n }\n\n //create local or delete remote\n if (eDirection == geoSyncRemote2Local) //if deleted in remote source\n return Download(pLocalDir, pRemoteFileSet, pTrackCancel);\n else if (eDirection == geoSyncLocal2Remote && wasExist)\n return pRemoteFileSet->Delete();\n else if (eDirection == geoSyncBoth)\n {\n if (wasExist)\n return pRemoteFileSet->Delete();\n else\n return Download(pLocalDir, pRemoteFileSet, pTrackCancel);\n }\n else\n {\n wxGISLogError(_(\"Wrong sync direction\"), wxEmptyString, wxEmptyString, pTrackCancel);\n }\n return false;\n\n}\n\nbool GeoSyncTask::SyncFile(wxGxFolder* const pLocalDir, wxGxNGWFileSet *pRemoteFileSet, geoSyncDirection eDirection, ITrackCancel * const pTrackCancel)\n{\n if (NULL == pLocalDir || NULL == pRemoteFileSet)\n {\n wxGISLogError(_(\"SyncFile failed\"), _(\"pLocalDir and/or pRemoteFileSet is null\"), wxEmptyString, pTrackCancel);\n return false;\n }\n\n //remote type changed\n if (eDirection == geoSyncRemote2Local || eDirection == geoSyncBoth)\n {\n wxGxFolder *pParent = wxDynamicCast(pLocalDir->GetParent(), wxGxFolder);\n //IGxObjectEdit* pGxEdit = dynamic_cast<IGxObjectEdit*>(pLocalDir);\n //if (pGxEdit->Delete())//TODO: download to temp dir, delete and then move to the dest dir (cannot be don now without NGW hidden resource group support)\n return Download(pParent, pRemoteFileSet, pTrackCancel);\n }\n else if (eDirection == geoSyncLocal2Remote)\n {\n wxGxNGWResourceGroup* pParent = wxDynamicCast(pRemoteFileSet->GetParent(), wxGxNGWResourceGroup);\n //if (pRemoteFileSet->Delete())//TODO: download to temp dir, delete and then move to the dest dir (cannot be don now without NGW hidden resource group support)\n return Upload(pParent, pLocalDir, pTrackCancel);\n }\n\n wxGISLogError(_(\"Wrong sync direction\"), wxEmptyString, wxEmptyString, pTrackCancel);\n\n return false;\n}\n\nbool GeoSyncTask::SyncFile(IGxDataset* const pGxDataset, wxGxNGWResourceGroup* const pRemoteDir, geoSyncDirection eDirection, ITrackCancel * const pTrackCancel)\n{\n if (NULL == pGxDataset || NULL == pRemoteDir)\n {\n wxGISLogError(_(\"SyncFile failed\"), _(\"pGxDataset and/or pRemoteDir is null\"), wxEmptyString, pTrackCancel);\n return false;\n }\n\n //local type changed\n if (eDirection == geoSyncRemote2Local)\n {\n wxGxObject* pGxObject = dynamic_cast<wxGxObject*>(pGxDataset);\n if (!pGxObject)\n return false;\n wxGxFolder *pParent = wxDynamicCast(pGxObject->GetParent(), wxGxFolder);\n //if (pGxDataset->Delete())//TODO: download to temp dir, delete and then move to the dest dir (cannot be don now without NGW hidden resource group support)\n return Download(pParent, pRemoteDir, pTrackCancel);\n }\n else if (eDirection == geoSyncLocal2Remote || eDirection == geoSyncBoth)\n {\n wxGxNGWResourceGroup* pParent = wxDynamicCast(pRemoteDir->GetParent(), wxGxNGWResourceGroup);\n //if (pRemoteDir->Delete())//TODO: download to temp dir, delete and then move to the dest dir (cannot be don now without NGW hidden resource group support)\n return Upload(pParent, pGxDataset, pTrackCancel);\n }\n\n wxGISLogError(_(\"Wrong sync direction\"), wxEmptyString, wxEmptyString, pTrackCancel);\n\n return false;\n}\n\nbool GeoSyncTask::Upload(wxGxNGWResourceGroup* const pRemoteDir, IGxDataset* const pGxDataset, ITrackCancel * const pTrackCancel)\n{\n if (NULL == pRemoteDir || NULL == pGxDataset)\n {\n wxGISLogError(_(\"Upload failed\"), _(\"pRemoteDir and/or pGxDataset is null\"), wxEmptyString, pTrackCancel);\n return false;\n }\n\n //add file based datasets\n IGxDataset *pDataset = dynamic_cast<IGxDataset*>(pGxDataset);\n //add archives\n wxGxArchive *pArchive = dynamic_cast<wxGxArchive*>(pGxDataset);\n //add wxGxFile\n wxGxFile *pFile = dynamic_cast<wxGxFile*>(pGxDataset);\n //TODO: wxGxQGISProjFile etc.\n if (pGxDataset && IsFileDataset(pGxDataset->GetType(), pGxDataset->GetSubType()))\n {\n wxGISDataset* pDSet = pGxDataset->GetDataset(false, pTrackCancel);\n if (pDSet)\n {\n int nPreviewXSize = 640;\n int nPreviewYSize = 640;\n wxGISAppConfig oConfig = GetConfig();\n if (oConfig.IsOk() && GetApplication())\n {\n wxString sAppName = GetApplication()->GetAppName();\n nPreviewXSize = oConfig.ReadInt(enumGISHKCU, sAppName + wxT(\"/ngw/preview_x_size\"), nPreviewXSize);\n nPreviewYSize = oConfig.ReadInt(enumGISHKCU, sAppName + wxT(\"/ngw/preview_y_size\"), nPreviewYSize);\n }\n\n //create raster preview\n CPLString osTmpPath = CPLGenerateTempFilename(\"ngw\");\n CPLString osPreviewPath = CPLFormFilename(CPLGetPath(osTmpPath), PREVIEW_FILE_NAME, PREVIEW_FILE_NAME_EXT);\n wxGISMapBitmap bmp(nPreviewXSize, nPreviewYSize);\n bmp.SetTrackCancel(pTrackCancel);\n wxVector<wxGISLayer*> paLayers;\n\n switch (pDSet->GetType())\n {\n case enumGISFeatureDataset:\n paLayers.push_back(bmp.GetLayerFromDataset(pDSet));\n while (pDSet->IsCaching())\n {\n wxSleep(1);\n }\n break;\n case enumGISRasterDataset:\n paLayers.push_back(bmp.GetLayerFromDataset(pDSet));\n break;\n case enumGISContainer:\n //iterate on datasets of the container\n {\n wxGxDatasetContainer* pGxDatasetCont = dynamic_cast<wxGxDatasetContainer*>(pGxDataset);\n if (pGxDatasetCont && pGxDatasetCont->HasChildren(true))\n {\n wxGxObjectList ObjectList = pGxDatasetCont->GetChildren();\n wxGxObjectList::iterator iter;\n for (iter = ObjectList.begin(); iter != ObjectList.end(); ++iter)\n {\n wxGxObject *current = *iter;\n wxGxDataset* pGxDataset = wxDynamicCast(current, wxGxDataset);\n if (pGxDataset)\n {\n wxGISDataset* pwxGISDataset = pGxDataset->GetDataset(true, pTrackCancel);\n if (pwxGISDataset)\n {\n wxGISLayer* pLayer = bmp.GetLayerFromDataset(pwxGISDataset);\n if (pLayer)\n {\n paLayers.push_back(pLayer);\n }\n while (pwxGISDataset->IsCaching())\n {\n wxSleep(1);\n }\n wsDELETE(pwxGISDataset);\n }\n }\n }\n }\n }\n break;\n };\n\n for (size_t k = 0; k < paLayers.size(); ++k)\n {\n if (paLayers[k])\n {\n if (paLayers[k]->IsValid())\n {\n bmp.AddLayer(paLayers[k]);\n }\n else\n {\n wxDELETE(paLayers[k]);\n }\n }\n }\n wxArrayString paths;\n char** papszFileList = pDSet->GetFileList();\n papszFileList = CSLAddString(papszFileList, pDSet->GetPath());\n\n //add it to paths list\n bmp.SetFullExtent();\n if (bmp.SaveAsBitmap(osPreviewPath, enumRasterPng, NULL, false))\n papszFileList = CSLAddString(papszFileList, osPreviewPath);\n\n for (int k = 0; papszFileList[k] != NULL; ++k)\n {\n wxString sPath = wxString::FromUTF8(papszFileList[k]);\n if (sPath.StartsWith(wxT(\"/vsi\")))\n {\n if (pTrackCancel)\n pTrackCancel->PutMessage(wxString::Format(_(\"The archived file '%s' cannot be added to file set\"), sPath.c_str()), wxNOT_FOUND, enumGISMessageWarning);\n }\n else\n {\n paths.Add(sPath);\n }\n }\n CSLDestroy(papszFileList);\n wxJSONValue meta = wxGxNGWResource::MakeMetadata(pDSet);\n wsDELETE(pDSet);\n wxGxObject *pUploadObject = dynamic_cast<wxGxObject*>(pGxDataset);\n if (!pUploadObject)\n return false;\n pGxDataset->FillMetadata();\n return UploadFileBucket(pRemoteDir, pUploadObject->GetName(), paths, pGxDataset->GetModificationDate(), meta, pTrackCancel);\n }\n }\n else if (pArchive)\n {\n wxArrayString paths;\n paths.Add(wxString::FromUTF8(pArchive->GetRealPath()));\n return UploadFileBucket(pRemoteDir, pArchive->GetName(), paths, GetFileModificatioDate(pArchive->GetRealPath()), wxJSONValue(wxJSONTYPE_INVALID), pTrackCancel);\n }\n else if (pFile)\n {\n wxArrayString paths;\n paths.Add(wxString::FromUTF8(pFile->GetPath()));\n return UploadFileBucket(pRemoteDir, pFile->GetName(), paths, GetFileModificatioDate(pFile->GetPath()), wxJSONValue(wxJSONTYPE_INVALID), pTrackCancel);\n }\n\n return true;\n}\n\nbool GeoSyncTask::UploadFileBucket(wxGxNGWResourceGroup* const pRemoteDir, const wxString &sName, const wxArrayString& asPaths, const wxDateTime &dt, const wxJSONValue& oMetadata, ITrackCancel* const pTrackCancel)\n{\n if (NULL == pRemoteDir || asPaths.empty())\n {\n wxGISLogError(_(\"UploadFileBucket failed\"), _(\"pRemoteDir is null and/or asPaths is empty\"), wxEmptyString, pTrackCancel);\n return false;\n }\n\n pRemoteDir->Refresh();\n if (pRemoteDir->IsNameExist(sName))\n {\n IGxObjectEdit* pObjectEdit = NULL;\n wxString sTempName = wxString(TEMP_NAME_PREFIX) + sName;\n if (pRemoteDir->IsNameExist(sTempName))\n {\n pObjectEdit = dynamic_cast<IGxObjectEdit*>(pRemoteDir->FindGxObject(pRemoteDir->GetFullName() + wxFileName::GetPathSeparator() + sTempName));\n if (pObjectEdit && !pObjectEdit->Delete())\n {\n wxGISLogError(wxString::Format(_(\"Delete '%s' failed\"), sTempName.c_str()), wxT(\"Error in UploadFileBucket\"), wxEmptyString, pTrackCancel);\n return false;\n }\n }\n //1. upload as temp file\n if (!pRemoteDir->CreateFileBucket(sTempName, asPaths, dt, oMetadata, pTrackCancel))\n return false;\n pRemoteDir->Refresh();\n //2. delete exist file\n pObjectEdit = dynamic_cast<IGxObjectEdit*>(pRemoteDir->FindGxObject(pRemoteDir->GetFullName() + wxFileName::GetPathSeparator() + sName));\n if (pObjectEdit && !pObjectEdit->Delete())\n {\n wxGISLogError(wxString::Format(_(\"Delete '%s' failed\"), sName.c_str()), wxT(\"Error in UploadFileBucket\"), wxEmptyString, pTrackCancel);\n return false;\n }\n\n //3. rename temp file\n pObjectEdit = dynamic_cast<IGxObjectEdit*>(pRemoteDir->FindGxObject(pRemoteDir->GetFullName() + wxFileName::GetPathSeparator() + sTempName));\n if (!pObjectEdit)\n {\n wxGISLogError(wxString::Format(_(\"cast '%s' to IGxObjectEdit failed\"), sTempName.c_str()), wxT(\"Error in UploadFileBucket\"), wxEmptyString, pTrackCancel);\n return false;\n }\n return pObjectEdit->Rename(sName);\n }\n else\n {\n return pRemoteDir->CreateFileBucket(sName, asPaths, dt, oMetadata, pTrackCancel);\n }\n return true;\n}\n\nbool GeoSyncTask::Download(wxGxFolder* const pLocalDir, wxGxNGWFileSet *pRemoteFileSet, ITrackCancel * const pTrackCancel)\n{\n if (NULL == pLocalDir || NULL == pRemoteFileSet)\n {\n wxGISLogError(_(\"Download failed\"), _(\"pLocalDir and/or pRemoteFileSet is null\"), wxEmptyString, pTrackCancel);\n return false;\n }\n else\n {\n wxLogMessage(\"Download %s\", pRemoteFileSet->GetName().c_str());\n }\n \n if (!pRemoteFileSet->CanSync())\n {\n wxGISLogMessage(wxString::Format(_(\"Skip unsupported file set '%s'\"), pRemoteFileSet->GetName().c_str()), pTrackCancel);\n return true;\n }\n\n wxGxFolder *pCont = GetOrCreateFolder(pLocalDir, wxT(TEMP_DIR), pTrackCancel);\n if (!pCont)\n return false;\n pCont->Refresh();\n\n IGxObjectEdit* pGxObjectEdit = NULL;\n if (pCont->IsNameExist(pRemoteFileSet->GetName()))\n {\n pGxObjectEdit = dynamic_cast<IGxObjectEdit*>(pCont->FindGxObject(pCont->GetFullName() + wxFileName::GetPathSeparator() + pRemoteFileSet->GetName()));\n if (pGxObjectEdit && !pGxObjectEdit->Delete())\n {\n wxGISLogError(wxString::Format(_(\"Delete '%s' failed\"), pRemoteFileSet->GetName().c_str()), wxEmptyString, wxEmptyString, pTrackCancel);\n return false;\n }\n }\n //3. if downloaded delete exist file\n if (!pRemoteFileSet->Copy(pCont->GetPath(), pTrackCancel))\n return false;\n pCont->Refresh();\n pGxObjectEdit = dynamic_cast<IGxObjectEdit*>(pLocalDir->FindGxObject(pLocalDir->GetFullName() + wxFileName::GetPathSeparator() + pRemoteFileSet->GetName()));\n if (pGxObjectEdit && !pGxObjectEdit->Delete())\n {\n wxGISLogError(wxString::Format(_(\"Delete '%s' failed\"), pRemoteFileSet->GetName().c_str()), wxEmptyString, wxEmptyString, pTrackCancel);\n return false;\n }\n\n //4. move form temp dir to destination dir \n pGxObjectEdit = dynamic_cast<IGxObjectEdit*>(pCont->FindGxObject(pCont->GetFullName() + wxFileName::GetPathSeparator() + pRemoteFileSet->GetName()));\n if (!pGxObjectEdit)\n {\n wxGISLogError(wxString::Format(_(\"Cast '%s' to IGxObjectEdit failed\"), pRemoteFileSet->GetName().c_str()), _(\"Error in Download\"), wxEmptyString, pTrackCancel);\n return false;\n }\n return pGxObjectEdit->Move(pLocalDir->GetPath(), pTrackCancel);\n}\n\nbool GeoSyncTask::Upload(wxGxNGWResourceGroup* const pRemoteDir, wxGxFolder* const pLocalDir, ITrackCancel * const pTrackCancel)\n{\n if (NULL == pRemoteDir || NULL == pLocalDir)\n {\n wxGISLogError(_(\"Upload failed\"), _(\"pRemoteDir and/or pLocalDir is null\"), wxEmptyString, pTrackCancel);\n return false;\n }\n\n pRemoteDir->Refresh();\n wxGxObjectList ObjectList = pLocalDir->GetChildren();\n wxGxObjectList::iterator iter;\n for (iter = ObjectList.begin(); iter != ObjectList.end(); ++iter)\n {\n wxGxObject *pLocalCurrent = *iter;\n if (pLocalCurrent->GetName().IsSameAs(wxT(TEMP_DIR)))\n continue;\n\n if (pLocalCurrent->IsKindOf(wxCLASSINFO(wxGxFolder)))\n {\n if (!pRemoteDir->IsNameExist(pLocalCurrent->GetName()))\n {\n if (!pRemoteDir->CreateResource(pLocalCurrent->GetName(), enumNGWResourceTypeResourceGroup))\n {\n wxGISLogError(wxString::Format(_(\"CreateResource '%s' failed\"), pLocalCurrent->GetName().c_str()), _(\"pRemoteDir and/or pLocalDir is null\"), wxEmptyString, pTrackCancel);\n return false;\n }\n pRemoteDir->Refresh();\n }\n\n wxGxNGWResourceGroup* pNewRemoteDir = wxDynamicCast(pRemoteDir->FindGxObject(pRemoteDir->GetFullName() + wxFileName::GetPathSeparator() + pLocalCurrent->GetName()), wxGxNGWResourceGroup); \n if (!Upload(pNewRemoteDir, wxDynamicCast(pLocalCurrent, wxGxFolder), pTrackCancel))\n return false;\n }\n else if (NULL != dynamic_cast<IGxDataset*>(pLocalCurrent))\n {\n if (!Upload(pRemoteDir, dynamic_cast<IGxDataset*>(pLocalCurrent), pTrackCancel))\n return false;\n }\n }\n return true;\n}\n\nbool GeoSyncTask::Download(wxGxFolder* const pLocalDir, wxGxNGWResourceGroup* const pRemoteDir, ITrackCancel * const pTrackCancel)\n{\n if (NULL == pRemoteDir || NULL == pLocalDir)\n {\n wxGISLogError(_(\"Download failed\"), _(\"pRemoteDir and/or pLocalDir is null\"), wxEmptyString, pTrackCancel);\n return false;\n }\n else\n {\n wxLogMessage(\"Download %s\", pRemoteDir->GetName().c_str());\n }\n\n pRemoteDir->Refresh();\n wxGxObjectList ObjectList = pRemoteDir->GetChildren();\n wxGxObjectList::iterator iter;\n for (iter = ObjectList.begin(); iter != ObjectList.end(); ++iter)\n {\n wxGxObject *pRemoteCurrent = *iter;\n if (pRemoteCurrent->IsKindOf(wxCLASSINFO(wxGxNGWResourceGroup)))\n {\n wxGxFolder *pNewFolder = GetOrCreateFolder(pLocalDir, pRemoteCurrent->GetName(), pTrackCancel);\n if (!Download(pNewFolder, wxDynamicCast(pRemoteCurrent, wxGxNGWResourceGroup), pTrackCancel))\n return false;\n }\n else if (pRemoteCurrent->IsKindOf(wxCLASSINFO(wxGxNGWFileSet)))\n {\n if (!Download(pLocalDir, wxDynamicCast(pRemoteCurrent, wxGxNGWFileSet), pTrackCancel))\n return false;\n }\n }\n return true;\n}\n\nwxGxFolder* GeoSyncTask::GetOrCreateFolder(wxGxFolder* const pFolder, const wxString &sSubFolderName, ITrackCancel* const pTrackCancel)\n{\n //1. check temp dir exist\n CPLString sTempDirName = CPLFormFilename(pFolder->GetPath(), sSubFolderName.ToUTF8(), NULL);\n if (!wxDir::Exists(wxString::FromUTF8(sTempDirName)))\n {\n if (!CreateDir(sTempDirName, 0755, pTrackCancel))\n return false;\n else\n pFolder->Refresh();\n }\n\n //2. check created file exist: delete (TODO: resume)\n wxGxFolder* pNewFolder = wxDynamicCast(pFolder->FindGxObject(pFolder->GetFullName() + wxFileName::GetPathSeparator() + sSubFolderName), wxGxFolder);\n m_paInspectedItems.Add((long)pNewFolder);\n return pNewFolder;\n}\n\n//TODO: resume download/upload\n//CURL *curl = curl_easy_init(); if (curl) {\n// curl_easy_setopt(curl, CURLOPT_URL, \"http://example.com\");\n//\n// /* get the first 200 bytes */ curl_easy_setopt(curl, CURLOPT_RANGE, \"0-199\");\n//\n// /* Perform the request */ //curl_easy_perform(curl);\n//}\n" }, { "alpha_fraction": 0.4769507646560669, "alphanum_fraction": 0.4805486798286438, "avg_line_length": 39.95283126831055, "blob_id": "07c8bc8b33fecd1719e775fdeb44c9bca3b6310c", "content_id": "bf74ee85f7eb423fbb5f1cc8534ab1a52ac635c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4447, "license_type": "no_license", "max_line_length": 123, "num_lines": 106, "path": "/qgis-installer/rekod-gis/plugins/shortcut_manager/shortcut_action.py", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n/***************************************************************************\r\n ShortcutManagerDialog\r\n A QGIS plugin\r\n This plugin create shortcuts in toolbar\r\n -------------------\r\n begin : 2014-07-18\r\n git sha : $Format:%H$\r\n copyright : (C) 2014 by NextGIS\r\n email : info@nextgis.ru\r\n ***************************************************************************/\r\n\r\n/***************************************************************************\r\n * *\r\n * This program is free software; you can redistribute it and/or modify *\r\n * it under the terms of the GNU General Public License as published by *\r\n * the Free Software Foundation; either version 2 of the License, or *\r\n * (at your option) any later version. *\r\n * *\r\n ***************************************************************************/\r\n\"\"\"\r\nimport os\r\nimport sys\r\nimport subprocess\r\nimport webbrowser\r\nimport functools\r\n\r\nfrom PyQt4.QtGui import QAction, QMessageBox\r\nfrom PyQt4.QtCore import QObject, SIGNAL\r\n\r\nfrom shortcut_utils import getShortcutIcon, getShortcutType\r\n\r\nfrom qgis.core import QgsMessageLog\r\n\r\nclass ShorcutAction(QAction):\r\n def __init__(self, iface, shortcut):\r\n self._iface = iface\r\n QAction.__init__(self, self._iface.mainWindow())\r\n \r\n self._shortcut = shortcut\r\n \r\n self.setEnabled(True)\r\n \r\n QObject.connect(self._shortcut, SIGNAL(\"updated()\"), self.__shortcutUpdated)\r\n QObject.connect(self._shortcut, SIGNAL(\"deleted()\"), self.__shortcutDeleted)\r\n \r\n self.__shortcutUpdated()\r\n \r\n self._iface.addToolBarIcon(self)\r\n \r\n self.triggered.connect(self._triggeredFunction)\r\n \r\n def __shortcutUpdated(self):\r\n self.setIcon(getShortcutIcon(self._shortcut.icon, self._shortcut.uri))\r\n self.setText(self._shortcut.name)\r\n \r\n shortcutType = getShortcutType(self._shortcut.uri)\r\n\r\n if shortcutType == \"desktop\":\r\n #self._callbackFunction = functools.partial(self._runApplication, self._shortcut.uri, self._shortcut.directory)\r\n self._callbackFunction = functools.partial(self._runApplication, self._shortcut.uri)\r\n elif shortcutType == \"web\":\r\n self._callbackFunction = functools.partial(self._runBrowser, self._shortcut.uri)\r\n else:\r\n self._callbackFunction = lambda: QMessageBox.information(\r\n self._iface.mainWindow(), \r\n 'Unknown shortcut type',\r\n 'Unknown shortcut type',\r\n QMessageBox.Ok)\r\n def _triggeredFunction(self):\r\n self._callbackFunction()\r\n \r\n def __shortcutDeleted(self):\r\n self.setParent(None)\r\n self._iface.removeToolBarIcon(self)\r\n \r\n def _runBrowser(self, url):\r\n try:\r\n webbrowser.open(url)\r\n except webbrowser.Error as err:\r\n QgsMessageLog.logMessage(\r\n \"Shortcuts manager. Error when open shortcut with http url: %s\"%url + \"\\n\" + str(err),\r\n None, QgsMessageLog.CRITICAL)\r\n \r\n def _runApplication(self, app):\r\n try:\r\n app = app.encode(sys.getfilesystemencoding())\r\n if sys.platform.startswith('darwin'):\r\n if os.path.exists(app) == False or os.access(app, os.X_OK):\r\n subprocess.call([app])\r\n else:\r\n subprocess.call(['open', app])\r\n elif os.name == 'nt':\r\n os.startfile(app)\r\n elif os.name == 'posix':\r\n if os.path.exists(app) == False or os.access(app, os.X_OK):\r\n subprocess.Popen([app])\r\n else:\r\n subprocess.Popen(['xdg-open', app])\r\n \r\n except Exception as err:\r\n QgsMessageLog.logMessage(\r\n \"Shortcuts manager. Error when open shortcut for app: %s\"%app + \"\\n\" + str(err),\r\n None, QgsMessageLog.CRITICAL)\r\n raise err\r\n" }, { "alpha_fraction": 0.6376481056213379, "alphanum_fraction": 0.6403828859329224, "avg_line_length": 30.797101974487305, "blob_id": "0b69f2470ae777dbf252f189326cc750011fe12a", "content_id": "609fffe4d0052eea226cbf9c2a5353298b54b3ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2194, "license_type": "no_license", "max_line_length": 79, "num_lines": 69, "path": "/geosync/include/app/tskmngr.h", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "/******************************************************************************\n * Project: geosync\n * Purpose: sync spatial data with NGW\n * Author: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru\n ******************************************************************************\n* Copyright (C) 2014 NextGIS\n*\n* This program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n ****************************************************************************/\n\n#pragma once\n\n#include \"app/tasksdlg.h\"\n\n#include \"wxgis/geoprocessing/tskmngr.h\"\n#include \"wxgis/geoprocessing/task.h\"\n\n#include <wx/taskbar.h>\n\n/** @class GeoSyncTaskManager\n\n Class for spatial data syncronization task managment.\n\n*/\nclass GeoSyncTaskManager :\n\tpublic wxTaskBarIcon\n{\n DECLARE_CLASS(GeoSyncTaskManager)\n enum{\n ID_MANAGE = wxID_HIGHEST + 1,\n ID_START_SYNC,\n ID_TIMER\n };\npublic:\n GeoSyncTaskManager(wxTaskBarIconType iconType = wxTBI_DEFAULT_TYPE);\n virtual ~GeoSyncTaskManager(void);\n\t// wxTaskBarIcon\n\tvirtual wxMenu *CreatePopupMenu();\n\t//events\n\tvoid OnExit(wxCommandEvent& event);\n void OnManage(wxCommandEvent& event);\n void OnStartAllSyncTasks(wxCommandEvent& event);\n void OnLeftUp(wxTaskBarIconEvent& event);\n void OnTimer(wxTimerEvent & event);\nprotected:\n void ShowTasksDialog();\nprotected:\n wxGISTaskManager* m_pTaskManager;\n wxGISTaskCategory* m_pGeoSyncCat;\n long m_TaskCategoryCookie;\n wxImageList m_ImageList;\n wxTimer m_timer;\n int m_nLastIcon;\n int m_nExtraTime;\n GeoSyncTaskDlg *m_pGeoSyncTaskDlg;\nprivate: \n DECLARE_EVENT_TABLE()\n};\n" }, { "alpha_fraction": 0.615078866481781, "alphanum_fraction": 0.6213064789772034, "avg_line_length": 28.365758895874023, "blob_id": "1b6ebcd3e272acf6a657366ba908f20792f75e1f", "content_id": "3206d69a39c1bd494562e082c29420588780362f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 7547, "license_type": "no_license", "max_line_length": 135, "num_lines": 257, "path": "/geosync/cmake/FindWXGIS.cmake", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "# - Try to find the WXGIS libraries\n# Once done this will define\n#\n# WXGIS_ROOT_DIR - Set this variable to the root installation of WXGISGDAL\n#\n# Read-Only variables:\n# WXGIS_FOUND - system has the WXGISGDAL library\n# WXGIS_INCLUDE_DIR - the WXGISGDAL include directory\n# WXGIS_LIBRARIES - The libraries needed to use WXGISGDAL\n# WXGIS_VERSION - This is set to $major.$minor.$revision (eg. 0.5.0)\n\n#=============================================================================\n# Copyright 2012 Dmitry Baryshnikov <polimax at mail dot ru>\n#\n# Distributed under the OSI-approved BSD License (the \"License\");\n# see accompanying file Copyright.txt for details.\n#\n# This software is distributed WITHOUT ANY WARRANTY; without even the\n# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n# See the License for more information.\n#=============================================================================\n# (To distribute this file outside of CMake, substitute the full\n# License text for the above reference.)\nMACRO(DBG_MSG _MSG)\n MESSAGE(STATUS\n \"${CMAKE_CURRENT_LIST_FILE}(${CMAKE_CURRENT_LIST_LINE}): ${_MSG}\")\nENDMACRO(DBG_MSG)\nMACRO(DBG_MSG_V _MSG)\n MESSAGE(STATUS\n \"${CMAKE_CURRENT_LIST_FILE}(${CMAKE_CURRENT_LIST_LINE}): ${_MSG}\")\nENDMACRO(DBG_MSG_V)\n \nif (UNIX)\n find_package(PkgConfig)\n if (PKG_CONFIG_FOUND)\n pkg_check_modules(_WXGIS wxgis)\n endif (PKG_CONFIG_FOUND)\nendif (UNIX)\n\nSET(_WXGIS_ROOT_HINTS\n $ENV{wxGIS_ROOT_DIR}\n $ENV{WXGIS}\n ${WXGIS_ROOT_DIR}\n )\nSET(_WXGIS_ROOT_PATHS\n $ENV{wxGIS_ROOT_DIR}\n $ENV{WXGIS}\n )\nSET(_WXGIS_ROOT_HINTS_AND_PATHS\n HINTS ${_WXGIS_ROOT_HINTS}\n PATHS ${_WXGIS_ROOT_PATHS}\n )\n\nFIND_PATH(WXGIS_INCLUDE_DIR\n NAMES\n wxgis/version.h\n HINTS\n ${_WXGIS_INCLUDEDIR}\n ${_WXGIS_ROOT_HINTS_AND_PATHS}\n PATH_SUFFIXES\n include\n)\n\nif (WXGIS_INCLUDE_DIR) \n file(READ \"${WXGIS_INCLUDE_DIR}/wxgis/version.h\" WXGIS_VERSION_H_CONTENTS)\n string(REGEX MATCH \"wxGIS_MAJOR_VERSION[ \\t]+([0-9]+)\"\n wxGIS_MAJOR_VERSION ${WXGIS_VERSION_H_CONTENTS})\n string (REGEX MATCH \"([0-9]+)\"\n wxGIS_MAJOR_VERSION ${wxGIS_MAJOR_VERSION})\n string(REGEX MATCH \"wxGIS_MINOR_VERSION[ \\t]+([0-9]+)\"\n wxGIS_MINOR_VERSION ${WXGIS_VERSION_H_CONTENTS})\n string (REGEX MATCH \"([0-9]+)\"\n wxGIS_MINOR_VERSION ${wxGIS_MINOR_VERSION})\n string(REGEX MATCH \"wxGIS_RELEASE_NUMBER[ \\t]+([0-9]+)\"\n wxGIS_RELEASE_NUMBER ${WXGIS_VERSION_H_CONTENTS}) \n string (REGEX MATCH \"([0-9]+)\"\n wxGIS_RELEASE_NUMBER ${wxGIS_RELEASE_NUMBER})\n \n # Setup package meta-data\n set(WXGIS_VERSION ${wxGIS_MAJOR_VERSION}.${wxGIS_MINOR_VERSION} CACHE INTERNAL \"The version number for wxgis libraries\")\n\nendif (WXGIS_INCLUDE_DIR)\n\nIF(MSVC)\n set(P_SUFF \"lib\" \"lib/Release\" \"lib/Debug\")\n if(CMAKE_CL_64)\n set(P_SUFF ${P_SUFF} \"lib/x64\")\n else() \n set(P_SUFF ${P_SUFF} \"lib/x86\") \n endif()\nELSE(MSVC)\n set(P_SUFF \"lib\" \"lib/wxgis\") \nENDIF(MSVC) \n\nFIND_PATH(WXGIS_LIB_DIR\n NAMES\n wxgiscore${wxGIS_MAJOR_VERSION}${wxGIS_MINOR_VERSION}d.dll \n wxgiscore${wxGIS_MAJOR_VERSION}${wxGIS_MINOR_VERSION}.dll \n wxgiscore${wxGIS_MAJOR_VERSION}${wxGIS_MINOR_VERSION}d.so \n wxgiscore${wxGIS_MAJOR_VERSION}${wxGIS_MINOR_VERSION}.so \n PATHS \n ${_WXGIS_ROOT_PATHS}\n PATH_SUFFIXES\n ${P_SUFF}\n DOC \"Path to wxGIS libraries?\"\n NO_DEFAULT_PATH\n )\n \nIF(NOT WXGIS_FIND_COMPONENTS)\n SET(WXGIS_FIND_COMPONENTS core)\nENDIF(NOT WXGIS_FIND_COMPONENTS) \nDBG_MSG(\"wxGIS_FIND_COMPONENTS : ${WXGIS_FIND_COMPONENTS}\") \n \nFOREACH(LIB ${WXGIS_FIND_COMPONENTS})\n FIND_LIBRARY(WXGIS_${LIB}\n NAMES\n wxgis${LIB}${wxGIS_MAJOR_VERSION}${wxGIS_MINOR_VERSION}\n PATHS ${WXGIS_LIB_DIR}\n NO_DEFAULT_PATH\n )\n MARK_AS_ADVANCED(WXGIS_${LIB})\n FIND_LIBRARY(WXGIS_${LIB}d\n NAMES\n wxgis${LIB}${wxGIS_MAJOR_VERSION}${wxGIS_MINOR_VERSION}d\n PATHS ${WXGIS_LIB_DIR}\n NO_DEFAULT_PATH\n )\n MARK_AS_ADVANCED(WXGIS_${LIB}d) \n \n if(NOT WXGIS_${LIB} AND WXGIS_${LIB}d)\n\tset(WXGIS_${LIB} WXGIS_${LIB}d)\n endif(NOT WXGIS_${LIB} AND WXGIS_${LIB}d)\nENDFOREACH(LIB) \n\nFOREACH(LIB ${WXGIS_FIND_COMPONENTS})\n DBG_MSG_V(\"Searching for ${LIB} and ${LIB}d\")\n DBG_MSG_V(\"WXGIS_${LIB} : ${WXGIS_${LIB}}\")\n DBG_MSG_V(\"WXGIS_${LIB}d : ${WXGIS_${LIB}d}\")\n IF(WXGIS_${LIB} AND WXGIS_${LIB}d)\n DBG_MSG_V(\"Found ${LIB} and ${LIB}d\")\n LIST(APPEND WXGIS_LIBRARIES\n debug ${WXGIS_${LIB}d} optimized ${WXGIS_${LIB}}\n )\n ELSE(WXGIS_${LIB} AND WXGIS_${LIB}d)\n DBG_MSG_V(\"- not found due to missing WXGIS_${LIB}=${WXGIS_${LIB}} or WXGIS_${LIB}d=${WXGIS_${LIB}d}\")\n SET(WXGIS_FOUND FALSE)\n ENDIF(WXGIS_${LIB} AND WXGIS_${LIB}d)\nENDFOREACH(LIB)\n\n\n# IF(WIN32 AND NOT CYGWIN)\n # # MINGW should go here too\n # IF(MSVC)\n # set(P_SUFF \"lib\" \"lib/Release\" \"lib/Debug\")\n # if(CMAKE_CL_64)\n # set(P_SUFF ${P_SUFF} \"lib/x64\")\n # else() \n # set(P_SUFF ${P_SUFF} \"lib/x86\") \n # endif()\n # # Implementation details:\n # # We are using the libraries located in the VC subdir instead of the parent directory eventhough :\n # FIND_LIBRARY(WXGISCARTO_DEBUG\n # NAMES\n # wxgiscarto04d\n # ${_WXGISGDAL_ROOT_HINTS_AND_PATHS}\n # PATH_SUFFIXES\n # ${P_SUFF}\n # )\n\n # FIND_LIBRARY(WXGISCARTO_RELEASE\n # NAMES\n # wxgiscarto04\n # ${_WXGISGDAL_ROOT_HINTS_AND_PATHS}\n # PATH_SUFFIXES\n # ${P_SUFF}\n # )\n\n # if( CMAKE_CONFIGURATION_TYPES OR CMAKE_BUILD_TYPE )\n # if(NOT WXGIS_DEBUG)\n # set(WXGIS_DEBUG ${WXGIS_RELEASE})\n # endif(NOT WXGIS_DEBUG) \n # set( WXGIS_LIBRARIES\n # optimized ${WXGIS_RELEASE} debug ${WXGIS_DEBUG}\n # )\n # else()\n # set( WXGIS_LIBRARIES ${WXGIS_RELEASE})\n # endif()\n # MARK_AS_ADVANCED(WXGIS_DEBUG WXGIS_RELEASE)\n # ELSEIF(MINGW)\n # # same player, for MingW\n # FIND_LIBRARY(WXGISCARTO\n # NAMES \n # wxgiscarto04\n # ${_WXGISGDAL_ROOT_HINTS_AND_PATHS}\n # PATH_SUFFIXES\n # \"lib\"\n # \"lib/MinGW\"\n # )\n\n # MARK_AS_ADVANCED(WXGISCARTO)\n # set( WXGIS_LIBRARIES ${WXGISCARTO})\n # ELSE(MSVC)\n # # Not sure what to pick for -say- intel, let's use the toplevel ones and hope someone report issues:\n # FIND_LIBRARY(WXGISCARTO\n # NAMES\n # wxgiscarto04\n # HINTS\n # ${_WXGIS_LIBDIR}\n # ${_WXGIS_ROOT_HINTS_AND_PATHS}\n # PATH_SUFFIXES\n # lib\n # ) \n\n # MARK_AS_ADVANCED(WXGISCARTO)\n # set( WXGIS_LIBRARIES ${WXGISCARTO} )\n # ENDIF(MSVC)\n# ELSE(WIN32 AND NOT CYGWIN)\n\n # FIND_LIBRARY(WXGISCARTO\n # NAMES\n # wxgiscarto04\n # HINTS\n # ${_WXGIS_LIBDIR}\n # ${_WXGIS_ROOT_HINTS_AND_PATHS}\n # PATH_SUFFIXES\n # lib\n # ) \n\n # MARK_AS_ADVANCED(WXGIS_LIBRARY)\n\n # # compat defines\n # SET(WXGIS_LIBRARIES ${WXGIS_LIBRARY})\n\n# ENDIF(WIN32 AND NOT CYGWIN)\n\n#SET(WXGIS_LIBRARIES \"qqq\")#hack\n\ninclude(FindPackageHandleStandardArgs)\n\nif (WXGIS_VERSION)\n find_package_handle_standard_args(WXGIS\n REQUIRED_VARS\n WXGIS_LIBRARIES\n WXGIS_INCLUDE_DIR\n VERSION_VAR\n WXGIS_VERSION\n FAIL_MESSAGE\n \"Could NOT find WXGIS, try to set the path to WXGIS root folder in the system variable WXGIS\"\n )\nelse (WXGIS_VERSION)\n find_package_handle_standard_args(WXGIS \"Could NOT find WXGIS, try to set the path to WXGIS root folder in the system variable WXGIS\"\n WXGIS_LIBRARIES\n WXGIS_INCLUDE_DIR\n )\nendif (WXGIS_VERSION)\n\nMARK_AS_ADVANCED(WXGIS_INCLUDE_DIR WXGIS_LIBRARIES)\n" }, { "alpha_fraction": 0.6185404658317566, "alphanum_fraction": 0.6286371350288391, "avg_line_length": 32.29503631591797, "blob_id": "0b93594c30d6f5ebea954dedd9951fb6eef9e6fa", "content_id": "b3f9a2388f9ff9122aabfee4bb710ccc96d0c578", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 23473, "license_type": "no_license", "max_line_length": 198, "num_lines": 705, "path": "/geosync/src/app/tasksdlg.cpp", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "/******************************************************************************\n* Project: geosync\n* Purpose: sync spatial data with NGW\n* Author: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru\n******************************************************************************\n* Copyright (C) 2014 NextGIS\n*\n* This program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n****************************************************************************/\n\n#include \"app/tasksdlg.h\"\n\n#ifdef wxGIS_USE_POSTGRES\n #undef wxGIS_USE_POSTGRES\n#endif\n\n#include \"wxgis/core/config.h\"\n#include \"wxgis/core/app.h\"\n#include \"wxgis/catalogui/gxcatalogui.h\"\n#include \"wxgis/catalog/gxngwconn.h\"\n#include \"wxgis/catalog/gxfolder.h\"\n#include \"wxgis/geoprocessing/tskmngr.h\"\n\n\n#include \"../../art/geosync.xpm\"\n#include \"../art/list_add.xpm\"\n#include \"../art/list_remove.xpm\"\n#include \"../art/state.xpm\"\n#include \"../art/other_16.xpm\"\n\n#include <wx/statline.h>\n\n//-----------------------------------------------------------------------------------\n/// GeoSyncTaskDlg\n//-----------------------------------------------------------------------------------\nBEGIN_EVENT_TABLE(GeoSyncTaskDlg, wxDialog)\n EVT_BUTTON(wxID_ADD, GeoSyncTaskDlg::OnAddTask)\n EVT_UPDATE_UI(wxID_ADD, GeoSyncTaskDlg::OnAddTaskUI)\n EVT_BUTTON(wxID_REMOVE, GeoSyncTaskDlg::OnRemoveTask)\n EVT_UPDATE_UI(wxID_REMOVE, GeoSyncTaskDlg::OnRemoveTaskUI)\n EVT_BUTTON(wxID_EXECUTE, GeoSyncTaskDlg::OnStartTask)\n EVT_UPDATE_UI(wxID_EXECUTE, GeoSyncTaskDlg::OnStartTaskUI)\n EVT_BUTTON(wxID_STOP, GeoSyncTaskDlg::OnStopTask)\n EVT_UPDATE_UI(wxID_STOP, GeoSyncTaskDlg::OnStopTaskUI)\n EVT_GISTASK_ADD(GeoSyncTaskDlg::OnTaskAdded)\n EVT_GISTASK_DEL(GeoSyncTaskDlg::OnTaskDeleted)\n EVT_GISTASK_CHNG(GeoSyncTaskDlg::OnTaskChanged)\nEND_EVENT_TABLE()\n\nGeoSyncTaskDlg::GeoSyncTaskDlg(wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style) : wxDialog(parent, id, title, pos, size, style)\n{\n SetIcon(wxIcon(geosync_xpm));\n\n wxBoxSizer* bSizerMain = new wxBoxSizer(wxHORIZONTAL);\n\n m_pTaskList = new wxListCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, LISTSTYLE);\n\n bSizerMain->Add(m_pTaskList, 1, wxEXPAND | wxALL, 5);\n\n wxBoxSizer* pBoxSizerButtons = new wxBoxSizer(wxVERTICAL);\n\n m_ImageList.Create(16, 16);\n m_ImageList.Add(wxBitmap(state_xpm));\n\n m_pTaskList->SetImageList(&m_ImageList, wxIMAGE_LIST_SMALL);\n\n wxBitmapButton* bpSizerAdd = new wxBitmapButton(this, wxID_ADD, wxBitmap(list_add_xpm), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW);\n pBoxSizerButtons->Add(bpSizerAdd, 0, wxALL, 5);\n\n wxBitmapButton*bpSizerDel = new wxBitmapButton(this, wxID_REMOVE, wxBitmap(list_remove_xpm), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW);\n pBoxSizerButtons->Add(bpSizerDel, 0, wxALL, 5);\n bpSizerDel->Enable(false);\n\n wxBitmapButton* bpSizerStart = new wxBitmapButton(this, wxID_EXECUTE, m_ImageList.GetBitmap(4), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW);\n pBoxSizerButtons->Add(bpSizerStart, 0, wxALL, 5);\n bpSizerStart->Enable(false);\n\n wxBitmapButton* bpSizerStop = new wxBitmapButton(this, wxID_STOP, m_ImageList.GetBitmap(7), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW);\n pBoxSizerButtons->Add(bpSizerStop, 0, wxALL, 5);\n bpSizerStop->Enable(false);\n\n bSizerMain->Add(pBoxSizerButtons, 0, wxALL, 0);\n\n this->SetSizerAndFit(bSizerMain);\n\tthis->Layout();\n\n SerializeFramePos(false);\n\n if (!GetGxCatalog())\n {\n SetGxCatalog(new wxGxCatalogUI());\n GetGxCatalog()->Init();\n }\n\n m_pGeoSyncCat = NULL;\n m_nCatCookie = wxNOT_FOUND;\n FillList();\n}\n\nGeoSyncTaskDlg::~GeoSyncTaskDlg()\n{\n RemoveAll();\n\n if (m_nCatCookie != wxNOT_FOUND && m_pGeoSyncCat)\n m_pGeoSyncCat->Unadvise(m_nCatCookie);\n\n SerializeFramePos(true);\n\n SetGxCatalog(NULL);\n}\n\nvoid GeoSyncTaskDlg::SerializeFramePos(bool bSave)\n{\n\twxGISAppConfig oConfig = GetConfig();\n\tif(!oConfig.IsOk())\n\t\treturn;\n\n wxString sAppName(wxT(\"geosync\"));\n IApplication* pApp = GetApplication();\n if (pApp)\n sAppName = pApp->GetAppName();\n\n\tif(bSave)\n\t{\n\t\tif( IsMaximized() )\n oConfig.Write(enumGISHKCU, sAppName + wxString(wxT(\"/customizedlg/maxi\")), true);\n\t\telse\n\t\t{\n\t\t\tint x, y, w, h;\n\t\t\tGetClientSize(&w, &h);\n\t\t\tGetPosition(&x, &y);\n oConfig.Write(enumGISHKCU, sAppName + wxString(wxT(\"/customizedlg/maxi\")), false);\n oConfig.Write(enumGISHKCU, sAppName + wxString(wxT(\"/customizedlg/width\")), w);\n oConfig.Write(enumGISHKCU, sAppName + wxString(wxT(\"/customizedlg/height\")), h);\n oConfig.Write(enumGISHKCU, sAppName + wxString(wxT(\"/customizedlg/xpos\")), x);\n oConfig.Write(enumGISHKCU, sAppName + wxString(wxT(\"/customizedlg/ypos\")), y);\n\t\t}\n\t}\n\telse\n\t{\n\t\t//load\n bool bMaxi = oConfig.ReadBool(enumGISHKCU, sAppName + wxString(wxT(\"/customizedlg/maxi\")), false);\n\t\tif(!bMaxi)\n\t\t{\n int x = oConfig.ReadInt(enumGISHKCU, sAppName + wxString(wxT(\"/customizedlg/xpos\")), 50);\n int y = oConfig.ReadInt(enumGISHKCU, sAppName + wxString(wxT(\"/customizedlg/ypos\")), 50);\n int w = oConfig.ReadInt(enumGISHKCU, sAppName + wxString(wxT(\"/customizedlg/width\")), 850);\n int h = oConfig.ReadInt(enumGISHKCU, sAppName + wxString(wxT(\"/customizedlg/height\")), 530);\n\t\t\tMove(x, y);\n\t\t\tSetClientSize(w, h);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tMaximize();\n\t\t}\n\t}\n}\n\nvoid GeoSyncTaskDlg::OnAddTask(wxCommandEvent& event)\n{\n CreateGeoSyncTaskDlg dlg(this);\n if (dlg.ShowModal() == wxID_OK)\n {\n //RefreshAll();\n }\n}\n\nvoid GeoSyncTaskDlg::RefreshAll()\n{\n RemoveAll();\n FillList();\n}\n\nvoid GeoSyncTaskDlg::RemoveAll()\n{\n for (size_t i = 0; i < m_staTasksCookie.size(); ++i)\n {\n if (m_staTasksCookie[i].pTask)\n m_staTasksCookie[i].pTask->Unadvise(m_staTasksCookie[i].nCookie);\n }\n m_staTasksCookie.clear();\n}\n\nvoid GeoSyncTaskDlg::OnRemoveTask(wxCommandEvent& event)\n{\n for (size_t i = 0; i < m_pTaskList->GetItemCount(); ++i)\n {\n int nMask = m_pTaskList->GetItemState(i, wxLIST_STATE_SELECTED);\n if (nMask == wxLIST_STATE_SELECTED)\n {\n int nTaskId = m_pTaskList->GetItemData(i);\n wxGISTaskBase* pTask = m_pGeoSyncCat->GetSubTask(nTaskId);\n if (pTask)\n pTask->Delete();\n }\n }\n}\n\nvoid GeoSyncTaskDlg::OnRemoveTaskUI(wxUpdateUIEvent& event)\n{\n for (size_t i = 0; i < m_pTaskList->GetItemCount(); ++i)\n {\n int nMask = m_pTaskList->GetItemState(i, wxLIST_STATE_SELECTED);\n if (nMask == wxLIST_STATE_SELECTED)\n {\n event.Enable(true);\n return;\n }\n }\n event.Enable(false);\n}\n\nvoid GeoSyncTaskDlg::OnAddTaskUI(wxUpdateUIEvent& event)\n{\n if (NULL == m_pGeoSyncCat)\n event.Enable(false);\n else\n event.Enable(true);\n}\n\nvoid GeoSyncTaskDlg::OnStartTask(wxCommandEvent& event)\n{\n for (size_t i = 0; i < m_pTaskList->GetItemCount(); ++i)\n {\n int nMask = m_pTaskList->GetItemState(i, wxLIST_STATE_SELECTED);\n if (nMask == wxLIST_STATE_SELECTED)\n {\n int nTaskId = m_pTaskList->GetItemData(i);\n wxGISTask* pTask = wxDynamicCast(m_pGeoSyncCat->GetSubTask(nTaskId), wxGISTask);\n if (pTask)\n pTask->StartTask();\n }\n }\n}\n\nvoid GeoSyncTaskDlg::OnStartTaskUI(wxUpdateUIEvent& event)\n{\n for (size_t i = 0; i < m_pTaskList->GetItemCount(); ++i)\n {\n int nMask = m_pTaskList->GetItemState(i, wxLIST_STATE_SELECTED);\n if (nMask == wxLIST_STATE_SELECTED)\n {\n int nTaskId = m_pTaskList->GetItemData(i);\n wxGISTask* pTask = wxDynamicCast(m_pGeoSyncCat->GetSubTask(nTaskId), wxGISTask);\n if (pTask && (pTask->GetState() == enumGISTaskWork || pTask->GetState() == enumGISTaskQuered))\n continue;\n event.Enable(true);\n return;\n }\n }\n event.Enable(false);\n}\n\nvoid GeoSyncTaskDlg::OnStopTask(wxCommandEvent& event)\n{\n for (size_t i = 0; i < m_pTaskList->GetItemCount(); ++i)\n {\n int nMask = m_pTaskList->GetItemState(i, wxLIST_STATE_SELECTED);\n if (nMask == wxLIST_STATE_SELECTED)\n {\n int nTaskId = m_pTaskList->GetItemData(i);\n wxGISTask* pTask = wxDynamicCast(m_pGeoSyncCat->GetSubTask(nTaskId), wxGISTask);\n if (pTask)\n pTask->StopTask();\n }\n }\n}\n\nvoid GeoSyncTaskDlg::OnStopTaskUI(wxUpdateUIEvent& event)\n{\n for (size_t i = 0; i < m_pTaskList->GetItemCount(); ++i)\n {\n int nMask = m_pTaskList->GetItemState(i, wxLIST_STATE_SELECTED);\n if (nMask == wxLIST_STATE_SELECTED)\n {\n int nTaskId = m_pTaskList->GetItemData(i);\n wxGISTask* pTask = wxDynamicCast(m_pGeoSyncCat->GetSubTask(nTaskId), wxGISTask);\n if (pTask && !(pTask->GetState() == enumGISTaskWork || pTask->GetState() == enumGISTaskQuered))\n continue;\n event.Enable(true);\n return;\n }\n }\n event.Enable(false);\n}\n\nvoid GeoSyncTaskDlg::FillList()\n{\n if (NULL == m_pGeoSyncCat)\n {\n wxGISTaskManager* pTaskManager = GetTaskManager();\n if (!pTaskManager)\n {\n wxMessageBox(_(\"Get task manager failed\"), _(\"Error\"), wxOK | wxICON_ERROR);\n return;\n }\n\n m_pGeoSyncCat = pTaskManager->GetCategory(GEOSYNCCAT);\n if (!m_pGeoSyncCat)\n {\n wxMessageBox(_(\"Get task category failed\"), _(\"Error\"), wxOK | wxICON_ERROR);\n return;\n }\n m_nCatCookie = m_pGeoSyncCat->Advise(this);\n }\n\n if (m_pTaskList->GetColumnCount() == 0)\n {\n m_pTaskList->InsertColumn(0, _(\"Local folder\"), wxLIST_FORMAT_LEFT, 150);\n m_pTaskList->InsertColumn(1, _(\"Remote folder\"), wxLIST_FORMAT_LEFT, 150);\n m_pTaskList->InsertColumn(2, _(\"Direction\"), wxLIST_FORMAT_LEFT, 50);\n m_pTaskList->InsertColumn(3, _(\"Start\"), wxLIST_FORMAT_LEFT, 100);\n m_pTaskList->InsertColumn(4, _(\"Finish\"), wxLIST_FORMAT_LEFT, 100);\n m_pTaskList->InsertColumn(5, _(\"Done %\"), wxLIST_FORMAT_CENTER, 50);\n#ifdef ERR_REPORTING\n m_pTaskList->InsertColumn(6, _(\"Error message\"), wxLIST_FORMAT_LEFT, 350);\n#endif //ERR_REPORTING\n }\n \n for (size_t i = 0; i < m_pGeoSyncCat->GetSubTaskCount(); ++i)\n {\n AddTask(wxDynamicCast(m_pGeoSyncCat->GetSubTask(i), wxGISTask));\n }\n}\n\nvoid GeoSyncTaskDlg::OnTaskAdded(wxGISTaskEvent& event)\n{\n AddTask(wxDynamicCast(m_pGeoSyncCat->GetSubTask(event.GetId()), wxGISTask));\n}\n\nvoid GeoSyncTaskDlg::OnTaskDeleted(wxGISTaskEvent& event)\n{\n for (size_t i = 0; i < m_staTasksCookie.size(); ++i)\n {\n if (m_staTasksCookie[i].nId == event.GetId())\n {\n m_staTasksCookie[i].pTask = NULL;\n break;\n }\n }\n\n for (long i = 0; i < m_pTaskList->GetItemCount(); ++i)\n {\n if (m_pTaskList->GetItemData(i) == event.GetId())\n {\n m_pTaskList->DeleteItem(i);\n break;\n }\n }\n}\n\nvoid GeoSyncTaskDlg::OnTaskChanged(wxGISTaskEvent& event)\n{\n for (long i = 0; i < m_pTaskList->GetItemCount(); ++i)\n {\n if (m_pTaskList->GetItemData(i) == event.GetId())\n {\n wxGISTask *pTask = wxDynamicCast(m_pGeoSyncCat->GetSubTask(event.GetId()), wxGISTask);\n char nIcon = wxNOT_FOUND;\n wxColour color;\n switch (pTask->GetState())\n {\n case enumGISTaskError:\n color = wxColour(255, 230, 230);\n nIcon = 2;\n break;\n case enumGISTaskWork:\n color = wxColour(230, 255, 230);\n nIcon = 4;\n break;\n case enumGISTaskQuered:\n color = wxColour(255, 230, 255);\n nIcon = 5;\n break;\n case enumGISTaskDone:\n color = wxColour(230, 230, 255);\n nIcon = 6;\n break;\n case enumGISTaskPaused:\n color = wxColour(255, 255, 230);\n nIcon = 7;\n break;\n };\n m_pTaskList->SetItemBackgroundColour(i, color);\n m_pTaskList->SetItemImage(i, nIcon);\n return SetItems(i, pTask);\n }\n }\n}\n\nvoid GeoSyncTaskDlg::AddTask(wxGISTask* pTask)\n{\n wxCHECK_RET(pTask, wxT(\"Input task pointer is null\"));\n\n for (size_t i = 0; i < m_pTaskList->GetItemCount(); ++i)\n {\n if (m_pTaskList->GetItemData(i) == pTask->GetId())\n {\n return;\n }\n }\n\n // enumGISTaskWork = 1, enumGISTaskDone = 2, enumGISTaskQuered = 3, enumGISTaskPaused = 4, enumGISTaskError = 5\n //0 - info, 1 - complete, 2 - error, 3 - warning, 4 - work, 5 - queued, 6 - done, 7 - paused, 8 - deleted\n char nIcon = wxNOT_FOUND;\n wxColour color;\n switch (pTask->GetState())\n {\n case enumGISTaskError:\n color = wxColour(255, 230, 230);\n nIcon = 2;\n break;\n case enumGISTaskWork:\n color = wxColour(230, 255, 230);\n nIcon = 4;\n break;\n case enumGISTaskQuered:\n color = wxColour(255, 230, 255);\n nIcon = 5;\n break;\n case enumGISTaskDone:\n color = wxColour(230, 230, 255);\n nIcon = 6;\n break;\n case enumGISTaskPaused:\n color = wxColour(255, 255, 230);\n nIcon = 7;\n break;\n };\n\n wxJSONValue oProp = pTask->GetParameters();\n wxString sLocalFolder = oProp[wxT(\"sync_detailes\")][\"local_name\"].AsString();\n wxString sRemoteFolder = oProp[wxT(\"sync_detailes\")][\"remote_name\"].AsString();\n wxString sDirection = oProp[\"direction\"].AsString();\n\n long ListItemID = m_pTaskList->InsertItem(0, sLocalFolder, nIcon);\n SetItems(ListItemID, pTask);\n m_pTaskList->SetItem(ListItemID, 1, sRemoteFolder);\n m_pTaskList->SetItem(ListItemID, 2, sDirection);\n\n m_pTaskList->SetItemBackgroundColour(ListItemID, color);\n m_pTaskList->SetItemData(ListItemID, (long)pTask->GetId());\n\n m_staTasksCookie.push_back({ pTask->Advise(this), pTask->GetId(), pTask });\n}\n\n\nvoid GeoSyncTaskDlg::SetItems(long nItem, wxGISTask* pTask)\n{\n if (!pTask)\n return;\n\n wxDateTime dts = pTask->GetDateBegin();\n wxString sStart = dts.Format();\n m_pTaskList->SetItem(nItem, 3, sStart);\n\n wxDateTime dtf = pTask->GetDateEnd();\n wxString sFinish = dtf.Format();\n m_pTaskList->SetItem(nItem, 4, sFinish);\n\n double dfDone = pTask->GetDone();\n wxString sDone = wxString::Format(_(\"%.0f%%\"), dfDone);\n m_pTaskList->SetItem(nItem, 5, sDone);\n \n#ifdef ERR_REPORTING\n wxString sLastErr = pTask->GetLastError();\n m_pTaskList->SetItem(nItem, 6, sLastErr); \n#endif //ERR_REPORTING\n}\n//---------------------------------------------------------------------------\n// CreateGeoSyncTaskDlg\n//---------------------------------------------------------------------------\n\nBEGIN_EVENT_TABLE(CreateGeoSyncTaskDlg, wxDialog)\n EVT_UPDATE_UI(wxID_OK, CreateGeoSyncTaskDlg::OnOKUI)\n EVT_BUTTON(wxID_OK, CreateGeoSyncTaskDlg::OnOk)\nEND_EVENT_TABLE()\n\nCreateGeoSyncTaskDlg::CreateGeoSyncTaskDlg(wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style) : wxDialog(parent, id, title, pos, size, style)\n{\n SetIcon(wxIcon(other_16_xpm));\n\n wxBoxSizer* bSizer;\n bSizer = new wxBoxSizer(wxVERTICAL);\n\n //create and fill parameters array\n wxGISGPParameter *pParamSrcFolder = new wxGISGPParameter(wxT(\"src_folder\"), _(\"Set local folder to sync\"), enumGISGPParameterTypeRequired, enumGISGPParamDTFolderPath);\n pParamSrcFolder->SetDirection(enumGISGPParameterDirectionInput);\n\n wxGISGPGxObjectDomain* pDomain1 = new wxGISGPGxObjectDomain();\n pDomain1->AddFilter(new wxGxFolderFilter());\n pParamSrcFolder->SetDomain(pDomain1);\n\n m_Parameters.Add(pParamSrcFolder);\n\n wxGISGPParameter *pParamDstFolder = new wxGISGPParameter(wxT(\"dst_folder\"), _(\"Set remote folder to sync\"), enumGISGPParameterTypeRequired, enumGISGPParamDTFolderPath);\n pParamDstFolder->SetDirection(enumGISGPParameterDirectionInput);\n\n wxGISGPGxObjectDomain* pDomain2 = new wxGISGPGxObjectDomain();\n pDomain2->AddFilter(new wxGxNGWResourceGroupFilter());\n\n pParamDstFolder->SetDomain(pDomain2);\n\n m_Parameters.Add(pParamDstFolder);\n\n wxGISGPParameter *pParamDirection = new wxGISGPParameter(wxT(\"direction\"), _(\"Set sync direction\"), enumGISGPParameterTypeRequired, enumGISGPParamDTStringChoice);\n pParamDirection->SetDirection(enumGISGPParameterDirectionInput);\n\n wxGISGPValueDomain* poGPValueDomain = new wxGISGPValueDomain();\n poGPValueDomain->AddValue(wxT(\"local2remote\"), wxT(\"Local -> Remote\"));\n poGPValueDomain->AddValue(wxT(\"remote2local\"), wxT(\"Remote -> Local\"));\n poGPValueDomain->AddValue(wxT(\"both\"), wxT(\"Local <-> Remote\"));\n pParamDirection->SetDomain(poGPValueDomain);\n pParamDirection->SetValue(wxT(\"both\"));\n\n m_Parameters.Add(pParamDirection);\n\n //create gpcontrols\n wxGISDTFolderPath* pLocalPath = new wxGISDTFolderPath(m_Parameters, 0, this);\n bSizer->Add(pLocalPath, 0, wxEXPAND, 5);\n m_paControls.push_back(pLocalPath);\n\n wxGISDTFolderPath* pRemotePath = new wxGISDTFolderPath(m_Parameters, 1, this);\n bSizer->Add(pRemotePath, 0, wxEXPAND, 5);\n m_paControls.push_back(pRemotePath);\n\n wxGISDTChoice* pDirection = new wxGISDTChoice(m_Parameters, 2, this);\n bSizer->Add(pDirection, 0, wxEXPAND, 5);\n m_paControls.push_back(pDirection);\n\n //\n wxStaticLine *pStatLine = new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL);\n bSizer->Add(pStatLine, 0, wxEXPAND | wxALL, 5);\n\n wxStdDialogButtonSizer* psdbSizer = new wxStdDialogButtonSizer();\n wxButton *sdbSizerOK = new wxButton(this, wxID_OK);\n psdbSizer->AddButton(sdbSizerOK);\n sdbSizerOK->Disable();\n wxButton *sdbSizerCancel = new wxButton(this, wxID_CANCEL, _(\"Cancel\"));\n psdbSizer->AddButton(sdbSizerCancel);\n psdbSizer->Realize();\n bSizer->Add(psdbSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxEXPAND | wxALL, 5);\n\n this->SetSizerAndFit(bSizer);\n this->Layout();\n\n this->Centre(wxBOTH);\n}\n\nCreateGeoSyncTaskDlg::~CreateGeoSyncTaskDlg()\n{\n for (size_t i = 0; i < m_paControls.size(); ++i)\n {\n if (m_paControls[i])\n m_paControls[i]->OnDelete();\n }\n \n for (size_t i = 0; i < m_Parameters.size(); ++i)\n {\n wxDELETE(m_Parameters[i]);\n }\n}\n\nvoid CreateGeoSyncTaskDlg::OnOKUI(wxUpdateUIEvent & event)\n{\n event.Enable(IsValid());\n}\n\nbool CreateGeoSyncTaskDlg::IsValid(void)\n{\n wxGxNGWResourceGroup* pRemoteFolder = wxDynamicCast(GetGxCatalog()->FindGxObject(m_Parameters[1]->GetValue().GetString()), wxGxNGWResourceGroup);\n if (!pRemoteFolder)\n return false;\n //check if file bucket is supported\n if (!pRemoteFolder->GetNGWService()->IsTypeSupported(enumNGWResourceTypeFileSet))\n {\n m_Parameters[1]->SetValid(false);\n m_Parameters[1]->SetMessage(enumGISMessageError, _(\"The selected NGW instance doesn't support file sets\"));\n return false;\n }\n for (size_t i = 0; i < m_Parameters.GetCount(); ++i)\n if (!m_Parameters[i]->IsValid())\n return false;\n return true;\n}\n\nvoid CreateGeoSyncTaskDlg::OnOk(wxCommandEvent & event)\n{\n wxString sLocalFolderFullName = m_Parameters[0]->GetValue().GetString();\n wxString sRemoteFolderFullName = m_Parameters[1]->GetValue().GetString();\n wxString sDirection = m_Parameters[2]->GetValue().GetString();\n wxGISAppConfig oConfig = GetConfig();\n\n wxString sAppName(wxT(\"geosync\"));\n IApplication* pApp = GetApplication();\n if (pApp)\n sAppName = pApp->GetAppName();\n\n\n wxGxCatalogBase* pCat = GetGxCatalog();\n if (!pCat)\n {\n wxMessageBox(_(\"Get catalog failed\"), _(\"Error\"), wxOK | wxICON_ERROR);\n return;\n }\n\n wxGxFolder* pGxFolder = wxDynamicCast(pCat->FindGxObject(sLocalFolderFullName), wxGxFolder);\n if (!pGxFolder) \n {\n wxMessageBox(_(\"Get local folder failed\"), _(\"Error\"), wxOK | wxICON_ERROR);\n return;\n }\n\n CPLString szPath = pGxFolder->GetPath();\n\n wxGxNGWResourceGroup* pRemoteFolder = wxDynamicCast(pCat->FindGxObject(sRemoteFolderFullName), wxGxNGWResourceGroup);\n if (!pRemoteFolder)\n {\n wxMessageBox(_(\"Get remote folder failed\"), _(\"Error\"), wxOK | wxICON_ERROR);\n return;\n }\n\n wxGxNGWService *pService = pRemoteFolder->GetNGWService();\n wxString sURL = pService->GetURL();\n wxString sUser = pService->GetLogin();\n wxString sPasswd = pService->GetPassword();\n long nResurceId = pRemoteFolder->GetRemoteId();\n\n //create task and exit\n wxGISTaskManager* pTaskManager = GetTaskManager();\n if (!pTaskManager)\n {\n wxMessageBox(_(\"Get task manager failed\"), _(\"Error\"), wxOK | wxICON_ERROR);\n return;\n }\n\n wxGISTaskCategory *pGeoSyncCat = pTaskManager->GetCategory(GEOSYNCCAT);\n if (!pGeoSyncCat)\n {\n wxMessageBox(_(\"Get task category failed\"), _(\"Error\"), wxOK | wxICON_ERROR);\n return;\n }\n\n //check task name\n wxGISTaskEdit EditTask;\n EditTask.SetName(wxString::Format(wxT(\"sync_task_%s\"), wxDateTime::Now().Format(wxT(\"%Y%m%d%H%M%S\"))));\n //EditTask.SetDescription(sDesc);\n EditTask.SetState(enumGISTaskQuered);\n\n wxJSONValue paramsval;\n paramsval[wxT(\"local\")] = wxString::FromUTF8(szPath);\n paramsval[wxT(\"url\")] = sURL;\n paramsval[wxT(\"user\")] = sUser;\n paramsval[wxT(\"passwd\")] = sPasswd;\n paramsval[wxT(\"id\")] = nResurceId;\n paramsval[wxT(\"direction\")] = sDirection;\n paramsval[wxT(\"sync_detailes\")][wxT(\"local_name\")] = sLocalFolderFullName;\n paramsval[wxT(\"sync_detailes\")][wxT(\"remote_name\")] = sRemoteFolderFullName;\n\n EditTask.SetParameters(paramsval);\n long nPeriod = 900;\n if (oConfig.IsOk())\n nPeriod = oConfig.ReadInt(enumGISHKCU, sAppName + wxString(wxT(\"/tasks/default_period\")), nPeriod);\n\n EditTask.SetPeriod(nPeriod); //15 min in secs\n EditTask.SetGroupId(777);\n\n //get path to task executor\n#ifdef __WINDOWS__\n wxString sExecPath(wxT(\"synctask.exe\"));\n#else\n wxString sExecPath(wxT(\"synctask\"));\n#endif\n\n if (oConfig.IsOk())\n sExecPath = oConfig.Read(enumGISHKCU, sAppName + wxString(wxT(\"/tasks/exe_path\")), sExecPath);\n\n EditTask.SetExecutable(sExecPath);\n\n wxBusyCursor wait;\n if (!pGeoSyncCat->CreateTask(&EditTask))\n {\n wxMessageBox(wxString::Format(_(\"Create task failed.\\n%s\"), pGeoSyncCat->GetLastError().c_str()), _(\"Error\"), wxICON_ERROR);\n return;\n }\n\n if (IsModal())\n EndModal(wxID_OK);\n else\n {\n SetReturnCode(wxID_OK);\n this->Show(false);\n }\n}\n" }, { "alpha_fraction": 0.5910230875015259, "alphanum_fraction": 0.5932798385620117, "avg_line_length": 23.74193572998047, "blob_id": "e40495ac8c668075983b8dfc6bc85bcab3dadf31", "content_id": "b18a3b89c4f79d8d9a44abe4a87072b1ee772d6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3988, "license_type": "no_license", "max_line_length": 97, "num_lines": 155, "path": "/geosync/src/app/app.cpp", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "/******************************************************************************\r\n * Project: geosync\r\n * Purpose: sync spatial data with NGW\r\n * Author: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru\r\n ******************************************************************************\r\n* Copyright (C) 2014 NextGIS\r\n*\r\n* This program is free software: you can redistribute it and/or modify\r\n* it under the terms of the GNU General Public License as published by\r\n* the Free Software Foundation, either version 3 of the License, or\r\n* (at your option) any later version.\r\n*\r\n* This program is distributed in the hope that it will be useful,\r\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n* GNU General Public License for more details.\r\n*\r\n* You should have received a copy of the GNU General Public License\r\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\r\n ****************************************************************************/\r\n\r\n#include \"app/app.h\"\r\n#include \"wxgis/core/config.h\"\r\n\r\n#include <wx/socket.h>\r\n\r\n//-----------------------------------------------------------------------------\r\n// GeoSyncApp\r\n//-----------------------------------------------------------------------------\r\n\r\nIMPLEMENT_APP(GeoSyncApp)\r\n\r\nGeoSyncApp::GeoSyncApp(void) : wxApp()\r\n{\r\n m_vendorName = wxString(VENDOR);\r\n m_vendorDisplayName = wxString(wxT(\"GeoSync\"));\r\n m_appName = wxString(wxT(\"geosync\"));\r\n m_appDisplayName = wxString(wxT(\"Spatial data syncronizator\"));\r\n m_className = wxString(wxT(\"GeoSyncApp\"));\r\n\r\n m_pTaskManager = NULL;\r\n}\r\n\r\nGeoSyncApp::~GeoSyncApp(void)\r\n{ \r\n wxDELETE(m_pTaskManager);\r\n#ifdef _WIN32\r\n wxSocketBase::Shutdown();\r\n#endif\r\n\r\n#ifdef wxUSE_SNGLINST_CHECKER\r\n wxDELETE(m_pChecker);\r\n#endif \r\n}\r\n\r\nbool GeoSyncApp::OnInit()\r\n{\r\n#ifdef _WIN32\r\n wxSocketBase::Initialize();\r\n#endif\r\n\r\n#ifdef wxUSE_SNGLINST_CHECKER\r\n m_pChecker = new wxSingleInstanceChecker();\r\n if ( m_pChecker->IsAnotherRunning() )\r\n {\r\n wxLogError(_(\"Another program instance is already running, aborting.\"));\r\n\r\n wxDELETE( m_pChecker ); // OnExit() won't be called if we return false\r\n\r\n return false;\r\n }\r\n#endif\r\n\r\n \tif(!Initialize(m_appName, \"geosync_\"))\r\n\t\treturn false;\r\n\r\n //send interesting things to console \r\n return wxApp::OnInit();\r\n}\r\n\r\nint GeoSyncApp::OnExit()\r\n{\r\n wxDELETE(m_pTaskManager);\r\n\r\n Uninitialize();\r\n\r\n return wxApp::OnExit();\r\n}\r\n\r\nvoid GeoSyncApp::OnAppAbout(void)\r\n{\r\n}\r\n\r\nvoid GeoSyncApp::OnAppOptions(void)\r\n{\r\n\r\n}\r\n\r\n//enter main loop\r\nvoid GeoSyncApp::OnEventLoopEnter(wxEventLoopBase* loop)\r\n{\r\n if (!m_pTaskManager)\r\n m_pTaskManager = new GeoSyncTaskManager();\r\n}\r\n\r\nbool GeoSyncApp::SetupSys(const wxString &sSysPath)\r\n{\r\n return true; //no need sys?\r\n}\r\n\r\nbool GeoSyncApp::Initialize(const wxString &sAppName, const wxString &sLogFilePrefix)\r\n{\r\n\twxGISAppConfig oConfig = GetConfig();\r\n if(!oConfig.IsOk())\r\n return false;\r\n\r\n\twxString sLogDir = oConfig.GetLogDir();\r\n\tif(!SetupLog(sLogDir, sLogFilePrefix))\r\n return false;\r\n wxLogMessage(_(\"%s %s is initializing...\"), sAppName.c_str(), GetAppVersionString().c_str());\r\n\r\n\tif(!SetupLoc(oConfig.GetLocale(), oConfig.GetLocaleDir()))\r\n return false;\r\n\r\n\t//setup sys dir\r\n\twxString sSysDir = oConfig.GetSysDir();\r\n\tif(!SetupSys(sSysDir))\r\n return false;\r\n\r\n\tbool bDebugMode = oConfig.GetDebugMode();\r\n\tSetDebugMode(bDebugMode);\r\n\r\n if(!GetApplication())\r\n SetApplication(this);\r\n\r\n return true;\r\n}\r\n\r\nbool GeoSyncApp::OnExceptionInMainLoop()\r\n{\r\n wxLogError(_(\"Unhandled Exception\"));\r\n exit(EXIT_FAILURE);\r\n}\r\n\r\nvoid GeoSyncApp::OnFatalException()\r\n{\r\n wxLogError(_(\"Unhandled Exception\"));\r\n exit(EXIT_FAILURE);\r\n}\r\n\r\nvoid GeoSyncApp::OnUnhandledException()\r\n{\r\n wxLogError(_(\"Unhandled Exception\"));\r\n exit(EXIT_FAILURE);\r\n}" }, { "alpha_fraction": 0.7349953651428223, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 64.6212158203125, "blob_id": "6f97de5a99220ed5eb0511d1c0b98a0c7e26cd51", "content_id": "47efd96f88126bd13e26eeab9794701f19144748", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4332, "license_type": "no_license", "max_line_length": 254, "num_lines": 66, "path": "/geosync/include/task/task.h", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "/******************************************************************************\n* Project: geosync\n* Purpose: sync spatial data with NGW\n* Author: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru\n******************************************************************************\n* Copyright (C) 2014 NextGIS\n*\n* This program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n****************************************************************************/\n#pragma once\n\n#include \"task/taskapp.h\"\n#include \"wxgis/catalog/gxcatalog.h\"\n#include \"wxgis/catalog/gxngwconn.h\"\n#include \"wxgis/catalog/gxdataset.h\"\n#include \"wxgis/catalog/gxfolder.h\"\n\n/** @class GeoSyncTask\n \n Main spatial data sync task class\n*/\nclass GeoSyncTask\n{\n enum enumSyncType{\n enumSyncUnknown = 0,\n enumSyncFolder,\n enumSyncFile\n };\npublic:\n GeoSyncTask(const wxString &sLocalPath, const wxString& sURL, const wxString& sUser, const wxString& sPasswd, long nRemoteId, geoSyncDirection eDirection);\n virtual ~GeoSyncTask(void);\n virtual bool Execute(ITrackCancel * const pTrackCancel = NULL);\nprotected:\n virtual bool SyncSources(wxGxFolder* const pLocalDir, wxGxNGWResourceGroup* const pRemoteDir, geoSyncDirection eDirection, ITrackCancel * const pTrackCancel = NULL);\n virtual bool SyncFile(IGxDataset* const pLocalFile, wxGxNGWFileSet* const pRemoteFileSet, geoSyncDirection eDirection, ITrackCancel * const pTrackCancel = NULL);\n virtual bool SyncFileCreateOrDelete(IGxDataset* const pGxDataset, wxGxNGWResourceGroup* const pRemoteDir, bool wasExist, geoSyncDirection eDirection, ITrackCancel * const pTrackCancel = NULL);\n virtual bool SyncFileCreateOrDelete(wxGxFolder* const pLocalDir, wxGxNGWFileSet *pRemoteFileSet, bool wasExist, geoSyncDirection eDirection, ITrackCancel * const pTrackCancel = NULL);\n virtual bool SyncFolderCreateOrDeleteL2R(wxGxFolder* const pLocalDir, wxGxNGWResourceGroup* const pRemoteDir, bool wasExist, geoSyncDirection eDirection, ITrackCancel * const pTrackCancel = NULL);\n virtual bool SyncFolderCreateOrDeleteR2L(wxGxFolder* const pLocalDir, wxGxNGWResourceGroup* const pRemoteDir, bool wasExist, geoSyncDirection eDirection, ITrackCancel * const pTrackCancel = NULL);\n virtual bool SyncFile(wxGxFolder* const pLocalDir, wxGxNGWFileSet *pRemoteFileSet, geoSyncDirection eDirection, ITrackCancel * const pTrackCancel = NULL);\n virtual bool SyncFile(IGxDataset* const pGxDataset, wxGxNGWResourceGroup* const pRemoteDir, geoSyncDirection eDirection, ITrackCancel * const pTrackCancel = NULL);\n virtual bool Upload(wxGxNGWResourceGroup* const pRemoteDir, IGxDataset* const pGxDataset, ITrackCancel * const pTrackCancel = NULL);\n virtual bool Download(wxGxFolder* const pLocalDir, wxGxNGWFileSet *pRemoteFileSet, ITrackCancel * const pTrackCancel = NULL);\n virtual bool Upload(wxGxNGWResourceGroup* const pRemoteDir, wxGxFolder* const pLocalDir, ITrackCancel * const pTrackCancel = NULL);\n virtual bool Download(wxGxFolder* const pLocalDir, wxGxNGWResourceGroup* const pRemoteDir, ITrackCancel * const pTrackCancel = NULL);\n virtual bool UploadFileBucket(wxGxNGWResourceGroup* const pRemoteDir, const wxString &sName, const wxArrayString& asPaths, const wxDateTime &dt, const wxJSONValue& oMetadata = wxJSONValue(wxJSONTYPE_INVALID), ITrackCancel* const pTrackCancel = NULL);\n virtual void GeoSyncTask::StoreSyncState(wxGxFolder* const pFolder);\n virtual wxGxFolder* GetOrCreateFolder(wxGxFolder* const pFolder, const wxString &sSubFolderName, ITrackCancel* const pTrackCancel = NULL);\nprotected:\n wxString m_sLocalPath;\n wxString m_sURL, m_sUser, m_sPasswd;\n long m_nRemoteId;\n geoSyncDirection m_eDirection;\n wxArrayLong m_paInspectedItems;\n};\n\n" }, { "alpha_fraction": 0.894287645816803, "alphanum_fraction": 0.9014487266540527, "avg_line_length": 63.9796028137207, "blob_id": "0a23c5fc0d1f71b3ec4b7270c4b9b8bccf324808", "content_id": "cc89be4a7effda461bcf561528a47c9d4dd682be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 139085, "license_type": "no_license", "max_line_length": 191, "num_lines": 2108, "path": "/qgis-installer/rekod-school-center/DEFAULT-LIGHT/QGISCUSTOMIZATION2.ini", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "[Customization]\r\nMenus=true\r\nMenus\\mDatabaseMenu=true\r\nMenus\\mDatabaseMenu\\DBManager=true\r\nMenus\\mDatabaseMenu\\OfflineEditing=true\r\nMenus\\mDatabaseMenu\\OfflineEditing\\mActionConvertProject=true\r\nMenus\\mDatabaseMenu\\OfflineEditing\\mActionSynchronize=true\r\nMenus\\mDatabaseMenu\\Spit=true\r\nMenus\\mDatabaseMenu\\Spit\\spitAction=true\r\nMenus\\mDatabaseMenu\\eVis=true\r\nMenus\\mDatabaseMenu\\eVis\\mDatabaseConnectionActionPointer=true\r\nMenus\\mDatabaseMenu\\eVis\\mEventBrowserActionPointer=true\r\nMenus\\mDatabaseMenu\\eVis\\mEventIdToolActionPointer=true\r\nMenus\\mEditMenu=true\r\nMenus\\mEditMenu\\mActionAddFeature=true\r\nMenus\\mEditMenu\\mActionAddPart=true\r\nMenus\\mEditMenu\\mActionAddRing=true\r\nMenus\\mEditMenu\\mActionCopyFeatures=true\r\nMenus\\mEditMenu\\mActionCutFeatures=true\r\nMenus\\mEditMenu\\mActionDeletePart=true\r\nMenus\\mEditMenu\\mActionDeleteRing=true\r\nMenus\\mEditMenu\\mActionDeleteSelected=true\r\nMenus\\mEditMenu\\mActionFillRing=true\r\nMenus\\mEditMenu\\mActionMergeFeatureAttributes=true\r\nMenus\\mEditMenu\\mActionMergeFeatures=true\r\nMenus\\mEditMenu\\mActionMoveFeature=true\r\nMenus\\mEditMenu\\mActionNodeTool=true\r\nMenus\\mEditMenu\\mActionOffsetCurve=true\r\nMenus\\mEditMenu\\mActionPasteFeatures=true\r\nMenus\\mEditMenu\\mActionRedo=true\r\nMenus\\mEditMenu\\mActionReshapeFeatures=true\r\nMenus\\mEditMenu\\mActionRotateFeature=true\r\nMenus\\mEditMenu\\mActionRotatePointSymbols=true\r\nMenus\\mEditMenu\\mActionSimplifyFeature=true\r\nMenus\\mEditMenu\\mActionSplitFeatures=true\r\nMenus\\mEditMenu\\mActionSplitParts=true\r\nMenus\\mEditMenu\\mActionUndo=true\r\nMenus\\mEditMenu\\mMenuPasteAs=true\r\nMenus\\mEditMenu\\mMenuPasteAs\\mActionPasteAsNewMemoryVector=true\r\nMenus\\mEditMenu\\mMenuPasteAs\\mActionPasteAsNewVector=true\r\nMenus\\mHelpMenu=true\r\nMenus\\mHelpMenu\\mActionAbout=true\r\nMenus\\mHelpMenu\\mActionCheckQgisVersion=false\r\nMenus\\mHelpMenu\\mActionHelpAPI=false\r\nMenus\\mHelpMenu\\mActionHelpContents=false\r\nMenus\\mHelpMenu\\mActionNeedSupport=false\r\nMenus\\mHelpMenu\\mActionQgisHomePage=false\r\nMenus\\mHelpMenu\\mActionSponsors=false\r\nMenus\\mLayerMenu=true\r\nMenus\\mLayerMenu\\mActionAddAllToOverview=true\r\nMenus\\mLayerMenu\\mActionAddDelimitedText=true\r\nMenus\\mLayerMenu\\mActionAddLayerSeparator=true\r\nMenus\\mLayerMenu\\mActionAddMssqlLayer=true\r\nMenus\\mLayerMenu\\mActionAddOgrLayer=true\r\nMenus\\mLayerMenu\\mActionAddOracleLayer=true\r\nMenus\\mLayerMenu\\mActionAddPgLayer=true\r\nMenus\\mLayerMenu\\mActionAddRasterLayer=true\r\nMenus\\mLayerMenu\\mActionAddSpatiaLiteLayer=true\r\nMenus\\mLayerMenu\\mActionAddSqlAnywhereLayer=true\r\nMenus\\mLayerMenu\\mActionAddToOverview=true\r\nMenus\\mLayerMenu\\mActionAddWcsLayer=true\r\nMenus\\mLayerMenu\\mActionAddWfsLayer=true\r\nMenus\\mLayerMenu\\mActionAddWmsLayer=true\r\nMenus\\mLayerMenu\\mActionCopyStyle=true\r\nMenus\\mLayerMenu\\mActionDuplicateLayer=true\r\nMenus\\mLayerMenu\\mActionEmbedLayers=true\r\nMenus\\mLayerMenu\\mActionHideAllLayers=true\r\nMenus\\mLayerMenu\\mActionLabeling=true\r\nMenus\\mLayerMenu\\mActionLayerProperties=true\r\nMenus\\mLayerMenu\\mActionLayerSaveAs=true\r\nMenus\\mLayerMenu\\mActionLayerSelectionSaveAs=true\r\nMenus\\mLayerMenu\\mActionLayerSubsetString=true\r\nMenus\\mLayerMenu\\mActionOpenTable=true\r\nMenus\\mLayerMenu\\mActionPasteStyle=true\r\nMenus\\mLayerMenu\\mActionRemoveAllFromOverview=true\r\nMenus\\mLayerMenu\\mActionRemoveLayer=true\r\nMenus\\mLayerMenu\\mActionSaveLayerEdits=true\r\nMenus\\mLayerMenu\\mActionSetLayerCRS=true\r\nMenus\\mLayerMenu\\mActionSetProjectCRSFromLayer=true\r\nMenus\\mLayerMenu\\mActionShowAllLayers=true\r\nMenus\\mLayerMenu\\mActionToggleEditing=true\r\nMenus\\mLayerMenu\\mNewLayerMenu=true\r\nMenus\\mLayerMenu\\mNewLayerMenu\\mActionNewSpatiaLiteLayer=true\r\nMenus\\mLayerMenu\\mNewLayerMenu\\mActionNewVectorLayer=true\r\nMenus\\mLayerMenu\\mNewLayerMenu\\mCreateGPXAction=true\r\nMenus\\mLayerMenu\\mQActionPointer=true\r\nMenus\\mPluginMenu=true\r\nMenus\\mPluginMenu\\GRASS=true\r\nMenus\\mPluginMenu\\GRASS\\mAddRasterAction=true\r\nMenus\\mPluginMenu\\GRASS\\mAddVectorAction=true\r\nMenus\\mPluginMenu\\GRASS\\mCloseMapsetAction=true\r\nMenus\\mPluginMenu\\GRASS\\mEditAction=true\r\nMenus\\mPluginMenu\\GRASS\\mEditRegionAction=true\r\nMenus\\mPluginMenu\\GRASS\\mNewMapsetAction=true\r\nMenus\\mPluginMenu\\GRASS\\mNewVectorAction=true\r\nMenus\\mPluginMenu\\GRASS\\mOpenMapsetAction=true\r\nMenus\\mPluginMenu\\GRASS\\mOpenToolsAction=true\r\nMenus\\mPluginMenu\\GRASS\\mRegionAction=true\r\nMenus\\mPluginMenu\\mActionManagePlugins=true\r\nMenus\\mPluginMenu\\mActionShowPythonDialog=true\r\nMenus\\mProjectMenu=true\r\nMenus\\mProjectMenu\\mActionDxfExport=false\r\nMenus\\mProjectMenu\\mActionExit=true\r\nMenus\\mProjectMenu\\mActionNewPrintComposer=true\r\nMenus\\mProjectMenu\\mActionNewProject=true\r\nMenus\\mProjectMenu\\mActionOpenProject=true\r\nMenus\\mProjectMenu\\mActionProjectProperties=true\r\nMenus\\mProjectMenu\\mActionSaveMapAsImage=true\r\nMenus\\mProjectMenu\\mActionSaveProject=true\r\nMenus\\mProjectMenu\\mActionSaveProjectAs=true\r\nMenus\\mProjectMenu\\mActionShowComposerManager=true\r\nMenus\\mProjectMenu\\mPrintComposersMenu=true\r\nMenus\\mProjectMenu\\mProjectFromTemplateMenu=true\r\nMenus\\mProjectMenu\\mRecentProjectsMenu=true\r\nMenus\\mRasterMenu=true\r\nMenus\\mRasterMenu\\Georeferencer=true\r\nMenus\\mRasterMenu\\Georeferencer\\mActionRunGeoref=true\r\nMenus\\mRasterMenu\\Heatmap=true\r\nMenus\\mRasterMenu\\Heatmap\\mQActionPointer=true\r\nMenus\\mRasterMenu\\Interpolation=true\r\nMenus\\mRasterMenu\\Interpolation\\mInterpolationAction=true\r\nMenus\\mRasterMenu\\Zonalstatistics=true\r\nMenus\\mRasterMenu\\Zonalstatistics\\ZonalStatistics=true\r\nMenus\\mRasterMenu\\mActionShowRasterCalculator=true\r\nMenus\\mRasterMenu\\mTerrainAnalysisMenu=true\r\nMenus\\mRasterMenu\\mTerrainAnalysisMenu\\aspectAction=true\r\nMenus\\mRasterMenu\\mTerrainAnalysisMenu\\hilshadeAction=true\r\nMenus\\mRasterMenu\\mTerrainAnalysisMenu\\reliefAction=true\r\nMenus\\mRasterMenu\\mTerrainAnalysisMenu\\ruggednesIndex=true\r\nMenus\\mRasterMenu\\mTerrainAnalysisMenu\\slopeAction=true\r\nMenus\\mSettingsMenu=true\r\nMenus\\mSettingsMenu\\mActionConfigureShortcuts=true\r\nMenus\\mSettingsMenu\\mActionCustomProjection=true\r\nMenus\\mSettingsMenu\\mActionCustomization=true\r\nMenus\\mSettingsMenu\\mActionOptions=true\r\nMenus\\mSettingsMenu\\mActionSnappingOptions=true\r\nMenus\\mSettingsMenu\\mActionStyleManagerV2=true\r\nMenus\\mVectorMenu=true\r\nMenus\\mVectorMenu\\CoordinateCapture=true\r\nMenus\\mVectorMenu\\CoordinateCapture\\mQActionPointer=true\r\nMenus\\mVectorMenu\\DxfShp=true\r\nMenus\\mVectorMenu\\DxfShp\\mQActionPointer=true\r\nMenus\\mVectorMenu\\GPS=true\r\nMenus\\mVectorMenu\\GPS\\mQActionPointer=true\r\nMenus\\mVectorMenu\\Roadgraph=true\r\nMenus\\mVectorMenu\\Roadgraph\\mQSettingsAction=true\r\nMenus\\mVectorMenu\\SpatialQuery=true\r\nMenus\\mVectorMenu\\SpatialQuery\\mSpatialQueryAction=true\r\nMenus\\mVectorMenu\\TopologyChecker=true\r\nMenus\\mVectorMenu\\TopologyChecker\\mQActionPointer=true\r\nMenus\\mVectorMenu\\analysisMenu=true\r\nMenus\\mVectorMenu\\analysisMenu\\compStats=true\r\nMenus\\mVectorMenu\\analysisMenu\\distMatrix=true\r\nMenus\\mVectorMenu\\analysisMenu\\intLines=true\r\nMenus\\mVectorMenu\\analysisMenu\\listUnique=true\r\nMenus\\mVectorMenu\\analysisMenu\\meanCoords=true\r\nMenus\\mVectorMenu\\analysisMenu\\nearestNeigh=true\r\nMenus\\mVectorMenu\\analysisMenu\\pointsPoly=true\r\nMenus\\mVectorMenu\\analysisMenu\\sumLines=true\r\nMenus\\mVectorMenu\\conversionMenu=true\r\nMenus\\mVectorMenu\\conversionMenu\\centroids=true\r\nMenus\\mVectorMenu\\conversionMenu\\checkGeom=true\r\nMenus\\mVectorMenu\\conversionMenu\\compGeo=true\r\nMenus\\mVectorMenu\\conversionMenu\\delaunay=true\r\nMenus\\mVectorMenu\\conversionMenu\\densify=true\r\nMenus\\mVectorMenu\\conversionMenu\\extNodes=true\r\nMenus\\mVectorMenu\\conversionMenu\\linesToPolys=true\r\nMenus\\mVectorMenu\\conversionMenu\\multiToSingle=true\r\nMenus\\mVectorMenu\\conversionMenu\\polysToLines=true\r\nMenus\\mVectorMenu\\conversionMenu\\simplify=true\r\nMenus\\mVectorMenu\\conversionMenu\\singleToMulti=true\r\nMenus\\mVectorMenu\\conversionMenu\\voronoi=true\r\nMenus\\mVectorMenu\\dataManageMenu=true\r\nMenus\\mVectorMenu\\dataManageMenu\\define=true\r\nMenus\\mVectorMenu\\dataManageMenu\\mergeShapes=true\r\nMenus\\mVectorMenu\\dataManageMenu\\spatJoin=true\r\nMenus\\mVectorMenu\\dataManageMenu\\spatialIndex=true\r\nMenus\\mVectorMenu\\dataManageMenu\\splitVect=true\r\nMenus\\mVectorMenu\\geoMenu=true\r\nMenus\\mVectorMenu\\geoMenu\\clip=true\r\nMenus\\mVectorMenu\\geoMenu\\dissolve=true\r\nMenus\\mVectorMenu\\geoMenu\\dynaBuffer=true\r\nMenus\\mVectorMenu\\geoMenu\\eliminate=true\r\nMenus\\mVectorMenu\\geoMenu\\erase=true\r\nMenus\\mVectorMenu\\geoMenu\\intersect=true\r\nMenus\\mVectorMenu\\geoMenu\\minConvex=true\r\nMenus\\mVectorMenu\\geoMenu\\symDifference=true\r\nMenus\\mVectorMenu\\geoMenu\\union=true\r\nMenus\\mVectorMenu\\menuOpenStreetMap=false\r\nMenus\\mVectorMenu\\menuOpenStreetMap\\mActionOSMDownload=true\r\nMenus\\mVectorMenu\\menuOpenStreetMap\\mActionOSMExport=true\r\nMenus\\mVectorMenu\\menuOpenStreetMap\\mActionOSMImport=true\r\nMenus\\mVectorMenu\\researchMenu=true\r\nMenus\\mVectorMenu\\researchMenu\\layerExtent=true\r\nMenus\\mVectorMenu\\researchMenu\\randPoints=true\r\nMenus\\mVectorMenu\\researchMenu\\randSel=true\r\nMenus\\mVectorMenu\\researchMenu\\randSub=true\r\nMenus\\mVectorMenu\\researchMenu\\regPoints=true\r\nMenus\\mVectorMenu\\researchMenu\\selectLocation=true\r\nMenus\\mVectorMenu\\researchMenu\\vectGrid=true\r\nMenus\\mViewMenu=true\r\nMenus\\mViewMenu\\mActionDraw=true\r\nMenus\\mViewMenu\\mActionIdentify=true\r\nMenus\\mViewMenu\\mActionMapTips=true\r\nMenus\\mViewMenu\\mActionNewBookmark=true\r\nMenus\\mViewMenu\\mActionPan=true\r\nMenus\\mViewMenu\\mActionPanToSelected=true\r\nMenus\\mViewMenu\\mActionShowBookmarks=true\r\nMenus\\mViewMenu\\mActionToggleFullScreen=true\r\nMenus\\mViewMenu\\mActionZoomActualSize=true\r\nMenus\\mViewMenu\\mActionZoomFullExtent=true\r\nMenus\\mViewMenu\\mActionZoomIn=true\r\nMenus\\mViewMenu\\mActionZoomLast=true\r\nMenus\\mViewMenu\\mActionZoomNext=true\r\nMenus\\mViewMenu\\mActionZoomOut=true\r\nMenus\\mViewMenu\\mActionZoomToLayer=true\r\nMenus\\mViewMenu\\mActionZoomToSelected=true\r\nMenus\\mViewMenu\\mPanelMenu=true\r\nMenus\\mViewMenu\\mPanelMenu\\toolboxAction=true\r\nMenus\\mViewMenu\\mToolbarMenu=true\r\nMenus\\mViewMenu\\mToolbarMenu\\mActionToggleAdvancedDigitizeToolBar=true\r\nMenus\\mViewMenu\\mToolbarMenu\\mActionToggleAttributesToolBar=true\r\nMenus\\mViewMenu\\mToolbarMenu\\mActionToggleDatabaseToolBar=true\r\nMenus\\mViewMenu\\mToolbarMenu\\mActionToggleDigitizeToolBar=true\r\nMenus\\mViewMenu\\mToolbarMenu\\mActionToggleFileToolBar=true\r\nMenus\\mViewMenu\\mToolbarMenu\\mActionToggleHelpToolBar=true\r\nMenus\\mViewMenu\\mToolbarMenu\\mActionToggleLabelToolBar=true\r\nMenus\\mViewMenu\\mToolbarMenu\\mActionToggleLayerToolBar=true\r\nMenus\\mViewMenu\\mToolbarMenu\\mActionToggleMapNavToolBar=true\r\nMenus\\mViewMenu\\mToolbarMenu\\mActionTogglePluginToolBar=true\r\nMenus\\mViewMenu\\mToolbarMenu\\mActionToggleRasterToolBar=true\r\nMenus\\mViewMenu\\mToolbarMenu\\mActionToggleVectorToolBar=true\r\nMenus\\mViewMenu\\mToolbarMenu\\mActionToggleWebToolBar=true\r\nMenus\\mViewMenu\\menuDecorations=true\r\nMenus\\mViewMenu\\menuDecorations\\mActionDecorationCopyright=true\r\nMenus\\mViewMenu\\menuDecorations\\mActionDecorationGrid=true\r\nMenus\\mViewMenu\\menuDecorations\\mActionDecorationNorthArrow=true\r\nMenus\\mViewMenu\\menuDecorations\\mActionDecorationScaleBar=true\r\nMenus\\mViewMenu\\menuMeasure=true\r\nMenus\\mViewMenu\\menuMeasure\\mActionMeasure=true\r\nMenus\\mViewMenu\\menuMeasure\\mActionMeasureAngle=true\r\nMenus\\mViewMenu\\menuMeasure\\mActionMeasureArea=true\r\nMenus\\mViewMenu\\menuSelect=true\r\nMenus\\mViewMenu\\menuSelect\\mActionDeselectAll=true\r\nMenus\\mViewMenu\\menuSelect\\mActionSelect=true\r\nMenus\\mViewMenu\\menuSelect\\mActionSelectByExpression=true\r\nMenus\\mViewMenu\\menuSelect\\mActionSelectFreehand=true\r\nMenus\\mViewMenu\\menuSelect\\mActionSelectPolygon=true\r\nMenus\\mViewMenu\\menuSelect\\mActionSelectRadius=true\r\nMenus\\mViewMenu\\menuSelect\\mActionSelectRectangle=true\r\nMenus\\mWebMenu=true\r\nMenus\\processing=true\r\nMenus\\processing\\commanderAction=true\r\nMenus\\processing\\configAction=true\r\nMenus\\processing\\historyAction=true\r\nMenus\\processing\\modelerAction=true\r\nMenus\\processing\\resultsAction=true\r\nMenus\\processing\\toolboxAction=true\r\nPanels=true\r\nPanels\\Browser=true\r\nPanels\\Browser2=false\r\nPanels\\CoordinateCapture=true\r\nPanels\\GPSInformation=false\r\nPanels\\LayerOrder=true\r\nPanels\\Legend=true\r\nPanels\\MessageLog=true\r\nPanels\\Overview=false\r\nPanels\\ProcessingToolbox=true\r\nPanels\\ShortestPathDock=true\r\nPanels\\Undo=false\r\nStatusBar=true\r\nStatusBar\\mCoordsEdit=true\r\nStatusBar\\mCoordsLabel=true\r\nStatusBar\\mMessageLogViewerButton=true\r\nStatusBar\\mOnTheFlyProjectionStatusLabel=true\r\nStatusBar\\mOntheFlyProjectionStatusButton=true\r\nStatusBar\\mProgressBar=true\r\nStatusBar\\mRenderSuppressionCBox=true\r\nStatusBar\\mScaleEdit=true\r\nStatusBar\\mScaleLable=true\r\nStatusBar\\mStopRenderButton=true\r\nStatusBar\\mToggleExtentsViewButton=true\r\nToolbars=true\r\nToolbars\\GRASS=false\r\nToolbars\\GRASS\\mAddRasterAction=true\r\nToolbars\\GRASS\\mAddVectorAction=true\r\nToolbars\\GRASS\\mCloseMapsetAction=true\r\nToolbars\\GRASS\\mEditAction=true\r\nToolbars\\GRASS\\mEditRegionAction=true\r\nToolbars\\GRASS\\mNewMapsetAction=true\r\nToolbars\\GRASS\\mNewVectorAction=true\r\nToolbars\\GRASS\\mOpenMapsetAction=true\r\nToolbars\\GRASS\\mOpenToolsAction=true\r\nToolbars\\GRASS\\mRegionAction=true\r\nToolbars\\mAdvancedDigitizeToolBar=true\r\nToolbars\\mAdvancedDigitizeToolBar\\mActionAddPart=true\r\nToolbars\\mAdvancedDigitizeToolBar\\mActionAddRing=true\r\nToolbars\\mAdvancedDigitizeToolBar\\mActionDeletePart=true\r\nToolbars\\mAdvancedDigitizeToolBar\\mActionDeleteRing=true\r\nToolbars\\mAdvancedDigitizeToolBar\\mActionFillRing=true\r\nToolbars\\mAdvancedDigitizeToolBar\\mActionMergeFeatureAttributes=true\r\nToolbars\\mAdvancedDigitizeToolBar\\mActionMergeFeatures=true\r\nToolbars\\mAdvancedDigitizeToolBar\\mActionOffsetCurve=true\r\nToolbars\\mAdvancedDigitizeToolBar\\mActionRedo=true\r\nToolbars\\mAdvancedDigitizeToolBar\\mActionReshapeFeatures=true\r\nToolbars\\mAdvancedDigitizeToolBar\\mActionRotateFeature=true\r\nToolbars\\mAdvancedDigitizeToolBar\\mActionRotatePointSymbols=true\r\nToolbars\\mAdvancedDigitizeToolBar\\mActionSimplifyFeature=true\r\nToolbars\\mAdvancedDigitizeToolBar\\mActionSplitFeatures=true\r\nToolbars\\mAdvancedDigitizeToolBar\\mActionSplitParts=true\r\nToolbars\\mAdvancedDigitizeToolBar\\mActionUndo=true\r\nToolbars\\mAttributesToolBar=true\r\nToolbars\\mAttributesToolBar\\ActionAnnotation=true\r\nToolbars\\mAttributesToolBar\\ActionFeatureAction=true\r\nToolbars\\mAttributesToolBar\\ActionMeasure=true\r\nToolbars\\mAttributesToolBar\\ActionSelect=true\r\nToolbars\\mAttributesToolBar\\mActionDeselectAll=true\r\nToolbars\\mAttributesToolBar\\mActionIdentify=true\r\nToolbars\\mAttributesToolBar\\mActionMapTips=true\r\nToolbars\\mAttributesToolBar\\mActionNewBookmark=true\r\nToolbars\\mAttributesToolBar\\mActionOpenFieldCalc=true\r\nToolbars\\mAttributesToolBar\\mActionOpenTable=true\r\nToolbars\\mAttributesToolBar\\mActionSelectByExpression=true\r\nToolbars\\mAttributesToolBar\\mActionShowBookmarks=true\r\nToolbars\\mDatabaseToolBar=true\r\nToolbars\\mDatabaseToolBar\\mActionConvertProject=true\r\nToolbars\\mDatabaseToolBar\\mActionSynchronize=true\r\nToolbars\\mDatabaseToolBar\\mDatabaseConnectionActionPointer=true\r\nToolbars\\mDatabaseToolBar\\mEventBrowserActionPointer=true\r\nToolbars\\mDatabaseToolBar\\mEventIdToolActionPointer=true\r\nToolbars\\mDatabaseToolBar\\spitAction=true\r\nToolbars\\mDigitizeToolBar=true\r\nToolbars\\mDigitizeToolBar\\mActionAddFeature=true\r\nToolbars\\mDigitizeToolBar\\mActionCopyFeatures=true\r\nToolbars\\mDigitizeToolBar\\mActionCutFeatures=true\r\nToolbars\\mDigitizeToolBar\\mActionDeleteSelected=true\r\nToolbars\\mDigitizeToolBar\\mActionMoveFeature=true\r\nToolbars\\mDigitizeToolBar\\mActionNodeTool=true\r\nToolbars\\mDigitizeToolBar\\mActionPasteFeatures=true\r\nToolbars\\mDigitizeToolBar\\mActionSaveLayerEdits=true\r\nToolbars\\mDigitizeToolBar\\mActionToggleEditing=true\r\nToolbars\\mFileToolBar=true\r\nToolbars\\mFileToolBar\\mActionNewPrintComposer=true\r\nToolbars\\mFileToolBar\\mActionNewProject=true\r\nToolbars\\mFileToolBar\\mActionOpenProject=true\r\nToolbars\\mFileToolBar\\mActionSaveProject=true\r\nToolbars\\mFileToolBar\\mActionSaveProjectAs=true\r\nToolbars\\mFileToolBar\\mActionShowComposerManager=true\r\nToolbars\\mHelpToolBar=false\r\nToolbars\\mHelpToolBar\\mActionHelpContents=true\r\nToolbars\\mLabelToolBar=true\r\nToolbars\\mLabelToolBar\\mActionChangeLabelProperties=true\r\nToolbars\\mLabelToolBar\\mActionLabeling=true\r\nToolbars\\mLabelToolBar\\mActionMoveLabel=true\r\nToolbars\\mLabelToolBar\\mActionPinLabels=true\r\nToolbars\\mLabelToolBar\\mActionRotateLabel=true\r\nToolbars\\mLabelToolBar\\mActionShowHideLabels=true\r\nToolbars\\mLabelToolBar\\mActionShowPinnedLabels=true\r\nToolbars\\mLayerToolBar=true\r\nToolbars\\mLayerToolBar\\ActionNewLayer=true\r\nToolbars\\mLayerToolBar\\mActionAddDelimitedText=true\r\nToolbars\\mLayerToolBar\\mActionAddMssqlLayer=true\r\nToolbars\\mLayerToolBar\\mActionAddOgrLayer=true\r\nToolbars\\mLayerToolBar\\mActionAddOracleLayer=true\r\nToolbars\\mLayerToolBar\\mActionAddPgLayer=true\r\nToolbars\\mLayerToolBar\\mActionAddRasterLayer=true\r\nToolbars\\mLayerToolBar\\mActionAddSpatiaLiteLayer=true\r\nToolbars\\mLayerToolBar\\mActionAddSqlAnywhereLayer=true\r\nToolbars\\mLayerToolBar\\mActionAddWcsLayer=true\r\nToolbars\\mLayerToolBar\\mActionAddWfsLayer=true\r\nToolbars\\mLayerToolBar\\mActionAddWmsLayer=true\r\nToolbars\\mLayerToolBar\\mActionRemoveLayer=true\r\nToolbars\\mLayerToolBar\\mCreateGPXAction=true\r\nToolbars\\mLayerToolBar\\mQActionPointer=true\r\nToolbars\\mMapNavToolBar=true\r\nToolbars\\mMapNavToolBar\\mActionDraw=true\r\nToolbars\\mMapNavToolBar\\mActionPan=true\r\nToolbars\\mMapNavToolBar\\mActionPanToSelected=true\r\nToolbars\\mMapNavToolBar\\mActionTouch=true\r\nToolbars\\mMapNavToolBar\\mActionZoomActualSize=true\r\nToolbars\\mMapNavToolBar\\mActionZoomFullExtent=true\r\nToolbars\\mMapNavToolBar\\mActionZoomIn=true\r\nToolbars\\mMapNavToolBar\\mActionZoomLast=true\r\nToolbars\\mMapNavToolBar\\mActionZoomNext=true\r\nToolbars\\mMapNavToolBar\\mActionZoomOut=true\r\nToolbars\\mMapNavToolBar\\mActionZoomToLayer=true\r\nToolbars\\mMapNavToolBar\\mActionZoomToSelected=true\r\nToolbars\\mPluginToolBar=true\r\nToolbars\\mRasterToolBar=true\r\nToolbars\\mRasterToolBar\\ZonalStatistics=true\r\nToolbars\\mRasterToolBar\\mActionDecreaseBrightness=true\r\nToolbars\\mRasterToolBar\\mActionDecreaseContrast=true\r\nToolbars\\mRasterToolBar\\mActionFullCumulativeCutStretch=true\r\nToolbars\\mRasterToolBar\\mActionFullHistogramStretch=true\r\nToolbars\\mRasterToolBar\\mActionIncreaseBrightness=true\r\nToolbars\\mRasterToolBar\\mActionIncreaseContrast=true\r\nToolbars\\mRasterToolBar\\mActionLocalCumulativeCutStretch=true\r\nToolbars\\mRasterToolBar\\mActionLocalHistogramStretch=true\r\nToolbars\\mRasterToolBar\\mActionRunGeoref=true\r\nToolbars\\mRasterToolBar\\mInterpolationAction=true\r\nToolbars\\mRasterToolBar\\mQActionPointer=true\r\nToolbars\\mVectorToolBar=true\r\nToolbars\\mVectorToolBar\\mQActionPointer=true\r\nToolbars\\mVectorToolBar\\mSpatialQueryAction=true\r\nToolbars\\mWebToolBar=false\r\nWidgets=true\r\nWidgets\\MainWindow=true\r\nWidgets\\MainWindow\\centralwidget=true\r\nWidgets\\QgsAbout=true\r\nWidgets\\QgsAbout\\buttonBox=true\r\nWidgets\\QgsAbout\\tabWidget=true\r\nWidgets\\QgsAbout\\tabWidget\\TabPage=true\r\nWidgets\\QgsAbout\\tabWidget\\TabPage\\txtProviders=true\r\nWidgets\\QgsAbout\\tabWidget\\TabPage\\txtProviders\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsAbout\\tabWidget\\TabPage\\txtProviders\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsAbout\\tabWidget\\TabPage\\txtProviders\\qt_scrollarea_viewport=true\r\nWidgets\\QgsAbout\\tabWidget\\Widget2=true\r\nWidgets\\QgsAbout\\tabWidget\\Widget2\\TextLabel4=true\r\nWidgets\\QgsAbout\\tabWidget\\Widget2\\btnQgisHome=true\r\nWidgets\\QgsAbout\\tabWidget\\Widget2\\btnQgisUser=true\r\nWidgets\\QgsAbout\\tabWidget\\Widget2\\label=true\r\nWidgets\\QgsAbout\\tabWidget\\Widget2\\label_2=true\r\nWidgets\\QgsAbout\\tabWidget\\Widget2\\qgisIcon=true\r\nWidgets\\QgsAbout\\tabWidget\\Widget3=true\r\nWidgets\\QgsAbout\\tabWidget\\Widget3\\txtWhatsNew=true\r\nWidgets\\QgsAbout\\tabWidget\\Widget3\\txtWhatsNew\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsAbout\\tabWidget\\Widget3\\txtWhatsNew\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsAbout\\tabWidget\\Widget3\\txtWhatsNew\\qt_scrollarea_viewport=true\r\nWidgets\\QgsAbout\\tabWidget\\tab=true\r\nWidgets\\QgsAbout\\tabWidget\\tab\\label_3=true\r\nWidgets\\QgsAbout\\tabWidget\\tab\\label_4=true\r\nWidgets\\QgsAbout\\tabWidget\\tab_3=true\r\nWidgets\\QgsAbout\\tabWidget\\tab_4=true\r\nWidgets\\QgsAbout\\tabWidget\\tab_4\\txtDonors=true\r\nWidgets\\QgsAbout\\tabWidget\\tab_4\\txtDonors\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsAbout\\tabWidget\\tab_4\\txtDonors\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsAbout\\tabWidget\\tab_4\\txtDonors\\qt_scrollarea_viewport=true\r\nWidgets\\QgsAbout\\tabWidget\\tab_5=true\r\nWidgets\\QgsAddAttrDialogBase=true\r\nWidgets\\QgsAddAttrDialogBase\\buttonBox=true\r\nWidgets\\QgsAddAttrDialogBase\\mCommentEdit=true\r\nWidgets\\QgsAddAttrDialogBase\\mLength=true\r\nWidgets\\QgsAddAttrDialogBase\\mLength\\qt_spinbox_lineedit=true\r\nWidgets\\QgsAddAttrDialogBase\\mNameEdit=true\r\nWidgets\\QgsAddAttrDialogBase\\mPrec=true\r\nWidgets\\QgsAddAttrDialogBase\\mPrec\\qt_spinbox_lineedit=true\r\nWidgets\\QgsAddAttrDialogBase\\mTypeBox=true\r\nWidgets\\QgsAddAttrDialogBase\\mTypeName=true\r\nWidgets\\QgsAddAttrDialogBase\\textLabel1=true\r\nWidgets\\QgsAddAttrDialogBase\\textLabel1_2=true\r\nWidgets\\QgsAddAttrDialogBase\\textLabel2=true\r\nWidgets\\QgsAddAttrDialogBase\\textLabel2_2=true\r\nWidgets\\QgsAddAttrDialogBase\\textLabel2_3=true\r\nWidgets\\QgsAddJoinDialogBase=true\r\nWidgets\\QgsAddJoinDialogBase\\buttonBox=true\r\nWidgets\\QgsAddJoinDialogBase\\mCacheInMemoryCheckBox=true\r\nWidgets\\QgsAddJoinDialogBase\\mCreateIndexCheckBox=true\r\nWidgets\\QgsAddJoinDialogBase\\mJoinFieldComboBox=true\r\nWidgets\\QgsAddJoinDialogBase\\mJoinFieldLabel=true\r\nWidgets\\QgsAddJoinDialogBase\\mJoinLayerComboBox=true\r\nWidgets\\QgsAddJoinDialogBase\\mJoinLayerLabel=true\r\nWidgets\\QgsAddJoinDialogBase\\mTargetFieldComboBox=true\r\nWidgets\\QgsAddJoinDialogBase\\mTargetFieldLabel=true\r\nWidgets\\QgsAddTabOrGroupBase=true\r\nWidgets\\QgsAddTabOrGroupBase\\buttonBox=true\r\nWidgets\\QgsAddTabOrGroupBase\\label=true\r\nWidgets\\QgsAddTabOrGroupBase\\label_2=true\r\nWidgets\\QgsAddTabOrGroupBase\\mGroupButton=true\r\nWidgets\\QgsAddTabOrGroupBase\\mName=true\r\nWidgets\\QgsAddTabOrGroupBase\\mTabButton=true\r\nWidgets\\QgsAddTabOrGroupBase\\mTabList=true\r\nWidgets\\QgsAnnotationWidgetBase=true\r\nWidgets\\QgsAnnotationWidgetBase\\mBackgroundColorLabel=true\r\nWidgets\\QgsAnnotationWidgetBase\\mFrameColorLabel=true\r\nWidgets\\QgsAnnotationWidgetBase\\mFrameWidthLabel=true\r\nWidgets\\QgsAnnotationWidgetBase\\mMapMarkerButton=true\r\nWidgets\\QgsAnnotationWidgetBase\\mMapMarkerLabel=true\r\nWidgets\\QgsAnnotationWidgetBase\\mMapPositionFixedCheckBox=true\r\nWidgets\\QgsAtlasCompositionWidgetBase=true\r\nWidgets\\QgsAttributeActionDialogBase=true\r\nWidgets\\QgsAttributeLoadValues=true\r\nWidgets\\QgsAttributeLoadValues\\buttonBox=true\r\nWidgets\\QgsAttributeLoadValues\\gridLayoutWidget=true\r\nWidgets\\QgsAttributeLoadValues\\gridLayoutWidget\\keyComboBox=true\r\nWidgets\\QgsAttributeLoadValues\\gridLayoutWidget\\keyLabel=true\r\nWidgets\\QgsAttributeLoadValues\\gridLayoutWidget\\layerComboBox=true\r\nWidgets\\QgsAttributeLoadValues\\gridLayoutWidget\\layerLabel=true\r\nWidgets\\QgsAttributeLoadValues\\gridLayoutWidget\\previewButton=true\r\nWidgets\\QgsAttributeLoadValues\\gridLayoutWidget\\valueComboBox=true\r\nWidgets\\QgsAttributeLoadValues\\gridLayoutWidget\\valueLabel=true\r\nWidgets\\QgsAttributeLoadValues\\gridLayoutWidget\\valueTableLabel=true\r\nWidgets\\QgsAttributeSelectionDialogBase=true\r\nWidgets\\QgsAttributeSelectionDialogBase\\buttonBox=true\r\nWidgets\\QgsAttributeSelectionDialogBase\\mClearButton=true\r\nWidgets\\QgsAttributeSelectionDialogBase\\mSelectAllButton=true\r\nWidgets\\QgsAttributeSelectionDialogBase\\mSortingGroupBox=true\r\nWidgets\\QgsAttributeSelectionDialogBase\\mSortingGroupBox\\mAddPushButton=true\r\nWidgets\\QgsAttributeSelectionDialogBase\\mSortingGroupBox\\mDownPushButton=true\r\nWidgets\\QgsAttributeSelectionDialogBase\\mSortingGroupBox\\mOrderComboBox=true\r\nWidgets\\QgsAttributeSelectionDialogBase\\mSortingGroupBox\\mRemovePushButton=true\r\nWidgets\\QgsAttributeSelectionDialogBase\\mSortingGroupBox\\mSortColumnComboBox=true\r\nWidgets\\QgsAttributeSelectionDialogBase\\mSortingGroupBox\\mUpPushButton=true\r\nWidgets\\QgsAttributeSelectionDialogBase\\scrollArea=true\r\nWidgets\\QgsAttributeSelectionDialogBase\\scrollArea\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsAttributeSelectionDialogBase\\scrollArea\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsAttributeSelectionDialogBase\\scrollArea\\qt_scrollarea_viewport=true\r\nWidgets\\QgsAttributeSelectionDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents=true\r\nWidgets\\QgsAttributeSelectionDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mAliasLabel=true\r\nWidgets\\QgsAttributeSelectionDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mAttributeLabel=true\r\nWidgets\\QgsAttributeTypeDialog=true\r\nWidgets\\QgsAttributeTypeDialog\\buttonBox=true\r\nWidgets\\QgsAttributeTypeDialog\\isFieldEditableCheckBox=true\r\nWidgets\\QgsAttributeTypeDialog\\labelOnTopCheckBox=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\calendarPage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\calendarPage\\label_10=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\calendarPage\\label_11=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\calendarPage\\label_4=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\calendarPage\\leDateFormat=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\checkBoxPage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\checkBoxPage\\label_2=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\checkBoxPage\\label_3=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\checkBoxPage\\leCheckedState=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\checkBoxPage\\leUncheckedState=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\classificationPage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\classificationPage\\classificationLabel=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\colorPage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\colorPage\\label_15=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\enumerationPage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\enumerationPage\\enumerationLabel=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\enumerationPage\\enumerationWarningLabel=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\fileNamePage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\fileNamePage\\fileNameLabel=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\hiddenPage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\hiddenPage\\hiddenLabel=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\immutablePage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\immutablePage\\immutableLabel=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\lineEditPage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\lineEditPage\\lineEditLabel=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\pictureOrUrlPage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\pictureOrUrlPage\\label_12=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\pictureOrUrlPage\\label_13=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\pictureOrUrlPage\\pictureOrUrlLabel=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\pictureOrUrlPage\\sbWidgetHeight=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\pictureOrUrlPage\\sbWidgetHeight\\qt_spinbox_lineedit=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\pictureOrUrlPage\\sbWidgetWidth=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\pictureOrUrlPage\\sbWidgetWidth\\qt_spinbox_lineedit=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\rangePage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\rangePage\\maximumLabel=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\rangePage\\minimumLabel=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\rangePage\\rangeLabel=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\rangePage\\rangeStackedWidget=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\rangePage\\rangeStackedWidget\\doublePage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\rangePage\\rangeStackedWidget\\intPage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\rangePage\\rangeStackedWidget\\intPage\\maximumSpinBox=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\rangePage\\rangeStackedWidget\\intPage\\maximumSpinBox\\qt_spinbox_lineedit=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\rangePage\\rangeStackedWidget\\intPage\\minimumSpinBox=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\rangePage\\rangeStackedWidget\\intPage\\minimumSpinBox\\qt_spinbox_lineedit=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\rangePage\\rangeStackedWidget\\intPage\\stepSpinBox=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\rangePage\\rangeStackedWidget\\intPage\\stepSpinBox\\qt_spinbox_lineedit=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\rangePage\\rangeWidget=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\rangePage\\stepLabel=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\rangePage\\valuesLabel=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\textEditPage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\textEditPage\\hiddenLabel_3=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\uniqueValuesPage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\uniqueValuesPage\\editableUniqueValues=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\uniqueValuesPage\\label=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\uuidGenPage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\uuidGenPage\\label_9=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueMapPage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueMapPage\\loadFromCSVButton=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueMapPage\\loadFromLayerButton=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueMapPage\\removeSelectedButton=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueMapPage\\valueMapLabel=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueRelationPage=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueRelationPage\\label_19=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueRelationPage\\label_5=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueRelationPage\\label_6=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueRelationPage\\label_7=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueRelationPage\\label_8=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueRelationPage\\valueRelationAllowMulti=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueRelationPage\\valueRelationAllowNull=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueRelationPage\\valueRelationFilterExpression=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueRelationPage\\valueRelationFilterExpression\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueRelationPage\\valueRelationFilterExpression\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueRelationPage\\valueRelationFilterExpression\\qt_scrollarea_viewport=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueRelationPage\\valueRelationKeyColumn=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueRelationPage\\valueRelationLayer=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueRelationPage\\valueRelationOrderByValue=true\r\nWidgets\\QgsAttributeTypeDialog\\stackedWidget\\valueRelationPage\\valueRelationValueColumn=true\r\nWidgets\\QgsBookmarksBase=true\r\nWidgets\\QgsBookmarksBase\\buttonBox=true\r\nWidgets\\QgsBrowserDirectoryPropertiesBase=true\r\nWidgets\\QgsBrowserDirectoryPropertiesBase\\buttonBox=true\r\nWidgets\\QgsBrowserDirectoryPropertiesBase\\label_2=true\r\nWidgets\\QgsBrowserDirectoryPropertiesBase\\leSource=true\r\nWidgets\\QgsBrowserDockWidgetBase=true\r\nWidgets\\QgsBrowserDockWidgetBase\\mContents=true\r\nWidgets\\QgsBrowserDockWidgetBase\\mContents\\mWidgetFilter=true\r\nWidgets\\QgsBrowserLayerPropertiesBase=true\r\nWidgets\\QgsBrowserLayerPropertiesBase\\buttonBox=true\r\nWidgets\\QgsBrowserLayerPropertiesBase\\label=true\r\nWidgets\\QgsBrowserLayerPropertiesBase\\label_2=true\r\nWidgets\\QgsBrowserLayerPropertiesBase\\label_3=true\r\nWidgets\\QgsBrowserLayerPropertiesBase\\label_4=true\r\nWidgets\\QgsBrowserLayerPropertiesBase\\lblNotice=true\r\nWidgets\\QgsBrowserLayerPropertiesBase\\leName=true\r\nWidgets\\QgsBrowserLayerPropertiesBase\\leProvider=true\r\nWidgets\\QgsBrowserLayerPropertiesBase\\leSource=true\r\nWidgets\\QgsBrowserLayerPropertiesBase\\txtbMetadata=true\r\nWidgets\\QgsBrowserLayerPropertiesBase\\txtbMetadata\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsBrowserLayerPropertiesBase\\txtbMetadata\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsBrowserLayerPropertiesBase\\txtbMetadata\\qt_scrollarea_viewport=true\r\nWidgets\\QgsCategorizedSymbolRendererV2Widget=true\r\nWidgets\\QgsCategorizedSymbolRendererV2Widget\\btnAddCategories=true\r\nWidgets\\QgsCategorizedSymbolRendererV2Widget\\btnAddCategory=true\r\nWidgets\\QgsCategorizedSymbolRendererV2Widget\\btnAdvanced=true\r\nWidgets\\QgsCategorizedSymbolRendererV2Widget\\btnChangeCategorizedSymbol=true\r\nWidgets\\QgsCategorizedSymbolRendererV2Widget\\btnDeleteAllCategories=true\r\nWidgets\\QgsCategorizedSymbolRendererV2Widget\\btnDeleteCategories=true\r\nWidgets\\QgsCategorizedSymbolRendererV2Widget\\btnJoinCategories=true\r\nWidgets\\QgsCategorizedSymbolRendererV2Widget\\cboCategorizedColumn=true\r\nWidgets\\QgsCategorizedSymbolRendererV2Widget\\label_10=true\r\nWidgets\\QgsCategorizedSymbolRendererV2Widget\\label_3=true\r\nWidgets\\QgsCategorizedSymbolRendererV2Widget\\label_9=true\r\nWidgets\\QgsCharacterSelectorBase=true\r\nWidgets\\QgsCharacterSelectorBase\\mCharSelectButtonBox=true\r\nWidgets\\QgsCharacterSelectorBase\\mCharSelectLabel=true\r\nWidgets\\QgsCharacterSelectorBase\\mCharSelectLabelFont=true\r\nWidgets\\QgsCharacterSelectorBase\\mCharSelectScrollArea=true\r\nWidgets\\QgsCharacterSelectorBase\\mCharSelectScrollArea\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsCharacterSelectorBase\\mCharSelectScrollArea\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsCharacterSelectorBase\\mCharSelectScrollArea\\qt_scrollarea_viewport=true\r\nWidgets\\QgsCharacterSelectorBase\\mCharSelectScrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents=true\r\nWidgets\\QgsComposerArrowWidgetBase=true\r\nWidgets\\QgsComposerArrowWidgetBase\\label_3=true\r\nWidgets\\QgsComposerArrowWidgetBase\\scrollArea=true\r\nWidgets\\QgsComposerArrowWidgetBase\\scrollArea\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsComposerArrowWidgetBase\\scrollArea\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsComposerArrowWidgetBase\\scrollArea\\qt_scrollarea_viewport=true\r\nWidgets\\QgsComposerArrowWidgetBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents=true\r\nWidgets\\QgsComposerBase=true\r\nWidgets\\QgsComposerBase\\centralwidget=true\r\nWidgets\\QgsComposerBase\\centralwidget\\mButtonBox=true\r\nWidgets\\QgsComposerHtmlWidgetBase=true\r\nWidgets\\QgsComposerHtmlWidgetBase\\label=true\r\nWidgets\\QgsComposerHtmlWidgetBase\\scrollArea=true\r\nWidgets\\QgsComposerHtmlWidgetBase\\scrollArea\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsComposerHtmlWidgetBase\\scrollArea\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsComposerHtmlWidgetBase\\scrollArea\\qt_scrollarea_viewport=true\r\nWidgets\\QgsComposerHtmlWidgetBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents=true\r\nWidgets\\QgsComposerItemWidgetBase=true\r\nWidgets\\QgsComposerLabelWidgetBase=true\r\nWidgets\\QgsComposerLabelWidgetBase\\label=true\r\nWidgets\\QgsComposerLabelWidgetBase\\scrollArea=true\r\nWidgets\\QgsComposerLabelWidgetBase\\scrollArea\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsComposerLabelWidgetBase\\scrollArea\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsComposerLabelWidgetBase\\scrollArea\\qt_scrollarea_viewport=true\r\nWidgets\\QgsComposerLabelWidgetBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents=true\r\nWidgets\\QgsComposerLegendItemDialogBase=true\r\nWidgets\\QgsComposerLegendItemDialogBase\\buttonBox=true\r\nWidgets\\QgsComposerLegendItemDialogBase\\mItemTextLabel=true\r\nWidgets\\QgsComposerLegendItemDialogBase\\mItemTextLineEdit=true\r\nWidgets\\QgsComposerLegendLayersDialogBase=true\r\nWidgets\\QgsComposerLegendLayersDialogBase\\buttonBox=true\r\nWidgets\\QgsComposerLegendWidgetBase=true\r\nWidgets\\QgsComposerLegendWidgetBase\\label_11=true\r\nWidgets\\QgsComposerLegendWidgetBase\\scrollArea=true\r\nWidgets\\QgsComposerLegendWidgetBase\\scrollArea\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsComposerLegendWidgetBase\\scrollArea\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsComposerLegendWidgetBase\\scrollArea\\qt_scrollarea_viewport=true\r\nWidgets\\QgsComposerLegendWidgetBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents=true\r\nWidgets\\QgsComposerManagerBase=true\r\nWidgets\\QgsComposerManagerBase\\mButtonBox=true\r\nWidgets\\QgsComposerMapWidgetBase=true\r\nWidgets\\QgsComposerMapWidgetBase\\label_3=true\r\nWidgets\\QgsComposerMapWidgetBase\\scrollArea=true\r\nWidgets\\QgsComposerMapWidgetBase\\scrollArea\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsComposerMapWidgetBase\\scrollArea\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsComposerMapWidgetBase\\scrollArea\\qt_scrollarea_viewport=true\r\nWidgets\\QgsComposerMapWidgetBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents=true\r\nWidgets\\QgsComposerPictureWidgetBase=true\r\nWidgets\\QgsComposerPictureWidgetBase\\label_2=true\r\nWidgets\\QgsComposerPictureWidgetBase\\scrollArea=true\r\nWidgets\\QgsComposerPictureWidgetBase\\scrollArea\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsComposerPictureWidgetBase\\scrollArea\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsComposerPictureWidgetBase\\scrollArea\\qt_scrollarea_viewport=true\r\nWidgets\\QgsComposerPictureWidgetBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents=true\r\nWidgets\\QgsComposerScaleBarWidgetBase=true\r\nWidgets\\QgsComposerScaleBarWidgetBase\\label_5=true\r\nWidgets\\QgsComposerScaleBarWidgetBase\\scrollArea=true\r\nWidgets\\QgsComposerScaleBarWidgetBase\\scrollArea\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsComposerScaleBarWidgetBase\\scrollArea\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsComposerScaleBarWidgetBase\\scrollArea\\qt_scrollarea_viewport=true\r\nWidgets\\QgsComposerScaleBarWidgetBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents=true\r\nWidgets\\QgsComposerShapeWidgetBase=true\r\nWidgets\\QgsComposerShapeWidgetBase\\label_2=true\r\nWidgets\\QgsComposerShapeWidgetBase\\scrollArea=true\r\nWidgets\\QgsComposerShapeWidgetBase\\scrollArea\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsComposerShapeWidgetBase\\scrollArea\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsComposerShapeWidgetBase\\scrollArea\\qt_scrollarea_viewport=true\r\nWidgets\\QgsComposerShapeWidgetBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents=true\r\nWidgets\\QgsComposerTableWidgetBase=true\r\nWidgets\\QgsComposerTableWidgetBase\\label=true\r\nWidgets\\QgsComposerTableWidgetBase\\scrollArea=true\r\nWidgets\\QgsComposerTableWidgetBase\\scrollArea\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsComposerTableWidgetBase\\scrollArea\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsComposerTableWidgetBase\\scrollArea\\qt_scrollarea_viewport=true\r\nWidgets\\QgsComposerTableWidgetBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents=true\r\nWidgets\\QgsComposerVectorLegendBase=true\r\nWidgets\\QgsComposerVectorLegendBase\\mFontButton=true\r\nWidgets\\QgsComposerVectorLegendBase\\mFrameCheckBox=true\r\nWidgets\\QgsComposerVectorLegendBase\\mMapComboBox=true\r\nWidgets\\QgsComposerVectorLegendBase\\mPreviewModeComboBox=true\r\nWidgets\\QgsComposerVectorLegendBase\\mTitleLineEdit=true\r\nWidgets\\QgsComposerVectorLegendBase\\textLabel1=true\r\nWidgets\\QgsComposerVectorLegendBase\\textLabel1_2=true\r\nWidgets\\QgsComposerVectorLegendBase\\textLabel1_5=true\r\nWidgets\\QgsCompositionBase=true\r\nWidgets\\QgsCompositionBase\\groupBox=true\r\nWidgets\\QgsCompositionBase\\groupBox\\mPaperHeightLineEdit=true\r\nWidgets\\QgsCompositionBase\\groupBox\\mPaperOrientationComboBox=true\r\nWidgets\\QgsCompositionBase\\groupBox\\mPaperSizeComboBox=true\r\nWidgets\\QgsCompositionBase\\groupBox\\mPaperUnitsComboBox=true\r\nWidgets\\QgsCompositionBase\\groupBox\\mPaperWidthLineEdit=true\r\nWidgets\\QgsCompositionBase\\groupBox\\textLabel3=true\r\nWidgets\\QgsCompositionBase\\groupBox\\textLabel4=true\r\nWidgets\\QgsCompositionBase\\groupBox\\textLabel5=true\r\nWidgets\\QgsCompositionBase\\groupBox\\textLabel6=true\r\nWidgets\\QgsCompositionBase\\groupBox\\textLabel7=true\r\nWidgets\\QgsCompositionWidgetBase=true\r\nWidgets\\QgsCompositionWidgetBase\\scrollArea=true\r\nWidgets\\QgsCompositionWidgetBase\\scrollArea\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsCompositionWidgetBase\\scrollArea\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsCompositionWidgetBase\\scrollArea\\qt_scrollarea_viewport=true\r\nWidgets\\QgsCompositionWidgetBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents=true\r\nWidgets\\QgsConfigureShortcutsDialog=true\r\nWidgets\\QgsConfigureShortcutsDialog\\btnChangeShortcut=true\r\nWidgets\\QgsConfigureShortcutsDialog\\btnLoadShortcuts=true\r\nWidgets\\QgsConfigureShortcutsDialog\\btnResetShortcut=true\r\nWidgets\\QgsConfigureShortcutsDialog\\btnSaveShortcuts=true\r\nWidgets\\QgsConfigureShortcutsDialog\\btnSetNoShortcut=true\r\nWidgets\\QgsConfigureShortcutsDialog\\buttonBox=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\buttonBox=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\cboConvertStandard=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab\\cboVariantName=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab\\label=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab\\label_2=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab\\label_6=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab\\lblLicensePreview=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab\\lblPreview=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab\\lblSchemeName=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab\\lblSchemePath=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab_2=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab_2\\label_3=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab_2\\label_4=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab_2\\label_5=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab_2\\lblAuthorName=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab_2\\lblLicenseName=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab_2\\lblLicenseName\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab_2\\lblLicenseName\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab_2\\lblLicenseName\\qt_scrollarea_viewport=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page\\tabWidget\\tab_2\\lblSrcLink=true\r\nWidgets\\QgsCptCityColorRampV2DialogBase\\mStackedWidget\\page_2=true\r\nWidgets\\QgsCredentialDialog=true\r\nWidgets\\QgsCredentialDialog\\buttonBox=true\r\nWidgets\\QgsCredentialDialog\\label=true\r\nWidgets\\QgsCredentialDialog\\labelMessage=true\r\nWidgets\\QgsCredentialDialog\\labelRealm=true\r\nWidgets\\QgsCredentialDialog\\label_2=true\r\nWidgets\\QgsCredentialDialog\\label_3=true\r\nWidgets\\QgsCredentialDialog\\lePassword=true\r\nWidgets\\QgsCredentialDialog\\leUsername=true\r\nWidgets\\QgsCustomProjectionDialogBase=true\r\nWidgets\\QgsCustomProjectionDialogBase\\buttonBox=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox\\label=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox\\label_3=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox\\label_4=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox\\leName=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox\\pbnAdd=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox\\pbnCopyCRS=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox\\pbnRemove=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox_2=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox_2\\eastWGS84=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox_2\\label_2=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox_2\\northWGS84=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox_2\\pbnCalculate=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox_2\\projectedX=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox_2\\projectedY=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox_2\\textLabel1_3=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox_2\\textLabel2_2=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox_2\\textLabel2_2_2=true\r\nWidgets\\QgsCustomProjectionDialogBase\\groupBox_2\\textLabel2_3=true\r\nWidgets\\QgsCustomizationDialogBase=true\r\nWidgets\\QgsCustomizationDialogBase\\centralwidget=true\r\nWidgets\\QgsCustomizationDialogBase\\centralwidget\\buttonBox=true\r\nWidgets\\QgsCustomizationDialogBase\\centralwidget\\mCustomizationEnabledCheckBox=true\r\nWidgets\\QgsDataDefinedSymbolDialog=true\r\nWidgets\\QgsDataDefinedSymbolDialog\\mButtonBox=true\r\nWidgets\\QgsDbSourceSelectBase=true\r\nWidgets\\QgsDbSourceSelectBase\\buttonBox=true\r\nWidgets\\QgsDbSourceSelectBase\\cbxAllowGeometrylessTables=true\r\nWidgets\\QgsDbSourceSelectBase\\connectionsGroupBox=true\r\nWidgets\\QgsDbSourceSelectBase\\connectionsGroupBox\\btnConnect=true\r\nWidgets\\QgsDbSourceSelectBase\\connectionsGroupBox\\btnDelete=true\r\nWidgets\\QgsDbSourceSelectBase\\connectionsGroupBox\\btnEdit=true\r\nWidgets\\QgsDbSourceSelectBase\\connectionsGroupBox\\btnLoad=true\r\nWidgets\\QgsDbSourceSelectBase\\connectionsGroupBox\\btnNew=true\r\nWidgets\\QgsDbSourceSelectBase\\connectionsGroupBox\\btnSave=true\r\nWidgets\\QgsDbSourceSelectBase\\connectionsGroupBox\\cmbConnections=true\r\nWidgets\\QgsDbSourceSelectBase\\mSearchGroupBox=true\r\nWidgets\\QgsDbSourceSelectBase\\mSearchGroupBox\\mSearchColumnComboBox=true\r\nWidgets\\QgsDbSourceSelectBase\\mSearchGroupBox\\mSearchColumnsLabel=true\r\nWidgets\\QgsDbSourceSelectBase\\mSearchGroupBox\\mSearchLabel=true\r\nWidgets\\QgsDbSourceSelectBase\\mSearchGroupBox\\mSearchModeComboBox=true\r\nWidgets\\QgsDbSourceSelectBase\\mSearchGroupBox\\mSearchModeLabel=true\r\nWidgets\\QgsDbSourceSelectBase\\mSearchGroupBox\\mSearchTableEdit=true\r\nWidgets\\QgsDecorationCopyrightDialog=true\r\nWidgets\\QgsDecorationCopyrightDialog\\buttonBox=true\r\nWidgets\\QgsDecorationCopyrightDialog\\cboOrientation=true\r\nWidgets\\QgsDecorationCopyrightDialog\\cboPlacement=true\r\nWidgets\\QgsDecorationCopyrightDialog\\cboxEnabled=true\r\nWidgets\\QgsDecorationCopyrightDialog\\label=true\r\nWidgets\\QgsDecorationCopyrightDialog\\label_2=true\r\nWidgets\\QgsDecorationCopyrightDialog\\textLabel15=true\r\nWidgets\\QgsDecorationCopyrightDialog\\textLabel16=true\r\nWidgets\\QgsDecorationCopyrightDialog\\txtCopyrightText=true\r\nWidgets\\QgsDecorationCopyrightDialog\\txtCopyrightText\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsDecorationCopyrightDialog\\txtCopyrightText\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsDecorationCopyrightDialog\\txtCopyrightText\\qt_scrollarea_viewport=true\r\nWidgets\\QgsDecorationGridDialog=true\r\nWidgets\\QgsDecorationGridDialog\\buttonBox=true\r\nWidgets\\QgsDecorationGridDialog\\chkEnable=true\r\nWidgets\\QgsDecorationGridDialog\\groupBox=true\r\nWidgets\\QgsDecorationGridDialog\\groupBox\\mPbtnUpdateFromExtents=true\r\nWidgets\\QgsDecorationGridDialog\\groupBox\\mPbtnUpdateFromLayer=true\r\nWidgets\\QgsDecorationGridDialog\\mDrawAnnotationCheckBox=true\r\nWidgets\\QgsDecorationGridDialog\\mDrawAnnotationCheckBox\\mAnnotationDirectionComboBox=true\r\nWidgets\\QgsDecorationGridDialog\\mDrawAnnotationCheckBox\\mAnnotationDirectionLabel=true\r\nWidgets\\QgsDecorationGridDialog\\mDrawAnnotationCheckBox\\mAnnotationFontButton=true\r\nWidgets\\QgsDecorationGridDialog\\mDrawAnnotationCheckBox\\mCoordinatePrecisionLabel=true\r\nWidgets\\QgsDecorationGridDialog\\mDrawAnnotationCheckBox\\mCoordinatePrecisionSpinBox=true\r\nWidgets\\QgsDecorationGridDialog\\mDrawAnnotationCheckBox\\mCoordinatePrecisionSpinBox\\qt_spinbox_lineedit=true\r\nWidgets\\QgsDecorationGridDialog\\mDrawAnnotationCheckBox\\mDistanceToFrameLabel=true\r\nWidgets\\QgsDecorationGridDialog\\mGridTypeComboBox=true\r\nWidgets\\QgsDecorationGridDialog\\mGridTypeLabel=true\r\nWidgets\\QgsDecorationGridDialog\\mIntervalXEdit=true\r\nWidgets\\QgsDecorationGridDialog\\mIntervalXLabel=true\r\nWidgets\\QgsDecorationGridDialog\\mIntervalYEdit=true\r\nWidgets\\QgsDecorationGridDialog\\mIntervalYLabel=true\r\nWidgets\\QgsDecorationGridDialog\\mLineSymbolButton=true\r\nWidgets\\QgsDecorationGridDialog\\mLineSymbolLabel=true\r\nWidgets\\QgsDecorationGridDialog\\mMarkerSymbolButton=true\r\nWidgets\\QgsDecorationGridDialog\\mMarkerSymbolLabel=true\r\nWidgets\\QgsDecorationGridDialog\\mOffsetXEdit=true\r\nWidgets\\QgsDecorationGridDialog\\mOffsetXLabel=true\r\nWidgets\\QgsDecorationGridDialog\\mOffsetYEdit=true\r\nWidgets\\QgsDecorationGridDialog\\mOffsetYLabel=true\r\nWidgets\\QgsDecorationNorthArrowDialog=true\r\nWidgets\\QgsDecorationNorthArrowDialog\\buttonBox=true\r\nWidgets\\QgsDecorationScaleBarDialog=true\r\nWidgets\\QgsDecorationScaleBarDialog\\buttonBox=true\r\nWidgets\\QgsDecorationScaleBarDialog\\cboPlacement=true\r\nWidgets\\QgsDecorationScaleBarDialog\\cboStyle=true\r\nWidgets\\QgsDecorationScaleBarDialog\\chkEnable=true\r\nWidgets\\QgsDecorationScaleBarDialog\\chkSnapping=true\r\nWidgets\\QgsDecorationScaleBarDialog\\spnSize=true\r\nWidgets\\QgsDecorationScaleBarDialog\\spnSize\\qt_spinbox_lineedit=true\r\nWidgets\\QgsDecorationScaleBarDialog\\textLabel1=true\r\nWidgets\\QgsDecorationScaleBarDialog\\textLabel1_2=true\r\nWidgets\\QgsDecorationScaleBarDialog\\textLabel1_3=true\r\nWidgets\\QgsDecorationScaleBarDialog\\textLabel1_3_2=true\r\nWidgets\\QgsDelAttrDialogBase=true\r\nWidgets\\QgsDelAttrDialogBase\\buttonBox=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\buttonBox=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\cbxPointIsComma=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\cbxSkipEmptyFields=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\cbxSpatialIndex=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\cbxSubsetIndex=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\cbxTrimFields=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\cbxUseHeader=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\cbxWatchFile=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\delimiterCSV=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\delimiterChars=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\delimiterRegexp=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\geomTypeNone=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\geomTypeWKT=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\geomTypeXY=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\labelFileFormat=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\label_2=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\label_3=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\label_4=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\label_6=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\label_8=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\lblStatus=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\rowCounter=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\rowCounter\\qt_spinbox_lineedit=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swFileFormat=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swFileFormat\\swpCSVOptions=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swFileFormat\\swpDelimOptions=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swFileFormat\\swpRegexpOptions=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swFileFormat\\swpRegexpOptions\\label_7=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swFileFormat\\swpRegexpOptions\\lblRegexpError=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swFileFormat\\swpRegexpOptions\\txtDelimiterRegexp=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swGeomType=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swGeomType\\swpGeomNone=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swGeomType\\swpGeomWKT=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swGeomType\\swpGeomWKT\\cmbGeometryType=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swGeomType\\swpGeomWKT\\cmbWktField=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swGeomType\\swpGeomWKT\\label=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swGeomType\\swpGeomWKT\\label_5=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swGeomType\\swpGeomXY=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swGeomType\\swpGeomXY\\cbxXyDms=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swGeomType\\swpGeomXY\\cmbXField=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swGeomType\\swpGeomXY\\cmbYField=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swGeomType\\swpGeomXY\\textLabelx=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\swGeomType\\swpGeomXY\\textLabely=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\widget_3=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\widget_3\\btnBrowseForFile=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\widget_3\\cmbEncoding=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\widget_3\\lblEncoding=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\widget_3\\textLabelFileName=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\widget_3\\textLabelLayerName=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\widget_3\\txtFilePath=true\r\nWidgets\\QgsDelimitedTextSourceSelectBase\\widget_3\\txtLayerName=true\r\nWidgets\\QgsDetailedItemWidgetBase=true\r\nWidgets\\QgsDetailedItemWidgetBase\\cbx=true\r\nWidgets\\QgsDetailedItemWidgetBase\\lblCategory=true\r\nWidgets\\QgsDetailedItemWidgetBase\\lblDetail=true\r\nWidgets\\QgsDetailedItemWidgetBase\\lblIcon=true\r\nWidgets\\QgsDetailedItemWidgetBase\\lblTitle=true\r\nWidgets\\QgsDetailedItemWidgetBase\\widget=true\r\nWidgets\\QgsDisplayAngleBase=true\r\nWidgets\\QgsDisplayAngleBase\\buttonBox=true\r\nWidgets\\QgsDisplayAngleBase\\mAngleLineEdit=true\r\nWidgets\\QgsEngineConfigDialog=true\r\nWidgets\\QgsEngineConfigDialog\\buttonBox=true\r\nWidgets\\QgsEngineConfigDialog\\cboSearchMethod=true\r\nWidgets\\QgsEngineConfigDialog\\chkShowAllLabels=true\r\nWidgets\\QgsEngineConfigDialog\\chkShowCandidates=true\r\nWidgets\\QgsEngineConfigDialog\\groupBox=true\r\nWidgets\\QgsEngineConfigDialog\\groupBox\\label_2=true\r\nWidgets\\QgsEngineConfigDialog\\groupBox\\label_3=true\r\nWidgets\\QgsEngineConfigDialog\\groupBox\\label_4=true\r\nWidgets\\QgsEngineConfigDialog\\groupBox\\spinCandLine=true\r\nWidgets\\QgsEngineConfigDialog\\groupBox\\spinCandLine\\qt_spinbox_lineedit=true\r\nWidgets\\QgsEngineConfigDialog\\groupBox\\spinCandPoint=true\r\nWidgets\\QgsEngineConfigDialog\\groupBox\\spinCandPoint\\qt_spinbox_lineedit=true\r\nWidgets\\QgsEngineConfigDialog\\groupBox\\spinCandPolygon=true\r\nWidgets\\QgsEngineConfigDialog\\groupBox\\spinCandPolygon\\qt_spinbox_lineedit=true\r\nWidgets\\QgsEngineConfigDialog\\label=true\r\nWidgets\\QgsEngineConfigDialog\\label_6=true\r\nWidgets\\QgsEngineConfigDialog\\mSaveWithProjectChkBox=true\r\nWidgets\\QgsEngineConfigDialog\\mShadowDebugRectChkBox=true\r\nWidgets\\QgsErrorDialogBase=true\r\nWidgets\\QgsErrorDialogBase\\buttonBox=true\r\nWidgets\\QgsErrorDialogBase\\mDetailCheckBox=true\r\nWidgets\\QgsErrorDialogBase\\mDetailPushButton=true\r\nWidgets\\QgsErrorDialogBase\\mDetailTextBrowser=true\r\nWidgets\\QgsErrorDialogBase\\mDetailTextBrowser\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsErrorDialogBase\\mDetailTextBrowser\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsErrorDialogBase\\mDetailTextBrowser\\qt_scrollarea_viewport=true\r\nWidgets\\QgsErrorDialogBase\\mIconLabel=true\r\nWidgets\\QgsErrorDialogBase\\mSummaryTextBrowser=true\r\nWidgets\\QgsErrorDialogBase\\mSummaryTextBrowser\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsErrorDialogBase\\mSummaryTextBrowser\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsErrorDialogBase\\mSummaryTextBrowser\\qt_scrollarea_viewport=true\r\nWidgets\\QgsExpressionBuilderDialogBase=true\r\nWidgets\\QgsExpressionBuilderDialogBase\\buttonBox=true\r\nWidgets\\QgsExpressionBuilderWidgetBase=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\btnLoadAll=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\btnLoadSample=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\groupBox=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\groupBox\\txtExpressionString=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\groupBox\\txtExpressionString\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\groupBox\\txtExpressionString\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\groupBox\\txtExpressionString\\qt_scrollarea_viewport=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\label_2=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\lblPreview=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\mFunctionHelGroup=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\mFunctionHelGroup\\txtHelpText=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\mFunctionHelGroup\\txtHelpText\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\mFunctionHelGroup\\txtHelpText\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\mFunctionHelGroup\\txtHelpText\\qt_scrollarea_viewport=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\mOperatorsGroupBox=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\mOperatorsGroupBox\\btnCloseBracketPushButton=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\mOperatorsGroupBox\\btnConcatButton=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\mOperatorsGroupBox\\btnDividePushButton=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\mOperatorsGroupBox\\btnEqualPushButton=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\mOperatorsGroupBox\\btnExpButton=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\mOperatorsGroupBox\\btnMinusPushButton=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\mOperatorsGroupBox\\btnMultiplyPushButton=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\mOperatorsGroupBox\\btnOpenBracketPushButton=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\mOperatorsGroupBox\\btnPlusPushButton=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\mValueGroupBox=true\r\nWidgets\\QgsExpressionBuilderWidgetBase\\moperationListGroup=true\r\nWidgets\\QgsExpressionSelectionDialogBase=true\r\nWidgets\\QgsExpressionSelectionDialogBase\\mPbnClose=true\r\nWidgets\\QgsFieldCalculatorBase=true\r\nWidgets\\QgsFieldCalculatorBase\\mButtonBox=true\r\nWidgets\\QgsFieldCalculatorBase\\mNewFieldGroupBox=true\r\nWidgets\\QgsFieldCalculatorBase\\mNewFieldGroupBox\\mFieldNameLabel=true\r\nWidgets\\QgsFieldCalculatorBase\\mNewFieldGroupBox\\mOutputFieldNameLineEdit=true\r\nWidgets\\QgsFieldCalculatorBase\\mNewFieldGroupBox\\mOutputFieldPrecisionLabel=true\r\nWidgets\\QgsFieldCalculatorBase\\mNewFieldGroupBox\\mOutputFieldPrecisionSpinBox=true\r\nWidgets\\QgsFieldCalculatorBase\\mNewFieldGroupBox\\mOutputFieldPrecisionSpinBox\\qt_spinbox_lineedit=true\r\nWidgets\\QgsFieldCalculatorBase\\mNewFieldGroupBox\\mOutputFieldTypeComboBox=true\r\nWidgets\\QgsFieldCalculatorBase\\mNewFieldGroupBox\\mOutputFieldTypeLabel=true\r\nWidgets\\QgsFieldCalculatorBase\\mNewFieldGroupBox\\mOutputFieldWidthLabel=true\r\nWidgets\\QgsFieldCalculatorBase\\mNewFieldGroupBox\\mOutputFieldWidthSpinBox=true\r\nWidgets\\QgsFieldCalculatorBase\\mNewFieldGroupBox\\mOutputFieldWidthSpinBox\\qt_spinbox_lineedit=true\r\nWidgets\\QgsFieldCalculatorBase\\mOnlyUpdateSelectedCheckBox=true\r\nWidgets\\QgsFieldCalculatorBase\\mUpdateExistingGroupBox=true\r\nWidgets\\QgsFieldCalculatorBase\\mUpdateExistingGroupBox\\mExistingFieldComboBox=true\r\nWidgets\\QgsFieldsPropertiesBase=true\r\nWidgets\\QgsFieldsPropertiesBase\\label_2=true\r\nWidgets\\QgsFieldsPropertiesBase\\label_3=true\r\nWidgets\\QgsFieldsPropertiesBase\\leEditFormInit=true\r\nWidgets\\QgsFieldsPropertiesBase\\mEditorLayoutComboBox=true\r\nWidgets\\QgsFormAnnotationDialogBase=true\r\nWidgets\\QgsFormAnnotationDialogBase\\mButtonBox=true\r\nWidgets\\QgsFormAnnotationDialogBase\\mFileLineEdit=true\r\nWidgets\\QgsFormAnnotationDialogBase\\mStackedWidget=true\r\nWidgets\\QgsFormAnnotationDialogBase\\mStackedWidget\\page=true\r\nWidgets\\QgsFormAnnotationDialogBase\\mStackedWidget\\page_2=true\r\nWidgets\\QgsGPSInformationWidgetBase=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mBtnAddVertex=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mBtnCloseFeature=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mConnectButton=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mLblStatusIndicator=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mLblAltitude=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mLblDirection=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mLblFixMode=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mLblFixType=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mLblHacc=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mLblHdop=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mLblLatitude=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mLblLongitude=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mLblPdop=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mLblQuality=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mLblSatellitesUsed=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mLblSpeed=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mLblStatus=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mLblUtcTime=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mLblVacc=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mLblVdop=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mTxtAltitude=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mTxtDateTime=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mTxtDirection=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mTxtFixMode=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mTxtFixType=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mTxtHacc=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mTxtHdop=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mTxtLatitude=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mTxtLongitude=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mTxtPdop=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mTxtQuality=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mTxtSatellitesUsed=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mTxtSpeed=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mTxtStatus=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mTxtVacc=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage1\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\mTxtVdop=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage2=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage3=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox\\mSpinMapExtentMultiplier=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox\\mSpinMapExtentMultiplier\\qt_spinbox_lineedit=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox\\radNeverRecenter=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox\\radRecenterMap=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox\\radRecenterWhenNeeded=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2\\groupBox_3=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2\\groupBox_3\\mBtnTrackColor=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2\\groupBox_3\\mCbxAutoAddVertices=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2\\groupBox_3\\mSpinTrackWidth=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2\\groupBox_3\\mSpinTrackWidth\\qt_spinbox_lineedit=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2\\mCbxAutoCommit=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mDeviceGroupBox=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mDeviceGroupBox\\label_3=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mDeviceGroupBox\\label_4=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mDeviceGroupBox\\label_5=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mDeviceGroupBox\\mCboDevices=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mDeviceGroupBox\\mGpsdDevice=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mDeviceGroupBox\\mGpsdHost=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mDeviceGroupBox\\mGpsdPort=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mDeviceGroupBox\\mRadAutodetect=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mDeviceGroupBox\\mRadGpsd=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mDeviceGroupBox\\mRadInternal=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mDeviceGroupBox\\mRadUserPath=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mGroupShowMarker=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mGroupShowMarker\\label=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mGroupShowMarker\\label_2=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mGroupShowMarker\\mSliderMarkerSize=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mLogFileGroupBox=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mLogFileGroupBox\\mBtnLogFile=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage4\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mLogFileGroupBox\\mTxtLogFile=true\r\nWidgets\\QgsGPSInformationWidgetBase\\mStackedWidget\\stackedWidgetPage5=true\r\nWidgets\\QgsGenericProjectionSelectorBase=true\r\nWidgets\\QgsGenericProjectionSelectorBase\\buttonBox=true\r\nWidgets\\QgsGenericProjectionSelectorBase\\textEdit=true\r\nWidgets\\QgsGenericProjectionSelectorBase\\textEdit\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsGenericProjectionSelectorBase\\textEdit\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsGenericProjectionSelectorBase\\textEdit\\qt_scrollarea_viewport=true\r\nWidgets\\QgsGraduatedSymbolRendererV2Widget=true\r\nWidgets\\QgsGraduatedSymbolRendererV2Widget\\btnAdvanced=true\r\nWidgets\\QgsGraduatedSymbolRendererV2Widget\\btnChangeGraduatedSymbol=true\r\nWidgets\\QgsGraduatedSymbolRendererV2Widget\\btnDeleteAllClasses=true\r\nWidgets\\QgsGraduatedSymbolRendererV2Widget\\btnGraduatedAdd=true\r\nWidgets\\QgsGraduatedSymbolRendererV2Widget\\btnGraduatedClassify=true\r\nWidgets\\QgsGraduatedSymbolRendererV2Widget\\btnGraduatedDelete=true\r\nWidgets\\QgsGraduatedSymbolRendererV2Widget\\cboGraduatedColumn=true\r\nWidgets\\QgsGraduatedSymbolRendererV2Widget\\cboGraduatedMode=true\r\nWidgets\\QgsGraduatedSymbolRendererV2Widget\\label_4=true\r\nWidgets\\QgsGraduatedSymbolRendererV2Widget\\label_5=true\r\nWidgets\\QgsGraduatedSymbolRendererV2Widget\\label_6=true\r\nWidgets\\QgsGraduatedSymbolRendererV2Widget\\label_7=true\r\nWidgets\\QgsGraduatedSymbolRendererV2Widget\\label_8=true\r\nWidgets\\QgsGraduatedSymbolRendererV2Widget\\spinGraduatedClasses=true\r\nWidgets\\QgsGraduatedSymbolRendererV2Widget\\spinGraduatedClasses\\qt_spinbox_lineedit=true\r\nWidgets\\QgsHandleBadLayersBase=true\r\nWidgets\\QgsHandleBadLayersBase\\buttonBox=true\r\nWidgets\\QgsIdentifyResultsBase=true\r\nWidgets\\QgsIdentifyResultsBase\\buttonBox=true\r\nWidgets\\QgsLUDialogBase=true\r\nWidgets\\QgsLUDialogBase\\buttonBox=true\r\nWidgets\\QgsLUDialogBase\\mLowerEdit=true\r\nWidgets\\QgsLUDialogBase\\mLowerLabel=true\r\nWidgets\\QgsLUDialogBase\\mUpperEdit=true\r\nWidgets\\QgsLUDialogBase\\mUpperLabel=true\r\nWidgets\\QgsLabelDialogBase=true\r\nWidgets\\QgsLabelDialogBase\\groupBox5=true\r\nWidgets\\QgsLabelDialogBase\\groupBox5\\lblSample=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\buttonGroup10=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\buttonGroup10\\cboOffsetUnits=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\chkUseBuffer=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\chkUseBuffer\\cboBufferSizeUnits=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\chkUseBuffer\\pbnDefaultBufferColor=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\chkUseBuffer\\spinBufferTransparency=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\chkUseBuffer\\spinBufferTransparency\\qt_spinbox_lineedit=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\chkUseBuffer\\textLabel4_3_2_2=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\chkUseScaleDependentRendering=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\chkUseScaleDependentRendering\\leMaximumScale=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\chkUseScaleDependentRendering\\leMinimumScale=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\chkUseScaleDependentRendering\\textLabel1_1=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\chkUseScaleDependentRendering\\textLabel1_2_2_1=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2\\radioAbove=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2\\radioAboveLeft=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2\\radioAboveRight=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2\\radioBelow=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2\\radioBelowLeft=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2\\radioBelowRight=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2\\radioLeft=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2\\radioOver=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2\\radioRight=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_8=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_8\\btnDefaultFont=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_8\\cboFontSizeUnits=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_8\\cboLabelField=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_8\\chkSelectedOnly=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_8\\chkUseMultiline=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_8\\leDefaultLabel=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_8\\pbnDefaultFontColor=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_8\\spinAngle=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_8\\spinAngle\\qt_spinbox_lineedit=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_8\\textLabel1=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_8\\textLabel1_2_2_2_2_2=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_8\\textLabel5=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_8\\textLabel5_2_2_3_2=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox\\cboBoldField=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox\\cboFontColorField=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox\\cboFontField=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox\\cboFontSizeField=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox\\cboFontSizeTypeField=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox\\cboItalicField=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox\\cboStrikeOutField=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox\\cboUnderlineField=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox\\label=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox\\lblFont=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox\\textLabel4=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox\\textLabel4_2_4=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox\\textLabel4_3=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox\\textLabel4_3_2=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox\\textLabel4_3_2_4=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox\\textLabel4_3_2_5=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_5=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_5\\cboAlignmentField=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_5\\cboAngleField=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_5\\textLabel1_2_2_2_2=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_5\\textLabel1_2_2_2_2_3=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_6=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_6\\cboBufferSizeField=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_6\\cboBufferTransparencyField=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_6\\textLabel1_3_2_2_2=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_6\\textLabel4_3_2_2_2=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_7=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_7\\cboXCoordinateField=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_7\\cboXOffsetField=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_7\\cboYCoordinateField=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_7\\cboYOffsetField=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_7\\textLabel1_2=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_7\\textLabel1_2_2=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_7\\textLabel1_2_2_2=true\r\nWidgets\\QgsLabelDialogBase\\tabWidget\\tab_2\\scrollArea_2\\qt_scrollarea_viewport\\scrollAreaWidgetContents_2\\groupBox_7\\textLabel1_2_3=true\r\nWidgets\\QgsLabelPropertyDialogBase=true\r\nWidgets\\QgsLabelPropertyDialogBase\\buttonBox=true\r\nWidgets\\QgsLabelPropertyDialogBase\\groupBox=true\r\nWidgets\\QgsLabelPropertyDialogBase\\groupBox\\label=true\r\nWidgets\\QgsLabelPropertyDialogBase\\groupBox\\mAlwaysShowChkbx=true\r\nWidgets\\QgsLabelPropertyDialogBase\\groupBox\\mMaxScaleSpinBox=true\r\nWidgets\\QgsLabelPropertyDialogBase\\groupBox\\mMaxScaleSpinBox\\qt_spinbox_lineedit=true\r\nWidgets\\QgsLabelPropertyDialogBase\\groupBox\\mMinScaleSpinBox=true\r\nWidgets\\QgsLabelPropertyDialogBase\\groupBox\\mMinScaleSpinBox\\qt_spinbox_lineedit=true\r\nWidgets\\QgsLabelPropertyDialogBase\\groupBox\\mShowLabelChkbx=true\r\nWidgets\\QgsLabelPropertyDialogBase\\mBufferGroupBox=true\r\nWidgets\\QgsLabelPropertyDialogBase\\mBufferGroupBox\\mBufferSizeLabel=true\r\nWidgets\\QgsLabelPropertyDialogBase\\mFontGroupBox=true\r\nWidgets\\QgsLabelPropertyDialogBase\\mFontGroupBox\\label_3=true\r\nWidgets\\QgsLabelPropertyDialogBase\\mFontGroupBox\\mFontSizeLabel=true\r\nWidgets\\QgsLabelPropertyDialogBase\\mFontGroupBox\\mFontStyleCmbBx=true\r\nWidgets\\QgsLabelPropertyDialogBase\\mLabelTextLabel=true\r\nWidgets\\QgsLabelPropertyDialogBase\\mLabelTextLineEdit=true\r\nWidgets\\QgsLabelPropertyDialogBase\\mPositionGroupBlox=true\r\nWidgets\\QgsLabelPropertyDialogBase\\mPositionGroupBlox\\mHaliComboBox=true\r\nWidgets\\QgsLabelPropertyDialogBase\\mPositionGroupBlox\\mHaliLabel=true\r\nWidgets\\QgsLabelPropertyDialogBase\\mPositionGroupBlox\\mLabelDistanceLabel=true\r\nWidgets\\QgsLabelPropertyDialogBase\\mPositionGroupBlox\\mRotationLabel=true\r\nWidgets\\QgsLabelPropertyDialogBase\\mPositionGroupBlox\\mValiComboBox=true\r\nWidgets\\QgsLabelPropertyDialogBase\\mPositionGroupBlox\\mValiLabel=true\r\nWidgets\\QgsLabelPropertyDialogBase\\mPositionGroupBlox\\mXCoordLabel=true\r\nWidgets\\QgsLabelPropertyDialogBase\\mPositionGroupBlox\\mYCoordLabel=true\r\nWidgets\\QgsLoadStyleFromDBDialogLayout=true\r\nWidgets\\QgsLoadStyleFromDBDialogLayout\\label=true\r\nWidgets\\QgsLoadStyleFromDBDialogLayout\\label_2=true\r\nWidgets\\QgsLoadStyleFromDBDialogLayout\\mCancelButton=true\r\nWidgets\\QgsLoadStyleFromDBDialogLayout\\mLoadButton=true\r\nWidgets\\QgsManageConnectionsDialogBase=true\r\nWidgets\\QgsManageConnectionsDialogBase\\buttonBox=true\r\nWidgets\\QgsManageConnectionsDialogBase\\label=true\r\nWidgets\\QgsMeasureBase=true\r\nWidgets\\QgsMeasureBase\\buttonBox=true\r\nWidgets\\QgsMeasureBase\\editTotal=true\r\nWidgets\\QgsMeasureBase\\textLabel2=true\r\nWidgets\\QgsMergeAttributesDialogBase=true\r\nWidgets\\QgsMergeAttributesDialogBase\\buttonBox=true\r\nWidgets\\QgsMergeAttributesDialogBase\\mFromSelectedPushButton=true\r\nWidgets\\QgsMergeAttributesDialogBase\\mRemoveFeatureFromSelectionButton=true\r\nWidgets\\QgsMergeAttributesDialogBase\\mRemoveFeatureFromSelectionLabel=true\r\nWidgets\\QgsMergeAttributesDialogBase\\mTakeSelectedAttributesLabel=true\r\nWidgets\\QgsMessageLogViewer=true\r\nWidgets\\QgsMessageLogViewer\\tabWidget=true\r\nWidgets\\QgsMessageViewer=true\r\nWidgets\\QgsMessageViewer\\buttonBox=true\r\nWidgets\\QgsMessageViewer\\checkBox=true\r\nWidgets\\QgsMessageViewer\\txtMessage=true\r\nWidgets\\QgsMessageViewer\\txtMessage\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsMessageViewer\\txtMessage\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsMessageViewer\\txtMessage\\qt_scrollarea_viewport=true\r\nWidgets\\QgsMssqlNewConnectionBase=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\TextLabel1=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\TextLabel1_2=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\TextLabel2=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\TextLabel3=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\TextLabel3_2=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\btnConnect=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\cb_allowGeometrylessTables=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\cb_geometryColumns=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\cb_trustedConnection=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\cb_useEstimatedMetadata=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\chkStorePassword=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\chkStoreUsername=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\label=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\label_2=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\txtDatabase=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\txtHost=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\txtName=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\txtPassword=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\txtService=true\r\nWidgets\\QgsMssqlNewConnectionBase\\GroupBox1\\txtUsername=true\r\nWidgets\\QgsMssqlNewConnectionBase\\buttonBox=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase\\label=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase\\label_2=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase\\mBlueBandComboBox=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase\\mBlueBandLabel=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase\\mBlueMaxLineEdit=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase\\mBlueMinLineEdit=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase\\mContrastEnhancementAlgorithmComboBox=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase\\mContrastEnhancementAlgorithmLabel=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase\\mGreenBandComboBox=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase\\mGreenBandLabel=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase\\mGreenMaxLineEdit=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase\\mGreenMinLineEdit=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase\\mMinLabel=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase\\mRedBandComboBox=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase\\mRedBandLabel=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase\\mRedMaxLineEdit=true\r\nWidgets\\QgsMultiBandColorRendererWidgetBase\\mRedMinLineEdit=true\r\nWidgets\\QgsNewHttpConnectionBase=true\r\nWidgets\\QgsNewHttpConnectionBase\\buttonBox=true\r\nWidgets\\QgsNewHttpConnectionBase\\mGroupBox=true\r\nWidgets\\QgsNewHttpConnectionBase\\mGroupBox\\TextLabel1=true\r\nWidgets\\QgsNewHttpConnectionBase\\mGroupBox\\TextLabel1_2=true\r\nWidgets\\QgsNewHttpConnectionBase\\mGroupBox\\cbxIgnoreAxisOrientation=true\r\nWidgets\\QgsNewHttpConnectionBase\\mGroupBox\\cbxIgnoreGetFeatureInfoURI=true\r\nWidgets\\QgsNewHttpConnectionBase\\mGroupBox\\cbxIgnoreGetMapURI=true\r\nWidgets\\QgsNewHttpConnectionBase\\mGroupBox\\cbxInvertAxisOrientation=true\r\nWidgets\\QgsNewHttpConnectionBase\\mGroupBox\\cbxSmoothPixmapTransform=true\r\nWidgets\\QgsNewHttpConnectionBase\\mGroupBox\\label=true\r\nWidgets\\QgsNewHttpConnectionBase\\mGroupBox\\label_2=true\r\nWidgets\\QgsNewHttpConnectionBase\\mGroupBox\\label_3=true\r\nWidgets\\QgsNewHttpConnectionBase\\mGroupBox\\lblReferer=true\r\nWidgets\\QgsNewHttpConnectionBase\\mGroupBox\\txtName=true\r\nWidgets\\QgsNewHttpConnectionBase\\mGroupBox\\txtPassword=true\r\nWidgets\\QgsNewHttpConnectionBase\\mGroupBox\\txtReferer=true\r\nWidgets\\QgsNewHttpConnectionBase\\mGroupBox\\txtUrl=true\r\nWidgets\\QgsNewHttpConnectionBase\\mGroupBox\\txtUserName=true\r\nWidgets\\QgsNewOgrConnectionBase=true\r\nWidgets\\QgsNewOgrConnectionBase\\GroupBox1=true\r\nWidgets\\QgsNewOgrConnectionBase\\GroupBox1\\TextLabel1=true\r\nWidgets\\QgsNewOgrConnectionBase\\GroupBox1\\TextLabel1_2=true\r\nWidgets\\QgsNewOgrConnectionBase\\GroupBox1\\TextLabel2=true\r\nWidgets\\QgsNewOgrConnectionBase\\GroupBox1\\TextLabel2_2=true\r\nWidgets\\QgsNewOgrConnectionBase\\GroupBox1\\TextLabel3=true\r\nWidgets\\QgsNewOgrConnectionBase\\GroupBox1\\TextLabel3_2=true\r\nWidgets\\QgsNewOgrConnectionBase\\GroupBox1\\btnConnect=true\r\nWidgets\\QgsNewOgrConnectionBase\\GroupBox1\\chkStorePassword=true\r\nWidgets\\QgsNewOgrConnectionBase\\GroupBox1\\cmbDatabaseTypes=true\r\nWidgets\\QgsNewOgrConnectionBase\\GroupBox1\\label=true\r\nWidgets\\QgsNewOgrConnectionBase\\GroupBox1\\txtDatabase=true\r\nWidgets\\QgsNewOgrConnectionBase\\GroupBox1\\txtHost=true\r\nWidgets\\QgsNewOgrConnectionBase\\GroupBox1\\txtName=true\r\nWidgets\\QgsNewOgrConnectionBase\\GroupBox1\\txtPassword=true\r\nWidgets\\QgsNewOgrConnectionBase\\GroupBox1\\txtPort=true\r\nWidgets\\QgsNewOgrConnectionBase\\GroupBox1\\txtUsername=true\r\nWidgets\\QgsNewOgrConnectionBase\\buttonBox=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\buttonBox=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\buttonGroup1=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\buttonGroup1\\mLineRadioButton=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\buttonGroup1\\mMultilineRadioButton=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\buttonGroup1\\mMultipointRadioButton=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\buttonGroup1\\mMultipolygonRadioButton=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\buttonGroup1\\mPointRadioButton=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\buttonGroup1\\mPolygonRadioButton=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\checkBoxPrimaryKey=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox\\mNameEdit=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox\\mTypeBox=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox\\textLabel1=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox\\textLabel2=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\groupBox_2=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\label=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\label_2=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\leGeometryColumn=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\leLayerName=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\leSRID=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mDatabaseComboBox=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\mFileFormatLabel=true\r\nWidgets\\QgsNewSpatialiteLayerDialogBase\\scrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents\\pbnFindSRID=true\r\nWidgets\\QgsNewVectorLayerDialogBase=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\buttonBox=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\buttonGroup1=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\buttonGroup1\\mLineRadioButton=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\buttonGroup1\\mPointRadioButton=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\buttonGroup1\\mPolygonRadioButton=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\groupBox=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\groupBox\\label=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\groupBox\\label_2=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\groupBox\\mNameEdit=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\groupBox\\mPrecision=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\groupBox\\mTypeBox=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\groupBox\\mWidth=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\groupBox\\textLabel1=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\groupBox\\textLabel2=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\groupBox_2=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\leSpatialRefSys=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\mFileFormatComboBox=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\mFileFormatLabel=true\r\nWidgets\\QgsNewVectorLayerDialogBase\\pbnChangeSpatialRefSys=true\r\nWidgets\\QgsOSMDownloadDialog=true\r\nWidgets\\QgsOSMDownloadDialog\\buttonBox=true\r\nWidgets\\QgsOSMDownloadDialog\\editSize=true\r\nWidgets\\QgsOSMDownloadDialog\\groupBox=true\r\nWidgets\\QgsOSMDownloadDialog\\groupBox\\cboLayers=true\r\nWidgets\\QgsOSMDownloadDialog\\groupBox\\editXMax=true\r\nWidgets\\QgsOSMDownloadDialog\\groupBox\\editXMin=true\r\nWidgets\\QgsOSMDownloadDialog\\groupBox\\editYMax=true\r\nWidgets\\QgsOSMDownloadDialog\\groupBox\\editYMin=true\r\nWidgets\\QgsOSMDownloadDialog\\groupBox\\radExtentCanvas=true\r\nWidgets\\QgsOSMDownloadDialog\\groupBox\\radExtentLayer=true\r\nWidgets\\QgsOSMDownloadDialog\\groupBox\\radExtentManual=true\r\nWidgets\\QgsOSMDownloadDialog\\groupBox_2=true\r\nWidgets\\QgsOSMDownloadDialog\\groupBox_2\\editFileName=true\r\nWidgets\\QgsOSMDownloadDialog\\progress=true\r\nWidgets\\QgsOSMExportDialog=true\r\nWidgets\\QgsOSMExportDialog\\buttonBox=true\r\nWidgets\\QgsOSMExportDialog\\chkLoadWhenFinished=true\r\nWidgets\\QgsOSMExportDialog\\groupBox=true\r\nWidgets\\QgsOSMExportDialog\\groupBox\\editDbFileName=true\r\nWidgets\\QgsOSMExportDialog\\groupBox_2=true\r\nWidgets\\QgsOSMExportDialog\\groupBox_2\\editLayerName=true\r\nWidgets\\QgsOSMExportDialog\\groupBox_3=true\r\nWidgets\\QgsOSMExportDialog\\groupBox_3\\btnLoadTags=true\r\nWidgets\\QgsOSMExportDialog\\groupBox_4=true\r\nWidgets\\QgsOSMExportDialog\\groupBox_4\\radPoints=true\r\nWidgets\\QgsOSMExportDialog\\groupBox_4\\radPolygons=true\r\nWidgets\\QgsOSMExportDialog\\groupBox_4\\radPolylines=true\r\nWidgets\\QgsOSMExportDialog\\progressBar=true\r\nWidgets\\QgsOSMImportDialog=true\r\nWidgets\\QgsOSMImportDialog\\buttonBox=true\r\nWidgets\\QgsOSMImportDialog\\groupBox=true\r\nWidgets\\QgsOSMImportDialog\\groupBox\\editDbFileName=true\r\nWidgets\\QgsOSMImportDialog\\groupBox_2=true\r\nWidgets\\QgsOSMImportDialog\\groupBox_2\\editXmlFileName=true\r\nWidgets\\QgsOSMImportDialog\\groupCreateConn=true\r\nWidgets\\QgsOSMImportDialog\\groupCreateConn\\editConnName=true\r\nWidgets\\QgsOSMImportDialog\\groupCreateConn\\label=true\r\nWidgets\\QgsOSMImportDialog\\progressBar=true\r\nWidgets\\QgsOWSSourceSelectBase=true\r\nWidgets\\QgsOWSSourceSelectBase\\mDialogButtonBox=true\r\nWidgets\\QgsOWSSourceSelectBase\\mStatusLabel=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayerOrderTab=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayerOrderTab\\mLayerDownButton=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayerOrderTab\\mLayerUpButton=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mAddDefaultButton=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mCRSWidget=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mCRSWidget\\mCRSLabel=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mCRSWidget\\mChangeCRSButton=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mCRSWidget\\mSelectedCRSLabel=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mCacheWidget=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mCacheWidget\\mCacheComboBox=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mCacheWidget\\mCacheLabel=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mConnectButton=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mConnectionsComboBox=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mDeleteButton=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mEditButton=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mFormatWidget=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mFormatWidget\\mFormatComboBox=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mFormatWidget\\mFormatLabel=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mLoadButton=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mNewButton=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mSaveButton=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mTimeWidget=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mTimeWidget\\mTimeComboBox=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mTimeWidget\\mTimeLabel=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mWMSGroupBox=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mWMSGroupBox\\mFeatureCountLabel=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mWMSGroupBox\\mFeatureCountLineEdit=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mWMSGroupBox\\mLayerNameLabel=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mWMSGroupBox\\mLayerNameLineEdit=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mWMSGroupBox\\mTileHeightLineEdit=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mWMSGroupBox\\mTileSizeLabel=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mLayersTab\\mWMSGroupBox\\mTileWidthLineEdit=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mSearchTab=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mSearchTab\\mSearchAddButton=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mSearchTab\\mSearchButton=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mSearchTab\\mSearchTermLineEdit=true\r\nWidgets\\QgsOWSSourceSelectBase\\mTabWidget\\mTilesetsTab=true\r\nWidgets\\QgsOpenVectorLayerDialogBase=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\buttonBox=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\dbGroupBox=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\dbGroupBox\\cmbDatabaseTypes=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\dbGroupBox\\groupBox=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\dbGroupBox\\groupBox\\btnDelete=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\dbGroupBox\\groupBox\\btnEdit=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\dbGroupBox\\groupBox\\btnNew=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\dbGroupBox\\groupBox\\cmbConnections=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\dbGroupBox\\label_4=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\fileGroupBox=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\fileGroupBox\\buttonSelectSrc=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\fileGroupBox\\cmbDirectoryTypes=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\fileGroupBox\\inputSrcDataset=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\fileGroupBox\\labelDirectoryType=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\fileGroupBox\\labelSrcDataset=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\protocolGroupBox=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\protocolGroupBox\\cmbProtocolTypes=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\protocolGroupBox\\label=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\protocolGroupBox\\label_2=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\protocolGroupBox\\protocolURI=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\srcGroupBox_2=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\srcGroupBox_2\\cmbEncodings=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\srcGroupBox_2\\label_3=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\srcGroupBox_2\\radioSrcDatabase=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\srcGroupBox_2\\radioSrcDirectory=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\srcGroupBox_2\\radioSrcFile=true\r\nWidgets\\QgsOpenVectorLayerDialogBase\\srcGroupBox_2\\radioSrcProtocol=true\r\nWidgets\\QgsOptionsBase=true\r\nWidgets\\QgsOracleNewConnectionBase=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\TextLabel1=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\TextLabel1_2=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\TextLabel2_2=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\TextLabel3=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\TextLabel3_2=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\btnConnect=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\cb_allowGeometrylessTables=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\cb_geometryColumnsOnly=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\cb_onlyExistingTypes=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\cb_useEstimatedMetadata=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\cb_userTablesOnly=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\chkStorePassword=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\chkStoreUsername=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\label=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\txtDatabase=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\txtHost=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\txtName=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\txtPassword=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\txtPort=true\r\nWidgets\\QgsOracleNewConnectionBase\\GroupBox1\\txtUsername=true\r\nWidgets\\QgsOracleNewConnectionBase\\buttonBox=true\r\nWidgets\\QgsPalettedRendererWidgetBase=true\r\nWidgets\\QgsPalettedRendererWidgetBase\\mBandComboBox=true\r\nWidgets\\QgsPalettedRendererWidgetBase\\mBandLabel=true\r\nWidgets\\QgsPasteTransformationsBase=true\r\nWidgets\\QgsPasteTransformationsBase\\buttonBox=true\r\nWidgets\\QgsPasteTransformationsBase\\destinationLayerComboBox=true\r\nWidgets\\QgsPasteTransformationsBase\\sourceLayerComboBox=true\r\nWidgets\\QgsPasteTransformationsBase\\textLabel1_2=true\r\nWidgets\\QgsPasteTransformationsBase\\textLabel3=true\r\nWidgets\\QgsPasteTransformationsBase\\textLabel4=true\r\nWidgets\\QgsPgNewConnectionBase=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\TextLabel1=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\TextLabel1_2=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\TextLabel2=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\TextLabel2_2=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\TextLabel3=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\TextLabel3_2=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\TextLabel3_3=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\btnConnect=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\cb_allowGeometrylessTables=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\cb_dontResolveType=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\cb_geometryColumnsOnly=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\cb_publicSchemaOnly=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\cb_useEstimatedMetadata=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\cbxSSLmode=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\chkStorePassword=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\chkStoreUsername=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\label=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\txtDatabase=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\txtHost=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\txtName=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\txtPassword=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\txtPort=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\txtService=true\r\nWidgets\\QgsPgNewConnectionBase\\GroupBox1\\txtUsername=true\r\nWidgets\\QgsPgNewConnectionBase\\buttonBox=true\r\nWidgets\\QgsPluginManagerBase=true\r\nWidgets\\QgsPluginManagerBase\\buttonBox=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mCenterSymbolLabel=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mCenterSymbolPushButton=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mDisplacementCirclesGroupBox=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mDisplacementCirclesGroupBox\\mCircleColorLabel=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mDisplacementCirclesGroupBox\\mCircleRadiusLabel=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mDisplacementCirclesGroupBox\\mCircleWidthLabel=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mDisplacementCirclesGroupBox\\mDistanceToleranceLabel=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mLabellingGroupBox=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mLabellingGroupBox\\mLabelAttributeLabel=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mLabellingGroupBox\\mLabelColorLabel=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mLabellingGroupBox\\mLabelFieldComboBox=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mLabellingGroupBox\\mLabelFontButton=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mLabellingGroupBox\\mMaxScaleDenominatorEdit=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mLabellingGroupBox\\mMaxScaleLabel=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mLabellingGroupBox\\mScaleDependentLabelsCheckBox=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mRendererComboBox=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mRendererLabel=true\r\nWidgets\\QgsPointDisplacementRendererWidgetBase\\mRendererSettingsButton=true\r\nWidgets\\QgsProjectLayerGroupDialogBase=true\r\nWidgets\\QgsProjectLayerGroupDialogBase\\mButtonBox=true\r\nWidgets\\QgsProjectLayerGroupDialogBase\\mProjectFileLabel=true\r\nWidgets\\QgsProjectLayerGroupDialogBase\\mProjectFileLineEdit=true\r\nWidgets\\QgsProjectPropertiesBase=true\r\nWidgets\\QgsProjectionSelectorBase=true\r\nWidgets\\QgsProjectionSelectorBase\\label=true\r\nWidgets\\QgsProjectionSelectorBase\\label_3=true\r\nWidgets\\QgsProjectionSelectorBase\\label_5=true\r\nWidgets\\QgsProjectionSelectorBase\\teProjection=true\r\nWidgets\\QgsProjectionSelectorBase\\teProjection\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsProjectionSelectorBase\\teProjection\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsProjectionSelectorBase\\teProjection\\qt_scrollarea_viewport=true\r\nWidgets\\QgsProjectionSelectorBase\\teSelected=true\r\nWidgets\\QgsQueryBuilderBase=true\r\nWidgets\\QgsQueryBuilderBase\\buttonBox=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox1=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox1\\lstFields=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox1\\lstFields\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox1\\lstFields\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox1\\lstFields\\qt_scrollarea_viewport=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox2=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox2\\btnGetAllValues=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox2\\btnSampleValues=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox2\\lstValues=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox2\\lstValues\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox2\\lstValues\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox2\\lstValues\\qt_scrollarea_viewport=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox2\\mUseUnfilteredLayer=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox3=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox3\\txtSQL=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox3\\txtSQL\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox3\\txtSQL\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox3\\txtSQL\\qt_scrollarea_viewport=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox4=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox4\\btnAnd=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox4\\btnEqual=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox4\\btnGreaterEqual=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox4\\btnGreaterThan=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox4\\btnILike=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox4\\btnIn=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox4\\btnLessEqual=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox4\\btnLessThan=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox4\\btnLike=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox4\\btnNot=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox4\\btnNotEqual=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox4\\btnNotIn=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox4\\btnOr=true\r\nWidgets\\QgsQueryBuilderBase\\groupBox4\\btnPct=true\r\nWidgets\\QgsQueryBuilderBase\\lblDataUri=true\r\nWidgets\\QgsRasterCalcDialogBase=true\r\nWidgets\\QgsRasterCalcDialogBase\\mButtonBox=true\r\nWidgets\\QgsRasterCalcDialogBase\\mExpressionTextEdit=true\r\nWidgets\\QgsRasterCalcDialogBase\\mExpressionTextEdit\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsRasterCalcDialogBase\\mExpressionTextEdit\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsRasterCalcDialogBase\\mExpressionTextEdit\\qt_scrollarea_viewport=true\r\nWidgets\\QgsRasterCalcDialogBase\\mExpressionValidLabel=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mACosButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mASinButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mATanButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mAndButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mCloseBracketPushButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mCosButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mDividePushButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mEqualButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mExpButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mGreaterButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mGreaterEqualButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mLessButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mLesserEqualButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mMinusPushButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mMultiplyPushButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mOpenBracketPushButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mOrButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mPlusPushButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mSinButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mSqrtButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mOperatorsGroupBox\\mTanButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mRasterBandsGroupBox=true\r\nWidgets\\QgsRasterCalcDialogBase\\mRasterCalculatorExpressionLabel=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox\\mAddResultToProjectCheckBox=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox\\mColumnsLabel=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox\\mCurrentLayerExtentButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox\\mNColumnsSpinBox=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox\\mNColumnsSpinBox\\qt_spinbox_lineedit=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox\\mNRowsSpinBox=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox\\mNRowsSpinBox\\qt_spinbox_lineedit=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox\\mOutputFormatComboBox=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox\\mOutputFormatLabel=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox\\mOutputLayerLabel=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox\\mOutputLayerLineEdit=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox\\mOutputLayerPushButton=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox\\mRowsLabel=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox\\mXMaxLabel=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox\\mXMinLabel=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox\\mYMaxLabel=true\r\nWidgets\\QgsRasterCalcDialogBase\\mResultGroupBox\\mYMinLabel=true\r\nWidgets\\QgsRasterFormatSaveOptionsWidgetBase=true\r\nWidgets\\QgsRasterFormatSaveOptionsWidgetBase\\mOptionsStackedWidget=true\r\nWidgets\\QgsRasterFormatSaveOptionsWidgetBase\\mOptionsStackedWidget\\page=true\r\nWidgets\\QgsRasterFormatSaveOptionsWidgetBase\\mOptionsStackedWidget\\page\\mOptionsAddButton=true\r\nWidgets\\QgsRasterFormatSaveOptionsWidgetBase\\mOptionsStackedWidget\\page\\mOptionsDeleteButton=true\r\nWidgets\\QgsRasterFormatSaveOptionsWidgetBase\\mOptionsStackedWidget\\page\\mOptionsHelpButton=true\r\nWidgets\\QgsRasterFormatSaveOptionsWidgetBase\\mOptionsStackedWidget\\page\\mOptionsValidateButton=true\r\nWidgets\\QgsRasterFormatSaveOptionsWidgetBase\\mOptionsStackedWidget\\page_2=true\r\nWidgets\\QgsRasterFormatSaveOptionsWidgetBase\\mOptionsStackedWidget\\page_2\\mOptionsLineEdit=true\r\nWidgets\\QgsRasterFormatSaveOptionsWidgetBase\\mProfileButtons=true\r\nWidgets\\QgsRasterFormatSaveOptionsWidgetBase\\mProfileButtons\\mProfileDeleteButton=true\r\nWidgets\\QgsRasterFormatSaveOptionsWidgetBase\\mProfileButtons\\mProfileNewButton=true\r\nWidgets\\QgsRasterFormatSaveOptionsWidgetBase\\mProfileButtons\\mProfileResetButton=true\r\nWidgets\\QgsRasterFormatSaveOptionsWidgetBase\\mProfileComboBox=true\r\nWidgets\\QgsRasterFormatSaveOptionsWidgetBase\\mProfileLabel=true\r\nWidgets\\QgsRasterHistogramWidgetBase=true\r\nWidgets\\QgsRasterHistogramWidgetBase\\stackedWidget2=true\r\nWidgets\\QgsRasterHistogramWidgetBase\\stackedWidget2\\page=true\r\nWidgets\\QgsRasterHistogramWidgetBase\\stackedWidget2\\page\\btnHistoCompute=true\r\nWidgets\\QgsRasterHistogramWidgetBase\\stackedWidget2\\page1_2=true\r\nWidgets\\QgsRasterHistogramWidgetBase\\stackedWidget2\\page2_2=true\r\nWidgets\\QgsRasterHistogramWidgetBase\\stackedWidget2\\page2_2\\mHistogramProgress=true\r\nWidgets\\QgsRasterLayerPropertiesBase=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\label_2=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\mBrowseButton=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\mButtonBox=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\mChangeCrsPushButton=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\mCrsComboBox=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\mFormatComboBox=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\mFormatLabel=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\mModeLabel=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\mRawModeRadioButton=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\mRenderedModeRadioButton=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\mSaveAsLabel=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\mSaveAsLineEdit=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\mScrollArea=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\mScrollArea\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\mScrollArea\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\mScrollArea\\qt_scrollarea_viewport=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\mScrollArea\\qt_scrollarea_viewport\\scrollAreaWidgetContents=true\r\nWidgets\\QgsRasterLayerSaveAsDialogBase\\mTileModeCheckBox=true\r\nWidgets\\QgsRasterMinMaxWidgetBase=true\r\nWidgets\\QgsRasterMinMaxWidgetBase\\mLoadMinMaxValuesGroupBox=true\r\nWidgets\\QgsRasterMinMaxWidgetBase\\mLoadMinMaxValuesGroupBox\\label=true\r\nWidgets\\QgsRasterMinMaxWidgetBase\\mLoadMinMaxValuesGroupBox\\label_2=true\r\nWidgets\\QgsRasterMinMaxWidgetBase\\mLoadMinMaxValuesGroupBox\\mAccuracyGroupBox=true\r\nWidgets\\QgsRasterMinMaxWidgetBase\\mLoadMinMaxValuesGroupBox\\mAccuracyGroupBox\\mActualRadioButton=true\r\nWidgets\\QgsRasterMinMaxWidgetBase\\mLoadMinMaxValuesGroupBox\\mAccuracyGroupBox\\mEstimateRadioButton=true\r\nWidgets\\QgsRasterMinMaxWidgetBase\\mLoadMinMaxValuesGroupBox\\mCumulativeCutRadioButton=true\r\nWidgets\\QgsRasterMinMaxWidgetBase\\mLoadMinMaxValuesGroupBox\\mExtentGroupBox=true\r\nWidgets\\QgsRasterMinMaxWidgetBase\\mLoadMinMaxValuesGroupBox\\mExtentGroupBox\\mCurrentExtentRadioButton=true\r\nWidgets\\QgsRasterMinMaxWidgetBase\\mLoadMinMaxValuesGroupBox\\mExtentGroupBox\\mFullExtentRadioButton=true\r\nWidgets\\QgsRasterMinMaxWidgetBase\\mLoadMinMaxValuesGroupBox\\mLoadPushButton=true\r\nWidgets\\QgsRasterMinMaxWidgetBase\\mLoadMinMaxValuesGroupBox\\mMinMaxRadioButton=true\r\nWidgets\\QgsRasterMinMaxWidgetBase\\mLoadMinMaxValuesGroupBox\\mStdDevRadioButton=true\r\nWidgets\\QgsRasterPyramidsOptionsWidgetBase=true\r\nWidgets\\QgsRasterPyramidsOptionsWidgetBase\\cboResamplingMethod=true\r\nWidgets\\QgsRasterPyramidsOptionsWidgetBase\\cbxPyramidsFormat=true\r\nWidgets\\QgsRasterPyramidsOptionsWidgetBase\\cbxPyramidsLevelsCustom=true\r\nWidgets\\QgsRasterPyramidsOptionsWidgetBase\\label_2=true\r\nWidgets\\QgsRasterPyramidsOptionsWidgetBase\\label_4=true\r\nWidgets\\QgsRasterPyramidsOptionsWidgetBase\\label_5=true\r\nWidgets\\QgsRasterPyramidsOptionsWidgetBase\\lePyramidsLevels=true\r\nWidgets\\QgsRasterPyramidsOptionsWidgetBase\\textLabel4_2=true\r\nWidgets\\QgsRendererRulePropsDialog=true\r\nWidgets\\QgsRendererRulePropsDialog\\btnExpressionBuilder=true\r\nWidgets\\QgsRendererRulePropsDialog\\btnTestFilter=true\r\nWidgets\\QgsRendererRulePropsDialog\\buttonBox=true\r\nWidgets\\QgsRendererRulePropsDialog\\editDescription=true\r\nWidgets\\QgsRendererRulePropsDialog\\editFilter=true\r\nWidgets\\QgsRendererRulePropsDialog\\editLabel=true\r\nWidgets\\QgsRendererRulePropsDialog\\groupScale=true\r\nWidgets\\QgsRendererRulePropsDialog\\groupScale\\label_2=true\r\nWidgets\\QgsRendererRulePropsDialog\\groupScale\\label_3=true\r\nWidgets\\QgsRendererRulePropsDialog\\groupScale\\spinMaxScale=true\r\nWidgets\\QgsRendererRulePropsDialog\\groupScale\\spinMaxScale\\qt_spinbox_lineedit=true\r\nWidgets\\QgsRendererRulePropsDialog\\groupScale\\spinMinScale=true\r\nWidgets\\QgsRendererRulePropsDialog\\groupScale\\spinMinScale\\qt_spinbox_lineedit=true\r\nWidgets\\QgsRendererRulePropsDialog\\groupSymbol=true\r\nWidgets\\QgsRendererRulePropsDialog\\label_1=true\r\nWidgets\\QgsRendererRulePropsDialog\\label_4=true\r\nWidgets\\QgsRendererRulePropsDialog\\label_5=true\r\nWidgets\\QgsRendererV2PropsDialogBase=true\r\nWidgets\\QgsRendererV2PropsDialogBase\\buttonBox=true\r\nWidgets\\QgsRendererV2PropsDialogBase\\cboRenderers=true\r\nWidgets\\QgsRendererV2PropsDialogBase\\stackedWidget=true\r\nWidgets\\QgsRendererV2PropsDialogBase\\stackedWidget\\pageNoWidget=true\r\nWidgets\\QgsRendererV2PropsDialogBase\\stackedWidget\\pageNoWidget\\label=true\r\nWidgets\\QgsRuleBasedRendererV2Widget=true\r\nWidgets\\QgsRuleBasedRendererV2Widget\\btnAddRule=true\r\nWidgets\\QgsRuleBasedRendererV2Widget\\btnCountFeatures=true\r\nWidgets\\QgsRuleBasedRendererV2Widget\\btnEditRule=true\r\nWidgets\\QgsRuleBasedRendererV2Widget\\btnRefineRule=true\r\nWidgets\\QgsRuleBasedRendererV2Widget\\btnRemoveRule=true\r\nWidgets\\QgsRuleBasedRendererV2Widget\\btnRenderingOrder=true\r\nWidgets\\QgsSaveToDBDialog=true\r\nWidgets\\QgsSaveToDBDialog\\buttonBox=true\r\nWidgets\\QgsSaveToDBDialog\\descriptionLabel=true\r\nWidgets\\QgsSaveToDBDialog\\label=true\r\nWidgets\\QgsSaveToDBDialog\\mFileNameLabel=true\r\nWidgets\\QgsSaveToDBDialog\\mNameEdit=true\r\nWidgets\\QgsSaveToDBDialog\\mUILabel=true\r\nWidgets\\QgsSaveToDBDialog\\mUseAsDefault=true\r\nWidgets\\QgsSaveToDBDialog\\nameLabel=true\r\nWidgets\\QgsSingleBandGrayRendererWidgetBase=true\r\nWidgets\\QgsSingleBandGrayRendererWidgetBase\\label=true\r\nWidgets\\QgsSingleBandGrayRendererWidgetBase\\mContrastEnhancementComboBox=true\r\nWidgets\\QgsSingleBandGrayRendererWidgetBase\\mContrastEnhancementLabel=true\r\nWidgets\\QgsSingleBandGrayRendererWidgetBase\\mGradientComboBox=true\r\nWidgets\\QgsSingleBandGrayRendererWidgetBase\\mGrayBandComboBox=true\r\nWidgets\\QgsSingleBandGrayRendererWidgetBase\\mGrayBandLabel=true\r\nWidgets\\QgsSingleBandGrayRendererWidgetBase\\mMaxLabel=true\r\nWidgets\\QgsSingleBandGrayRendererWidgetBase\\mMaxLineEdit=true\r\nWidgets\\QgsSingleBandGrayRendererWidgetBase\\mMinLabel=true\r\nWidgets\\QgsSingleBandGrayRendererWidgetBase\\mMinLineEdit=true\r\nWidgets\\QgsSingleBandGrayRendererWidgetBase\\mMinMaxContainerWidget=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\grpGenerateColorMap=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\grpGenerateColorMap\\label_2=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\grpGenerateColorMap\\mClassificationModeComboBox=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\grpGenerateColorMap\\mClassificationModeLabel=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\grpGenerateColorMap\\mClassifyButton=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\grpGenerateColorMap\\mInvertCheckBox=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\grpGenerateColorMap\\mMaxLabel=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\grpGenerateColorMap\\mMaxLineEdit=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\grpGenerateColorMap\\mMinLabel=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\grpGenerateColorMap\\mMinLineEdit=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\grpGenerateColorMap\\mMinMaxOriginLabel=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\grpGenerateColorMap\\mNumberOfEntriesLabel=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\grpGenerateColorMap\\mNumberOfEntriesSpinBox=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\grpGenerateColorMap\\mNumberOfEntriesSpinBox\\qt_spinbox_lineedit=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\mBandComboBox=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\mBandLabel=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\mClipCheckBox=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\mColorInterpolationComboBox=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\mColorInterpolationLabel=true\r\nWidgets\\QgsSingleBandPseudoColorRendererWidgetBase\\mMinMaxContainerWidget=true\r\nWidgets\\QgsSmartGroupConditionWidget=true\r\nWidgets\\QgsSmartGroupConditionWidget\\label=true\r\nWidgets\\QgsSmartGroupConditionWidget\\mCondCombo=true\r\nWidgets\\QgsSmartGroupConditionWidget\\mCondLineEdit=true\r\nWidgets\\QgsSmartGroupConditionWidget\\mRemoveBtn=true\r\nWidgets\\QgsSmartGroupEditorDialogBase=true\r\nWidgets\\QgsSmartGroupEditorDialogBase\\buttonBox=true\r\nWidgets\\QgsSmartGroupEditorDialogBase\\label=true\r\nWidgets\\QgsSmartGroupEditorDialogBase\\label_2=true\r\nWidgets\\QgsSmartGroupEditorDialogBase\\mAddConditionBtn=true\r\nWidgets\\QgsSmartGroupEditorDialogBase\\mAndOrCombo=true\r\nWidgets\\QgsSmartGroupEditorDialogBase\\mConditionsBox=true\r\nWidgets\\QgsSmartGroupEditorDialogBase\\mNameLineEdit=true\r\nWidgets\\QgsSnappingDialogBase=true\r\nWidgets\\QgsSnappingDialogBase\\cbxEnableIntersectionSnappingCheckBox=true\r\nWidgets\\QgsSnappingDialogBase\\cbxEnableTopologicalEditingCheckBox=true\r\nWidgets\\QgsSnappingDialogBase\\mButtonBox=true\r\nWidgets\\QgsSpatialiteSridsDialogBase=true\r\nWidgets\\QgsSpatialiteSridsDialogBase\\buttonBox=true\r\nWidgets\\QgsSpatialiteSridsDialogBase\\groupBox=true\r\nWidgets\\QgsSpatialiteSridsDialogBase\\groupBox\\radioButtonName=true\r\nWidgets\\QgsSpatialiteSridsDialogBase\\groupBox\\radioButtonSrid=true\r\nWidgets\\QgsSpatialiteSridsDialogBase\\label=true\r\nWidgets\\QgsSpatialiteSridsDialogBase\\leSearch=true\r\nWidgets\\QgsSpatialiteSridsDialogBase\\pbnFilter=true\r\nWidgets\\QgsSponsorsBase=true\r\nWidgets\\QgsSponsorsBase\\buttonBox=true\r\nWidgets\\QgsSponsorsBase\\qgisIcon=true\r\nWidgets\\QgsSponsorsBase\\txtSponsors=true\r\nWidgets\\QgsSponsorsBase\\txtSponsors\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsSponsorsBase\\txtSponsors\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsSponsorsBase\\txtSponsors\\qt_scrollarea_viewport=true\r\nWidgets\\QgsStyleV2ExportImportDialogBase=true\r\nWidgets\\QgsStyleV2ExportImportDialogBase\\btnBrowse=true\r\nWidgets\\QgsStyleV2ExportImportDialogBase\\buttonBox=true\r\nWidgets\\QgsStyleV2ExportImportDialogBase\\fromLabel=true\r\nWidgets\\QgsStyleV2ExportImportDialogBase\\groupCombo=true\r\nWidgets\\QgsStyleV2ExportImportDialogBase\\groupLabel=true\r\nWidgets\\QgsStyleV2ExportImportDialogBase\\importTypeCombo=true\r\nWidgets\\QgsStyleV2ExportImportDialogBase\\label=true\r\nWidgets\\QgsStyleV2ExportImportDialogBase\\listItems=true\r\nWidgets\\QgsStyleV2ExportImportDialogBase\\listItems\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsStyleV2ExportImportDialogBase\\listItems\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsStyleV2ExportImportDialogBase\\listItems\\qt_scrollarea_viewport=true\r\nWidgets\\QgsStyleV2ExportImportDialogBase\\locationLabel=true\r\nWidgets\\QgsStyleV2ExportImportDialogBase\\locationLineEdit=true\r\nWidgets\\QgsStyleV2ManagerDialogBase=true\r\nWidgets\\QgsSublayersDialogBase=true\r\nWidgets\\QgsSublayersDialogBase\\buttonBox=true\r\nWidgets\\QgsSymbolLevelsV2DialogBase=true\r\nWidgets\\QgsSymbolLevelsV2DialogBase\\buttonBox=true\r\nWidgets\\QgsSymbolLevelsV2DialogBase\\chkEnable=true\r\nWidgets\\QgsSymbolLevelsV2DialogBase\\label=true\r\nWidgets\\QgsSymbolV2SelectorDialogBase=true\r\nWidgets\\QgsSymbolV2SelectorDialogBase\\btnAddLayer=true\r\nWidgets\\QgsSymbolV2SelectorDialogBase\\btnDown=true\r\nWidgets\\QgsSymbolV2SelectorDialogBase\\btnLock=true\r\nWidgets\\QgsSymbolV2SelectorDialogBase\\btnRemoveLayer=true\r\nWidgets\\QgsSymbolV2SelectorDialogBase\\btnUp=true\r\nWidgets\\QgsSymbolV2SelectorDialogBase\\buttonBox=true\r\nWidgets\\QgsSymbolV2SelectorDialogBase\\label_3=true\r\nWidgets\\QgsSymbolV2SelectorDialogBase\\lblPreview=true\r\nWidgets\\QgsTextAnnotationDialogBase=true\r\nWidgets\\QgsTextAnnotationDialogBase\\mBoldPushButton=true\r\nWidgets\\QgsTextAnnotationDialogBase\\mButtonBox=true\r\nWidgets\\QgsTextAnnotationDialogBase\\mFontSizeSpinBox=true\r\nWidgets\\QgsTextAnnotationDialogBase\\mFontSizeSpinBox\\qt_spinbox_lineedit=true\r\nWidgets\\QgsTextAnnotationDialogBase\\mItalicsPushButton=true\r\nWidgets\\QgsTextAnnotationDialogBase\\mStackedWidget=true\r\nWidgets\\QgsTextAnnotationDialogBase\\mStackedWidget\\page=true\r\nWidgets\\QgsTextAnnotationDialogBase\\mStackedWidget\\page_2=true\r\nWidgets\\QgsTextAnnotationDialogBase\\mTextEdit=true\r\nWidgets\\QgsTextAnnotationDialogBase\\mTextEdit\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsTextAnnotationDialogBase\\mTextEdit\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsTextAnnotationDialogBase\\mTextEdit\\qt_scrollarea_viewport=true\r\nWidgets\\QgsTileScaleWidget=true\r\nWidgets\\QgsTileScaleWidget\\mSlider=true\r\nWidgets\\QgsTipGuiBase=true\r\nWidgets\\QgsTipGuiBase\\buttonBox=true\r\nWidgets\\QgsTipGuiBase\\cbxDisableTips=true\r\nWidgets\\QgsTipGuiBase\\txtTip=true\r\nWidgets\\QgsTipGuiBase\\txtTip\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsTipGuiBase\\txtTip\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsTipGuiBase\\txtTip\\qt_scrollarea_viewport=true\r\nWidgets\\QgsVectorColorBrewerColorRampV2DialogBase=true\r\nWidgets\\QgsVectorColorBrewerColorRampV2DialogBase\\buttonBox=true\r\nWidgets\\QgsVectorColorBrewerColorRampV2DialogBase\\cboColors=true\r\nWidgets\\QgsVectorColorBrewerColorRampV2DialogBase\\cboSchemeName=true\r\nWidgets\\QgsVectorColorBrewerColorRampV2DialogBase\\groupBox=true\r\nWidgets\\QgsVectorColorBrewerColorRampV2DialogBase\\groupBox\\lblPreview=true\r\nWidgets\\QgsVectorColorBrewerColorRampV2DialogBase\\label=true\r\nWidgets\\QgsVectorColorBrewerColorRampV2DialogBase\\label_2=true\r\nWidgets\\QgsVectorGradientColorRampV2DialogBase=true\r\nWidgets\\QgsVectorGradientColorRampV2DialogBase\\btnInformation=true\r\nWidgets\\QgsVectorGradientColorRampV2DialogBase\\buttonBox=true\r\nWidgets\\QgsVectorGradientColorRampV2DialogBase\\cboType=true\r\nWidgets\\QgsVectorGradientColorRampV2DialogBase\\groupBox=true\r\nWidgets\\QgsVectorGradientColorRampV2DialogBase\\groupBox\\lblPreview=true\r\nWidgets\\QgsVectorGradientColorRampV2DialogBase\\groupStops=true\r\nWidgets\\QgsVectorGradientColorRampV2DialogBase\\groupStops\\btnAddStop=true\r\nWidgets\\QgsVectorGradientColorRampV2DialogBase\\groupStops\\btnRemoveStop=true\r\nWidgets\\QgsVectorGradientColorRampV2DialogBase\\label=true\r\nWidgets\\QgsVectorGradientColorRampV2DialogBase\\label_2=true\r\nWidgets\\QgsVectorGradientColorRampV2DialogBase\\label_3=true\r\nWidgets\\QgsVectorLayerPropertiesBase=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\browseCRS=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\browseFilename=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\buttonBox=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\groupBox=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\groupBox\\label_5=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\groupBox\\label_6=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\groupBox\\mAddToCanvas=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\groupBox\\mOgrDatasourceOptions=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\groupBox\\mOgrDatasourceOptions\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\groupBox\\mOgrDatasourceOptions\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\groupBox\\mOgrDatasourceOptions\\qt_scrollarea_viewport=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\groupBox\\mOgrLayerOptions=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\groupBox\\mOgrLayerOptions\\qt_scrollarea_hcontainer=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\groupBox\\mOgrLayerOptions\\qt_scrollarea_vcontainer=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\groupBox\\mOgrLayerOptions\\qt_scrollarea_viewport=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\groupBox\\mSkipAttributeCreation=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\label=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\label_2=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\label_3=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\label_4=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\leCRS=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\leFilename=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\mCRSSelection=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\mEncodingComboBox=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\mFormatComboBox=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\mScaleLabel=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\mScaleSpinBox=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\mScaleSpinBox\\qt_spinbox_lineedit=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\mSymbologyExportComboBox=true\r\nWidgets\\QgsVectorLayerSaveAsDialogBase\\mSymbologyExportLabel=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\buttonBox=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\groupBox=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\groupBox\\lblPreview=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\label=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\label_10=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\label_2=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\label_3=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\label_4=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\label_5=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\label_6=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\label_7=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\label_8=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\label_9=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\spinCount=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\spinCount\\qt_spinbox_lineedit=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\spinHue1=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\spinHue1\\qt_spinbox_lineedit=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\spinHue2=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\spinHue2\\qt_spinbox_lineedit=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\spinSat1=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\spinSat1\\qt_spinbox_lineedit=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\spinSat2=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\spinSat2\\qt_spinbox_lineedit=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\spinVal1=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\spinVal1\\qt_spinbox_lineedit=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\spinVal2=true\r\nWidgets\\QgsVectorRandomColorRampV2DialogBase\\spinVal2\\qt_spinbox_lineedit=true\r\nWidgets\\QgsWFSSourceSelectBase=true\r\nWidgets\\QgsWFSSourceSelectBase\\GroupBox1=true\r\nWidgets\\QgsWFSSourceSelectBase\\GroupBox1\\btnConnect=true\r\nWidgets\\QgsWFSSourceSelectBase\\GroupBox1\\btnDelete=true\r\nWidgets\\QgsWFSSourceSelectBase\\GroupBox1\\btnEdit=true\r\nWidgets\\QgsWFSSourceSelectBase\\GroupBox1\\btnLoad=true\r\nWidgets\\QgsWFSSourceSelectBase\\GroupBox1\\btnNew=true\r\nWidgets\\QgsWFSSourceSelectBase\\GroupBox1\\btnSave=true\r\nWidgets\\QgsWFSSourceSelectBase\\GroupBox1\\cmbConnections=true\r\nWidgets\\QgsWFSSourceSelectBase\\buttonBox=true\r\nWidgets\\QgsWFSSourceSelectBase\\cbxUseTitleLayerName=true\r\nWidgets\\QgsWFSSourceSelectBase\\gbCRS=true\r\nWidgets\\QgsWFSSourceSelectBase\\gbCRS\\btnChangeSpatialRefSys=true\r\nWidgets\\QgsWFSSourceSelectBase\\gbCRS\\labelCoordRefSys=true\r\nWidgets\\QgsWFSSourceSelectBase\\labelFilter=true\r\nWidgets\\QgsWFSSourceSelectBase\\lineFilter=true\r\nWidgets\\QgsWMSSourceSelectBase=true\r\nWidgets\\QgsWMSSourceSelectBase\\buttonBox=true\r\nWidgets\\QgsWMSSourceSelectBase\\labelStatus=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayerOrder=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayerOrder\\mLayerDownButton=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayerOrder\\mLayerUpButton=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\btnAddDefault=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\btnConnect=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\btnDelete=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\btnEdit=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\btnGrpImageEncoding=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\btnLoad=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\btnNew=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\btnSave=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\cmbConnections=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\gbCRS=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\gbCRS\\btnChangeSpatialRefSys=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\gbCRS\\label=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\gbCRS\\labelCoordRefSys=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\gbCRS\\label_2=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\gbCRS\\label_3=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\gbCRS\\leLayerName=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\gbCRS\\mFeatureCount=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\gbCRS\\mTileHeight=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabLayers\\gbCRS\\mTileWidth=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabServerSearch=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabServerSearch\\btnAddWMS=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabServerSearch\\btnSearch=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabServerSearch\\leSearchTerm=true\r\nWidgets\\QgsWMSSourceSelectBase\\tabServers\\tabTilesets=true\r\nWidgets\\QgsWmtsDimensionsBase=true\r\nWidgets\\QgsWmtsDimensionsBase\\buttonBox=true\r\nWidgets\\SimplifyLineDialog=true\r\nWidgets\\SimplifyLineDialog\\horizontalSlider=true\r\nWidgets\\SimplifyLineDialog\\label=true\r\nWidgets\\SimplifyLineDialog\\okButton=true\r\nWidgets\\SimplifyLineDialog\\spinBox=true\r\nWidgets\\SimplifyLineDialog\\spinBox\\qt_spinbox_lineedit=true\r\nstatus=1\r\nMenus\\mLayerMenu\\mActionAddLayerDefinition=true\r\nMenus\\mLayerMenu\\mActionSaveLayerDefinition=true\r\nMenus\\mLayerMenu\\mActionSetLayerScaleVisibility=true\r\nMenus\\mRasterMenu\\analysisMenu=true\r\nMenus\\mRasterMenu\\analysisMenu\\dem=true\r\nMenus\\mRasterMenu\\analysisMenu\\fillNodata=true\r\nMenus\\mRasterMenu\\analysisMenu\\grid=true\r\nMenus\\mRasterMenu\\analysisMenu\\nearBlack=true\r\nMenus\\mRasterMenu\\analysisMenu\\proximity=true\r\nMenus\\mRasterMenu\\analysisMenu\\sieve=true\r\nMenus\\mRasterMenu\\conversionMenu=true\r\nMenus\\mRasterMenu\\conversionMenu\\paletted=true\r\nMenus\\mRasterMenu\\conversionMenu\\polygonize=true\r\nMenus\\mRasterMenu\\conversionMenu\\rasterize=true\r\nMenus\\mRasterMenu\\conversionMenu\\rgb=true\r\nMenus\\mRasterMenu\\conversionMenu\\translate=true\r\nMenus\\mRasterMenu\\extractionMenu=true\r\nMenus\\mRasterMenu\\extractionMenu\\clipper=true\r\nMenus\\mRasterMenu\\extractionMenu\\contour=true\r\nMenus\\mRasterMenu\\miscellaneousMenu=true\r\nMenus\\mRasterMenu\\miscellaneousMenu\\buildVRT=true\r\nMenus\\mRasterMenu\\miscellaneousMenu\\info=true\r\nMenus\\mRasterMenu\\miscellaneousMenu\\merge=true\r\nMenus\\mRasterMenu\\miscellaneousMenu\\overview=true\r\nMenus\\mRasterMenu\\miscellaneousMenu\\tileindex=true\r\nMenus\\mRasterMenu\\projectionsMenu=true\r\nMenus\\mRasterMenu\\projectionsMenu\\extractProj=true\r\nMenus\\mRasterMenu\\projectionsMenu\\projection=true\r\nMenus\\mRasterMenu\\projectionsMenu\\warp=true\r\nMenus\\mRasterMenu\\settings=true\r\nMenus\\mViewMenu\\menuPreview_Mode=true\r\nMenus\\mViewMenu\\menuPreview_Mode\\mActionPreviewDeuteranope=true\r\nMenus\\mViewMenu\\menuPreview_Mode\\mActionPreviewModeGrayscale=true\r\nMenus\\mViewMenu\\menuPreview_Mode\\mActionPreviewModeMono=true\r\nMenus\\mViewMenu\\menuPreview_Mode\\mActionPreviewModeOff=true\r\nMenus\\mViewMenu\\menuPreview_Mode\\mActionPreviewProtanope=true\r\nPanels\\Layers=true\r\nToolbars\\mDatabaseToolBar\\dbManager=true\r\n" }, { "alpha_fraction": 0.4770965576171875, "alphanum_fraction": 0.4806201457977295, "avg_line_length": 36.02678680419922, "blob_id": "19837622389550f59959d0cbbaabe28debaf8595", "content_id": "b6d32acca67b1745b5e11ee497c0a54fe60ca751", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4257, "license_type": "no_license", "max_line_length": 79, "num_lines": 112, "path": "/qgis-installer/rekod-gis/plugins/shortcut_manager/shortcut.py", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n/***************************************************************************\r\n ShortcutManagerDialog\r\n A QGIS plugin\r\n This plugin create shortcuts in toolbar\r\n -------------------\r\n begin : 2014-07-18\r\n git sha : $Format:%H$\r\n copyright : (C) 2014 by NextGIS\r\n email : info@nextgis.ru\r\n ***************************************************************************/\r\n\r\n/***************************************************************************\r\n * *\r\n * This program is free software; you can redistribute it and/or modify *\r\n * it under the terms of the GNU General Public License as published by *\r\n * the Free Software Foundation; either version 2 of the License, or *\r\n * (at your option) any later version. *\r\n * *\r\n ***************************************************************************/\r\n\"\"\"\r\n\r\nfrom PyQt4.QtCore import QObject, QSettings, pyqtSignal\r\n\r\nfrom qgis.core import QgsMessageLog\r\n\r\ndef shortcutsFromSettings():\r\n shortcuts = []\r\n \r\n settings = QSettings()\r\n settings.beginGroup('/NextGIS/ShortcutManager/shortcuts')\r\n shortcuts_names = settings.childGroups()\r\n for shortcut_name in shortcuts_names:\r\n shortcuts.append(Shorcut(shortcut_name))\r\n \r\n return shortcuts\r\n\r\nclass Shorcut(QObject):\r\n updated = pyqtSignal(name = \"updated\")\r\n deleted = pyqtSignal(name = \"deleted\")\r\n \r\n def __init__(self, name, uri = None, icon = None):\r\n super(Shorcut, self).__init__()\r\n \r\n self.settings = QSettings()\r\n self.settings.beginGroup('/NextGIS/ShortcutManager/shortcuts')\r\n \r\n self._name = name\r\n \r\n if self._name in self.settings.childGroups():\r\n self._uri = self.settings.value(\"%s/uri\"%self._name)\r\n self._icon = self.settings.value(\"%s/icon\"%self._name)\r\n #self._directory = self.settings.value(\"%s/_directory\"%self._name)\r\n QgsMessageLog.logMessage(\r\n \"Shortcuts manager. Load shortcut with name: %s\"% self._name,\r\n None, QgsMessageLog.INFO)\r\n else:\r\n self._uri = uri\r\n self._icon = icon\r\n self.settings.setValue(\"%s/uri\"%self._name, self._uri)\r\n self.settings.setValue(\"%s/icon\"%self._name, self._icon)\r\n #self.settings.setValue(\"%s/directory\"%self._name, self._directory)\r\n QgsMessageLog.logMessage(\r\n \"Shortcuts manager. Create shortcut with name: %s\"% self._name,\r\n None, QgsMessageLog.INFO)\r\n \r\n def delete(self):\r\n self.settings.remove(self._name)\r\n self.deleted.emit()\r\n \r\n #def editShortcut(self, name, uri, icon, directory):\r\n def editShortcut(self, name, uri, icon):\r\n if self._name != name:\r\n self.settings.remove(self._name)\r\n \r\n self._name =name\r\n self.settings.setValue(\"%s/uri\"%self._name,self._uri)\r\n self.settings.setValue(\"%s/icon\"%self._name,self._icon)\r\n \r\n if self._uri != uri:\r\n self._uri = uri\r\n self.settings.setValue(\"%s/uri\"%self._name,self._uri)\r\n \r\n if self._icon != icon:\r\n self._icon = icon\r\n self.settings.setValue(\"%s/icon\"%self._name,self._icon)\r\n \r\n QgsMessageLog.logMessage(\r\n \"Shortcuts manager. Edit shortcut with name: %s\"% self._name,\r\n None, QgsMessageLog.INFO)\r\n #if self._directory != directory:\r\n # self._directory = directory\r\n # self.settings.setValue(\"%s/directory\"%self._name,self._directory)\r\n \r\n self.updated.emit()\r\n \r\n @property\r\n def name(self):\r\n return self._name\r\n \r\n @property\r\n def uri(self):\r\n return self._uri\r\n \r\n @property\r\n def icon(self):\r\n return self._icon\r\n \r\n #@property\r\n #def directory(self):\r\n # return self._directory" }, { "alpha_fraction": 0.4823615849018097, "alphanum_fraction": 0.4897109270095825, "avg_line_length": 40.103092193603516, "blob_id": "fd87abfc899d52b5c91460bfa659f395dc384cd4", "content_id": "cbb19ae5dfe57ed5944ccedda6683a3a3cea9e8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4082, "license_type": "no_license", "max_line_length": 101, "num_lines": 97, "path": "/qgis-installer/rekod-gis/plugins/shortcut_manager/shortcut_settings.py", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n/***************************************************************************\r\n ShortcutManagerDialog\r\n A QGIS plugin\r\n This plugin create shortcuts in toolbar\r\n -------------------\r\n begin : 2014-07-18\r\n git sha : $Format:%H$\r\n copyright : (C) 2014 by NextGIS\r\n email : info@nextgis.ru\r\n ***************************************************************************/\r\n\r\n/***************************************************************************\r\n * *\r\n * This program is free software; you can redistribute it and/or modify *\r\n * it under the terms of the GNU General Public License as published by *\r\n * the Free Software Foundation; either version 2 of the License, or *\r\n * (at your option) any later version. *\r\n * *\r\n ***************************************************************************/\r\n\"\"\"\r\n\r\nfrom shortcut_utils import getShortcutIcon\r\nfrom shortcut_settings_ui_base import Ui_ShortcutSettings\r\nfrom __init__ import default_icons_dir\r\n\r\nfrom PyQt4.QtGui import QDialog, QFileDialog, QIcon\r\nfrom PyQt4.QtCore import QObject, SIGNAL, QSize\r\n\r\nimport os\r\n\r\nclass ShortcutSettings(QDialog, Ui_ShortcutSettings):\r\n def __init__(self, parent, shortcut):\r\n QDialog.__init__(self, parent)\r\n self.setupUi(self)\r\n \r\n self._shortcut = shortcut\r\n \r\n self._shortcutName_le.setText(self._shortcut.name)\r\n \r\n if self._shortcut.uri is not None:\r\n self._shortcutURI_le.setText(self._shortcut.uri)\r\n \r\n shortcutIcon = getShortcutIcon(\r\n self._shortcut.icon,\r\n self._shortcut.uri)\r\n self._shortcutIcon_l.setPixmap(shortcutIcon.pixmap(QSize(32,32)))\r\n \r\n self._shortcutNewIcon = self._shortcut.icon\r\n QObject.connect(self._changeIconBtn, SIGNAL(\"clicked()\"), self._chooseIcon)\r\n QObject.connect(self.pbSetDefaultIcon, SIGNAL(\"clicked()\"), self._setDefaultIcon)\r\n \r\n def _chooseIcon(self):\r\n fileName = QFileDialog.getOpenFileName(self,\r\n self.tr(\"Select icon file\"),\r\n default_icons_dir\r\n )\r\n if fileName != \"\":\r\n self._shortcutNewIcon = os.path.normpath(unicode(fileName))\r\n self._shortcutIcon_l.setPixmap( QIcon(self._shortcutNewIcon).pixmap(QSize(32,32)) )\r\n \r\n def _setDefaultIcon(self):\r\n self._shortcutNewIcon = None\r\n shortcutIcon = getShortcutIcon(\r\n self._shortcutNewIcon,\r\n self._shortcut.uri)\r\n self._shortcutIcon_l.setPixmap(shortcutIcon.pixmap(QSize(32,32)))\r\n \r\n def _validatePage(self):\r\n isValid = True\r\n \r\n if self._shortcutName_le.text() == \"\":\r\n self._shortcutName_le.setPlaceholderText(self.tr(\"Please, fill this field\"))\r\n isValid = False\r\n \r\n if self._shortcutURI_le.text() == \"\":\r\n self._shortcutURI_le.setPlaceholderText(self.tr(\"Please, fill this field\"))\r\n isValid = False\r\n \r\n return isValid\r\n \r\n def accept(self):\r\n \r\n if self._validatePage() == False:\r\n return\r\n \r\n self.shortcutNewName = self._shortcutName_le.text()\r\n self.shortcutNewURI = self._shortcutURI_le.text()\r\n \r\n if self._shortcutNewIcon is not None:\r\n if self._shortcutNewIcon.lower().find(default_icons_dir.lower()) == 0:\r\n self._shortcutNewIcon = self._shortcutNewIcon[len(default_icons_dir)+1:]\r\n \r\n self._shortcut.editShortcut(self.shortcutNewName, self.shortcutNewURI, self._shortcutNewIcon)\r\n \r\n QDialog.accept(self)" }, { "alpha_fraction": 0.6287795901298523, "alphanum_fraction": 0.6320582628250122, "avg_line_length": 47.83636474609375, "blob_id": "d60a0ec610a7de9462fa037b214454e0cc8c84a1", "content_id": "525e4b2b67f457b2443846657bb7832c359f2d8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2745, "license_type": "no_license", "max_line_length": 114, "num_lines": 55, "path": "/geosync/include/version.h", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "/******************************************************************************\r\n * Project: geosync\r\n * Purpose: version functions\r\n * Author: Baryshnikov Dmitry (aka Bishop), polimax@mail.ru\r\n ******************************************************************************\r\n* Copyright (C) 2014 NextGIS\r\n*\r\n* This program is free software: you can redistribute it and/or modify\r\n* it under the terms of the GNU General Public License as published by\r\n* the Free Software Foundation, either version 3 of the License, or\r\n* (at your option) any later version.\r\n*\r\n* This program is distributed in the hope that it will be useful,\r\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n* GNU General Public License for more details.\r\n*\r\n* You should have received a copy of the GNU General Public License\r\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\r\n ****************************************************************************/\r\n#pragma once\r\n\r\n#include \"wx/version.h\"\r\n\r\n/* NB: this file is parsed by automatic tools so don't change its format! */\r\n#define GEOSYNC_MAJOR_VERSION 1\r\n#define GEOSYNC_MINOR_VERSION 0\r\n#define GEOSYNC_RELEASE_NUMBER 0\r\n#define GEOSYNC_SUBRELEASE_NUMBER 0\r\n\r\n/* these are used by version.rc and should always be ASCII, not Unicode */\r\n#define GEOSYNC_VERSION_NUM_STRING \\\r\n wxMAKE_VERSION_STRING(GEOSYNC_MAJOR_VERSION, GEOSYNC_MINOR_VERSION, GEOSYNC_RELEASE_NUMBER)\r\n#define GEOSYNC_VERSION_NUM_DOT_STRING \\\r\n wxMAKE_VERSION_DOT_STRING(GEOSYNC_MAJOR_VERSION, GEOSYNC_MINOR_VERSION, GEOSYNC_RELEASE_NUMBER)\r\n\r\n/* those are Unicode-friendly */\r\n#define GEOSYNC_VERSION_NUM_STRING_T \\\r\n wxMAKE_VERSION_STRING_T(GEOSYNC_MAJOR_VERSION, GEOSYNC_MINOR_VERSION, GEOSYNC_RELEASE_NUMBER)\r\n#define GEOSYNC_VERSION_NUM_DOT_STRING_T \\\r\n wxMAKE_VERSION_DOT_STRING_T(GEOSYNC_MAJOR_VERSION, GEOSYNC_MINOR_VERSION, GEOSYNC_RELEASE_NUMBER)\r\n\r\n/* check if the current version is at least major.minor.release */\r\n#define GEOSYNC_CHECK_VERSION(major,minor,release) \\\r\n (GEOSYNC_MAJOR_VERSION > (major) || \\\r\n (GEOSYNC_MAJOR_VERSION == (major) && GEOSYNC_MINOR_VERSION > (minor)) || \\\r\n (GEOSYNC_MAJOR_VERSION == (major) && GEOSYNC_MINOR_VERSION == (minor) && GEOSYNC_RELEASE_NUMBER >= (release)))\r\n\r\n/* the same but check the subrelease also */\r\n#define GEOSYNC_CHECK_VERSION_FULL(major,minor,release,subrel) \\\r\n (wxCHECK_VERSION(major, minor, release) && \\\r\n ((major) != GEOSYNC_MAJOR_VERSION || \\\r\n (minor) != GEOSYNC_MINOR_VERSION || \\\r\n (release) != GEOSYNC_RELEASE_NUMBER || \\\r\n (subrel) <= GEOSYNC_SUBRELEASE_NUMBER))\r\n\r\n\r\n" }, { "alpha_fraction": 0.6922300457954407, "alphanum_fraction": 0.7124117016792297, "avg_line_length": 37.63999938964844, "blob_id": "3f3d02213f90377d41e71d9558d00df387e5edfb", "content_id": "9bc5b971adfa72a32062d46ca93c648fdafc3fa2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 991, "license_type": "no_license", "max_line_length": 177, "num_lines": 25, "path": "/geosync/cmake/lib.cmake", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "project (wxgis${PROJECT_NAME})\r\n\r\nset(CMAKE_CONFIGURATION_TYPES \"Debug;Release\" CACHE STRING \"Configs\" FORCE)\r\n\r\nif(WIN32)\r\n set(LIB_NAME ${PROJECT_NAME}${wxGISMON_MAJOR_VERSION}${wxGISMON_MINOR_VERSION})\r\nelse(WIN32)\r\n set(LIB_NAME ${PROJECT_NAME})\r\nendif(WIN32)\r\nmessage(STATUS \"${PROJECT_NAME} lib name ${LIB_NAME}\")\r\n\r\ninclude_directories(${CMAKE_CURRENT_BINARY_DIR})\r\nfile(WRITE ${CMAKE_CURRENT_BINARY_DIR}/version_dll.h \"//Copyright (C) 2007-2014 Baryshnikov Dmitry (aka Bishop), polimax@mail.ru\\n#pragma once\\n#define wxGISMON_FILENAME \\\"${PROJECT_NAME}\\\" \\n\\n\" )\r\n\r\nif(MSVC)\r\n set(CMAKE_DEBUG_POSTFIX \"d\")\r\n add_definitions(-D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE)\r\n add_definitions(-D_UNICODE -DUNICODE -D_USRDLL)\r\n set(PROJECT_CSOURCES ${PROJECT_CSOURCES} ${WXGISMON_CURRENT_SOURCE_DIR}/src/version_dll.rc)\r\n source_group(\"Resource Files\" FILES ${WXGISMON_CURRENT_SOURCE_DIR}/src/version_dll.rc) \r\nendif(MSVC)\r\n\r\nif(WIN32)\r\n add_definitions(-DWIN32 -D__WXMSW__)\r\nendif(WIN32)\r\n" }, { "alpha_fraction": 0.6590774655342102, "alphanum_fraction": 0.6643997430801392, "avg_line_length": 30.59813117980957, "blob_id": "46667480f5d67b513da43877cd40e6f2a079f418", "content_id": "2c3b8aa0c2eae3b507459ebfc2591b0ecf2e1613", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 3382, "license_type": "no_license", "max_line_length": 79, "num_lines": 107, "path": "/geosync/src/task/CMakeLists.txt", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "# **************************************************************************** \n# * Project: geosync\n# * Purpose: cmake script\n# * Author: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru\n# ****************************************************************************\n# * Copyright (C) 2014 Bishop\n# * Copyright (C) 2014 NextGIS\n# *\n# * This program is free software: you can redistribute it and/or modify\n# * it under the terms of the GNU General Public License as published by\n# * the Free Software Foundation, either version 3 of the License, or\n# * (at your option) any later version.\n# *\n# * This program is distributed in the hope that it will be useful,\n# * but WITHOUT ANY WARRANTY; without even the implied warranty of\n# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# * GNU General Public License for more details.\n# *\n# * You should have received a copy of the GNU General Public License\n# * along with this program. If not, see <http://www.gnu.org/licenses/>.\n# ****************************************************************************\ncmake_minimum_required (VERSION 2.8)\nset(PROJECT_NAME taskapp)\nset(APP_NAME synctask)\nset(GEOSYNC_MAINFAMEICON \"${GEOSYNC_CURRENT_SOURCE_DIR}/art/geosync.ico\")\n\ninclude(app)\nadd_definitions(-DwxUSE_GUI=0)\n\nset(APP_HEADERS ${GEOSYNC_CURRENT_SOURCE_DIR}/include/task)\nset(APP_SOURCES ${GEOSYNC_CURRENT_SOURCE_DIR}/src/task)\n\nif(WIN32)\n set(wxWidgets_EXCLUDE_COMMON_LIBRARIES TRUE)\nendif(WIN32)\n\nfind_package(wxWidgets 2.9 REQUIRED base core xml)\nif(wxWidgets_FOUND)\n include(${wxWidgets_USE_FILE})\nendif(wxWidgets_FOUND)\n\nfind_package(WXGIS REQUIRED core datasource catalog carto)\nif(WXGIS_FOUND)\n include_directories(${WXGIS_INCLUDE_DIR})\nendif(WXGIS_FOUND)\n\nfind_package(CURL REQUIRED)\nif(CURL_FOUND)\n include_directories(${CURL_INCLUDE_DIRS})\n add_definitions(-DHAVE_CURL)\nendif(CURL_FOUND)\n\nfind_package(CAIRO REQUIRED)\nif(CAIRO_FOUND)\n include_directories(${CAIRO_INCLUDE_DIR})\n add_definitions(-DHAVE_CAIRO)\nendif(CAIRO_FOUND)\n\n#find needed packages\nfind_package(GDAL REQUIRED)\nif(GDAL_FOUND)\n FOREACH(file_path ${GDAL_INCLUDE_DIR})\n include_directories(${file_path}/ogr)\n include_directories(${file_path}/ogr/ogrsf_frmts)\n include_directories(${file_path}/port)\n include_directories(${file_path}/gcore)\n# include_directories(${file_path}/alg)\n# include_directories(${file_path}/frmts/vrt)\n ENDFOREACH() \nendif(GDAL_FOUND)\n\nset(PROJECT_HHEADERS ${PROJECT_HHEADERS} \n ${APP_HEADERS}/taskapp.h \n ${APP_HEADERS}/task.h\n)\n\nset(PROJECT_CSOURCES ${PROJECT_CSOURCES}\n ${APP_SOURCES}/taskapp.cpp\n ${APP_SOURCES}/task.cpp\n)\n\nadd_executable(${APP_NAME} ${PROJECT_HHEADERS} ${PROJECT_CSOURCES})\n#set_target_properties(${APP_NAME} PROPERTIES ENABLE_EXPORTS TRUE)\n\nif(wxWidgets_FOUND)\n target_link_libraries(${APP_NAME} ${wxWidgets_LIBRARIES})\nendif(wxWidgets_FOUND)\n\nif(WXGIS_FOUND)\n target_link_libraries(${APP_NAME} ${WXGIS_LIBRARIES})\nendif(WXGIS_FOUND)\n\nif(GDAL_FOUND)\n target_link_libraries(${APP_NAME} ${GDAL_LIBRARIES})\nendif(GDAL_FOUND) \n\nif(CURL_FOUND)\n target_link_libraries(${APP_NAME} ${CURL_LIBRARIES})\nendif(CURL_FOUND)\n\nif(CAIRO_FOUND)\n target_link_libraries(${APP_NAME} ${CAIRO_LIBRARIES})\nendif(CAIRO_FOUND)\n\ntarget_link_libraries(${APP_NAME} ${WXGISREMMON_LIB_NAME})\n\ninclude(installapp)\n\n" }, { "alpha_fraction": 0.7532327771186829, "alphanum_fraction": 0.7769396305084229, "avg_line_length": 42.095237731933594, "blob_id": "7e1d9ccf823e319a681a9724dc1d692dc66b8467", "content_id": "69bc49b055d4e5c5f1248ca0be56504bb86839d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 928, "license_type": "no_license", "max_line_length": 102, "num_lines": 21, "path": "/qgis-installer/src/qgis_builder_new.ini", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "[Download]\r\ntag = final-2_6_0\r\n\r\n[Patching]\r\nfilename = D:/Development/NextGIS/rekod-storage/qgis-installer/src/TMSforST/diff.patch\r\nicon = D:/Development/NextGIS/rekod-storage/qgis-installer/src/TMSforST/qgis.ico\r\nsplash = D:/Development/NextGIS/rekod-storage/qgis-installer/src/TMSforST/splash.png\r\nqgis-icon-16x16 = D:/Development/NextGIS/rekod-storage/qgis-installer/src/TMSforST/qgis-icon-16x16.png\r\nqgis-icon-60x60 = D:/Development/NextGIS/rekod-storage/qgis-installer/src/TMSforST/qgis-icon-60x60.png\r\n\r\n[QGIS]\r\nsrc_dir = D:\\Development\\NextGIS\\qgis\r\n\r\n[NextGIS QGIS Building]\r\ngdal = D:\\builds\\gdal-2.0.0-dev\r\ncmake_configuration = D:/Development/NextGIS/rekod-storage/qgis-installer/configure_qgis.bat\r\nbuild_path = C:\\builds\\nextgis-qgis-rekod-tmsforst-build\r\ninstall_path = C:\\builds\\nextgis-qgis-rekod-tmsforst\r\n\r\n[Installer]\r\nnsis_filename = D:/Development/NextGIS/rekod-storage/qgis-installer/NSIS/TMSforST.nsi\r\n\r\n" }, { "alpha_fraction": 0.6320141553878784, "alphanum_fraction": 0.6396928429603577, "avg_line_length": 31.176469802856445, "blob_id": "751c3cdc0e695dc621c0b8027cca1437d7540839", "content_id": "07273ae8d6caeacd8bf830522a0db99cb23cd13b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 3386, "license_type": "no_license", "max_line_length": 85, "num_lines": 102, "path": "/geosync/src/app/CMakeLists.txt", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "# **************************************************************************** \r\n# * Project: geosync\r\n# * Purpose: cmake script\r\n# * Author: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru\r\n# ****************************************************************************\r\n# * Copyright (C) 2014 Dmitry Baryshnikov\r\n# * Copyright (C) 2014 NextGIS\r\n# *\r\n# * This program is free software: you can redistribute it and/or modify\r\n# * it under the terms of the GNU General Public License as published by\r\n# * the Free Software Foundation, either version 3 of the License, or\r\n# * (at your option) any later version.\r\n# *\r\n# * This program is distributed in the hope that it will be useful,\r\n# * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# * GNU General Public License for more details.\r\n# *\r\n# * You should have received a copy of the GNU General Public License\r\n# * along with this program. If not, see <http://www.gnu.org/licenses/>.\r\n# ****************************************************************************\r\ncmake_minimum_required (VERSION 2.8)\r\nset(PROJECT_NAME app)\r\nset(APP_NAME geosync)\r\nset(GEOSYNC_MAINFAMEICON \"${GEOSYNC_CURRENT_SOURCE_DIR}/art/geosync.ico\")\r\n\r\ninclude(app)\r\nadd_definitions(-DwxUSE_GUI=1)\r\n\r\nset(APP_HEADERS ${GEOSYNC_CURRENT_SOURCE_DIR}/include/app)\r\nset(APP_SOURCES ${GEOSYNC_CURRENT_SOURCE_DIR}/src/app)\r\n\r\nif(WIN32)\r\n set(wxWidgets_EXCLUDE_COMMON_LIBRARIES TRUE)\r\nendif(WIN32)\r\n\r\nfind_package(wxWidgets 2.9 REQUIRED base core adv net)\r\nif(wxWidgets_FOUND)\r\n include(${wxWidgets_USE_FILE})\r\nendif(wxWidgets_FOUND)\r\n\r\nfind_package(CURL REQUIRED)\r\nif(CURL_FOUND)\r\n include_directories(${CURL_INCLUDE_DIRS})\r\n add_definitions(-DHAVE_CURL)\r\nendif(CURL_FOUND)\r\n\r\nfind_package(WXGIS REQUIRED core net catalog catalogui geoprocessing geoprocessingui)\r\nif(WXGIS_FOUND)\r\n include_directories(${WXGIS_INCLUDE_DIR})\r\nendif(WXGIS_FOUND)\r\n\r\n#find needed packages\r\nfind_package(GDAL REQUIRED)\r\nif(GDAL_FOUND)\r\n FOREACH(file_path ${GDAL_INCLUDE_DIR})\r\n include_directories(${file_path}/ogr)\r\n include_directories(${file_path}/ogr/ogrsf_frmts)\r\n include_directories(${file_path}/port)\r\n include_directories(${file_path}/gcore)\r\n# include_directories(${file_path}/alg)\r\n# include_directories(${file_path}/frmts/vrt)\r\n ENDFOREACH() \r\nendif(GDAL_FOUND)\r\n\r\nset(PROJECT_HHEADERS ${PROJECT_HHEADERS} \r\n ${APP_HEADERS}/app.h\r\n ${APP_HEADERS}/tskmngr.h\r\n ${APP_HEADERS}/tasksdlg.h\r\n)\r\n\r\nset(PROJECT_CSOURCES ${PROJECT_CSOURCES}\r\n ${APP_SOURCES}/app.cpp\r\n ${APP_SOURCES}/tskmngr.cpp\r\n ${APP_SOURCES}/tasksdlg.cpp\r\n)\r\n\r\nif(WIN32)\r\n add_executable(${APP_NAME} WIN32 ${PROJECT_HHEADERS} ${PROJECT_CSOURCES})\r\nelse(WIN32)\r\n add_executable(${APP_NAME} ${PROJECT_HHEADERS} ${PROJECT_CSOURCES})\r\nendif(WIN32)\r\n\r\n#set_target_properties(${APP_NAME} PROPERTIES ENABLE_EXPORTS TRUE)\r\n\r\nif(wxWidgets_FOUND)\r\n target_link_libraries(${APP_NAME} ${wxWidgets_LIBRARIES})\r\nendif(wxWidgets_FOUND)\r\n\r\nif(WXGIS_FOUND)\r\n target_link_libraries(${APP_NAME} ${WXGIS_LIBRARIES})\r\nendif(WXGIS_FOUND)\r\n\r\nif(GDAL_FOUND)\r\n target_link_libraries(${APP_NAME} ${GDAL_LIBRARIES})\r\nendif(GDAL_FOUND) \r\n\r\nif(CURL_FOUND)\r\n target_link_libraries(${APP_NAME} ${CURL_LIBRARIES})\r\nendif(CURL_FOUND)\r\n\r\ninclude(installapp)\r\n\r\n" }, { "alpha_fraction": 0.6766743659973145, "alphanum_fraction": 0.6787272095680237, "avg_line_length": 32.31623840332031, "blob_id": "d495c21b2b48d5edca3d31e5af7bd7b262720cd8", "content_id": "0c12f8c1ed2771c8cdc2d4b53695e6bf527ec3ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3897, "license_type": "no_license", "max_line_length": 108, "num_lines": 117, "path": "/geosync/include/task/taskapp.h", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "/******************************************************************************\n* Project: geosync\n* Purpose: sync spatial data with NGW\n* Author: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru\n******************************************************************************\n* Copyright (C) 2014 NextGIS\n*\n* This program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n****************************************************************************/\n#pragma once\n\n#include \"wxgis/base.h\"\n#include \"wxgis/core/core.h\"\n#include \"wxgis/core/process.h\"\n#include \"wxgis/core/init.h\"\n#include \"wxgis/core/app.h\"\n#include \"version.h\"\n\n#include <wx/app.h>\n#include <wx/cmdline.h>\n\n#include \"wx/wfstream.h\"\n#include \"wx/txtstrm.h\"\n#include \"wx/ffile.h\"\n\n#ifdef wxGIS_USE_POSTGRES\n #undef wxGIS_USE_POSTGRES\n#endif\n\nenum geoSyncDirection{\n geoSyncLocal2Remote = 1,\n geoSyncRemote2Local,\n geoSyncBoth\n};\n\n/** @class GeoSyncTaskApp\n \n Main spatial data sync task application\n*/\nclass GeoSyncTaskApp :\n\tpublic wxAppConsole,\n\tpublic wxGISInitializer,\n public ITrackCancel,\n\tpublic IProgressor, \n public wxGISThreadHelper\n{\npublic:\n GeoSyncTaskApp(void);\n virtual ~GeoSyncTaskApp(void);\n //wxAppConsole\n virtual bool OnInit();\n virtual void CleanUp();\n virtual int OnRun();\n void OnInitCmdLine(wxCmdLineParser& pParser);\n bool OnCmdLineParsed(wxCmdLineParser& pParser);\n // ITrackCancel\n\tvirtual void PutMessage(const wxString &sMessage, size_t nIndex, wxGISEnumMessageType nType);\n // IProgressor\n virtual bool ShowProgress(bool){return true;};//always shown\n virtual void SetValue(int value);\n virtual int GetValue(void) const {return m_nValue;};\n virtual bool Show(bool bShow){return true;};\n virtual void SetRange(int range){m_nRange = range;};\n virtual int GetRange(void) const {return m_nRange;};\n virtual void Play(void){};\n virtual void Stop(void){};\n\tvirtual void SetYield(bool bYield = false){};\n //wxGISInitializer\n\tvirtual bool Initialize(const wxString &sAppName, const wxString &sLogFilePrefix);\n // IApplication\n virtual wxString GetAppName(void) const { return m_appName; };\n virtual wxString GetAppDisplayName(void) const{ return m_appDisplayName; };\n virtual wxString GetAppDisplayNameShort(void) const { return wxString(_(\"Geo Sync Task\")); };\n virtual wxString GetAppVersionString(void) const { return wxString(GEOSYNC_VERSION_NUM_DOT_STRING_T); };\n virtual void OnAppAbout(void);\n virtual void OnAppOptions(void);\n virtual bool SetupSys(const wxString &sSysPath);\n //exceptions\n virtual bool \tOnExceptionInMainLoop();\n virtual void \tOnFatalException();\n virtual void \tOnUnhandledException();\nprotected:\n //wxGISThreadHelper\n virtual wxThread::ExitCode Entry();\n virtual void AddMessage(const wxString& sMessage);\n virtual wxString GetMessage();\nprotected:\n int m_nValue;\n int m_nRange;\n wxString m_sPrevMsg;\n wxFFile m_StdOutFile;\n wxFFileOutputStream *m_pFFileOutputStream;\n wxTextOutputStream *m_pOutTxtStream;\n wxCriticalSection m_CritSec;\n\n wxString m_sLocalPath;\n wxString m_sURL, m_sUser, m_sPasswd;\n long m_nRemoteId;\n geoSyncDirection m_eDirection;\n\n int m_nExitStatus;\n\n wxArrayString m_saMessages;\n};\n\nDECLARE_APP(GeoSyncTaskApp)" }, { "alpha_fraction": 0.8349514603614807, "alphanum_fraction": 0.8349514603614807, "avg_line_length": 103, "blob_id": "d2d725aa9dd68547935539e68effa6681a5d6a6b", "content_id": "a67df5f75893b3c67b06e67adbfcd6e664a6cf7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 103, "license_type": "no_license", "max_line_length": 103, "num_lines": 1, "path": "/ngm_branding/README.md", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "Branding files and NSIS installer script for NextGIS Manager. Put this directories to the sources root." }, { "alpha_fraction": 0.5895015001296997, "alphanum_fraction": 0.5959214568138123, "avg_line_length": 45.438594818115234, "blob_id": "241b776fd4b2e56184b4c83dd3937897e3949e1e", "content_id": "63e93f02b632c953842d94fb0ac1371eb7316365", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 2648, "license_type": "no_license", "max_line_length": 175, "num_lines": 57, "path": "/geosync/opt/CMakeLists.txt", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "# **************************************************************************** \n# * Project: wxGIS\n# * Purpose: cmake script\n# * Author: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru\n# ****************************************************************************\n# * Copyright (C) 2013-2014 Dmitry Baryshnikov\n# *\n# * This program is free software: you can redistribute it and/or modify\n# * it under the terms of the GNU General Public License as published by\n# * the Free Software Foundation, either version 2 of the License, or\n# * (at your option) any later version.\n# *\n# * This program is distributed in the hope that it will be useful,\n# * but WITHOUT ANY WARRANTY; without even the implied warranty of\n# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# * GNU General Public License for more details.\n# *\n# * You should have received a copy of the GNU General Public License\n# * along with this program. If not, see <http://www.gnu.org/licenses/>.\n# ****************************************************************************\n\ncmake_minimum_required (VERSION 2.8)\n\nfind_program(EXE_MSGFMT msgfmt)\n\nset(MB_LANG \"ru\" \"cs\" \"es\" \"gl_es\" \"pt\" \"pt_BR\")\n\nif(EXE_MSGFMT)\n set(MO_FILES)\n foreach(LANG ${MB_LANG}) \n message(STATUS \"process ${LANG} translation\")\n file(MAKE_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}/loc/${LANG}\")\n file(GLOB inFiles RELATIVE \"${CMAKE_CURRENT_SOURCE_DIR}\" \"${CMAKE_CURRENT_SOURCE_DIR}/loc/${LANG}/*.po\")\n foreach(PO ${inFiles})\n GET_FILENAME_COMPONENT(MO_NAME ${PO} NAME_WE)\n set(MO ${CMAKE_CURRENT_BINARY_DIR}/loc/${LANG}/${MO_NAME}.mo)\n message(STATUS \"process ${MO}\")\n set(MO_FILES ${MO_FILES} ${MO})\n add_custom_command(\n OUTPUT ${MO}\n COMMAND ${EXE_MSGFMT} -o ${MO} ${PO}\n WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}\n DEPENDS ${PO})\n endforeach()\n endforeach()\n add_custom_target(create-mo ALL DEPENDS ${MO_FILES})\nelse()\n message(STATUS \"msgfmt not found, translations not generatied\")\nendif()\n\nif(WIN32)\n install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/loc/ DESTINATION ${WXGIS_CURRENT_BINARY_DIR}/Debug/locale CONFIGURATIONS Debug FILES_MATCHING PATTERN \"*.mo\" PATTERN \"*.txt\")\n install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/loc/ DESTINATION locale CONFIGURATIONS Release FILES_MATCHING PATTERN \"*.mo\" PATTERN \"*.txt\")\nelse(WIN32)#UNIX\n file(MAKE_DIRECTORY share/wxgis)\n install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/loc/ DESTINATION share/wxgis/locale FILES_MATCHING PATTERN \"*.mo\" PATTERN \"*.txt\")\nendif(WIN32)\n\n" }, { "alpha_fraction": 0.676462709903717, "alphanum_fraction": 0.6777985692024231, "avg_line_length": 35.686275482177734, "blob_id": "b7eff6563cf9ab84a932eadf3861d9fd6e82aa73", "content_id": "37f936c5cfcf019e04c82defa1970fa47094d3c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3743, "license_type": "no_license", "max_line_length": 278, "num_lines": 102, "path": "/geosync/include/app/tasksdlg.h", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "/******************************************************************************\n* Project: geosync\n* Purpose: sync spatial data with NGW\n* Author: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru\n******************************************************************************\n* Copyright (C) 2014 NextGIS\n*\n* This program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n****************************************************************************/\n#pragma once\n\n#include \"wx/intl.h\"\n#include \"wx/gdicmn.h\"\n#include \"wx/string.h\"\n#include \"wx/sizer.h\"\n#include \"wx/button.h\"\n#include \"wx/dialog.h\"\n#include \"wx/listctrl.h\"\n\n#include \"wxgis/geoprocessingui/gpcontrols.h\"\n#include \"wxgis/geoprocessing/task.h\"\n\n#define GEOSYNCCAT wxT(\"geosync\")\n\n/** @class CreateGeoSyncTaskDlg\n \n A dialog to create new sync task\n*/\n\nclass CreateGeoSyncTaskDlg : public wxDialog\n{\npublic:\n CreateGeoSyncTaskDlg(wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _(\"Add new sync task\"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxCAPTION | wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER | wxCLIP_CHILDREN);\n ~CreateGeoSyncTaskDlg();\n bool IsValid(void);\n //events\n void OnOKUI(wxUpdateUIEvent & event);\n void OnOk(wxCommandEvent & event);\nprotected:\n wxButton* m_sdbSizerOk;\n wxVector<wxGISDTBase*> m_paControls;\n wxGISGPParameterArray m_Parameters;\nprivate:\n DECLARE_EVENT_TABLE()\n};\n\n/** @class GeoSyncTaskDlg\n\n A geo sync task dialog. A dialog provide create, delete, start, stop tasks and show their properties \n */\n#define LISTSTYLE (wxLC_REPORT | wxLC_AUTOARRANGE | wxLC_NO_SORT_HEADER) //wxLC_LIST| wxBORDER_NONE | wxLC_SORT_ASCENDING | wxLC_EDIT_LABELS\n\n\nclass GeoSyncTaskDlg : public wxDialog\n{\npublic:\n GeoSyncTaskDlg(wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _(\"GeoSync Tasks\"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);\n ~GeoSyncTaskDlg();\n //event\n void OnAddTask(wxCommandEvent& event);\n void OnAddTaskUI(wxUpdateUIEvent& event);\n void OnRemoveTask(wxCommandEvent& event);\n void OnRemoveTaskUI(wxUpdateUIEvent& event);\n void OnStartTask(wxCommandEvent& event);\n void OnStartTaskUI(wxUpdateUIEvent& event);\n void OnStopTask(wxCommandEvent& event);\n void OnStopTaskUI(wxUpdateUIEvent& event);\n void OnTaskAdded(wxGISTaskEvent& event);\n void OnTaskDeleted(wxGISTaskEvent& event);\n void OnTaskChanged(wxGISTaskEvent& event);\n typedef struct _taskinfo{\n long nCookie;\n long nId;\n wxGISTaskBase* pTask;\n } TASKINFO;\nprotected:\n virtual void SerializeFramePos(bool bSave = false);\n virtual void FillList();\n virtual void AddTask(wxGISTask* pTask);\n virtual void SetItems(long nItem, wxGISTask* pTask);\n virtual void RefreshAll();\n virtual void RemoveAll();\nprotected:\n wxListCtrl *m_pTaskList;\n wxVector<TASKINFO> m_staTasksCookie;\n wxGISTaskCategory *m_pGeoSyncCat;\n long m_nCatCookie;\n wxImageList m_ImageList;\nprivate:\n DECLARE_EVENT_TABLE()\n};\n\n" }, { "alpha_fraction": 0.6147540807723999, "alphanum_fraction": 0.6171584725379944, "avg_line_length": 28.8045597076416, "blob_id": "a1404400a5ae98d9f21d8d1c0b5a49abb4abb44c", "content_id": "f2448f14d4d586c973bd639bb01b6977cf567c92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9150, "license_type": "no_license", "max_line_length": 243, "num_lines": 307, "path": "/geosync/src/task/taskapp.cpp", "repo_name": "nextgis/rekod_storage", "src_encoding": "UTF-8", "text": "/******************************************************************************\n* Project: geosync\n* Purpose: sync spatial data with NGW\n* Author: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru\n******************************************************************************\n* Copyright (C) 2014 NextGIS\n*\n* This program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n****************************************************************************/\n\n#include \"task/taskapp.h\"\n#include \"task/task.h\"\n\n//-----------------------------------------------------------------------------\n// GeoSyncTaskApp\n//-----------------------------------------------------------------------------\n\nIMPLEMENT_APP_CONSOLE(GeoSyncTaskApp)\n\nGeoSyncTaskApp::GeoSyncTaskApp(void) : wxAppConsole(), wxGISThreadHelper()\n{\n m_vendorName = wxString(VENDOR);\n m_vendorDisplayName = wxString(wxT(\"GeoSync\"));\n m_appName = wxString(wxT(\"geosynctask\"));\n m_appDisplayName = wxString(wxT(\"Spatial data syncronization task\"));\n m_className = wxString(wxT(\"GeoSyncTaskApp\"));\n}\n\nGeoSyncTaskApp::~GeoSyncTaskApp(void)\n{ \n}\n\nint GeoSyncTaskApp::OnRun()\n{\n m_nExitStatus = EXIT_FAILURE;\n \n if (!Initialize(m_appName, \"geosynctask_\"))\n return m_nExitStatus;\n\n \n CreateAndRunThread();\n\n GeoSyncTask oTask(m_sLocalPath, m_sURL, m_sUser, m_sPasswd, m_nRemoteId, m_eDirection);\n if (oTask.Execute(this))\n m_nExitStatus = EXIT_SUCCESS;\n else\n PutMessage(_(\"The program encountered an error\"), wxNOT_FOUND, enumGISMessageError);\n\n //wxAppConsole::OnRun();\n\n KillThread();\n\n return m_nExitStatus;\n}\n\nbool GeoSyncTaskApp::OnInit()\n{\n m_StdOutFile.Attach(stdout);\n m_pFFileOutputStream = new wxFFileOutputStream(m_StdOutFile);\n\tm_pOutTxtStream = new wxTextOutputStream(*m_pFFileOutputStream, wxEOL_NATIVE, *wxConvCurrent);//wxConvUTF8\n\n SetProgressor(static_cast<IProgressor*>(this));\n\n //send interesting things to console\n return wxAppConsole::OnInit();\n}\n\nvoid GeoSyncTaskApp::CleanUp()\n{\n Uninitialize();\n \n wxDELETE(m_pOutTxtStream);\n wxDELETE(m_pFFileOutputStream);\n \n wxAppConsole::CleanUp();\n}\n\nvoid GeoSyncTaskApp::OnInitCmdLine(wxCmdLineParser& pParser)\n{\n wxAppConsole::OnInitCmdLine(pParser);\n //common\n pParser.AddSwitch(wxT( \"v\" ), wxT( \"version\" ), _( \"The version of this program\" ));\n //main parameters\n pParser.AddOption(wxT(\"l\"), wxT(\"local\"), _(\"local sync path\"));\n pParser.AddOption(wxT(\"u\"), wxT(\"url\"), _(\"NGW URL\"));\n pParser.AddOption(wxT(\"ru\"), wxT(\"user\"), _(\"NGW login\"));\n pParser.AddOption(wxT(\"rp\"), wxT(\"passwd\"), _(\"NGW Password\"));\n pParser.AddOption(wxT(\"id\"), wxT(\"id\"), _(\"resource group id\"), wxCMD_LINE_VAL_NUMBER);\n pParser.AddOption(wxT(\"d\"), wxT(\"direction\"), _(\"sync direction [local2remote|remote2local|both]\"));\n pParser.AddOption(wxT(\"c\"), wxT(\"execonf\"), _(\"JSON config path\"));\n pParser.SetLogo(wxString::Format(_(\"The geosync task utility (%s)\\nAuthor: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru\\nCopyright (c) NextGIS %d\"), GetAppVersionString().c_str(), __YEAR__));\n}\n\nvoid GeoSyncTaskApp::OnAppAbout(void)\n{\n wxString out = wxString::Format(_(\"The geosync task utility (%s)\\nAuthor: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru\\nCopyright (c) NextGIS %d\"), GetAppVersionString().c_str(), __YEAR__);\n\twxFprintf(stdout, out);\n}\n\nvoid GeoSyncTaskApp::OnAppOptions(void)\n{\n wxCmdLineParser pParser;\n pParser.AddSwitch(wxT(\"v\"), wxT(\"version\"), _(\"The version of this program\"));\n //main parameters\n pParser.AddOption(wxT(\"l\"), wxT(\"local\"), _(\"local sync path\"));\n pParser.AddOption(wxT(\"u\"), wxT(\"url\"), _(\"NGW URL\"));\n pParser.AddOption(wxT(\"ru\"), wxT(\"user\"), _(\"NGW login\"));\n pParser.AddOption(wxT(\"rp\"), wxT(\"passwd\"), _(\"NGW Password\"));\n pParser.AddOption(wxT(\"id\"), wxT(\"id\"), _(\"resource group id\"), wxCMD_LINE_VAL_NUMBER);\n pParser.AddOption(wxT(\"d\"), wxT(\"direction\"), _(\"sync direction [local2remote|remote2local|both]\"));\n pParser.SetLogo(wxString::Format(_(\"The geosync task utility (%s)\\nAuthor: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru\\nCopyright (c) NextGIS %d\"), GetAppVersionString().c_str(), __YEAR__));\n pParser.Usage();\n}\n\nbool GeoSyncTaskApp::OnCmdLineParsed(wxCmdLineParser& pParser)\n{\n \tif( pParser.Found( wxT( \"v\" ) ) )\n\t{\n OnAppAbout();\n exit(EXIT_SUCCESS);\n return true;\n\t}\n \n wxString sDirection;\n if (pParser.Found(wxT(\"l\"), &m_sLocalPath) && pParser.Found(wxT(\"u\"), &m_sURL) && pParser.Found(wxT(\"ru\"), &m_sUser) && pParser.Found(wxT(\"rp\"), &m_sPasswd) && pParser.Found(wxT(\"id\"), &m_nRemoteId) && pParser.Found(wxT(\"d\"), &sDirection))\n {\n if (sDirection.IsSameAs(wxT(\"local2remote\"), false))\n {\n m_eDirection = geoSyncLocal2Remote;\n }\n else if (sDirection.IsSameAs(wxT(\"remote2local\"), false))\n {\n m_eDirection = geoSyncRemote2Local;\n }\n else if (sDirection.IsSameAs(wxT(\"both\"), false))\n {\n m_eDirection = geoSyncBoth;\n }\n else\n {\n return false;\n }\n return true;\n }\n\n pParser.Usage();\n\n return wxAppConsole::OnCmdLineParsed(pParser);\n}\n\nvoid GeoSyncTaskApp::PutMessage(const wxString &sMessage, size_t nIndex, wxGISEnumMessageType nType)\n{\n if(m_sPrevMsg == sMessage)\n return;\n wxString sOut;\n\n switch(nType)\n {\n case enumGISMessageError:\n wxLogError(sMessage);\n sOut.Append(wxT(\"ERR: \"));\n break;\n case enumGISMessageWarning:\n wxLogWarning(sMessage);\n sOut.Append(wxT(\"WARN: \"));\n break;\n case enumGISMessageQuestion: \n case enumGISMessageNormal:\n case enumGISMessageInformation:\n case enumGISMessageTitle:\n case enumGISMessageOk:\n wxLogMessage(sMessage);\n sOut.Append(wxT(\"INFO: \"));\n break;\n case enumGISMessageSend:\n wxLogMessage(sMessage);\n sOut.Append(wxT(\"SND: \"));\n break;\n case enumGISMessageReceive:\n wxLogMessage(sMessage);\n sOut.Append(wxT(\"RCV: \"));\n break;\n case enumGISMessageUnknown:\n default:\n wxLogVerbose(sMessage);\n break;\n }\n sOut.Append(sMessage + wxT(\"\\r\\n\"));\n\n AddMessage(sOut);\n\n m_sPrevMsg = sMessage;\n}\n\n\nvoid GeoSyncTaskApp::SetValue(int value)\n{\n if(m_nValue == value)\n return;\n m_nValue = value;\n\n AddMessage(wxString::Format(wxT(\"DONE: %d%% \\r\"), value));\n}\n\nvoid GeoSyncTaskApp::AddMessage(const wxString& sMessage)\n{\n wxCriticalSectionLocker lock(m_CritSec);\n m_saMessages.Add(sMessage);\n}\n\nwxString GeoSyncTaskApp::GetMessage()\n{\n wxCriticalSectionLocker lock(m_CritSec);\n if (m_saMessages.IsEmpty())\n return wxEmptyString;\n wxString sRet = m_saMessages[0];\n m_saMessages.RemoveAt(0);\n return sRet;\n}\n\nwxThread::ExitCode GeoSyncTaskApp::Entry()\n{\n while (!TestDestroy())\n {\n wxString sMessage = GetMessage();\n if (sMessage.IsEmpty())\n wxMilliSleep(450);\n else\n {\n if (m_pFFileOutputStream->IsOk())\n {\n m_pOutTxtStream->WriteString(sMessage);\n//#if wxUSE_LOG\n // flush the logged messages if any\n //wxLog::FlushActive();\n//#endif\n m_StdOutFile.Flush();\n }\n wxMilliSleep(150);\n }\n \n }\n\n return (wxThread::ExitCode)wxTHREAD_NO_ERROR;\n}\n\nbool GeoSyncTaskApp::SetupSys(const wxString &sSysPath)\n{\n return true; //no need sys?\n}\n\nbool GeoSyncTaskApp::Initialize(const wxString &sAppName, const wxString &sLogFilePrefix)\n{\n\twxGISAppConfig oConfig = GetConfig();\n if(!oConfig.IsOk())\n return false;\n\n\twxString sLogDir = oConfig.GetLogDir();\n\tif(!SetupLog(sLogDir, sLogFilePrefix))\n return false;\n wxLogMessage(_(\"%s %s is initializing...\"), sAppName.c_str(), GetAppVersionString().c_str());\n\n\tif(!SetupLoc(oConfig.GetLocale(), oConfig.GetLocaleDir()))\n return false;\n\n\t//setup sys dir\n\twxString sSysDir = oConfig.GetSysDir();\n\tif(!SetupSys(sSysDir))\n return false;\n\n\tbool bDebugMode = oConfig.GetDebugMode();\n\tSetDebugMode(bDebugMode);\n\n if(!GetApplication())\n SetApplication(this);\n\n return true;\n}\n\nbool GeoSyncTaskApp::OnExceptionInMainLoop()\n{\n wxLogError(_(\"Unhandled Exception\"));\n exit(EXIT_FAILURE);\n}\n\nvoid GeoSyncTaskApp::OnFatalException()\n{\n wxLogError(_(\"Unhandled Exception\"));\n exit(EXIT_FAILURE);\n}\n\nvoid GeoSyncTaskApp::OnUnhandledException()\n{\n wxLogError(_(\"Unhandled Exception\"));\n exit(EXIT_FAILURE);\n}\n" } ]
30
justincheng20/sgcap
https://github.com/justincheng20/sgcap
27f6ee71877375b7caf554e7474e5b3d8669e96f
d8379d5509c48ce72ac4db33a34a11bd33077af8
46c37f28b0951be4018df53fa47d9088b2722a73
refs/heads/master
2022-12-07T10:27:15.977137
2020-09-09T03:11:39
2020-09-09T03:11:39
293,989,425
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5874015688896179, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 30.725000381469727, "blob_id": "3da5c6976c462153b0dbb12286357380cca4664f", "content_id": "0793d899d7684a3793ef212e76ed8bfc0c7e48d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1270, "license_type": "no_license", "max_line_length": 68, "num_lines": 40, "path": "/script.py", "repo_name": "justincheng20/sgcap", "src_encoding": "UTF-8", "text": "import sys\nimport csv\n\nnumber_of_indices = int(sys.argv[1])\nindex = str(sys.argv[2])\nhistorical_prices = str(sys.argv[3])\n\nindice_count = 0\nchosen_index_values = []\nselected_index_values = {}\nweighted_values = {}\n\nwith open(historical_prices) as csvfile:\n readCSV = csv.reader(csvfile, delimiter=',')\n for row in readCSV:\n if row[0] == 'Symbol':\n continue\n elif row[0] == index:\n chosen_index_values.append(float(row[2]))\n else:\n if row[0] not in selected_index_values.keys():\n indice_count += 1\n if indice_count > number_of_indices:\n continue\n selected_index_values[row[0]] = []\n weighted_values[row[0]] = []\n selected_index_values[row[0]].append(float(row[2]))\n\nfor i in range(0,len(chosen_index_values)):\n current_val = chosen_index_values[i]/number_of_indices\n for key in selected_index_values.keys():\n weighted_value = current_val/(selected_index_values[key][i])\n weighted_values[key].append(weighted_value)\n\nprint('Symbol, Weight')\nfor key in weighted_values.keys():\n sum = 0\n for num in weighted_values[key]:\n sum += num\n print(key+\",\", round(sum/len(chosen_index_values),3))\n\n" } ]
1
DimLav/learning
https://github.com/DimLav/learning
f94e0405f0df95837aa4889b5246486b67cdf948
ed2f04399ebdf64d35fcc91b74b90554f6352607
83be53e986174fb80912de3c2b8f345623ed6e66
refs/heads/master
2022-01-19T10:59:40.163437
2022-01-01T14:49:55
2022-01-01T14:49:55
85,989,322
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.31416308879852295, "alphanum_fraction": 0.31845492124557495, "avg_line_length": 15.590909004211426, "blob_id": "7f6d86ee4c1c910ffc51eeaac913363abf9ce422", "content_id": "0e3423a4cab50aa2ac29e8b856118bf76292b822", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1168, "license_type": "no_license", "max_line_length": 83, "num_lines": 66, "path": "/RPS.py", "repo_name": "DimLav/learning", "src_encoding": "UTF-8", "text": "rock = '''\r\n _______\r\n---' ____)\r\n (_____)\r\n (_____)\r\n (____)\r\n---.__(___)\r\n'''\r\n\r\npaper = '''\r\n _______\r\n---' ____)____\r\n ______)\r\n _______)\r\n _______)\r\n---.__________)\r\n'''\r\n\r\nscissors = '''\r\n _______\r\n---' ____)____\r\n ______)\r\n __________)\r\n (____)\r\n---.__(___)\r\n'''\r\n\r\n#Write your code below this line 👇\r\n\r\nimport random\r\n\r\nh = input('Input please')\r\n\r\n# if h != r or h != p or h != s:\r\n# print(\"Game over\")\r\n\r\nc = random.randint(1, 3)\r\nif c == 1:\r\n c = 'r'\r\nelif c == 2:\r\n c = 'p'\r\nelif c == 3:\r\n c = 's'\r\n\r\nprint(h, c)\r\n\r\nif h == 'r':\r\n print(rock)\r\nelif h == 'p':\r\n print(paper)\r\nelif h == 's':\r\n print(scissors)\r\n\r\nif c == 'r':\r\n print(rock)\r\nelif c == 'p':\r\n print(paper)\r\nelif c == 's':\r\n print(scissors)\r\n\r\nif (h == 'r' and c == 'r') or (h == 'p' and c == 'p') or (h == 's' and c == 's'):\r\n print('please repeat')\r\nelif (h == 'r' and c == 's') or (h == 'p' and c == 'r') or (h == 's' and c == 'p'):\r\n print(\"Human wins!\")\r\nelif (h == 'r' and c == 'p') or (h == 'p' and c == 's') or (h == 's' and c == 'r'):\r\n print(\"Computer wins!\")\r\n\r\n\r\n" }, { "alpha_fraction": 0.28125, "alphanum_fraction": 0.5208333134651184, "avg_line_length": 9.777777671813965, "blob_id": "bb679f5f982afc10339eb757c07e26befb8ba0dd", "content_id": "218be17bd67d905a826b95cc41fff330377df2fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 96, "license_type": "no_license", "max_line_length": 17, "num_lines": 9, "path": "/2 euler.py", "repo_name": "DimLav/learning", "src_encoding": "UTF-8", "text": "y1=1\ny2=1\nz=0\nwhile y2<4000000:\n y2=y1+y2\n y1=y2-y1\n if (y2%2==0):\n z=z+y2\nprint(z)" } ]
2
katarzynalatos/Lab_2
https://github.com/katarzynalatos/Lab_2
8aa0d45980d3a2470928852e37853177b4c17493
2286de836dc0b73189c83e844ef39b381edcb46e
6686e6a4dc1988ef3e936ca5b4150a48b61bfc42
refs/heads/master
2021-01-23T00:35:10.273909
2017-05-30T18:20:55
2017-05-30T18:20:55
85,746,743
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5344506502151489, "alphanum_fraction": 0.550744891166687, "avg_line_length": 29.77777862548828, "blob_id": "22da962ed1ea9b512e64d4e3b744c704f3f51ef0", "content_id": "bf58be73a9e66cdda01d46892435cd310299d5d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4296, "license_type": "no_license", "max_line_length": 112, "num_lines": 135, "path": "/TestCalc.py", "repo_name": "katarzynalatos/Lab_2", "src_encoding": "UTF-8", "text": "from Calc import Calc\r\nfrom unittest import TestCase\r\nfrom unittest.mock import patch\r\nimport Exceptions\r\nimport unittest\r\n\r\n\r\nclass TestCalc(TestCase):\r\n#add\r\n def test_correct_adding__two_integers(self):\r\n c = Calc()\r\n first = 20\r\n second = 25\r\n expected_result = 45\r\n self.assertEqual(expected_result, c.add(first, second))\r\n\r\n def test_correct_adding_two_floats(self):\r\n c = Calc()\r\n first = 20.3\r\n second = 25.9\r\n expected_result = 46.2\r\n self.assertAlmostEqual(expected_result, c.add(first, second))\r\n\r\n def test_correct_adding_float_and_integer(self):\r\n c = Calc()\r\n first = 20.3\r\n second = 25\r\n expected_result = 45.3\r\n self.assertAlmostEqual(expected_result, c.add(first, second))\r\n\r\n def test_correct_adding_integer_and_float(self):\r\n c = Calc()\r\n first = 20\r\n second = 25.3\r\n expected_result = 45.3\r\n self.assertAlmostEqual(expected_result, c.add(first, second))\r\n\r\n def test_correct_adding_string_and_string_(self):\r\n c = Calc()\r\n first = \"+\"\r\n second = \"+\"\r\n self.assertRaises(Exceptions.NotANumber, c.add, first, second)\r\n\r\n def test_correct_adding_string_and_not_string_(self):\r\n c = Calc()\r\n first = \"+\"\r\n second = 1.3\r\n self.assertRaises(Exceptions.NotANumber, c.add, first, second)\r\n\r\n def test_correct_adding_not_string_and_string(self):\r\n c = Calc()\r\n first = 1\r\n second = \"+\"\r\n self.assertRaises(Exceptions.NotANumber, c.add, first, second)\r\n\r\n#---------------------------------------------------------------------------------------\r\n#divide\r\n def test_correct_divide_two_integers(self):\r\n c = Calc()\r\n first = 5\r\n second = 2\r\n expected_result = 2.5\r\n self.assertAlmostEqual(expected_result, c.divide(first, second))\r\n\r\n def test_correct_divide_two_floats(self):\r\n c = Calc()\r\n first = 8.5\r\n second = 2.5\r\n expected_result = 3.4\r\n self.assertAlmostEqual(expected_result, c.divide(first, second))\r\n\r\n def test_correct_divide_float_and_integer(self):\r\n c = Calc()\r\n first = 8.5\r\n second = 2\r\n expected_result = 4.25\r\n self.assertAlmostEqual(expected_result, c.divide(first, second))\r\n\r\n def test_correct_divide_integer_and_float(self):\r\n c = Calc()\r\n first = 8\r\n second = 2.5\r\n expected_result = 3.2\r\n self.assertAlmostEqual(expected_result, c.divide(first, second))\r\n\r\n def test_correct_divide_number_and_float_zero(self):\r\n c = Calc()\r\n first = 8\r\n second = 0\r\n self.assertRaises(Exceptions.IsZero, c.divide, first, second)\r\n\r\n def test_correct_divide_number_and_integer_zero(self):\r\n c = Calc()\r\n first = 8\r\n second = 0.0\r\n self.assertRaises(Exceptions.IsZero, c.divide, first, second)\r\n\r\n def test_correct_divide_string_and_string_(self):\r\n c = Calc()\r\n first = \"+\"\r\n second = \"+\"\r\n self.assertRaises(Exceptions.NotANumber, c.divide, first, second)\r\n\r\n#---------------------------------------------------------------------------------------------------------------\r\n#derivative\r\n\r\n def test_correct_derivative_string_and_string_(self):\r\n c = Calc()\r\n first = \"x**2\"\r\n second = \"xss\"\r\n self.assertRaises(Exceptions.NotANumber, c.derivative, first, second)\r\n\r\n def test_correct_derivative_string_and_not_int_(self):\r\n c = Calc()\r\n first = \"x**2\"\r\n second = 1.2\r\n self.assertRaises(Exceptions.NotInteger, c.derivative, first, second)\r\n\r\n def test_correct_derivative_string_and_less_than_zero_int_(self):\r\n c = Calc()\r\n first = \"x**2\"\r\n second = -1\r\n self.assertRaises(Exceptions.NotHigherAndEqualZero, c.derivative, first, second)\r\n\r\n @patch('Calc.Calc.derivative')\r\n def test_correct_derivative_str_and_integer(self, mock):\r\n mock.return_value = \"2*x\"\r\n c = Calc()\r\n first = \"x**2\"\r\n second = 1\r\n expected_result = \"2*x\"\r\n self.assertEqual(expected_result, c.derivative(first, second))\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n \r\n" }, { "alpha_fraction": 0.7697160840034485, "alphanum_fraction": 0.7823343873023987, "avg_line_length": 62.400001525878906, "blob_id": "371cc58ecdede07ba6027c78841757904a4c4f9b", "content_id": "1508deb18172315f7012702b51a481e63ffe76ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 317, "license_type": "no_license", "max_line_length": 123, "num_lines": 5, "path": "/README.md", "repo_name": "katarzynalatos/Lab_2", "src_encoding": "UTF-8", "text": "# Lab_2\nPitE solutions\nImplementation of basic calculator in Calc.py that have 3 options: add, divide and derivative.\nIt's possibile to test it by running unittests from TestCalc.py by Travis.\n[![Build Status](https://travis-ci.org/katarzynalatos/Lab_2.svg?branch=master)](https://travis-ci.org/katarzynalatos/Lab_2)\n" }, { "alpha_fraction": 0.659913182258606, "alphanum_fraction": 0.6613603234291077, "avg_line_length": 32.150001525878906, "blob_id": "a126cbc7d55da60c6aadb8cb504488ed7be8efc2", "content_id": "45da9ef817105c35bb8e11a4075bc2274eb0fe6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 691, "license_type": "no_license", "max_line_length": 74, "num_lines": 20, "path": "/Calc.py", "repo_name": "katarzynalatos/Lab_2", "src_encoding": "UTF-8", "text": "from AbstractCalc import AbstractCalc\r\nfrom Validator import Validator\r\nfrom sympy import diff\r\n\r\n\r\nclass Calc(AbstractCalc):\r\n def add(self, first, second):\r\n add_validate = Validator(first, second, \"add\")\r\n add_validate.validate()\r\n return first + second\r\n\r\n def divide(self, numerator, denominator):\r\n divide_validate = Validator(numerator, denominator, \"divide\")\r\n divide_validate.validate()\r\n return numerator/denominator\r\n\r\n def derivative(self, function, degree):\r\n derivative_validate = Validator(0, degree, \"derivative\", function)\r\n derivative_validate.validate()\r\n return diff(function, 'x', degree)\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.6591928005218506, "alphanum_fraction": 0.6591928005218506, "avg_line_length": 10.38888931274414, "blob_id": "dd12adf1c45fa557a6b5661d47e2c0524e0aa237", "content_id": "bdb011515789b4dd598abeb908e8030ef88faaa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 223, "license_type": "no_license", "max_line_length": 39, "num_lines": 18, "path": "/Exceptions.py", "repo_name": "katarzynalatos/Lab_2", "src_encoding": "UTF-8", "text": "class NotANumber(Exception):\r\n pass\r\n\r\n\r\nclass NotAString(Exception):\r\n pass\r\n\r\n\r\nclass NotHigherAndEqualZero(Exception):\r\n pass\r\n\r\n\r\nclass NotInteger(Exception):\r\n pass\r\n\r\n\r\nclass IsZero(Exception):\r\n pass\r\n" }, { "alpha_fraction": 0.6141079068183899, "alphanum_fraction": 0.6141079068183899, "avg_line_length": 18.08333396911621, "blob_id": "3548a026fbabf6bc35ede55fd4d95d2b55a53716", "content_id": "2e12530427b65e399b5a1f85404f5a20656a18ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 241, "license_type": "no_license", "max_line_length": 50, "num_lines": 12, "path": "/AbstractCalc.py", "repo_name": "katarzynalatos/Lab_2", "src_encoding": "UTF-8", "text": "import abc\r\n\r\n\r\nclass AbstractCalc(object, metaclass=abc.ABCMeta):\r\n def add(self, first, second):\r\n pass\r\n\r\n def divide(self, numerator, denominator):\r\n pass\r\n\r\n def derivative(self, function, degree):\r\n pass\r\n" }, { "alpha_fraction": 0.573616623878479, "alphanum_fraction": 0.5770751237869263, "avg_line_length": 31.733333587646484, "blob_id": "d3dbeccfcde772baa3d8c14134f7e2b3639a296e", "content_id": "0cf3e54e7e75f205ebec300e51ab13c894a9c2d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2024, "license_type": "no_license", "max_line_length": 104, "num_lines": 60, "path": "/Validator.py", "repo_name": "katarzynalatos/Lab_2", "src_encoding": "UTF-8", "text": "from AbstractValidator import AbstractValidator\r\nimport Exceptions\r\n\r\n\r\nclass Validator(AbstractValidator):\r\n def __init__(self, to_validate_first, to_validate_second, action, to_derivative_str=\"\"):\r\n super(Validator, self).__init__()\r\n self._to_validate_first = to_validate_first\r\n self._to_validate_second = to_validate_second\r\n self._action = action\r\n self._to_derivative_str=to_derivative_str\r\n\r\n def validate(self):\r\n if self._is_number(self._to_validate_first) and self._is_number(self._to_validate_second):\r\n if self._action==\"divide\" and self._is_a_zero(self._to_validate_second):\r\n raise Exceptions.IsZero\r\n if self._action==\"derivative\" and self._is_not_more_or_equal_zero(self._to_validate_second):\r\n raise Exceptions.NotHigherAndEqualZero\r\n if self._action==\"derivative\" and self._is_not_a_string(self._to_derivative_str):\r\n raise Exceptions.NotAString\r\n if self._action==\"derivative\" and not self._is_integer(self._to_validate_second):\r\n raise Exceptions.NotInteger\r\n else:\r\n return True\r\n else:\r\n raise Exceptions.NotANumber\r\n\r\n @staticmethod\r\n def _is_number( number):\r\n if isinstance(number, int):\r\n return True\r\n elif isinstance(number, float):\r\n return True\r\n else:\r\n return False\r\n\r\n @staticmethod\r\n def _is_a_zero(number):\r\n if number>-1E-10 and number<1E-10:\r\n return True\r\n else:\r\n return False\r\n\r\n @staticmethod\r\n def _is_not_more_or_equal_zero(number):\r\n if number >= 0:\r\n return False\r\n else:\r\n return True\r\n\r\n @staticmethod\r\n def _is_not_a_string(string):\r\n if isinstance(string, str):\r\n return False\r\n else:\r\n return True\r\n\t\r\n @staticmethod\r\n def _is_integer(number):\r\n return isinstance(number, int)\r\n" } ]
6
u3shit/neptools
https://github.com/u3shit/neptools
04930d4169d66ec940c9b9790d50eb8a841bc151
2bf6576ad4e86ef7cae602182b90cfe2246a1565
25eaa4eaaa250324330bfe3f78deaa2e479618db
refs/heads/master
2021-05-23T21:47:34.129436
2021-04-25T14:01:17
2021-04-25T14:01:17
50,874,883
62
14
null
null
null
null
null
[ { "alpha_fraction": 0.540120542049408, "alphanum_fraction": 0.5592337250709534, "avg_line_length": 29.97333335876465, "blob_id": "aeff81cafa63c8b3fb297cb52b4da0afc117309d", "content_id": "65ef2d5ae2b81d2e4f8e6292ab46cd25476a4713", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 23230, "license_type": "permissive", "max_line_length": 83, "num_lines": 750, "path": "/src/format/gbnl.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"gbnl_lua.hpp\"\n#include \"../open.hpp\"\n#include \"../sink.hpp\"\n\n#include <libshit/except.hpp>\n#include <libshit/char_utils.hpp>\n\n#include <map>\n#include <boost/algorithm/string/replace.hpp>\n#include <boost/algorithm/string/predicate.hpp>\n#include <boost/container/small_vector.hpp>\n#include <boost/preprocessor/repetition/repeat.hpp>\n#include <brigand/algorithms/wrap.hpp>\n\nnamespace Neptools\n{\n static constexpr bool STRTOOL_COMPAT = false;\n\n namespace { enum class Separator { AUTO, SJIS, UTF8 }; }\n static Separator export_sep = Separator::AUTO;\n\n static Libshit::Option sep_opt{\n GetFlavorOptions(), \"txt-encoding\", 1, \"ENCODING\",\n \"Set exported txt encoding of .cl3/.gbin/.gstr files: \"\n \"auto, sjis (Shift-JIS) or utf8\",\n [](auto&& args)\n {\n if (strcmp(args.front(), \"auto\") == 0) export_sep = Separator::AUTO;\n else if (strcmp(args.front(), \"sjis\") == 0) export_sep = Separator::SJIS;\n else if (strcmp(args.front(), \"utf8\") == 0) export_sep = Separator::UTF8;\n else throw Libshit::InvalidParam{\"invalid argument\"};\n }};\n\n static bool simple_ids = false;\n static Libshit::Option simple_opt{\n GetFlavorOptions(), \"simple-ids\", 0, nullptr,\n \"Use simple IDs with txt export \"\n \"(Incompatible with STRTOOL and txts produced without this option!)\",\n [](auto&& args) { simple_ids = true; }};\n\n void Gbnl::Header::Validate(size_t chunk_size) const\n {\n#define VALIDATE(x) LIBSHIT_VALIDATE_FIELD(\"Gbnl::Header\", x)\n VALIDATE(endian == 'L' || endian == 'B');\n VALIDATE(field_04 == 1 && field_06 == 0 && field_08 == 16 && field_0c == 4);\n VALIDATE(descr_offset + msg_descr_size * count_msgs < chunk_size);\n VALIDATE(offset_types + sizeof(TypeDescriptor) * count_types < chunk_size);\n VALIDATE(offset_msgs < chunk_size);\n VALIDATE(field_34 == 0 && field_38 == 0 && field_3c == 0);\n\n if (memcmp(magic, \"GBN\", 3) == 0)\n VALIDATE(descr_offset == 0);\n else if (memcmp(magic, \"GST\", 3) == 0)\n VALIDATE(descr_offset == sizeof(Header));\n else\n VALIDATE(!\"Invalid magic\");\n#undef VALIDATE\n }\n\n void endian_reverse_inplace(Gbnl::Header& hdr)\n {\n boost::endian::endian_reverse_inplace(hdr.field_04);\n boost::endian::endian_reverse_inplace(hdr.field_06);\n boost::endian::endian_reverse_inplace(hdr.field_08);\n boost::endian::endian_reverse_inplace(hdr.field_0c);\n boost::endian::endian_reverse_inplace(hdr.flags);\n boost::endian::endian_reverse_inplace(hdr.descr_offset);\n boost::endian::endian_reverse_inplace(hdr.count_msgs);\n boost::endian::endian_reverse_inplace(hdr.msg_descr_size);\n boost::endian::endian_reverse_inplace(hdr.count_types);\n boost::endian::endian_reverse_inplace(hdr.offset_types);\n boost::endian::endian_reverse_inplace(hdr.field_28);\n boost::endian::endian_reverse_inplace(hdr.offset_msgs);\n boost::endian::endian_reverse_inplace(hdr.field_30);\n boost::endian::endian_reverse_inplace(hdr.field_34);\n boost::endian::endian_reverse_inplace(hdr.field_38);\n boost::endian::endian_reverse_inplace(hdr.field_3c);\n }\n\n void endian_reverse_inplace(Gbnl::TypeDescriptor& desc)\n {\n boost::endian::endian_reverse_inplace(desc.type);\n boost::endian::endian_reverse_inplace(desc.offset);\n }\n\n static size_t GetTypeSize(uint16_t type)\n {\n switch (type)\n {\n case Gbnl::TypeDescriptor::INT8: return 1;\n case Gbnl::TypeDescriptor::INT16: return 2;\n case Gbnl::TypeDescriptor::INT32: return 4;\n case Gbnl::TypeDescriptor::INT64: return 8;\n case Gbnl::TypeDescriptor::FLOAT: return 4;\n case Gbnl::TypeDescriptor::STRING: return 4;\n }\n LIBSHIT_THROW(Libshit::DecodeError, \"Gbnl: invalid type\");\n }\n\n Gbnl::Gbnl(Source src)\n {\n ADD_SOURCE(Parse_(src), src);\n }\n\n void Gbnl::Parse_(Source& src)\n {\n#define VALIDATE(msg, x) LIBSHIT_VALIDATE_FIELD(\"Gbnl\" msg, x)\n\n src.CheckSize(sizeof(Header));\n auto foot = src.PreadGen<Header>(0);\n if (memcmp(foot.magic, \"GST\", 3) == 0)\n is_gstl = true;\n else\n {\n src.PreadGen(src.GetSize() - sizeof(Header), foot);\n is_gstl = false;\n }\n\n endian = foot.endian == 'L' ? Endian::LITTLE : Endian::BIG;\n ToNative(foot, endian);\n foot.Validate(src.GetSize());\n flags = foot.flags;\n field_28 = foot.field_28;\n field_30 = foot.field_30;\n\n src.Seek(foot.offset_types);\n msg_descr_size = foot.msg_descr_size;\n size_t calc_offs = 0;\n\n Struct::TypeBuilder bld;\n bool int8_in_progress = false;\n for (size_t i = 0; i < foot.count_types; ++i)\n {\n auto type = src.ReadGen<TypeDescriptor>();\n ToNative(type, endian);\n VALIDATE(\"unordered types\", calc_offs <= type.offset);\n\n Pad(type.offset - calc_offs, bld, int8_in_progress);\n calc_offs = type.offset + GetTypeSize(type.type);\n\n switch (type.type)\n {\n case TypeDescriptor::INT8:\n LIBSHIT_ASSERT(!int8_in_progress);\n int8_in_progress = true;\n break;\n case TypeDescriptor::INT16:\n bld.Add<int16_t>();\n break;\n case TypeDescriptor::INT32:\n bld.Add<int32_t>();\n break;\n case TypeDescriptor::INT64:\n bld.Add<int64_t>();\n break;\n case TypeDescriptor::FLOAT:\n bld.Add<float>();\n break;\n case TypeDescriptor::STRING:\n bld.Add<OffsetString>();\n break;\n default:\n LIBSHIT_THROW(Libshit::DecodeError, \"GBNL: invalid type\");\n }\n }\n Pad(msg_descr_size - calc_offs, bld, int8_in_progress);\n\n type = bld.Build();\n\n auto msgs = foot.descr_offset;\n messages.reserve(foot.count_msgs);\n for (size_t i = 0; i < foot.count_msgs; ++i)\n {\n messages.emplace_back(Struct::New(type));\n auto& m = messages.back();\n src.Seek(msgs);\n for (size_t i = 0; i < type->item_count; ++i)\n {\n switch (type->items[i].idx)\n {\n case Struct::GetIndexFromType<int8_t>():\n m->Get<int8_t>(i) = src.ReadUint8(endian);\n break;\n case Struct::GetIndexFromType<int16_t>():\n m->Get<int16_t>(i) = src.ReadUint16(endian);\n break;\n case Struct::GetIndexFromType<int32_t>():\n m->Get<int32_t>(i) = src.ReadUint32(endian);\n break;\n case Struct::GetIndexFromType<int64_t>():\n m->Get<int64_t>(i) = src.ReadUint64(endian);\n break;\n case Struct::GetIndexFromType<float>():\n {\n union { float f; uint32_t i; } x;\n x.i = src.ReadUint32(endian);\n m->Get<float>(i) = x.f;\n break;\n }\n case Struct::GetIndexFromType<OffsetString>():\n {\n uint32_t offs = src.ReadUint32(endian);\n if (offs == 0xffffffff)\n m->Get<OffsetString>(i).offset = -1;\n else\n {\n VALIDATE(\"\", offs < src.GetSize() - foot.offset_msgs);\n auto str = foot.offset_msgs + offs;\n\n m->Get<OffsetString>(i) = {src.PreadCString(str), 0};\n }\n break;\n }\n case Struct::GetIndexFromType<FixStringTag>():\n src.Read(m->Get<FixStringTag>(i).str, type->items[i].size);\n break;\n case Struct::GetIndexFromType<PaddingTag>():\n src.Read(m->Get<PaddingTag>(i).pad, type->items[i].size);\n break;\n }\n }\n\n msgs += msg_descr_size;\n }\n RecalcSize();\n\n VALIDATE(\" invalid size after repack\", msg_descr_size == foot.msg_descr_size);\n VALIDATE(\" invalid size after repack\", GetSize() == src.GetSize());\n#undef VALIDATE\n }\n\n#if LIBSHIT_WITH_LUA\n Gbnl::Gbnl(Libshit::Lua::StateRef vm, Endian endian, bool is_gstl,\n uint32_t flags, uint32_t field_28, uint32_t field_30,\n Libshit::AT<Struct::TypePtr> type, Libshit::Lua::RawTable msgs)\n : endian{endian}, is_gstl{is_gstl}, flags{flags}, field_28{field_28},\n field_30{field_30}, type{std::move(type.Get())}\n {\n auto [len, one] = vm.RawLen01(msgs);\n messages.reserve(len);\n vm.Fori(msgs, one, len, [&](size_t, int type)\n {\n if (type != LUA_TTABLE) vm.TypeError(false, \"table\", -1);\n messages.emplace_back(brigand::wrap<Struct, DynamicStructLua>::New(\n vm, this->type, {lua_absindex(vm, -1)}));\n });\n }\n#endif\n\n void Gbnl::Pad(uint16_t diff, Struct::TypeBuilder& bld, bool& int8_in_progress)\n {\n if (int8_in_progress)\n {\n int8_in_progress = false;\n if (diff <= 3) // probably padding\n bld.Add<int8_t>();\n else\n {\n bld.Add<FixStringTag>(diff+1);\n return;\n }\n }\n\n if (diff) bld.Add<PaddingTag>(diff);\n }\n\n namespace\n {\n struct WriteDescr\n {\n WriteDescr(Byte* ptr, Endian e) : ptr{ptr}, e{e} {}\n Byte* ptr;\n Endian e;\n\n // int8, 16, 32, 64\n template <typename T,\n typename Enable = std::enable_if_t<std::is_integral_v<T>>>\n void operator()(T x, size_t len)\n {\n LIBSHIT_ASSERT(sizeof(T) == len); (void) len;\n *reinterpret_cast<T*>(ptr) = FromNativeCopy(x, e);\n ptr += sizeof(T);\n }\n\n void operator()(float y, size_t)\n {\n static_assert(sizeof(float) == sizeof(uint32_t));\n union { float f; uint32_t i; } x;\n x.f = y;\n *reinterpret_cast<std::uint32_t*>(ptr) = FromNativeCopy(x.i, e);\n ptr += 4;\n }\n void operator()(const Gbnl::OffsetString& os, size_t)\n {\n *reinterpret_cast<std::uint32_t*>(ptr) = FromNativeCopy(os.offset, e);\n ptr += 4;\n }\n void operator()(const Gbnl::FixStringTag& fs, size_t len)\n {\n strncpy(reinterpret_cast<char*>(ptr), fs.str, len-1);\n ptr[len-1] = '\\0';\n ptr += len;\n }\n void operator()(const Gbnl::PaddingTag& pd, size_t len)\n {\n memcpy(ptr, pd.pad, len);\n ptr += len;\n }\n };\n }\n\n void Gbnl::Dump_(Sink& sink) const\n {\n if (is_gstl) DumpHeader(sink);\n\n // RB2-3 scripts: 36\n // VII scrips: 392\n // gbin/gstrs are usually smaller than VII scripts\n // RB3's stdungeon.gbin: 7576, stsqdungeon.gbin: 1588 though\n //std::cerr << msg_descr_size << std::endl;\n boost::container::small_vector<Byte, 392> msgd;\n msgd.resize(msg_descr_size);\n\n for (const auto& m : messages)\n {\n m->ForEach(WriteDescr{msgd.data(), endian});\n sink.Write({reinterpret_cast<char*>(msgd.data()), msg_descr_size});\n }\n\n auto msgs_end = msg_descr_size * messages.size();\n auto msgs_end_round = Align(msgs_end);\n sink.Pad(msgs_end_round - msgs_end);\n\n TypeDescriptor ctrl;\n uint16_t offs = 0;\n for (size_t i = 0; i < type->item_count; ++i)\n {\n ctrl.offset = offs;\n switch (type->items[i].idx)\n {\n case Struct::GetIndexFromType<int8_t>():\n ctrl.type = TypeDescriptor::INT8;\n offs += 1;\n break;\n case Struct::GetIndexFromType<int16_t>():\n ctrl.type = TypeDescriptor::INT16;\n offs += 2;\n break;\n case Struct::GetIndexFromType<int32_t>():\n ctrl.type = TypeDescriptor::INT32;\n offs += 4;\n break;\n case Struct::GetIndexFromType<int64_t>():\n ctrl.type = TypeDescriptor::INT64;\n offs += 8;\n break;\n case Struct::GetIndexFromType<float>():\n ctrl.type = TypeDescriptor::FLOAT;\n offs += 4;\n break;\n case Struct::GetIndexFromType<OffsetString>():\n ctrl.type = TypeDescriptor::STRING;\n offs += 4;\n break;\n case Struct::GetIndexFromType<FixStringTag>():\n ctrl.type = TypeDescriptor::INT8;\n offs += type->items[i].size;\n break;\n case Struct::GetIndexFromType<PaddingTag>():\n offs += type->items[i].size;\n goto skip;\n }\n FromNative(ctrl, endian);\n sink.WriteGen(ctrl);\n skip: ;\n }\n auto control_end = msgs_end_round + sizeof(TypeDescriptor) * real_item_count;\n auto control_end_round = Align(control_end);\n sink.Pad(control_end_round - control_end);\n\n size_t offset = 0;\n for (const auto& m : messages)\n for (size_t i = 0; i < m->GetSize(); ++i)\n if (m->Is<OffsetString>(i))\n {\n auto& ofs = m->Get<OffsetString>(i);\n if (ofs.offset == offset)\n {\n sink.WriteCString(ofs.str);\n offset += ofs.str.size() + 1;\n }\n }\n\n LIBSHIT_ASSERT(offset == msgs_size);\n auto offset_round = Align(offset);\n sink.Pad(offset_round - offset);\n\n // sanity checks\n LIBSHIT_ASSERT(msgs_end_round == Align(msg_descr_size * messages.size()));\n LIBSHIT_ASSERT(\n control_end_round == Align(\n msgs_end_round + sizeof(TypeDescriptor) * real_item_count));\n if (!is_gstl) DumpHeader(sink);\n }\n\n void Gbnl::DumpHeader(Sink& sink) const\n {\n Header head;\n memcpy(head.magic, is_gstl ? \"GST\" : \"GBN\", 4);\n head.endian = endian == Endian::LITTLE ? 'L' : 'B';\n head.field_04 = 1;\n head.field_06 = 0;\n head.field_08 = 16;\n head.field_0c = 4;\n head.flags = flags;\n auto offset = is_gstl ? sizeof(Header) : 0;\n head.descr_offset = offset;\n head.count_msgs = messages.size();\n head.msg_descr_size = msg_descr_size;\n head.count_types = real_item_count;\n auto msgs_end_round = Align(offset + msg_descr_size * messages.size());\n head.offset_types = msgs_end_round;;\n head.field_28 = field_28;\n auto control_end_round = Align(msgs_end_round +\n sizeof(TypeDescriptor) * real_item_count);\n head.offset_msgs = msgs_size ? control_end_round : 0;\n head.field_30 = field_30;\n head.field_34 = 0;\n head.field_38 = 0;\n head.field_3c = 0;\n FromNative(head, endian);\n sink.WriteGen(head);\n }\n\n namespace\n {\n struct Print\n {\n std::ostream& os;\n void operator()(const Gbnl::OffsetString& ofs, size_t)\n {\n if (ofs.offset == static_cast<uint32_t>(-1))\n os << \"nil\";\n else\n Libshit::DumpBytes(os, ofs.str);\n }\n void operator()(const Gbnl::FixStringTag& fs, size_t)\n { Libshit::DumpBytes(os, fs.str); }\n void operator()(const Gbnl::PaddingTag& pd, size_t size)\n { Libshit::DumpBytes(os, {pd.pad, size}); }\n void operator()(int8_t x, size_t) { os << static_cast<unsigned>(x); }\n template <typename T> void operator()(T x, size_t) { os << x; }\n };\n }\n\n void Gbnl::Inspect_(std::ostream& os, unsigned indent) const\n {\n os << \"neptools.\";\n InspectGbnl(os, indent);\n }\n void Gbnl::InspectGbnl(std::ostream& os, unsigned indent) const\n {\n os << \"gbnl(neptools.endian.\" << ToString(endian) << \", \"\n << (is_gstl ? \"true\" : \"false\") << \", \" << flags << \", \" << field_28\n << \", \" << field_30 << \", {\";\n\n for (size_t i = 0; i < type->item_count; ++i)\n {\n if (i != 0) os << \", \";\n switch (type->items[i].idx)\n {\n case Struct::GetIndexFromType<int8_t>(): os << \"\\\"int8\\\"\"; break;\n case Struct::GetIndexFromType<int16_t>(): os << \"\\\"int16\\\"\"; break;\n case Struct::GetIndexFromType<int32_t>(): os << \"\\\"int32\\\"\"; break;\n case Struct::GetIndexFromType<int64_t>(): os << \"\\\"int64\\\"\"; break;\n case Struct::GetIndexFromType<float>(): os << \"\\\"float\\\"\"; break;\n case Struct::GetIndexFromType<OffsetString>(): os << \"\\\"string\\\"\"; break;\n case Struct::GetIndexFromType<FixStringTag>():\n os << \"{\\\"fix_string\\\", \" << type->items[i].size << \"}\";\n break;\n case Struct::GetIndexFromType<PaddingTag>():\n os << \"{\\\"padding\\\", \" << type->items[i].size << \"}\";\n break;\n }\n }\n\n os << \"}, {\\n\";\n for (const auto& m : messages)\n {\n Indent(os, indent+1) << '{';\n for (size_t i = 0; i < m->GetSize(); ++i)\n {\n if (i != 0) os << \", \";\n m->Visit<void>(i, Print{os});\n }\n os << \"},\\n\";\n }\n Indent(os, indent) << \"})\";\n }\n\n void Gbnl::RecalcSize()\n {\n size_t len = 0, count = 0;\n for (size_t i = 0; i < type->item_count; ++i)\n switch (type->items[i].idx)\n {\n case Struct::GetIndexFromType<int8_t>(): len += 1; ++count; break;\n case Struct::GetIndexFromType<int16_t>(): len += 2; ++count; break;\n case Struct::GetIndexFromType<int32_t>(): len += 4; ++count; break;\n case Struct::GetIndexFromType<int64_t>(): len += 8; ++count; break;\n case Struct::GetIndexFromType<float>(): len += 4; ++count; break;\n case Struct::GetIndexFromType<OffsetString>(): len += 4; ++count; break;\n case Struct::GetIndexFromType<FixStringTag>():\n len += type->items[i].size; ++count; break;\n case Struct::GetIndexFromType<PaddingTag>():\n len += type->items[i].size; break;\n }\n msg_descr_size = len;\n real_item_count = count;\n\n std::map<std::string, size_t> offset_map;\n size_t offset = 0;\n for (auto& m : messages)\n {\n LIBSHIT_ASSERT(m->GetType() == type);\n for (size_t i = 0; i < m->GetSize(); ++i)\n if (m->Is<OffsetString>(i))\n {\n auto& os = m->Get<OffsetString>(i);\n if (os.offset == static_cast<uint32_t>(-1)) continue;\n auto x = offset_map.emplace(os.str, offset);\n if (x.second) // new item inserted\n offset += os.str.size() + 1;\n os.offset = x.first->second;\n }\n }\n msgs_size = offset;\n }\n\n FilePosition Gbnl::GetSize() const noexcept\n {\n FilePosition ret = msg_descr_size * messages.size();\n ret = Align(ret) + sizeof(TypeDescriptor) * real_item_count;\n ret = Align(ret) + msgs_size;\n ret = Align(ret) + sizeof(Header);\n return ret;\n }\n\n FilePosition Gbnl::Align(FilePosition x) const noexcept\n {\n return is_gstl ? x : ((x+15) & ~15);\n }\n\n static const char SEP_DASH_DATA[] = {\n#define REP_MACRO(x,y,z) char(0x81), char(0x5c),\n BOOST_PP_REPEAT(40, REP_MACRO, )\n#undef REP_MACRO\n ' '\n };\n static const std::string_view SEP_DASH{\n SEP_DASH_DATA, sizeof(SEP_DASH_DATA)};\n\n static const char SEP_DASH_UTF8_DATA[] = {\n#define REP_MACRO(x,y,z) char(0xe2), char(0x80), char(0x95),\n BOOST_PP_REPEAT(40, REP_MACRO, )\n#undef REP_MACRO\n ' '\n };\n static const std::string_view SEP_DASH_UTF8{\n SEP_DASH_UTF8_DATA, sizeof(SEP_DASH_UTF8_DATA)};\n\n\n std::optional<int32_t> Gbnl::GetId(\n bool simple, const Gbnl::Struct& m, size_t i, size_t j, size_t& k) const\n {\n size_t this_k;\n if (m.Is<Gbnl::OffsetString>(i))\n {\n if (m.Get<Gbnl::OffsetString>(i).offset == static_cast<uint32_t>(-1))\n return {};\n this_k = ++k;\n }\n else if (m.Is<Gbnl::FixStringTag>(i))\n this_k = (flags && field_28 != 1) ? 10000 : 0;\n else\n return {};\n\n if (simple) return std::int32_t(i + j*1000);\n\n // hack\n if (!is_gstl && m.Is<int32_t>(0) && (\n (i == 8 && m.GetSize() == 9) || // rebirths\n (i == 105 && m.GetSize() == 107))) // vii\n return m.Get<int32_t>(0);\n else if (is_gstl && m.GetSize() == 3 && m.Is<int32_t>(1))\n {\n if (STRTOOL_COMPAT && i == 0) return -1;\n return m.Get<int32_t>(1) + 100000*(i==0);\n }\n else\n return this_k*10000+j;\n }\n\n void Gbnl::WriteTxt_(std::ostream& os) const\n {\n bool utf8 = export_sep == Separator::UTF8 ||\n (export_sep == Separator::AUTO && field_30 == 8);\n auto sep = utf8 ? SEP_DASH_UTF8 : SEP_DASH;\n size_t j = 0;\n for (const auto& m : messages)\n {\n size_t k = 0;\n for (size_t i = 0; i < m->GetSize(); ++i)\n {\n auto id = GetId(simple_ids, *m, i, j, k);\n if (id)\n {\n std::string str;\n if (m->Is<FixStringTag>(i))\n str = m->Get<FixStringTag>(i).str;\n else\n str = m->Get<OffsetString>(i).str;\n boost::replace_all(str, \"\\n\", \"\\r\\n\");\n\n if constexpr (STRTOOL_COMPAT)\n boost::replace_all(str, \"#n\", \"\\r\\n\");\n\n if (!STRTOOL_COMPAT || !str.empty())\n {\n os.write(sep.data(), sep.size());\n if (simple_ids) os << '#';\n os << *id << \"\\r\\n\" << str << \"\\r\\n\";\n }\n }\n }\n ++j;\n }\n os.write(sep.data(), sep.size());\n os << \"EOF\\r\\n\";\n }\n\n size_t Gbnl::FindDst(bool simple, int32_t id, std::vector<StructPtr>& messages,\n size_t& index) const\n {\n if (simple)\n {\n index = id / 1000;\n return id % 1000;\n }\n\n auto size = messages.size();\n for (size_t j = 0; j < size; ++j)\n {\n auto j2 = (index+j) % size;\n auto& m = messages[j2];\n size_t k = 0;\n for (size_t i = 0; i < m->GetSize(); ++i)\n {\n auto tid = GetId(false, *m, i, j2, k);\n if (tid && *tid == id)\n {\n index = j2;\n return i;\n }\n }\n }\n return -1;\n }\n\n void Gbnl::ReadTxt_(std::istream& is)\n {\n std::string line, msg;\n size_t last_index = 0, pos = -1;\n\n while (is.good())\n {\n std::getline(is, line);\n\n size_t offs;\n if ((boost::algorithm::starts_with(line, SEP_DASH) &&\n (offs = SEP_DASH.size())) ||\n (boost::algorithm::starts_with(line, SEP_DASH_UTF8) &&\n (offs = SEP_DASH_UTF8.size())))\n {\n if (pos != static_cast<size_t>(-1))\n {\n LIBSHIT_ASSERT(msg.empty() || msg.back() == '\\n');\n if (!msg.empty()) msg.pop_back();\n auto& m = messages[last_index];\n if (m->Is<OffsetString>(pos))\n m->Get<OffsetString>(pos).str = std::move(msg);\n else\n strncpy(m->Get<FixStringTag>(pos).str, msg.c_str(),\n m->GetSize(pos)-1);\n msg.clear();\n }\n\n if (line.compare(offs, 3, \"EOF\") == 0)\n {\n RecalcSize();\n return;\n }\n bool simple = false;\n if (line[offs] == '#') simple = true, ++offs;\n int32_t id = std::strtol(line.data() + offs, nullptr, 10);\n pos = FindDst(simple, id, messages, last_index);\n if (pos == static_cast<size_t>(-1))\n {\n LIBSHIT_THROW(\n Libshit::DecodeError, \"GbnlTxt: invalid id in input\",\n \"Failed id\", id);\n }\n }\n else\n {\n if (pos == static_cast<size_t>(-1))\n LIBSHIT_THROW(\n Libshit::DecodeError, \"GbnlTxt: data before separator\");\n if (!line.empty() && line.back() == '\\r') line.pop_back();\n msg.append(line).append(1, '\\n');\n }\n }\n LIBSHIT_THROW(Libshit::DecodeError, \"GbnlTxt: EOF\");\n }\n\n static OpenFactory gbnl_open{[](const Source& src) -> Libshit::SmartPtr<Dumpable>\n {\n if (src.GetSize() < sizeof(Gbnl::Header)) return nullptr;\n char buf[4];\n src.PreadGen(0, buf);\n if (memcmp(buf, \"GST\", 3) == 0)\n return Libshit::MakeSmart<Gbnl>(src);\n src.PreadGen(src.GetSize() - sizeof(Gbnl::Header), buf);\n if (memcmp(buf, \"GBN\", 3) == 0)\n return Libshit::MakeSmart<Gbnl>(src);\n\n return nullptr;\n }};\n\n}\n\n#include <libshit/container/vector.lua.hpp>\n\nNEPTOOLS_DYNAMIC_STRUCT_LUAGEN(\n gbnl, int8_t, int16_t, int32_t, int64_t, float,\n ::Neptools::Gbnl::OffsetString, ::Neptools::Gbnl::FixStringTag,\n ::Neptools::Gbnl::PaddingTag);\nLIBSHIT_STD_VECTOR_LUAGEN(gbnl_struct, Neptools::Gbnl::StructPtr);\n\n#include \"gbnl.binding.hpp\"\n" }, { "alpha_fraction": 0.6467065811157227, "alphanum_fraction": 0.6546906232833862, "avg_line_length": 21.772727966308594, "blob_id": "a047bbae8ec7d4541c207b56acde7271398e4b7b", "content_id": "785cbeb12dce5271ae51b9d081ed29d27b24d212", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1002, "license_type": "permissive", "max_line_length": 77, "num_lines": 44, "path": "/src/vita_plugin/taihen_cpp.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef GUARD_CRANIALLY_GENEVESE_DISOMY_DISCLOUTS_4156\n#define GUARD_CRANIALLY_GENEVESE_DISOMY_DISCLOUTS_4156\n#pragma once\n\n#include <libshit/except.hpp>\n\n#include <utility>\n#include <taihen.h>\n\nnamespace Neptools::VitaPlugin\n{\n\n // replacement for tai_hook_ref_t and TAI_CONTINUE that works in c++\n template <typename F> class TaiHook;\n template <typename Res, typename... Args>\n class TaiHook<Res(Args...)>\n {\n public:\n Res operator()(Args... args)\n {\n return (n->next ? n->next->func : n->old)(std::forward<Args>(args)...);\n };\n\n operator uintptr_t*() { return reinterpret_cast<uintptr_t*>(&n); }\n operator uintptr_t() { return reinterpret_cast<uintptr_t>(n); }\n\n private:\n using FuncPtr = Res(*)(Args...);\n struct Node\n {\n Node* next;\n FuncPtr func, old;\n };\n Node* n;\n };\n\n inline static const char* TAI_MAIN_MOD_STR =\n reinterpret_cast<const char*>(TAI_MAIN_MODULE);\n\n LIBSHIT_GEN_EXCEPTION_TYPE(TaiError, std::runtime_error);\n\n}\n\n#endif\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7318982481956482, "avg_line_length": 24.549999237060547, "blob_id": "c7f7b559f8c531285440d9d78ea9b966ded51678", "content_id": "2c8dbe48b251fb5cdfb1428a4b690dd3a013b340", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 511, "license_type": "permissive", "max_line_length": 92, "num_lines": 20, "path": "/tools/qemu_vdso_fix_linux_amd64.c", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "/* Workaround qemu-x86_64 not supporting either of vdso/vsyscall and old glibc\n * versions unconditionally using vsyscall when vdso is not available (no\n * syscall fallback). */\n\n/* Compile:\n * clang -O2 -shared -o tools/qemu_vdso_fix_linux_amd64.so tools/qemu_vdso_fix_linux_amd64.c\n */\n\n#ifndef _GNU_SOURCE\n#define _GNU_SOURCE\n#endif\n\n#include <sys/syscall.h>\n#include <sys/time.h>\n#include <unistd.h>\n\nint gettimeofday(struct timeval* tv, struct timezone* tz)\n{\n return syscall(SYS_gettimeofday, tv, tz);\n}\n" }, { "alpha_fraction": 0.6526687741279602, "alphanum_fraction": 0.6979963183403015, "avg_line_length": 48.49166488647461, "blob_id": "605776d2c6d500197a80f0385dbc70836266c2f9", "content_id": "abb28a8917ae996ab69eff8b90985fa1e78ba782", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 29695, "license_type": "permissive", "max_line_length": 141, "num_lines": 600, "path": "/src/format/stsc/instruction.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_0A01B0B9_DA9A_4A05_919B_A5503594CA9D\n#define UUID_0A01B0B9_DA9A_4A05_919B_A5503594CA9D\n#pragma once\n\n#include \"file.hpp\"\n#include \"../../source.hpp\"\n#include \"../item.hpp\"\n\n#include <libshit/lua/auto_table.hpp>\n\n#include <boost/endian/arithmetic.hpp>\n\nnamespace Neptools::Stsc\n{\n\n class InstructionBase : public Item\n {\n LIBSHIT_LUA_CLASS;\n public:\n InstructionBase(Key k, Context& ctx, uint8_t opcode)\n : Item{k, ctx}, opcode{opcode} {}\n\n static InstructionBase& CreateAndInsert(ItemPointer ptr, Flavor f);\n\n const uint8_t opcode;\n\n protected:\n void InstrDump(Sink& sink) const;\n std::ostream& InstrInspect(std::ostream& os, unsigned indent) const;\n\n private:\n virtual void PostInsert(Flavor f) = 0;\n };\n\n using Tagged = uint32_t;\n struct Code;\n\n template <typename T> struct TupleTypeMap { using Type = T; };\n template<> struct TupleTypeMap<std::string> { using Type = LabelPtr; };\n template<> struct TupleTypeMap<void*> { using Type = LabelPtr; };\n template<> struct TupleTypeMap<Code*> { using Type = LabelPtr; };\n\n template <typename T>\n using TupleTypeMapT = typename TupleTypeMap<T>::Type;\n\n // namegen\n template <char... Args> struct StringContainer\n {\n template <char... X> using Append = StringContainer<Args..., X...>;\n static inline constexpr const char str[sizeof...(Args)+1] = { Args... };\n };\n\n template <typename Cnt, typename... Args> struct AppendTypes;\n template <typename Cnt> struct AppendTypes<Cnt> { using Type = Cnt; };\n#define NEPTOOLS_GEN(x, ...) \\\n template <typename Cnt, typename... Args> \\\n struct AppendTypes<Cnt, x, Args...> \\\n { \\\n using Type = typename AppendTypes<typename Cnt::template Append< \\\n '_',__VA_ARGS__>, Args...>::Type; \\\n }\n NEPTOOLS_GEN(uint8_t, 'u','i','n','t','8');\n NEPTOOLS_GEN(uint16_t, 'u','i','n','t','1','6');\n NEPTOOLS_GEN(uint32_t, 'u','i','n','t','3','2');\n NEPTOOLS_GEN(float, 'f','l','o','a','t');\n NEPTOOLS_GEN(std::string, 's','t','r','i','n','g');\n NEPTOOLS_GEN(Code*, 'c','o','d','e');\n NEPTOOLS_GEN(void*, 'd','a','t','a');\n#undef NEPTOOLS_GEN\n\n template <bool NoReturn, typename... Args>\n class SimpleInstruction final : public InstructionBase\n {\n using Pref = StringContainer<\n 'n','e','p','t','o','o','l','s','.','s','t','s','c','.',\n 's','i','m','p','l','e','_','i','n','s','t','r','u','c','t','i','o','n','_'>;\n using Boold = std::conditional_t<\n NoReturn,\n Pref::Append<'t','r','u','e'>,\n Pref::Append<'f','a','l','s','e'>>;\n using TypeName = typename AppendTypes<Boold, Args...>::Type;\n\n LIBSHIT_DYNAMIC_OBJ_GEN;\n public:\n static constexpr const char* TYPE_NAME = TypeName::str;\n\n SimpleInstruction(Key k, Context& ctx, uint8_t opcode, Source src);\n SimpleInstruction(\n Key k, Context& ctx, uint8_t opcode, TupleTypeMapT<Args>... args)\n : InstructionBase{k, ctx, opcode}, args{std::move(args)...} {}\n\n static const FilePosition SIZE;\n FilePosition GetSize() const noexcept override { return SIZE; }\n\n using ArgsT = std::tuple<TupleTypeMapT<Args>...>;\n ArgsT args;\n\n private:\n void Parse_(Context& ctx, Source& src);\n void Dump_(Sink& sink) const override;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n void PostInsert(Flavor f) override;\n };\n\n class InstructionRndJumpItem final : public InstructionBase\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n InstructionRndJumpItem(Key k, Context& ctx, uint8_t opcode, Source src);\n FilePosition GetSize() const noexcept override { return 2 + tgts.size()*4; }\n\n LIBSHIT_LUAGEN(get=\"::Libshit::Lua::GetSmartOwnedMember\")\n std::vector<Libshit::NotNull<LabelPtr>> tgts;\n\n private:\n void Parse_(Context& ctx, Source& src);\n void Dump_(Sink& sink) const override;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n void PostInsert(Flavor f) override;\n };\n\n class UnimplementedInstructionItem final : public InstructionBase\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n UnimplementedInstructionItem(\n Key k, Context& ctx, uint8_t opcode, const Source&)\n : InstructionBase{k, ctx, opcode}\n { LIBSHIT_THROW(Libshit::DecodeError, \"Unimplemented instruction\"); }\n\n FilePosition GetSize() const noexcept override { return 0; }\n\n private:\n void Dump_(Sink&) const override {}\n void Inspect_(std::ostream&, unsigned) const override {}\n void PostInsert(Flavor) override {}\n };\n\n class InstructionJumpIfItem final : public InstructionBase\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n struct FixParams\n {\n boost::endian::little_uint16_t size;\n boost::endian::little_uint32_t tgt;\n\n void Validate(FilePosition rem_size, FilePosition size);\n };\n static_assert(sizeof(FixParams) == 6);\n\n struct NodeParams\n {\n boost::endian::little_uint8_t operation;\n boost::endian::little_uint32_t value;\n boost::endian::little_uint16_t left;\n boost::endian::little_uint16_t right;\n\n void Validate(uint16_t size);\n };\n static_assert(sizeof(NodeParams) == 9);\n\n struct Node : Libshit::Lua::ValueObject\n {\n uint8_t operation = 0;\n uint32_t value = 0;\n size_t left = 0, right = 0;\n\n Node() = default;\n Node(uint8_t operation, uint32_t value, size_t left, size_t right)\n : operation{operation}, value{value}, left{left}, right{right} {}\n LIBSHIT_LUA_CLASS;\n };\n\n InstructionJumpIfItem(Key k, Context& ctx, uint8_t opcode, Source src);\n InstructionJumpIfItem(Key k, Context& ctx, uint8_t opcode,\n Libshit::NotNull<LabelPtr> tgt, std::vector<Node> tree)\n : InstructionBase{k, ctx, opcode}, tgt{tgt}, tree{Libshit::Move(tree)} {}\n#if LIBSHIT_WITH_LUA\n InstructionJumpIfItem(\n Key k, Context& ctx, Libshit::Lua::StateRef vm, uint8_t opcode,\n Libshit::NotNull<LabelPtr> tgt, Libshit::Lua::RawTable tree);\n#endif\n\n FilePosition GetSize() const noexcept override\n { return 1 + sizeof(FixParams) + tree.size() * sizeof(NodeParams); }\n\n Libshit::NotNull<LabelPtr> tgt;\n LIBSHIT_LUAGEN(get=\"::Libshit::Lua::GetSmartOwnedMember\")\n std::vector<Node> tree;\n\n void Dispose() noexcept override;\n\n private:\n void Parse_(Context& ctx, Source& src);\n void Dump_(Sink& sink) const override;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n void InspectNode(std::ostream& os, size_t i) const;\n void PostInsert(Flavor f) override;\n };\n\n class InstructionJumpSwitchItemNoire : public InstructionBase\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n struct FixParams\n {\n boost::endian::little_uint32_t expected_val;\n boost::endian::little_uint16_t size;\n\n void Validate(FilePosition rem_size);\n };\n static_assert(sizeof(FixParams) == 6);\n\n struct ExpressionParams\n {\n boost::endian::little_uint32_t expression;\n boost::endian::little_uint32_t tgt;\n\n void Validate(FilePosition size);\n };\n static_assert(sizeof(ExpressionParams) == 8);\n\n struct Expression : Libshit::Lua::ValueObject\n {\n uint32_t expression;\n Libshit::NotNull<LabelPtr> target;\n\n Expression(uint32_t expression, Libshit::NotNull<LabelPtr> target)\n : expression{expression}, target{std::move(target)} {}\n LIBSHIT_LUA_CLASS;\n };\n\n\n InstructionJumpSwitchItemNoire(\n Key k, Context& ctx, uint8_t opcode, Source src);\n InstructionJumpSwitchItemNoire(\n Key k, Context& ctx, uint8_t opcode, uint32_t expected_val,\n bool last_is_default, Libshit::AT<std::vector<Expression>> expressions)\n : InstructionBase{k, ctx, opcode}, expected_val{expected_val},\n last_is_default{last_is_default},\n expressions{Libshit::Move(expressions)} {}\n\n\n FilePosition GetSize() const noexcept override\n { return 1 + sizeof(FixParams) + expressions.size() * sizeof(ExpressionParams); }\n\n uint32_t expected_val;\n bool last_is_default;\n\n LIBSHIT_LUAGEN(get=\"::Libshit::Lua::GetSmartOwnedMember\")\n std::vector<Expression> expressions;\n\n void Dispose() noexcept override;\n\n protected:\n InstructionJumpSwitchItemNoire(Key k, Context& ctx, uint8_t opcode)\n : InstructionBase{k, ctx, opcode} {}\n\n void Parse_(Context& ctx, Source& src);\n void Dump_(Sink& sink) const override;\n void InspectBase(std::ostream& os, unsigned indent) const;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n void PostInsert(Flavor f) override;\n };\n\n class InstructionJumpSwitchItemPotbb final : public InstructionJumpSwitchItemNoire\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n\n InstructionJumpSwitchItemPotbb(\n Key k, Context& ctx, uint8_t opcode, Source src);\n InstructionJumpSwitchItemPotbb(\n Key k, Context& ctx, uint8_t opcode, uint32_t expected_val,\n bool last_is_default, Libshit::AT<std::vector<Expression>> expressions,\n uint8_t trailing_byte)\n : InstructionJumpSwitchItemNoire{\n k, ctx, opcode, expected_val, last_is_default, Libshit::Move(expressions)},\n trailing_byte{trailing_byte} {}\n\n FilePosition GetSize() const noexcept override\n { return 1 + InstructionJumpSwitchItemNoire::GetSize(); }\n\n uint8_t trailing_byte;\n\n private:\n void Parse_(Context& ctx, Source& src);\n void Dump_(Sink& sink) const override;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n };\n\n // compile time map of opcode->instruction classes\n template <Flavor F, uint8_t Opcode> struct InstructionMap\n { using Type = SimpleInstruction<false>; };\n\n // In POTBB dummy instructions skip one byte...\n template <uint8_t Opcode> struct InstructionMap<Flavor::POTBB, Opcode>\n { using Type = SimpleInstruction<false, uint8_t>; };\n\n#define NEPTOOLS_OPCODE(flavor, id, ...) \\\n template<> struct InstructionMap<Flavor::flavor, id> \\\n { using Type = __VA_ARGS__; }\n#define NEPTOOLS_SIMPLE_OPCODE(flavor, id, ...) \\\n NEPTOOLS_OPCODE(flavor, id, SimpleInstruction<__VA_ARGS__>)\n\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x01, true);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x04, true);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x05, false, uint32_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x06, false, Code*);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x07, true);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x0a, false, Code*);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x0b, false, uint8_t, void*);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x0c, false, uint8_t);\n NEPTOOLS_OPCODE(NOIRE, 0x0d, InstructionRndJumpItem);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x0e, false, std::string);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x0f, true, std::string, std::string);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x10, false, Tagged, Code*);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x11, false, Tagged, Code*);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x12, false, uint32_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x13, false, Tagged, uint8_t, uint32_t, Code*);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x14, false, Tagged, uint8_t, uint32_t, Code*);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x15, false, Tagged, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x16, false, Tagged, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x17, false, Tagged, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x18, false, Tagged, Tagged);\n NEPTOOLS_OPCODE(NOIRE, 0x19, UnimplementedInstructionItem); // noreturn\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x1a, false, Code*);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x1b, true);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x1c, false, uint8_t);\n NEPTOOLS_OPCODE(NOIRE, 0x1d, InstructionJumpIfItem);\n NEPTOOLS_OPCODE(NOIRE, 0x1e, InstructionJumpSwitchItemNoire);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x1f, false, Tagged, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x20, false, uint8_t, void*, void*);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x21, false, void*, void*);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x22, false, void*, void*);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x23, false, void*, void*);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x24, false, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x30, false, std::string, uint8_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x31, false, uint8_t, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x32, false, float, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x33, false, uint32_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x34, false, uint32_t, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x35, false, uint32_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x36, false, uint32_t, float, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x37, false, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x38, false, std::string);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x39, false, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x3a, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x3f, false, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x40, false, Tagged, uint16_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x41, false, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x42, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x43, false, uint16_t, uint16_t, uint16_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x44, false, float, uint16_t, uint8_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x45, false, uint8_t, uint32_t, uint8_t, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x46, false, uint8_t, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x47, false, uint8_t, uint16_t, uint16_t, uint16_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x48, false, uint8_t, uint16_t, uint16_t, uint16_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x49, false, uint8_t, float, uint16_t, uint8_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x4a, false, uint8_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x4b, false, uint8_t, uint8_t, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x4c, false, uint8_t, uint32_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x4d, false, uint8_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x4e, false, uint8_t, float, float, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x4f, false, std::string);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x50, false, uint16_t, uint16_t, std::string);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x51, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x53, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x54, false, uint8_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x55, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x57, false, uint8_t, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x58, false, uint8_t, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x59, false, uint8_t, uint8_t, uint8_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x5a, false, uint32_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x5b, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x5c, false, uint32_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x5d, false, uint8_t, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x5e, false, uint8_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x5f, false, uint16_t, uint8_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x60, false, Tagged, uint8_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x61, false, uint32_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x62, false, std::string);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x63, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x64, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x65, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x66, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x67, false, uint32_t, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x68, false, uint32_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x69, false, uint8_t, uint32_t, std::string);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x6a, false, uint16_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x6b, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x6c, false, uint32_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x6d, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x6e, false, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x6f, false, std::string, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x70, false, uint32_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x71, true, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x73, false, std::string);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x74, false, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x75, false, uint16_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x76, false, uint8_t, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x77, false, uint8_t, std::string);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x78, false, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x79, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x7a, false, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x7b, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x7c, false, uint32_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x7d, false, std::string);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x7e, false, uint8_t, uint32_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x7f, false, uint16_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x80, false, uint32_t, std::string);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x81, true);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x82, false, uint32_t, uint32_t, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x83, false, uint32_t, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x84, false, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x87, false, uint16_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x88, false, uint16_t, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x89, false, uint8_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x8a, false, uint8_t, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x8b, false, uint8_t, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x8c, false, uint32_t, uint32_t, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x8d, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x8e, false, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x8f, false, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x90, false, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x91, false, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x92, false, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x93, false, std::string, uint8_t, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x94, false, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x95, false, std::string, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x96, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x97, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x98, false, uint16_t, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0x99, false, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xa0, false, void*);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xa1, false, uint8_t, void*, uint16_t, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xa2, false, uint16_t, void*, uint16_t, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xa3, false, std::string);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xa5, false, void*);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xa6, false, uint8_t, void*, uint16_t, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xa7, false, uint8_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xa8, false, uint8_t, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xa9, false, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xaa, false, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xab, false, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xb0, false, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xb1, false, uint16_t, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xb3, false, uint16_t, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xb4, false, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xb5, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xd0, false, uint32_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xd1, false, uint32_t, uint8_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xd2, false, uint32_t, uint8_t, uint8_t, float);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xd3, false, uint32_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xd4, false, uint32_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xd5, false, uint32_t, uint16_t, float, float, float, float, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xd6, false, uint32_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xd7, false, uint32_t, float, float, float, float, uint16_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xd8, false, uint8_t, uint8_t, float, float, float, float, uint16_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xd9, false, uint32_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xda, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xdb, false, uint8_t, uint16_t, uint8_t, uint8_t, float, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xdc, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xdd, false, uint32_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xdf, false, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xf0, false, uint8_t, Tagged);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xf1, false, uint8_t, uint16_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xf2, false, uint8_t, std::string);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xf3, false, uint8_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xf4, false, std::string);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xf5, false, uint16_t, uint8_t);\n NEPTOOLS_SIMPLE_OPCODE(NOIRE, 0xf7, false, uint16_t, uint8_t);\n\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x00, false); // Nop\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x01, true); // Exit\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x02, true); // Cont\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x03, false, uint8_t /*ignored*/); // Endv\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x04, true); // InfiniWait (infinite loop)\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x05, false, uint32_t); // VWait\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x06, false, Code*); // Goto (actually, call)\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x07, true); // Return\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x08, false); // RetAddrPush\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x09, false); // RetAddrPop\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x0a, false, uint32_t /*ignored*/); // Call1V\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x0b, false, uint8_t, void*); // SubStart\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x0c, false, uint8_t); // SubStop\n NEPTOOLS_OPCODE(POTBB, 0x0d, InstructionRndJumpItem); // RndJump\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x0e, false, std::string /*ignored*/); // Printf\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x0f, true, std::string); // FileJump\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x10, false, Tagged, Code*); // IsFlg\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x11, false, Tagged, Code*); // NgFlg\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x12, false, Tagged, uint8_t); // FlgSw\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x13, false, Tagged, uint8_t, Tagged, Code*); // IsPrm\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x14, false, Tagged, uint8_t, Tagged, Code*); // NgPrm\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x15, false, Tagged, Tagged); // SetPrm\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x16, false, Tagged, Tagged); // SetPrmWk\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x17, false, Tagged, Tagged); // AddPrm\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x18, false, Tagged, Tagged); // AddPrmWk\n // Tagged, Code*... (unknown count, impossible to determine)\n NEPTOOLS_OPCODE(POTBB, 0x19, UnimplementedInstructionItem); // noreturn, PrmBranch\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x1a, false, Code*); // Call\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x1b, true); // CallRet\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x1c, true, uint8_t); // SubEndWait\n NEPTOOLS_OPCODE(POTBB, 0x1d, InstructionJumpIfItem); // JumpIf\n NEPTOOLS_OPCODE(POTBB, 0x1e, InstructionJumpSwitchItemPotbb); // JumpSwitch\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x1f, false, Tagged, uint16_t); // RandPrm\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x20, false, uint8_t, void*, void*); // DataBaseParam\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x21, false, uint16_t); // CourseFlag\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x22, false, uint16_t); // SetNowScenario\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x23, false, uint16_t); // CharEntry\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x24, false, uint16_t); // CrossFade\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x25, false, uint8_t, uint16_t, uint8_t); // PatternCrossFade\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x26, false, uint8_t); // DispTone\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x27, false, uint8_t); // Monologue\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x28, false, uint16_t, uint8_t /*unused*/, uint8_t, uint16_t, uint16_t, uint16_t, float, uint8_t); // ExiPlay\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x29, false, uint8_t /*unused*/, uint8_t); // ExiStop\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x2a, false, uint8_t, uint8_t, uint8_t, uint16_t, uint8_t); // PatternFade\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x2b, false, float, uint8_t, uint8_t); // Ambiguous\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x2c, false, float, float, uint16_t); // AmbiguousFade\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x2d, false, uint32_t /*unused*/); // TouchWait\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x2e, false, Tagged, uint16_t); // CourseFlagGet\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x2f, false, uint16_t); // Chapter\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x30, false, std::string, uint8_t, uint8_t); // Movie\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x31, false, uint8_t, uint16_t); // BgmPlay\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x32, false, float, uint16_t); // BgmVolume\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x33, false, uint32_t, uint8_t); // SePlay\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x34, false, uint32_t, uint16_t); // SeStop\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x35, false, uint32_t, uint8_t); // SeWait\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x36, false, uint32_t, float, uint16_t); // SeVolume\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x37, false, uint16_t); // SeAllStop\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x38, false, std::string); // VoicePlay\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x39, false, uint16_t); // VoiceStop\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x3a, false, uint8_t); // VoiceWait\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x3b, false, Tagged); // VoiceVolumePlay\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x3e, false, uint32_t /*unused*/); // BackLogReset\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x3f, false, Tagged); // GetCountry\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x40, false, uint32_t, uint16_t, uint8_t); // BgOpen\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x41, false, uint16_t); // BgClose\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x42, false, uint16_t, uint16_t); // BgFrame\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x43, false, uint16_t, uint16_t, uint16_t, uint8_t); // BgMove\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x44, false, float, uint16_t, uint8_t, uint8_t); // BgScale\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x45, false, uint8_t, uint32_t, uint8_t, uint16_t); // BustOpen\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x46, false, uint8_t, uint16_t); // BustClose\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x47, false, uint8_t, uint16_t, uint16_t, uint16_t, uint8_t); // BustClose\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x48, false, uint8_t, uint16_t, uint16_t, uint16_t /*unused*/, uint8_t); // BustMoveAdd\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x49, false, uint8_t, float, uint16_t, uint8_t, uint8_t); // BustScale\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x4a, false, uint8_t, uint8_t); // BustPriority\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x4b, false, uint8_t, uint8_t, uint8_t, uint16_t); // BustQuake\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x4c, false, uint8_t); // SetEntryCharFlg\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x4d, false, uint16_t /*unused*/); // BustTone\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x4e, false, uint8_t, float, float, uint16_t); // BustFade\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x4f, false, std::string); // Name\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x50, false, uint16_t, uint16_t, std::string, uint8_t, uint16_t); // Message\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x51, false, uint8_t); // MessageWait\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x52, false); // MessageWinClose\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x53, false, uint8_t); // MessageFontSize\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x54, false, uint16_t, uint16_t); // MessageQuake\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x55, false, uint8_t); // Trophy\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x56, false); // MessageDelete\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x57, false, uint16_t, uint16_t); // Quake\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x58, false, uint8_t, uint8_t, uint16_t); // Fade\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x59, false, Code* /*guess*/, std::string, uint16_t); // Choice\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x5a, true); // ChoiceStart\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x5b, false, Tagged); // GetBg\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x5c, false, uint16_t); // FontColor\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x5d, false, uint8_t); // WorldType\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x5e, false, Tagged); // GetWorld\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x5f, true, uint16_t); // FlowChart\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x60, true, std::string); // MiniGame\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x61, false, Tagged, uint16_t); // CourseOpenGet\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x62, false); // SystemSave\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x63, false, uint8_t); // BackLogNg\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x64, false, uint8_t); // EventSkipNg\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x65, false, uint8_t); // EventAutoNg\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x66, false, uint8_t); // StopNg\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x67, false); // DataSave\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x68, false); // SkipStop\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x69, false, std::string, std::string); // MessageVoice\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x6a, false, std::string, std::string); // MessageVoice2\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x6b, false, uint8_t); // SaveNg\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x6f, false, std::string, uint8_t); // Dialog\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x70, false, uint16_t, uint8_t); // ExiLoopStop\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x71, false, uint16_t, uint8_t); // ExiEndWait\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x72, false, uint8_t); // ClearSet\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x73, false, std::string); // SaveTitleSet\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x78, false, uint16_t); // VideoFlg\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x79, false, uint16_t, uint16_t /*unused*/); // AlbumFlg\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x7a, false, uint8_t); // WaitFlg\n NEPTOOLS_SIMPLE_OPCODE(POTBB, 0x7b, false, uint8_t); // AudioFlg\n\n\n#undef NEPTOOLS_OPCODE\n#undef NEPTOOLS_SIMPLE_OPCODE\n\n template <Flavor F, uint8_t Opcode>\n using InstructionItem = typename InstructionMap<F, Opcode>::Type;\n}\n\n#endif\n" }, { "alpha_fraction": 0.6052631735801697, "alphanum_fraction": 0.6081871390342712, "avg_line_length": 21.064516067504883, "blob_id": "5ad2056117633fcfa08a401af1e9c9d8278577a5", "content_id": "bf21c38b13775420008e7f3e3108a7131b1b0d1a", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 684, "license_type": "permissive", "max_line_length": 86, "num_lines": 31, "path": "/tools/ci_conf_linuxcommon.sh", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "function do_strip()\n{\n local f=\"$1\"\n run objcopy --only-keep-debug \"$f\" \"$f.debug\"\n run chmod -x \"$f.debug\"\n run strip --strip-unneeded -R .comment -R .GCC.command.line -R .gnu_debuglink \"$f\"\n run objcopy --add-gnu-debuglink=\"$f.debug\" \"$f\"\n}\n\nfunction after_build()\n{\n for f in stcm-editor libshit/ext/luajit-ljx; do\n [[ -f \"build/$f\" ]] && do_strip \"build/$f\"\n done\n}\n\nfunction join()\n{\n local IFS=$1\n shift\n echo \"$*\"\n}\n\nvalgrind=\"valgrind --suppressions=tools/valgrind.supp --leak-check=full \\\n--track-origins=yes --show-leak-kinds=all --xml=yes \\\n--xml-file=valgrind.xml build/stcm-editor --test\"\n\ntests=(\n \"${tests[@]}\"\n \"$valgrind\"\n)\n" }, { "alpha_fraction": 0.5534370541572571, "alphanum_fraction": 0.5870546698570251, "avg_line_length": 26.68055534362793, "blob_id": "5e1af1e675f95620da04c9091602df3a804df7f3", "content_id": "3cf70f2778d98bf2d29ef4b5f747b4b1e300cb85", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1993, "license_type": "permissive", "max_line_length": 81, "num_lines": 72, "path": "/src/format/primitive_item.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_2223739B_EEF5_4E62_B610_F34A86369503\n#define UUID_2223739B_EEF5_4E62_B610_F34A86369503\n#pragma once\n\n#include \"item.hpp\"\n#include \"raw_item.hpp\"\n#include \"sink.hpp\"\n\nnamespace Neptools\n{\n\n template <typename T, typename DumpT, typename Endian, char... Name>\n class PrimitiveItem final : public Item\n {\n static_assert(sizeof(T) == sizeof(DumpT));\n static_assert(sizeof(T) == sizeof(Endian));\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n using Type = T;\n\n PrimitiveItem(Key k, Context& ctx, T val)\n : Item{k, ctx}, value{val} {}\n PrimitiveItem(Key k, Context& ctx, Source src)\n : Item{k, ctx}\n {\n Union u;\n src.PreadGen<Libshit::Check::Throw>(0, u.dump);\n value = u.native;\n }\n static PrimitiveItem& CreateAndInsert(ItemPointer ptr)\n {\n auto x = RawItem::GetSource(ptr, -1);\n return x.ritem.SplitCreate<PrimitiveItem>(ptr.offset, x.src);\n }\n\n FilePosition GetSize() const noexcept override { return sizeof(T); }\n\n T value;\n\n private:\n union Union\n {\n T native;\n DumpT dump;\n };\n\n void Dump_(Sink& sink) const override\n {\n Union u{value};\n sink.WriteGen(Endian{u.dump});\n }\n void Inspect_(std::ostream& os, unsigned indent) const override\n {\n Item::Inspect_(os, indent);\n static constexpr const char name[] = { Name..., 0 };\n os << name << '(' << value << ')';\n }\n };\n\n#define NEPTOOLS_PRIMITIVE_ITEMS(x) \\\n x(Int32Item, int32, PrimitiveItem< \\\n int32_t, int32_t, boost::endian::little_int32_t, 'i','n','t','3','2'>); \\\n x(FloatItem, float, PrimitiveItem< \\\n float, int32_t, boost::endian::little_int32_t, 'f','l','o','a','t'>)\n#define NEPTOOLS_GEN(cname, lname, ...) \\\n using cname LIBSHIT_LUAGEN(fullname=\"neptools.\"..#lname..\"_item\") = __VA_ARGS__\n NEPTOOLS_PRIMITIVE_ITEMS(NEPTOOLS_GEN);\n#undef NEPTOOLS_GEN\n\n}\n\n#endif\n" }, { "alpha_fraction": 0.6495619416236877, "alphanum_fraction": 0.7021276354789734, "avg_line_length": 25.633333206176758, "blob_id": "01103c19c4f3c90e6739f147d9a1af3d3dc34a0e", "content_id": "4b033e264cb00ed4cc5b94bed886cc0e2a41cbc5", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 799, "license_type": "permissive", "max_line_length": 75, "num_lines": 30, "path": "/src/txt_serializable.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_E17CE799_6569_40E4_A8FE_39F088AE30AB\n#define UUID_E17CE799_6569_40E4_A8FE_39F088AE30AB\n#pragma once\n\n#include <libshit/meta.hpp>\n#include <libshit/lua/type_traits.hpp>\n#include <libshit/lua/dynamic_object.hpp>\n\n#include <iosfwd>\n#include <string>\n\nnamespace Neptools\n{\n\n class TxtSerializable : public Libshit::Lua::DynamicObject\n {\n LIBSHIT_LUA_CLASS;\n public:\n LIBSHIT_NOLUA void WriteTxt(std::ostream& os) const { WriteTxt_(os); }\n LIBSHIT_NOLUA void WriteTxt(std::ostream&& os) const { WriteTxt_(os); }\n LIBSHIT_NOLUA void ReadTxt(std::istream& is) { ReadTxt_(is); }\n LIBSHIT_NOLUA void ReadTxt(std::istream&& is) { ReadTxt_(is); }\n\n private:\n virtual void WriteTxt_(std::ostream& os) const = 0;\n virtual void ReadTxt_(std::istream& is) = 0;\n };\n\n}\n#endif\n" }, { "alpha_fraction": 0.6409152150154114, "alphanum_fraction": 0.6410498023033142, "avg_line_length": 45.14906692504883, "blob_id": "d202c4777451327483f5fc5d1d4c63ee99d50e54", "content_id": "1bb9c9ba5460004049b3446517719e791120234a", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7430, "license_type": "permissive", "max_line_length": 333, "num_lines": 161, "path": "/src/format/item.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Label::TYPE_NAME[] = \"neptools.label\";\n\nconst char ::Neptools::Item::TYPE_NAME[] = \"neptools.item\";\n\nconst char ::Neptools::ItemWithChildren::TYPE_NAME[] = \"neptools.item_with_children\";\ntemplate <>\nconst char ::item::TYPE_NAME[] = \"libshit.parent_list_item\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.label\n template<>\n void TypeRegisterTraits<::Neptools::Label>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Label>::Make<LuaGetRef<std::string>, LuaGetRef<::Neptools::ItemPointer>>\n >(\"new\");\n bld.AddFunction<\n static_cast<const std::string & (::Neptools::Label::*)() const>(&::Neptools::Label::GetName)\n >(\"get_name\");\n bld.AddFunction<\n static_cast<const ::Neptools::ItemPointer & (::Neptools::Label::*)() const>(&::Neptools::Label::GetPtr)\n >(\"get_ptr\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Label> reg_neptools_label;\n\n // class neptools.item\n template<>\n void TypeRegisterTraits<::Neptools::Item>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Item, ::Neptools::Dumpable>();\n\n bld.AddFunction<\n static_cast<Libshit::RefCountedPtr<::Neptools::Context> (::Neptools::Item::*)() noexcept>(&::Neptools::Item::GetContextMaybe)\n >(\"get_context_maybe\");\n bld.AddFunction<\n static_cast<::Libshit::NotNull<Libshit::RefCountedPtr<::Neptools::Context> > (::Neptools::Item::*)()>(&::Neptools::Item::GetContext)\n >(\"get_context\");\n bld.AddFunction<\n static_cast<::Neptools::ItemWithChildren * (::Neptools::Item::*)() noexcept>(&::Neptools::Item::GetParent)\n >(\"get_parent\");\n bld.AddFunction<\n static_cast<::Neptools::FilePosition (::Neptools::Item::*)() const noexcept>(&::Neptools::Item::GetPosition)\n >(\"get_position\");\n bld.AddFunction<\n static_cast<void (::Neptools::Item::*)(const ::Libshit::NotNull<Libshit::RefCountedPtr<::Neptools::Item> > &)>(&::Neptools::Item::Replace<Check::Throw>)\n >(\"replace\");\n bld.AddFunction<\n TableRetWrap<static_cast<const ::Neptools::Item::LabelsContainer & (::Neptools::Item::*)() const>(&::Neptools::Item::GetLabels)>::Wrap\n >(\"get_labels\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Item> reg_neptools_item;\n\n // class neptools.item_with_children\n template<>\n void TypeRegisterTraits<::Neptools::ItemWithChildren>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::ItemWithChildren, ::Neptools::Item>();\n\n bld.AddFunction<\n OwnedSharedPtrWrap<static_cast<::Neptools::ItemList & (::Neptools::ItemWithChildren::*)() noexcept>(&::Neptools::ItemWithChildren::GetChildren)>::Wrap\n >(\"get_children\");\n LIBSHIT_LUA_RUNBC(bld, builder, 1); bld.SetField(\"build\");\n }\n static TypeRegister::StateRegister<::Neptools::ItemWithChildren> reg_neptools_item_with_children;\n\n // class libshit.parent_list_item\n template<>\n void TypeRegisterTraits<::item>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::item>::Make<>\n >(\"new\");\n bld.AddFunction<\n static_cast<void (::item::*)(::item &) noexcept>(&::item::swap)\n >(\"swap\");\n bld.AddFunction<\n static_cast<void (::item::*)(::item::reference)>(&::item::push_back<Check::Throw>)\n >(\"push_back\");\n bld.AddFunction<\n static_cast<void (::item::*)()>(&::item::pop_back<Check::Throw>)\n >(\"pop_back\");\n bld.AddFunction<\n static_cast<void (::item::*)(::item::reference)>(&::item::push_front<Check::Throw>)\n >(\"push_front\");\n bld.AddFunction<\n static_cast<void (::item::*)()>(&::item::pop_front<Check::Throw>)\n >(\"pop_front\");\n bld.AddFunction<\n static_cast<::item::reference (::item::*)()>(&::item::front<Check::Throw>)\n >(\"front\");\n bld.AddFunction<\n static_cast<::item::reference (::item::*)()>(&::item::back<Check::Throw>)\n >(\"back\");\n bld.AddFunction<\n static_cast<::item::size_type (::item::*)() const noexcept>(&::item::size)\n >(\"size\");\n bld.AddFunction<\n static_cast<bool (::item::*)() const noexcept>(&::item::empty)\n >(\"empty\");\n bld.AddFunction<\n static_cast<void (::item::*)(::item::size_type) noexcept>(&::item::shift_backwards)\n >(\"shift_backwards\");\n bld.AddFunction<\n static_cast<void (::item::*)(::item::size_type) noexcept>(&::item::shift_forward)\n >(\"shift_forward\");\n bld.AddFunction<\n static_cast<::item::iterator (::item::*)(::item::const_iterator)>(&::item::erase<Check::Throw>),\n static_cast<::item::iterator (::item::*)(::item::const_iterator, ::item::const_iterator)>(&::item::erase<Check::Throw>)\n >(\"erase\");\n bld.AddFunction<\n static_cast<void (::item::*)() noexcept>(&::item::clear)\n >(\"clear\");\n bld.AddFunction<\n static_cast<::item::iterator (::item::*)(::item::const_iterator, ::item::reference)>(&::item::insert<Check::Throw>)\n >(\"insert\");\n bld.AddFunction<\n static_cast<void (::item::*)(::item::const_iterator, ::item &)>(&::item::splice<Check::Throw>),\n static_cast<void (::item::*)(::item::const_iterator, ::item &, ::item::const_iterator)>(&::item::splice<Check::Throw>),\n static_cast<void (::item::*)(::item::const_iterator, ::item &, ::item::const_iterator, ::item::const_iterator)>(&::item::splice<Check::Throw>)\n >(\"splice\");\n bld.AddFunction<\n static_cast<void (::item::*)(::Libshit::Lua::FunctionWrapGen<bool>)>(&::item::sort<::Libshit::Lua::FunctionWrapGen<bool>>)\n >(\"sort\");\n bld.AddFunction<\n static_cast<void (::item::*)(::item &, ::Libshit::Lua::FunctionWrapGen<bool>)>(&::item::merge<::Libshit::Check::Throw, ::Libshit::Lua::FunctionWrapGen<bool>>)\n >(\"merge\");\n bld.AddFunction<\n static_cast<void (::item::*)() noexcept>(&::item::reverse)\n >(\"reverse\");\n bld.AddFunction<\n static_cast<void (::item::*)(::Libshit::Lua::FunctionWrapGen<bool>)>(&::item::remove_if<::Libshit::Lua::FunctionWrapGen<bool>>)\n >(\"remove_if\");\n bld.AddFunction<\n static_cast<void (::item::*)(::Libshit::Lua::FunctionWrapGen<bool>)>(&::item::unique<::Libshit::Lua::FunctionWrapGen<bool>>)\n >(\"unique\");\n bld.AddFunction<\n static_cast<::Libshit::Lua::RetNum (*)(::Libshit::Lua::StateRef, ::Libshit::ParentListLua<::Neptools::Item, ::Neptools::ItemListTraits, ::Libshit::ParentListBaseHookTraits<::Neptools::Item, ::Libshit::DefaultTag> >::FakeClass &, ::Neptools::Item &)>(::Libshit::ParentListLua<::Neptools::Item, ::Neptools::ItemListTraits>::Next)\n >(\"next\");\n bld.AddFunction<\n static_cast<::Libshit::Lua::RetNum (*)(::Libshit::Lua::StateRef, ::Libshit::ParentListLua<::Neptools::Item, ::Neptools::ItemListTraits, ::Libshit::ParentListBaseHookTraits<::Neptools::Item, ::Libshit::DefaultTag> >::FakeClass &, ::Neptools::Item &)>(::Libshit::ParentListLua<::Neptools::Item, ::Neptools::ItemListTraits>::Prev)\n >(\"prev\");\n bld.AddFunction<\n static_cast<::Libshit::Lua::RetNum (*)(::Libshit::Lua::StateRef, ::Libshit::ParentListLua<::Neptools::Item, ::Neptools::ItemListTraits, ::Libshit::ParentListBaseHookTraits<::Neptools::Item, ::Libshit::DefaultTag> >::FakeClass &)>(::Libshit::ParentListLua<::Neptools::Item, ::Neptools::ItemListTraits>::ToTable)\n >(\"to_table\");\n\n }\n static TypeRegister::StateRegister<::item> reg_libshit_parent_list_item;\n\n}\n#endif\n" }, { "alpha_fraction": 0.6097643375396729, "alphanum_fraction": 0.6299663186073303, "avg_line_length": 49.625, "blob_id": "5f3a85dba51ab3b3e3d407f69a33ec4c900497ed", "content_id": "b9a78fe3bf18e228d48d37d00d6438ffd3bc72ce", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8910, "license_type": "permissive", "max_line_length": 307, "num_lines": 176, "path": "/src/format/cl3.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Cl3::TYPE_NAME[] = \"neptools.cl3\";\n\nconst char ::Neptools::Cl3::Entry::TYPE_NAME[] = \"neptools.cl3.entry\";\ntemplate <>\nconst char ::cl3_entry::TYPE_NAME[] = \"libshit.ordered_map_cl3_entry\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.cl3\n template<>\n void TypeRegisterTraits<::Neptools::Cl3>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Cl3, ::Neptools::Dumpable>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Cl3>::Make<LuaGetRef<::Neptools::Source>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Cl3>::Make<LuaGetRef<::Neptools::Endian>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Cl3>::Make<LuaGetRef<::Libshit::Lua::StateRef>, LuaGetRef<::Neptools::Endian>, LuaGetRef<::uint32_t>, LuaGetRef<::Libshit::Lua::RawTable>>\n >(\"new\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Cl3, ::Neptools::Endian, &::Neptools::Cl3::endian>\n >(\"get_endian\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Cl3, ::Neptools::Endian, &::Neptools::Cl3::endian>\n >(\"set_endian\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Cl3, ::uint32_t, &::Neptools::Cl3::field_14>\n >(\"get_field_14\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Cl3, ::uint32_t, &::Neptools::Cl3::field_14>\n >(\"set_field_14\");\n bld.AddFunction<\n &::Libshit::Lua::GetRefCountedOwnedMember<::Neptools::Cl3, ::Neptools::Cl3::Entries, &::Neptools::Cl3::entries>\n >(\"get_entries\");\n bld.AddFunction<\n static_cast<::uint32_t (::Neptools::Cl3::*)(const Libshit::WeakSmartPtr<::Neptools::Cl3::Entry> &) const noexcept>(&::Neptools::Cl3::IndexOf)\n >(\"index_of\");\n bld.AddFunction<\n static_cast<::Neptools::Cl3::Entry & (::Neptools::Cl3::*)(std::string_view)>(&::Neptools::Cl3::GetOrCreateFile)\n >(\"get_or_create_file\");\n bld.AddFunction<\n static_cast<void (::Neptools::Cl3::*)(const ::boost::filesystem::path &) const>(&::Neptools::Cl3::ExtractTo)\n >(\"extract_to\");\n bld.AddFunction<\n static_cast<void (::Neptools::Cl3::*)(const ::boost::filesystem::path &)>(&::Neptools::Cl3::UpdateFromDir)\n >(\"update_from_dir\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::File & (::Neptools::Cl3::*)()>(&::Neptools::Cl3::GetStcm)\n >(\"get_stcm\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Cl3> reg_neptools_cl3;\n\n // class neptools.cl3.entry\n template<>\n void TypeRegisterTraits<::Neptools::Cl3::Entry>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Cl3::Entry, std::string, &::Neptools::Cl3::Entry::name>\n >(\"get_name\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Cl3::Entry, std::string, &::Neptools::Cl3::Entry::name>\n >(\"set_name\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Cl3::Entry, ::uint32_t, &::Neptools::Cl3::Entry::field_200>\n >(\"get_field_200\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Cl3::Entry, ::uint32_t, &::Neptools::Cl3::Entry::field_200>\n >(\"set_field_200\");\n bld.AddFunction<\n &::Libshit::Lua::GetRefCountedOwnedMember<::Neptools::Cl3::Entry, ::Neptools::Cl3::Entry::Links, &::Neptools::Cl3::Entry::links>\n >(\"get_links\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Cl3::Entry, Libshit::SmartPtr<::Neptools::Dumpable>, &::Neptools::Cl3::Entry::src>\n >(\"get_src\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Cl3::Entry, Libshit::SmartPtr<::Neptools::Dumpable>, &::Neptools::Cl3::Entry::src>\n >(\"set_src\");\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Cl3::Entry>::Make<LuaGetRef<std::string>, LuaGetRef<::uint32_t>, LuaGetRef<Libshit::SmartPtr<::Neptools::Dumpable>>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Cl3::Entry>::Make<LuaGetRef<std::string>>\n >(\"new\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Cl3::Entry> reg_neptools_cl3_entry;\n\n // class libshit.ordered_map_cl3_entry\n template<>\n void TypeRegisterTraits<::cl3_entry>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::cl3_entry>::Make<>\n >(\"new\");\n bld.AddFunction<\n static_cast<::Neptools::Cl3::Entry & (::cl3_entry::*)(::cl3_entry::size_type)>(&::cl3_entry::at)\n >(\"at\");\n bld.AddFunction<\n static_cast<::Neptools::Cl3::Entry & (::cl3_entry::*)()>(&::cl3_entry::front<Check::Throw>)\n >(\"front\");\n bld.AddFunction<\n static_cast<::Neptools::Cl3::Entry & (::cl3_entry::*)()>(&::cl3_entry::back<Check::Throw>)\n >(\"back\");\n bld.AddFunction<\n static_cast<bool (::cl3_entry::*)() const noexcept>(&::cl3_entry::empty)\n >(\"empty\");\n bld.AddFunction<\n static_cast<::cl3_entry::size_type (::cl3_entry::*)() const noexcept>(&::cl3_entry::size)\n >(\"size\");\n bld.AddFunction<\n static_cast<::cl3_entry::size_type (::cl3_entry::*)() const noexcept>(&::cl3_entry::size)\n >(\"__len\");\n bld.AddFunction<\n static_cast<::cl3_entry::size_type (::cl3_entry::*)() const noexcept>(&::cl3_entry::max_size)\n >(\"max_size\");\n bld.AddFunction<\n static_cast<void (::cl3_entry::*)(::size_t)>(&::cl3_entry::reserve)\n >(\"reserve\");\n bld.AddFunction<\n static_cast<::cl3_entry::size_type (::cl3_entry::*)() const noexcept>(&::cl3_entry::capacity)\n >(\"capacity\");\n bld.AddFunction<\n static_cast<void (::cl3_entry::*)()>(&::cl3_entry::shrink_to_fit)\n >(\"shrink_to_fit\");\n bld.AddFunction<\n static_cast<void (::cl3_entry::*)() noexcept>(&::cl3_entry::clear)\n >(\"clear\");\n bld.AddFunction<\n static_cast<void (::cl3_entry::*)() noexcept>(&::cl3_entry::pop_back<Check::Throw>)\n >(\"pop_back\");\n bld.AddFunction<\n static_cast<void (::cl3_entry::*)(::cl3_entry &)>(&::cl3_entry::swap)\n >(\"swap\");\n bld.AddFunction<\n static_cast<::cl3_entry::size_type (::cl3_entry::*)(const ::Neptools::Cl3::Entry &) const>(&::cl3_entry::index_of<Check::Throw>)\n >(\"index_of\");\n bld.AddFunction<\n static_cast<::cl3_entry::size_type (::cl3_entry::*)(const ::cl3_entry::key_type &) const>(&::cl3_entry::count)\n >(\"count\");\n bld.AddFunction<\n static_cast<Libshit::SmartPtr<::Neptools::Cl3::Entry> (*)(::cl3_entry &, ::size_t) noexcept>(::Libshit::OrderedMapLua<::Neptools::Cl3::Entry, ::Neptools::Cl3::EntryKeyOfValue>::get),\n static_cast<Libshit::SmartPtr<::Neptools::Cl3::Entry> (*)(::cl3_entry &, const typename ::cl3_entry::key_type &)>(::Libshit::OrderedMapLua<::Neptools::Cl3::Entry, ::Neptools::Cl3::EntryKeyOfValue>::get),\n static_cast<void (*)(::cl3_entry &, ::Libshit::Lua::Skip) noexcept>(::Libshit::OrderedMapLua<::Neptools::Cl3::Entry, ::Neptools::Cl3::EntryKeyOfValue>::get)\n >(\"get\");\n bld.AddFunction<\n static_cast<std::tuple<bool, ::size_t> (*)(::cl3_entry &, ::size_t, ::Libshit::OrderedMapLua<::Neptools::Cl3::Entry, ::Neptools::Cl3::EntryKeyOfValue, ::std::less<::std::basic_string<char> > >::NotNullPtr &&)>(::Libshit::OrderedMapLua<::Neptools::Cl3::Entry, ::Neptools::Cl3::EntryKeyOfValue>::insert)\n >(\"insert\");\n bld.AddFunction<\n static_cast<::size_t (*)(::cl3_entry &, ::size_t, ::size_t)>(::Libshit::OrderedMapLua<::Neptools::Cl3::Entry, ::Neptools::Cl3::EntryKeyOfValue>::erase),\n static_cast<::size_t (*)(::cl3_entry &, ::size_t)>(::Libshit::OrderedMapLua<::Neptools::Cl3::Entry, ::Neptools::Cl3::EntryKeyOfValue>::erase)\n >(\"erase\");\n bld.AddFunction<\n static_cast<::Libshit::OrderedMapLua<::Neptools::Cl3::Entry, ::Neptools::Cl3::EntryKeyOfValue, ::std::less<::std::basic_string<char> > >::NotNullPtr (*)(::cl3_entry &, ::size_t)>(::Libshit::OrderedMapLua<::Neptools::Cl3::Entry, ::Neptools::Cl3::EntryKeyOfValue>::remove)\n >(\"remove\");\n bld.AddFunction<\n static_cast<std::tuple<bool, ::size_t> (*)(::cl3_entry &, ::Libshit::OrderedMapLua<::Neptools::Cl3::Entry, ::Neptools::Cl3::EntryKeyOfValue, ::std::less<::std::basic_string<char> > >::NotNullPtr &&)>(::Libshit::OrderedMapLua<::Neptools::Cl3::Entry, ::Neptools::Cl3::EntryKeyOfValue>::push_back)\n >(\"push_back\");\n bld.AddFunction<\n static_cast<::Libshit::Lua::RetNum (*)(::Libshit::Lua::StateRef, ::cl3_entry &, const typename ::cl3_entry::key_type &)>(::Libshit::OrderedMapLua<::Neptools::Cl3::Entry, ::Neptools::Cl3::EntryKeyOfValue>::find)\n >(\"find\");\n bld.AddFunction<\n static_cast<::Libshit::Lua::RetNum (*)(::Libshit::Lua::StateRef, ::cl3_entry &)>(::Libshit::OrderedMapLua<::Neptools::Cl3::Entry, ::Neptools::Cl3::EntryKeyOfValue>::to_table)\n >(\"to_table\");\n luaL_getmetatable(bld, \"libshit_ipairs\"); bld.SetField(\"__ipairs\");\n }\n static TypeRegister::StateRegister<::cl3_entry> reg_libshit_ordered_map_cl3_entry;\n\n}\n#endif\n" }, { "alpha_fraction": 0.5675190687179565, "alphanum_fraction": 0.5945864915847778, "avg_line_length": 28.919462203979492, "blob_id": "40ea7e51803d6f0c017db5204facd6c60a2a4066", "content_id": "367da4588f698446963396d40266d7c990b1b923", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13374, "license_type": "permissive", "max_line_length": 97, "num_lines": 447, "path": "/src/format/stcm/instruction.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"instruction.hpp\"\n#include \"data.hpp\"\n#include \"expansion.hpp\"\n#include \"../context.hpp\"\n#include \"../raw_item.hpp\"\n#include \"../../sink.hpp\"\n\n#include <libshit/except.hpp>\n#include <libshit/container/vector.lua.hpp>\n\n#include <set>\n#include <iostream>\n\nnamespace Neptools::Stcm\n{\n\n#define IP InstructionItem::Parameter\n\n static void Param48Validate(uint32_t param, FilePosition file_size)\n {\n#define VALIDATE(x) LIBSHIT_VALIDATE_FIELD(\"Stcm Param48\", x)\n switch (IP::TypeTag(param))\n {\n case IP::Type48::MEM_OFFSET:\n VALIDATE((IP::Value(param) + 16) < file_size);\n return;\n case IP::Type48::IMMEDIATE:\n return;\n case IP::Type48::INDIRECT:\n return; // ??\n default:\n VALIDATE((param >= IP::Type48Special::READ_STACK_MIN &&\n param <= IP::Type48Special::READ_STACK_MAX) ||\n (param >= IP::Type48Special::READ_4AC_MIN &&\n param <= IP::Type48Special::READ_4AC_MAX));\n return;\n }\n#undef VALIDATE\n }\n\n void InstructionItem::Parameter::Validate(FilePosition file_size) const\n {\n#define VALIDATE(x) LIBSHIT_VALIDATE_FIELD(\"Stcm::InstructionItem::Parameter\", x)\n switch (TypeTag(param_0))\n {\n case Type0::MEM_OFFSET:\n VALIDATE(Value(param_0) < file_size);\n Param48Validate(param_4, file_size);\n Param48Validate(param_8, file_size);\n return;\n\n //case Type0::UNK: todo\n case Type0::INDIRECT:\n VALIDATE(Value(param_0) < 256 && param_4 == 0x40000000);\n Param48Validate(param_8, file_size);\n return;\n\n case Type0::SPECIAL:\n if ((param_0 >= Type0Special::READ_STACK_MIN && param_0 <= Type0Special::READ_STACK_MAX) ||\n (param_0 >= Type0Special::READ_4AC_MIN && param_0 <= Type0Special::READ_4AC_MAX))\n {\n VALIDATE(param_4 == 0x40000000);\n VALIDATE(param_8 == 0x40000000);\n }\n else if (param_0 == Type0Special::INSTR_PTR0 ||\n param_0 == Type0Special::INSTR_PTR1)\n {\n VALIDATE(param_4 < file_size);\n VALIDATE(param_8 == 0x40000000);\n }\n else if (param_0 == Type0Special::COLL_LINK)\n {\n VALIDATE(param_4 + 8 < file_size);\n VALIDATE(param_8 == 0);\n }\n else if (param_0 == Type0Special::EXPANSION)\n {\n VALIDATE(param_4 + 80 < file_size);\n VALIDATE(param_8 == 0);\n }\n else\n VALIDATE(!\"Unknown special\");\n return;\n default:\n VALIDATE(!\"Unknown type0\");\n }\n#undef VALIDATE\n }\n\n void InstructionItem::Header::Validate(FilePosition file_size) const\n {\n#define VALIDATE(x) LIBSHIT_VALIDATE_FIELD(\"Stcm::InstructionItem::Header\", x)\n VALIDATE(is_call == 0 || is_call == 1);\n VALIDATE(param_count < 16);\n VALIDATE(size >= sizeof(Header) + param_count*sizeof(Parameter));\n\n if (is_call)\n VALIDATE(opcode < file_size);\n else\n VALIDATE(\n opcode < USER_OPCODES ||\n (opcode >= SYSTEM_OPCODES_BEGIN && opcode <= SYSTEM_OPCODES_END));\n#undef VALIDATE\n }\n\n InstructionItem::InstructionItem(Key k, Context& ctx, Source src)\n : ItemWithChildren{k, ctx}\n {\n ADD_SOURCE(Parse_(ctx, src), src);\n }\n\n void InstructionItem::Parse_(Context& ctx, Source& src)\n {\n auto instr = src.ReadGen<Header>();\n instr.Validate(ctx.GetSize());\n\n if (instr.is_call)\n SetTarget(ctx.GetLabelTo(instr.opcode));\n else\n SetOpcode(instr.opcode);\n\n params.reserve(instr.param_count);\n for (size_t i = 0; i < instr.param_count; ++i)\n {\n auto p = src.ReadGen<Parameter>();\n params.emplace_back(ctx, p);\n }\n }\n\n auto InstructionItem::Param::GetVariant(Context& ctx, const Parameter& in)\n -> Variant\n {\n in.Validate(ctx.GetSize());\n\n switch (Parameter::TypeTag(in.param_0))\n {\n case Parameter::Type0::MEM_OFFSET:\n return MemOffset{\n ctx.GetLabelTo(Parameter::Value(in.param_0)),\n Param48{ctx, in.param_4},\n Param48{ctx, in.param_8}};\n\n case Parameter::Type0::INDIRECT:\n return Indirect{\n Parameter::Value(in.param_0),\n Param48{ctx, in.param_8}};\n\n#define RETVAR(type, val) return Variant{ \\\n std::in_place_index<static_cast<size_t>(Type::type)>, val}\n case Parameter::Type0::SPECIAL:\n if (in.param_0 >= Parameter::Type0Special::READ_STACK_MIN &&\n in.param_0 <= Parameter::Type0Special::READ_STACK_MAX)\n RETVAR(READ_STACK, in.param_0 - Parameter::Type0Special::READ_STACK_MIN);\n else if (in.param_0 >= Parameter::Type0Special::READ_4AC_MIN &&\n in.param_0 <= Parameter::Type0Special::READ_4AC_MAX)\n RETVAR(READ_4AC, in.param_0 - Parameter::Type0Special::READ_4AC_MIN);\n else if (in.param_0 == Parameter::Type0Special::INSTR_PTR0)\n RETVAR(INSTR_PTR0, ctx.GetLabelTo(in.param_4));\n else if (in.param_0 == Parameter::Type0Special::INSTR_PTR1)\n RETVAR(INSTR_PTR1, ctx.GetLabelTo(in.param_4));\n else if (in.param_0 == Parameter::Type0Special::COLL_LINK)\n RETVAR(COLL_LINK, ctx.GetLabelTo(in.param_4));\n else if (in.param_0 == Parameter::Type0Special::EXPANSION)\n RETVAR(EXPANSION, ctx.GetLabelTo(in.param_4));\n else\n LIBSHIT_UNREACHABLE(\"Invalid special parameter type\");\n }\n\n LIBSHIT_UNREACHABLE(\"Invalid parameter type\");\n }\n\n void InstructionItem::Param::Dump(Sink& sink) const\n {\n Parameter pp;\n switch (GetType())\n {\n case Type::MEM_OFFSET:\n {\n const auto& o = Get<Type::MEM_OFFSET>();\n pp.param_0 = Parameter::Tag(\n Parameter::Type0::MEM_OFFSET, ToFilePos(o.target->GetPtr()));\n pp.param_4 = o.param_4.Dump();\n pp.param_8 = o.param_8.Dump();\n break;\n }\n\n case Type::INDIRECT:\n {\n const auto& i = Get<Type::INDIRECT>();\n pp.param_0 = Parameter::Tag(Parameter::Type0::INDIRECT, i.param_0);\n pp.param_4 = 0x40000000;\n pp.param_8 = i.param_8.Dump();\n break;\n }\n\n case Type::READ_STACK:\n pp.param_0 = Parameter::Type0Special::READ_STACK_MIN +\n Get<Type::READ_STACK>();\n pp.param_4 = 0x40000000;\n pp.param_8 = 0x40000000;\n break;\n\n case Type::READ_4AC:\n pp.param_0 = Parameter::Type0Special::READ_4AC_MIN +\n Get<Type::READ_4AC>();\n pp.param_4 = 0x40000000;\n pp.param_8 = 0x40000000;\n break;\n\n case Type::INSTR_PTR0:\n pp.param_0 = Parameter::Type0Special::INSTR_PTR0;\n pp.param_4 = ToFilePos(Get<Type::INSTR_PTR0>()->GetPtr());\n pp.param_8 = 0x40000000;\n break;\n\n case Type::INSTR_PTR1:\n pp.param_0 = Parameter::Type0Special::INSTR_PTR1;\n pp.param_4 = ToFilePos(Get<Type::INSTR_PTR1>()->GetPtr());\n pp.param_8 = 0x40000000;\n break;\n\n case Type::COLL_LINK:\n pp.param_0 = Parameter::Type0Special::COLL_LINK;\n pp.param_4 = ToFilePos(Get<Type::COLL_LINK>()->GetPtr());\n pp.param_8 = 0;\n break;\n\n case Type::EXPANSION:\n pp.param_0 = Parameter::Type0Special::EXPANSION;\n pp.param_4 = ToFilePos(Get<Type::EXPANSION>()->GetPtr());\n pp.param_8 = 0;\n break;\n }\n sink.WriteGen(pp);\n }\n\n std::ostream& operator<<(std::ostream& os, const InstructionItem::Param& p)\n {\n using T = InstructionItem::Param::Type;\n switch (p.GetType())\n {\n case T::MEM_OFFSET:\n {\n const auto& o = p.Get<T::MEM_OFFSET>();\n return os << \"{'mem_offset', \" << PrintLabel(o.target) << \", \"\n << o.param_4 << \", \" << o.param_8 << '}';\n }\n case T::INDIRECT:\n {\n const auto& i = p.Get<T::INDIRECT>();\n return os << \"{'indirect', \" << i.param_0 << \", \" << i.param_8 << '}';\n }\n case T::READ_STACK:\n return os << \"{'read_stack', \" << p.Get<T::READ_STACK>() << \"}\";\n case T::READ_4AC:\n return os << \"{'read_4ac', \" << p.Get<T::READ_4AC>() << \"}\";\n case T::INSTR_PTR0:\n return os << \"{'instr_ptr0', \" << PrintLabel(p.Get<T::INSTR_PTR0>()) << '}';\n case T::INSTR_PTR1:\n return os << \"{'instr_ptr1', \" << PrintLabel(p.Get<T::INSTR_PTR1>()) << '}';\n case T::COLL_LINK:\n return os << \"{'coll_link', \" << PrintLabel(p.Get<T::COLL_LINK>()) << '}';\n case T::EXPANSION:\n return os << \"{'expansion', \" << PrintLabel(p.Get<T::EXPANSION>()) << '}';\n }\n LIBSHIT_UNREACHABLE(\"Invalid type\");\n }\n\n\n auto InstructionItem::Param48::GetVariant(Context& ctx, uint32_t in) -> Variant\n {\n switch (Parameter::TypeTag(in))\n {\n case Parameter::Type48::MEM_OFFSET:\n RETVAR(MEM_OFFSET, ctx.GetLabelTo(Parameter::Value(in)));\n\n case Parameter::Type48::IMMEDIATE:\n RETVAR(IMMEDIATE, Parameter::Value(in));\n\n case Parameter::Type48::INDIRECT:\n RETVAR(INDIRECT, Parameter::Value(in));\n\n case Parameter::Type48::SPECIAL:\n if (in >= Parameter::Type48Special::READ_STACK_MIN &&\n in <= Parameter::Type48Special::READ_STACK_MAX)\n {\n RETVAR(READ_STACK, in - Parameter::Type48Special::READ_STACK_MIN);\n }\n else if (in >= Parameter::Type48Special::READ_4AC_MIN &&\n in <= Parameter::Type48Special::READ_4AC_MAX)\n {\n RETVAR(READ_4AC, in - Parameter::Type48Special::READ_4AC_MIN);\n }\n else\n LIBSHIT_UNREACHABLE(\"Invalid 48Special param\");\n }\n#undef RETVAR\n\n LIBSHIT_UNREACHABLE(\"Invalid 48 param\");\n }\n\n std::ostream& operator<<(std::ostream& os, const InstructionItem::Param48& p)\n {\n using T = InstructionItem::Param48::Type;\n switch (p.GetType())\n {\n case T::MEM_OFFSET:\n return os << \"{'mem_offset', \" << PrintLabel(p.Get<T::MEM_OFFSET>()) << '}';\n case T::IMMEDIATE:\n return os << \"{'immediate', \" << p.Get<T::IMMEDIATE>() << '}';\n case T::INDIRECT:\n return os << \"{'indirect', \" << p.Get<T::INDIRECT>() << '}';\n case T::READ_STACK:\n return os << \"{'read_stack', \" << p.Get<T::READ_STACK>() << '}';\n case T::READ_4AC:\n return os << \"{'read_4ac', \" << p.Get<T::READ_4AC>() << '}';\n }\n\n LIBSHIT_UNREACHABLE(\"Invalid 48 param\");\n }\n\n static const std::set<uint32_t> no_returns{0, 6};\n\n InstructionItem& InstructionItem::CreateAndInsert(ItemPointer ptr)\n {\n auto x = RawItem::GetSource(ptr, -1);\n\n x.src.CheckSize(sizeof(Header));\n auto inst = x.src.PreadGen<Header>(0);\n x.src.CheckSize(inst.size);\n\n auto& ret = x.ritem.SplitCreate<InstructionItem>(ptr.offset, x.src);\n\n auto rem_data = inst.size - sizeof(Header) -\n sizeof(Parameter) * inst.param_count;\n if (rem_data)\n ret.MoveNextToChild(rem_data);\n\n LIBSHIT_ASSERT(ret.GetSize() == inst.size);\n\n // recursive parse\n if (ret.IsCall())\n MaybeCreate<InstructionItem>(ret.GetTarget()->GetPtr());\n if (ret.IsCall() || !no_returns.count(ret.GetOpcode()))\n MaybeCreate<InstructionItem>({&*++ret.Iterator(), 0});\n for (const auto& p : ret.params)\n {\n using T = Param::Type;\n switch (p.GetType())\n {\n case T::MEM_OFFSET:\n MaybeCreate<DataItem>(p.Get<T::MEM_OFFSET>().target->GetPtr());\n break;\n case T::INSTR_PTR0:\n MaybeCreate<InstructionItem>(p.Get<T::INSTR_PTR0>()->GetPtr());\n break;\n case T::INSTR_PTR1:\n MaybeCreate<InstructionItem>(p.Get<T::INSTR_PTR1>()->GetPtr());\n break;\n default:;\n }\n }\n\n return ret;\n }\n\n\n FilePosition InstructionItem::GetSize() const noexcept\n {\n return sizeof(Header) + params.size() * sizeof(Parameter) +\n ItemWithChildren::GetSize();\n }\n\n uint32_t InstructionItem::Param48::Dump() const noexcept\n {\n switch (GetType())\n {\n case Type::MEM_OFFSET:\n return Parameter::Tag(Parameter::Type48::MEM_OFFSET,\n ToFilePos(Get<Type::MEM_OFFSET>()->GetPtr()));\n case Type::IMMEDIATE:\n return Parameter::Tag(Parameter::Type48::IMMEDIATE, Get<Type::IMMEDIATE>());\n case Type::INDIRECT:\n return Parameter::Tag(Parameter::Type48::INDIRECT, Get<Type::INDIRECT>());\n case Type::READ_STACK:\n return Parameter::Type48Special::READ_STACK_MIN + Get<Type::READ_STACK>();\n case Type::READ_4AC:\n return Parameter::Type48Special::READ_4AC_MIN + Get<Type::READ_4AC>();\n }\n LIBSHIT_UNREACHABLE(\"Invalid Param48 Type stored\");\n }\n\n void InstructionItem::Fixup()\n {\n ItemWithChildren::Fixup_(sizeof(Header) + params.size() * sizeof(Parameter));\n }\n\n void InstructionItem::Dispose() noexcept\n {\n params.clear();\n ItemWithChildren::Dispose();\n }\n\n void InstructionItem::Dump_(Sink& sink) const\n {\n Header hdr;\n hdr.is_call = IsCall();\n\n if (IsCall())\n hdr.opcode = ToFilePos(GetTarget()->GetPtr());\n else\n hdr.opcode = GetOpcode();\n hdr.param_count = params.size();\n hdr.size = GetSize();\n sink.WriteGen(hdr);\n\n for (const auto& p : params)\n p.Dump(sink);\n\n ItemWithChildren::Dump_(sink);\n }\n\n void InstructionItem::Inspect_(std::ostream &os, unsigned indent) const\n {\n Item::Inspect_(os, indent);\n\n if (IsCall())\n os << \"call(\" << PrintLabel(GetTarget());\n else\n os << \"instruction(\" << GetOpcode();\n if (!params.empty())\n {\n os << \", {\\n\";\n size_t i = 0;\n for (const auto& p : params)\n Indent(os, indent+1) << '[' << i++ << \"] = \" << p << \",\\n\";\n Indent(os, indent) << '}';\n }\n os << ')';\n InspectChildren(os, indent);\n }\n\n}\n\nLIBSHIT_STD_VECTOR_LUAGEN(\n stcm_instruction_param, Neptools::Stcm::InstructionItem::Param);\n#include \"instruction.binding.hpp\"\n" }, { "alpha_fraction": 0.5772495865821838, "alphanum_fraction": 0.5995330810546875, "avg_line_length": 28.267080307006836, "blob_id": "50925f557ab6e1f580e6d34af8d80c907d32de81", "content_id": "9254dec2003bb88d24b4e35d08b6a673be3b23d3", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4712, "license_type": "permissive", "max_line_length": 80, "num_lines": 161, "path": "/src/format/stcm/collection_link.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"collection_link.hpp\"\n#include \"../context.hpp\"\n#include \"../cstring_item.hpp\"\n#include \"../eof_item.hpp\"\n#include \"../raw_item.hpp\"\n#include \"../../sink.hpp\"\n\n#include <libshit/container/vector.lua.hpp>\n\nnamespace Neptools::Stcm\n{\n\n void CollectionLinkHeaderItem::Header::Validate(FilePosition file_size) const\n {\n#define VALIDATE(x) \\\n LIBSHIT_VALIDATE_FIELD(\"Stcm::CollectionLinkHeaderItem::Header\", x)\n\n VALIDATE(field_00 == 0);\n VALIDATE(offset <= file_size);\n VALIDATE(offset + sizeof(CollectionLinkItem::Entry)*count <= file_size);\n VALIDATE(field_0c == 0);\n VALIDATE(field_10 == 0 && field_14 == 0 && field_18 == 0 && field_1c == 0);\n VALIDATE(field_20 == 0 && field_24 == 0 && field_28 == 0 && field_2c == 0);\n VALIDATE(field_30 == 0 && field_34 == 0 && field_38 == 0 && field_3c == 0);\n#undef VALIDATE\n }\n\n void CollectionLinkItem::Entry::Validate(FilePosition file_size) const\n {\n#define VALIDATE(x) LIBSHIT_VALIDATE_FIELD(\"Stcm::CollectionLinkItem::Entry\", x)\n VALIDATE(name_0 <= file_size);\n VALIDATE(name_1 <= file_size);\n VALIDATE(ptr == 0);\n VALIDATE(field_0c == 0);\n VALIDATE(field_10 == 0 && field_14 == 0 && field_18 == 0 && field_1c == 0);\n#undef VALIDATE\n }\n\n CollectionLinkHeaderItem::CollectionLinkHeaderItem(\n Key k, Context& ctx, const Header& s)\n : Item{k, ctx},\n data{(s.Validate(ctx.GetSize()),\n ctx.CreateLabelFallback(\"collection_link\", s.offset))}\n {}\n\n CollectionLinkHeaderItem& CollectionLinkHeaderItem::CreateAndInsert(\n ItemPointer ptr)\n {\n auto x = RawItem::Get<Header>(ptr);\n auto& ret = x.ritem.SplitCreate<CollectionLinkHeaderItem>(ptr.offset, x.t);\n\n auto ptr2 = ret.data->GetPtr();\n auto* ritem2 = ptr2.Maybe<RawItem>();\n if (!ritem2)\n {\n // HACK!\n LIBSHIT_VALIDATE_FIELD(\n \"Stcm::CollectionLinkHeaderItem\",\n ptr2.offset == 0 && x.t.count == 0);\n auto& eof = ptr2.AsChecked0<EofItem>();\n auto ctx = eof.GetContext();\n eof.Replace(ctx->Create<CollectionLinkItem>());\n return ret;\n }\n\n auto e = RawItem::GetSource(\n ptr2, x.t.count*sizeof(CollectionLinkItem::Entry));\n\n e.ritem.SplitCreate<CollectionLinkItem>(ptr2.offset, e.src, x.t.count);\n\n return ret;\n }\n\n void CollectionLinkHeaderItem::Dump_(Sink& sink) const\n {\n Header hdr{};\n hdr.offset = ToFilePos(data->GetPtr());\n hdr.count = data->GetPtr().AsChecked0<CollectionLinkItem>().entries.size();\n sink.WriteGen(hdr);\n }\n\n void CollectionLinkHeaderItem::Inspect_(\n std::ostream& os, unsigned indent) const\n {\n Item::Inspect_(os, indent);\n os << \"collection_link_header(\" << PrintLabel(data) << \")\";\n }\n\n CollectionLinkItem::CollectionLinkItem(\n Key k, Context& ctx, Source src, uint32_t count)\n : Item{k, ctx}\n {\n ADD_SOURCE(Parse_(ctx, src, count), src);\n }\n\n void CollectionLinkItem::Dispose() noexcept\n {\n entries.clear();\n Item::Dispose();\n }\n\n void CollectionLinkItem::Parse_(Context& ctx, Source& src, uint32_t count)\n {\n entries.reserve(count);\n for (uint32_t i = 0; i < count; ++i)\n {\n auto e = src.ReadGen<Entry>();\n e.Validate(ctx.GetSize());\n\n LabelPtr label0, label1;\n if (e.name_0)\n {\n auto& str0 = MaybeCreate<CStringItem>(ctx.GetPointer(e.name_0));\n label0 = ctx.GetLabelTo(e.name_0, str0.GetLabelName());\n }\n\n if (e.name_1)\n {\n auto& str1 = MaybeCreate<CStringItem>(ctx.GetPointer(e.name_1));\n label1 = ctx.GetLabelTo(e.name_1, str1.GetLabelName());\n }\n\n entries.emplace_back(label0, label1);\n }\n }\n\n void CollectionLinkItem::Dump_(Sink& sink) const\n {\n Entry ee{};\n for (const auto& e : entries)\n {\n ee.name_0 = e.name_0 ? ToFilePos(e.name_0->GetPtr()) : 0;\n ee.name_1 = e.name_1 ? ToFilePos(e.name_1->GetPtr()) : 0;\n sink.WriteGen(ee);\n }\n }\n\n void CollectionLinkItem::Inspect_(std::ostream& os, unsigned indent) const\n {\n Item::Inspect_(os, indent);\n\n os << \"collection_link{\\n\";\n for (const auto& e : entries)\n {\n if (!e.name_0 || ! e.name_1)\n Indent(os, indent+1) << \"neptools.stcm.collection_link_item.link_entry(\"\n << PrintLabel(e.name_0) << \", \"\n << PrintLabel(e.name_1) << \"),\\n\";\n else\n Indent(os, indent+1) << '{' << PrintLabel(e.name_0) << \", \"\n << PrintLabel(e.name_1) << \"},\\n\";\n }\n Indent(os, indent) << \"}\";\n }\n\n}\n\nLIBSHIT_STD_VECTOR_LUAGEN(\n stcm_collection_link_item_link_entry,\n Neptools::Stcm::CollectionLinkItem::LinkEntry);\n#include \"collection_link.binding.hpp\"\n" }, { "alpha_fraction": 0.5653015375137329, "alphanum_fraction": 0.568848729133606, "avg_line_length": 25.279661178588867, "blob_id": "908628616f7e5158e36c3f36f9e4c09cbfe1c546", "content_id": "aeeea0618e4b3d432630a95042358210cd1960fd", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3101, "license_type": "permissive", "max_line_length": 83, "num_lines": 118, "path": "/src/format/stsc/file.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"file.hpp\"\n#include \"header.hpp\"\n#include \"../cstring_item.hpp\"\n#include \"../eof_item.hpp\"\n#include \"../raw_item.hpp\"\n#include \"../../open.hpp\"\n\n#include <boost/algorithm/string/replace.hpp>\n\nnamespace Neptools::Stsc\n{\n\n File::File(Source src, Flavor flavor) : flavor{flavor}\n {\n ADD_SOURCE(Parse_(src), src);\n }\n\n void File::Parse_(Source& src)\n {\n auto root = Create<RawItem>(src);\n SetupParseFrom(*root);\n root->Split(root->GetSize(), Create<EofItem>());\n HeaderItem::CreateAndInsert({&*root, 0}, flavor);\n }\n\n void File::Inspect_(std::ostream& os, unsigned indent) const\n {\n LIBSHIT_ASSERT(GetLabels().empty());\n os << \"neptools.stsc.file(neptools.stsc.flavor.\" << ToString(flavor) << \")\";\n InspectChildren(os, indent);\n }\n\n static const char SEP_DASH[] = {\n#define REP_MACRO(x,y,z) '-',\n BOOST_PP_REPEAT(40, REP_MACRO, )\n '\\r', 0,\n };\n\n void File::WriteTxt_(std::ostream& os) const\n {\n for (auto& it : GetChildren())\n {\n auto str = dynamic_cast<const CStringItem*>(&it);\n if (str)\n {\n os << boost::replace_all_copy(str->string, \"\\\\n\", \"\\r\\n\")\n << \"\\r\\n\" << SEP_DASH << '\\n';\n }\n }\n }\n\n void File::ReadTxt_(std::istream& is)\n {\n std::string line, msg;\n auto it = GetChildren().begin();\n auto end = GetChildren().end();\n while (it != end && !dynamic_cast<CStringItem*>(&*it)) ++it;\n\n is.exceptions(std::ios_base::badbit);\n while (!std::getline(is, line).fail())\n {\n if (line == SEP_DASH)\n {\n if (it == end)\n LIBSHIT_THROW(Libshit::DecodeError, \"StscTxt: too many strings\");\n\n LIBSHIT_ASSERT(msg.empty() || msg.substr(msg.length()-2) == \"\\\\n\");\n if (!msg.empty()) { msg.pop_back(); msg.pop_back(); }\n static_cast<CStringItem&>(*it).string = std::move(msg);\n\n ++it;\n while (it != end && !dynamic_cast<CStringItem*>(&*it)) ++it;\n\n msg.clear();\n }\n else\n {\n if (!line.empty() && line.back() == '\\r') line.pop_back();\n msg.append(line).append(\"\\\\n\");\n }\n }\n\n if (it != end)\n LIBSHIT_THROW(Libshit::DecodeError, \"StscTxt: not enough strings\");\n }\n\n static Flavor glob_flavor = Flavor::NOIRE;\n static Libshit::Option flavor_opt{\n GetFlavorOptions(), \"stsc-flavor\", 1, \"FLAVOR\",\n#define GEN_HELP(x,y) \"\\t\\t\" #x \"\\n\"\n \"Set STSC flavor:\\n\" NEPTOOLS_GEN_STSC_FLAVOR(GEN_HELP,),\n#undef GEN_HELP\n [](auto&& args)\n {\n if (false); // NOLINT\n#define GEN_IFS(x, y) \\\n else if (strcmp(args.front(), #x) == 0) \\\n glob_flavor = Flavor::x;\n\n NEPTOOLS_GEN_STSC_FLAVOR(GEN_IFS,)\n#undef GEN_IFS\n else throw Libshit::InvalidParam{\"invalid argument\"};\n }};\n\n static OpenFactory stsc_open{[](const Source& src) -> Libshit::SmartPtr<Dumpable>\n {\n if (src.GetSize() < sizeof(HeaderItem::Header)) return nullptr;\n char buf[4];\n src.PreadGen(0, buf);\n if (memcmp(buf, \"STSC\", 4) == 0)\n return Libshit::MakeSmart<File>(src, glob_flavor);\n else\n return nullptr;\n }};\n\n}\n\n#include \"file.binding.hpp\"\n" }, { "alpha_fraction": 0.5192012190818787, "alphanum_fraction": 0.5545315146446228, "avg_line_length": 14.686746597290039, "blob_id": "08abb53c97cfde62f7aab46cb7a47136631f772b", "content_id": "02d814d1589127e97802650ad9e271c79e112508", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1302, "license_type": "permissive", "max_line_length": 74, "num_lines": 83, "path": "/tools/ci.sh", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\nexport TERM=xterm\n\nfunction einfo()\n{\n echo -e \" \\033[32m*\\033[0m $@\" >&2\n}\n\nfunction ewarn()\n{\n echo -e \" \\033[33m*\\033[0m $@\" >&2\n}\n\nfunction eerror()\n{\n echo -e \" \\033[31m*\\033[0m $@\" >&2\n}\n\ntrap \"exit 1\" ERR\n\nif [[ $# != 2 ]]; then\n eerror \"Usage: $0 compiler mode\"\n exit 1\nfi\ncompiler=\"$1\"\nmode=\"$2\"\n\nif [[ $mode != rel && $mode != rel-test && $mode != debug ]]; then\n eerror \"Invalid mode $mode\"\n exit 1\nfi\n\ncd \"$(dirname \"${BASH_SOURCE[0]}\")/..\"\n\nfunction before_build() { :; }\nfunction after_build() { :; }\nfunction after() { :; }\n\nfunction load()\n{\n if [[ -f ~/.neptools_ci_conf.\"$1\".sh ]]; then\n source ~/.neptools_ci_conf.\"$1\".sh\n else\n source tools/ci_conf.\"$1\".sh\n fi\n}\n\n# env printf: bypass bash's printf as gnu printf uses 'foo bar' instead of\n# foo\\ bar. provided we have gnu printf...\nif env printf '%q' >/dev/null 2>/dev/null; then\n quot_printf='env printf'\nelse\n quot_printf=printf\nfi\n\nfunction quot()\n{\n $quot_printf '%q' \"$1\"\n}\n\nfunction run()\n{\n einfo \"$($quot_printf '%q ' \"$@\")\"\n \"$@\" || exit 1\n}\n\nload default\nload \"$compiler\"\n\nbefore_build\nbuild\nafter_build\n\nret=0\nif [[ $mode != rel ]]; then\n for t in \"${tests[@]}\"; do\n einfo \"$t\"\n time eval \"$t\" || ret=1\n done\nfi\nafter\nexit $ret\n" }, { "alpha_fraction": 0.5777778029441833, "alphanum_fraction": 0.6045351624488831, "avg_line_length": 28.79729652404785, "blob_id": "1507213b6466b735e0d13dfc3e34f96e1d493957", "content_id": "39786f52def534a4a7d3e9c71d731cc936e203c6", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4410, "license_type": "permissive", "max_line_length": 85, "num_lines": 148, "path": "/src/format/stsc/header.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"header.hpp\"\n#include \"instruction.hpp\"\n#include \"../context.hpp\"\n#include \"../raw_item.hpp\"\n#include \"../../sink.hpp\"\n\n#include <libshit/char_utils.hpp>\n\nnamespace Neptools::Stsc\n{\n\n void HeaderItem::Header::Validate(FilePosition size) const\n {\n#define VALIDATE(x) LIBSHIT_VALIDATE_FIELD(\"Stsc::HeaderItem::Header\", x)\n VALIDATE(memcmp(magic, \"STSC\", 4) == 0);\n VALIDATE(entry_point < size - 1);\n VALIDATE((flags & ~0x07) == 0);\n\n FilePosition hdr_len = sizeof(Header);\n if (flags & 1) hdr_len += 32;\n if (flags & 2) hdr_len += sizeof(ExtraHeader2Ser);\n if (flags & 4) hdr_len += 2; // uint16_t\n VALIDATE(entry_point >= hdr_len);\n#undef VALIDATE\n }\n\n HeaderItem::HeaderItem(Key k, Context& ctx, Source src)\n : Item{k, ctx}, entry_point{Libshit::EmptyNotNull{}}\n {\n ADD_SOURCE(Parse_(ctx, src), src);\n }\n\n HeaderItem::HeaderItem(\n Key k, Context& ctx, Libshit::NotNull<LabelPtr> entry_point,\n std::optional<std::string_view> extra_headers_1,\n std::optional<ExtraHeaders2> extra_headers_2,\n std::optional<uint16_t> extra_headers_4)\n : Item{k, ctx}, entry_point{entry_point},\n extra_headers_2{extra_headers_2}, extra_headers_4{extra_headers_4}\n {\n if (extra_headers_1)\n {\n LIBSHIT_VALIDATE_FIELD(\"Ststc::HeaderItem\", extra_headers_1->size() <= 32);\n this->extra_headers_1.emplace();\n\n auto s = extra_headers_1->size();\n memcpy(this->extra_headers_1->data(), extra_headers_1->data(), s);\n memset(this->extra_headers_1->data() + s, 0, 32 - s);\n }\n }\n\n FilePosition HeaderItem::GetSize() const noexcept\n {\n FilePosition size = sizeof(Header);\n if (extra_headers_1) size += 32;\n if (extra_headers_2) size += sizeof(ExtraHeader2Ser);\n if (extra_headers_4) size += 2;\n return size;\n }\n\n HeaderItem& HeaderItem::CreateAndInsert(ItemPointer ptr, Flavor flavor)\n {\n auto x = RawItem::GetSource(ptr, -1);\n auto& ret = x.ritem.SplitCreate<HeaderItem>(ptr.offset, x.src);\n\n InstructionBase::CreateAndInsert(ret.entry_point->GetPtr(), flavor);\n return ret;\n }\n\n void HeaderItem::Parse_(Context& ctx, Source& src)\n {\n src.CheckRemainingSize(sizeof(Header));\n auto hdr = src.ReadGen<Header>();\n hdr.Validate(src.GetSize());\n\n entry_point = ctx.CreateLabelFallback(\"entry_point\", hdr.entry_point);\n\n if (hdr.flags & 1)\n {\n extra_headers_1.emplace();\n src.ReadGen(*extra_headers_1);\n }\n if (hdr.flags & 2)\n {\n auto eh2 = src.ReadGen<ExtraHeader2Ser>();\n extra_headers_2.emplace(\n eh2.field_0, eh2.field_2, eh2.field_4, eh2.field_6, eh2.field_8,\n eh2.field_a, eh2.field_c);\n }\n if (hdr.flags & 4)\n extra_headers_4 = src.ReadLittleUint16();\n }\n\n void HeaderItem::Dump_(Sink& sink) const\n {\n Header hdr;\n memcpy(hdr.magic, \"STSC\", 4);\n hdr.entry_point = ToFilePos(entry_point->GetPtr());\n uint32_t flags = 0;\n if (extra_headers_1) flags |= 1;\n if (extra_headers_2) flags |= 2;\n if (extra_headers_4) flags |= 4;\n hdr.flags = flags;\n sink.WriteGen(hdr);\n\n if (extra_headers_1) sink.WriteGen(*extra_headers_1);\n if (extra_headers_2)\n {\n ExtraHeader2Ser eh{\n extra_headers_2->field_0, extra_headers_2->field_2,\n extra_headers_2->field_4, extra_headers_2->field_6,\n extra_headers_2->field_8, extra_headers_2->field_a,\n extra_headers_2->field_c,\n };\n sink.WriteGen(eh);\n }\n if (extra_headers_4)\n sink.WriteLittleUint16(*extra_headers_4);\n }\n\n void HeaderItem::Inspect_(std::ostream& os, unsigned indent) const\n {\n Item::Inspect_(os, indent);\n\n os << \"header(\" << PrintLabel(entry_point) << \", \";\n if (extra_headers_1)\n Libshit::DumpBytes(os, {\n reinterpret_cast<const char*>(extra_headers_1->data()),\n extra_headers_1->size()});\n else os << \"nil\";\n\n if (extra_headers_2)\n os << \", neptools.stsc.header_item.extra_headers_2(\" <<extra_headers_2->field_0\n << \", \" << extra_headers_2->field_2\n << \", \" << extra_headers_2->field_4\n << \", \" << extra_headers_2->field_6\n << \", \" << extra_headers_2->field_8\n << \", \" << extra_headers_2->field_a\n << \", \" << extra_headers_2->field_c << \"), \";\n else os << \", nil, \";\n if (extra_headers_4) os << *extra_headers_4;\n else os << \"nil\";\n os << \")\";\n }\n\n}\n\n#include \"header.binding.hpp\"\n" }, { "alpha_fraction": 0.6833333373069763, "alphanum_fraction": 0.6833333373069763, "avg_line_length": 51.173912048339844, "blob_id": "7836cfaf013ef7b376a1185b4e2f40acdb1217f5", "content_id": "afb493c69bbfed1a989463e79b8ef9a0a64ff462", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2400, "license_type": "permissive", "max_line_length": 174, "num_lines": 46, "path": "/src/format/context.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Context::TYPE_NAME[] = \"neptools.context\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.context\n template<>\n void TypeRegisterTraits<::Neptools::Context>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Context, ::Neptools::ItemWithChildren>();\n\n bld.AddFunction<\n static_cast<::Libshit::NotNull<::Neptools::LabelPtr> (::Neptools::Context::*)(const std::string &) const>(&::Neptools::Context::GetLabel)\n >(\"get_label\");\n bld.AddFunction<\n static_cast<::Libshit::NotNull<::Neptools::LabelPtr> (::Neptools::Context::*)(std::string, ::Neptools::ItemPointer)>(&::Neptools::Context::CreateLabel)\n >(\"create_label\");\n bld.AddFunction<\n static_cast<::Libshit::NotNull<::Neptools::LabelPtr> (::Neptools::Context::*)(const std::string &, ::Neptools::ItemPointer)>(&::Neptools::Context::CreateLabelFallback),\n static_cast<::Libshit::NotNull<::Neptools::LabelPtr> (::Neptools::Context::*)(const std::string &, ::Neptools::FilePosition)>(&::Neptools::Context::CreateLabelFallback)\n >(\"create_label_fallback\");\n bld.AddFunction<\n static_cast<::Libshit::NotNull<::Neptools::LabelPtr> (::Neptools::Context::*)(std::string, ::Neptools::ItemPointer)>(&::Neptools::Context::CreateOrSetLabel)\n >(\"create_or_set_label\");\n bld.AddFunction<\n static_cast<::Libshit::NotNull<::Neptools::LabelPtr> (::Neptools::Context::*)(std::string)>(&::Neptools::Context::GetOrCreateDummyLabel)\n >(\"get_or_create_dummy_label\");\n bld.AddFunction<\n static_cast<::Libshit::NotNull<::Neptools::LabelPtr> (::Neptools::Context::*)(::Neptools::ItemPointer)>(&::Neptools::Context::GetLabelTo),\n static_cast<::Libshit::NotNull<::Neptools::LabelPtr> (::Neptools::Context::*)(::Neptools::FilePosition)>(&::Neptools::Context::GetLabelTo),\n static_cast<::Libshit::NotNull<::Neptools::LabelPtr> (::Neptools::Context::*)(::Neptools::FilePosition, const std::string &)>(&::Neptools::Context::GetLabelTo)\n >(\"get_label_to\");\n bld.AddFunction<\n static_cast<::Neptools::ItemPointer (::Neptools::Context::*)(::Neptools::FilePosition) const noexcept>(&::Neptools::Context::GetPointer)\n >(\"get_pointer\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Context> reg_neptools_context;\n\n}\n#endif\n" }, { "alpha_fraction": 0.5895625948905945, "alphanum_fraction": 0.5954443216323853, "avg_line_length": 36.858299255371094, "blob_id": "b386b9beafb4aa0d58492e3c2ffb8e93c0792d2d", "content_id": "5c8d90e2d2a3261cde8200e06eb52386912437ba", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9351, "license_type": "permissive", "max_line_length": 84, "num_lines": 247, "path": "/src/source.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_11A3E8B0_C5C5_4C4E_A22E_56F6E5346CEC\n#define UUID_11A3E8B0_C5C5_4C4E_A22E_56F6E5346CEC\n#pragma once\n\n#include \"dumpable.hpp\"\n#include \"endian.hpp\"\n\n#include <libshit/check.hpp>\n#include <libshit/low_io.hpp>\n#include <libshit/lua/value_object.hpp>\n#include <libshit/meta_utils.hpp>\n#include <libshit/not_null.hpp>\n#include <libshit/shared_ptr.hpp>\n\n#include <boost/filesystem/path.hpp>\n\n#include <array>\n#include <cstdint>\n#include <string_view>\n\nnamespace Neptools\n{\n\n LIBSHIT_GEN_EXCEPTION_TYPE(SourceOverflow, std::logic_error);\n\n /// A fixed size, read-only, seekable data source (or something that emulates\n /// it)\n class LIBSHIT_LUAGEN(const=false) Source final\n : public Libshit::Lua::ValueObject\n {\n LIBSHIT_LUA_CLASS;\n public:\n struct BufEntry\n {\n const Byte* ptr = nullptr;\n FilePosition offset = -1;\n FileMemSize size = 0;\n };\n\n Source(Source s, FilePosition offset, FilePosition size) noexcept\n : Source{std::move(s)} { Slice(offset, size); get = 0; }\n\n static Source FromFile(const boost::filesystem::path& fname);\n LIBSHIT_NOLUA\n static Source FromFd(\n boost::filesystem::path fname, Libshit::LowIo::FdType fd, bool owning);\n static Source FromMemory(std::string data)\n { return FromMemory(\"\", std::move(data)); }\n static Source FromMemory(boost::filesystem::path fname, std::string data);\n LIBSHIT_NOLUA\n static Source FromMemory(boost::filesystem::path fname,\n std::unique_ptr<char[]> data, std::size_t len);\n\n template <typename Checker = Libshit::Check::Assert>\n void Slice(FilePosition offset, FilePosition size) noexcept\n {\n LIBSHIT_CHECK(SourceOverflow, offset <= this->size &&\n offset + size <= this->size, \"Slice: invalid sizes\");\n this->offset += offset;\n this->get -= offset;\n this->size = size;\n }\n\n FilePosition GetOffset() const noexcept { return offset; }\n FilePosition GetOrigSize() const noexcept { return p->size; }\n const boost::filesystem::path& GetFileName() const noexcept\n { return p->file_name; }\n\n FilePosition GetSize() const noexcept { return size; }\n\n template <typename Checker = Libshit::Check::Assert>\n void Seek(FilePosition pos) noexcept\n {\n LIBSHIT_CHECK(SourceOverflow, pos <= size, \"Seek past end of source\");\n get = pos;\n }\n FilePosition Tell() const noexcept { return get; }\n FilePosition GetRemainingSize() const noexcept { return size - get; }\n bool Eof() const noexcept { return get == size; }\n\n void CheckSize(FilePosition size) const\n {\n if (p->size < size)\n LIBSHIT_THROW(Libshit::DecodeError, \"Premature end of data\",\n \"Used source\", *this);\n }\n void CheckRemainingSize(FilePosition size) const { CheckSize(get + size); }\n\n template <typename Checker = Libshit::Check::Assert, typename T>\n LIBSHIT_NOLUA void ReadGen(T& x)\n { Read<Checker>(reinterpret_cast<Byte*>(&x), Libshit::EmptySizeof<T>); }\n\n template <typename T, typename Checker = Libshit::Check::Assert>\n LIBSHIT_NOLUA T ReadGen() { T ret; ReadGen<Checker>(ret); return ret; }\n\n\n template <typename Checker = Libshit::Check::Assert, typename T>\n LIBSHIT_NOLUA void PreadGen(FilePosition offs, T& x) const\n { Pread<Checker>(offs, reinterpret_cast<Byte*>(&x), Libshit::EmptySizeof<T>); }\n\n template <typename T, typename Checker = Libshit::Check::Assert>\n LIBSHIT_NOLUA T PreadGen(FilePosition offs) const\n { T ret; PreadGen<Checker>(offs, ret); return ret; }\n\n\n template <typename Checker = Libshit::Check::Assert>\n LIBSHIT_NOLUA void Read(Byte* buf, FileMemSize len)\n { Pread<Checker>(get, buf, len); get += len; }\n template <typename Checker = Libshit::Check::Assert>\n LIBSHIT_NOLUA void Read(char* buf, FileMemSize len)\n { Pread<Checker>(get, buf, len); get += len; }\n\n template <typename Checker = Libshit::Check::Assert>\n LIBSHIT_NOLUA void Pread(\n FilePosition offs, Byte* buf, FileMemSize len) const\n {\n LIBSHIT_ADD_INFOS(\n LIBSHIT_CHECK(SourceOverflow, offs <= size && offs+len <= size,\n \"Source overflow\");\n Pread_(offs, buf, len),\n \"Used source\", *this, \"Read offset\", offs, \"Read size\", len);\n }\n\n template <typename Checker = Libshit::Check::Assert>\n LIBSHIT_NOLUA\n void Pread(FilePosition offs, char* buf, FileMemSize len) const\n { Pread<Checker>(offs, reinterpret_cast<Byte*>(buf), len); }\n\n // helper\n#define NEPTOOLS_GEN_HLP2(bits, Camel, snake) \\\n template <typename Checker = Libshit::Check::Assert> \\\n std::uint##bits##_t Read##Camel##Uint##bits() \\\n { \\\n return boost::endian::snake##_to_native( \\\n ReadGen<std::uint##bits##_t, Checker>()); \\\n } \\\n template <typename Checker = Libshit::Check::Assert> \\\n std::uint##bits##_t Pread##Camel##Uint##bits(FilePosition offs) const \\\n { \\\n return boost::endian::snake##_to_native( \\\n PreadGen<std::uint##bits##_t, Checker>(offs)); \\\n }\n#define NEPTOOLS_GEN_HLP(bits) \\\n template <typename Checker = Libshit::Check::Assert> \\\n std::uint##bits##_t ReadUint##bits(Endian e) \\\n { \\\n return ToNativeCopy(ReadGen<std::uint##bits##_t, Checker>(), e); \\\n } \\\n template <typename Checker = Libshit::Check::Assert> \\\n std::uint##bits##_t PreadUint##bits(FilePosition offs, Endian e) \\\n { \\\n return ToNativeCopy( \\\n PreadGen<std::uint##bits##_t, Checker>(offs), e); \\\n } \\\n NEPTOOLS_GEN_HLP2(bits, Little, little) \\\n NEPTOOLS_GEN_HLP2(bits, Big, big)\n\n // 8-bit values have no endian, but have these functions for consistency\n NEPTOOLS_GEN_HLP(8)\n NEPTOOLS_GEN_HLP(16)\n NEPTOOLS_GEN_HLP(32)\n NEPTOOLS_GEN_HLP(64)\n#undef NEPTOOLS_GEN_HLP\n\n std::string ReadCString()\n {\n auto ret = PreadCString(Tell());\n Seek(Tell() + ret.size() + 1);\n return ret;\n }\n std::string PreadCString(FilePosition offs) const;\n\n struct Provider : public Libshit::RefCounted\n {\n Provider(boost::filesystem::path file_name, FilePosition size)\n : file_name{std::move(file_name)}, size{size} {}\n Provider(const Provider&) = delete;\n void operator=(const Provider&) = delete;\n virtual ~Provider() = default;\n\n virtual void Pread(FilePosition offs, Byte* buf, FileMemSize len) = 0;\n\n void LruPush(const Byte* ptr, FilePosition offset, FileMemSize size);\n bool LruGet(FilePosition offs);\n\n std::array<BufEntry, 4> lru;\n boost::filesystem::path file_name;\n FilePosition size;\n };\n LIBSHIT_NOLUA Source(Libshit::NotNullSmartPtr<Provider> p)\n : size{p->size}, p{Libshit::Move(p)} {}\n\n void Dump(Sink& sink) const;\n LIBSHIT_NOLUA void Dump(Sink&& sink) const { Dump(sink); }\n LIBSHIT_NOLUA void Inspect(std::ostream& os) const;\n LIBSHIT_NOLUA void Inspect(std::ostream&& os) const { Inspect(os); }\n std::string Inspect() const;\n\n LIBSHIT_NOLUA std::string_view GetChunk(FilePosition offs) const;\n\n private:\n // offset: in original file!\n BufEntry GetTemporaryEntry(FilePosition offs) const;\n\n void Pread_(FilePosition offs, Byte* buf, FileMemSize len) const;\n static Source FromFile_(const boost::filesystem::path& fname);\n\n FilePosition offset = 0, size, get = 0;\n\n Libshit::NotNull<Libshit::SmartPtr<Provider>> p;\n };\n\n inline std::ostream& operator<<(std::ostream& os, const Source s)\n { s.Inspect(os); return os; }\n\n std::string to_string(const Source& s);\n\n class DumpableSource final : public Dumpable\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n LIBSHIT_NOLUA\n DumpableSource(Source&& s) noexcept : src{std::move(s)} {}\n DumpableSource(const Source& s, FilePosition offset, FilePosition size) noexcept\n : src{s, offset, size} {}\n DumpableSource(const Source& s) noexcept : src{s} {} // NOLINT\n\n void Fixup() override {}\n\n FilePosition GetSize() const override { return src.GetSize(); }\n Source GetSource() const noexcept { return src; }\n private:\n Source src;\n void Dump_(Sink& sink) const override { src.Dump(sink); }\n void Inspect_(std::ostream& os, unsigned) const override;\n };\n\n#define ADD_SOURCE(expr, ...) \\\n LIBSHIT_ADD_INFOS(expr, \"Used source\", __VA_ARGS__)\n\n struct QuotedSource { Source src; };\n inline std::ostream& operator<<(std::ostream& os, QuotedSource q)\n { DumpBytes(os, q.src); return os; }\n inline QuotedSource Quoted(Source src) { return {src}; }\n\n}\n#endif\n" }, { "alpha_fraction": 0.6419752836227417, "alphanum_fraction": 0.6604938507080078, "avg_line_length": 26, "blob_id": "a3c3ac7cc692188563ffd3345a3d7d18739239d5", "content_id": "9ef8fb2276c2827c0bcc658f8d0441a90d9607a1", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 324, "license_type": "permissive", "max_line_length": 56, "num_lines": 12, "path": "/tools/ci_conf.gcc.sh", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "source tools/ci_conf_linuxcommon.sh\n\nopt=\"-march=x86-64 -mtune=generic\"\n\nrun export CC=\"$(cd /usr/bin; ls gcc-*.*.* | tail -n1)\"\nrun export CXX=\"$(cd /usr/bin; ls g++-*.*.* | tail -n1)\"\nrun export AR=gcc-ar\nrun export CFLAGS=\"$opt\"\nrun export CXXFLAGS=\"$opt\"\nrun export LINKFLAGS=\"$opt -static-libstdc++\"\n\nrun $CC --version\n" }, { "alpha_fraction": 0.7731958627700806, "alphanum_fraction": 0.7731958627700806, "avg_line_length": 23.25, "blob_id": "48d4fbfc833d5dce6fedc6e93dccdaa4390664f2", "content_id": "c9e34bca30c49ef6f50cdf8322048103695c7bf0", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 97, "license_type": "permissive", "max_line_length": 40, "num_lines": 4, "path": "/test/pattern_fail.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"pattern_parse.hpp\"\n\nusing namespace Neptools;\nauto x = NEPTOOLS_PATTERN(TEST_PATTERN);\n" }, { "alpha_fraction": 0.6746987700462341, "alphanum_fraction": 0.6746987700462341, "avg_line_length": 15.600000381469727, "blob_id": "2aa8e5a4117c18947ec2c6f9358093ca679a21e6", "content_id": "c0c977ae4f5a3b5ff7bb37d5e110ca34da979648", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 415, "license_type": "permissive", "max_line_length": 67, "num_lines": 25, "path": "/src/txt_serializable.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"txt_serializable.hpp\"\n\n#include <sstream>\n\nnamespace Neptools\n{\n\n LIBSHIT_LUAGEN()\n static std::string WriteTxt(TxtSerializable& ser)\n {\n std::stringstream ss;\n ser.WriteTxt(ss);\n return ss.str();\n }\n\n LIBSHIT_LUAGEN()\n static void ReadTxt(TxtSerializable& ser, const std::string& str)\n {\n std::stringstream ss{str};\n ser.ReadTxt(ss);\n }\n\n}\n\n#include \"txt_serializable.binding.hpp\"\n" }, { "alpha_fraction": 0.6288959980010986, "alphanum_fraction": 0.6702592372894287, "avg_line_length": 30.209091186523438, "blob_id": "1fe2b27f52f76151da7695e7c648547e3334d084", "content_id": "de5fb7ec6ac735801d8446a643c441db62aa4df9", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3433, "license_type": "permissive", "max_line_length": 72, "num_lines": 110, "path": "/src/format/stcm/collection_link.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_51AA015D_E824_48D3_8BB4_37BC559302DA\n#define UUID_51AA015D_E824_48D3_8BB4_37BC559302DA\n#pragma once\n\n#include \"../item.hpp\"\n#include \"../../source.hpp\"\n\n#include <libshit/lua/auto_table.hpp>\n#include <libshit/lua/value_object.hpp>\n#include <boost/endian/arithmetic.hpp>\n\nnamespace Neptools::Stcm\n{\n\n class CollectionLinkHeaderItem final : public Item\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n struct Header\n {\n boost::endian::little_uint32_t field_00;\n boost::endian::little_uint32_t offset;\n boost::endian::little_uint32_t count;\n boost::endian::little_uint32_t field_0c;\n boost::endian::little_uint32_t field_10;\n boost::endian::little_uint32_t field_14;\n boost::endian::little_uint32_t field_18;\n boost::endian::little_uint32_t field_1c;\n boost::endian::little_uint32_t field_20;\n boost::endian::little_uint32_t field_24;\n boost::endian::little_uint32_t field_28;\n boost::endian::little_uint32_t field_2c;\n boost::endian::little_uint32_t field_30;\n boost::endian::little_uint32_t field_34;\n boost::endian::little_uint32_t field_38;\n boost::endian::little_uint32_t field_3c;\n\n void Validate(FilePosition file_size) const;\n };\n static_assert(sizeof(Header) == 0x40);\n\n CollectionLinkHeaderItem(\n Key k, Context& ctx, Libshit::NotNull<LabelPtr> data)\n : Item{k, ctx}, data{std::move(data)} {}\n\n LIBSHIT_NOLUA\n CollectionLinkHeaderItem(Key k, Context& ctx, const Header& s);\n static CollectionLinkHeaderItem& CreateAndInsert(ItemPointer ptr);\n\n FilePosition GetSize() const noexcept override\n { return sizeof(Header); }\n\n Libshit::NotNull<LabelPtr> data;\n\n private:\n void Dump_(Sink& sink) const override;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n };\n\n class CollectionLinkItem final : public Item\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n struct Entry\n {\n boost::endian::little_uint32_t name_0;\n boost::endian::little_uint32_t name_1;\n boost::endian::little_uint32_t ptr; // filled by engine\n boost::endian::little_uint32_t field_0c;\n boost::endian::little_uint32_t field_10;\n boost::endian::little_uint32_t field_14;\n boost::endian::little_uint32_t field_18;\n boost::endian::little_uint32_t field_1c;\n\n void Validate(FilePosition file_size) const;\n };\n static_assert(sizeof(Entry) == 0x20);\n\n struct LinkEntry;\n CollectionLinkItem(Key k, Context& ctx) : Item{k, ctx} {}\n CollectionLinkItem(Key k, Context& ctx, Source src, uint32_t count);\n CollectionLinkItem(\n Key k, Context& ctx, Libshit::AT<std::vector<LinkEntry>> entries)\n : Item{k, ctx}, entries{std::move(entries.Get())} {}\n\n FilePosition GetSize() const noexcept override\n { return entries.size() * sizeof(Entry); }\n\n struct LinkEntry : public Libshit::Lua::ValueObject\n {\n LabelPtr name_0;\n LabelPtr name_1;\n\n LinkEntry(LabelPtr name_0, LabelPtr name_1)\n : name_0{std::move(name_0)}, name_1{std::move(name_1)} {}\n LIBSHIT_LUA_CLASS;\n };\n LIBSHIT_LUAGEN(get=\"::Libshit::Lua::GetSmartOwnedMember\")\n std::vector<LinkEntry> entries;\n\n void Dispose() noexcept override;\n\n private:\n void Dump_(Sink& sink) const override;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n void Parse_(Context& ctx, Source& src, uint32_t count);\n };\n\n}\n#endif\n" }, { "alpha_fraction": 0.6447802186012268, "alphanum_fraction": 0.6576923131942749, "avg_line_length": 24.815603256225586, "blob_id": "7c02d8c0304aad2f41f8aa95094e5548e7a056a1", "content_id": "d340ef2355e4b01d96a56ccf6efae33d5a48bce6", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3640, "license_type": "permissive", "max_line_length": 72, "num_lines": 141, "path": "/src/format/item_base.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_02043882_EC07_4CCA_BD13_1BB9F5C7DB9F\n#define UUID_02043882_EC07_4CCA_BD13_1BB9F5C7DB9F\n#pragma once\n\n#include \"../utils.hpp\"\n\n#include <libshit/assert.hpp>\n#include <libshit/meta.hpp>\n#include <libshit/shared_ptr.hpp>\n#include <libshit/utils.hpp>\n#include <libshit/container/intrusive.hpp>\n#include <libshit/lua/dynamic_object.hpp>\n#include <libshit/lua/function_call_types.hpp>\n#include <libshit/lua/type_traits.hpp>\n\n#include <cstdint>\n#include <functional>\n#include <boost/intrusive/set_hook.hpp>\n\nnamespace Neptools LIBSHIT_META(\"alias_file src/format/item.hpp\")\n{\n\n class Item;\n class Context;\n\n struct ItemPointer\n {\n Item* item;\n FilePosition offset;\n\n ItemPointer(Item* item, FilePosition offset = 0)\n : item{item}, offset{offset} {}\n ItemPointer(Item& item, FilePosition offset = 0)\n : item{&item}, offset{offset} {}\n\n bool operator==(const ItemPointer& o) const\n { return item == o.item && offset == o.offset; }\n bool operator!=(const ItemPointer& o) const\n { return item != o.item || offset != o.offset; }\n\n Item& operator*() const { return *item; }\n Item* operator->() const { return &*item; }\n\n template <typename T>\n T& As() const { return *Libshit::asserted_cast<T*>(item); }\n\n template <typename T>\n T& AsChecked() const { return dynamic_cast<T&>(*item); }\n\n template <typename T>\n T* Maybe() const { return dynamic_cast<T*>(item); }\n\n template <typename T>\n T& As0() const\n {\n LIBSHIT_ASSERT(offset == 0);\n return *Libshit::asserted_cast<T*>(item);\n }\n\n template <typename T>\n T& AsChecked0() const\n {\n LIBSHIT_ASSERT(offset == 0);\n return dynamic_cast<T&>(*item);\n }\n\n template <typename T>\n T* Maybe0() const\n {\n LIBSHIT_ASSERT(offset == 0);\n return dynamic_cast<T*>(item);\n }\n };\n\n using LabelNameHook = boost::intrusive::set_base_hook<\n boost::intrusive::tag<struct NameTag>,\n boost::intrusive::optimize_size<true>, Libshit::LinkMode>;\n using LabelOffsetHook = boost::intrusive::set_base_hook<\n boost::intrusive::tag<struct OffsetTag>,\n boost::intrusive::optimize_size<true>, Libshit::LinkMode>;\n\n class Label final :\n public Libshit::RefCounted, public Libshit::Lua::DynamicObject,\n public LabelNameHook, public LabelOffsetHook\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n\n Label(std::string name, ItemPointer ptr)\n : name{std::move(name)}, ptr{ptr} {}\n\n const std::string& GetName() const { return name; }\n const ItemPointer& GetPtr() const { return ptr; }\n\n friend class Context;\n friend class Item;\n private:\n std::string name;\n ItemPointer ptr;\n };\n\n using LabelPtr = Libshit::RefCountedPtr<Label>;\n using WeakLabelPtr = Libshit::WeakRefCountedPtr<Label>;\n\n // to be used by boost::intrusive::set\n struct LabelKeyOfValue\n {\n using type = std::string;\n const type& operator()(const Label& l) { return l.GetName(); }\n };\n\n struct LabelOffsetKeyOfValue\n {\n using type = FilePosition;\n const type& operator()(const Label& l) { return l.GetPtr().offset; }\n };\n\n}\n\n\ntemplate<> struct Libshit::Lua::TupleLike<Neptools::ItemPointer>\n{\n template <size_t I> static auto& Get(\n const Neptools::ItemPointer& ptr) noexcept\n {\n if constexpr (I == 0) return *ptr.item;\n else if constexpr (I == 1) return ptr.offset;\n }\n static constexpr size_t SIZE = 2;\n};\n\ntemplate<> struct std::hash<::Neptools::ItemPointer>\n{\n std::size_t operator()(const ::Neptools::ItemPointer& ptr) const\n {\n return hash<::Neptools::Item*>()(ptr.item) ^\n hash<::Neptools::FilePosition>()(ptr.offset);\n }\n};\n\n#endif\n" }, { "alpha_fraction": 0.6406551003456116, "alphanum_fraction": 0.6849710941314697, "avg_line_length": 22.590909957885742, "blob_id": "54c89d2dc4d618d34f81a4d3d4d174d4b665651a", "content_id": "e81a06b3a348a984709b7800f735e9a756e5ecc6", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1038, "license_type": "permissive", "max_line_length": 74, "num_lines": 44, "path": "/src/format/stcm/file.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_61A5519F_6624_43C0_8451_0BCA60B5D69A\n#define UUID_61A5519F_6624_43C0_8451_0BCA60B5D69A\n#pragma once\n\n#include \"../../source.hpp\"\n#include \"../../txt_serializable.hpp\"\n#include \"../context.hpp\"\n\nnamespace Neptools::Stcm\n{\n class GbnlItem;\n\n class File final : public Context, public TxtSerializable\n {\n LIBSHIT_DYNAMIC_OBJECT;\n\n template <typename T>\n using GbnlVectG = std::vector<Libshit::NotNull<Libshit::SmartPtr<T>>>;\n\n GbnlItem* first_gbnl = nullptr;\n\n public:\n File() = default;\n File(Source src);\n\n LIBSHIT_NOLUA void SetGbnl(GbnlItem& gbnl) noexcept;\n LIBSHIT_NOLUA void UnsetGbnl(GbnlItem& gbnl) noexcept\n { if (first_gbnl == &gbnl) first_gbnl = nullptr; }\n GbnlItem* GetGbnl() const noexcept { return first_gbnl; };\n\n void Gc() noexcept;\n\n protected:\n void Inspect_(std::ostream& os, unsigned indent) const override;\n\n private:\n void Parse_(Source& src);\n\n void WriteTxt_(std::ostream& os) const override;\n void ReadTxt_(std::istream& is) override;\n };\n\n}\n#endif\n" }, { "alpha_fraction": 0.6105934381484985, "alphanum_fraction": 0.6253065466880798, "avg_line_length": 30.859375, "blob_id": "8d80709ac91f97e1f352c0073858efe18fd82263", "content_id": "9f7f1d6efe41cf25b7c98f7b1be8aca5e4530ec1", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2039, "license_type": "permissive", "max_line_length": 83, "num_lines": 64, "path": "/src/format/stcm/string_data.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"string_data.hpp\"\n\n#include \"data.hpp\"\n#include \"../raw_item.hpp\"\n#include \"../../sink.hpp\"\n\n#include <libshit/char_utils.hpp>\n\nnamespace Neptools::Stcm\n{\n\n Libshit::RefCountedPtr<StringDataItem>\n StringDataItem::MaybeCreateAndReplace(DataItem& it)\n {\n // string: data(0, x, 1), where x = size/4, size is strlen+1 rounded to 4 bytes\n // ignore x == 1: it's probably an int32\n if (it.type != 0 || it.offset_unit <= 1 || it.field_8 != 1 ||\n it.GetChildren().empty() || // only one child\n &it.GetChildren().front() != &it.GetChildren().back()) return nullptr;\n auto child = dynamic_cast<RawItem*>(&it.GetChildren().front());\n if (!child || child->GetSize() != it.offset_unit * 4) return nullptr;\n\n auto src = child->GetSource();\n auto s = src.ReadCString();\n auto padlen = it.offset_unit * 4 - s.size() - 1;\n if (padlen > 4) return nullptr;\n char pad[4];\n src.Read(pad, padlen);\n // check padding all zero. I don't think it's required, but in the game\n // files they're zero filled, + dump will generate zeros, so do not lose\n // information by discarding a non-null padding...\n for (size_t i = 0; i < padlen; ++i)\n if (pad[i] != 0) return nullptr;\n\n auto sit = it.GetContext()->Create<StringDataItem>(Libshit::Move(s));\n it.Replace(sit);\n return Libshit::Move(sit);\n }\n\n FilePosition StringDataItem::GetSize() const noexcept\n {\n return sizeof(DataItem::Header) + (string.length() + 1 + 3) / 4 * 4;\n }\n\n void StringDataItem::Dump_(Sink& sink) const\n {\n auto len = (string.length() + 1 + 3) / 4 * 4;\n sink.WriteGen(DataItem::Header{0, len/4, 1, len});\n sink.Write(string);\n sink.Pad(len - string.length());\n }\n\n void StringDataItem::Inspect_(std::ostream& os, unsigned indent) const\n {\n Item::Inspect_(os, indent);\n os << \"string_data(\" << Libshit::Quoted(string) << ')';\n }\n\n static Stcm::DataFactory reg{[](DataItem& it) {\n return !!StringDataItem::MaybeCreateAndReplace(it); }};\n\n}\n\n#include \"string_data.binding.hpp\"\n" }, { "alpha_fraction": 0.6996282339096069, "alphanum_fraction": 0.6996282339096069, "avg_line_length": 38.55882263183594, "blob_id": "014dcc4df8c508d720d0ed45e2c15cf469fd9c2b", "content_id": "b9ec7207b4c802c0ee31acbdc78c6da0be462c54", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1345, "license_type": "permissive", "max_line_length": 166, "num_lines": 34, "path": "/src/format/stcm/string_data.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Stcm::StringDataItem::TYPE_NAME[] = \"neptools.stcm.string_data_item\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.stcm.string_data_item\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::StringDataItem>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stcm::StringDataItem, ::Neptools::Item>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::StringDataItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<std::string>>\n >(\"new\");\n bld.AddFunction<\n static_cast<Libshit::RefCountedPtr<::Neptools::Stcm::StringDataItem> (*)(::Neptools::Stcm::DataItem &)>(::Neptools::Stcm::StringDataItem::MaybeCreateAndReplace)\n >(\"maybe_create_and_replace\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::StringDataItem, std::string, &::Neptools::Stcm::StringDataItem::string>\n >(\"get_string\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stcm::StringDataItem, std::string, &::Neptools::Stcm::StringDataItem::string>\n >(\"set_string\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::StringDataItem> reg_neptools_stcm_string_data_item;\n\n}\n#endif\n" }, { "alpha_fraction": 0.6884545087814331, "alphanum_fraction": 0.6957849860191345, "avg_line_length": 53.56666564941406, "blob_id": "bdc7fd21521b4be5e2f44087fa1bac5669216752", "content_id": "6a97c16742a739a529e221a1e1d68e245aa765ba", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1637, "license_type": "permissive", "max_line_length": 385, "num_lines": 30, "path": "/src/format/stcm/gbnl.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Stcm::GbnlItem::TYPE_NAME[] = \"neptools.stcm.gbnl_item\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.stcm.gbnl_item\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::GbnlItem>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stcm::GbnlItem, ::Neptools::Item, ::Neptools::Gbnl>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::GbnlItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::Neptools::Source>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::GbnlItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::Neptools::Endian>, LuaGetRef<bool>, LuaGetRef<::uint32_t>, LuaGetRef<::uint32_t>, LuaGetRef<::uint32_t>, LuaGetRef<Libshit::AT<::Neptools::Gbnl::Struct::TypePtr>>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::GbnlItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::Libshit::Lua::StateRef>, LuaGetRef<::Neptools::Endian>, LuaGetRef<bool>, LuaGetRef<::uint32_t>, LuaGetRef<::uint32_t>, LuaGetRef<::uint32_t>, LuaGetRef<Libshit::AT<::Neptools::Gbnl::Struct::TypePtr>>, LuaGetRef<::Libshit::Lua::RawTable>>\n >(\"new\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::GbnlItem & (*)(::Neptools::ItemPointer)>(::Neptools::Stcm::GbnlItem::CreateAndInsert)\n >(\"create_and_insert\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::GbnlItem> reg_neptools_stcm_gbnl_item;\n\n}\n#endif\n" }, { "alpha_fraction": 0.6912650465965271, "alphanum_fraction": 0.6912650465965271, "avg_line_length": 25.559999465942383, "blob_id": "ff3dae783b3059f322b76600210ccf794069b760", "content_id": "286f209d4194a0c532524e9dc537f93fe0fdfe35", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 664, "license_type": "permissive", "max_line_length": 128, "num_lines": 25, "path": "/src/format/eof_item.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::EofItem::TYPE_NAME[] = \"neptools.eof_item\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.eof_item\n template<>\n void TypeRegisterTraits<::Neptools::EofItem>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::EofItem, ::Neptools::Item>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::EofItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>>\n >(\"new\");\n\n }\n static TypeRegister::StateRegister<::Neptools::EofItem> reg_neptools_eof_item;\n\n}\n#endif\n" }, { "alpha_fraction": 0.6026341915130615, "alphanum_fraction": 0.6458747386932373, "avg_line_length": 28.58823585510254, "blob_id": "07845b328bb63bc5361ee9df79c0539caa78b2ad", "content_id": "07200e03725422550416ac428b0d00e98a11ed82", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4024, "license_type": "permissive", "max_line_length": 81, "num_lines": 136, "path": "/src/format/gbnl.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_9037C300_D4EF_473C_8387_A1A9797069A7\n#define UUID_9037C300_D4EF_473C_8387_A1A9797069A7\n#pragma once\n\n#include \"../dumpable.hpp\"\n#include \"../endian.hpp\"\n#include \"../source.hpp\"\n#include \"../dynamic_struct.hpp\"\n#include \"../txt_serializable.hpp\"\n\n#include <libshit/lua/auto_table.hpp>\n#include <boost/endian/arithmetic.hpp>\n#include <vector>\n\nnamespace Neptools\n{\n\n class Gbnl : public Dumpable, public TxtSerializable\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n struct Header // or Footer\n {\n char magic[3];\n char endian;\n\n std::uint16_t field_04;\n std::uint16_t field_06;\n std::uint32_t field_08;\n std::uint32_t field_0c;\n std::uint32_t flags; // 1 if there's a string, 0 otherwise?\n std::uint32_t descr_offset;\n std::uint32_t count_msgs;\n std::uint32_t msg_descr_size;\n std::uint32_t count_types;\n std::uint32_t offset_types;\n std::uint32_t field_28;\n std::uint32_t offset_msgs;\n std::uint32_t field_30;\n std::uint32_t field_34;\n std::uint32_t field_38;\n std::uint32_t field_3c;\n\n void Validate(std::size_t chunk_size) const;\n };\n static_assert(sizeof(Header) == 0x40);\n\n struct TypeDescriptor\n {\n enum Type\n {\n INT32 = 0,\n INT8 = 1,\n INT16 = 2,\n FLOAT = 3,\n STRING = 5,\n INT64 = 6,\n };\n std::uint16_t type;\n std::uint16_t offset;\n };\n static_assert(sizeof(TypeDescriptor) == 0x04);\n\n struct OffsetString\n {\n std::string str;\n uint32_t offset;\n };\n\n struct FixStringTag { char str[1]; };\n struct PaddingTag { char pad[1]; };\n\n using Struct = DynamicStruct<\n int8_t, int16_t, int32_t, int64_t, float, OffsetString,\n FixStringTag, PaddingTag>;\n using StructPtr = Libshit::NotNull<boost::intrusive_ptr<Struct>>;\n using Messages = std::vector<StructPtr>;\n\n Gbnl(Source src);\n Gbnl(Endian endian, bool is_gstl, uint32_t flags, uint32_t field_28,\n uint32_t field_30, Libshit::AT<Struct::TypePtr> type)\n : endian{endian}, is_gstl{is_gstl}, flags{flags}, field_28{field_28},\n field_30{field_30}, type{std::move(type.Get())} {}\n#if LIBSHIT_WITH_LUA\n Gbnl(Libshit::Lua::StateRef vm, Endian endian, bool is_gstl, uint32_t flags,\n uint32_t field_28, uint32_t field_30, Libshit::AT<Struct::TypePtr> type,\n Libshit::Lua::RawTable messages);\n#endif\n\n void Fixup() override { RecalcSize(); }\n\n Endian endian;\n bool is_gstl;\n uint32_t flags, field_28, field_30;\n\n // no setter - it doesn't work how you expect in lua\n LIBSHIT_LUAGEN(get=\"::Libshit::Lua::GetSmartOwnedMember\")\n Messages messages;\n\n Struct::TypePtr type;\n\n void RecalcSize();\n FilePosition GetSize() const noexcept override;\n\n Libshit::NotNullSharedPtr<TxtSerializable> GetDefaultTxtSerializable(\n const Libshit::NotNullSharedPtr<Dumpable>& thiz) override\n { return Libshit::NotNullSharedPtr<TxtSerializable>{thiz.Get(), this}; }\n\n protected:\n // todo: private after removing GbnlItem\n void Dump_(Sink& sink) const override;\n void InspectGbnl(std::ostream& os, unsigned indent) const;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n\n private:\n void WriteTxt_(std::ostream& os) const override;\n void ReadTxt_(std::istream& is) override;\n\n void Parse_(Source& src);\n void DumpHeader(Sink& sink) const;\n void Pad(uint16_t diff, Struct::TypeBuilder& bld, bool& int8_in_progress);\n FilePosition Align(FilePosition x) const noexcept;\n\n std::optional<std::int32_t> GetId(\n bool simple, const Gbnl::Struct& m, size_t i, size_t j, size_t& k) const;\n size_t FindDst(bool simple, int32_t id, std::vector<StructPtr>& messages,\n size_t& index) const;\n\n size_t msg_descr_size, msgs_size;\n size_t real_item_count; // excluding dummy pad items\n };\n\n void endian_reverse_inplace(Gbnl::Header& hdr);\n void endian_reverse_inplace(Gbnl::TypeDescriptor& desc);\n}\n#endif\n" }, { "alpha_fraction": 0.6812773942947388, "alphanum_fraction": 0.6812773942947388, "avg_line_length": 39.9487190246582, "blob_id": "1aa18b2c10a73a991dc609d2cace2afdd1b41864", "content_id": "72f278c13f10d88222e6941c905cf1004642b752", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1597, "license_type": "permissive", "max_line_length": 171, "num_lines": 39, "path": "/src/format/cstring_item.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::CStringItem::TYPE_NAME[] = \"neptools.c_string_item\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.c_string_item\n template<>\n void TypeRegisterTraits<::Neptools::CStringItem>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::CStringItem, ::Neptools::Item>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::CStringItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<std::string>>,\n &::Libshit::Lua::TypeTraits<::Neptools::CStringItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<const ::Neptools::Source &>>\n >(\"new\");\n bld.AddFunction<\n static_cast<::Neptools::CStringItem & (*)(::Neptools::ItemPointer)>(::Neptools::CStringItem::CreateAndInsert)\n >(\"create_and_insert\");\n bld.AddFunction<\n static_cast<std::string (*)(std::string)>(::Neptools::CStringItem::GetLabelName),\n static_cast<std::string (::Neptools::CStringItem::*)() const>(&::Neptools::CStringItem::GetLabelName)\n >(\"get_label_name\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::CStringItem, std::string, &::Neptools::CStringItem::string>\n >(\"get_string\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::CStringItem, std::string, &::Neptools::CStringItem::string>\n >(\"set_string\");\n\n }\n static TypeRegister::StateRegister<::Neptools::CStringItem> reg_neptools_c_string_item;\n\n}\n#endif\n" }, { "alpha_fraction": 0.6659902334213257, "alphanum_fraction": 0.6834415793418884, "avg_line_length": 55, "blob_id": "894b5e1fa764ba737845f92a0db506b17d715aa4", "content_id": "2adb21dd0d734bb8aa513ad8636c7b303e31fe46", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4928, "license_type": "permissive", "max_line_length": 343, "num_lines": 88, "path": "/src/format/stsc/header.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Stsc::HeaderItem::TYPE_NAME[] = \"neptools.stsc.header_item\";\n\nconst char ::Neptools::Stsc::HeaderItem::ExtraHeaders2::TYPE_NAME[] = \"extra_headers_2\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.stsc.header_item\n template<>\n void TypeRegisterTraits<::Neptools::Stsc::HeaderItem>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stsc::HeaderItem, ::Neptools::Item>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stsc::HeaderItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::Neptools::Source>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stsc::HeaderItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::Libshit::NotNull<::Neptools::LabelPtr>>, LuaGetRef<std::optional<std::string_view>>, LuaGetRef<std::optional<::Neptools::Stsc::HeaderItem::ExtraHeaders2>>, LuaGetRef<std::optional<::uint16_t>>>\n >(\"new\");\n bld.AddFunction<\n static_cast<::Neptools::Stsc::HeaderItem & (*)(::Neptools::ItemPointer, ::Neptools::Stsc::Flavor)>(::Neptools::Stsc::HeaderItem::CreateAndInsert)\n >(\"create_and_insert\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::HeaderItem, ::Libshit::NotNull<::Neptools::LabelPtr>, &::Neptools::Stsc::HeaderItem::entry_point>\n >(\"get_entry_point\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stsc::HeaderItem, ::Libshit::NotNull<::Neptools::LabelPtr>, &::Neptools::Stsc::HeaderItem::entry_point>\n >(\"set_entry_point\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::HeaderItem, std::optional<std::array<std::uint8_t, 32> >, &::Neptools::Stsc::HeaderItem::extra_headers_1>\n >(\"get_extra_headers_1\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stsc::HeaderItem, std::optional<std::array<std::uint8_t, 32> >, &::Neptools::Stsc::HeaderItem::extra_headers_1>\n >(\"set_extra_headers_1\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::HeaderItem, std::optional<::Neptools::Stsc::HeaderItem::ExtraHeaders2>, &::Neptools::Stsc::HeaderItem::extra_headers_2>\n >(\"get_extra_headers_2\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stsc::HeaderItem, std::optional<::Neptools::Stsc::HeaderItem::ExtraHeaders2>, &::Neptools::Stsc::HeaderItem::extra_headers_2>\n >(\"set_extra_headers_2\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::HeaderItem, std::optional<std::uint16_t>, &::Neptools::Stsc::HeaderItem::extra_headers_4>\n >(\"get_extra_headers_4\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stsc::HeaderItem, std::optional<std::uint16_t>, &::Neptools::Stsc::HeaderItem::extra_headers_4>\n >(\"set_extra_headers_4\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stsc::HeaderItem> reg_neptools_stsc_header_item;\n\n // class extra_headers_2\n template<>\n void TypeRegisterTraits<::Neptools::Stsc::HeaderItem::ExtraHeaders2>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::HeaderItem::ExtraHeaders2, std::uint16_t, &::Neptools::Stsc::HeaderItem::ExtraHeaders2::field_0>\n >(\"get_field_0\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::HeaderItem::ExtraHeaders2, std::uint16_t, &::Neptools::Stsc::HeaderItem::ExtraHeaders2::field_2>\n >(\"get_field_2\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::HeaderItem::ExtraHeaders2, std::uint16_t, &::Neptools::Stsc::HeaderItem::ExtraHeaders2::field_4>\n >(\"get_field_4\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::HeaderItem::ExtraHeaders2, std::uint16_t, &::Neptools::Stsc::HeaderItem::ExtraHeaders2::field_6>\n >(\"get_field_6\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::HeaderItem::ExtraHeaders2, std::uint16_t, &::Neptools::Stsc::HeaderItem::ExtraHeaders2::field_8>\n >(\"get_field_8\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::HeaderItem::ExtraHeaders2, std::uint16_t, &::Neptools::Stsc::HeaderItem::ExtraHeaders2::field_a>\n >(\"get_field_a\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::HeaderItem::ExtraHeaders2, std::uint16_t, &::Neptools::Stsc::HeaderItem::ExtraHeaders2::field_c>\n >(\"get_field_c\");\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stsc::HeaderItem::ExtraHeaders2>::Make<LuaGetRef<std::uint16_t>, LuaGetRef<std::uint16_t>, LuaGetRef<std::uint16_t>, LuaGetRef<std::uint16_t>, LuaGetRef<std::uint16_t>, LuaGetRef<std::uint16_t>, LuaGetRef<std::uint16_t>>\n >(\"new\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stsc::HeaderItem::ExtraHeaders2> reg_extra_headers_2;\n\n}\n#endif\n" }, { "alpha_fraction": 0.7031662464141846, "alphanum_fraction": 0.7031662464141846, "avg_line_length": 27.074073791503906, "blob_id": "9b641ae8c520de16a993307bed7b25c714b0fe47", "content_id": "ad6df2585614c66d55b5a6d5fef26f7726a263b5", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 758, "license_type": "permissive", "max_line_length": 99, "num_lines": 27, "path": "/src/txt_serializable.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::TxtSerializable::TYPE_NAME[] = \"neptools.txt_serializable\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.txt_serializable\n template<>\n void TypeRegisterTraits<::Neptools::TxtSerializable>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n static_cast<std::string (*)(::Neptools::TxtSerializable &)>(&Neptools::WriteTxt)\n >(\"write_txt\");\n bld.AddFunction<\n static_cast<void (*)(::Neptools::TxtSerializable &, const std::string &)>(&Neptools::ReadTxt)\n >(\"read_txt\");\n\n }\n static TypeRegister::StateRegister<::Neptools::TxtSerializable> reg_neptools_txt_serializable;\n\n}\n#endif\n" }, { "alpha_fraction": 0.602232038974762, "alphanum_fraction": 0.650452733039856, "avg_line_length": 26.771930694580078, "blob_id": "9e5452d12340b0aac267329437b19dcea45ba1c2", "content_id": "8f8a08bdb06dd61e87c5fb8eef33e8bda7e4342a", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4749, "license_type": "permissive", "max_line_length": 77, "num_lines": 171, "path": "/src/format/cl3.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_4CADE91E_2AF1_47AF_8425_9AA799509BFD\n#define UUID_4CADE91E_2AF1_47AF_8425_9AA799509BFD\n#pragma once\n\n#include \"../endian.hpp\"\n#include \"../source.hpp\"\n#include \"../sink.hpp\"\n\n#include <libshit/fixed_string.hpp>\n#include <libshit/container/ordered_map.hpp>\n#include <libshit/lua/auto_table.hpp>\n\n#include <boost/filesystem/path.hpp>\n\n#include <cstdint>\n#include <vector>\n#include <string_view>\n\nnamespace Neptools\n{\n namespace Stcm { class File; }\n\n class Cl3 final : public Libshit::RefCounted, public Dumpable\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n struct Header\n {\n char magic[3];\n char endian;\n std::uint32_t field_04;\n std::uint32_t field_08;\n std::uint32_t sections_count;\n std::uint32_t sections_offset;\n std::uint32_t field_14;\n\n void Validate(FilePosition file_size) const;\n };\n static_assert(sizeof(Header) == 0x18);\n\n struct Section\n {\n Libshit::FixedString<0x20> name;\n std::uint32_t count;\n std::uint32_t data_size;\n std::uint32_t data_offset;\n std::uint32_t field_2c;\n std::uint32_t field_30;\n std::uint32_t field_34;\n std::uint32_t field_38;\n std::uint32_t field_3c;\n std::uint32_t field_40;\n std::uint32_t field_44;\n std::uint32_t field_48;\n std::uint32_t field_4c;\n\n void Validate(FilePosition file_size) const;\n };\n static_assert(sizeof(Section) == 0x50);\n\n struct FileEntry\n {\n Libshit::FixedString<0x200> name;\n std::uint32_t field_200;\n std::uint32_t data_offset;\n std::uint32_t data_size;\n std::uint32_t link_start;\n std::uint32_t link_count;\n std::uint32_t field_214;\n std::uint32_t field_218;\n std::uint32_t field_21c;\n std::uint32_t field_220;\n std::uint32_t field_224;\n std::uint32_t field_228;\n std::uint32_t field_22c;\n\n void Validate(uint32_t block_size) const;\n };\n static_assert(sizeof(FileEntry) == 0x230);\n\n struct LinkEntry\n {\n std::uint32_t field_00;\n std::uint32_t linked_file_id;\n std::uint32_t link_id;\n std::uint32_t field_0c;\n std::uint32_t field_10;\n std::uint32_t field_14;\n std::uint32_t field_18;\n std::uint32_t field_1c;\n\n void Validate(std::uint32_t i, std::uint32_t file_count) const;\n };\n static_assert(sizeof(LinkEntry) == 0x20);\n\n struct Entry\n : public Libshit::OrderedMapItem, public Libshit::Lua::DynamicObject\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n std::string name;\n uint32_t field_200 = 0;\n\n using Links = std::vector<Libshit::WeakRefCountedPtr<Cl3::Entry>>;\n // no setter - it doesn't work how you expect in lua\n LIBSHIT_LUAGEN(get=\"::Libshit::Lua::GetRefCountedOwnedMember\")\n Links links;\n\n Libshit::SmartPtr<Dumpable> src;\n\n Entry(std::string name, uint32_t field_200,\n Libshit::SmartPtr<Dumpable> src)\n : name{std::move(name)}, field_200{field_200}, src{std::move(src)} {}\n explicit Entry(std::string name) : name{std::move(name)} {}\n\n void Dispose() noexcept override;\n };\n struct EntryKeyOfValue\n {\n using type = std::string;\n const type& operator()(const Entry& e) { return e.name; }\n };\n using Entries = Libshit::OrderedMap<Entry, EntryKeyOfValue>;\n\n\n Cl3(Source src);\n explicit Cl3(Endian endian = Endian::LITTLE)\n : endian{endian}, field_14{0} {}\n#if LIBSHIT_WITH_LUA\n Cl3(Libshit::Lua::StateRef vm, Endian endian, uint32_t field_14,\n Libshit::Lua::RawTable entries);\n#endif\n\n void Fixup() override;\n FilePosition GetSize() const override;\n\n Endian endian;\n uint32_t field_14;\n\n // no setter - it doesn't work how you expect in lua\n LIBSHIT_LUAGEN(get=\"::Libshit::Lua::GetRefCountedOwnedMember\")\n Entries entries;\n uint32_t IndexOf(const Libshit::WeakSmartPtr<Entry>& ptr) const noexcept;\n\n Entry& GetOrCreateFile(std::string_view fname);\n\n void ExtractTo(const boost::filesystem::path& dir) const;\n void UpdateFromDir(const boost::filesystem::path& dir);\n\n Stcm::File& GetStcm();\n\n Libshit::NotNullSharedPtr<TxtSerializable> GetDefaultTxtSerializable(\n const Libshit::NotNullSharedPtr<Dumpable>& thiz) override;\n\n void Dispose() noexcept override;\n\n private:\n FilePosition data_size;\n unsigned link_count;\n\n void Parse_(Source& src);\n void Dump_(Sink& os) const override;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n };\n\n void endian_reverse_inplace(Cl3::Header& hdr) noexcept;\n void endian_reverse_inplace(Cl3::Section& sec) noexcept;\n void endian_reverse_inplace(Cl3::FileEntry& entry) noexcept;\n void endian_reverse_inplace(Cl3::LinkEntry& entry) noexcept;\n}\n#endif\n" }, { "alpha_fraction": 0.5927602052688599, "alphanum_fraction": 0.6606335043907166, "avg_line_length": 15.370369911193848, "blob_id": "6d01ed96acffd36e54dfe92e4335a4bf46021ae1", "content_id": "a83e22e6efd2b3b7569e151e9392bc504fd28299", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 442, "license_type": "permissive", "max_line_length": 51, "num_lines": 27, "path": "/src/factory.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_F3B9AB07_80DA_4DCF_AA4F_F6E225EFA110\n#define UUID_F3B9AB07_80DA_4DCF_AA4F_F6E225EFA110\n#pragma once\n\n#include <vector>\n\nnamespace Neptools\n{\n\n template <typename FunT>\n class BaseFactory\n {\n public:\n using Fun = FunT;\n BaseFactory(Fun f) { GetStore().push_back(f); }\n\n protected:\n using Store = std::vector<Fun>;\n static Store& GetStore()\n {\n static Store store;\n return store;\n }\n };\n\n}\n#endif\n" }, { "alpha_fraction": 0.6505087018013, "alphanum_fraction": 0.6744464635848999, "avg_line_length": 22.53521156311035, "blob_id": "d4bcd5195ec8830bc9ee1081f0278dd9ae2aea37", "content_id": "96c6d14c0ad02ee412df5d30e9190176d9cb3aa7", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1671, "license_type": "permissive", "max_line_length": 63, "num_lines": 71, "path": "/src/endian.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_A2E491BD_BA3E_4C92_B931_72017B89C33C\n#define UUID_A2E491BD_BA3E_4C92_B931_72017B89C33C\n#pragma once\n\n#include <libshit/assert.hpp>\n#include <libshit/meta.hpp>\n#include <libshit/lua/type_traits.hpp>\n\n#include <boost/endian/conversion.hpp>\n\nnamespace Neptools\n{\n enum class LIBSHIT_LUAGEN() Endian\n {\n BIG, LITTLE,\n };\n\n // not constexpr because gcc is retarded\n inline boost::endian::order ToBoost(Endian e) noexcept\n {\n switch (e)\n {\n case Endian::BIG: return boost::endian::order::big;\n case Endian::LITTLE: return boost::endian::order::little;\n }\n LIBSHIT_UNREACHABLE(\"Invalid Endian value\");\n }\n\n inline const char* ToString(Endian e) noexcept\n {\n switch (e)\n {\n case Endian::BIG: return \"BIG\";\n case Endian::LITTLE: return \"LITTLE\";\n }\n LIBSHIT_UNREACHABLE(\"Invalid Endian value\");\n }\n\n template <typename T>\n [[nodiscard]] inline T ToNativeCopy(T t, Endian e) noexcept\n {\n return boost::endian::conditional_reverse(\n std::move(t), ToBoost(e), boost::endian::order::native);\n }\n\n template <typename T>\n [[nodiscard]] inline T FromNativeCopy(T t, Endian e) noexcept\n {\n return boost::endian::conditional_reverse(\n std::move(t), ToBoost(e), boost::endian::order::native);\n }\n\n template <typename T>\n inline void ToNative(T& t, Endian e) noexcept\n {\n boost::endian::conditional_reverse_inplace(\n t, ToBoost(e), boost::endian::order::native);\n }\n\n template <typename T>\n inline void FromNative(T& t, Endian e) noexcept\n {\n boost::endian::conditional_reverse_inplace(\n t, ToBoost(e), boost::endian::order::native);\n }\n\n}\n\nLIBSHIT_ENUM(Neptools::Endian);\n\n#endif\n" }, { "alpha_fraction": 0.6853487491607666, "alphanum_fraction": 0.6923545598983765, "avg_line_length": 31.66666603088379, "blob_id": "d48805bd0ad911b64234c4629c18af830673c4ea", "content_id": "b40f55d044bc4d1aa9c600641c3baf74c919f392", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6566, "license_type": "permissive", "max_line_length": 83, "num_lines": 201, "path": "/src/format/item.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_294A7F35_D9EC_4A07_961F_A74307C4FA29\n#define UUID_294A7F35_D9EC_4A07_961F_A74307C4FA29\n#pragma once\n\n#include \"item_base.hpp\"\n#include \"../dumpable.hpp\"\n\n#include <libshit/check.hpp>\n#include <libshit/shared_ptr.hpp>\n#include <libshit/container/parent_list.hpp>\n#include <libshit/lua/user_type_fwd.hpp>\n\n#include <iosfwd>\n#include <vector>\n#include <map>\n#include <boost/intrusive/set.hpp>\n\nnamespace Neptools\n{\n\n class ItemWithChildren;\n struct ItemListTraits;\n\n LIBSHIT_GEN_EXCEPTION_TYPE(InvalidItemState, std::logic_error);\n\n class Item\n : public Libshit::RefCounted, public Dumpable,\n public Libshit::ParentListBaseHook<>\n {\n LIBSHIT_LUA_CLASS;\n protected:\n struct Key {};\n public:\n // do not change Context& to Weak/Shared ptr\n // otherwise Context's constructor will try to construct a WeakPtr before\n // RefCounted's constructor is finished, making an off-by-one error and\n // freeing the context twice\n explicit Item(\n Key, Context& ctx, FilePosition position = 0) noexcept\n : position{position}, context{&ctx} {}\n Item(const Item&) = delete;\n void operator=(const Item&) = delete;\n virtual ~Item();\n\n Libshit::RefCountedPtr<Context> GetContextMaybe() noexcept\n { return context.lock(); }\n Libshit::NotNull<Libshit::RefCountedPtr<Context>> GetContext()\n { return Libshit::NotNull<Libshit::RefCountedPtr<Context>>{context}; }\n LIBSHIT_NOLUA Context& GetUnsafeContext() noexcept\n { return *context.unsafe_get(); }\n ItemWithChildren* GetParent() noexcept;\n\n LIBSHIT_NOLUA Libshit::RefCountedPtr<const Context>\n GetContextMaybe() const noexcept\n { return context.lock(); }\n LIBSHIT_NOLUA Libshit::NotNull<Libshit::RefCountedPtr<const Context>>\n GetContext() const\n { return Libshit::NotNull<Libshit::RefCountedPtr<const Context>>{context}; }\n LIBSHIT_NOLUA const Context& GetUnsafeContext() const noexcept\n { return *context.unsafe_get(); }\n LIBSHIT_NOLUA const ItemWithChildren* GetParent() const noexcept;\n LIBSHIT_NOLUA auto Iterator() const noexcept;\n LIBSHIT_NOLUA auto Iterator() noexcept;\n\n FilePosition GetPosition() const noexcept { return position; }\n\n template <typename Checker = Libshit::Check::Assert>\n void Replace(const Libshit::NotNull<Libshit::RefCountedPtr<Item>>& nitem)\n {\n LIBSHIT_CHECK(InvalidItemState, GetParent(), \"no parent\");\n if constexpr (!Checker::IS_NOP)\n {\n auto nsize = nitem->GetSize();\n for (auto& l : labels)\n LIBSHIT_CHECK(InvalidItemState, l.GetPtr().offset <= nsize,\n \"would invalidate labels\");\n }\n LIBSHIT_CHECK(InvalidItemState, nitem->labels.empty(),\n \"new item has labels\");\n Replace_(nitem);\n }\n\n // properties needed: none (might help if ordered)\n // update Slice if no longer ordered\n using LabelsContainer = boost::intrusive::multiset<\n Label,\n boost::intrusive::base_hook<LabelOffsetHook>,\n boost::intrusive::constant_time_size<false>,\n boost::intrusive::key_of_value<LabelOffsetKeyOfValue>>;\n LIBSHIT_LUAGEN(wrap=\"TableRetWrap\")\n const LabelsContainer& GetLabels() const { return labels; }\n\n void Dispose() noexcept override;\n\n protected:\n void UpdatePosition(FilePosition npos);\n\n void Inspect_(std::ostream& os, unsigned indent) const override = 0;\n\n using SlicePair = std::pair<Libshit::NotNull<\n Libshit::RefCountedPtr<Item>>, FilePosition>;\n using SliceSeq = std::vector<SlicePair>;\n void Slice(SliceSeq seq);\n\n FilePosition position;\n\n private:\n Libshit::WeakRefCountedPtr<Context> context;\n\n LabelsContainer labels;\n\n void Replace_(const Libshit::NotNull<Libshit::RefCountedPtr<Item>>& nitem);\n virtual void Removed();\n\n friend class Context;\n friend struct ItemListTraits;\n friend class ItemWithChildren;\n template <typename, typename> friend struct Libshit::Lua::TypeRegisterTraits;\n };\n static_assert(\n std::is_same_v<Libshit::SmartPtr<Item>, Libshit::RefCountedPtr<Item>>);\n\n std::ostream& operator<<(std::ostream& os, const Item& item);\n inline FilePosition ToFilePos(ItemPointer ptr) noexcept\n { return ptr.item->GetPosition() + ptr.offset; }\n\n using ItemList = Libshit::ParentList<Item, ItemListTraits>;\n struct ItemListTraits\n {\n static void add(ItemList&, Item& item) noexcept\n { item.AddRef(); }\n static void remove(ItemList&, Item& item) noexcept\n { item.Removed(); item.RemoveRef(); }\n };\n\n inline auto Item::Iterator() const noexcept\n { return ItemList::s_iterator_to(*this); }\n inline auto Item::Iterator() noexcept\n { return ItemList::s_iterator_to(*this); }\n\n class ItemWithChildren : public Item, private ItemList\n {\n LIBSHIT_LUA_CLASS;\n public:\n using Item::Item;\n\n LIBSHIT_LUAGEN(wrap=\"OwnedSharedPtrWrap\")\n ItemList& GetChildren() noexcept { return *this; }\n LIBSHIT_NOLUA const ItemList& GetChildren() const noexcept { return *this; }\n\n FilePosition GetSize() const override;\n void Fixup() override { Fixup_(0); }\n\n LIBSHIT_NOLUA void MoveNextToChild(size_t size) noexcept;\n\n void Dispose() noexcept override;\n\n protected:\n void Dump_(Sink& sink) const override;\n void InspectChildren(std::ostream& sink, unsigned indent) const;\n void Fixup_(FilePosition offset);\n\n private:\n void Removed() override;\n\n friend struct ::Neptools::ItemListTraits;\n friend class Item;\n } LIBSHIT_LUAGEN(post_register=[[\n LIBSHIT_LUA_RUNBC(bld, builder, 1);\n bld.SetField(\"build\");\n ]]);\n\n inline ItemWithChildren* Item::GetParent() noexcept\n { return static_cast<ItemWithChildren*>(ItemList::opt_get_parent(*this)); }\n inline const ItemWithChildren* Item::GetParent() const noexcept\n { return static_cast<const ItemWithChildren*>(ItemList::opt_get_parent(*this)); }\n\n}\n\n#if LIBSHIT_WITH_LUA\ntemplate <typename T>\nstruct Libshit::Lua::SmartObjectMaker<\n T, std::enable_if_t<\n std::is_base_of_v<Neptools::Item, T> &&\n !std::is_base_of_v<Neptools::Context, T>>>\n{\n template <typename Key, typename Ctx, typename... Args>\n static decltype(auto) Make(std::remove_pointer_t<Ctx>& ctx, Args&&... args)\n { return ctx.template Create<T>(std::forward<Args>(args)...); }\n};\n\ntemplate<> struct Libshit::Lua::TypeTraits<Neptools::Item::Key>\n{\n // HACK\n // Dummy function, needed by LuaGetRef to get above maker to work when\n // using binding generator. It's undefined on purpose.\n template <bool> static void Get(Lua::StateRef, bool, int);\n};\n#endif\n\n#endif\n" }, { "alpha_fraction": 0.6070175170898438, "alphanum_fraction": 0.6736842393875122, "avg_line_length": 17.387096405029297, "blob_id": "f1b0d132327f37a6ca715e18d92e90d2f3cbdc5f", "content_id": "b6b0c4b7601b38b56a6d9b981ba54678e5836983", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 570, "license_type": "permissive", "max_line_length": 75, "num_lines": 31, "path": "/src/pattern.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_741BE2A9_1F86_4DD5_A032_0D7D5CCBA762\n#define UUID_741BE2A9_1F86_4DD5_A032_0D7D5CCBA762\n#pragma once\n\n#include \"utils.hpp\"\n\n#include <libshit/except.hpp>\n\n#include <string_view>\n\nnamespace Neptools\n{\n\n struct Pattern\n {\n const Byte* pattern;\n const Byte* mask;\n size_t size;\n\n const Byte* MaybeFind(std::string_view data) const noexcept;\n\n const Byte* Find(std::string_view data) const\n {\n auto ret = MaybeFind(data);\n if (!ret) LIBSHIT_THROW(std::runtime_error, \"Couldn't find pattern\");\n return ret;\n }\n };\n\n}\n#endif\n" }, { "alpha_fraction": 0.6110715270042419, "alphanum_fraction": 0.6180565357208252, "avg_line_length": 27.98760414123535, "blob_id": "912c49c6cb2b036597d5a41b286b2e2a24329b6c", "content_id": "530e45877d6226f71a28568225a4bd941552e47c", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 21045, "license_type": "permissive", "max_line_length": 82, "num_lines": 726, "path": "/src/format/stsc/instruction.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"instruction.hpp\"\n\n#include \"../cstring_item.hpp\"\n#include \"../raw_item.hpp\"\n#include \"../../sink.hpp\"\n\n#include <libshit/lua/static_class.hpp>\n#include <libshit/lua/user_type.hpp>\n#include <iomanip>\n\n#include <brigand/sequences/list.hpp>\n#include <brigand/algorithms/transform.hpp>\n#include <brigand/sequences/make_sequence.hpp>\n#include <brigand/algorithms/flatten.hpp>\n\nnamespace Neptools::Stsc\n{\n\n // helpers for generic CreateAndInsert\n namespace\n {\n using CreateType = Libshit::NotNull<Libshit::SmartPtr<InstructionBase>>\n (*)(Context&, const Source&);\n\n template <Flavor F, uint8_t I>\n Libshit::NotNull<Libshit::SmartPtr<InstructionBase>>\n CreateAdapt(Context& ctx, const Source& src)\n { return ctx.Create<InstructionItem<F, I>>(I, src); }\n\n\n#define NEPTOOLS_GEN(x,y) , Flavor::x\n using Flavors = brigand::integral_list<\n Flavor NEPTOOLS_GEN_STSC_FLAVOR(NEPTOOLS_GEN,)>;\n#undef NEPTOOLS_GEN\n\n template <typename F>\n using MakeMap = brigand::transform<\n brigand::make_sequence<brigand::uint32_t<0>, 256>,\n brigand::bind<brigand::pair, F, brigand::_1>>;\n using AllOpcodes = brigand::flatten<\n brigand::transform<Flavors, brigand::bind<MakeMap, brigand::_1>>>;\n\n template <typename List> struct CreateMapImpl;\n template <typename... X>\n struct CreateMapImpl<brigand::list<X...>>\n {\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wmissing-braces\"\n static inline const constexpr CreateType\n MAP[brigand::size<Flavors>::value][256] =\n { CreateAdapt<X::first_type::value, X::second_type::value>... };\n#pragma GCC diagnostic pop\n };\n\n using CreateMap = CreateMapImpl<AllOpcodes>;\n }\n\n // base\n InstructionBase& InstructionBase::CreateAndInsert(ItemPointer ptr, Flavor f)\n {\n auto x = RawItem::GetSource(ptr, -1);\n x.src.CheckSize(1);\n uint8_t opcode = x.src.ReadLittleUint8();\n auto ctx = x.ritem.GetContext();\n auto& ret = x.ritem.Split(\n ptr.offset, CreateMap::MAP[static_cast<size_t>(f)][opcode](*ctx, x.src));\n\n ret.PostInsert(f);\n return ret;\n }\n\n void InstructionBase::InstrDump(Sink& sink) const\n {\n sink.WriteLittleUint8(opcode);\n }\n\n std::ostream& InstructionBase::InstrInspect(\n std::ostream& os, unsigned indent) const\n {\n Item::Inspect_(os, indent);\n auto flags = os.flags();\n os << \"instruction(0x\" << std::setw(2) << std::setfill('0') << std::hex\n << unsigned(opcode);\n os.flags(flags);\n return os;\n }\n\n\n // generic implementation\n namespace\n {\n\n template <typename... Args> struct PODTuple;\n\n template <typename Head, typename... Args>\n struct PODTuple<Head, Args...>\n {\n Head head;\n PODTuple<Args...> tail;\n };\n\n template <typename T> struct PODTuple<T> { T head; };\n template<> struct PODTuple<> {};\n\n template <size_t I> struct PODTupleGet\n {\n template <typename T> static auto& Get(T& tuple)\n { return PODTupleGet<I-1>::Get(tuple.tail); }\n };\n template<> struct PODTupleGet<0>\n {\n template <typename T> static auto& Get(T& tuple)\n { return tuple.head; }\n };\n\n template <size_t I, typename T> inline auto& Get(T& tuple)\n { return PODTupleGet<I>::Get(tuple); }\n\n\n template <typename T> struct EndianMap;\n template<> struct EndianMap<uint8_t>\n { using Type = boost::endian::little_uint8_t; };\n template<> struct EndianMap<uint16_t>\n { using Type = boost::endian::little_uint16_t; };\n template<> struct EndianMap<uint32_t>\n { using Type = boost::endian::little_uint32_t; };\n\n template <typename T> using ToVoid = void;\n\n\n template <typename T, typename Enable = void> struct Traits;\n\n template <typename T>\n struct Traits<T, ToVoid<typename EndianMap<T>::Type>>\n {\n using RawType = typename EndianMap<T>::Type;\n static constexpr const size_t SIZE = sizeof(T);\n\n static void Validate(RawType, FilePosition) {}\n static T Parse(RawType r, Context&) { return r; }\n static RawType Dump(T r) { return r; }\n static void Inspect(std::ostream& os, T t) { os << uint32_t(t); }\n static void PostInsert(T, Flavor) {}\n };\n\n template<> struct Traits<float>\n {\n using RawType = boost::endian::little_uint32_t;\n static constexpr const size_t SIZE = 4;\n\n static void Validate(RawType, FilePosition) {}\n static float Parse(RawType r, Context&)\n {\n uint32_t num = r;\n float ret;\n memcpy(&ret, &num, sizeof(ret));\n return ret;\n }\n\n static RawType Dump(float f)\n {\n uint32_t ret;\n memcpy(&ret, &f, sizeof(ret));\n return ret;\n }\n\n static void Inspect(std::ostream& os, float v) { os << v; }\n static void PostInsert(float, Flavor) {}\n };\n\n template<> struct Traits<void*>\n {\n using RawType = boost::endian::little_uint32_t;\n static constexpr const size_t SIZE = 4;\n\n static void Validate(uint32_t r, FilePosition size)\n { LIBSHIT_VALIDATE_FIELD(\"Stsc::Instruction\", r <= size); }\n\n static LabelPtr Parse(uint32_t r, Context& ctx)\n { return r ? ctx.GetLabelTo(r) : LabelPtr{}; }\n\n static RawType Dump(const LabelPtr& l)\n { return l ? ToFilePos(l->GetPtr()) : 0; }\n\n static void Inspect(std::ostream& os, const LabelPtr& l)\n { os << PrintLabel(l); }\n\n static void PostInsert(const LabelPtr&, Flavor) {}\n };\n\n template<> struct Traits<std::string> : public Traits<void*>\n {\n static LabelPtr Parse(uint32_t r, Context& ctx)\n {\n if (!r) return {};\n if (auto ptr = ctx.GetPointer(r); ptr.Maybe<RawItem>())\n {\n auto x = RawItem::GetSource(ptr, -1);\n return ctx.GetLabelTo(\n r, CStringItem::GetLabelName(x.src.PreadCString(0)));\n }\n else\n return ctx.GetLabelTo(r);\n }\n\n static void PostInsert(const LabelPtr& lbl, Flavor)\n { if (lbl) MaybeCreate<CStringItem>(lbl->GetPtr()); }\n };\n\n template<> struct Traits<Code*> : public Traits<void*>\n {\n static void PostInsert(const LabelPtr& lbl, Flavor f)\n { if (lbl) MaybeCreateUnchecked<InstructionBase>(lbl->GetPtr(), f); }\n };\n\n template <typename T, typename... Args> struct OperationsImpl;\n template <typename... T, size_t... I>\n struct OperationsImpl<std::index_sequence<I...>, T...>\n {\n#define FORALL(...) ((__VA_ARGS__), ...)\n\n template <typename Tuple>\n static void Validate(const Tuple& tuple, FilePosition size)\n {\n (void) size; // shut up, retarded gcc\n FORALL(Traits<T>::Validate(Get<I>(tuple), size));\n }\n\n template <typename Dst, typename Src>\n static void Parse(Dst& dst, const Src& src, Context& ctx)\n {\n (void) ctx; // shut up, retarded gcc\n FORALL(std::get<I>(dst) = Traits<T>::Parse(Get<I>(src), ctx));\n }\n\n template <typename Dst, typename Src>\n static void Dump(Dst& dst, const Src& src)\n { FORALL(Get<I>(dst) = Traits<T>::Dump(std::get<I>(src))); }\n\n template <typename Tuple>\n static void Inspect(std::ostream& os, const Tuple& tuple)\n {\n FORALL(\n os << \", \",\n Traits<T>::Inspect(os, std::get<I>(tuple)));\n }\n\n template <typename Tuple>\n static void PostInsert(const Tuple& tuple, Flavor f)\n {\n (void) f; // shut up, retarded gcc\n FORALL(Traits<T>::PostInsert(std::get<I>(tuple), f));\n }\n\n static constexpr size_t Size()\n {\n size_t sum = 0;\n FORALL(sum += Traits<T>::SIZE);\n return sum;\n }\n#undef FORALL\n };\n\n template <typename... Args>\n using Operations = OperationsImpl<std::index_sequence_for<Args...>, Args...>;\n\n }\n\n template <bool NoReturn, typename... Args>\n const FilePosition SimpleInstruction<NoReturn, Args...>::SIZE =\n Operations<Args...>::Size() + 1;\n\n template <bool NoReturn, typename... Args>\n SimpleInstruction<NoReturn, Args...>::SimpleInstruction(\n Key k, Context& ctx, uint8_t opcode, Source src)\n : InstructionBase{k, ctx, opcode}\n {\n ADD_SOURCE(Parse_(ctx, src), src);\n }\n\n template <bool NoReturn, typename... Args>\n void SimpleInstruction<NoReturn, Args...>::Parse_(Context& ctx, Source& src)\n {\n src.CheckSize(SIZE);\n using Tuple = PODTuple<typename Traits<Args>::RawType...>;\n static_assert(std::is_pod_v<Tuple>);\n static_assert(Libshit::EmptySizeof<Tuple> == Operations<Args...>::Size());\n\n auto raw = src.ReadGen<Tuple>();\n\n Operations<Args...>::Validate(raw, ctx.GetSize());\n Operations<Args...>::Parse(args, raw, ctx);\n }\n\n template <bool NoReturn, typename... Args>\n void SimpleInstruction<NoReturn, Args...>::Dump_(Sink& sink) const\n {\n InstrDump(sink);\n\n using Tuple = PODTuple<typename Traits<Args>::RawType...>;\n Tuple t;\n Operations<Args...>::Dump(t, args);\n sink.WriteGen(t);\n }\n\n template <bool NoReturn, typename... Args>\n void SimpleInstruction<NoReturn, Args...>::Inspect_(\n std::ostream& os, unsigned indent) const\n {\n InstrInspect(os, indent);\n Operations<Args...>::Inspect(os, args);\n os << ')';\n }\n\n template <bool NoReturn, typename... Args>\n void SimpleInstruction<NoReturn, Args...>::PostInsert(Flavor f)\n {\n Operations<Args...>::PostInsert(args, f);\n if (!NoReturn) MaybeCreateUnchecked<InstructionBase>(&*++Iterator(), f);\n }\n\n // ------------------------------------------------------------------------\n // specific instruction implementations\n InstructionRndJumpItem::InstructionRndJumpItem(\n Key k, Context& ctx, uint8_t opcode, Source src)\n : InstructionBase{k, ctx, opcode}\n {\n ADD_SOURCE(Parse_(ctx, src), src);\n }\n\n void InstructionRndJumpItem::Parse_(Context& ctx, Source& src)\n {\n src.CheckRemainingSize(1);\n uint8_t n = src.ReadLittleUint8();\n src.CheckRemainingSize(4*n);\n\n tgts.reserve(n);\n\n for (size_t i = 0; i < n; ++i)\n {\n uint32_t t = src.ReadLittleUint32();\n LIBSHIT_VALIDATE_FIELD(\n \"Stsc::InstructionRndJumpItem\", t < ctx.GetSize());\n tgts.push_back(ctx.GetLabelTo(t));\n }\n }\n\n void InstructionRndJumpItem::Dump_(Sink& sink) const\n {\n InstrDump(sink);\n sink.WriteLittleUint8(tgts.size());\n for (const auto& l : tgts)\n sink.WriteLittleUint32(ToFilePos(l->GetPtr()));\n }\n\n void InstructionRndJumpItem::Inspect_(std::ostream& os, unsigned indent) const\n {\n InstrInspect(os, indent);\n bool first = true;\n for (const auto& l : tgts)\n {\n if (!first) os << \", \";\n first = false;\n os << PrintLabel(l);\n }\n os << ')';\n }\n\n void InstructionRndJumpItem::PostInsert(Flavor f)\n {\n for (const auto& l : tgts)\n MaybeCreateUnchecked<InstructionBase>(l->GetPtr(), f);\n MaybeCreateUnchecked<InstructionBase>(&*++Iterator(), f);\n }\n\n // ------------------------------------------------------------------------\n\n void InstructionJumpIfItem::FixParams::Validate(\n FilePosition rem_size, FilePosition size)\n {\n#define VALIDATE(x) \\\n LIBSHIT_VALIDATE_FIELD(\"Stsc::InstructionJumpIfItem::FixParams\", x)\n VALIDATE(this->size * sizeof(NodeParams) <= rem_size);\n VALIDATE(tgt < size);\n#undef VALIDATE\n }\n\n void InstructionJumpIfItem::NodeParams::Validate(uint16_t size)\n {\n#define VALIDATE(x) \\\n LIBSHIT_VALIDATE_FIELD(\"Stsc::InstructionJumpIfItem::NodeParams\", x)\n VALIDATE(left <= size);\n VALIDATE(right <= size);\n#undef VALIDATE\n }\n\n InstructionJumpIfItem::InstructionJumpIfItem(\n Key k, Context& ctx, uint8_t opcode, Source src)\n : InstructionBase{k, ctx, opcode}, tgt{Libshit::EmptyNotNull{}}\n {\n ADD_SOURCE(Parse_(ctx, src), src);\n }\n\n#if LIBSHIT_WITH_LUA\n static size_t ParseTree(\n Libshit::Lua::StateRef vm, std::vector<InstructionJumpIfItem::Node>& tree,\n Libshit::Lua::Any lua_tree, int type)\n {\n if (type == LUA_TNIL) return 0;\n\n lua_checkstack(vm, 5);\n\n auto i = tree.size();\n tree.emplace_back();\n\n lua_rawgeti(vm, lua_tree, 1); // +1\n tree[i].operation = vm.Check<uint8_t>(-1);\n lua_rawgeti(vm, lua_tree, 2); // +2\n tree[i].value = vm.Check<uint32_t>(-1);\n lua_pop(vm, 2); // 0\n\n type = lua_rawgeti(vm, lua_tree, 3); // +1\n tree[i].left = ParseTree(vm, tree, lua_gettop(vm), type);\n lua_pop(vm, 1); // 0\n\n type = lua_rawgeti(vm, lua_tree, 4); // +1\n tree[i].right = ParseTree(vm, tree, lua_gettop(vm), type);\n lua_pop(vm, 1); // 0\n return i+1;\n }\n\n InstructionJumpIfItem::InstructionJumpIfItem(\n Key k, Context& ctx, Libshit::Lua::StateRef vm, uint8_t opcode,\n Libshit::NotNull<LabelPtr> tgt, Libshit::Lua::RawTable lua_tree)\n : InstructionBase{k, ctx, opcode}, tgt{tgt}\n { ParseTree(vm, tree, lua_tree, LUA_TTABLE); }\n#endif\n\n void InstructionJumpIfItem::Dispose() noexcept\n {\n tree.clear();\n InstructionBase::Dispose();\n }\n\n void InstructionJumpIfItem::Parse_(Context& ctx, Source& src)\n {\n src.CheckRemainingSize(sizeof(FixParams));\n auto fp = src.ReadGen<FixParams>();\n fp.Validate(src.GetRemainingSize(), ctx.GetSize());\n tgt = ctx.GetLabelTo(fp.tgt);\n\n uint16_t n = fp.size;\n src.CheckRemainingSize(n * sizeof(NodeParams));\n tree.reserve(n);\n for (uint16_t i = 0; i < n; ++i)\n {\n auto nd = src.ReadGen<NodeParams>();\n nd.Validate(n);\n tree.push_back({nd.operation, nd.value, nd.left, nd.right});\n }\n }\n\n void InstructionJumpIfItem::Dump_(Sink& sink) const\n {\n InstrDump(sink);\n sink.WriteGen(FixParams{tree.size(), ToFilePos(tgt->GetPtr())});\n for (auto& n : tree)\n sink.WriteGen(NodeParams{n.operation, n.value, n.left, n.right});\n }\n\n void InstructionJumpIfItem::Inspect_(std::ostream& os, unsigned indent) const\n {\n InstrInspect(os, indent) << \", \" << PrintLabel(tgt) << \", \";\n InspectNode(os, 0);\n os << ')';\n }\n\n void InstructionJumpIfItem::InspectNode(std::ostream& os, size_t i) const\n {\n if (i >= tree.size())\n {\n os << \"nil\";\n return;\n }\n\n auto& n = tree[i];\n os << '{' << unsigned(n.operation) << \", \" << n.value << \", \";\n InspectNode(os, n.left - 1);\n os << \", \";\n InspectNode(os, n.right - 1);\n os << '}';\n }\n\n void InstructionJumpIfItem::PostInsert(Flavor f)\n {\n MaybeCreateUnchecked<InstructionBase>(tgt->GetPtr(), f);\n MaybeCreateUnchecked<InstructionBase>(&*++Iterator(), f);\n }\n\n // ------------------------------------------------------------------------\n\n void InstructionJumpSwitchItemNoire::FixParams::Validate(FilePosition rem_size)\n {\n LIBSHIT_VALIDATE_FIELD(\"Stsc::InstructionJumpSwitchItemNoire::FixParams\",\n size * sizeof(ExpressionParams) <= rem_size);\n }\n\n void InstructionJumpSwitchItemNoire::ExpressionParams::Validate(\n FilePosition size)\n {\n LIBSHIT_VALIDATE_FIELD(\n \"Stsc::InstructionJumpSwitchItemNoire::ExpressionParams\", tgt < size);\n }\n\n InstructionJumpSwitchItemNoire::InstructionJumpSwitchItemNoire(\n Key k, Context& ctx, uint8_t opcode, Source src)\n : InstructionBase{k, ctx, opcode}\n {\n ADD_SOURCE(Parse_(ctx, src), src);\n }\n\n InstructionJumpSwitchItemPotbb::InstructionJumpSwitchItemPotbb(\n Key k, Context& ctx, uint8_t opcode, Source src)\n : InstructionJumpSwitchItemNoire{k, ctx, opcode}\n {\n ADD_SOURCE(Parse_(ctx, src), src);\n }\n\n void InstructionJumpSwitchItemNoire::Dispose() noexcept\n {\n expressions.clear();\n InstructionBase::Dispose();\n }\n\n void InstructionJumpSwitchItemNoire::Parse_(Context& ctx, Source& src)\n {\n src.CheckRemainingSize(sizeof(FixParams));\n auto fp = src.ReadGen<FixParams>();\n fp.Validate(src.GetRemainingSize());\n\n expected_val = fp.expected_val;\n last_is_default = fp.size & 0x8000;\n auto size = last_is_default ? fp.size & 0x7ff : uint16_t(fp.size);\n\n expressions.reserve(size);\n for (uint16_t i = 0; i < size; ++i)\n {\n auto exp = src.ReadGen<ExpressionParams>();\n exp.Validate(ctx.GetSize());\n expressions.emplace_back(\n exp.expression, ctx.GetLabelTo(exp.tgt));\n }\n }\n\n void InstructionJumpSwitchItemPotbb::Parse_(Context& ctx, Source& src)\n {\n InstructionJumpSwitchItemNoire::Parse_(ctx, src);\n src.CheckRemainingSize(1);\n trailing_byte = src.ReadLittleUint8();\n }\n\n void InstructionJumpSwitchItemNoire::Dump_(Sink& sink) const\n {\n InstrDump(sink);\n sink.WriteGen(FixParams{expected_val,\n (last_is_default << 15) | expressions.size()});\n for (auto& e : expressions)\n sink.WriteGen(ExpressionParams{\n e.expression, ToFilePos(e.target->GetPtr())});\n }\n\n void InstructionJumpSwitchItemPotbb::Dump_(Sink& sink) const\n {\n InstructionJumpSwitchItemNoire::Dump_(sink);\n sink.WriteLittleUint8(trailing_byte);\n }\n\n void InstructionJumpSwitchItemNoire::InspectBase(\n std::ostream& os, unsigned indent) const\n {\n InstrInspect(os, indent) << \", \" << expected_val << \", \"\n << last_is_default << \", {\";\n bool first = true;\n for (auto& e : expressions)\n {\n if (!first) os << \", \";\n first = false;\n os << '{' << e.expression << \", \" << PrintLabel(e.target) << '}';\n }\n os << '}';\n }\n\n void InstructionJumpSwitchItemNoire::Inspect_(\n std::ostream& os, unsigned indent) const\n {\n InspectBase(os, indent);\n os << ')';\n }\n\n void InstructionJumpSwitchItemPotbb::Inspect_(\n std::ostream& os, unsigned indent) const\n {\n InspectBase(os, indent);\n os << \", \" << int(trailing_byte) << ')';\n }\n\n void InstructionJumpSwitchItemNoire::PostInsert(Flavor f)\n {\n for (const auto& e : expressions)\n MaybeCreate<InstructionBase>(e.target->GetPtr(), f);\n if (!last_is_default)\n MaybeCreateUnchecked<InstructionBase>(&*++Iterator(), f);\n }\n\n}\n\n#if LIBSHIT_WITH_LUA\nnamespace Libshit::Lua\n{\n\n template <bool NoReturn, typename... Args>\n struct TypeRegisterTraits<Neptools::Stsc::SimpleInstruction<NoReturn, Args...>>\n {\n using T = Neptools::Stsc::SimpleInstruction<NoReturn, Args...>;\n\n template <size_t I>\n static RetNum Get0(StateRef vm, T& instr, int idx)\n {\n if constexpr (I == sizeof...(Args))\n lua_pushnil(vm);\n else if (idx == I)\n vm.Push(std::get<I>(instr.args));\n else\n return Get0<I+1>(vm, instr, idx);\n return 1;\n }\n static void Get1(const T&, Libshit::Lua::VarArg) noexcept {}\n\n\n template <size_t I>\n static void Set(StateRef vm, T& instr, int idx, Skip val)\n {\n (void) val;\n if constexpr (I == sizeof...(Args))\n luaL_error(vm, \"trying to set invalid index\");\n else if (idx == I)\n std::get<I>(instr.args) = vm.Check<std::tuple_element_t<\n I, typename T::ArgsT>>(3);\n else\n Set<I+1>(vm, instr, idx, {});\n }\n\n static void Register(TypeBuilder& bld)\n {\n bld.Inherit<T, Neptools::Stsc::InstructionBase>();\n\n // that tuple constructors can blow up exponentially, disable overload\n // check (tuple constructors can't take source, so it should be ok)\n bld.AddFunction<\n TypeTraits<T>::template Make<\n Neptools::Context::Key, Neptools::Context&, uint8_t, Neptools::Source&>,\n TypeTraits<T>::template Make<\n Neptools::Context::Key, Neptools::Context&, uint8_t,\n LuaGetRef<Neptools::Stsc::TupleTypeMapT<Args>>...>\n >(\"new\");\n\n bld.AddFunction<&Get0<0>, &Get1>(\"get\");\n bld.AddFunction<&Set<0>>(\"set\");\n }\n };\n\n namespace\n {\n struct LIBSHIT_NOLUA InstructionItem : StaticClass\n {\n constexpr static char TYPE_NAME[] = \"neptools.stsc.instruction_item\";\n };\n constexpr char InstructionItem::TYPE_NAME[];\n\n template <typename T> struct InstructionReg;\n template <typename... X> struct InstructionReg<brigand::list<X...>>\n {\n static void GetTab(Lua::StateRef vm, int i, int& prev)\n {\n if (i == prev) return;\n if (prev != -1) lua_pop(vm, 1);\n prev = i;\n lua_createtable(vm, 255, 0);\n lua_pushvalue(vm, -1);\n lua_rawseti(vm, -4, i);\n }\n\n static void Register(TypeBuilder& bld)\n {\n static_assert(sizeof...(X) > 0);\n auto vm = bld.GetVm();\n int prev = -1;\n ((GetTab(vm, static_cast<int>(X::first_type::value), prev),\n TypeRegister::Register<Neptools::Stsc::InstructionItem<\n X::first_type::value, X::second_type::value>>(vm),\n lua_rawseti(vm, -2, X::second_type::value)), ...);\n lua_pop(vm, 1);\n }\n };\n\n }\n\n template<> struct TypeRegisterTraits<InstructionItem>\n : InstructionReg<Neptools::Stsc::AllOpcodes> {};\n\n static TypeRegister::StateRegister<InstructionItem> reg;\n\n}\n\n#include <libshit/container/vector.lua.hpp>\nLIBSHIT_STD_VECTOR_LUAGEN(\n label, Libshit::NotNull<Neptools::LabelPtr>);\nLIBSHIT_STD_VECTOR_LUAGEN(\n stsc_instruction_jump_if_item_node,\n Neptools::Stsc::InstructionJumpIfItem::Node);\nLIBSHIT_STD_VECTOR_LUAGEN(\n stsc_instruction_jump_switch_item_noire_expression,\n Neptools::Stsc::InstructionJumpSwitchItemNoire::Expression);\n#include \"instruction.binding.hpp\"\n\n#endif\n" }, { "alpha_fraction": 0.6230645775794983, "alphanum_fraction": 0.6268019080162048, "avg_line_length": 21.566265106201172, "blob_id": "028323f1c4298892c0f3085c3e9689ef92b882d6", "content_id": "63238076a4d7715657e3357d48d3c9e767498a0c", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1873, "license_type": "permissive", "max_line_length": 79, "num_lines": 83, "path": "/src/format/stcm/data.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"data.hpp\"\n#include \"../context.hpp\"\n#include \"../raw_item.hpp\"\n#include \"../../sink.hpp\"\n#include <iostream>\n\nnamespace Neptools::Stcm\n{\n\n void DataItem::Header::Validate(FilePosition chunk_size) const\n {\n#define VALIDATE(x) LIBSHIT_VALIDATE_FIELD(\"Stcm::DataItem::Header\", x)\n VALIDATE(type < 0xff);\n VALIDATE(length <= chunk_size);\n#undef VALIDATE\n }\n\n DataItem::DataItem(Key k, Context& ctx, const Header& raw, size_t chunk_size)\n : ItemWithChildren{k, ctx}\n {\n raw.Validate(chunk_size);\n\n type = raw.type;\n offset_unit = raw.offset_unit;\n field_8 = raw.field_8;\n }\n\n DataItem& DataItem::CreateAndInsert(ItemPointer ptr)\n {\n auto x = RawItem::Get<Header>(ptr);\n\n auto& ret = x.ritem.SplitCreate<DataItem>(\n ptr.offset, x.t, x.ritem.GetSize() - ptr.offset - sizeof(Header));\n if (x.t.length > 0)\n ret.MoveNextToChild(x.t.length);\n\n LIBSHIT_ASSERT(ret.GetSize() == sizeof(Header) + x.t.length);\n\n // check heuristics\n if (!ret.GetChildren().empty())\n DataFactory::Check(ret);\n\n return ret;\n }\n\n void DataItem::Dump_(Sink& sink) const\n {\n Header hdr;\n hdr.type = type;\n hdr.offset_unit = offset_unit;\n hdr.field_8 = field_8;\n hdr.length = GetSize() - sizeof(Header);\n sink.WriteGen(hdr);\n\n ItemWithChildren::Dump_(sink);\n }\n\n void DataItem::Inspect_(std::ostream& os, unsigned indent) const\n {\n Item::Inspect_(os, indent);\n os << \"data(\" << type << \", \" << offset_unit << \", \" << field_8 << ')';\n InspectChildren(os, indent);\n }\n\n FilePosition DataItem::GetSize() const noexcept\n {\n return ItemWithChildren::GetSize() + sizeof(Header);\n }\n\n void DataItem::Fixup()\n {\n ItemWithChildren::Fixup_(sizeof(Header));\n }\n\n void DataFactory::Check(DataItem& it)\n {\n for (auto f : GetStore())\n if (f(it)) return;\n }\n\n}\n\n#include \"data.binding.hpp\"\n" }, { "alpha_fraction": 0.661611795425415, "alphanum_fraction": 0.6655112504959106, "avg_line_length": 25.837209701538086, "blob_id": "5d031547af4a2dce87ed8ac27f85e2b746c19fd3", "content_id": "ef57c98268e7bcdee8a38190d01683d229f01f1e", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 2308, "license_type": "permissive", "max_line_length": 90, "num_lines": 86, "path": "/src/format/builder.lua", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "local setfenv, setmetatable, typename, match, gsub, format, ipairs, error =\n setfenv, setmetatable, typename, string.match, string.gsub, string.format, ipairs, error\nassert(setfenv, \"no setfenv\") -- will fail on plain lua 5.2+\n\nlocal get_ctx = neptools.item.get_context\nlocal get_children = neptools.item_with_children.get_children\n\nlocal helpers = {}\n-- lazy load table\n-- When this script runs, only items and item_with_children is registered.\n-- We would need to run this script at the very end of registration phase, but\n-- that would fuck up inheritance...\nlocal function gen_helpers(tbl, ns)\n for k,v in pairs(ns) do\n if match(k, \"_item$\") then\n tbl[gsub(k, \"_item$\", \"\")] = v.new\n end\n end\nend\n\nlocal function get_helpers(typename)\n local tbl = helpers[typename]\n if tbl then return tbl end\n\n tbl = {}\n gen_helpers(tbl, neptools)\n if typename == \"neptools.stcm.file\" then\n gen_helpers(tbl, neptools.stcm)\n tbl.call = tbl.instruction -- alias\n elseif typename == \"neptools.stsc.file\" then\n gen_helpers(tbl, neptools.stsc)\n function tbl.instruction(ctx, opcode, ...)\n return neptools.stsc.instruction_item[ctx.flavor][opcode].\n new(ctx, opcode, ...)\n end\n else\n error(\"unknown type \"..typename)\n end\n\n helpers[typename] = tbl\n return tbl\nend\n\nlocal function build(item, fun)\n local get_label = neptools.context.get_or_create_dummy_label\n local create_label = neptools.context.create_or_set_label\n\n local ctx = get_ctx(item)\n local children = get_children(item)\n local labels = {}\n local function defer_label(name, offs)\n labels[#labels+1] = { name, offs or 0 }\n end\n\n local function add(item)\n children:push_back(item)\n for i,v in ipairs(labels) do\n create_label(ctx, v[1], item, v[2])\n labels[i] = nil\n end\n return item\n end\n\n local tbl = {\n label = defer_label,\n l = function(n) return get_label(ctx, n) end,\n add = add,\n __index = _G,\n __newindex = error,\n }\n\n -- helpers\n for k,v in pairs(get_helpers(typename(ctx))) do\n tbl[k] = function(...) return add(v(ctx, ...)) end\n end\n\n setfenv(fun, setmetatable(tbl, tbl))\n fun()\n if labels[1] then\n error(format(\"label %q after last item\", labels[1][1]))\n end\n if ctx == item then ctx:fixup() end -- todo\n return ctx\nend\n\nreturn build\n" }, { "alpha_fraction": 0.5208596587181091, "alphanum_fraction": 0.5587073564529419, "avg_line_length": 24.312000274658203, "blob_id": "e9aa64e0616143feb679040815be728ffd9da251", "content_id": "34589905a2e21d4e3ae13f8b2056c58612436e58", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12656, "license_type": "permissive", "max_line_length": 82, "num_lines": 500, "path": "/src/sink.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"sink.hpp\"\n\n#include <libshit/except.hpp>\n#include <libshit/low_io.hpp>\n#include <libshit/lua/boost_endian_traits.hpp>\n\n#include <iostream>\n#include <fstream>\n\n#include <libshit/doctest.hpp>\n\n#define LIBSHIT_LOG_NAME \"sink\"\n#include <libshit/logger_helper.hpp>\n\nnamespace Neptools\n{\n TEST_SUITE_BEGIN(\"Neptools::Sink\");\n\n namespace\n {\n struct LIBSHIT_NOLUA MmapSink final : public Sink\n {\n MmapSink(Libshit::LowIo&& io, FilePosition size);\n void Write_(std::string_view data) override;\n void Pad_(FileMemSize len) override;\n\n void MapNext(FileMemSize len);\n\n Libshit::LowIo io;\n Libshit::LowIo::MmapPtr mm;\n };\n\n struct LIBSHIT_NOLUA SimpleSink final : public Sink\n {\n SimpleSink(Libshit::LowIo io, FilePosition size)\n : Sink{size}, io{Libshit::Move(io)}\n {\n Sink::buf = buf;\n buf_size = MEM_CHUNK;\n }\n ~SimpleSink() override;\n\n void Write_(std::string_view data) override;\n void Pad_(FileMemSize len) override;\n void Flush() override;\n\n Libshit::LowIo io;\n Byte buf[MEM_CHUNK];\n };\n }\n\n MmapSink::MmapSink(Libshit::LowIo&& io, FilePosition size) : Sink{size}\n {\n size_t to_map = size < MMAP_LIMIT ? size : MMAP_CHUNK;\n\n io.Truncate(size);\n io.PrepareMmap(true);\n mm = io.Mmap(0, to_map, true);\n buf_size = to_map;\n buf = reinterpret_cast<Neptools::Byte*>(mm.Get());\n\n this->io = Libshit::Move(io);\n }\n\n void MmapSink::Write_(std::string_view data)\n {\n LIBSHIT_ASSERT(buf_put == buf_size && offset < size &&\n buf_size == MMAP_CHUNK);\n\n offset += buf_put;\n if (data.length() / MMAP_CHUNK)\n {\n auto to_write = data.length() / MMAP_CHUNK * MMAP_CHUNK;\n io.Pwrite(data.data(), to_write, offset);\n data.remove_prefix(to_write);\n offset += to_write;\n buf_put = 0;\n }\n\n MapNext(data.length());\n if (buf) // https://stackoverflow.com/a/5243068; C99 7.21.1/2\n memcpy(buf, data.data(), data.length());\n else\n LIBSHIT_ASSERT(data.length() == 0);\n }\n\n void MmapSink::Pad_(FileMemSize len)\n {\n LIBSHIT_ASSERT(buf_put == buf_size && offset < size &&\n buf_size == MMAP_CHUNK);\n\n offset += buf_put + len / MMAP_CHUNK * MMAP_CHUNK;\n LIBSHIT_ASSERT_MSG(offset <= size, \"sink overflow\");\n MapNext(len % MMAP_CHUNK);\n }\n\n void MmapSink::MapNext(FileMemSize len)\n {\n // wine fails on 0 size\n // windows fails if offset+size > file_length...\n // (linux doesn't care...)\n if (offset < size)\n {\n auto nbuf_size = std::min<FileMemSize>(MMAP_CHUNK, size-offset);\n LIBSHIT_ASSERT(nbuf_size >= len);\n mm = io.Mmap(offset, nbuf_size, true);\n buf = static_cast<Byte*>(mm.Get());\n buf_put = len;\n buf_size = nbuf_size;\n }\n else\n {\n mm.Reset();\n buf = nullptr;\n }\n }\n\n SimpleSink::~SimpleSink()\n {\n try { Flush(); }\n catch (std::exception& e)\n {\n ERR << \"~SimpleSink \"\n << Libshit::PrintException(Libshit::Logger::HasAnsiColor())\n << std::endl;\n }\n }\n\n void SimpleSink::Flush()\n {\n if (buf_put)\n {\n io.Write(buf, buf_put);\n offset += buf_put;\n buf_put = 0;\n }\n }\n\n void SimpleSink::Write_(std::string_view data)\n {\n LIBSHIT_ASSERT(buf_size == MEM_CHUNK && buf_put == MEM_CHUNK);\n io.Write(buf, MEM_CHUNK);\n offset += MEM_CHUNK;\n\n if (data.length() >= MEM_CHUNK)\n {\n io.Write(data.data(), data.length());\n offset += data.length();\n buf_put = 0;\n }\n else\n {\n memcpy(buf, data.data(), data.length());\n buf_put = data.length();\n }\n }\n\n void SimpleSink::Pad_(FileMemSize len)\n {\n LIBSHIT_ASSERT(buf_size == MEM_CHUNK && buf_put == MEM_CHUNK);\n io.Write(buf, MEM_CHUNK);\n offset += MEM_CHUNK;\n\n // assume we're not seekable (I don't care about not mmap-able but seekable\n // files)\n if (len >= MEM_CHUNK)\n {\n memset(buf, 0, MEM_CHUNK);\n size_t i;\n for (i = MEM_CHUNK; i < len; i += MEM_CHUNK)\n io.Write(buf, MEM_CHUNK);\n offset += i - MEM_CHUNK;\n }\n else\n memset(buf, 0, len);\n buf_put = len % MEM_CHUNK;\n }\n\n Libshit::NotNull<Libshit::RefCountedPtr<Sink>> Sink::ToFile(\n boost::filesystem::path fname, FilePosition size, bool try_mmap)\n {\n return Libshit::AddInfo(\n [&]() -> Libshit::NotNull<Libshit::RefCountedPtr<Sink>>\n {\n Libshit::LowIo io{fname.c_str(), Libshit::LowIo::Permission::READ_WRITE,\n Libshit::LowIo::Mode::TRUNC_OR_CREATE};\n if (LIBSHIT_OS_IS_VITA || !try_mmap)\n return Libshit::MakeRefCounted<SimpleSink>(Libshit::Move(io), size);\n\n try { return Libshit::MakeRefCounted<MmapSink>(Libshit::Move(io), size); }\n catch (const Libshit::SystemError& e)\n {\n WARN << \"Mmmap failed, falling back to normal writing: \"\n << Libshit::PrintException(Libshit::Logger::HasAnsiColor())\n << std::endl;\n return Libshit::MakeRefCounted<SimpleSink>(Libshit::Move(io), size);\n }\n },\n [&](auto& e) { Libshit::AddInfos(e, \"File name\", fname.string()); });\n }\n\n Libshit::NotNull<Libshit::RefCountedPtr<Sink>> Sink::ToStdOut()\n {\n return Libshit::MakeRefCounted<SimpleSink>(Libshit::LowIo::OpenStdOut(), -1);\n }\n\n#define TRY_MMAP \\\n bool try_mmap; \\\n SUBCASE(\"mmap\") { try_mmap = false; } \\\n SUBCASE(\"no mmap\") { try_mmap = true; } \\\n CAPTURE(try_mmap)\n\n TEST_CASE(\"small simple write\")\n {\n TRY_MMAP;\n char buf[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};\n {\n auto sink = Sink::ToFile(\"tmp\", 16, try_mmap);\n REQUIRE(sink->Tell() == 0);\n sink->WriteGen(buf);\n REQUIRE(sink->Tell() == 16);\n }\n\n char buf2[16];\n std::ifstream is{\"tmp\", std::ios_base::binary};\n is.read(buf2, 16);\n REQUIRE(is.good());\n REQUIRE(memcmp(buf, buf2, 16) == 0);\n\n is.get();\n REQUIRE(is.eof());\n }\n\n TEST_CASE(\"many small writes\")\n {\n TRY_MMAP;\n int buf[6] = {0,77,-123,98,77,-1};\n static_assert(sizeof(buf) == 24);\n\n static constexpr FilePosition SIZE = 2*1024*1024 / 24 * 24;\n {\n auto sink = Sink::ToFile(\"tmp\", SIZE, try_mmap);\n for (FilePosition i = 0; i < SIZE; i += 24)\n {\n buf[0] = static_cast<int>(i / 24);\n sink->WriteGen(buf);\n }\n REQUIRE(sink->Tell() == SIZE);\n }\n\n std::unique_ptr<char[]> buf_exp{new char[SIZE]};\n for (FilePosition i = 0; i < SIZE; i += 24)\n {\n buf[0] = static_cast<int>(i / 24);\n memcpy(buf_exp.get()+i, buf, 24);\n }\n\n std::unique_ptr<char[]> buf_act{new char[SIZE]};\n std::ifstream is{\"tmp\", std::ios_base::binary};\n is.read(buf_act.get(), SIZE);\n REQUIRE(is.good());\n REQUIRE(memcmp(buf_exp.get(), buf_act.get(), SIZE) == 0);\n\n is.get();\n REQUIRE(is.eof());\n }\n\n TEST_CASE(\"big write\")\n {\n TRY_MMAP;\n static constexpr FilePosition SIZE = 2*1024*1024;\n std::unique_ptr<Byte[]> buf{new Byte[SIZE]};\n for (size_t i = 0; i < SIZE; ++i)\n buf[i] = i;\n\n {\n auto sink = Sink::ToFile(\"tmp\", SIZE, try_mmap);\n REQUIRE(sink->Tell() == 0);\n sink->Write({reinterpret_cast<char*>(buf.get()), SIZE});\n REQUIRE(sink->Tell() == SIZE);\n }\n\n std::unique_ptr<char[]> buf2{new char[SIZE]};\n std::ifstream is{\"tmp\", std::ios_base::binary};\n is.read(buf2.get(), SIZE);\n REQUIRE(is.good());\n REQUIRE(memcmp(buf.get(), buf2.get(), SIZE) == 0);\n\n is.get();\n REQUIRE(is.eof());\n }\n\n TEST_CASE(\"small pad\")\n {\n TRY_MMAP;\n char buf[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};\n {\n auto sink = Sink::ToFile(\"tmp\", 16*3, try_mmap);\n REQUIRE(sink->Tell() == 0);\n sink->WriteGen(buf);\n REQUIRE(sink->Tell() == 16);\n sink->Pad(16);\n REQUIRE(sink->Tell() == 2*16);\n sink->WriteGen(buf);\n REQUIRE(sink->Tell() == 3*16);\n }\n\n char buf2[16];\n std::ifstream is{\"tmp\", std::ios_base::binary};\n is.read(buf2, 16);\n REQUIRE(is.good());\n REQUIRE(memcmp(buf, buf2, 16) == 0);\n\n is.read(buf2, 16);\n REQUIRE(is.good());\n REQUIRE(std::count(buf2, buf2+16, 0) == 16);\n\n is.read(buf2, 16);\n REQUIRE(is.good());\n REQUIRE(memcmp(buf, buf2, 16) == 0);\n\n is.get();\n REQUIRE(is.eof());\n }\n\n TEST_CASE(\"many small pad\")\n {\n TRY_MMAP;\n char buf[10] = {4,5,6,7,8,9,10,11,12,13};\n static constexpr FilePosition SIZE = 2*1024*1024 / 24 * 24;\n {\n auto sink = Sink::ToFile(\"tmp\", SIZE, try_mmap);\n\n for (FilePosition i = 0; i < SIZE; i += 24)\n {\n sink->WriteGen(buf);\n sink->Pad(14);\n }\n REQUIRE(sink->Tell() == SIZE);\n }\n\n std::unique_ptr<char[]> buf_exp{new char[SIZE]};\n for (FilePosition i = 0; i < SIZE; i += 24)\n {\n memcpy(buf_exp.get()+i, buf, 10);\n memset(buf_exp.get()+i+10, 0, 14);\n }\n\n std::unique_ptr<char[]> buf_act{new char[SIZE]};\n std::ifstream is{\"tmp\", std::ios_base::binary};\n is.read(buf_act.get(), SIZE);\n REQUIRE(is.good());\n REQUIRE(memcmp(buf_exp.get(), buf_act.get(), SIZE) == 0);\n\n is.get();\n REQUIRE(is.eof());\n }\n\n TEST_CASE(\"large pad\")\n {\n TRY_MMAP;\n char buf[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};\n static constexpr FilePosition ZERO_SIZE = 2*1024*1024;\n {\n auto sink = Sink::ToFile(\"tmp\", 16*2 + ZERO_SIZE, try_mmap);\n REQUIRE(sink->Tell() == 0);\n sink->WriteGen(buf);\n REQUIRE(sink->Tell() == 16);\n sink->Pad(ZERO_SIZE);\n REQUIRE(sink->Tell() == 16+ZERO_SIZE);\n sink->WriteGen(buf);\n REQUIRE(sink->Tell() == 2*16+ZERO_SIZE);\n }\n\n std::unique_ptr<char[]> buf2{new char[ZERO_SIZE]};\n std::ifstream is{\"tmp\", std::ios_base::binary};\n is.read(buf2.get(), 16);\n REQUIRE(is.good());\n REQUIRE(memcmp(buf, buf2.get(), 16) == 0);\n\n is.read(buf2.get(), ZERO_SIZE);\n REQUIRE(is.good());\n REQUIRE(std::count(buf2.get(), buf2.get()+ZERO_SIZE, 0) == ZERO_SIZE);\n\n is.read(buf2.get(), 16);\n REQUIRE(is.good());\n REQUIRE(memcmp(buf, buf2.get(), 16) == 0);\n\n is.get();\n REQUIRE(is.eof());\n }\n\n TEST_CASE(\"sink helpers\")\n {\n TRY_MMAP;\n {\n auto sink = Sink::ToFile(\"tmp\", 15, try_mmap);\n sink->WriteLittleUint8(247);\n sink->WriteLittleUint16(1234);\n sink->WriteLittleUint32(98765);\n sink->WriteCString(\"asd\");\n sink->WriteCString(std::string{\"def\"});\n }\n\n Byte exp[15] = { 247, 0xd2, 0x04, 0xcd, 0x81, 0x01, 0x00,\n 'a', 's', 'd', 0, 'd', 'e', 'f', 0 };\n char act[15];\n\n std::ifstream is{\"tmp\", std::ios_base::binary};\n is.read(act, 15);\n REQUIRE(is.good());\n REQUIRE(memcmp(exp, act, 15) == 0);\n\n is.get();\n REQUIRE(is.eof());\n }\n\n\n void MemorySink::Write_(std::string_view)\n { LIBSHIT_UNREACHABLE(\"MemorySink::Write_ called\"); }\n void MemorySink::Pad_(FileMemSize)\n { LIBSHIT_UNREACHABLE(\"MemorySink::Pad_ called\"); }\n\n TEST_CASE(\"memory one write\")\n {\n Byte buf[16] = {15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30};\n Byte buf2[16];\n {\n MemorySink sink{buf2, 16};\n sink.WriteGen(buf);\n }\n\n REQUIRE(memcmp(buf, buf2, 16) == 0);\n }\n\n TEST_CASE(\"memory multiple writes\")\n {\n Byte buf[8] = {42,43,44,45,46,47,48,49};\n Byte buf_out[32];\n Byte buf_exp[32];\n {\n MemorySink sink{buf_out, 32};\n for (size_t i = 0; i < 32; i+=8)\n {\n memcpy(buf_exp+i, buf, 8);\n sink.WriteGen(buf);\n buf[0] = i;\n }\n }\n\n REQUIRE(memcmp(buf_out, buf_exp, 32) == 0);\n }\n\n TEST_CASE(\"memory pad\")\n {\n Byte buf[8] = {77,78,79,80,81,82,83,84};\n Byte buf_out[32];\n Byte buf_exp[32];\n {\n MemorySink sink{buf_out, 32};\n memcpy(buf_exp, buf, 8);\n sink.WriteGen(buf);\n\n memset(buf_exp+8, 0, 16);\n sink.Pad(16);\n\n memcpy(buf_exp+24, buf, 8);\n sink.WriteGen(buf);\n }\n\n REQUIRE(memcmp(buf_out, buf_exp, 32) == 0);\n }\n\n TEST_CASE(\"memory alloc by itself\")\n {\n char buf_exp[4] = { 0x78, 0x56, 0x34, 0x12 };\n MemorySink sink{4};\n\n sink.WriteLittleUint32(0x12345678);\n auto buf = sink.Release();\n\n REQUIRE(memcmp(buf.get(), buf_exp, 4) == 0);\n }\n\n\n#if LIBSHIT_WITH_LUA\n LIBSHIT_LUAGEN(name=\"new\", class=\"Neptools::MemorySink\")\n static Libshit::NotNull<Libshit::SmartPtr<MemorySink>>\n MemorySinkFromLua(std::string_view view)\n {\n std::unique_ptr<Byte[]> buf{new Byte[view.length()]};\n memcpy(buf.get(), view.data(), view.length());\n return Libshit::MakeSmart<MemorySink>(Libshit::Move(buf), view.length());\n }\n#endif\n\n TEST_SUITE_END();\n}\n\n#include \"sink.binding.hpp\"\n" }, { "alpha_fraction": 0.67393559217453, "alphanum_fraction": 0.7154724597930908, "avg_line_length": 22.487804412841797, "blob_id": "72829a57ec28e3d07661485a0b302f2eab8f1c89", "content_id": "b875ceb4eb5ff5e91ede1f25c33a7d3fcc807d7f", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 963, "license_type": "permissive", "max_line_length": 76, "num_lines": 41, "path": "/src/open.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_93BCB6F7_0156_4793_BAD5_76A9E9ABE263\n#define UUID_93BCB6F7_0156_4793_BAD5_76A9E9ABE263\n#pragma once\n\n#include \"dumpable.hpp\"\n#include \"factory.hpp\"\n#include \"source.hpp\"\n\n#include <libshit/lua/static_class.hpp>\n#include <libshit/options.hpp>\n#include <libshit/shared_ptr.hpp>\n\n#include <functional>\n#include <vector>\n\nnamespace Neptools\n{\n\n inline Libshit::OptionGroup& GetFlavorOptions()\n {\n static Libshit::OptionGroup grp{\n Libshit::OptionParser::GetGlobal(), \"Game specific options\"};\n return grp;\n }\n\n class OpenFactory\n : public BaseFactory<Libshit::SmartPtr<Dumpable> (*)(const Source&)>,\n public Libshit::Lua::StaticClass\n {\n LIBSHIT_LUA_CLASS;\n public:\n using Ret = Libshit::SmartPtr<Dumpable>;\n LIBSHIT_NOLUA OpenFactory(BaseFactory::Fun f) : BaseFactory{f} {}\n\n static Libshit::NotNull<Ret> Open(Source src);\n static Libshit::NotNull<Ret> Open(const boost::filesystem::path& fname);\n };\n\n}\n\n#endif\n" }, { "alpha_fraction": 0.6406172513961792, "alphanum_fraction": 0.6441015601158142, "avg_line_length": 24.43037986755371, "blob_id": "25ff63ad8b3d4177333783b577e231e752081edd", "content_id": "8f4a197ec24c64ba375516eaf16bb08cc1186df9", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2009, "license_type": "permissive", "max_line_length": 80, "num_lines": 79, "path": "/src/format/stcm/expansion.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"expansion.hpp\"\n#include \"../context.hpp\"\n#include \"../raw_item.hpp\"\n#include \"../cstring_item.hpp\"\n#include \"../../sink.hpp\"\n\nnamespace Neptools::Stcm\n{\n\n void ExpansionItem::Header::Validate(FilePosition file_size) const\n {\n#define VALIDATE(x) LIBSHIT_VALIDATE_FIELD(\"Stcm::ExpansionItemItem::Header\", x)\n VALIDATE(name < file_size);\n VALIDATE(ptr == 0);\n for (const auto& p : pad) VALIDATE(p == 0);\n#undef VALIDATE\n }\n\n ExpansionItem::ExpansionItem(Key k, Context& ctx, const Header& hdr)\n : Item{k, ctx}, name{Libshit::EmptyNotNull{}}\n {\n hdr.Validate(ctx.GetSize());\n\n index = hdr.index;\n name = ctx.GetLabelTo(hdr.name);\n }\n\n ExpansionItem& ExpansionItem::CreateAndInsert(ItemPointer ptr)\n {\n auto x = RawItem::Get<Header>(ptr);\n auto& ret = x.ritem.SplitCreate<ExpansionItem>(ptr.offset, x.t);\n\n MaybeCreate<CStringItem>(ret.name->GetPtr());\n\n return ret;\n }\n\n void ExpansionItem::Dump_(Sink& sink) const\n {\n Header hdr{};\n hdr.index = index;\n hdr.name = ToFilePos(name->GetPtr());\n sink.WriteGen(hdr);\n }\n\n void ExpansionItem::Inspect_(std::ostream& os, unsigned indent) const\n {\n Item::Inspect_(os, indent);\n os << \"expansion(\" << index << \", \" << PrintLabel(name) << \")\";\n }\n\n\n ExpansionsItem& ExpansionsItem::CreateAndInsert(\n ItemPointer ptr, uint32_t count)\n {\n auto& ret = ptr.AsChecked<RawItem>().SplitCreate<ExpansionsItem>(\n ptr.offset);\n ret.MoveNextToChild(count * sizeof(ExpansionItem::Header));\n auto it = ret.GetChildren().begin();\n\n for (uint32_t i = 0; i < count; ++i)\n {\n auto lbl = ret.GetContext()->CreateLabelFallback(\"expansion\", *it);\n auto& exp = ExpansionItem::CreateAndInsert(lbl->GetPtr());\n it = std::next(exp.Iterator());\n }\n return ret;\n }\n\n void ExpansionsItem::Inspect_(std::ostream& os, unsigned indent) const\n {\n Item::Inspect_(os, indent);\n os << \"expansions()\";\n InspectChildren(os, indent);\n }\n\n}\n\n#include \"expansion.binding.hpp\"\n" }, { "alpha_fraction": 0.7068702578544617, "alphanum_fraction": 0.7267175316810608, "avg_line_length": 61.380950927734375, "blob_id": "8b3044f013e275b2ce946a667efaddeda7335239", "content_id": "35a2ac2e6dee225b427bf3c5f03760a49f2de4c0", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2620, "license_type": "permissive", "max_line_length": 493, "num_lines": 42, "path": "/tools/README.md", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "The scripts in this folder are used by a jenkins slave to build and test\nneptools. To use it you'll need an amd64 sysroot, a qemu image of win 7 (or\nlater) with ssh, wine, msvc includes+libs, patched clang, gcc, and probably\nelse. Documetation is mostly non-existing.\n\nSysroot creation\n================\n\nYou need docker to run this script, it will place the base sysroot in your\nworking directory. Readline and its deps (ncurses, tinfo) are only required by\nthe ljx executble, they're not linked into stcm-editor.\n\n```sh\ndocker run --rm jimbly/steamrt-amd64-gcc bash -c 'apt-get update >&2 && apt-get -y install libreadline6-dev >&2 && dpkg-query -L libc6 libc6-dev linux-libc-dev libgcc1 gcc-4.6 libreadline6-dev libncurses5-dev libtinfo-dev | grep -E \"^(/usr/include/|/usr/lib/|/lib/)\" | xargs tar cvh --no-recursion' | tar x\nrm usr/lib/x86_64-linux-gnu/lib{readline,ncurses,tinfo}.so\nmv usr/lib/x86_64-linux-gnu/lib{*_nonshared,readline,ncurses,tinfo}.a ./\nrm usr/lib/x86_64-linux-gnu/*.a\nrm -r usr/lib/x86_64-linux-gnu/{gconv,libc}\nrm usr/lib/gcc/x86_64-linux-gnu/*/{lto1,lto-wrapper}\nmv lib{*_nonshared,readline,ncurses,tinfo}.a usr/lib/x86_64-linux-gnu/\n```\n\nTo compile libc++, you'll need an [llvm git clone][llvm-git] at `release/8.x` or\nmanually downloading and unpacking a libc++ and libc++abi tarball to a\ndirectory.\n\n```sh\nLLVM=\"/path/to/llvm/clone\"\nSYSROOT=\"/path/to/sysroot\"\nmkdir tmp\ncd tmp\nrm *.o\nclang++ --sysroot \"$SYSROOT\" -g -DNDEBUG -D_GNU_SOURCE -D_LIBCPP_BUILDING_LIBRARY -D_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -fPIC -fvisibility-inlines-hidden -std=c++11 -ffunction-sections -fdata-sections -O3 -flto=thin -DLIBCXX_BUILDING_LIBCXXABI -nostdinc++ -I \"$LLVM\"/libcxxabi/include -I \"$LLVM\"/libcxx/lib -I \"$LLVM\"/libcxx/include -c \"$LLVM\"/libcxx/src/*.cpp\nclang++ --sysroot \"$SYSROOT\" -g -D_GNU_SOURCE -D_LIBCPP_DISABLE_EXTERN_TEMPLATE -D_LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS -D_LIBCXXABI_BUILDING_LIBRARY -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -fPIC -fvisibility-inlines-hidden -std=c++11 -ffunction-sections -fdata-sections -O3 -flto=thin -nostdinc++ -fstrict-aliasing -funwind-tables -D_DEBUG -I \"$LLVM\"/libcxxabi/src -I \"$LLVM\"/libcxxabi/include -I \"$LLVM\"/libcxx/include -c \"$LLVM\"/libcxxabi/src/*.cpp\nllvm-ar rs libc++.a *.o\nmv libc++.a \"$SYSROOT\"/usr/lib\nmkdir -p \"$SYSROOT\"/usr/include/c++/v1\ncp -R \"$LLVM\"/libcxx{,abi}/include/* \"$SYSROOT\"/usr/include/c++/v1\nrm \"$SYSROOT\"/usr/include/c++/v1/{CMakeLists.txt,__config_site.in}\n```\n\n[llvm-git]: https://github.com/llvm/llvm-project\n" }, { "alpha_fraction": 0.598499059677124, "alphanum_fraction": 0.6261056065559387, "avg_line_length": 35.94059371948242, "blob_id": "07c7a4c6b9a9c7cb6d97263cf348b7182e05d020", "content_id": "5006a10d7e665f6f86ae41ce5e2a1b6e57685019", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11193, "license_type": "permissive", "max_line_length": 87, "num_lines": 303, "path": "/src/format/stcm/instruction.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_032F4E0D_CAAE_429A_9928_2ACC24EC51E1\n#define UUID_032F4E0D_CAAE_429A_9928_2ACC24EC51E1\n#pragma once\n\n#include \"../item.hpp\"\n#include \"../../source.hpp\"\n\n#include <libshit/check.hpp>\n#include <libshit/lua/auto_table.hpp>\n\n#include <boost/endian/arithmetic.hpp>\n#include <variant>\n\nnamespace Neptools { class RawItem; }\n\nnamespace Neptools::Stcm\n{\n\n class InstructionItem final : public ItemWithChildren\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n struct Header\n {\n boost::endian::little_uint32_t is_call;\n boost::endian::little_uint32_t opcode;\n boost::endian::little_uint32_t param_count;\n boost::endian::little_uint32_t size;\n\n enum Opcode : uint32_t\n {\n USER_OPCODES = 0x1000,\n SYSTEM_OPCODES_BEGIN = 0xffffff00,\n SYSTEM_OPCODES_END = 0xffffff14,\n };\n\n void Validate(FilePosition file_size) const;\n };\n static_assert(sizeof(Header) == 0x10);\n\n struct Parameter\n {\n struct Type0\n {\n static constexpr uint32_t MEM_OFFSET = 0;\n static constexpr uint32_t UNK = 1;\n static constexpr uint32_t INDIRECT = 2;\n static constexpr uint32_t SPECIAL = 3;\n };\n\n struct Type0Special\n {\n static constexpr uint32_t READ_STACK_MIN = 0xffffff00;\n static constexpr uint32_t READ_STACK_MAX = 0xffffff0f;\n static constexpr uint32_t READ_4AC_MIN = 0xffffff20;\n static constexpr uint32_t READ_4AC_MAX = 0xffffff27;\n static constexpr uint32_t INSTR_PTR0 = 0xffffff40;\n static constexpr uint32_t INSTR_PTR1 = 0xffffff41;\n static constexpr uint32_t COLL_LINK = 0xffffff42;\n static constexpr uint32_t EXPANSION = 0xffffff43;\n };\n\n struct Type48\n {\n static constexpr uint32_t MEM_OFFSET = 0;\n static constexpr uint32_t IMMEDIATE = 1;\n static constexpr uint32_t INDIRECT = 2;\n static constexpr uint32_t SPECIAL = 3;\n };\n\n struct Type48Special\n {\n static constexpr uint32_t READ_STACK_MIN = 0xffffff00;\n static constexpr uint32_t READ_STACK_MAX = 0xffffff0f;\n static constexpr uint32_t READ_4AC_MIN = 0xffffff20;\n static constexpr uint32_t READ_4AC_MAX = 0xffffff27;\n };\n\n boost::endian::little_uint32_t param_0;\n boost::endian::little_uint32_t param_4;\n boost::endian::little_uint32_t param_8;\n\n static constexpr inline uint32_t TypeTag(uint32_t x) { return x >> 30; }\n static constexpr inline uint32_t Value(uint32_t x) { return x & 0x3fffffff; }\n static constexpr inline uint32_t Tag(uint32_t tag, uint32_t val)\n { return (tag << 30) | val; }\n void Validate(FilePosition file_size) const;\n };\n static_assert(sizeof(Parameter) == 0xc);\n\n class Param;\n InstructionItem(Key k, Context& ctx) : ItemWithChildren{k, ctx} {}\n InstructionItem(Key k, Context& ctx, Source src);\n InstructionItem(Key k, Context& ctx, Libshit::NotNull<LabelPtr> tgt)\n : ItemWithChildren{k, ctx}, opcode_target{std::move(tgt)} {}\n InstructionItem(Key k, Context& ctx, Libshit::NotNull<LabelPtr> tgt,\n Libshit::AT<std::vector<Param>> params)\n : ItemWithChildren{k, ctx}, params{std::move(params.Get())},\n opcode_target{std::move(tgt)} {}\n\n InstructionItem(Key k, Context& ctx, uint32_t opcode)\n : ItemWithChildren{k, ctx}, opcode_target{opcode} {}\n InstructionItem(Key k, Context& ctx, uint32_t opcode,\n Libshit::AT<std::vector<Param>> params)\n : ItemWithChildren{k, ctx}, params{std::move(params.Get())},\n opcode_target{opcode} {}\n static InstructionItem& CreateAndInsert(ItemPointer ptr);\n\n FilePosition GetSize() const noexcept override;\n void Fixup() override;\n void Dispose() noexcept override;\n\n bool IsCall() const noexcept\n { return !std::holds_alternative<uint32_t>(opcode_target); }\n\n uint32_t GetOpcode() const { return std::get<0>(opcode_target); }\n\n void SetOpcode(uint32_t oc) noexcept { opcode_target = oc; }\n Libshit::NotNull<LabelPtr> GetTarget() const\n { return std::get<1>(opcode_target); }\n\n void SetTarget(Libshit::NotNull<LabelPtr> label) noexcept\n { opcode_target = label; }\n\n class Param48 : public Libshit::Lua::ValueObject\n {\n LIBSHIT_LUA_CLASS;\n public:\n enum class LIBSHIT_LUAGEN() Type\n {\n#define NEPTOOLS_GEN_TYPES(x, ...) \\\n x(MEM_OFFSET, __VA_ARGS__) \\\n x(IMMEDIATE, __VA_ARGS__) \\\n x(INDIRECT, __VA_ARGS__) \\\n x(READ_STACK, __VA_ARGS__) \\\n x(READ_4AC, __VA_ARGS__)\n#define NEPTOOLS_GEN_ENUM(x,y) x,\n NEPTOOLS_GEN_TYPES(NEPTOOLS_GEN_ENUM,)\n };\n using Variant = std::variant<\n Libshit::NotNull<LabelPtr>, uint32_t, uint32_t, uint32_t, uint32_t>;\n\n Param48(Context& ctx, uint32_t val) : val{GetVariant(ctx, val)} {}\n template <size_t type, typename T> LIBSHIT_NOLUA\n Param48(std::in_place_index_t<type> x, T val) : val{x, std::move(val)} {}\n\n uint32_t Dump() const noexcept;\n\n Type GetType() const noexcept { return static_cast<Type>(val.index()); }\n\n template <typename Visitor> LIBSHIT_NOLUA\n auto Visit(Visitor&& v) const\n { return std::visit(std::forward<Visitor>(v), val); }\n\n#define NEPTOOLS_GEN_TMPL(x,xname) LIBSHIT_LUAGEN( \\\n name=xname..string.lower(#x), template_params={ \\\n \"Neptools::Stcm::InstructionItem::Param48::Type::\"..#x})\n template <Type type> NEPTOOLS_GEN_TYPES(NEPTOOLS_GEN_TMPL, \"get_\")\n auto Get() const { return std::get<static_cast<size_t>(type)>(val); }\n template <Type type> LIBSHIT_NOLUA\n void Set(std::variant_alternative_t<\n static_cast<size_t>(type), Variant> nval)\n { val.emplace(std::in_place_index<type>(std::move(nval))); }\n\n template <Type type> NEPTOOLS_GEN_TYPES(NEPTOOLS_GEN_TMPL, \"new_\")\n static Param48 New(std::variant_alternative_t<\n static_cast<size_t>(type), Variant> nval)\n { return {std::in_place_index<static_cast<size_t>(type)>, std::move(nval)}; }\n#undef NEPTOOLS_GEN_TMPL\n#undef NEPTOOLS_GEN_TYPES\n\n\n // NEPTOOLS_GEN_INT(Immediate, IMMEDIATE, Param48, Parameter::TypeTag(val) == 0)\n // NEPTOOLS_GEN_INT(Indirect, INDIRECT, Param48, Parameter::TypeTag(val) == 0)\n // NEPTOOLS_GEN_INT(ReadStack, READ_STACK, Param48, val < 16)\n // NEPTOOLS_GEN_INT(Read4ac, READ_4AC, Param48, val < 16)\n\n private:\n Variant val;\n static Variant GetVariant(Context& ctx, uint32_t val);\n } LIBSHIT_LUAGEN(post_register=\"bld.TaggedNew();\");\n\n class Param : public Libshit::Lua::ValueObject\n {\n LIBSHIT_LUA_CLASS;\n public:\n struct MemOffset : Libshit::Lua::ValueObject\n {\n Libshit::NotNull<LabelPtr> target;\n Param48 param_4;\n Param48 param_8;\n\n MemOffset(Libshit::NotNull<LabelPtr> target, Param48 param_4,\n Param48 param_8)\n : target{std::move(target)}, param_4{std::move(param_4)},\n param_8{std::move(param_8)} {}\n LIBSHIT_LUA_CLASS;\n };\n struct Indirect : Libshit::Lua::ValueObject\n {\n uint32_t param_0;\n Param48 param_8;\n\n Indirect(uint32_t param_0, Param48 param_8)\n : param_0{param_0}, param_8{std::move(param_8)} {}\n LIBSHIT_LUA_CLASS;\n };\n enum class LIBSHIT_LUAGEN() Type\n {\n#define NEPTOOLS_GEN_TYPES(x, ...) \\\n x(MEM_OFFSET, __VA_ARGS__) \\\n x(INDIRECT, __VA_ARGS__) \\\n x(READ_STACK, __VA_ARGS__) \\\n x(READ_4AC, __VA_ARGS__) \\\n x(INSTR_PTR0, __VA_ARGS__) \\\n x(INSTR_PTR1, __VA_ARGS__) \\\n x(COLL_LINK, __VA_ARGS__) \\\n x(EXPANSION, __VA_ARGS__)\n NEPTOOLS_GEN_TYPES(NEPTOOLS_GEN_ENUM,)\n#undef NEPTOOLS_GEN_ENUM\n };\n using Variant = std::variant<\n MemOffset, Indirect, uint32_t, uint32_t, Libshit::NotNull<LabelPtr>,\n Libshit::NotNull<LabelPtr>, Libshit::NotNull<LabelPtr>,\n Libshit::NotNull<LabelPtr>>;\n\n LIBSHIT_NOLUA\n Param(Context& ctx, const Parameter& p) : val{GetVariant(ctx, p)} {}\n template <size_t type, typename T> LIBSHIT_NOLUA\n Param(std::in_place_index_t<type> x, T val) : val{x, std::move(val)} {}\n\n void Dump(Sink& sink) const;\n LIBSHIT_NOLUA void Dump(Sink&& sink) const { Dump(sink); }\n\n Type GetType() const noexcept { return static_cast<Type>(val.index()); }\n\n template <typename Visitor> LIBSHIT_NOLUA\n auto Visit(Visitor&& v) const\n { return std::visit(std::forward<Visitor>(v), val); }\n\n#define NEPTOOLS_GEN_TMPL(x,xname) LIBSHIT_LUAGEN( \\\n name=xname..string.lower(#x), template_params={ \\\n \"Neptools::Stcm::InstructionItem::Param::Type::\"..#x})\n template <Type type> NEPTOOLS_GEN_TYPES(NEPTOOLS_GEN_TMPL, \"get_\")\n auto Get() const { return std::get<static_cast<size_t>(type)>(val); }\n template <Type type> LIBSHIT_NOLUA\n void Set(std::variant_alternative_t<\n static_cast<size_t>(type), Variant> nval)\n { val.emplace(std::in_place_index<type>(std::move(nval))); }\n\n template <Type type> NEPTOOLS_GEN_TYPES(NEPTOOLS_GEN_TMPL, \"new_\")\n static Param New(std::variant_alternative_t<\n static_cast<size_t>(type), Variant> nval)\n { return {std::in_place_index<static_cast<size_t>(type)>, std::move(nval)}; }\n\n static Param NewMemOffset(\n Libshit::NotNull<LabelPtr> target, Libshit::AT<Param48> param_4,\n Libshit::AT<Param48> param_8)\n {\n return New<Type::MEM_OFFSET>({\n std::move(target), std::move(param_4.Get()),\n std::move(param_8.Get())});\n }\n static Param NewIndirect(uint32_t param_0, Libshit::AT<Param48> param_8)\n { return New<Type::INDIRECT>({param_0, std::move(param_8.Get())}); }\n\n#undef NEPTOOLS_GEN_TYPES\n#undef NEPTOOL_GEN_ENUM\n#undef NEPTOOLS_GEN_TMPL\n\n // NEPTOOLS_GEN_LABEL(MemOffset, MEM_OFFSET, Param)\n // NEPTOOLS_GEN_INT (Indirect, INDIRECT, Param, Parameter::TypeTag(val) == 0)\n // NEPTOOLS_GEN_INT (ReadStack, READ_STACK, Param, val < 16)\n // NEPTOOLS_GEN_INT (Read4ac, READ_4AC, Param, val < 16)\n // NEPTOOLS_GEN_LABEL(InstrPtr0, INSTR_PTR0, Param)\n // NEPTOOLS_GEN_LABEL(InstrPtr1, INSTR_PTR1, Param)\n // NEPTOOLS_GEN_LABEL(CollLink, COLL_LINK, Param)\n\n private:\n Variant val;\n static Variant GetVariant(Context& ctx, const Parameter& in);\n } LIBSHIT_LUAGEN(post_register=\"bld.TaggedNew();\");\n\n LIBSHIT_LUAGEN(get=\"::Libshit::Lua::GetSmartOwnedMember\")\n std::vector<Param> params;\n\n private:\n std::variant<uint32_t, Libshit::NotNull<LabelPtr>> opcode_target;\n\n void Dump_(Sink& sink) const override;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n void Parse_(Context& ctx, Source& src);\n };\n\n std::ostream& operator<<(std::ostream& os, const InstructionItem::Param48& p);\n std::ostream& operator<<(std::ostream& os, const InstructionItem::Param& p);\n\n}\n\nLIBSHIT_ENUM(Neptools::Stcm::InstructionItem::Param48::Type);\nLIBSHIT_ENUM(Neptools::Stcm::InstructionItem::Param::Type);\n\n#endif\n" }, { "alpha_fraction": 0.6324121952056885, "alphanum_fraction": 0.6482440829277039, "avg_line_length": 29.473684310913086, "blob_id": "871aac1dc651ea7ff493f1762a25bc7d11f17641", "content_id": "5fb1f2360acc78da0c9b1e276fa78a1607432334", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3474, "license_type": "permissive", "max_line_length": 81, "num_lines": 114, "path": "/src/format/raw_item.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_49BE292D_0E45_47B1_8901_97A22C0190F6\n#define UUID_49BE292D_0E45_47B1_8901_97A22C0190F6\n#pragma once\n\n#include \"context.hpp\"\n#include \"../source.hpp\"\n\n#include <libshit/except.hpp>\n\nnamespace Neptools\n{\n\n class RawItem final : public Item\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n RawItem(Key k, Context& ctx, Source src) noexcept\n : Item{k, ctx}, src{std::move(src)} {}\n RawItem(Key k, Context& ctx, std::string src)\n : Item{k, ctx}, src{Source::FromMemory(std::move(src))} {}\n LIBSHIT_NOLUA\n RawItem(Key k, Context& ctx, Source src, FilePosition pos) noexcept\n : Item{k, ctx, pos}, src{std::move(src)} {}\n\n const Source& GetSource() const noexcept { return src; }\n FilePosition GetSize() const noexcept override { return src.GetSize(); }\n\n template <typename T>\n LIBSHIT_LUAGEN(template_params={\"::Neptools::Item\"})\n T& Split(FilePosition pos, Libshit::NotNull<Libshit::RefCountedPtr<T>> nitem)\n {\n T& ret = *nitem;\n Split2(pos, std::move(nitem));\n return ret;\n }\n\n template <typename T, typename... Args>\n LIBSHIT_NOLUA T& SplitCreate(FilePosition pos, Args&&... args)\n {\n auto ctx = GetContext();\n return Split(pos, ctx->Create<T>(std::forward<Args>(args)...));\n }\n\n RawItem& Split(FilePosition offset, FilePosition size);\n\n template <typename T>\n LIBSHIT_NOLUA static auto Get(ItemPointer ptr)\n {\n auto& ritem = ptr.AsChecked<RawItem>();\n LIBSHIT_ASSERT_MSG(ptr.offset <= ritem.GetSize(), \"invalid offset\");\n if (ptr.offset + sizeof(T) > ritem.GetSize())\n LIBSHIT_THROW(Libshit::DecodeError, \"Premature end of data\");\n\n struct Ret { RawItem& ritem; T t; };\n return Ret{\n std::ref(ritem),\n ritem.src.PreadGen<T>(ptr.offset)};\n }\n\n struct GetSourceRet { RawItem& ritem; Source src; };\n static GetSourceRet GetSource(ItemPointer ptr, FilePosition len)\n {\n auto& ritem = ptr.AsChecked<RawItem>();\n LIBSHIT_ASSERT_MSG(ptr.offset <= ritem.GetSize(), \"invalid offset\");\n if (len == FilePosition(-1)) len = ritem.GetSize() - ptr.offset;\n\n if (ptr.offset + len > ritem.GetSize())\n LIBSHIT_THROW(Libshit::DecodeError, \"Premature end of data\");\n return {std::ref(ritem), {ritem.src, ptr.offset, len}};\n }\n\n private:\n Libshit::NotNull<Libshit::RefCountedPtr<RawItem>> InternalSlice(\n FilePosition offset, FilePosition size);\n void Split2(\n FilePosition pos, Libshit::NotNull<Libshit::SmartPtr<Item>> nitem);\n\n void Dump_(Sink& sink) const override;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n\n Source src;\n };\n\n template <typename T, typename... Args>\n inline auto& MaybeCreate(ItemPointer ptr, Args&&... args)\n {\n auto item = ptr.Maybe<RawItem>();\n if (item)\n return T::CreateAndInsert(ptr, std::forward<Args>(args)...);\n else\n return ptr.AsChecked0<T>(); // check it\n }\n\n template <typename T, typename... Args>\n inline void MaybeCreateUnchecked(ItemPointer ptr, Args&&... args)\n {\n if (ptr.Maybe<RawItem>())\n T::CreateAndInsert(ptr, std::forward<Args>(args)...);\n }\n\n}\n\ntemplate<> struct Libshit::Lua::TupleLike<Neptools::RawItem::GetSourceRet>\n{\n template <size_t I>\n static auto& Get(const Neptools::RawItem::GetSourceRet& ret) noexcept\n {\n if constexpr (I == 0) return ret.ritem;\n else if constexpr (I == 1) return ret.src;\n }\n static constexpr size_t SIZE = 2;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6586306691169739, "alphanum_fraction": 0.6586306691169739, "avg_line_length": 31.40625, "blob_id": "6d45f1dcc44fe03af563be2d7dfa8adb835de8d8", "content_id": "8de7af5912f3c8da0c5bd53120412a507585d554", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1037, "license_type": "permissive", "max_line_length": 126, "num_lines": 32, "path": "/src/format/stcm/file.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Stcm::File::TYPE_NAME[] = \"neptools.stcm.file\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.stcm.file\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::File>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stcm::File, ::Neptools::Context, ::Neptools::TxtSerializable>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::File>::Make<>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::File>::Make<LuaGetRef<::Neptools::Source>>\n >(\"new\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::GbnlItem * (::Neptools::Stcm::File::*)() const noexcept>(&::Neptools::Stcm::File::GetGbnl)\n >(\"get_gbnl\");\n bld.AddFunction<\n static_cast<void (::Neptools::Stcm::File::*)() noexcept>(&::Neptools::Stcm::File::Gc)\n >(\"gc\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::File> reg_neptools_stcm_file;\n\n}\n#endif\n" }, { "alpha_fraction": 0.5508447289466858, "alphanum_fraction": 0.5616593360900879, "avg_line_length": 27.418960571289062, "blob_id": "067bd47e46561d7dbf40cfe5eaebcbd34532060c", "content_id": "cce2e08b251d191fa69347811b0de610141fb7a4", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 18586, "license_type": "permissive", "max_line_length": 85, "num_lines": 654, "path": "/src/programs/stcm-editor.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"../format/item.hpp\"\n#include \"../format/cl3.hpp\"\n#include \"../format/primitive_item.hpp\"\n#include \"../format/stcm/file.hpp\"\n#include \"../format/stcm/gbnl.hpp\"\n#include \"../format/stcm/string_data.hpp\"\n#include \"../format/stsc/file.hpp\"\n#include \"../open.hpp\"\n#include \"../txt_serializable.hpp\"\n#include \"../utils.hpp\"\n#include \"version.hpp\"\n\n#include <libshit/except.hpp>\n#include <libshit/lua/base.hpp>\n#include <libshit/options.hpp>\n#include <libshit/platform.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <deque>\n#include <boost/algorithm/string/predicate.hpp>\n#include <boost/filesystem/path.hpp>\n#include <boost/filesystem/operations.hpp>\n\n#if LIBSHIT_STDLIB_IS_MSVC\n# undef _CRT_NONSTDC_DEPRECATE // fuck off m$\n# define _CRT_NONSTDC_DEPRECATE(x)\n# include <io.h>\n#endif\n\n#define LIBSHIT_LOG_NAME \"stcm-editor\"\n#include <libshit/logger_helper.hpp>\n\nusing namespace Neptools;\nusing namespace Libshit;\n\nnamespace\n{\n struct State\n {\n SmartPtr<Dumpable> dump;\n Cl3* cl3;\n Stcm::File* stcm;\n TxtSerializable* txt;\n };\n}\n\nstatic State SmartOpen(const boost::filesystem::path& fname)\n{\n auto x = OpenFactory::Open(fname);\n return {x, dynamic_cast<Cl3*>(x.get()), dynamic_cast<Stcm::File*>(x.get()),\n dynamic_cast<TxtSerializable*>(x.get())};\n}\n\ntemplate <typename T>\nstatic void ShellDump(const T* item, const char* name)\n{\n RefCountedPtr<Sink> sink;\n if (name[0] == '-' && name[1] == '\\0')\n sink = Sink::ToStdOut();\n else\n sink = Sink::ToFile(name, item->GetSize());\n item->Dump(*sink);\n}\n\ntemplate <typename T, typename Fun>\nstatic void ShellInspectGen(const T* item, const char* name, Fun f)\n{\n if (name[0] == '-' && name[1] == '\\0')\n f(item, std::cout);\n else\n f(item, OpenOut(name));\n}\n\ntemplate <typename T>\nstatic void ShellInspect(const T* item, const char* name)\n{\n ShellInspectGen(\n item, name, [](auto x, auto&& y) { y << \"return \" << *x << '\\n'; });\n}\n\nstatic void EnsureStcm(State& st)\n{\n if (st.stcm) return;\n if (!st.dump) throw InvalidParam{\"no file loaded\"};\n if (!st.cl3)\n throw InvalidParam{\"invalid file loaded: can't find STCM without CL3\"};\n\n st.stcm = &st.cl3->GetStcm();\n}\n\nstatic void EnsureTxt(State& st)\n{\n if (st.txt) return;\n EnsureStcm(st);\n if (!st.stcm->GetGbnl())\n LIBSHIT_THROW(DecodeError, \"No GBNL found in STCM\");\n st.txt = st.stcm;\n}\n\nstatic bool auto_failed = false;\ntemplate <typename Pred, typename Fun>\nstatic void RecDo(\n const boost::filesystem::path& path, Pred p, Fun f, bool rec = false)\n{\n if (p(path, rec))\n {\n try { f(path); }\n catch (const std::exception& e)\n {\n auto_failed = true;\n ERR << \"Failed: \"\n << Libshit::PrintException(Libshit::Logger::HasAnsiColor())\n << std::endl;\n }\n }\n else if (boost::filesystem::is_directory(path))\n for (auto& e: boost::filesystem::directory_iterator(path))\n RecDo(e, p, f, true);\n else if (!rec)\n ERR << \"Invalid filename: \" << path << std::endl;\n}\n\nnamespace\n{\n enum class Mode\n {\n#define MODE_PARS_PRE(X) \\\n X(AUTO_STRTOOL, \"auto-strtool\", \"import/export .cl3/.gbin/.gstr texts\") \\\n X(EXPORT_STRTOOL, \"export-strtool\", \"export .cl3/.gbin/.gstr to .txt\") \\\n X(IMPORT_STRTOOL, \"import-strtool\", \"import .cl3/.gbin/.gstr from .txt\") \\\n X(AUTO_CL3, \"auto-cl3\", \"unpack/pack .cl3 files\") \\\n X(UNPACK_CL3, \"unpack-cl3\", \"unpack .cl3 files\") \\\n X(PACK_CL3, \"pack-cl3\", \"pack .cl3 files\")\n#define MODE_PARS_LUA(X) \\\n X(AUTO_LUA, \"auto-lua\", \"import/export stcms\") \\\n X(EXPORT_LUA, \"export-lua\", \"export stcms\") \\\n X(IMPORT_LUA, \"import-lua\", \"import lua\")\n#define MODE_PARS_POST(X) \\\n X(MANUAL, \"manual\", \"manual processing (set automatically)\")\n#if LIBSHIT_WITH_LUA\n# define MODE_PARS(X) MODE_PARS_PRE(X) MODE_PARS_LUA(X) MODE_PARS_POST(X)\n#else\n# define MODE_PARS(X) MODE_PARS_PRE(X) MODE_PARS_POST(X)\n#endif\n#define GEN_ENUM(name, shit1, shit2) name,\n MODE_PARS(GEN_ENUM)\n#undef GEN_ENUM\n } mode = Mode::AUTO_STRTOOL;\n}\n\nstatic auto BaseDoAutoFun(const boost::filesystem::path& p, const char* ext)\n{\n boost::filesystem::path cl3, txt;\n bool import;\n if (boost::ends_with(p.native(), ext))\n {\n cl3 = p.native().substr(0, p.native().size()-4);\n txt = p;\n import = true;\n INF << \"Importing: \" << cl3 << \" <- \" << txt << std::endl;\n }\n else\n {\n cl3 = txt = p;\n txt += ext;\n import = false;\n INF << \"Exporting: \" << cl3 << \" -> \" << txt << std::endl;\n }\n\n return std::make_tuple(import, cl3, txt);\n}\n\nstatic void DoAutoTxt(const boost::filesystem::path& p)\n{\n auto [import, cl3, txt] = BaseDoAutoFun(p, \".txt\");\n auto st = SmartOpen(cl3);\n EnsureTxt(st);\n if (import)\n {\n st.txt->ReadTxt(OpenIn(txt));\n if (st.stcm) st.stcm->Fixup();\n st.dump->Fixup();\n st.dump->Dump(cl3);\n }\n else\n st.txt->WriteTxt(OpenOut(txt));\n}\n\n#if LIBSHIT_WITH_LUA\nstatic void DoAutoLua(const boost::filesystem::path& p)\n{\n auto [import, bin, lua] = BaseDoAutoFun(p, \".lua\");\n if (import)\n {\n Lua::State vm;\n lua_getglobal(vm, \"debug\"); // +1\n lua_getfield(vm, -1, \"traceback\"); // +2\n if (luaL_loadfile(vm, lua.string().c_str()) || lua_pcall(vm, 0, 1, -2))\n {\n Logger::Log(\"lua\", Logger::ERROR, nullptr, 0, nullptr)\n << lua_tostring(vm, -1) << std::endl;\n return;\n }\n auto dmp = vm.Get<NotNull<SmartPtr<Dumpable>>>(-1);\n // hack? when importing a cl3, and we get a gbnl, put it into the\n // existing cl3\n if (boost::iends_with(bin.native(), \".cl3\") &&\n dynamic_cast<Stcm::File*>(dmp.get()))\n {\n auto cl3 = MakeSmart<Cl3>(Source::FromFile(bin));\n auto stcme = cl3->entries.find(\"main.DAT\", std::less<>{});\n if (stcme == cl3->entries.end())\n LIBSHIT_THROW(DecodeError, \"Invalid CL3 file: no main.DAT\");\n dmp->Fixup();\n stcme->src = dmp;\n dmp = cl3;\n }\n dmp->Fixup();\n dmp->Dump(bin);\n }\n else\n {\n auto st = SmartOpen(bin);\n EnsureStcm(st);\n OpenOut(lua) << \"return \" << *(st.stcm ? st.stcm : st.dump.get()) << '\\n';\n }\n}\n#endif\n\nstatic void DoAutoCl3(const boost::filesystem::path& p)\n{\n if (boost::filesystem::is_directory(p))\n {\n boost::filesystem::path cl3_file =\n p.native().substr(0, p.native().size() - 4);\n INF << \"Packing \" << cl3_file << std::endl;\n Cl3 cl3{Source::FromFile(cl3_file)};\n cl3.UpdateFromDir(p);\n cl3.Fixup();\n cl3.Dump(cl3_file);\n }\n else\n {\n INF << \"Extracting \" << p << std::endl;\n Cl3 cl3{Source::FromFile(p)};\n auto out = p;\n cl3.ExtractTo(out += \".out\");\n }\n}\n\nstatic inline bool is_file(const boost::filesystem::path& pth)\n{\n auto stat = boost::filesystem::status(pth);\n return boost::filesystem::is_regular_file(stat) ||\n boost::filesystem::is_symlink(stat);\n}\n\nstatic bool IsBin(const boost::filesystem::path& p, bool = false)\n{\n return is_file(p) && (\n boost::iends_with(p.native(), \".cl3\") ||\n boost::iends_with(p.native(), \".gbin\") ||\n boost::iends_with(p.native(), \".gstr\") ||\n boost::iends_with(p.native(), \".bin\"));\n}\n\nstatic bool IsTxt(const boost::filesystem::path& p, bool = false)\n{\n return is_file(p) && (\n boost::iends_with(p.native(), \".cl3.txt\") ||\n boost::iends_with(p.native(), \".gbin.txt\") ||\n boost::iends_with(p.native(), \".gstr.txt\") ||\n boost::iends_with(p.native(), \".bin.txt\"));\n}\n\n#if LIBSHIT_WITH_LUA\nstatic bool IsLua(const boost::filesystem::path& p, bool = false)\n{\n return is_file(p) && (\n boost::iends_with(p.native(), \".cl3.lua\") ||\n boost::iends_with(p.native(), \".gbin.lua\") ||\n boost::iends_with(p.native(), \".gstr.lua\") ||\n boost::iends_with(p.native(), \".bin.lua\"));\n}\n#endif\n\nstatic bool IsCl3(const boost::filesystem::path& p, bool = false)\n{\n return is_file(p) && boost::iends_with(p.native(), \".cl3\");\n}\n\nstatic bool IsCl3Dir(const boost::filesystem::path& p, bool = false)\n{\n return boost::filesystem::is_directory(p) &&\n boost::iends_with(p.native(), \".cl3.out\");\n}\n\nstatic void DoAuto(const boost::filesystem::path& path)\n{\n bool (*pred)(const boost::filesystem::path&, bool);\n void (*fun)(const boost::filesystem::path& p);\n\n switch (mode)\n {\n case Mode::AUTO_STRTOOL:\n pred = [](auto& p, bool rec)\n {\n if (rec)\n return (IsTxt(p) && boost::filesystem::exists(\n p.native().substr(0, p.native().size()-4))) ||\n (IsBin(p) && !boost::filesystem::exists(\n boost::filesystem::path(p)+=\".txt\"));\n else\n return IsBin(p) || IsTxt(p);\n };\n fun = DoAutoTxt;\n break;\n\n case Mode::EXPORT_STRTOOL:\n pred = IsBin;\n fun = DoAutoTxt;\n break;\n case Mode::IMPORT_STRTOOL:\n pred = IsTxt;\n fun = DoAutoTxt;\n break;\n\n case Mode::AUTO_CL3:\n pred = [](auto& p, bool rec)\n {\n if (rec)\n return IsCl3Dir(p) || (IsCl3(p) && !boost::filesystem::exists(\n boost::filesystem::path(p)+=\".out\"));\n else\n return IsCl3(p) || IsCl3Dir(p);\n };\n fun = DoAutoCl3;\n break;\n\n case Mode::UNPACK_CL3:\n pred = IsCl3;\n fun = DoAutoCl3;\n break;\n case Mode::PACK_CL3:\n pred = IsCl3Dir;\n fun = DoAutoCl3;\n break;\n\n#if LIBSHIT_WITH_LUA\n case Mode::AUTO_LUA:\n pred = [](auto& p, bool rec)\n {\n if (rec)\n return (IsLua(p) && boost::filesystem::exists(\n p.native().substr(0, p.native().size()-4))) ||\n (IsBin(p) && !boost::filesystem::exists(\n boost::filesystem::path(p)+=\".lua\"));\n else\n return IsBin(p) || IsLua(p);\n };\n fun = DoAutoLua;\n break;\n\n case Mode::EXPORT_LUA:\n pred = IsBin;\n fun = DoAutoLua;\n break;\n\n case Mode::IMPORT_LUA:\n pred = IsLua;\n fun = DoAutoLua;\n break;\n#endif\n\n case Mode::MANUAL:\n throw InvalidParam{\"Can't use auto files in manual mode\"};\n }\n RecDo(path, pred, fun);\n}\n\nint main(int argc, char** argv)\n{\n State st;\n auto& parser = OptionParser::GetGlobal();\n OptionGroup hgrp{parser, \"High-level options\"};\n OptionGroup lgrp{parser, \"Low-level options\", \"See README for details\"};\n\n Option mode_opt{\n hgrp, \"mode\", 'm', 1, \"OPTION\",\n#define GEN_HELP(_, key, help) \"\\t\\t\" key \": \" help \"\\n\"\n \"Set operating mode:\\n\" MODE_PARS(GEN_HELP),\n#undef GEN_HELP\n [](auto&& args)\n {\n if (false); // NOLINT\n#define GEN_IFS(c, str, _) else if (strcmp(args.front(), str) == 0) mode = Mode::c;\n MODE_PARS(GEN_IFS)\n#undef GEN_IFS\n else throw InvalidParam{\"invalid argument\"};\n }};\n\n Option open_opt{\n lgrp, \"open\", 1, \"FILE\", \"Opens FILE as cl3 or stcm file\",\n [&](auto&& args)\n {\n mode = Mode::MANUAL;\n st = SmartOpen(args.front());\n }};\n Option save_opt{\n lgrp, \"save\", 1, \"FILE|-\", \"Saves the loaded file to FILE or stdout\",\n [&](auto&& args)\n {\n mode = Mode::MANUAL;\n if (!st.dump) throw InvalidParam{\"no file loaded\"};\n st.dump->Fixup();\n ShellDump(st.dump.get(), args.front());\n }};\n Option create_cl3_opt{\n lgrp, \"create-cl3\", 0, nullptr, \"Creates an empty cl3 file\",\n [&](auto&&)\n {\n mode = Mode::MANUAL;\n SmartPtr<Cl3> c = MakeSmart<Cl3>();\n st = {c, c.get(), nullptr, nullptr};\n }};\n Option list_files_opt{\n lgrp, \"list-files\", 0, nullptr, \"Lists the contents of the cl3 archive\",\n [&](auto&&)\n {\n mode = Mode::MANUAL;\n if (!st.cl3) throw InvalidParam{\"no cl3 loaded\"};\n size_t i = 0;\n for (const auto& e : st.cl3->entries)\n {\n std::cout << i++ << '\\t' << e.name << '\\t' << e.src->GetSize()\n << \"\\tlinks:\";\n for (const auto& l : e.links)\n std::cout << ' ' << st.cl3->IndexOf(l);\n std::cout << std::endl;\n }\n }};\n Option extract_file_opt{\n lgrp, \"extract-file\", 2, \"NAME OUT_FILE|-\",\n \"Extract NAME from cl3 archive to OUT_FILE or stdout\",\n [&](auto&& args)\n {\n mode = Mode::MANUAL;\n if (!st.cl3) throw InvalidParam{\"no cl3 loaded\"};\n auto& entries = st.cl3->entries;\n auto e = entries.find(args[0]);\n\n if (e == entries.end())\n throw InvalidParam{\"specified file not found\"};\n else\n ShellDump(e->src.get(), args[1]);\n }};\n Option extract_files_opt{\n lgrp, \"extract-files\", 1, \"DIR\", \"Extract the cl3 archive to DIR\",\n [&](auto&& args)\n {\n mode = Mode::MANUAL;\n if (!st.cl3) throw InvalidParam{\"no cl3 loaded\"};\n st.cl3->ExtractTo(args.front());\n }};\n Option replace_file_opt{\n lgrp, \"replace-file\", 2, \"NAME IN_FILE\",\n \"Adds or replaces NAME in cl3 archive with IN_FILE\",\n [&](auto&& args)\n {\n mode = Mode::MANUAL;\n if (!st.cl3) throw InvalidParam{\"no cl3 loaded\"};\n\n auto& e = st.cl3->GetOrCreateFile(args[0]);\n e.src = MakeSmart<DumpableSource>(Source::FromFile(args[1]));\n }};\n Option remove_file_opt{\n lgrp, \"remove-file\", 1, \"NAME\", \"Removes NAME from cl3 archive\",\n [&](auto&& args)\n {\n mode = Mode::MANUAL;\n if (!st.cl3) throw InvalidParam{\"no cl3 loaded\"};\n auto& entries = st.cl3->entries;\n auto e = entries.find(args.front());\n if (e == entries.end())\n throw InvalidParam{\"specified file not found\"};\n else\n entries.erase(e);\n }};\n Option set_link_opt{\n lgrp, \"set-link\", 3, \"NAME ID DEST\", \"Sets link at NAME, ID to DEST\",\n [&](auto&& args)\n {\n mode = Mode::MANUAL;\n if (!st.cl3) throw InvalidParam{\"no cl3 loaded\"};\n auto& entries = st.cl3->entries;\n auto e = entries.find(args[0]);\n auto i = std::stoul(args[1]);\n auto e2 = entries.find(args[2]);\n if (e == entries.end() || e2 == entries.end())\n throw InvalidParam{\"specified file not found\"};\n\n if (i < e->links.size())\n e->links[i] = &entries[entries.index_of(e2)];\n else if (i == e->links.size())\n e->links.push_back(&entries[entries.index_of(e2)]);\n else\n throw InvalidParam{\"invalid link id\"};\n }};\n Option remove_link_opt{\n lgrp, \"remove-link\", 2, \"NAME ID\", \"Remove link ID from NAME\",\n [&](auto&& args)\n {\n mode = Mode::MANUAL;\n if (!st.cl3) throw InvalidParam{\"no cl3 loaded\"};\n auto& entries = st.cl3->entries;\n auto e = entries.find(args[0]);\n auto i = std::stoul(args[1]);\n if (e == entries.end())\n throw InvalidParam{\"specified file not found\"};\n\n if (i < e->links.size())\n e->links.erase(e->links.begin() + i);\n else\n throw InvalidParam{\"invalid link id\"};\n }};\n Option inspect_opt{\n lgrp, \"inspect\", 1, \"OUT|-\",\n \"Inspects currently loaded file into OUT or stdout\",\n [&](auto&& args)\n {\n mode = Mode::MANUAL;\n if (!st.dump) throw InvalidParam{\"No file loaded\"};\n ShellInspect(st.dump.get(), args.front());\n }};\n Option inspect_stcm_opt{\n lgrp, \"inspect-stcm\", 1, \"OUT|-\",\n \"Inspects only the stcm portion of the currently loaded file into OUT or stdout\",\n [&](auto&& args)\n {\n mode = Mode::MANUAL;\n EnsureStcm(st);\n ShellInspect(st.stcm, args.front());\n }};\n Option parse_stcmp_opt{\n lgrp, \"parse-stcm\", 0, nullptr,\n \"Parse STCM-inside-CL3 (usually done automatically)\",\n [&](auto&&)\n {\n mode = Mode::MANUAL;\n EnsureStcm(st);\n }};\n\n Option export_txt_opt{\n lgrp, \"export-txt\", 1, \"OUT_FILE|-\", \"Export text to OUT_FILE or stdout\",\n [&](auto&& args)\n {\n mode = Mode::MANUAL;\n EnsureTxt(st);\n ShellInspectGen(st.txt, args.front(),\n [](auto& x, auto&& y) { x->WriteTxt(y); });\n }};\n Option import_txt_opt{\n lgrp, \"import-txt\", 1, \"IN_FILE|-\", \"Read text from IN_FILE or stdin\",\n [&](auto&& args)\n {\n mode = Mode::MANUAL;\n EnsureTxt(st);\n auto fname = args.front();\n if (fname[0] == '-' && fname[1] == '\\0')\n st.txt->ReadTxt(std::cin);\n else\n st.txt->ReadTxt(OpenIn(fname));\n if (st.stcm) st.stcm->Fixup();\n }};\n\n#if LIBSHIT_WITH_LUA\n Option lua{\n lgrp, \"lua\", 'i', 0, nullptr, \"Interactive lua prompt\",\n [&](auto&&)\n {\n Lua::State vm;\n std::string str;\n\n // use print (I'm lazy to write my own)\n lua_getglobal(vm, \"print\"); // 1\n lua_getglobal(vm, \"debug\"); // 2\n lua_getfield(vm, 2, \"traceback\"); // 3\n lua_remove(vm, 2); // 2 = traceback\n\n auto prompt = isatty(0);\n\n while ((prompt && std::cout << \"> \", std::getline(std::cin, str)))\n {\n // if input starts with \"> \" it's a copy-pasted prompt, remove\n if (boost::algorithm::starts_with(str, \"> \"))\n str.erase(0, 2);\n\n lua_pushvalue(vm, 1); // 3 // push print\n if ((luaL_loadstring(vm, (\"return \"+str).c_str()) &&\n (lua_pop(vm, 1), luaL_loadstring(vm, str.c_str()))) || // 4\n lua_pcall(vm, 0, LUA_MULTRET, 2)) // 3+?\n {\n Logger::Log(\"lua\", Logger::ERROR, nullptr, 0, nullptr)\n << lua_tostring(vm, -1) << std::endl;\n lua_pop(vm, 2);\n }\n else\n {\n auto top = lua_gettop(vm);\n if (top > 3)\n lua_call(vm, top-3, 0);\n else\n lua_pop(vm, 1);\n }\n }\n }};\n Option lua_script{\n lgrp, \"lua-script\", 'L', 1, \"FILE\", \"Run lua script\",\n [&](auto&& args)\n {\n Lua::State vm;\n lua_getglobal(vm, \"debug\"); // +1\n lua_getfield(vm, -1, \"traceback\"); // +2\n if (luaL_loadfile(vm, args[0]) || lua_pcall(vm, 0, 0, -2))\n Logger::Log(\"lua\", Logger::ERROR, nullptr, 0, nullptr)\n << lua_tostring(vm, -1) << std::endl;\n }};\n#endif\n\n boost::filesystem::path self{argv[0]};\n if (boost::iequals(self.filename().string(), \"cl3-tool\")\n#if LIBSHIT_OS_IS_WINDOWS\n || boost::iequals(self.filename().string(), \"cl3-tool.exe\")\n#endif\n )\n mode = Mode::AUTO_CL3;\n\n parser.SetVersion(\"NepTools stcm-editor v\" NEPTOOLS_VERSION);\n parser.SetUsage(\"[--options] [<file/directory>...]\");\n parser.SetShowHelpOnNoOptions();\n parser.SetNonArgHandler(FUNC<DoAuto>);\n\n try { parser.Run(argc, argv); }\n catch (const Exit& e) { return !e.success; }\n catch (...)\n {\n ERR << \"Fatal error, aborting\\n\"\n << Libshit::PrintException(Libshit::Logger::HasAnsiColor())\n << std::endl;\n return 2;\n }\n return auto_failed;\n}\n" }, { "alpha_fraction": 0.6011754870414734, "alphanum_fraction": 0.6062132716178894, "avg_line_length": 21.903846740722656, "blob_id": "b8feb852bb3307dc37a7269fd62d32eca1fba970", "content_id": "f3d322a4b5728f720059e81922409fe3a1bac4f3", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1191, "license_type": "permissive", "max_line_length": 71, "num_lines": 52, "path": "/src/format/cstring_item.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"cstring_item.hpp\"\n#include \"raw_item.hpp\"\n#include \"../sink.hpp\"\n\n#include <libshit/char_utils.hpp>\n\nnamespace Neptools\n{\n\n CStringItem::CStringItem(Key k, Context& ctx, const Source& src)\n : Item{k, ctx}, string{src.PreadCString(0)}\n {}\n\n CStringItem& CStringItem::CreateAndInsert(ItemPointer ptr)\n {\n auto x = RawItem::GetSource(ptr, -1);\n return x.ritem.SplitCreate<CStringItem>(ptr.offset, x.src);\n }\n\n void CStringItem::Dump_(Sink& sink) const\n {\n sink.WriteCString(string);\n }\n\n void CStringItem::Inspect_(std::ostream& os, unsigned indent) const\n {\n Item::Inspect_(os, indent);\n os << \"c_string(\" << Libshit::Quoted(string) << ')';\n }\n\n std::string CStringItem::GetLabelName(std::string string)\n {\n size_t iptr = 0, optr = 0;\n bool last_valid = false;\n for (size_t len = string.length(); iptr < len && optr < 16; ++iptr)\n if (isalnum(string[iptr]))\n {\n string[optr++] = string[iptr];\n last_valid = true;\n }\n else if (last_valid)\n {\n string[optr++] = '_';\n last_valid = false;\n }\n string.resize(optr);\n return \"str_\" + string;\n }\n\n}\n\n#include \"cstring_item.binding.hpp\"\n" }, { "alpha_fraction": 0.5861912369728088, "alphanum_fraction": 0.5934590101242065, "avg_line_length": 28.451505661010742, "blob_id": "bc0b11c33e92d4a4d4dde1b0453e298f5237f46a", "content_id": "48ab5ddde58a4c51c51741a5b78b279c3464312d", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8806, "license_type": "permissive", "max_line_length": 90, "num_lines": 299, "path": "/src/dynamic_struct.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_98C06485_8AE9_47DA_B99F_62CA5AF00FF4\n#define UUID_98C06485_8AE9_47DA_B99F_62CA5AF00FF4\n#pragma once\n\n#include \"utils.hpp\"\n\n#include <libshit/meta.hpp>\n#include <libshit/lua/intrusive_object.hpp>\n#include <libshit/lua/value_object.hpp>\n\n#include <atomic>\n#include <cstdint>\n#include <iostream>\n#include <memory>\n#include <typeindex>\n#include <vector>\n#include <boost/intrusive_ptr.hpp>\n\nnamespace Neptools\n{\n\n template <typename Item, typename... Rest> struct IndexOf;\n template <typename Item, typename... Rest>\n struct IndexOf<Item, Item, Rest...>\n : std::integral_constant<size_t, 0> {};\n\n template <typename Item, typename Head, typename... Rest>\n struct IndexOf<Item, Head, Rest...>\n : std::integral_constant<size_t, 1 + IndexOf<Item, Rest...>::value> {};\n\n template <typename Item, typename... Args>\n constexpr auto IndexOfV = IndexOf<Item, Args...>::value;\n\n static_assert(IndexOfV<int, float, double, int> == 2);\n\n template <typename... Args>\n class LIBSHIT_LUAGEN(\n post_register = \"::Neptools::DynamicStructLua</*$= template_args */>::Register(bld);\")\n DynamicStruct final : public Libshit::Lua::IntrusiveObject\n {\n LIBSHIT_LUA_CLASS;\n private:\n template <typename Ret, size_t I, typename T, typename... TRest,\n typename Thiz, typename Fun, typename... FunArgs>\n static Ret VisitHlp(Thiz thiz, size_t i, Fun&& fun, FunArgs&&... args)\n {\n if (thiz->type->items[i].idx == I)\n return fun(thiz->template Get<T>(i), thiz->GetSize(i),\n std::forward<FunArgs>(args)...);\n else\n return VisitHlp<Ret, I+1, TRest...>(\n thiz, i, std::forward<Fun>(fun), std::forward<FunArgs>(args)...);\n }\n\n template <typename Ret, size_t I, typename Thiz, typename Fun,\n typename... FunArgs>\n static Ret VisitHlp(Thiz, size_t, Fun&&, FunArgs&&...) { abort(); }\n\n public:\n template <typename T>\n LIBSHIT_NOLUA static constexpr size_t GetIndexFromType()\n { return IndexOfV<T, Args...>; }\n\n static constexpr const size_t SIZE_OF[] = { sizeof(Args)... };\n static constexpr const size_t ALIGN_OF[] = { alignof(Args)... };\n\n struct Type final : public Libshit::Lua::IntrusiveObject\n {\n LIBSHIT_LUA_CLASS;\n public:\n Type(const Type&) = delete;\n void operator=(const Type&) = delete;\n ~Type() = delete;\n\n LIBSHIT_NOLUA mutable std::atomic<size_t> refcount;\n LIBSHIT_LUAGEN(get=true) LIBSHIT_LUAGEN(get=true,name=\"__len\")\n size_t item_count;\n LIBSHIT_LUAGEN(get=true) size_t byte_size;\n struct Item\n {\n size_t idx;\n size_t size;\n size_t offset;\n };\n LIBSHIT_NOLUA Item items[1];\n };\n static_assert(std::is_standard_layout_v<Type>);\n using TypePtr = boost::intrusive_ptr<const Type>;\n\n friend void intrusive_ptr_add_ref(const Type* t)\n { t->refcount.fetch_add(1, std::memory_order_relaxed); }\n\n friend void intrusive_ptr_release(const Type* t)\n {\n if (t->refcount.fetch_sub(1, std::memory_order_acq_rel) == 1)\n ::operator delete(const_cast<Type*>(t));\n }\n\n class TypeBuilder final : public Libshit::Lua::ValueObject\n {\n LIBSHIT_LUA_CLASS;\n public:\n TypeBuilder() = default; // force lua ctor\n\n LIBSHIT_NOLUA auto& GetDesc() { return desc; }\n LIBSHIT_NOLUA const auto& GetDesc() const { return desc; }\n\n void Reserve(size_t size) { desc.reserve(size); }\n\n template <typename T>\n LIBSHIT_NOLUA void Add(size_t size = sizeof(T))\n { desc.emplace_back(IndexOfV<T, Args...>, size); }\n\n LIBSHIT_NOLUA void Add(size_t i, size_t size)\n {\n LIBSHIT_ASSERT_MSG(i < sizeof...(Args), \"index out of range\");\n desc.push_back({i, size});\n }\n\n TypePtr Build() const\n {\n auto ptr = operator new(\n sizeof(Type) + (desc.size() - 1) * sizeof(typename Type::Item));\n boost::intrusive_ptr<Type> ret{static_cast<Type*>(ptr), false};\n ret->refcount.store(1, std::memory_order_relaxed);\n ret->item_count = desc.size();\n\n size_t offs = 0;\n for (size_t i = 0; i < desc.size(); ++i)\n {\n ret->items[i].idx = desc[i].first;\n ret->items[i].size = desc[i].second;\n ret->items[i].offset = offs;\n\n offs += desc[i].second;\n auto al = ALIGN_OF[desc[i].first];\n offs = (offs + al - 1) / al * al;\n }\n ret->byte_size = offs;\n\n return ret;\n }\n\n private:\n std::vector<std::pair<size_t, size_t>> desc;\n };\n\n // actual class begin\n LIBSHIT_LUAGEN(result_type=\n \"::boost::intrusive_ptr<::Neptools::DynamicStruct</*$= cls.template_args */>>\")\n static boost::intrusive_ptr<DynamicStruct> New(TypePtr type)\n {\n auto ptr = ::operator new(sizeof(DynamicStruct) + type->byte_size - 1);\n try\n {\n auto obj = new (ptr) DynamicStruct{std::move(type)};\n return {obj, false};\n }\n catch (...)\n {\n ::operator delete(ptr);\n throw;\n }\n }\n\n DynamicStruct(const DynamicStruct&) = delete;\n void operator=(const DynamicStruct&) = delete;\n ~DynamicStruct()\n {\n if (type)\n ForEach(Destroy{});\n }\n\n LIBSHIT_LUAGEN() LIBSHIT_LUAGEN(name=\"__len\")\n size_t GetSize() const noexcept { return type->item_count; }\n LIBSHIT_NOLUA size_t GetSize(size_t i) const noexcept\n {\n LIBSHIT_ASSERT_MSG(i < GetSize(), \"index out of range\");\n return type->items[i].size;\n }\n LIBSHIT_NOLUA size_t GetTypeIndex(size_t i) const noexcept\n {\n LIBSHIT_ASSERT_MSG(i < GetSize(), \"index out of range\");\n return type->items[i].idx;\n }\n\n template <typename T>\n LIBSHIT_NOLUA bool Is(size_t i) const noexcept\n {\n return GetTypeIndex(i) == GetIndexFromType<T>();\n }\n\n const TypePtr& GetType() const noexcept { return type; }\n LIBSHIT_NOLUA void* GetData() noexcept { return data; }\n LIBSHIT_NOLUA const void* GetData() const noexcept { return data; }\n\n LIBSHIT_NOLUA void* GetData(size_t i) noexcept\n {\n LIBSHIT_ASSERT_MSG(i <= GetSize(), \"index out of range\");\n return &data[type->items[i].offset];\n }\n LIBSHIT_NOLUA const void* GetData(size_t i) const noexcept\n {\n LIBSHIT_ASSERT_MSG(i <= GetSize(), \"index out of range\");\n return &data[type->items[i].offset];\n }\n\n template <typename T>\n LIBSHIT_NOLUA T& Get(size_t i) noexcept\n {\n LIBSHIT_ASSERT_MSG(Is<T>(i), \"specified item is not T\");\n return *reinterpret_cast<T*>(data + type->items[i].offset);\n }\n\n template <typename T>\n LIBSHIT_NOLUA const T& Get(size_t i) const noexcept\n {\n LIBSHIT_ASSERT_MSG(Is<T>(i), \"specified item is not T\");\n return *reinterpret_cast<const T*>(data + type->items[i].offset);\n }\n\n template <typename Ret = void, typename... FunArgs>\n LIBSHIT_NOLUA Ret Visit(size_t i, FunArgs&&... f)\n { return VisitHlp<Ret, 0, Args...>(this, i, std::forward<FunArgs>(f)...); }\n\n template <typename... FunArgs>\n LIBSHIT_NOLUA void ForEach(FunArgs&&... f)\n {\n for (size_t i = 0; i < type->item_count; ++i)\n Visit(i, std::forward<FunArgs>(f)...);\n }\n\n // const version\n template <typename Ret = void, typename... FunArgs>\n LIBSHIT_NOLUA Ret Visit(size_t i, FunArgs&&... f) const\n { return VisitHlp<Ret, 0, Args...>(this, i, std::forward<FunArgs>(f)...); }\n\n template <typename... FunArgs>\n LIBSHIT_NOLUA void ForEach(FunArgs&&... args) const\n {\n for (size_t i = 0; i < type->item_count; ++i)\n Visit(i, std::forward<FunArgs>(args)...);\n }\n\n private:\n DynamicStruct(TypePtr type) : type{std::move(type)}\n {\n size_t i = 0;\n try\n {\n for (i = 0; i < this->type->item_count; ++i)\n Visit(i, Make{});\n }\n catch (...)\n {\n while (i > 0) Visit(--i, Destroy{});\n throw;\n }\n }\n\n struct Make\n {\n template <typename T>\n void operator()(T& x, size_t)\n { new (&x) T; }\n };\n\n struct Destroy\n {\n template <typename T>\n void operator()(T& x, size_t)\n { x.~T(); }\n };\n\n TypePtr type;\n mutable std::atomic<size_t> refcount{1};\n char data[1];\n\n friend void intrusive_ptr_add_ref(const DynamicStruct* t)\n { t->refcount.fetch_add(1, std::memory_order_relaxed); }\n\n friend void intrusive_ptr_release(const DynamicStruct* t)\n {\n if (t->refcount.fetch_sub(1, std::memory_order_acq_rel) == 1)\n {\n t->~DynamicStruct();\n ::operator delete(const_cast<DynamicStruct*>(t));\n }\n }\n };\n\n template <typename... Args>\n constexpr const size_t DynamicStruct<Args...>::SIZE_OF[];\n\n template <typename... Args>\n constexpr const size_t DynamicStruct<Args...>::ALIGN_OF[];\n\n}\n#endif\n" }, { "alpha_fraction": 0.6331994533538818, "alphanum_fraction": 0.7242302298545837, "avg_line_length": 24.758621215820312, "blob_id": "e4a82591485513b3c31a44c944e1eac5407168f6", "content_id": "fa2367fee83f2047782b4f9089ed47ec17bbc971", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 747, "license_type": "permissive", "max_line_length": 70, "num_lines": 29, "path": "/src/utils.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_9AE0723F_DD0B_434B_8880_D7981FAF1F20\n#define UUID_9AE0723F_DD0B_434B_8880_D7981FAF1F20\n#pragma once\n\n#include <boost/filesystem/path.hpp>\n\n#include <cstdint>\n#include <cstdlib>\n#include <iosfwd>\n\nnamespace Neptools\n{\n class Source; // fwd\n\n using Byte = unsigned char;\n\n using FilePosition = std::uint64_t;\n using FileMemSize = std::size_t;\n\n static constexpr const std::size_t MEM_CHUNK = 8*1024; // 8KiB\n static constexpr const std::size_t MMAP_CHUNK = 128*1024; // 128KiB\n static constexpr const std::size_t MMAP_LIMIT = 1*1024*1024; // 1MiB\n\n std::ofstream OpenOut(const boost::filesystem::path& pth);\n std::ifstream OpenIn(const boost::filesystem::path& pth);\n\n void DumpBytes(std::ostream& os, Source data);\n}\n#endif\n" }, { "alpha_fraction": 0.5925071835517883, "alphanum_fraction": 0.5936599373817444, "avg_line_length": 23.322429656982422, "blob_id": "2a1e1fbe90d0756ad8f4ce137f5bb0b04984d027", "content_id": "b3d673e2f86c373e2dbe81999bb450704b8f866e", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5205, "license_type": "permissive", "max_line_length": 85, "num_lines": 214, "path": "/src/format/item.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"item.hpp\"\n#include \"context.hpp\"\n#include \"raw_item.hpp\"\n#include \"../utils.hpp\"\n\n#include <libshit/char_utils.hpp>\n\n#include <algorithm>\n#include <iostream>\n\n#if LIBSHIT_WITH_LUA && !defined(LIBSHIT_BINDING_GENERATOR)\n# include \"format/builder.lua.h\"\n#endif\n\n#define LIBSHIT_LOG_NAME \"item\"\n#include <libshit/logger_helper.hpp>\n\nnamespace Neptools\n{\n\n Item::~Item()\n {\n Item::Dispose();\n }\n\n void Item::Inspect_(std::ostream& os, unsigned indent) const\n {\n for (const auto& it : GetLabels())\n {\n os << \"label(\" << Libshit::Quoted(it.GetName());\n if (it.GetPtr().offset != 0)\n os << \", \" << it.GetPtr().offset;\n os << \")\\n\";\n }\n Indent(os, indent);\n }\n\n void Item::UpdatePosition(FilePosition npos)\n {\n position = npos;\n Fixup();\n }\n\n void Item::Replace_(const Libshit::NotNull<Libshit::SmartPtr<Item>>& nitem)\n {\n auto ctx = GetContext();\n // move labels\n nitem->labels.swap(labels); // intrusive move op= does this... (but undocumented)\n for (auto& l : nitem->labels)\n l.ptr.item = nitem.get();\n\n // update pointermap\n nitem->position = position;\n auto it = ctx->pmap.find(position);\n if (it != ctx->pmap.end() && it->second == this)\n it->second = nitem.get();\n\n auto& list = GetParent()->GetChildren();\n auto self = Iterator();\n\n list.insert(self, *nitem);\n list.erase(self);\n }\n\n void Item::Removed()\n {\n auto ctx = GetContextMaybe();\n if (!ctx) return;\n auto it = ctx->pmap.find(position);\n if (it != ctx->pmap.end() && it->second == this)\n ctx->pmap.erase(it);\n }\n\n void Item::Slice(SliceSeq seq)\n {\n LIBSHIT_ASSERT(std::is_sorted(seq.begin(), seq.end(),\n [](const auto& a, const auto& b) { return a.second < b.second; }));\n\n Libshit::SmartPtr<Item> do_not_delete_this_until_returning{this};\n\n LabelsContainer lbls{std::move(labels)};\n auto ctx = GetContext();\n auto& pmap = ctx->pmap;\n auto empty = pmap.empty();\n\n auto& list = GetParent()->GetChildren();\n auto it = Iterator();\n it = list.erase(it);\n\n FilePosition offset = 0;\n auto base_pos = position;\n\n auto label = lbls.unlink_leftmost_without_rebalance();\n FilePosition last_offset = 0;\n for (auto& el : seq)\n {\n LIBSHIT_ASSERT(el.first->labels.empty());\n while (label && (label->ptr.offset < el.second ||\n (label->ptr.offset == el.second &&\n label->ptr.offset == last_offset)))\n {\n label->ptr.item = el.first.get();\n label->ptr.offset -= offset;\n el.first->labels.insert(*label);\n\n label = lbls.unlink_leftmost_without_rebalance();\n }\n last_offset = el.second;\n\n // move in place\n el.first->position = base_pos + offset;\n list.insert(it, *el.first);\n\n // add to pmap if needed\n if (!empty)\n // may throw! but only used during parsing, and an exception there\n // is fatal, so it's not really a problem\n pmap.emplace(el.first->position, &*el.first);\n\n offset = el.second;\n }\n LIBSHIT_ASSERT(label == nullptr);\n }\n\n void Item::Dispose() noexcept\n {\n LIBSHIT_ASSERT(labels.empty() && !GetParent());\n if (auto ctx = GetContextMaybe())\n {\n auto it = ctx->pmap.find(position);\n if (it != ctx->pmap.end() && it->second == this)\n {\n WARN << \"Item \" << this << \" unlinked from pmap in Dispose\" << std::endl;\n ctx->pmap.erase(it);\n }\n }\n\n context.reset();\n }\n\n std::ostream& operator<<(std::ostream& os, const Item& item)\n {\n item.Inspect(os);\n return os;\n }\n\n void ItemWithChildren::Dump_(Sink& sink) const\n {\n for (auto& c : GetChildren())\n c.Dump(sink);\n }\n\n void ItemWithChildren::InspectChildren(std::ostream& os, unsigned indent) const\n {\n if (GetChildren().empty()) return;\n\n os << \":build(function()\\n\";\n for (auto& c : GetChildren())\n {\n c.Inspect_(os, indent+1);\n os << '\\n';\n }\n Indent(os, indent) << \"end)\";\n }\n\n\n FilePosition ItemWithChildren::GetSize() const\n {\n FilePosition ret = 0;\n for (auto& c : GetChildren())\n ret += c.GetSize();\n return ret;\n }\n\n void ItemWithChildren::Fixup_(FilePosition offset)\n {\n FilePosition pos = position + offset;\n for (auto& c : GetChildren())\n {\n c.UpdatePosition(pos);\n pos += c.GetSize();\n }\n }\n\n void ItemWithChildren::MoveNextToChild(size_t size) noexcept\n {\n auto& list = GetParent()->GetChildren();\n // make sure we have a ref when erasing...\n Libshit::SmartPtr<Item> nchild = &Libshit::asserted_cast<RawItem&>(\n *++Iterator()).Split(0, size);\n list.erase(nchild->Iterator());\n GetChildren().push_back(*nchild);\n }\n\n void ItemWithChildren::Dispose() noexcept\n {\n GetChildren().clear();\n Item::Dispose();\n }\n\n void ItemWithChildren::Removed()\n {\n Item::Removed();\n for (auto& ch : GetChildren()) ch.Removed();\n }\n\n}\n\n#include <libshit/container/parent_list.lua.hpp>\n#include <libshit/lua/table_ret_wrap.hpp>\n#include <libshit/lua/owned_shared_ptr_wrap.hpp>\nLIBSHIT_PARENT_LIST_LUAGEN(\n item, false, Neptools::Item, Neptools::ItemListTraits);\n#include \"item.binding.hpp\"\n" }, { "alpha_fraction": 0.6626213788986206, "alphanum_fraction": 0.6626213788986206, "avg_line_length": 34.31428527832031, "blob_id": "aaedc969922c17419aa0bac4326d44c4c311df2c", "content_id": "f0fa366b6c2c49af63c99fc1c57a650582728078", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1236, "license_type": "permissive", "max_line_length": 123, "num_lines": 35, "path": "/src/dumpable.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Dumpable::TYPE_NAME[] = \"neptools.dumpable\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.dumpable\n template<>\n void TypeRegisterTraits<::Neptools::Dumpable>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n static_cast<void (::Neptools::Dumpable::*)()>(&::Neptools::Dumpable::Fixup)\n >(\"fixup\");\n bld.AddFunction<\n static_cast<::Neptools::FilePosition (::Neptools::Dumpable::*)() const>(&::Neptools::Dumpable::GetSize)\n >(\"get_size\");\n bld.AddFunction<\n static_cast<void (::Neptools::Dumpable::*)(::Neptools::Sink &) const>(&::Neptools::Dumpable::Dump),\n static_cast<void (::Neptools::Dumpable::*)(const ::boost::filesystem::path &) const>(&::Neptools::Dumpable::Dump)\n >(\"dump\");\n bld.AddFunction<\n static_cast<void (::Neptools::Dumpable::*)(const ::boost::filesystem::path &) const>(&::Neptools::Dumpable::Inspect),\n static_cast<std::string (::Neptools::Dumpable::*)() const>(&::Neptools::Dumpable::Inspect)\n >(\"inspect\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Dumpable> reg_neptools_dumpable;\n\n}\n#endif\n" }, { "alpha_fraction": 0.5742342472076416, "alphanum_fraction": 0.5960850715637207, "avg_line_length": 29.87751007080078, "blob_id": "9adbf9aff49e4d42567d825eeb8070d3f1021f0c", "content_id": "bdaf584ac4de1f65e2529ea29654712462df608d", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 15377, "license_type": "permissive", "max_line_length": 83, "num_lines": 498, "path": "/src/format/cl3.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"cl3.hpp\"\n#include \"stcm/file.hpp\"\n#include \"../open.hpp\"\n\n#include <libshit/char_utils.hpp>\n#include <libshit/except.hpp>\n#include <libshit/container/ordered_map.lua.hpp>\n#include <libshit/container/vector.lua.hpp>\n\n#include <fstream>\n#include <boost/filesystem/operations.hpp>\n\nnamespace Neptools\n{\n\n void Cl3::Header::Validate(FilePosition file_size) const\n {\n#define VALIDATE(x) LIBSHIT_VALIDATE_FIELD(\"Cl3::Header\", x)\n VALIDATE(memcmp(magic, \"CL3\", 3) == 0);\n VALIDATE(endian == 'L' || endian == 'B');\n VALIDATE(field_04 == 0);\n VALIDATE(field_08 == 3);\n VALIDATE(sections_offset + sections_count * sizeof(Section) <= file_size);\n#undef VALIDATE\n }\n\n void endian_reverse_inplace(Cl3::Header& hdr) noexcept\n {\n boost::endian::endian_reverse_inplace(hdr.field_04);\n boost::endian::endian_reverse_inplace(hdr.field_08);\n boost::endian::endian_reverse_inplace(hdr.sections_count);\n boost::endian::endian_reverse_inplace(hdr.sections_offset);\n boost::endian::endian_reverse_inplace(hdr.field_14);\n }\n\n void Cl3::Section::Validate(FilePosition file_size) const\n {\n#define VALIDATE(x) LIBSHIT_VALIDATE_FIELD(\"Cl3::Section\", x)\n VALIDATE(name.is_valid());\n VALIDATE(data_offset <= file_size);\n VALIDATE(data_offset + data_size <= file_size);\n VALIDATE(field_2c == 0);\n VALIDATE(field_30 == 0 && field_34 == 0 && field_38 == 0 && field_3c == 0);\n VALIDATE(field_40 == 0 && field_44 == 0 && field_48 == 0 && field_4c == 0);\n#undef VALIDATE\n }\n\n void endian_reverse_inplace(Cl3::Section& sec) noexcept\n {\n boost::endian::endian_reverse_inplace(sec.count);\n boost::endian::endian_reverse_inplace(sec.data_size);\n boost::endian::endian_reverse_inplace(sec.data_offset);\n boost::endian::endian_reverse_inplace(sec.field_2c);\n boost::endian::endian_reverse_inplace(sec.field_30);\n boost::endian::endian_reverse_inplace(sec.field_34);\n boost::endian::endian_reverse_inplace(sec.field_38);\n boost::endian::endian_reverse_inplace(sec.field_3c);\n boost::endian::endian_reverse_inplace(sec.field_40);\n boost::endian::endian_reverse_inplace(sec.field_44);\n boost::endian::endian_reverse_inplace(sec.field_48);\n boost::endian::endian_reverse_inplace(sec.field_4c);\n }\n\n void Cl3::FileEntry::Validate(uint32_t block_size) const\n {\n#define VALIDATE(x) LIBSHIT_VALIDATE_FIELD(\"Cl3::FileEntry\", x)\n VALIDATE(name.is_valid());\n VALIDATE(data_offset <= block_size);\n VALIDATE(data_offset + data_size <= block_size);\n VALIDATE(field_214 == 0 && field_218 == 0 && field_21c == 0);\n VALIDATE(field_220 == 0 && field_224 == 0 && field_228 == 0 && field_22c == 0);\n#undef VALIDATE\n }\n\n void endian_reverse_inplace(Cl3::FileEntry& entry) noexcept\n {\n boost::endian::endian_reverse_inplace(entry.field_200);\n boost::endian::endian_reverse_inplace(entry.data_offset);\n boost::endian::endian_reverse_inplace(entry.data_size);\n boost::endian::endian_reverse_inplace(entry.link_start);\n boost::endian::endian_reverse_inplace(entry.link_count);\n boost::endian::endian_reverse_inplace(entry.field_214);\n boost::endian::endian_reverse_inplace(entry.field_218);\n boost::endian::endian_reverse_inplace(entry.field_21c);\n boost::endian::endian_reverse_inplace(entry.field_220);\n boost::endian::endian_reverse_inplace(entry.field_224);\n boost::endian::endian_reverse_inplace(entry.field_228);\n boost::endian::endian_reverse_inplace(entry.field_22c);\n }\n\n void Cl3::LinkEntry::Validate(uint32_t i, uint32_t file_count) const\n {\n#define VALIDATE(x) LIBSHIT_VALIDATE_FIELD(\"Cl3::LinkEntry\", x)\n VALIDATE(field_00 == 0);\n VALIDATE(linked_file_id < file_count);\n VALIDATE(link_id == i);\n VALIDATE(field_0c == 0);\n VALIDATE(field_10 == 0 && field_14 == 0 && field_18 == 0 && field_1c == 0);\n#undef VALIDATE\n }\n\n void endian_reverse_inplace(Cl3::LinkEntry& entry) noexcept\n {\n boost::endian::endian_reverse_inplace(entry.field_00);\n boost::endian::endian_reverse_inplace(entry.linked_file_id);\n boost::endian::endian_reverse_inplace(entry.link_id);\n boost::endian::endian_reverse_inplace(entry.field_0c);\n boost::endian::endian_reverse_inplace(entry.field_10);\n boost::endian::endian_reverse_inplace(entry.field_14);\n boost::endian::endian_reverse_inplace(entry.field_18);\n boost::endian::endian_reverse_inplace(entry.field_1c);\n }\n\n void Cl3::Entry::Dispose() noexcept\n {\n links.clear();\n src.reset();\n }\n\n Cl3::Cl3(Source src)\n {\n ADD_SOURCE(Parse_(src), src);\n }\n\n#if LIBSHIT_WITH_LUA\n Cl3::Cl3(Libshit::Lua::StateRef vm, Endian endian, uint32_t field_14,\n Libshit::Lua::RawTable tbl)\n : endian{endian}, field_14{field_14}\n {\n auto [len, one] = vm.RawLen01(tbl);\n entries.reserve(len);\n bool do_links = false;\n // we need two passes: first add entries, ignoring links\n // then add links when the entries are in place\n // can't do in one pass, as there may be forward links\n vm.Fori(tbl, one, len, [&](size_t, int type)\n {\n if (type == LUA_TTABLE)\n {\n auto [len, one] = vm.RawLen01(-1);\n if (len == 4) // todo: is there a better way??\n {\n do_links = true;\n lua_rawgeti(vm, -1, one); // +1\n lua_rawgeti(vm, -2, one+1); // +2\n lua_rawgeti(vm, -3, one+3); // +3\n entries.emplace_back(\n vm.Get<std::string>(-3),\n vm.Get<uint32_t>(-2),\n vm.Get<Libshit::SmartPtr<Dumpable>>(-1));\n lua_pop(vm, 3);\n return;\n }\n }\n // probably unlikely: try the 3-param ctor, or use existing entry\n entries.push_back(vm.Get<\n Libshit::Lua::AutoTable<Libshit::NotNull<Libshit::SmartPtr<Entry>>>>());\n });\n\n if (do_links)\n {\n vm.Fori(tbl, one, len, [&](size_t i, int type)\n {\n if (type != LUA_TTABLE) return;\n auto [len, one] = vm.RawLen01(-1);\n if (len != 4) return;\n auto t = lua_rawgeti(vm, -1, one+2); // +1\n if (t != LUA_TTABLE) vm.TypeError(false, \"table\", -1);\n\n auto [len2, one2] = vm.RawLen01(-1);\n auto& e = entries[i];\n e.links.reserve(len2);\n vm.Fori(lua_absindex(vm, -1), one2, len2, [&](size_t, int)\n {\n auto it = entries.find(vm.Get<std::string>());\n if (it == entries.end())\n luaL_error(vm, \"invalid cl3 link: '%s' not found\",\n vm.Get<const char*>());\n e.links.push_back(&*it);\n });\n lua_pop(vm, 1);\n });\n }\n Fixup();\n }\n#endif\n\n void Cl3::Dispose() noexcept\n {\n entries.clear();\n }\n\n void Cl3::Parse_(Source& src)\n {\n src.CheckSize(sizeof(Header));\n auto hdr = src.PreadGen<Header>(0);\n endian = hdr.endian == 'L' ? Endian::LITTLE : Endian::BIG;\n ToNative(hdr, endian);\n hdr.Validate(src.GetSize());\n\n field_14 = hdr.field_14;\n\n src.Seek(hdr.sections_offset);\n uint32_t secs = hdr.sections_count;\n\n uint32_t file_offset = 0, file_count = 0, file_size,\n link_offset, link_count = 0;\n for (size_t i = 0; i < secs; ++i)\n {\n auto sec = src.ReadGen<Section>();\n ToNative(sec, endian);\n sec.Validate(src.GetSize());\n\n if (sec.name == \"FILE_COLLECTION\")\n {\n file_offset = sec.data_offset;\n file_count = sec.count;\n file_size = sec.data_size;\n }\n else if (sec.name == \"FILE_LINK\")\n {\n link_offset = sec.data_offset;\n link_count = sec.count;\n LIBSHIT_VALIDATE_FIELD(\n \"Cl3::Section\",\n sec.data_size == link_count * sizeof(LinkEntry));\n }\n }\n\n entries.reserve(file_count);\n src.Seek(file_offset);\n for (uint32_t i = 0; i < file_count; ++i)\n {\n auto e = src.ReadGen<FileEntry>();\n ToNative(e, endian);\n e.Validate(file_size);\n\n entries.emplace_back(\n e.name.c_str(), e.field_200, Libshit::MakeSmart<DumpableSource>(\n src, file_offset+e.data_offset, e.data_size));\n }\n\n src.Seek(file_offset);\n for (uint32_t i = 0; i < file_count; ++i)\n {\n auto e = src.ReadGen<FileEntry>();\n ToNative(e, endian);\n auto& ls = entries[i].links;\n uint32_t lbase = e.link_start;\n uint32_t lcount = e.link_count;\n\n for (uint32_t i = lbase; i < lbase+lcount; ++i)\n {\n auto le = src.PreadGen<LinkEntry>(link_offset + i*sizeof(LinkEntry));\n le.Validate(i - lbase, file_count);\n ls.emplace_back(&entries[le.linked_file_id]);\n }\n }\n }\n\n static constexpr unsigned PAD_BYTES = 0x40;\n static constexpr unsigned PAD = 0x3f;\n void Cl3::Fixup()\n {\n data_size = 0;\n link_count = 0;\n for (auto& e : entries)\n {\n if (e.src)\n {\n e.src->Fixup();\n data_size += e.src->GetSize();\n }\n data_size = (data_size + PAD) & ~PAD;\n link_count += e.links.size();\n }\n }\n\n FilePosition Cl3::GetSize() const\n {\n FilePosition ret = (sizeof(Header)+PAD) & ~PAD;\n ret = (ret+sizeof(Section)*2+PAD) & ~PAD;\n ret = (ret+sizeof(FileEntry)*entries.size()+PAD) & ~PAD;\n ret += data_size+sizeof(LinkEntry)*link_count;\n return ret;\n }\n\n Cl3::Entry& Cl3::GetOrCreateFile(std::string_view fname)\n {\n auto it = entries.find(fname, std::less<>{});\n if (it == entries.end())\n {\n entries.emplace_back(std::string{fname});\n return entries.back();\n }\n return *it;\n }\n\n void Cl3::ExtractTo(const boost::filesystem::path& dir) const\n {\n if (!boost::filesystem::is_directory(dir))\n boost::filesystem::create_directories(dir);\n\n for (const auto& e : entries)\n {\n if (!e.src) continue;\n auto sink = Sink::ToFile(dir / e.name.c_str(), e.src->GetSize());\n e.src->Dump(*sink);\n }\n }\n\n void Cl3::UpdateFromDir(const boost::filesystem::path& dir)\n {\n for (auto& e : boost::filesystem::directory_iterator(dir))\n GetOrCreateFile(e.path().filename().string()).src =\n Libshit::MakeSmart<DumpableSource>(Source::FromFile(e));\n\n for (auto it = entries.begin(); it != entries.end(); )\n if (!boost::filesystem::exists(dir / it->name))\n it = entries.erase(it);\n else\n ++it;\n }\n\n uint32_t Cl3::IndexOf(const Libshit::WeakSmartPtr<Entry>& ptr) const noexcept\n {\n auto sptr = ptr.lock();\n if (!sptr) return -1;\n auto it = entries.checked_iterator_to(*sptr);\n if (it == entries.end()) return -1;\n return entries.index_of(it);\n }\n\n void Cl3::Inspect_(std::ostream& os, unsigned indent) const\n {\n os << \"neptools.cl3(neptools.endian.\" << ToString(endian) << \", \"\n << field_14 << \", {\\n\";\n for (auto& e : entries)\n {\n Indent(os, indent+1)\n << '{' << Libshit::Quoted(e.name) << \", \" << e.field_200 << \", {\";\n bool first = true;\n for (auto& l : e.links)\n {\n if (!first) os << \", \";\n first = false;\n auto ll = l.lock();\n if (ll) Libshit::DumpBytes(os, ll->name);\n else os << \"nil\";\n }\n os << \"}, \";\n if (e.src)\n e.src->Inspect(os, indent+1);\n else\n os << \"nil\";\n os << \"},\\n\";\n }\n os << \"})\";\n }\n\n // workaround, revert to template if/when\n // https://github.com/boostorg/endian/issues/41 is fixed\n#define GEN_REVERSE(T) \\\n static T endian_reverse(T t) noexcept \\\n { \\\n endian_reverse_inplace(t); \\\n return t; \\\n }\n GEN_REVERSE(Cl3::Section);\n GEN_REVERSE(Cl3::FileEntry);\n GEN_REVERSE(Cl3::LinkEntry);\n#undef GEN_REVERSE\n\n void Cl3::Dump_(Sink& sink) const\n {\n auto sections_offset = (sizeof(Header)+PAD) & ~PAD;\n auto files_offset = (sections_offset+sizeof(Section)*2+PAD) & ~PAD;\n auto data_offset = (files_offset+sizeof(FileEntry)*entries.size()+PAD) & ~PAD;\n auto link_offset = data_offset + data_size;\n\n Header hdr;\n memcpy(hdr.magic, \"CL3\", 3);\n hdr.endian = endian == Endian::LITTLE ? 'L' : 'B';\n hdr.field_04 = 0;\n hdr.field_08 = 3;\n hdr.sections_count = 2;\n hdr.sections_offset = sections_offset;\n hdr.field_14 = field_14;\n FromNative(hdr, endian);\n sink.WriteGen(hdr);\n sink.Pad(sections_offset-sizeof(Header));\n\n Section sec;\n memset(&sec, 0, sizeof(Section));\n sec.name = \"FILE_COLLECTION\";\n sec.count = entries.size();\n sec.data_size = link_offset - files_offset;\n sec.data_offset = files_offset;\n sink.WriteGen(FromNativeCopy(sec, endian));\n\n sec.name = \"FILE_LINK\";\n sec.count = link_count;\n sec.data_size = link_count * sizeof(LinkEntry);\n sec.data_offset = link_offset;\n FromNative(hdr, endian);\n sink.WriteGen(sec);\n sink.Pad((PAD_BYTES - ((2*sizeof(Section)) & PAD)) & PAD);\n\n FileEntry fe;\n fe.field_214 = fe.field_218 = fe.field_21c = 0;\n fe.field_220 = fe.field_224 = fe.field_228 = fe.field_22c = 0;\n\n // file entry header\n uint32_t offset = data_offset-files_offset, link_i = 0;\n for (auto& e : entries)\n {\n fe.name = e.name;\n fe.field_200 = e.field_200;\n fe.data_offset = offset;\n auto size = e.src ? e.src->GetSize() : 0;\n fe.data_size = size;\n fe.link_start = link_i;\n fe.link_count = e.links.size();\n sink.WriteGen(FromNativeCopy(fe, endian));\n\n offset = (offset+size+PAD) & ~PAD;\n link_i += e.links.size();\n }\n sink.Pad((PAD_BYTES - ((entries.size()*sizeof(FileEntry)) & PAD)) & PAD);\n\n // file data\n for (auto& e : entries)\n {\n if (!e.src) continue;\n e.src->Dump(sink);\n sink.Pad((PAD_BYTES - (e.src->GetSize() & PAD)) & PAD);\n }\n\n // links\n LinkEntry le;\n memset(&le, 0, sizeof(LinkEntry));\n for (auto& e : entries)\n {\n uint32_t i = 0;\n for (const auto& l : e.links)\n {\n le.linked_file_id = IndexOf(l);\n if (le.linked_file_id == uint32_t(-1))\n LIBSHIT_THROW(std::runtime_error, \"Invalid file link\");\n le.link_id = i++;\n sink.WriteGen(FromNativeCopy(le, endian));\n }\n }\n }\n\n Stcm::File& Cl3::GetStcm()\n {\n auto dat = entries.find(\"main.DAT\", std::less<>{});\n if (dat == entries.end() || !dat->src)\n LIBSHIT_THROW(Libshit::DecodeError, \"Invalid CL3 file: no main.DAT\");\n\n auto stcm = dynamic_cast<Stcm::File*>(dat->src.get());\n if (stcm) return *stcm;\n\n auto src = Libshit::asserted_cast<DumpableSource*>(dat->src.get());\n auto nstcm = Libshit::MakeSmart<Stcm::File>(src->GetSource());\n auto ret = nstcm.get();\n dat->src = std::move(nstcm);\n return *ret;\n }\n\n Libshit::NotNullSharedPtr<TxtSerializable> Cl3::GetDefaultTxtSerializable(\n const Libshit::NotNullSharedPtr<Dumpable>& thiz)\n {\n auto& stcm = GetStcm();\n if (!stcm.GetGbnl())\n LIBSHIT_THROW(Libshit::DecodeError, \"No GBNL found in STCM\");\n return Libshit::NotNullRefCountedPtr<Stcm::File>{&stcm};\n }\n\n static OpenFactory cl3_open{[](const Source& src) -> Libshit::SmartPtr<Dumpable>\n {\n if (src.GetSize() < sizeof(Cl3::Header)) return nullptr;\n char buf[3];\n src.PreadGen(0, buf);\n if (memcmp(buf, \"CL3\", 3) == 0)\n return Libshit::MakeSmart<Cl3>(src);\n else\n return nullptr;\n }};\n\n}\n\nLIBSHIT_ORDERED_MAP_LUAGEN(\n cl3_entry, Neptools::Cl3::Entry, Neptools::Cl3::EntryKeyOfValue);\nLIBSHIT_STD_VECTOR_LUAGEN(\n cl3_entry, Libshit::WeakRefCountedPtr<Neptools::Cl3::Entry>);\n#include \"cl3.binding.hpp\"\n" }, { "alpha_fraction": 0.6419864296913147, "alphanum_fraction": 0.6562076807022095, "avg_line_length": 50.213871002197266, "blob_id": "cd7411da4588dd9840bab17e2dc1c4152b017cdb", "content_id": "180bbbd51a94a4360ea7bb7261b5d0b603ee2427", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8860, "license_type": "permissive", "max_line_length": 181, "num_lines": 173, "path": "/src/source.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Source::TYPE_NAME[] = \"neptools.source\";\n\nconst char ::Neptools::DumpableSource::TYPE_NAME[] = \"neptools.dumpable_source\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.source\n template<>\n void TypeRegisterTraits<::Neptools::Source>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Source>::Make<LuaGetRef<::Neptools::Source>, LuaGetRef<::Neptools::FilePosition>, LuaGetRef<::Neptools::FilePosition>>\n >(\"new\");\n bld.AddFunction<\n static_cast<::Neptools::Source (*)(const ::boost::filesystem::path &)>(::Neptools::Source::FromFile)\n >(\"from_file\");\n bld.AddFunction<\n static_cast<::Neptools::Source (*)(std::string)>(::Neptools::Source::FromMemory),\n static_cast<::Neptools::Source (*)(::boost::filesystem::path, std::string)>(::Neptools::Source::FromMemory)\n >(\"from_memory\");\n bld.AddFunction<\n static_cast<void (::Neptools::Source::*)(::Neptools::FilePosition, ::Neptools::FilePosition) noexcept>(&::Neptools::Source::Slice<Check::Throw>)\n >(\"slice\");\n bld.AddFunction<\n static_cast<::Neptools::FilePosition (::Neptools::Source::*)() const noexcept>(&::Neptools::Source::GetOffset)\n >(\"get_offset\");\n bld.AddFunction<\n static_cast<::Neptools::FilePosition (::Neptools::Source::*)() const noexcept>(&::Neptools::Source::GetOrigSize)\n >(\"get_orig_size\");\n bld.AddFunction<\n static_cast<const ::boost::filesystem::path & (::Neptools::Source::*)() const noexcept>(&::Neptools::Source::GetFileName)\n >(\"get_file_name\");\n bld.AddFunction<\n static_cast<::Neptools::FilePosition (::Neptools::Source::*)() const noexcept>(&::Neptools::Source::GetSize)\n >(\"get_size\");\n bld.AddFunction<\n static_cast<void (::Neptools::Source::*)(::Neptools::FilePosition) noexcept>(&::Neptools::Source::Seek<Check::Throw>)\n >(\"seek\");\n bld.AddFunction<\n static_cast<::Neptools::FilePosition (::Neptools::Source::*)() const noexcept>(&::Neptools::Source::Tell)\n >(\"tell\");\n bld.AddFunction<\n static_cast<::Neptools::FilePosition (::Neptools::Source::*)() const noexcept>(&::Neptools::Source::GetRemainingSize)\n >(\"get_remaining_size\");\n bld.AddFunction<\n static_cast<bool (::Neptools::Source::*)() const noexcept>(&::Neptools::Source::Eof)\n >(\"eof\");\n bld.AddFunction<\n static_cast<void (::Neptools::Source::*)(::Neptools::FilePosition) const>(&::Neptools::Source::CheckSize)\n >(\"check_size\");\n bld.AddFunction<\n static_cast<void (::Neptools::Source::*)(::Neptools::FilePosition) const>(&::Neptools::Source::CheckRemainingSize)\n >(\"check_remaining_size\");\n bld.AddFunction<\n static_cast<std::uint8_t (::Neptools::Source::*)(::Neptools::Endian)>(&::Neptools::Source::ReadUint8<Check::Throw>)\n >(\"read_uint8\");\n bld.AddFunction<\n static_cast<std::uint8_t (::Neptools::Source::*)(::Neptools::FilePosition, ::Neptools::Endian)>(&::Neptools::Source::PreadUint8<Check::Throw>)\n >(\"pread_uint8\");\n bld.AddFunction<\n static_cast<std::uint8_t (::Neptools::Source::*)()>(&::Neptools::Source::ReadLittleUint8<Check::Throw>)\n >(\"read_little_uint8\");\n bld.AddFunction<\n static_cast<std::uint8_t (::Neptools::Source::*)(::Neptools::FilePosition) const>(&::Neptools::Source::PreadLittleUint8<Check::Throw>)\n >(\"pread_little_uint8\");\n bld.AddFunction<\n static_cast<std::uint8_t (::Neptools::Source::*)()>(&::Neptools::Source::ReadBigUint8<Check::Throw>)\n >(\"read_big_uint8\");\n bld.AddFunction<\n static_cast<std::uint8_t (::Neptools::Source::*)(::Neptools::FilePosition) const>(&::Neptools::Source::PreadBigUint8<Check::Throw>)\n >(\"pread_big_uint8\");\n bld.AddFunction<\n static_cast<std::uint16_t (::Neptools::Source::*)(::Neptools::Endian)>(&::Neptools::Source::ReadUint16<Check::Throw>)\n >(\"read_uint16\");\n bld.AddFunction<\n static_cast<std::uint16_t (::Neptools::Source::*)(::Neptools::FilePosition, ::Neptools::Endian)>(&::Neptools::Source::PreadUint16<Check::Throw>)\n >(\"pread_uint16\");\n bld.AddFunction<\n static_cast<std::uint16_t (::Neptools::Source::*)()>(&::Neptools::Source::ReadLittleUint16<Check::Throw>)\n >(\"read_little_uint16\");\n bld.AddFunction<\n static_cast<std::uint16_t (::Neptools::Source::*)(::Neptools::FilePosition) const>(&::Neptools::Source::PreadLittleUint16<Check::Throw>)\n >(\"pread_little_uint16\");\n bld.AddFunction<\n static_cast<std::uint16_t (::Neptools::Source::*)()>(&::Neptools::Source::ReadBigUint16<Check::Throw>)\n >(\"read_big_uint16\");\n bld.AddFunction<\n static_cast<std::uint16_t (::Neptools::Source::*)(::Neptools::FilePosition) const>(&::Neptools::Source::PreadBigUint16<Check::Throw>)\n >(\"pread_big_uint16\");\n bld.AddFunction<\n static_cast<std::uint32_t (::Neptools::Source::*)(::Neptools::Endian)>(&::Neptools::Source::ReadUint32<Check::Throw>)\n >(\"read_uint32\");\n bld.AddFunction<\n static_cast<std::uint32_t (::Neptools::Source::*)(::Neptools::FilePosition, ::Neptools::Endian)>(&::Neptools::Source::PreadUint32<Check::Throw>)\n >(\"pread_uint32\");\n bld.AddFunction<\n static_cast<std::uint32_t (::Neptools::Source::*)()>(&::Neptools::Source::ReadLittleUint32<Check::Throw>)\n >(\"read_little_uint32\");\n bld.AddFunction<\n static_cast<std::uint32_t (::Neptools::Source::*)(::Neptools::FilePosition) const>(&::Neptools::Source::PreadLittleUint32<Check::Throw>)\n >(\"pread_little_uint32\");\n bld.AddFunction<\n static_cast<std::uint32_t (::Neptools::Source::*)()>(&::Neptools::Source::ReadBigUint32<Check::Throw>)\n >(\"read_big_uint32\");\n bld.AddFunction<\n static_cast<std::uint32_t (::Neptools::Source::*)(::Neptools::FilePosition) const>(&::Neptools::Source::PreadBigUint32<Check::Throw>)\n >(\"pread_big_uint32\");\n bld.AddFunction<\n static_cast<std::uint64_t (::Neptools::Source::*)(::Neptools::Endian)>(&::Neptools::Source::ReadUint64<Check::Throw>)\n >(\"read_uint64\");\n bld.AddFunction<\n static_cast<std::uint64_t (::Neptools::Source::*)(::Neptools::FilePosition, ::Neptools::Endian)>(&::Neptools::Source::PreadUint64<Check::Throw>)\n >(\"pread_uint64\");\n bld.AddFunction<\n static_cast<std::uint64_t (::Neptools::Source::*)()>(&::Neptools::Source::ReadLittleUint64<Check::Throw>)\n >(\"read_little_uint64\");\n bld.AddFunction<\n static_cast<std::uint64_t (::Neptools::Source::*)(::Neptools::FilePosition) const>(&::Neptools::Source::PreadLittleUint64<Check::Throw>)\n >(\"pread_little_uint64\");\n bld.AddFunction<\n static_cast<std::uint64_t (::Neptools::Source::*)()>(&::Neptools::Source::ReadBigUint64<Check::Throw>)\n >(\"read_big_uint64\");\n bld.AddFunction<\n static_cast<std::uint64_t (::Neptools::Source::*)(::Neptools::FilePosition) const>(&::Neptools::Source::PreadBigUint64<Check::Throw>)\n >(\"pread_big_uint64\");\n bld.AddFunction<\n static_cast<std::string (::Neptools::Source::*)()>(&::Neptools::Source::ReadCString)\n >(\"read_cstring\");\n bld.AddFunction<\n static_cast<std::string (::Neptools::Source::*)(::Neptools::FilePosition) const>(&::Neptools::Source::PreadCString)\n >(\"pread_cstring\");\n bld.AddFunction<\n static_cast<void (::Neptools::Source::*)(::Neptools::Sink &) const>(&::Neptools::Source::Dump)\n >(\"dump\");\n bld.AddFunction<\n static_cast<std::string (::Neptools::Source::*)() const>(&::Neptools::Source::Inspect)\n >(\"inspect\");\n bld.AddFunction<\n static_cast<::Libshit::Lua::RetNum (*)(::Libshit::Lua::StateRef, ::Neptools::Source &, ::Neptools::FileMemSize)>(&Neptools::LuaRead)\n >(\"read\");\n bld.AddFunction<\n static_cast<::Libshit::Lua::RetNum (*)(::Libshit::Lua::StateRef, ::Neptools::Source &, ::Neptools::FilePosition, ::Neptools::FileMemSize)>(&Neptools::LuaPread)\n >(\"pread\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Source> reg_neptools_source;\n\n // class neptools.dumpable_source\n template<>\n void TypeRegisterTraits<::Neptools::DumpableSource>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::DumpableSource, ::Neptools::Dumpable>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::DumpableSource>::Make<LuaGetRef<const ::Neptools::Source &>, LuaGetRef<::Neptools::FilePosition>, LuaGetRef<::Neptools::FilePosition>>,\n &::Libshit::Lua::TypeTraits<::Neptools::DumpableSource>::Make<LuaGetRef<const ::Neptools::Source &>>\n >(\"new\");\n bld.AddFunction<\n static_cast<::Neptools::Source (::Neptools::DumpableSource::*)() const noexcept>(&::Neptools::DumpableSource::GetSource)\n >(\"get_source\");\n\n }\n static TypeRegister::StateRegister<::Neptools::DumpableSource> reg_neptools_dumpable_source;\n\n}\n#endif\n" }, { "alpha_fraction": 0.6191298365592957, "alphanum_fraction": 0.6714433431625366, "avg_line_length": 24.40350914001465, "blob_id": "07b327b50d5927601a4504aaecc8d93c9a1faf63", "content_id": "ab22be1815f1f4d53ffa44ec36a9616221b905ac", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5792, "license_type": "permissive", "max_line_length": 80, "num_lines": 228, "path": "/doc/formats/stcm.md", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "STCM\n====\n\nSTCM files store bytecode for a VM used by the Re;Births.\n\nThe general structure of an STCM file is:\n\n* Header\n* Padding until 0x50, `GLOBAL_DATA` string, padding until 0x70.\n* Data structures\n* Padding until dividable by 16, `CODE_START_\\0`\n* Instructions\n* `EXPORT_DATA\\0`\n* Export entries\n* `COLLECTION_LINK\\0`\n* Collection link header, entries until EOF\n\nBut generally the engine do not care about it, it only follows the offsets. The\nstrings and extra padding can be removed without breaking anything. There are\nusually a lot of dead code and unused data in the STCM files.\n\nHeader\n------\n\n```c++\nstruct Header\n{\n char magic[0x20];\n uint32_t export_offset;\n uint32_t export_count;\n uint32_t field_28; // ??\n uint32_t collection_link_offset;\n};\nsizeof(Header) == 0x30\n```\n\n`magic` starts with `STCM2L` (where `L` likely means little-endian), after a\nnull terminated describing the build date (?) of the generator follows (ignored\nby the game). (Like`STCM2L Apr 22 2013 19:39:01` in R;B3).\n\nThere are `export_count` count `ExportEntry` at `export_offset` and a\n`CollectionLinkHeader` at `collection_link_offset`.\n\n\nExport entry\n------------\n\n```c++\nstruct ExportEntry\n{\n uint32_t type; // 0 = CODE, 1 = DATA\n char name[0x20];\n uint32_t offset;\n};\nsizeof(ExportEntry) == 0x28\n```\n\nIf `type == 0`, `offset` is an offset to an `InstructionHeader`, if `type == 1`,\nit should be an offset to `Data` (not really used by the game). `name` is a null\nterminated string.\n\nData\n----\n\n```c++\nstruct Data\n{\n uint32_t type; // 0 or 1 ??\n uint32_t offset_unit;\n uint32_t field_8;\n uint32_t length;\n};\nsizeof(Data) = 0x10\n```\n\n`length` bytes of data follow the structure. `offset_unit` is `length/4` for\nstring data, 1 otherwise?\n\nStrings are stored as null terminated strings, the length is padded to a\nmultiple of 4 (so a string of length 4 will have a terminating zero byte and 3\npadding zero bytes at the end).\n\n\nInstruction\n-----------\n\n```c++\nstruct InstructionHeader\n{\n uint32_t is_call; // 0 or 1\n uint32_t opcode_offset;\n uint32_t param_count; // < 16\n uint32_t size;\n};\nsizeof(InstructionHeader) == 0x10;\n```\n\nIf `is_call` is true, `opcode_offset` contains an offset to the called\ninstruction. If `is_call` is false, `opcode_offset` is simply an opcode number\nin the VM, not an offset.\n\n`param_count` of `Parameter` structure follows the header, followed by `size`\nbytes of arbitrary payload (usually `Data` structures described above). After\nthe payload usually comes the next instruction. The following opcodes are known\nto jump unconditionally, thus in this case the engine won't try to parse and\nexecute the next instruction: 0, 6.\n\n```c++\nstruct Parameter\n{\n uint32_t param_0;\n uint32_t param_4;\n uint32_t param_8;\n};\nsizeof(Parameter) == 0x0c\n\nuint32_t TypeTag(uint32_t x) { return x >> 30; }\nuint32_t Value(uint32_t x) { return x & 0x3fffffff; }\n```\n\nThe meaning of the members depend on the value of `TypeTag(param_0)` (i.e. the\nupper two bits of `param_0`.\n\n### `param_0`\n\n```c++\nenum Type\n{\n MEM_OFFSET = 0,\n IMMEDIATE = 1,\n INDIRECT = 2,\n SPECIAL = 3,\n};\n```\n\nIf `TypeTag(param_0) == MEM_OFFSET`, `Value(param_0)` (the lower 30 bits of\n`param_0`) contains an offset to a `Data` structure, `param_4` and `param_8`\nparsed normally.\n\nIf `TypeTag(param_0) == INDIRECT`, `Value() < 256` (and not a file offset).\n`param_4` must be `0x40000000`. `param_8` parsed normally.\n\nIf `TypeTag(param_0) == SPECIAL`, then there are other subcases:\n\n```c++\nenum TypeSpecial\n{\n READ_STACK_MIN = 0xffffff00, // range MIN..MAX\n READ_STACK_MAX = 0xffffff0f,\n READ_4AC_MIN = 0xffffff20, // range MIN..MAX\n READ_4AC_MAX = 0xffffff27,\n INSTR_PTR0 = 0xffffff40,\n INSTR_PTR1 = 0xffffff41,\n COLL_LINK = 0xffffff42,\n};\n```\n\nIf `(param_0 >= READ_STACK_MIN && param_0 <= READ_STACK_MAX) || (param_0 >=\nREAD_4AC_MIN && param_0 <= READ_4AC_MAX)`, then `param_4` and `param_8` must be\n`0x40000000`.\n\nIf `param_0 == INSTR_PTR0 || param_0 == INSTR_PTR1`, then `param_4` contains an\noffset to an another instruction, `param_8` must be `0x40000000`.\n\nIf `patam_0 == COLL_LINK`, `param_4` contains an offset to a `CollectionLink`\nstructure, `param_8` must be 8.\n\n### `param_4` and `param_8`\n\nThe following only applies when these parameters are \"parsed normally\".\n`param_n` refers to either `param_4` or `param_8`.\n\nIf `TypeTag(param_n) == MEM_OFFSET`, `Value(param_n)` contains an offset to ???.\n\nIf `TypeTag(param_n) == IMMEDIATE || TypeTag(param_n) == INDIRECT`,\n`Value(param_n)` contains a value.\n\nIf `TypeTag(param_n) == SPECIAL`, then `(param_n >= READ_STACK_MIN && param_n <=\nREAD_STACK_MAX) || (param_n >= READ_4AC_MIN && param_n <= READ_4AC_MAX)`.\n\nCollection link\n---------------\n\n```c++\nstruct CollectionLinkHeader\n{\n uint32_t field_00;\n uint32_t offset;\n uint32_t count;\n uint32_t field_0c;\n uint32_t field_10;\n uint32_t field_14;\n uint32_t field_18;\n uint32_t field_1c;\n uint32_t field_20;\n uint32_t field_24;\n uint32_t field_28;\n uint32_t field_2c;\n uint32_t field_30;\n uint32_t field_34;\n uint32_t field_38;\n uint32_t field_3c;\n};\nsizeof(CollectionLinkHeader) == 0x40);\n```\n\nThe `field_*` members are always zero in the files I encountered... There are\n`count` `CollectionLinkEntry` structures at `offset`.\n\n\n```c++\nstruct CollectionLinkEntry\n{\n uint32_t name_0;\n uint32_t name_1;\n uint32_t field_08;\n uint32_t field_0c;\n uint32_t field_10;\n uint32_t field_14;\n uint32_t field_18;\n uint32_t field_1c;\n};\nsizeof(CollectionLinkEntry) == 0x20;\n```\n\nThe `field_*` members are always zero in the files I encountered... `name_0` and\n`name_1` are offsets to null terminated strings (they're generally after the\nlast entry).\n" }, { "alpha_fraction": 0.6038074493408203, "alphanum_fraction": 0.6221264600753784, "avg_line_length": 25.769229888916016, "blob_id": "5abc3328935e24309bd10dff6510a3f0885f751c", "content_id": "be3360ce39d496311f37282cb4112c25c194ce72", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2784, "license_type": "permissive", "max_line_length": 79, "num_lines": 104, "path": "/src/format/gbnl_lua.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_907F2DFB_AA53_4295_B41F_9AAA950AEEB4\n#define UUID_907F2DFB_AA53_4295_B41F_9AAA950AEEB4\n#pragma once\n\n#include \"gbnl.hpp\"\n#include \"../dynamic_struct.lua.hpp\"\n\n#include <string_view>\n\n#if LIBSHIT_WITH_LUA\n\nnamespace Neptools\n{\n\n template <>\n struct DynamicStructTypeTraits<Gbnl::OffsetString>\n {\n static void Push(Libshit::Lua::StateRef vm, const void* ptr, size_t size)\n {\n LIBSHIT_ASSERT(size == sizeof(Gbnl::OffsetString)); (void) size;\n auto ofs = static_cast<const Gbnl::OffsetString*>(ptr);\n if (ofs->offset == static_cast<uint32_t>(-1))\n lua_pushnil(vm);\n else\n vm.Push(ofs->str);\n }\n\n static void Get(Libshit::Lua::StateRef vm, int idx, void* ptr, size_t size)\n {\n LIBSHIT_ASSERT(size == sizeof(Gbnl::OffsetString)); (void) size;\n auto ofs = static_cast<Gbnl::OffsetString*>(ptr);\n\n if (Libshit::Lua::IsNoneOrNil(lua_type(vm, idx)))\n {\n ofs->offset = static_cast<uint32_t>(-1);\n ofs->str.clear();\n }\n else\n {\n ofs->str = vm.Check<std::string>(idx);\n ofs->offset = 0; // no longer null\n }\n }\n\n static constexpr bool SIZABLE = false;\n static constexpr const char* NAME = \"string\";\n };\n\n // FixString is zero terminated, Padding is not\n template <>\n struct DynamicStructTypeTraits<Gbnl::FixStringTag>\n {\n static void Push(Libshit::Lua::StateRef vm, const void* ptr, size_t size)\n {\n auto str = static_cast<const char*>(ptr);\n lua_pushlstring(vm, str, strnlen(str, size));\n }\n\n static void Get(Libshit::Lua::StateRef vm, int idx, void* ptr, size_t size)\n {\n auto str = vm.Check<std::string_view>(idx);\n auto dst = static_cast<char*>(ptr);\n\n auto n = std::min(size-1, str.length());\n memcpy(dst, str.data(), n);\n memset(dst+n, 0, size-n);\n }\n\n static constexpr bool SIZABLE = true;\n static constexpr const char* NAME = \"fix_string\";\n };\n\n template<>\n struct DynamicStructTypeTraits<Gbnl::PaddingTag>\n {\n static void Push(Libshit::Lua::StateRef vm, const void* ptr, size_t size)\n {\n auto str = static_cast<const char*>(ptr);\n lua_pushlstring(vm, str, size);\n }\n\n static void Get(Libshit::Lua::StateRef vm, int idx, void* ptr, size_t size)\n {\n auto str = vm.Check<std::string_view>(idx);\n auto dst = static_cast<char*>(ptr);\n\n auto n = std::min(size, str.length());\n memcpy(dst, str.data(), n);\n memset(dst+n, 0, size-n);\n }\n\n static constexpr bool SIZABLE = true;\n static constexpr const char* NAME = \"padding\";\n };\n\n}\n\nNEPTOOLS_DYNAMIC_STRUCT_TABLECTOR(\n int8_t, int16_t, int32_t, int64_t, float,\n ::Neptools::Gbnl::OffsetString, ::Neptools::Gbnl::FixStringTag,\n ::Neptools::Gbnl::PaddingTag);\n\n#endif\n#endif\n" }, { "alpha_fraction": 0.5017730593681335, "alphanum_fraction": 0.508643627166748, "avg_line_length": 33.97674560546875, "blob_id": "7e33c6516e4c9d7ab4d28bf52c70cfcc09589104", "content_id": "5a35f28d97e5121794e8d86ffa0072c02d3d8921", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4512, "license_type": "permissive", "max_line_length": 85, "num_lines": 129, "path": "/wscript", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "# -*- mode: python -*-\n\n# libshit 'config'\nAPPNAME='neptools'\nBOOST_LIBS = ['system', 'filesystem']\nDEFAULT_LUA = 'ljx'\n\ndef options(opt):\n opt.recurse('libshit', name='options')\n\ndef configure(cfg):\n cfg.recurse('libshit', name='configure', once=False)\n\n if cfg.env.DEST_OS == 'vita':\n cfg.check_cxx(lib='taihen_stub', uselib_store='TAIHEN')\n\ndef build(bld):\n bld.recurse('libshit')\n\n bld.gen_version_hpp('src/version.hpp')\n\n src = [\n 'src/dumpable.cpp',\n 'src/endian.cpp',\n 'src/open.cpp',\n 'src/pattern.cpp',\n 'src/sink.cpp',\n 'src/source.cpp',\n 'src/utils.cpp',\n 'src/format/cl3.cpp',\n 'src/format/context.cpp',\n 'src/format/cstring_item.cpp',\n 'src/format/eof_item.cpp',\n 'src/format/gbnl.cpp',\n 'src/format/item.cpp',\n 'src/format/primitive_item.cpp',\n 'src/format/raw_item.cpp',\n 'src/format/stcm/collection_link.cpp',\n 'src/format/stcm/data.cpp',\n 'src/format/stcm/expansion.cpp',\n 'src/format/stcm/exports.cpp',\n 'src/format/stcm/file.cpp',\n 'src/format/stcm/gbnl.cpp',\n 'src/format/stcm/header.cpp',\n 'src/format/stcm/instruction.cpp',\n 'src/format/stcm/string_data.cpp',\n ]\n if bld.env.WITH_LUA != 'none':\n src += [\n 'src/txt_serializable.cpp',\n 'src/format/builder.lua',\n ]\n if bld.env.WITH_TESTS:\n src += [ 'test/pattern.cpp' ]\n\n bld.objects(source = src,\n uselib = 'NEPTOOLS',\n use = 'libshit boost_system boost_filesystem',\n includes = 'src',\n target = 'common')\n\n src = [\n 'src/format/stsc/file.cpp',\n 'src/format/stsc/header.cpp',\n 'src/format/stsc/instruction.cpp',\n ]\n bld.objects(source = src,\n uselib = 'NEPTOOLS',\n use = 'libshit boost_system boost_filesystem',\n includes = 'src',\n target = 'common-stsc')\n\n if bld.env.DEST_OS == 'vita':\n src = [\n 'src/vita_plugin/cpk.cpp',\n 'src/vita_plugin/plugin.cpp',\n ]\n bld.program(source = src,\n includes = 'src', # for version.hpp\n ldflags = '-lSceAppMgr_stub',\n uselib = 'NEPTOOLS TAIHEN',\n use = 'common',\n target = 'vita_plugin')\n else:\n bld.program(source = ['src/programs/stcm-editor.cpp',\n 'src/programs/stcm-editor.rc'],\n includes = 'src', # for version.hpp\n uselib = 'NEPTOOLS',\n use = 'common common-stsc',\n target = 'stcm-editor')\n\n if bld.env.DEST_OS == 'win32' and bld.env.DEST_CPU == 'x86':\n # technically launcher can be compiled for 64bits, but it makes no sense\n ld = ['-Wl,/nodefaultlib', '-Wl,/entry:start', '-Wl,/subsystem:windows',\n '-Wl,/FIXED', '-Wl,/NXCOMPAT:NO', '-Wl,/IGNORE:4254']\n bld.program(source = 'src/programs/launcher.c src/programs/launcher.rc',\n includes = 'src', # for version.hpp\n target = 'launcher',\n cflags = '-Os -mstack-probe-size=999999999 -fno-stack-protector',\n uselib = 'KERNEL32 SHELL32 USER32 NEPTOOLS',\n linkflags = ld)\n\n src_inject = [\n 'src/windows_server/cpk.cpp',\n 'src/windows_server/hook.cpp',\n 'src/windows_server/server.cpp',\n 'src/windows_server/server.rc',\n ]\n bld.shlib(source = src_inject,\n includes = 'src', # for version.hpp\n target = 'neptools-server',\n use = 'common',\n uselib = 'SHELL32 USER32 NEPTOOLS',\n defs = 'src/windows_server/server.def')\n\n if bld.env.WITH_TESTS:\n # test pattern parser\n bld(features='cxx',\n source='test/pattern_fail.cpp',\n uselib='BOOST NEPTOOLS',\n use='boost_system boost_filesystem libshit',\n includes='src',\n defines=['TEST_PATTERN=\"b2 ff\"'])\n bld(features='cxx fail_cxx',\n source='test/pattern_fail.cpp',\n uselib='BOOST NEPTOOLS',\n use='boost_system boost_filesystem libshit',\n includes='src',\n defines=['TEST_PATTERN=\"bz ff\"'])\n" }, { "alpha_fraction": 0.6790123581886292, "alphanum_fraction": 0.6790123581886292, "avg_line_length": 44.264705657958984, "blob_id": "7bebef5c0149748aa3b58d1a38d648a32b346e7f", "content_id": "73d3ec3101ec16e7b138fb3ac38474355bf5c138", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1539, "license_type": "permissive", "max_line_length": 201, "num_lines": 34, "path": "/src/format/raw_item.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::RawItem::TYPE_NAME[] = \"neptools.raw_item\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.raw_item\n template<>\n void TypeRegisterTraits<::Neptools::RawItem>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::RawItem, ::Neptools::Item>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::RawItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::Neptools::Source>>,\n &::Libshit::Lua::TypeTraits<::Neptools::RawItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<std::string>>\n >(\"new\");\n bld.AddFunction<\n static_cast<const ::Neptools::Source & (::Neptools::RawItem::*)() const noexcept>(&::Neptools::RawItem::GetSource),\n static_cast<::Neptools::RawItem::GetSourceRet (*)(::Neptools::ItemPointer, ::Neptools::FilePosition)>(::Neptools::RawItem::GetSource)\n >(\"get_source\");\n bld.AddFunction<\n static_cast<::Neptools::Item & (::Neptools::RawItem::*)(::Neptools::FilePosition, ::Libshit::NotNull<::Libshit::RefCountedPtr<::Neptools::Item> >)>(&::Neptools::RawItem::Split<::Neptools::Item>),\n static_cast<::Neptools::RawItem & (::Neptools::RawItem::*)(::Neptools::FilePosition, ::Neptools::FilePosition)>(&::Neptools::RawItem::Split)\n >(\"split\");\n\n }\n static TypeRegister::StateRegister<::Neptools::RawItem> reg_neptools_raw_item;\n\n}\n#endif\n" }, { "alpha_fraction": 0.6593567132949829, "alphanum_fraction": 0.7061403393745422, "avg_line_length": 20.375, "blob_id": "e341dec8f6533f54ca5a9943e805bebb0d52e035", "content_id": "15646e819a79edb4b5800f7881f7c6ccfe2d70a9", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 684, "license_type": "permissive", "max_line_length": 68, "num_lines": 32, "path": "/src/format/stcm/string_data.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_5AE4EF4E_E8EB_4A3D_90A7_58FA73AF7B71\n#define UUID_5AE4EF4E_E8EB_4A3D_90A7_58FA73AF7B71\n#pragma once\n\n#include \"../item.hpp\"\n\nnamespace Neptools::Stcm\n{\n class DataItem;\n\n class StringDataItem final : public Item\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n StringDataItem(Key k, Context& ctx, std::string str)\n : Item{k, ctx}, string{std::move(str)} {}\n\n static Libshit::RefCountedPtr<StringDataItem>\n MaybeCreateAndReplace(DataItem& it);\n\n FilePosition GetSize() const noexcept override;\n\n std::string string;\n\n private:\n void Dump_(Sink& sink) const override;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n };\n\n}\n\n#endif\n" }, { "alpha_fraction": 0.5800776481628418, "alphanum_fraction": 0.6033729910850525, "avg_line_length": 28.86231803894043, "blob_id": "347a85fa639a2b16fbfe7506d31443d2f0d49fd3", "content_id": "4972935c6575fdc14684cf74c560993aef93c678", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8242, "license_type": "permissive", "max_line_length": 85, "num_lines": 276, "path": "/src/vita_plugin/cpk.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"vita_plugin/cpk.hpp\"\n\n#include \"format/stcm/file.hpp\"\n#include \"open.hpp\"\n#include \"pattern_parse.hpp\"\n#include \"sink.hpp\"\n#include \"source.hpp\"\n#include \"txt_serializable.hpp\"\n#include \"vita_plugin/taihen_cpp.hpp\"\n\n#include <libshit/memory_utils.hpp>\n\n#include <boost/filesystem/operations.hpp>\n\n#include <cstdint>\n#include <fstream>\n#include <psp2/kernel/modulemgr.h>\n#include <stdexcept>\n#include <string_view>\n\n#define LIBSHIT_LOG_NAME \"cpk\"\n#include <libshit/logger_helper.hpp>\n\nnamespace Neptools::VitaPlugin\n{\n\n namespace\n {\n struct FsBinderHandle\n {\n FsBinderHandle* parent;\n FsBinderHandle* left;\n FsBinderHandle* right;\n void* unk0;\n std::uint32_t unk1;\n std::uint32_t index;\n std::uint32_t usage;\n // ...\n };\n\n struct FileHandle\n {\n std::int32_t fd;\n // ...\n };\n\n struct FileCpkData\n {\n FileHandle* fhan;\n const char* cpk_name;\n std::uint64_t offs;\n std::uint32_t compr_size, uncompr_size;\n std::uint32_t binder_index;\n };\n\n struct FileInfo\n {\n FileCpkData* dat;\n char* name;\n std::uint32_t id;\n std::uint32_t id_ignored;\n FileHandle* fhan;\n const char* cpk_name;\n std::uint64_t cpk_offs;\n std::uint32_t idx1, idx2;\n std::uint32_t chain_length;\n // ...\n };\n }\n\n static std::string data_path;\n static std::string cache_path;\n\n using DecompressFun = uint64_t (*)(char*, char*, uint64_t, char*, uint64_t);\n static DecompressFun decompress;\n\n static Source GetSource(const FileCpkData& dat)\n {\n auto src = Source::FromFd(dat.cpk_name, dat.fhan->fd, false);\n src.Slice(dat.offs, dat.compr_size);\n if (dat.compr_size == dat.uncompr_size) return src;\n\n auto buf = Libshit::MakeUnique<char[]>(dat.uncompr_size, Libshit::uninitialized);\n src.Pread(0, buf.get(), dat.compr_size);\n\n char tmp[0x104];\n auto res = decompress(tmp, buf.get(), dat.compr_size, buf.get(),\n dat.uncompr_size);\n if (res != dat.uncompr_size)\n LIBSHIT_THROW(std::runtime_error, \"Data decompression failed\");\n\n return Source::FromMemory(\"\", Libshit::Move(buf), dat.uncompr_size);\n }\n\n static std::pair<const char*, size_t> DoTxt(\n const char* fname, const FileCpkData& dat)\n {\n auto cpth = cache_path + fname;\n if (boost::filesystem::exists(cpth))\n {\n DBG(3) << \"Cached exists: \" << cpth << std::endl;\n return {cache_path.c_str(), boost::filesystem::file_size(cpth)};\n }\n\n auto pth = data_path + fname + \".txt\";\n if (!boost::filesystem::exists(pth)) return {nullptr, 0};\n\n auto dir = boost::filesystem::path(cpth).remove_filename();\n DBG(4) << \"Mkdir \" << dir << std::endl;\n boost::filesystem::create_directories(dir);\n\n DBG(3) << \"Opening original \" << pth << std::endl;\n auto src = GetSource(dat);\n\n if (CHECK_DBG(4)) src.Dump(*Sink::ToFile(cpth + \".orig\", src.GetSize()));\n\n auto dump = OpenFactory::Open(src);\n DBG(4) << \"GetTxt\" << std::endl;\n auto txt = dump->GetDefaultTxtSerializable(dump);\n DBG(4) << \"Importing...\" << std::endl;\n txt->ReadTxt(OpenIn(pth));\n DBG(4) << \"Gc...\" << std::endl;\n if (auto f = dynamic_cast<Stcm::File*>(txt.get())) f->Gc();\n DBG(4) << \"Fixup...\" << std::endl;\n dump->Fixup();\n DBG(4) << \"Dump...\" << std::endl;\n dump->Dump(Libshit::Move(cpth));\n\n return {cache_path.c_str(), dump->GetSize()};\n }\n\n static std::pair<const char*, size_t> DoBin(const char* fname)\n {\n auto pth = data_path + fname;\n if (!boost::filesystem::exists(pth)) return {nullptr, 0};\n DBG(3) << \"Simple exists \" << pth << std::endl;\n return {data_path.c_str(), boost::filesystem::file_size(pth)};\n }\n\n using FsBinderHandleCreateFun = int(*)(FsBinderHandle**);\n static FsBinderHandleCreateFun fs_binder_handle_create;\n\n static FileHandle* dir_fhan = reinterpret_cast<FileHandle*>(0x8143ada0);\n\n static TaiHook<int(FsBinderHandle*, FileInfo*, FsBinderHandle**, int*)>\n get_file_info_hook;\n static FsBinderHandle* my_han;\n\n static int HookGetFileInfo(\n FsBinderHandle* han, FileInfo* fi, FsBinderHandle** han_out, int* succ)\n {\n auto ret = get_file_info_hook(han, fi, han_out, succ);\n\n if (ret != 0 || *succ != 1 || !fi->dat) return ret;\n if (!my_han)\n {\n DBG(0) << \"Creating FsBinder handle: \" << fs_binder_handle_create(&my_han)\n << std::endl;\n fs_binder_handle_create(&my_han);\n if (!my_han) return ret;\n my_han->usage = 3;\n }\n\n try\n {\n DBG(2) << \"Checking file: \" << fi->name << std::endl;\n\n auto r = DoBin(fi->name);\n if (!r.first) r = DoTxt(fi->name, *fi->dat);\n if (!r.first) return ret;\n\n DBG(1) << \"Hooked file: \" << fi->name << \" to \" << r.first\n << \", size: \" << r.second << std::endl;\n\n fi->dat->fhan = dir_fhan;\n fi->dat->cpk_name = r.first;\n fi->dat->offs = 0;\n fi->dat->compr_size = r.second;\n fi->dat->uncompr_size = r.second;\n fi->dat->binder_index = my_han->index;\n\n fi->cpk_name = r.first;\n fi->cpk_offs = 0;\n fi->fhan = dir_fhan;\n fi->idx1 = fi->idx2 = my_han->index;\n if (han_out) *han_out = my_han;\n\n return ret;\n }\n catch (...)\n {\n ERR << Libshit::PrintException(Libshit::Logger::HasAnsiColor())\n << std::endl;\n\n abort();\n }\n }\n\n static auto GET_FILE_INFO_PATTERN = NEPTOOLS_PATTERN(\n \"2d e9 30/bf 4f c0/f0 b0\");\n\n static auto DECOMPRESS_PATTERN = NEPTOOLS_PATTERN(\n \"2d e9 f0 43 83 b0 0a 9e\");\n\n static auto FS_BINDER_HANDLE_CREATE_PATTERN = NEPTOOLS_PATTERN(\n \"70 b5 04 1c 01 d0\");\n\n static auto DIR_FHAN_PATTERN = NEPTOOLS_PATTERN(\n \"4a/f0 f6/fb a0/00 5e/8f c8/f0 f2/fb 43/00 1e/8f b9 f1 00 0f 12 d0 c9 f8 \"\n \"00 e0\");\n\n template <typename T>\n static T ThumbPtr(const Byte* ptr) noexcept\n { return reinterpret_cast<T>(reinterpret_cast<uintptr_t>(ptr)|1); }\n\n static uint16_t GetThumbImm16(const uint16_t* ptr) noexcept\n {\n auto b0 = ptr[0], b1 = ptr[1];\n return ((b0 & 0x000f) << 12) | ((b0 & 0x0400) << 1) |\n ((b1 & 0x7000) >> 4) | (b1 & 0x00ff);\n }\n\n void Init(std::string data_path_in, std::string cache_path_in)\n {\n data_path = Libshit::Move(data_path_in);\n cache_path = Libshit::Move(cache_path_in);\n\n INF << \"Data path: \" << data_path\n << \"\\nCache path: \" << cache_path << std::endl;\n\n DBG(0) << \"Erasing cache...\" << std::endl;\n boost::filesystem::remove_all(cache_path);\n\n tai_module_info_t tai_info;\n tai_info.size = sizeof(tai_info);\n auto ret = taiGetModuleInfo(TAI_MAIN_MOD_STR, &tai_info);\n if (ret < 0)\n LIBSHIT_THROW(TaiError, \"taiGetModuleInfo failed\", \"Error code\", ret);\n\n SceKernelModuleInfo kern_info;\n kern_info.size = sizeof(kern_info);\n ret = sceKernelGetModuleInfo(tai_info.modid, &kern_info);\n if (ret < 0)\n LIBSHIT_THROW(TaiError, \"sceKernelGetModuleInfo failed\", \"Error code\", ret);\n\n std::string_view seg0{static_cast<char*>(kern_info.segments[0].vaddr),\n kern_info.segments[0].memsz};\n DBG(1) << \"Base: \" << static_cast<const void*>(seg0.data())\n << \", size: \" << seg0.size() << std::endl;\n\n DBG(2) << \"Finding GET_FILE_INFO\" << std::endl;\n auto get_file_info_addr = GET_FILE_INFO_PATTERN.Find(seg0);\n\n DBG(2) << \"Finding DECOMPRESS\" << std::endl;\n decompress = ThumbPtr<DecompressFun>(DECOMPRESS_PATTERN.Find(seg0));\n DBG(2) << \"Finding FS_BINDER_HANDLE_CREATE\" << std::endl;\n fs_binder_handle_create = ThumbPtr<FsBinderHandleCreateFun>(\n FS_BINDER_HANDLE_CREATE_PATTERN.Find(seg0));\n\n DBG(2) << \"Finding DIR_FHAN\" << std::endl;\n auto dir_fhan_info = reinterpret_cast<const uint16_t*>(\n DIR_FHAN_PATTERN.Find(seg0));\n dir_fhan = reinterpret_cast<FileHandle*>(\n GetThumbImm16(dir_fhan_info) | (GetThumbImm16(dir_fhan_info+2) << 16));\n DBG(3) << \"dir_fhan -> \" << dir_fhan << std::endl;\n\n ret = taiHookFunctionOffset(\n get_file_info_hook, tai_info.modid, 0,\n get_file_info_addr - static_cast<Byte*>(kern_info.segments[0].vaddr), 1,\n reinterpret_cast<void*>(&HookGetFileInfo));\n\n if (ret < 0)\n LIBSHIT_THROW(TaiError, \"Hook GetFileInfo failed\", \"Error code\", ret);\n }\n\n}\n" }, { "alpha_fraction": 0.6519607901573181, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 24.5, "blob_id": "de0d3c2b0c0a0766cd5c3c84792dc16f70328e4b", "content_id": "2b4e12f24b059b5ef0b3008ebdb9645b7e96813d", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 816, "license_type": "permissive", "max_line_length": 68, "num_lines": 32, "path": "/src/format/primitive_item.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"primitive_item.hpp\"\n#include \"context.hpp\"\n\n// factory\n#include \"stcm/data.hpp\"\n\n#include \"primitive_item.binding.hpp\"\n\nnamespace Neptools\n{\n#define NEPTOOLS_GEN(cname, lname, ...) template class __VA_ARGS__\n NEPTOOLS_PRIMITIVE_ITEMS(NEPTOOLS_GEN);\n#undef NEPTOOLS_GEN\n\n template <typename Item, int32_t TypeId>\n static bool CheckFun(Stcm::DataItem& it)\n {\n if (it.type != TypeId || it.offset_unit != 1 || it.field_8 != 1)\n return false;\n auto child = dynamic_cast<RawItem*>(&it.GetChildren().front());\n if (child && child->GetSize() == sizeof(typename Item::Type))\n {\n Item::CreateAndInsert({child, 0});\n return true;\n }\n return false;\n }\n\n static Stcm::DataFactory reg_int32{CheckFun<Int32Item, 0>};\n static Stcm::DataFactory reg_float{CheckFun<FloatItem, 1>};\n\n}\n" }, { "alpha_fraction": 0.7383627891540527, "alphanum_fraction": 0.7415730357170105, "avg_line_length": 40.53333282470703, "blob_id": "7ddba72d4040563c7c68cf57b3131146a15f0664", "content_id": "7f82a7c8c6108c21ba801469e328fa5f1a1fee87", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 623, "license_type": "permissive", "max_line_length": 78, "num_lines": 15, "path": "/gen_binding.sh", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\ncd \"$(dirname \"${BASH_SOURCE[0]}\")\"\n\nsrc=(src/dumpable src/endian src/open src/sink src/source src/txt_serializable\n src/format/cl3 src/format/context src/format/cstring_item\n src/format/eof_item src/format/gbnl src/format/item\n src/format/primitive_item src/format/raw_item\n src/format/stcm/collection_link src/format/stcm/data\n src/format/stcm/exports src/format/stcm/file src/format/stcm/gbnl\n src/format/stcm/header src/format/stcm/instruction\n src/format/stcm/string_data\n src/format/stsc/file src/format/stsc/header src/format/stsc/instruction)\n\n. libshit/gen_binding.sh\n" }, { "alpha_fraction": 0.6920344829559326, "alphanum_fraction": 0.6945712566375732, "avg_line_length": 49.53845977783203, "blob_id": "3583e174af578b470167507e0a4207b5743cf699", "content_id": "3e1f8fb083ed788fc419fb6389b62af4de61bfb3", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3942, "license_type": "permissive", "max_line_length": 229, "num_lines": 78, "path": "/src/format/stcm/exports.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Stcm::ExportsItem::TYPE_NAME[] = \"neptools.stcm.exports_item\";\nconst char ::Libshit::Lua::TypeName<::Neptools::Stcm::ExportsItem::Type>::TYPE_NAME[] =\n \"neptools.stcm.exports_item.type\";\n\nconst char ::Neptools::Stcm::ExportsItem::EntryType::TYPE_NAME[] = \"neptools.stcm.exports_item.entry_type\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.stcm.exports_item\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::ExportsItem>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stcm::ExportsItem, ::Neptools::Item>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::ExportsItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::ExportsItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::Neptools::Source>, LuaGetRef<::uint32_t>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::ExportsItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<Libshit::AT<std::vector<::Neptools::Stcm::ExportsItem::VectorEntry> >>>\n >(\"new\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::ExportsItem & (*)(::Neptools::ItemPointer, ::uint32_t)>(::Neptools::Stcm::ExportsItem::CreateAndInsert)\n >(\"create_and_insert\");\n bld.AddFunction<\n &::Libshit::Lua::GetSmartOwnedMember<::Neptools::Stcm::ExportsItem, std::vector<::Neptools::Stcm::ExportsItem::VectorEntry>, &::Neptools::Stcm::ExportsItem::entries>\n >(\"get_entries\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::ExportsItem> reg_neptools_stcm_exports_item;\n\n // class neptools.stcm.exports_item.type\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::ExportsItem::Type>::Register(TypeBuilder& bld)\n {\n\n bld.Add(\"CODE\", ::Neptools::Stcm::ExportsItem::Type::CODE);\n bld.Add(\"DATA\", ::Neptools::Stcm::ExportsItem::Type::DATA);\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::ExportsItem::Type> reg_neptools_stcm_exports_item_type;\n\n // class neptools.stcm.exports_item.entry_type\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::ExportsItem::EntryType>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::ExportsItem::EntryType, ::Neptools::Stcm::ExportsItem::Type, &::Neptools::Stcm::ExportsItem::EntryType::type>\n >(\"get_type\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stcm::ExportsItem::EntryType, ::Neptools::Stcm::ExportsItem::Type, &::Neptools::Stcm::ExportsItem::EntryType::type>\n >(\"set_type\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::ExportsItem::EntryType, ::Libshit::FixedString<32>, &::Neptools::Stcm::ExportsItem::EntryType::name>\n >(\"get_name\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stcm::ExportsItem::EntryType, ::Libshit::FixedString<32>, &::Neptools::Stcm::ExportsItem::EntryType::name>\n >(\"set_name\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::ExportsItem::EntryType, ::Libshit::NotNull<::Neptools::LabelPtr>, &::Neptools::Stcm::ExportsItem::EntryType::lbl>\n >(\"get_lbl\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stcm::ExportsItem::EntryType, ::Libshit::NotNull<::Neptools::LabelPtr>, &::Neptools::Stcm::ExportsItem::EntryType::lbl>\n >(\"set_lbl\");\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::ExportsItem::EntryType>::Make<LuaGetRef<::Neptools::Stcm::ExportsItem::Type>, LuaGetRef<const ::Libshit::FixedString<32> &>, LuaGetRef<::Libshit::NotNull<::Neptools::LabelPtr>>>\n >(\"new\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::ExportsItem::EntryType> reg_neptools_stcm_exports_item_entry_type;\n\n}\n#endif\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.7026712894439697, "avg_line_length": 25.090909957885742, "blob_id": "b5d9f07f2158e168c9606daa4e252b8c901dfe20", "content_id": "f878bc97e304806e6d4b6f818824fa02248e8c84", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 861, "license_type": "permissive", "max_line_length": 80, "num_lines": 33, "path": "/src/format/cstring_item.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_94EB7F8A_BDE7_47F7_9B17_BF00A9A3EEBB\n#define UUID_94EB7F8A_BDE7_47F7_9B17_BF00A9A3EEBB\n#pragma once\n\n#include \"item.hpp\"\n#include \"../source.hpp\"\n\nnamespace Neptools\n{\n\n class CStringItem final : public Item\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n CStringItem(Key k, Context& ctx, std::string string)\n : Item{k, ctx}, string{std::move(string)} {}\n CStringItem(Key k, Context& ctx, const Source& src);\n static CStringItem& CreateAndInsert(ItemPointer ptr);\n FilePosition GetSize() const noexcept override { return string.size() + 1; }\n\n static std::string GetLabelName(std::string string);\n std::string GetLabelName() const { return GetLabelName(string); }\n\n std::string string;\n\n private:\n void Dump_(Sink& sink) const override;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n };\n\n}\n\n#endif\n" }, { "alpha_fraction": 0.6282420754432678, "alphanum_fraction": 0.6772334575653076, "avg_line_length": 25.69230842590332, "blob_id": "4c9a9aa69e2094d567f6318082e9cae26d5a76b1", "content_id": "27cb62b70eb0070ed78d0e815bb7462a85a60ae8", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1388, "license_type": "permissive", "max_line_length": 72, "num_lines": 52, "path": "/src/format/stcm/data.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_CB40AD6D_5157_4C96_A9A9_371A9F215955\n#define UUID_CB40AD6D_5157_4C96_A9A9_371A9F215955\n#pragma once\n\n#include \"../item.hpp\"\n#include \"../../factory.hpp\"\n#include <boost/endian/arithmetic.hpp>\n\nnamespace Neptools::Stcm\n{\n\n class DataItem final : public ItemWithChildren\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n struct Header\n {\n boost::endian::little_uint32_t type;\n boost::endian::little_uint32_t offset_unit;\n boost::endian::little_uint32_t field_8;\n boost::endian::little_uint32_t length;\n\n void Validate(FilePosition chunk_size) const;\n };\n static_assert(sizeof(Header) == 0x10);\n\n DataItem(Key k, Context& ctx, uint32_t type, uint32_t offset_unit,\n uint32_t field_8)\n : ItemWithChildren{k, ctx}, type{type}, offset_unit{offset_unit},\n field_8{field_8} {}\n LIBSHIT_NOLUA\n DataItem(Key k, Context& ctx, const Header& hdr, size_t chunk_size);\n static DataItem& CreateAndInsert(ItemPointer ptr);\n\n FilePosition GetSize() const noexcept override;\n void Fixup() override;\n\n uint32_t type, offset_unit, field_8;\n\n private:\n void Dump_(Sink& sink) const override;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n };\n\n struct DataFactory : BaseFactory<bool (*)(DataItem& it)>\n {\n using BaseFactory::BaseFactory;\n static void Check(DataItem& it);\n };\n\n}\n#endif\n" }, { "alpha_fraction": 0.6888266205787659, "alphanum_fraction": 0.6920304298400879, "avg_line_length": 42.05172348022461, "blob_id": "04ca65a6366f0d89b8a176fb5b979495a1dfe7e8", "content_id": "ab31ce068c0ac39d57ca54b394703baf118e390b", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2497, "license_type": "permissive", "max_line_length": 196, "num_lines": 58, "path": "/src/format/stcm/expansion.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Stcm::ExpansionItem::TYPE_NAME[] = \"neptools.stcm.expansion_item\";\n\nconst char ::Neptools::Stcm::ExpansionsItem::TYPE_NAME[] = \"neptools.stcm.expansions_item\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.stcm.expansion_item\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::ExpansionItem>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stcm::ExpansionItem, ::Neptools::Item>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::ExpansionItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::uint32_t>, LuaGetRef<::Neptools::LabelPtr>>\n >(\"new\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::ExpansionItem & (*)(::Neptools::ItemPointer)>(::Neptools::Stcm::ExpansionItem::CreateAndInsert)\n >(\"create_and_insert\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::ExpansionItem, ::uint32_t, &::Neptools::Stcm::ExpansionItem::index>\n >(\"get_index\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stcm::ExpansionItem, ::uint32_t, &::Neptools::Stcm::ExpansionItem::index>\n >(\"set_index\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::ExpansionItem, ::Libshit::NotNull<::Neptools::LabelPtr>, &::Neptools::Stcm::ExpansionItem::name>\n >(\"get_name\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stcm::ExpansionItem, ::Libshit::NotNull<::Neptools::LabelPtr>, &::Neptools::Stcm::ExpansionItem::name>\n >(\"set_name\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::ExpansionItem> reg_neptools_stcm_expansion_item;\n\n // class neptools.stcm.expansions_item\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::ExpansionsItem>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stcm::ExpansionsItem, ::Neptools::ItemWithChildren>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::ExpansionsItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>>\n >(\"new\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::ExpansionsItem & (*)(::Neptools::ItemPointer, ::uint32_t)>(::Neptools::Stcm::ExpansionsItem::CreateAndInsert)\n >(\"create_and_insert\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::ExpansionsItem> reg_neptools_stcm_expansions_item;\n\n}\n#endif\n" }, { "alpha_fraction": 0.675159215927124, "alphanum_fraction": 0.675159215927124, "avg_line_length": 33.88888931274414, "blob_id": "89b589946949f3e49458ff575946eed5b150f3b0", "content_id": "288081823cf77fa06e561e6f910408c6c95cc26e", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1570, "license_type": "permissive", "max_line_length": 131, "num_lines": 45, "path": "/src/format/stsc/file.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\nconst char ::Libshit::Lua::TypeName<::Neptools::Stsc::Flavor>::TYPE_NAME[] =\n \"neptools.stsc.flavor\";\n\nconst char ::Neptools::Stsc::File::TYPE_NAME[] = \"neptools.stsc.file\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.stsc.flavor\n template<>\n void TypeRegisterTraits<::Neptools::Stsc::Flavor>::Register(TypeBuilder& bld)\n {\n\n bld.Add(\"NOIRE\", ::Neptools::Stsc::Flavor::NOIRE);\n bld.Add(\"POTBB\", ::Neptools::Stsc::Flavor::POTBB);\n\n }\n static TypeRegister::StateRegister<::Neptools::Stsc::Flavor> reg_neptools_stsc_flavor;\n\n // class neptools.stsc.file\n template<>\n void TypeRegisterTraits<::Neptools::Stsc::File>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stsc::File, ::Neptools::Context, ::Neptools::TxtSerializable>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stsc::File>::Make<LuaGetRef<::Neptools::Stsc::Flavor>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stsc::File>::Make<LuaGetRef<::Neptools::Source>, LuaGetRef<::Neptools::Stsc::Flavor>>\n >(\"new\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::File, ::Neptools::Stsc::Flavor, &::Neptools::Stsc::File::flavor>\n >(\"get_flavor\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stsc::File, ::Neptools::Stsc::Flavor, &::Neptools::Stsc::File::flavor>\n >(\"set_flavor\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stsc::File> reg_neptools_stsc_file;\n\n}\n#endif\n" }, { "alpha_fraction": 0.6466739177703857, "alphanum_fraction": 0.6859323978424072, "avg_line_length": 29.065574645996094, "blob_id": "0683d8b771777f2faddf3b5d31e3d0e8a72977e3", "content_id": "1e20502bbdebcf12d9b637bfbb5d4297a28b8b82", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1834, "license_type": "permissive", "max_line_length": 77, "num_lines": 61, "path": "/src/format/stcm/header.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_B9D3C4DA_158C_4858_903C_9EBDD92C2CBC\n#define UUID_B9D3C4DA_158C_4858_903C_9EBDD92C2CBC\n#pragma once\n\n#include \"../raw_item.hpp\"\n#include <libshit/fixed_string.hpp>\n#include <boost/endian/arithmetic.hpp>\n\nnamespace Neptools::Stcm\n{\n\n class HeaderItem final : public Item\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n using MsgType = Libshit::FixedString<0x20-5-1>;\n struct Header\n {\n char magic[5];\n char endian;\n MsgType msg;\n\n boost::endian::little_uint32_t export_offset;\n boost::endian::little_uint32_t export_count;\n boost::endian::little_uint32_t field_28;\n boost::endian::little_uint32_t collection_link_offset;\n boost::endian::little_uint32_t field_30;\n boost::endian::little_uint32_t expansion_offset;\n boost::endian::little_uint32_t expansion_count;\n\n void Validate(FilePosition file_size) const;\n };\n static_assert(sizeof(Header) == 0x3c);\n\n HeaderItem(\n Key k, Context& ctx, const MsgType& msg,\n Libshit::NotNull<LabelPtr> export_sec,\n Libshit::NotNull<LabelPtr> collection_link, uint32_t field_28,\n LabelPtr expansion)\n : Item{k, ctx}, msg{msg}, export_sec{Libshit::Move(export_sec)},\n collection_link{Libshit::Move(collection_link)},\n expansion{Libshit::Move(expansion)},field_28{field_28} {}\n LIBSHIT_NOLUA\n HeaderItem(Key k, Context& ctx, const Header& hdr);\n static HeaderItem& CreateAndInsert(ItemPointer ptr);\n\n FilePosition GetSize() const noexcept override { return sizeof(Header); }\n\n MsgType msg;\n Libshit::NotNull<LabelPtr> export_sec;\n Libshit::NotNull<LabelPtr> collection_link;\n LabelPtr expansion;\n uint32_t field_28;\n\n private:\n void Dump_(Sink& sink) const override;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n };\n\n}\n#endif\n" }, { "alpha_fraction": 0.6512921452522278, "alphanum_fraction": 0.6584886908531189, "avg_line_length": 40.876712799072266, "blob_id": "7411864eebe2d6cdcd1287443c426b521944024e", "content_id": "5dbc944a85f3b084b615ee55d51cdff471421afc", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3057, "license_type": "permissive", "max_line_length": 169, "num_lines": 73, "path": "/src/sink.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Sink::TYPE_NAME[] = \"neptools.sink\";\n\nconst char ::Neptools::MemorySink::TYPE_NAME[] = \"neptools.memory_sink\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.sink\n template<>\n void TypeRegisterTraits<::Neptools::Sink>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n static_cast<::Libshit::NotNull<Libshit::RefCountedPtr<::Neptools::Sink> > (*)(::boost::filesystem::path, ::Neptools::FilePosition, bool)>(::Neptools::Sink::ToFile)\n >(\"to_file\");\n bld.AddFunction<\n static_cast<::Libshit::NotNull<Libshit::RefCountedPtr<::Neptools::Sink> > (*)()>(::Neptools::Sink::ToStdOut)\n >(\"to_std_out\");\n bld.AddFunction<\n static_cast<::Neptools::FilePosition (::Neptools::Sink::*)() const noexcept>(&::Neptools::Sink::Tell)\n >(\"tell\");\n bld.AddFunction<\n static_cast<void (::Neptools::Sink::*)(std::string_view)>(&::Neptools::Sink::Write<Check::Throw>)\n >(\"write\");\n bld.AddFunction<\n static_cast<void (::Neptools::Sink::*)(::Neptools::FileMemSize)>(&::Neptools::Sink::Pad<Check::Throw>)\n >(\"pad\");\n bld.AddFunction<\n static_cast<void (::Neptools::Sink::*)()>(&::Neptools::Sink::Flush)\n >(\"flush\");\n bld.AddFunction<\n static_cast<void (::Neptools::Sink::*)(::boost::endian::little_uint8_t)>(&::Neptools::Sink::WriteLittleUint8<Check::Throw>)\n >(\"write_little_uint8\");\n bld.AddFunction<\n static_cast<void (::Neptools::Sink::*)(::boost::endian::little_uint16_t)>(&::Neptools::Sink::WriteLittleUint16<Check::Throw>)\n >(\"write_little_uint16\");\n bld.AddFunction<\n static_cast<void (::Neptools::Sink::*)(::boost::endian::little_uint32_t)>(&::Neptools::Sink::WriteLittleUint32<Check::Throw>)\n >(\"write_little_uint32\");\n bld.AddFunction<\n static_cast<void (::Neptools::Sink::*)(::boost::endian::little_uint64_t)>(&::Neptools::Sink::WriteLittleUint64<Check::Throw>)\n >(\"write_little_uint64\");\n bld.AddFunction<\n static_cast<void (::Neptools::Sink::*)(const std::string &)>(&::Neptools::Sink::WriteCString<Check::Throw>)\n >(\"write_cstring\");\n lua_getfield(bld, -2, \"__gc\"); bld.SetField(\"close\");\n }\n static TypeRegister::StateRegister<::Neptools::Sink> reg_neptools_sink;\n\n // class neptools.memory_sink\n template<>\n void TypeRegisterTraits<::Neptools::MemorySink>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::MemorySink, ::Neptools::Sink>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::MemorySink>::Make<LuaGetRef<::Neptools::FileMemSize>>,\n static_cast<::Libshit::NotNull<Libshit::SmartPtr<::Neptools::MemorySink> > (*)(std::string_view)>(&Neptools::MemorySinkFromLua)\n >(\"new\");\n bld.AddFunction<\n static_cast<std::string_view (::Neptools::MemorySink::*)() const noexcept>(&::Neptools::MemorySink::GetStringView)\n >(\"to_string\");\n\n }\n static TypeRegister::StateRegister<::Neptools::MemorySink> reg_neptools_memory_sink;\n\n}\n#endif\n" }, { "alpha_fraction": 0.6560605764389038, "alphanum_fraction": 0.7303030490875244, "avg_line_length": 46.14285659790039, "blob_id": "374ca704ef9343a62f786190bd68b863d8917554", "content_id": "edc264c8a7ca195275437142074a49667e5e3dd1", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 660, "license_type": "permissive", "max_line_length": 76, "num_lines": 14, "path": "/tools/ci_conf.clang-msvc.sh", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "source tools/ci_conf_wincommon.sh\n\nrun export CFLAGS=\"-target i386-pc-windows-msvc18-m32 -march=x86-64 \\\n -fms-compatibility-version=18 \\\n -Xclang -internal-isystem -Xclang /mnt/msvc/vc12/include \\\n -Xclang -internal-isystem -Xclang /mnt/msvc/vc12/win_sdk/include/um \\\n -Xclang -internal-isystem -Xclang /mnt/msvc/vc12/win_sdk/include/shared\"\nrun export CXXFLAGS=\"$CFLAGS -DDOCTEST_CONFIG_COLORS_ANSI\"\nrun export LINKFLAGS=\"-target i386-pc-windows-msvc18-m32 -march=x86-64\\\n -fuse-ld=lld \\\n -L/mnt/msvc/vc12/lib \\\n -L/mnt/msvc/vc12/win_sdk/lib/winv6.3/um/x86\"\nrun export WINRC=x86_64-w64-mingw32-windres\nrun export WINRCFLAGS='-F pe-i386'\n" }, { "alpha_fraction": 0.595995306968689, "alphanum_fraction": 0.6493914127349854, "avg_line_length": 27.617977142333984, "blob_id": "11ecd4bbd51c4e041d0c0038ace5d9e86c726ced", "content_id": "981abf327fac56fad89da978bf52bcfc96600899", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2547, "license_type": "permissive", "max_line_length": 76, "num_lines": 89, "path": "/src/format/stsc/header.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_F87DF453_742A_4C38_8660_ABC81ACB04B8\n#define UUID_F87DF453_742A_4C38_8660_ABC81ACB04B8\n#pragma once\n\n#include \"file.hpp\"\n#include \"../../source.hpp\"\n#include \"../item.hpp\"\n\n#include <boost/endian/arithmetic.hpp>\n\n#include <string_view>\n\nnamespace Neptools::Stsc\n{\n\n class HeaderItem final : public Item\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n struct Header\n {\n char magic[4];\n boost::endian::little_uint32_t entry_point;\n boost::endian::little_uint32_t flags;\n\n void Validate(FilePosition size) const;\n };\n static_assert(sizeof(Header) == 12);\n\n struct ExtraHeader2Ser\n {\n boost::endian::little_uint16_t field_0;\n boost::endian::little_uint16_t field_2;\n boost::endian::little_uint16_t field_4;\n boost::endian::little_uint16_t field_6;\n boost::endian::little_uint16_t field_8;\n boost::endian::little_uint16_t field_a;\n boost::endian::little_uint16_t field_c;\n };\n static_assert(sizeof(ExtraHeader2Ser) == 14);\n\n class LIBSHIT_LUAGEN(name=\"extra_headers_2\") ExtraHeaders2\n : public Libshit::Lua::ValueObject\n {\n LIBSHIT_LUA_CLASS;\n\n public:\n std::uint16_t field_0;\n std::uint16_t field_2;\n std::uint16_t field_4;\n std::uint16_t field_6;\n std::uint16_t field_8;\n std::uint16_t field_a;\n std::uint16_t field_c;\n\n ExtraHeaders2(\n std::uint16_t field_0, std::uint16_t field_2, std::uint16_t field_4,\n std::uint16_t field_6, std::uint16_t field_8, std::uint16_t field_a,\n std::uint16_t field_c) noexcept\n : field_0{field_0}, field_2{field_2}, field_4{field_4},\n field_6{field_6}, field_8{field_8}, field_a{field_a},\n field_c{field_c} {}\n };\n\n HeaderItem(Key k, Context& ctx, Source src);\n HeaderItem(\n Key k, Context& ctx, Libshit::NotNull<LabelPtr> entry_point,\n std::optional<std::string_view> extra_headers_1,\n std::optional<ExtraHeaders2> extra_headers_2,\n std::optional<uint16_t> extra_headers_4);\n static HeaderItem& CreateAndInsert(ItemPointer ptr, Flavor flavor);\n\n FilePosition GetSize() const noexcept override;\n\n Libshit::NotNull<LabelPtr> entry_point;\n\n std::optional<std::array<std::uint8_t, 32>> extra_headers_1;\n std::optional<ExtraHeaders2> extra_headers_2;\n std::optional<std::uint16_t> extra_headers_4;\n\n private:\n void Parse_(Context& ctx, Source& src);\n void Dump_(Sink& sink) const override;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n };\n\n}\n\n#endif\n" }, { "alpha_fraction": 0.5595816373825073, "alphanum_fraction": 0.5720167756080627, "avg_line_length": 33.10955047607422, "blob_id": "ab5a40a124839fe22a5e1dad2f4da588a3fa27aa", "content_id": "cd957ed8332430a9d98707b4f6d7ee5c17525e2f", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12143, "license_type": "permissive", "max_line_length": 92, "num_lines": 356, "path": "/src/dynamic_struct.lua.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_8BEC2FCA_66B2_48E5_A689_E29590320829\n#define UUID_8BEC2FCA_66B2_48E5_A689_E29590320829\n#pragma once\n\n#if !LIBSHIT_WITH_LUA\n#define NEPTOOLS_DYNAMIC_STRUCT_LUAGEN(name, ...)\n#define NEPTOOLS_DYNAMIC_STRUCT_TABLECTOR(...)\n#else\n\n#include \"dynamic_struct.hpp\"\n\n#include <libshit/lua/auto_table.hpp>\n#include <libshit/lua/user_type.hpp>\n#include <libshit/utils.hpp>\n\n#include <type_traits>\n#include <boost/integer.hpp>\n\nnamespace Neptools\n{\n\n namespace Detail\n {\n\n template <typename T, size_t N, typename... Args> struct IndexOfImpl;\n\n template <typename T, size_t N, typename... Args>\n struct IndexOfImpl<T, N, T, Args...>\n { static constexpr size_t VALUE = N; };\n\n template <typename T, size_t N, typename U, typename... Args>\n struct IndexOfImpl<T, N, U, Args...>\n { static constexpr size_t VALUE = IndexOfImpl<T,N+1,Args...>::VALUE; };\n\n template <typename T, typename... Args>\n constexpr size_t IndexOf = IndexOfImpl<T, 0, Args...>::VALUE;\n\n template <typename T>\n struct DynamicStructTypeTraitsName\n {\n static constexpr const char* NAME = Libshit::Lua::TYPE_NAME<T>;\n };\n\n }\n\n template <typename T, typename Enable = void>\n struct DynamicStructTypeTraits : Detail::DynamicStructTypeTraitsName<T>\n {\n static void Push(Libshit::Lua::StateRef vm, const void* ptr, size_t size)\n {\n LIBSHIT_ASSERT(size == sizeof(T)); (void) size;\n vm.Push(*static_cast<const T*>(ptr));\n }\n\n static void Get(Libshit::Lua::StateRef vm, int idx, void* ptr, size_t size)\n {\n LIBSHIT_ASSERT(size == sizeof(T)); (void) size;\n *static_cast<T*>(ptr) = vm.Check<T>(idx);\n }\n\n static constexpr bool SIZABLE = false;\n };\n\n // do not use standard lua names for them since they're only \"integer\"/\"number\"\n // as far as lua is concerned\n#define CNAME(type, name) \\\n template<> struct Detail::DynamicStructTypeTraitsName<type> \\\n { static constexpr const char* NAME = name; }\n CNAME(int8_t, \"int8\"); CNAME(int16_t, \"int16\");\n CNAME(int32_t, \"int32\"); CNAME(int64_t, \"int64\");\n CNAME(uint8_t, \"uint8\"); CNAME(uint16_t, \"uint16\");\n CNAME(uint32_t, \"uint32\"); CNAME(uint64_t, \"uint64\");\n CNAME(float, \"float\"); CNAME(double, \"double\");\n#undef CNAME\n\n template <typename... Args>\n struct DynamicStructTypeInfo\n {\n void (*push)(Libshit::Lua::StateRef vm, const void* ptr, size_t size);\n void (*get)(Libshit::Lua::StateRef vm, int idx, void* ptr, size_t size);\n const char* name;\n\n typename boost::uint_value_t<sizeof...(Args)-1>::least index;\n typename boost::uint_value_t<std::max({sizeof(Args)...})>::least size;\n bool sizable;\n };\n\n template <typename... Args>\n inline constexpr const DynamicStructTypeInfo<Args...> infos[sizeof...(Args)] = {\n {\n &DynamicStructTypeTraits<Args>::Push,\n &DynamicStructTypeTraits<Args>::Get,\n DynamicStructTypeTraits<Args>::NAME,\n Detail::IndexOf<Args, Args...>,\n sizeof(Args),\n DynamicStructTypeTraits<Args>::SIZABLE,\n }...,\n };\n\n template <typename... Args>\n struct DynamicStructBuilderLua\n {\n using FakeClass = typename DynamicStruct<Args...>::TypeBuilder;\n\n LIBSHIT_NOLUA\n static const DynamicStructTypeInfo<Args...>&\n GetInfo(Libshit::Lua::StateRef vm, Libshit::Lua::Raw<LUA_TSTRING> name)\n {\n LIBSHIT_LUA_GETTOP(vm, top);\n\n int r = lua_rawgetp(vm, LUA_REGISTRYINDEX, &infos<Args...>); //+1\n LIBSHIT_ASSERT(r);\n lua_pushvalue(vm, name); //+2\n r = lua_rawget(vm, -2); //+2\n if (Libshit::Lua::IsNoneOrNil(r))\n luaL_error(vm, \"Invalid type %s\", vm.Get<const char*, true>(name));\n\n LIBSHIT_ASSERT(r == LUA_TLIGHTUSERDATA);\n auto ret = lua_touserdata(vm, -1);\n LIBSHIT_ASSERT(ret);\n lua_pop(vm, 2); //+0\n\n LIBSHIT_LUA_CHECKTOP(vm, top);\n return *static_cast<DynamicStructTypeInfo<Args...>*>(ret);\n }\n\n // bld:add(type, size) -> bld\n static Libshit::Lua::RetNum Add(\n Libshit::Lua::StateRef vm,\n typename DynamicStruct<Args...>::TypeBuilder& bld,\n Libshit::Lua::Raw<LUA_TSTRING> name, size_t size)\n {\n LIBSHIT_LUA_GETTOP(vm, top);\n auto& t = GetInfo(vm, name);\n if (!t.sizable && t.size != size)\n luaL_error(vm, \"Type %s is not sizable\", t.name);\n bld.Add(t.index, size);\n\n lua_pushvalue(vm, 1);\n LIBSHIT_LUA_CHECKTOP(vm, top+1);\n return 1;\n }\n\n // bld:add(type) -> bld\n static Libshit::Lua::RetNum Add(\n Libshit::Lua::StateRef vm,\n typename DynamicStruct<Args...>::TypeBuilder& bld,\n Libshit::Lua::Raw<LUA_TSTRING> name)\n {\n LIBSHIT_LUA_GETTOP(vm, top);\n auto& t = GetInfo(vm, name);\n if (t.sizable)\n luaL_error(vm, \"Type %s requires size\", t.name);\n bld.Add(t.index, t.size);\n\n lua_pushvalue(vm, 1);\n LIBSHIT_LUA_CHECKTOP(vm, top+1);\n return 1;\n }\n };\n\n template <typename... Args>\n struct DynamicStructTypeLua\n {\n using FakeClass = typename DynamicStruct<Args...>::Type;\n using Builder = typename DynamicStruct<Args...>::TypeBuilder;\n using BuilderLua = DynamicStructBuilderLua<Args...>;\n\n // type[i] -> {type=string,size=int}|nil\n static Libshit::Lua::RetNum Get(\n Libshit::Lua::StateRef vm,\n const typename DynamicStruct<Args...>::Type& t,\n size_t i) noexcept\n {\n LIBSHIT_LUA_GETTOP(vm, top);\n if (i >= t.item_count)\n {\n lua_pushnil(vm); // +1\n LIBSHIT_LUA_CHECKTOP(vm, top+1);\n return 1;\n }\n LIBSHIT_ASSERT(t.items[i].idx < sizeof...(Args));\n\n const auto& info = infos<Args...>[t.items[i].idx];\n lua_createtable(vm, 0, 2); // +1\n lua_pushstring(vm, info.name); // +2\n lua_setfield(vm, -2, \"type\"); // +1\n\n lua_pushinteger(vm, info.size); // +2\n lua_setfield(vm, -2, \"size\"); // +1\n\n LIBSHIT_LUA_CHECKTOP(vm, top+1);\n return 1;\n }\n\n static void Get(\n const typename DynamicStruct<Args...>::Type&,\n Libshit::Lua::VarArg) noexcept {}\n\n LIBSHIT_NOLUA\n // {\"name\",size} or {name=\"name\",size=size}\n // size optional\n static void AddTableType(Libshit::Lua::StateRef vm, Builder& bld)\n {\n LIBSHIT_LUA_GETTOP(vm, top);\n int size_type = LUA_TSTRING; // whatever, just be invalid\n if (lua_rawgeti(vm, -1, 1) == LUA_TSTRING) // +1\n size_type = lua_rawgeti(vm, -2, 2); // +2\n else if (lua_pop(vm, 1); lua_getfield(vm, -1, \"name\") == LUA_TSTRING) // +1\n size_type = lua_getfield(vm, -2, \"size\"); // +2\n\n if (Libshit::Lua::IsNoneOrNil(size_type))\n BuilderLua::Add(vm, bld, {lua_absindex(vm, -2)}); // +3\n else if (size_type == LUA_TNUMBER)\n BuilderLua::Add(vm, bld, {lua_absindex(vm, -2)},\n vm.Get<int, true>(-1)); // +3\n else\n luaL_error(vm, \"invalid type table, expected {string,integer} or \"\n \"{name=string, size=integer}\");\n\n lua_pop(vm, 2);\n LIBSHIT_LUA_CHECKTOP(vm, top+1);\n }\n\n // create from table\n static boost::intrusive_ptr<const FakeClass>\n New(Libshit::Lua::StateRef vm, Libshit::Lua::RawTable tbl)\n {\n Builder bld;\n auto [len, one] = vm.RawLen01(tbl);\n bld.Reserve(len);\n vm.Fori(tbl, one, len, [&](size_t, int type)\n {\n if (type == LUA_TSTRING)\n BuilderLua::Add(vm, bld, {lua_absindex(vm, -1)}); // +1\n else if (type == LUA_TTABLE)\n AddTableType(vm, bld); // +1\n else\n vm.TypeError(false, \"string or table\", -1);\n\n lua_pop(vm, 1); // 0\n });\n\n return bld.Build();\n }\n };\n\n template <typename... Args>\n struct DynamicStructLua\n {\n using FakeClass = DynamicStruct<Args...>; // must be first\n static_assert(sizeof...(Args) > 0);\n\n static Libshit::Lua::RetNum Get(\n Libshit::Lua::StateRef vm, const DynamicStruct<Args...>& s,\n size_t i) noexcept\n {\n if (i >= s.GetSize())\n {\n lua_pushnil(vm);\n return 1;\n }\n auto idx = s.GetTypeIndex(i);\n LIBSHIT_ASSERT(idx < sizeof...(Args));\n infos<Args...>[idx].push(vm, s.GetData(i), s.GetSize(i));\n return 1;\n }\n static void Get(\n const DynamicStruct<Args...>&, Libshit::Lua::VarArg) noexcept {}\n\n static void Set(\n Libshit::Lua::StateRef vm, DynamicStruct<Args...>& s, size_t i,\n Libshit::Lua::Any val)\n {\n if (i >= s.GetSize())\n LIBSHIT_THROW(std::out_of_range, \"DynamicStruct\");\n auto idx = s.GetTypeIndex(i);\n LIBSHIT_ASSERT(idx < sizeof...(Args));\n infos<Args...>[idx].get(vm, val, s.GetData(i), s.GetSize(i));\n }\n\n static Libshit::Lua::RetNum ToTable(\n Libshit::Lua::StateRef vm, DynamicStruct<Args...>& s)\n {\n auto size = s.GetSize();\n lua_createtable(vm, size ? size-1 : size, 0); // +1\n for (size_t i = 0; i < size; ++i)\n {\n auto idx = s.GetTypeIndex(i);\n LIBSHIT_ASSERT(idx < sizeof...(Args));\n infos<Args...>[idx].push(vm, s.GetData(i), s.GetSize(i)); // +2\n lua_rawseti(vm, -2, i); // +1\n }\n return 1;\n }\n\n static boost::intrusive_ptr<FakeClass> New(\n Libshit::Lua::StateRef vm, const typename FakeClass::TypePtr type,\n Libshit::Lua::RawTable vals)\n {\n auto s = FakeClass::New(type);\n size_t i = 0;\n vm.Ipairs01(vals, [&](size_t, int)\n { Set(vm, *s, i++, {lua_absindex(vm, -1)}); });\n return s;\n }\n\n LIBSHIT_NOLUA static void Register(Libshit::Lua::TypeBuilder& bld)\n {\n // create type table\n lua_createtable(bld, sizeof...(Args)-1, 0); //+1\n\n for (size_t i = 0; i < sizeof...(Args); ++i)\n {\n lua_pushlightuserdata(\n bld, Libshit::implicit_const_cast<void*>(&infos<Args...>[i])); //+2\n lua_setfield(bld, -2, infos<Args...>[i].name); //+1\n }\n lua_rawsetp(bld, LUA_REGISTRYINDEX, infos<Args...>); //+0\n\n luaL_getmetatable(bld, \"libshit_ipairs\");\n bld.SetField(\"__ipairs\");\n }\n };\n\n}\n\n#define NEPTOOLS_DYNAMIC_STRUCT_TABLECTOR(...) \\\n /* workaround can't specialize for nested classes in template class, because \\\n well, including a wrapper around cairo in the standard is more important \\\n than fixing problems like this */ \\\n template<> struct Libshit::Lua::GetTableCtor< \\\n boost::intrusive_ptr<const ::Neptools::DynamicStruct<__VA_ARGS__>::Type>> \\\n : std::integral_constant<::Libshit::Lua::TableCtorPtr< \\\n boost::intrusive_ptr< \\\n const ::Neptools::DynamicStruct<__VA_ARGS__>::Type>>, \\\n ::Neptools::DynamicStructTypeLua<__VA_ARGS__>::New> {}\n#define NEPTOOLS_DYNAMIC_STRUCT_LUAGEN(nam, ...) \\\n template class ::Neptools::DynamicStruct<__VA_ARGS__>::TypeBuilder; \\\n template struct ::Neptools::DynamicStructLua<__VA_ARGS__>; \\\n template struct ::Neptools::DynamicStructBuilderLua<__VA_ARGS__>; \\\n template struct ::Neptools::DynamicStructTypeLua<__VA_ARGS__>; \\\n template<> struct Libshit::Lua::GetTableCtor< \\\n ::Libshit::NotNull<boost::intrusive_ptr<::Neptools::DynamicStruct<__VA_ARGS__>>>> \\\n : std::integral_constant<::Libshit::Lua::TableCtorPtr< \\\n ::Libshit::NotNull<boost::intrusive_ptr<::Neptools::DynamicStruct<__VA_ARGS__>>>>, \\\n nullptr> {}; \\\n LIBSHIT_LUA_TEMPLATE(DynStructBind##nam, (name=#nam), \\\n ::Neptools::DynamicStruct<__VA_ARGS__>); \\\n LIBSHIT_LUA_TEMPLATE(DynStructTypeBind##nam, (name=#nam..\".type\"), \\\n ::Neptools::DynamicStruct<__VA_ARGS__>::Type); \\\n LIBSHIT_LUA_TEMPLATE(DynStructBldBind##nam, (name=#nam..\".builder\"), \\\n ::Neptools::DynamicStruct<__VA_ARGS__>::TypeBuilder)\n\n#endif\n#endif\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 25, "blob_id": "14f992792223bc4c26ccb0a3b3a01699cf2ac4b1", "content_id": "14e0ecc6593bddabb738b8c9545f982121bb21fc", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 52, "license_type": "permissive", "max_line_length": 29, "num_lines": 2, "path": "/src/endian.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"endian.hpp\"\n#include \"endian.binding.hpp\"\n" }, { "alpha_fraction": 0.6242905855178833, "alphanum_fraction": 0.6254256367683411, "avg_line_length": 27.419355392456055, "blob_id": "9f0d41ee4d5766205864df893e6368b81e6504f4", "content_id": "4283d0e30baed8d8118c12e6807cf5d415506755", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 881, "license_type": "permissive", "max_line_length": 90, "num_lines": 31, "path": "/tools/ci_conf.default.sh", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "function before_build()\n{\n run ln -nsf /opt/boost libshit/ext/boost\n\n run rm -f test*.xml\n # should remove exactly the same items jenkins put into artifacts to prevent\n # stale files ending up in archives\n run rm -f build/stcm-editor build/*.{debug,exe,dll,pdb} \\\n build/libshit/ext/luajit-ljx{,.exe,.debug,.pdb} \\\n build/libshit/ext/jit/*\n}\nbuild_opts=(-j2)\n\nif [[ $mode = rel ]]; then\n mode_arg=(--release)\nelif [[ $mode = rel-test ]]; then\n mode_arg=(--release --with-tests)\nelse\n mode_arg=(--optimize-ext --with-tests)\nfi\n\nfunction build()\n{\n [[ $WAF_DISTCLEAN == true ]] && run ./waf distclean\n run ./waf --color=yes configure \"${config_opts[@]}\" \"${mode_arg[@]}\" --all-bundle\n run ./waf --color=yes build \"${build_opts[@]}\"\n}\n\ntests=(\n 'build/stcm-editor --xml-output=test.xml --test -fc --reporters=libshit-junit,console'\n)\n" }, { "alpha_fraction": 0.7250000238418579, "alphanum_fraction": 0.7583333253860474, "avg_line_length": 16.14285659790039, "blob_id": "17d4f3cc19cebe2b38c1881d030e5a4245072c6f", "content_id": "1b1dca56f47873d3604fedb0f7cfa00e313f9082", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 240, "license_type": "permissive", "max_line_length": 65, "num_lines": 14, "path": "/src/vita_plugin/cpk.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef GUARD_ACERBLY_PYROBORIC_HUSS_SMOFS_2629\n#define GUARD_ACERBLY_PYROBORIC_HUSS_SMOFS_2629\n#pragma once\n\n#include <string>\n\nnamespace Neptools::VitaPlugin\n{\n\n void Init(std::string data_path_in, std::string cache_path_in);\n\n}\n\n#endif\n" }, { "alpha_fraction": 0.5960969924926758, "alphanum_fraction": 0.6031934022903442, "avg_line_length": 23.157142639160156, "blob_id": "2978bd03d462a1ada7c482882611e81d1ba92236", "content_id": "fe8638be18d6754995ed32cc1260b7aebb19c196", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1691, "license_type": "permissive", "max_line_length": 82, "num_lines": 70, "path": "/src/format/raw_item.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"raw_item.hpp\"\n#include \"context.hpp\"\n#include <iomanip>\n\nnamespace Neptools\n{\n\n void RawItem::Dump_(Sink& sink) const\n {\n src.Dump(sink);\n }\n\n void RawItem::Inspect_(std::ostream& os, unsigned indent) const\n {\n Item::Inspect_(os, indent);\n os << \"raw(\" << Quoted(src) << \")\";\n }\n\n Libshit::NotNull<Libshit::RefCountedPtr<RawItem>> RawItem::InternalSlice(\n FilePosition spos, FilePosition slen)\n {\n LIBSHIT_ASSERT(spos+slen <= GetSize());\n auto ctx = GetContext();\n return ctx->Create<RawItem>(Source{src, spos, slen}, position+spos);\n }\n\n // split into 3 parts: 0...pos, pos...pos+nitem size, pos+nitem size...this size\n void RawItem::Split2(\n FilePosition pos, Libshit::NotNull<Libshit::SmartPtr<Item>> nitem)\n {\n auto len = nitem->GetSize();\n LIBSHIT_ASSERT(pos <= GetSize() && pos+len <= GetSize());\n auto rem_len = GetSize() - len - pos;\n\n if (pos == 0 && rem_len == 0)\n {\n Replace(std::move(nitem));\n return;\n }\n\n SliceSeq seq;\n if (pos != 0) seq.emplace_back(MakeNotNull(this), pos);\n seq.emplace_back(std::move(nitem), pos+len);\n if (rem_len > 0)\n if (pos == 0)\n seq.emplace_back(MakeNotNull(this), GetSize());\n else\n seq.emplace_back(InternalSlice(pos+len, rem_len), GetSize());\n\n Item::Slice(std::move(seq));\n if (pos == 0)\n {\n LIBSHIT_ASSERT(rem_len > 0);\n src.Slice(len, rem_len);\n }\n else\n src.Slice(0, pos);\n }\n\n RawItem& RawItem::Split(FilePosition offset, FilePosition size)\n {\n auto it = InternalSlice(offset, size);\n auto& ret = *it;\n Split2(offset, std::move(it));\n return ret;\n }\n\n}\n\n#include \"raw_item.binding.hpp\"\n" }, { "alpha_fraction": 0.593042254447937, "alphanum_fraction": 0.6280644536018372, "avg_line_length": 70.38333129882812, "blob_id": "21f52ee51c4f9f155473e5a6e489af1096523af6", "content_id": "608d0e8e5a62310efff0f92013dc308af206a84c", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4283, "license_type": "permissive", "max_line_length": 267, "num_lines": 60, "path": "/src/format/primitive_item.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\ntemplate <>\nconst char ::Neptools::PrimitiveItem<int32_t, int32_t, boost::endian::little_int32_t, 'i', 'n', 't', '3', '2'>::TYPE_NAME[] = \"neptools.int32_item\";\ntemplate <>\nconst char ::Neptools::PrimitiveItem<float, int32_t, boost::endian::little_int32_t, 'f', 'l', 'o', 'a', 't'>::TYPE_NAME[] = \"neptools.float_item\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.int32_item\n template<>\n void TypeRegisterTraits<::Neptools::PrimitiveItem<int32_t, int32_t, boost::endian::little_int32_t, 'i', 'n', 't', '3', '2'>>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::PrimitiveItem<int32_t, int32_t, boost::endian::little_int32_t, 'i', 'n', 't', '3', '2'>, ::Neptools::Item>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::PrimitiveItem<int32_t, int32_t, boost::endian::little_int32_t, 'i', 'n', 't', '3', '2'>>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<int>>,\n &::Libshit::Lua::TypeTraits<::Neptools::PrimitiveItem<int32_t, int32_t, boost::endian::little_int32_t, 'i', 'n', 't', '3', '2'>>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::Neptools::Source>>\n >(\"new\");\n bld.AddFunction<\n static_cast<::Neptools::PrimitiveItem<int32_t, int32_t, boost::endian::little_int32_t, 'i', 'n', 't', '3', '2'> & (*)(::Neptools::ItemPointer)>(::Neptools::PrimitiveItem<int32_t, int32_t, boost::endian::little_int32_t, 'i', 'n', 't', '3', '2'>::CreateAndInsert)\n >(\"create_and_insert\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::PrimitiveItem<int32_t, int32_t, boost::endian::little_int32_t, 'i', 'n', 't', '3', '2'>, int, &::Neptools::PrimitiveItem<int32_t, int32_t, boost::endian::little_int32_t, 'i', 'n', 't', '3', '2'>::value>\n >(\"get_value\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::PrimitiveItem<int32_t, int32_t, boost::endian::little_int32_t, 'i', 'n', 't', '3', '2'>, int, &::Neptools::PrimitiveItem<int32_t, int32_t, boost::endian::little_int32_t, 'i', 'n', 't', '3', '2'>::value>\n >(\"set_value\");\n\n }\n static TypeRegister::StateRegister<::Neptools::PrimitiveItem<int32_t, int32_t, boost::endian::little_int32_t, 'i', 'n', 't', '3', '2'>> reg_neptools_int32_item;\n\n // class neptools.float_item\n template<>\n void TypeRegisterTraits<::Neptools::PrimitiveItem<float, int32_t, boost::endian::little_int32_t, 'f', 'l', 'o', 'a', 't'>>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::PrimitiveItem<float, int32_t, boost::endian::little_int32_t, 'f', 'l', 'o', 'a', 't'>, ::Neptools::Item>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::PrimitiveItem<float, int32_t, boost::endian::little_int32_t, 'f', 'l', 'o', 'a', 't'>>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<float>>,\n &::Libshit::Lua::TypeTraits<::Neptools::PrimitiveItem<float, int32_t, boost::endian::little_int32_t, 'f', 'l', 'o', 'a', 't'>>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::Neptools::Source>>\n >(\"new\");\n bld.AddFunction<\n static_cast<::Neptools::PrimitiveItem<float, int32_t, boost::endian::little_int32_t, 'f', 'l', 'o', 'a', 't'> & (*)(::Neptools::ItemPointer)>(::Neptools::PrimitiveItem<float, int32_t, boost::endian::little_int32_t, 'f', 'l', 'o', 'a', 't'>::CreateAndInsert)\n >(\"create_and_insert\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::PrimitiveItem<float, int32_t, boost::endian::little_int32_t, 'f', 'l', 'o', 'a', 't'>, float, &::Neptools::PrimitiveItem<float, int32_t, boost::endian::little_int32_t, 'f', 'l', 'o', 'a', 't'>::value>\n >(\"get_value\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::PrimitiveItem<float, int32_t, boost::endian::little_int32_t, 'f', 'l', 'o', 'a', 't'>, float, &::Neptools::PrimitiveItem<float, int32_t, boost::endian::little_int32_t, 'f', 'l', 'o', 'a', 't'>::value>\n >(\"set_value\");\n\n }\n static TypeRegister::StateRegister<::Neptools::PrimitiveItem<float, int32_t, boost::endian::little_int32_t, 'f', 'l', 'o', 'a', 't'>> reg_neptools_float_item;\n\n}\n#endif\n" }, { "alpha_fraction": 0.6346644163131714, "alphanum_fraction": 0.6355140209197998, "avg_line_length": 23.52083396911621, "blob_id": "5edb2ca3a7400a8c7c414c6c524739e55e6c0bf9", "content_id": "79e97b7b8de11e487081428716de4e7a8abd10eb", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1177, "license_type": "permissive", "max_line_length": 84, "num_lines": 48, "path": "/src/utils.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"utils.hpp\"\n#include <libshit/char_utils.hpp>\n\n#include \"source.hpp\"\n#include <fstream>\n#include <iomanip>\n\n// workaround incompatibilities between clang+msvc libs, mingw ofstream (no wide\n// char open) and linux...\n#ifndef BOOST_FILESYSTEM_C_STR\n# define BOOST_FILESYSTEM_C_STR c_str()\n#endif\n\nnamespace Neptools\n{\n\n std::ofstream OpenOut(const boost::filesystem::path& pth)\n {\n std::ofstream os;\n os.exceptions(std::ios_base::failbit | std::ios_base::badbit);\n os.open(pth.BOOST_FILESYSTEM_C_STR, std::ios_base::out | std::ios_base::binary);\n return os;\n }\n\n std::ifstream OpenIn(const boost::filesystem::path& pth)\n {\n std::ifstream is;\n is.exceptions(std::ios_base::failbit | std::ios_base::badbit);\n is.open(pth.BOOST_FILESYSTEM_C_STR, std::ios_base::in | std::ios_base::binary);\n return is;\n }\n\n void DumpBytes(std::ostream& os, Source data)\n {\n os << '\"';\n\n bool hex = false;\n for (FilePosition offs = 0, size = data.GetSize(); offs < size; )\n {\n auto chunk = data.GetChunk(offs);\n for (char c : chunk)\n hex = Libshit::DumpByte(os, c, hex);\n offs += chunk.length();\n }\n os << '\"';\n }\n\n}\n" }, { "alpha_fraction": 0.6291690468788147, "alphanum_fraction": 0.6444318890571594, "avg_line_length": 27.532258987426758, "blob_id": "5776a0a583a10927d936bddecbf1f9dac68d8468", "content_id": "2d69d625af03e55b01844238d80b874b81e19a47", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1769, "license_type": "permissive", "max_line_length": 115, "num_lines": 62, "path": "/tools/vmrun.sh", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\nif [[ $# -lt 3 ]]; then\n echo \"Usage: $0 vm.opts test.xml files\" >&2\n exit 1\nfi\n\ndir=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\n\ntemp_img=img.img\nfifo=fifo\n# should set:\n# username: ssh login user\n# tmp_dir: temp dir inside vm\n# src_img: image that will be copied to $temp_img to use\n# qemu_opts: additional qemu options (bash array)\n# should probably contain: -enable-kvm -nodefaults -m -cpu -smp -rtc\n# -drive (with file=$temp_img), -netdev user, -loadvm\n# you have to modify this script if you don't want to use user networking\nsource \"$1\"\nshift\n\ntest_dest=\"$1\"\nshift\n\nset -eEx\nfunction cleanup() {\n \"$dir/qmp\" --path=qemu.sock quit\n exit 1\n}\ntrap cleanup ERR SIGTERM SIGINT\n\ncp --reflink=auto \"$src_img\" \"$temp_img\"\n\nqemu-system-x86_64 \\\n \"${qemu_opts[@]}\" \\\n -display none -monitor none \\\n -daemonize -qmp unix:qemu.sock,server,nowait\n\nfor i in $(seq 0 4); do\n port=$(python -c 'import socket; s=socket.socket(); s.bind((\"\", 0)); print(s.getsockname()[1]); s.close()')\n fwd=\"$(\"$dir/qmp\" --path=qemu.sock human-monitor-command \\\n --command-line=\"hostfwd_add tcp:127.0.0.1:$port-:22\")\"\n if [[ -z $fwd ]]; then break; fi\ndone\n\nscp -o StrictHostKeyChecking=no -P $port \"$@\" \"$username@localhost:$tmp_dir/\"\n\n# the braindead windows server closes connection on EOF, so fake something\nrm -f \"$fifo\" && mkfifo \"$fifo\"\nsleep 60 > \"$fifo\" &\nssh -o StrictHostKeyChecking=no -p $port $username@localhost \\\n \"cd $tmp_dir && stcm-editor --ansi-colors --xml-output=test.xml --test -fc --reporters=libshit-junit,console\" \\\n < \"$fifo\"\nkill %1\n\nscp -o StrictHostKeyChecking=no -P $port \\\n \"$username@localhost:$tmp_dir/test.xml\" \"$test_dest\"\n\n\"$dir/qmp\" --path=qemu.sock quit\n\nrm \"$temp_img\" \"$fifo\"\n" }, { "alpha_fraction": 0.7015706896781921, "alphanum_fraction": 0.7015706896781921, "avg_line_length": 29.559999465942383, "blob_id": "3ceed0dda2837a54a3541c274a5188fe4a55ce2d", "content_id": "d9097909ac63ae66cd9929f219e7e8e7276bf4f1", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 764, "license_type": "permissive", "max_line_length": 137, "num_lines": 25, "path": "/src/open.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::OpenFactory::TYPE_NAME[] = \"neptools.open_factory\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.open_factory\n template<>\n void TypeRegisterTraits<::Neptools::OpenFactory>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n static_cast<::Libshit::NotNull<::Neptools::OpenFactory::Ret> (*)(::Neptools::Source)>(::Neptools::OpenFactory::Open),\n static_cast<::Libshit::NotNull<::Neptools::OpenFactory::Ret> (*)(const ::boost::filesystem::path &)>(::Neptools::OpenFactory::Open)\n >(\"open\");\n\n }\n static TypeRegister::StateRegister<::Neptools::OpenFactory> reg_neptools_open_factory;\n\n}\n#endif\n" }, { "alpha_fraction": 0.670292317867279, "alphanum_fraction": 0.6750509738922119, "avg_line_length": 49.72413635253906, "blob_id": "0b0dcc671489d3d2abc28464e316b22c9e703f9f", "content_id": "82f5d42cc14c2e56c2c552697b4e9f35ba67daea", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2942, "license_type": "permissive", "max_line_length": 357, "num_lines": 58, "path": "/src/format/stcm/header.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Stcm::HeaderItem::TYPE_NAME[] = \"neptools.stcm.header_item\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.stcm.header_item\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::HeaderItem>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stcm::HeaderItem, ::Neptools::Item>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::HeaderItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<const ::Neptools::Stcm::HeaderItem::MsgType &>, LuaGetRef<::Libshit::NotNull<::Neptools::LabelPtr>>, LuaGetRef<::Libshit::NotNull<::Neptools::LabelPtr>>, LuaGetRef<::uint32_t>, LuaGetRef<::Neptools::LabelPtr>>\n >(\"new\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::HeaderItem & (*)(::Neptools::ItemPointer)>(::Neptools::Stcm::HeaderItem::CreateAndInsert)\n >(\"create_and_insert\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::HeaderItem, ::Neptools::Stcm::HeaderItem::MsgType, &::Neptools::Stcm::HeaderItem::msg>\n >(\"get_msg\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stcm::HeaderItem, ::Neptools::Stcm::HeaderItem::MsgType, &::Neptools::Stcm::HeaderItem::msg>\n >(\"set_msg\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::HeaderItem, ::Libshit::NotNull<::Neptools::LabelPtr>, &::Neptools::Stcm::HeaderItem::export_sec>\n >(\"get_export_sec\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stcm::HeaderItem, ::Libshit::NotNull<::Neptools::LabelPtr>, &::Neptools::Stcm::HeaderItem::export_sec>\n >(\"set_export_sec\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::HeaderItem, ::Libshit::NotNull<::Neptools::LabelPtr>, &::Neptools::Stcm::HeaderItem::collection_link>\n >(\"get_collection_link\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stcm::HeaderItem, ::Libshit::NotNull<::Neptools::LabelPtr>, &::Neptools::Stcm::HeaderItem::collection_link>\n >(\"set_collection_link\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::HeaderItem, ::Neptools::LabelPtr, &::Neptools::Stcm::HeaderItem::expansion>\n >(\"get_expansion\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stcm::HeaderItem, ::Neptools::LabelPtr, &::Neptools::Stcm::HeaderItem::expansion>\n >(\"set_expansion\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::HeaderItem, ::uint32_t, &::Neptools::Stcm::HeaderItem::field_28>\n >(\"get_field_28\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stcm::HeaderItem, ::uint32_t, &::Neptools::Stcm::HeaderItem::field_28>\n >(\"set_field_28\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::HeaderItem> reg_neptools_stcm_header_item;\n\n}\n#endif\n" }, { "alpha_fraction": 0.7292576432228088, "alphanum_fraction": 0.7379912734031677, "avg_line_length": 27.625, "blob_id": "dc6e4002c37e2b9c9c089dcd80b5df71ed2bf5d5", "content_id": "f527664e46de8e9bff4fd6458b737a4820280278", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 458, "license_type": "permissive", "max_line_length": 118, "num_lines": 16, "path": "/tools/ci_conf_wincommon.sh", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "run clang --version\n\nrun export HOST_CC=gcc\nrun export HOST_CXX=g++\nrun export HOST_CFLAGS=\nrun export HOST_CXXFLAGS=\nrun export HOST_LINKFLAGS=\nrun export AR=llvm-ar\nrun export CC=clang\nrun export CXX=clang++\nconfig_opts=(--lua-dll)\n\ntests=(\n 'wine build/stcm-editor.exe --ansi-colors --xml-output=test-wine.xml --test -fc --reporters=libshit-junit,console'\n 'tools/vmrun.sh /opt/win7-vm/vm.opts test-win7.xml build/stcm-editor.exe build/lua53.dll'\n)\n" }, { "alpha_fraction": 0.6173752546310425, "alphanum_fraction": 0.6229205131530762, "avg_line_length": 23.044445037841797, "blob_id": "576080e995df56059c1c13d5dd55ec7f2bcb3a23", "content_id": "a28bcfea17314078c1b703a582f3feb2b6888975", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1082, "license_type": "permissive", "max_line_length": 80, "num_lines": 45, "path": "/src/format/stcm/gbnl.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"gbnl.hpp\"\n#include \"data.hpp\"\n#include \"../context.hpp\"\n#include \"../gbnl_lua.hpp\"\n#include \"../raw_item.hpp\"\n\n#include <libshit/container/vector.lua.hpp>\n\nnamespace Neptools::Stcm\n{\n\n void GbnlItem::Dispose() noexcept\n {\n if (auto ctx = GetContextMaybe())\n if (auto file = ctx.DynamicPointerCast<File>())\n file->UnsetGbnl(*this);\n Item::Dispose();\n }\n\n GbnlItem& GbnlItem::CreateAndInsert(ItemPointer ptr)\n {\n auto x = RawItem::GetSource(ptr, -1);\n return x.ritem.SplitCreate<GbnlItem>(ptr.offset, x.src);\n }\n\n static DataFactory factory{[](DataItem& it)\n {\n auto child = dynamic_cast<RawItem*>(&it.GetChildren().front());\n if (child && child->GetSize() > sizeof(Gbnl::Header))\n {\n char buf[4];\n child->GetSource().Pread(child->GetSize() - sizeof(Gbnl::Header), buf, 4);\n if (memcmp(buf, \"GBNL\", 4) == 0)\n {\n GbnlItem::CreateAndInsert({child, 0});\n return true;\n }\n }\n return false;\n }};\n\n}\n\nLIBSHIT_STD_VECTOR_FWD(gbnl_struct, Neptools::Gbnl::StructPtr);\n#include \"gbnl.binding.hpp\"\n" }, { "alpha_fraction": 0.678905189037323, "alphanum_fraction": 0.6969292163848877, "avg_line_length": 26.740739822387695, "blob_id": "9de0837a17434165af27eb23f74c62b3b8b4945e", "content_id": "2ac5fbff0be0cc6eed7dee06a1f17de69d9a4ac1", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1498, "license_type": "permissive", "max_line_length": 77, "num_lines": 54, "path": "/src/format/stcm/expansion.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef GUARD_KNOBBILY_BROGUED_NET_REGISTER_TON_BESOTS_7814\n#define GUARD_KNOBBILY_BROGUED_NET_REGISTER_TON_BESOTS_7814\n#pragma once\n\n#include \"../item.hpp\"\n#include <boost/endian/arithmetic.hpp>\n\nnamespace Neptools::Stcm\n{\n\n class ExpansionItem final : public Item\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n struct Header\n {\n boost::endian::little_uint32_t index;\n boost::endian::little_uint32_t name;\n boost::endian::little_uint64_t ptr; // used by game engine\n boost::endian::little_uint32_t pad[16];\n\n void Validate(FilePosition file_size) const;\n };\n static_assert(sizeof(Header) == 0x50);\n\n ExpansionItem(Key k, Context& ctx, uint32_t index, LabelPtr name)\n : Item{k, ctx}, index{index}, name{name} {}\n LIBSHIT_NOLUA\n ExpansionItem(Key k, Context& ctx, const Header& hdr);\n static ExpansionItem& CreateAndInsert(ItemPointer ptr);\n\n FilePosition GetSize() const noexcept override { return sizeof(Header); }\n\n uint32_t index;\n Libshit::NotNull<LabelPtr> name;\n\n private:\n void Dump_(Sink& sink) const override;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n };\n\n class ExpansionsItem final : public ItemWithChildren\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n ExpansionsItem(Key k, Context& ctx) : ItemWithChildren{k, ctx} {}\n static ExpansionsItem& CreateAndInsert(ItemPointer ptr, uint32_t count);\n\n private:\n void Inspect_(std::ostream& os, unsigned indent) const override;\n };\n\n}\n#endif\n" }, { "alpha_fraction": 0.6285714507102966, "alphanum_fraction": 0.6285714507102966, "avg_line_length": 19, "blob_id": "48fe5b77015f850ec0592f0742f1c0c15e46539f", "content_id": "679ecaceffcc8d9250413f72741cdbdf065fe133", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 560, "license_type": "permissive", "max_line_length": 62, "num_lines": 28, "path": "/src/open.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"open.hpp\"\n\n#include <libshit/except.hpp>\n\nnamespace Neptools\n{\n\n auto OpenFactory::Open(Source src) -> Libshit::NotNull<Ret>\n {\n for (auto& x : GetStore())\n {\n auto ret = x(src);\n if (ret) return MakeNotNull(ret);\n }\n LIBSHIT_THROW(Libshit::DecodeError, \"Unknown input file\");\n }\n\n auto OpenFactory::Open(const boost::filesystem::path& fname)\n -> Libshit::NotNull<Ret>\n {\n LIBSHIT_ADD_INFOS(\n return Open(Source::FromFile(fname.native())),\n \"File name\", fname.string());\n }\n\n}\n\n#include \"open.binding.hpp\"\n" }, { "alpha_fraction": 0.5127972364425659, "alphanum_fraction": 0.5273189544677734, "avg_line_length": 34.08917236328125, "blob_id": "41b078b3d9c4e3250fbe3c1fdf74a0fc1ed4815e", "content_id": "d2d77f049962d7a691dd60f4df08f6bcf4022b68", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5509, "license_type": "permissive", "max_line_length": 96, "num_lines": 157, "path": "/wscript_user_sample.py", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "import os\ncompilers = ['gcc', 'clang', 'clang-msvc', 'clang-msvc64']\nconfigs = ['debug', 'rel-test', 'rel']\n\nimport itertools\nvariants = list(map(lambda x: '%s-%s' % x, itertools.product(compilers, configs)))\n\ndef my_configure(cfg):\n bdir = cfg.path.abspath()\n\n gcc = 'gcc'\n gxx = 'g++'\n clang_bin = os.path.expanduser('~/llvm/prefix/bin/')\n clang_flags = [\n '-stdlib=libc++', '-ferror-limit=5', '-ftemplate-backtrace-limit=0',\n '-march=native'\n ]\n clang_linkflags = [\n '-stdlib=libc++', '-fuse-ld=lld', '-march=native'\n ]\n\n vcdir = '/mnt/msvc/vc12'\n # i386 and x86_64\n clang_win32_tgt = [ '-target', 'i386-pc-windows-msvc18' ]\n clang_win64_tgt = [ '-target', 'x86_64-pc-windows-msvc18' ]\n clang_win_cxxflags = [\n '-march=x86-64',\n '-fms-compatibility-version=18',\n '-Xclang', '-internal-isystem', '-Xclang', vcdir+'/include',\n '-Xclang', '-internal-isystem', '-Xclang', vcdir+'/win_sdk/include/um',\n '-Xclang', '-internal-isystem', '-Xclang', vcdir+'/win_sdk/include/shared',\n '-DDOCTEST_CONFIG_COLORS_ANSI',\n '-ferror-limit=5',\n ]\n clang_win32_linkflags = clang_win32_tgt + [\n '-fuse-ld=lld',\n '-L%s/lib' % vcdir,\n '-L%s/win_sdk/lib/winv6.3/um/x86' % vcdir,\n ]\n clang_win64_linkflags = clang_win64_tgt + [\n '-fuse-ld=lld',\n '-L%s/lib/amd64' % vcdir,\n '-L%s/win_sdk/lib/winv6.3/um/x64' % vcdir,\n ]\n\n cfg.options.host_lua = 'luajit'\n cfg.options.lua_dll = True\n\n for comp in compilers:\n for conf in configs:\n var = '%s-%s' % (comp, conf)\n if var not in variants: continue\n\n cfg.setenv(var)\n if comp == 'gcc':\n cfg.env.AR = 'gcc-ar'\n cfg.env.CC = gcc\n cfg.env.CXX = gxx\n cfg.env.CXXFLAGS = ['-march=native']\n cfg.env.LINKFLAGS = ['-march=native']\n cfg.environ.pop('HOST_CC', None)\n cfg.environ.pop('HOST_CXX', None)\n cfg.options.all_system = None\n elif comp == 'clang':\n cfg.env.AR = clang_bin+'llvm-ar'\n cfg.env.CC = clang_bin+'clang'\n cfg.env.CXX = clang_bin+'clang++'\n cfg.env.CXXFLAGS = clang_flags\n cfg.env.LINKFLAGS = clang_linkflags\n cfg.environ.pop('HOST_CC', None)\n cfg.environ.pop('HOST_CXX', None)\n cfg.options.all_system = 'bundle'\n else: # clang-msvc*\n cfg.env.AR = clang_bin+'llvm-ar'\n cfg.env.CC = clang_bin+'clang'\n cfg.env.CXX = clang_bin+'clang++'\n cfg.environ['HOST_CC'] = 'gcc'\n cfg.environ['HOST_CXX'] = 'g++'\n cfg.options.all_system = 'bundle'\n\n if comp == 'clang-msvc':\n cfg.environ['WINRC'] = 'i686-w64-mingw32-windres'\n cfg.env.CXXFLAGS = cfg.env.CFLAGS = \\\n clang_win32_tgt + clang_win_cxxflags\n cfg.env.LINKFLAGS = clang_win32_linkflags\n elif comp == 'clang-msvc64':\n cfg.environ['WINRC'] = 'x86_64-w64-mingw32-windres'\n cfg.env.CXXFLAGS = cfg.env.CFLAGS = \\\n clang_win64_tgt + clang_win_cxxflags\n cfg.env.LINKFLAGS = clang_win64_linkflags\n else:\n error()\n\n cfg.options.optimize_ext = True\n if conf == 'debug':\n cfg.options.optimize = False\n cfg.options.release = False\n cfg.options.with_tests = True\n elif conf == 'rel-test':\n cfg.options.optimize = True\n cfg.options.release = True\n cfg.options.with_tests = True\n elif conf == 'rel':\n cfg.options.optimize = True\n cfg.options.release = True\n cfg.options.with_tests = False\n else:\n error()\n configure(cfg)\n\nfrom waflib.Configure import ConfigurationContext\nclass my_configure_cls(ConfigurationContext):\n cmd = 'my_configure'\n fun = 'my_configure'\n\nfrom waflib.Build import BuildContext, CleanContext, InstallContext, UninstallContext\n\ndef init(ctx):\n for x in variants:\n for y in (BuildContext, CleanContext, InstallContext, UninstallContext):\n name = y.__name__.replace('Context','').lower()\n class tmp(y):\n cmd = '%s-%s' % (name, x)\n variant = x\n\n\nfrom waflib import Utils, Build\nclass buildall_ctx(Build.BuildContext):\n cmd = fun = 'buildall'\n def compile(self):\n pass\n\ndef buildall(ctx):\n _build_many(ctx, variants)\n\ndef _build_many(ctx, variants):\n from waflib import Options, Task\n sem = Utils.threading.Semaphore(Options.options.jobs)\n def with_sem(f):\n def f2(self):\n sem.acquire()\n f(self)\n sem.release()\n return f2\n Task.TaskBase.process = with_sem(Task.TaskBase.process)\n\n threads = []\n for var in variants:\n cls = type(Build.BuildContext)(var, (Build.BuildContext,), {'cmd': var, 'variant': var})\n bld = cls(top_dir=ctx.top_dir, out_dir=ctx.out_dir)\n bld.targets = ctx.targets\n t = Utils.threading.Thread()\n t.run = bld.execute\n threads.append(t)\n\n for t in threads: t.start()\n for t in threads: t.join()\n" }, { "alpha_fraction": 0.6978417038917542, "alphanum_fraction": 0.6978417038917542, "avg_line_length": 23.173913955688477, "blob_id": "90a68d7b4230459612350afc4875549d11dab87b", "content_id": "556f126c2f231b1c79b72ba5b415fa66f01e0b2f", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 556, "license_type": "permissive", "max_line_length": 77, "num_lines": 23, "path": "/src/endian.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\nconst char ::Libshit::Lua::TypeName<::Neptools::Endian>::TYPE_NAME[] =\n \"neptools.endian\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.endian\n template<>\n void TypeRegisterTraits<::Neptools::Endian>::Register(TypeBuilder& bld)\n {\n\n bld.Add(\"BIG\", ::Neptools::Endian::BIG);\n bld.Add(\"LITTLE\", ::Neptools::Endian::LITTLE);\n\n }\n static TypeRegister::StateRegister<::Neptools::Endian> reg_neptools_endian;\n\n}\n#endif\n" }, { "alpha_fraction": 0.6720368266105652, "alphanum_fraction": 0.6956271529197693, "avg_line_length": 26.58730125427246, "blob_id": "1d74fe81cae109a60a02680dbc2fb45b1b20734f", "content_id": "bd206ff530350155718a26ca2dd8e66ceede6817", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1738, "license_type": "permissive", "max_line_length": 81, "num_lines": 63, "path": "/src/dumpable.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_C9446864_0020_4D2F_8E96_CBC6ADCCA3BE\n#define UUID_C9446864_0020_4D2F_8E96_CBC6ADCCA3BE\n#pragma once\n\n#include \"utils.hpp\"\n\n#include <libshit/lua/dynamic_object.hpp>\n#include <libshit/lua/type_traits.hpp>\n#include <libshit/meta.hpp>\n#include <libshit/shared_ptr.hpp>\n\n#include <boost/filesystem/path.hpp>\n\nnamespace Neptools\n{\n\n class TxtSerializable;\n class Sink;\n\n class Dumpable : public Libshit::Lua::DynamicObject\n {\n LIBSHIT_LUA_CLASS;\n public:\n Dumpable() = default;\n Dumpable(const Dumpable&) = delete;\n void operator=(const Dumpable&) = delete;\n virtual ~Dumpable() = default;\n\n virtual void Fixup() {};\n virtual FilePosition GetSize() const = 0;\n\n LIBSHIT_NOLUA\n virtual Libshit::NotNullSharedPtr<TxtSerializable>\n GetDefaultTxtSerializable(const Libshit::NotNullSharedPtr<Dumpable>& thiz);\n\n void Dump(Sink& os) const { return Dump_(os); }\n LIBSHIT_NOLUA\n void Dump(Sink&& os) const { return Dump_(os); }\n void Dump(const boost::filesystem::path& path) const;\n\n LIBSHIT_NOLUA\n void Inspect(std::ostream& os, unsigned indent = 0) const\n { return Inspect_(os, indent); }\n LIBSHIT_NOLUA\n void Inspect(std::ostream&& os, unsigned indent = 0) const\n { return Inspect_(os, indent); }\n void Inspect(const boost::filesystem::path& path) const;\n std::string Inspect() const;\n\n protected:\n static std::ostream& Indent(std::ostream& os, unsigned indent);\n\n private:\n virtual void Dump_(Sink& sink) const = 0;\n virtual void Inspect_(std::ostream& os, unsigned indent) const = 0;\n };\n\n std::ostream& operator<<(std::ostream& os, const Dumpable& dmp);\n\n inline Libshit::Lua::DynamicObject& GetDynamicObject(Dumpable& d) { return d; }\n\n}\n#endif\n" }, { "alpha_fraction": 0.6648608446121216, "alphanum_fraction": 0.6804758906364441, "avg_line_length": 61.3443717956543, "blob_id": "9e8db24b26bfc9a7b9d8ace4eb11f18fe0162b4f", "content_id": "7808b28330bee2a72c400ab8f5b42ae1bdddc3af", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9414, "license_type": "permissive", "max_line_length": 646, "num_lines": 151, "path": "/src/format/gbnl.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Gbnl::TYPE_NAME[] = \"neptools.gbnl\";\ntemplate <>\nconst char ::DynStructBindgbnl::TYPE_NAME[] = \"neptools.dynamic_struct_gbnl\";\ntemplate <>\nconst char ::DynStructTypeBindgbnl::TYPE_NAME[] = \"neptools.dynamic_struct_gbnl.type\";\ntemplate <>\nconst char ::DynStructBldBindgbnl::TYPE_NAME[] = \"neptools.dynamic_struct_gbnl.builder\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.gbnl\n template<>\n void TypeRegisterTraits<::Neptools::Gbnl>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Gbnl, ::Neptools::Dumpable, ::Neptools::TxtSerializable>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Gbnl>::Make<LuaGetRef<::Neptools::Source>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Gbnl>::Make<LuaGetRef<::Neptools::Endian>, LuaGetRef<bool>, LuaGetRef<::uint32_t>, LuaGetRef<::uint32_t>, LuaGetRef<::uint32_t>, LuaGetRef<Libshit::AT<::Neptools::Gbnl::Struct::TypePtr>>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Gbnl>::Make<LuaGetRef<::Libshit::Lua::StateRef>, LuaGetRef<::Neptools::Endian>, LuaGetRef<bool>, LuaGetRef<::uint32_t>, LuaGetRef<::uint32_t>, LuaGetRef<::uint32_t>, LuaGetRef<Libshit::AT<::Neptools::Gbnl::Struct::TypePtr>>, LuaGetRef<::Libshit::Lua::RawTable>>\n >(\"new\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Gbnl, ::Neptools::Endian, &::Neptools::Gbnl::endian>\n >(\"get_endian\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Gbnl, ::Neptools::Endian, &::Neptools::Gbnl::endian>\n >(\"set_endian\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Gbnl, bool, &::Neptools::Gbnl::is_gstl>\n >(\"get_is_gstl\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Gbnl, bool, &::Neptools::Gbnl::is_gstl>\n >(\"set_is_gstl\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Gbnl, ::uint32_t, &::Neptools::Gbnl::flags>\n >(\"get_flags\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Gbnl, ::uint32_t, &::Neptools::Gbnl::flags>\n >(\"set_flags\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Gbnl, ::uint32_t, &::Neptools::Gbnl::field_28>\n >(\"get_field_28\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Gbnl, ::uint32_t, &::Neptools::Gbnl::field_28>\n >(\"set_field_28\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Gbnl, ::uint32_t, &::Neptools::Gbnl::field_30>\n >(\"get_field_30\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Gbnl, ::uint32_t, &::Neptools::Gbnl::field_30>\n >(\"set_field_30\");\n bld.AddFunction<\n &::Libshit::Lua::GetSmartOwnedMember<::Neptools::Gbnl, ::Neptools::Gbnl::Messages, &::Neptools::Gbnl::messages>\n >(\"get_messages\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Gbnl, ::Neptools::Gbnl::Struct::TypePtr, &::Neptools::Gbnl::type>\n >(\"get_type\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Gbnl, ::Neptools::Gbnl::Struct::TypePtr, &::Neptools::Gbnl::type>\n >(\"set_type\");\n bld.AddFunction<\n static_cast<void (::Neptools::Gbnl::*)()>(&::Neptools::Gbnl::RecalcSize)\n >(\"recalc_size\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Gbnl> reg_neptools_gbnl;\n\n // class neptools.dynamic_struct_gbnl\n template<>\n void TypeRegisterTraits<::DynStructBindgbnl>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n static_cast<::boost::intrusive_ptr<::Neptools::DynamicStruct<int8_t, int16_t, int32_t, int64_t, float, ::Neptools::Gbnl::OffsetString, ::Neptools::Gbnl::FixStringTag, ::Neptools::Gbnl::PaddingTag>> (*)(::DynStructBindgbnl::TypePtr)>(::DynStructBindgbnl::New),\n static_cast<::boost::intrusive_ptr<::Neptools::DynamicStructLua<int8_t, int16_t, int32_t, int64_t, float, ::Neptools::Gbnl::OffsetString, ::Neptools::Gbnl::FixStringTag, ::Neptools::Gbnl::PaddingTag>::FakeClass> (*)(::Libshit::Lua::StateRef, const typename ::Neptools::DynamicStructLua<int8_t, int16_t, int32_t, int64_t, float, ::Neptools::Gbnl::OffsetString, ::Neptools::Gbnl::FixStringTag, ::Neptools::Gbnl::PaddingTag>::FakeClass::TypePtr, ::Libshit::Lua::RawTable)>(::Neptools::DynamicStructLua<int8_t, int16_t, int32_t, int64_t, float, ::Neptools::Gbnl::OffsetString, ::Neptools::Gbnl::FixStringTag, ::Neptools::Gbnl::PaddingTag>::New)\n >(\"new\");\n bld.AddFunction<\n static_cast<::size_t (::DynStructBindgbnl::*)() const noexcept>(&::DynStructBindgbnl::GetSize)\n >(\"get_size\");\n bld.AddFunction<\n static_cast<::size_t (::DynStructBindgbnl::*)() const noexcept>(&::DynStructBindgbnl::GetSize)\n >(\"__len\");\n bld.AddFunction<\n static_cast<const ::DynStructBindgbnl::TypePtr & (::DynStructBindgbnl::*)() const noexcept>(&::DynStructBindgbnl::GetType)\n >(\"get_type\");\n bld.AddFunction<\n static_cast<::Libshit::Lua::RetNum (*)(::Libshit::Lua::StateRef, const ::DynStructBindgbnl &, ::size_t) noexcept>(::Neptools::DynamicStructLua<int8_t, int16_t, int32_t, int64_t, float, ::Neptools::Gbnl::OffsetString, ::Neptools::Gbnl::FixStringTag, ::Neptools::Gbnl::PaddingTag>::Get),\n static_cast<void (*)(const ::DynStructBindgbnl &, ::Libshit::Lua::VarArg) noexcept>(::Neptools::DynamicStructLua<int8_t, int16_t, int32_t, int64_t, float, ::Neptools::Gbnl::OffsetString, ::Neptools::Gbnl::FixStringTag, ::Neptools::Gbnl::PaddingTag>::Get)\n >(\"get\");\n bld.AddFunction<\n static_cast<void (*)(::Libshit::Lua::StateRef, ::DynStructBindgbnl &, ::size_t, ::Libshit::Lua::Any)>(::Neptools::DynamicStructLua<int8_t, int16_t, int32_t, int64_t, float, ::Neptools::Gbnl::OffsetString, ::Neptools::Gbnl::FixStringTag, ::Neptools::Gbnl::PaddingTag>::Set)\n >(\"set\");\n bld.AddFunction<\n static_cast<::Libshit::Lua::RetNum (*)(::Libshit::Lua::StateRef, ::DynStructBindgbnl &)>(::Neptools::DynamicStructLua<int8_t, int16_t, int32_t, int64_t, float, ::Neptools::Gbnl::OffsetString, ::Neptools::Gbnl::FixStringTag, ::Neptools::Gbnl::PaddingTag>::ToTable)\n >(\"to_table\");\n::Neptools::DynamicStructLua<int8_t, int16_t, int32_t, int64_t, float, ::Neptools::Gbnl::OffsetString, ::Neptools::Gbnl::FixStringTag, ::Neptools::Gbnl::PaddingTag>::Register(bld);\n }\n static TypeRegister::StateRegister<::DynStructBindgbnl> reg_neptools_dynamic_struct_gbnl;\n\n // class neptools.dynamic_struct_gbnl.type\n template<>\n void TypeRegisterTraits<::DynStructTypeBindgbnl>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::DynStructTypeBindgbnl, ::size_t, &::DynStructTypeBindgbnl::item_count>\n >(\"get_item_count\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::DynStructTypeBindgbnl, ::size_t, &::DynStructTypeBindgbnl::item_count>\n >(\"__len\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::DynStructTypeBindgbnl, ::size_t, &::DynStructTypeBindgbnl::byte_size>\n >(\"get_byte_size\");\n bld.AddFunction<\n static_cast<::Libshit::Lua::RetNum (*)(::Libshit::Lua::StateRef, const typename ::DynStructTypeBindgbnl &, ::size_t) noexcept>(::Neptools::DynamicStructTypeLua<int8_t, int16_t, int32_t, int64_t, float, ::Neptools::Gbnl::OffsetString, ::Neptools::Gbnl::FixStringTag, ::Neptools::Gbnl::PaddingTag>::Get),\n static_cast<void (*)(const typename ::DynStructTypeBindgbnl &, ::Libshit::Lua::VarArg) noexcept>(::Neptools::DynamicStructTypeLua<int8_t, int16_t, int32_t, int64_t, float, ::Neptools::Gbnl::OffsetString, ::Neptools::Gbnl::FixStringTag, ::Neptools::Gbnl::PaddingTag>::Get)\n >(\"get\");\n bld.AddFunction<\n static_cast<::boost::intrusive_ptr<const ::Neptools::DynamicStructTypeLua<int8_t, int16_t, int32_t, int64_t, float, ::Neptools::Gbnl::OffsetString, ::Neptools::Gbnl::FixStringTag, ::Neptools::Gbnl::PaddingTag>::FakeClass> (*)(::Libshit::Lua::StateRef, ::Libshit::Lua::RawTable)>(::Neptools::DynamicStructTypeLua<int8_t, int16_t, int32_t, int64_t, float, ::Neptools::Gbnl::OffsetString, ::Neptools::Gbnl::FixStringTag, ::Neptools::Gbnl::PaddingTag>::New)\n >(\"new\");\n\n }\n static TypeRegister::StateRegister<::DynStructTypeBindgbnl> reg_neptools_dynamic_struct_gbnl_type;\n\n // class neptools.dynamic_struct_gbnl.builder\n template<>\n void TypeRegisterTraits<::DynStructBldBindgbnl>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::DynStructBldBindgbnl>::Make<>\n >(\"new\");\n bld.AddFunction<\n static_cast<::DynStructBindgbnl::TypePtr (::DynStructBldBindgbnl::*)() const>(&::DynStructBldBindgbnl::Build)\n >(\"build\");\n bld.AddFunction<\n static_cast<::Libshit::Lua::RetNum (*)(::Libshit::Lua::StateRef, typename ::DynStructBindgbnl::TypeBuilder &, ::Libshit::Lua::Raw<4>, ::size_t)>(::Neptools::DynamicStructBuilderLua<int8_t, int16_t, int32_t, int64_t, float, ::Neptools::Gbnl::OffsetString, ::Neptools::Gbnl::FixStringTag, ::Neptools::Gbnl::PaddingTag>::Add),\n static_cast<::Libshit::Lua::RetNum (*)(::Libshit::Lua::StateRef, typename ::DynStructBindgbnl::TypeBuilder &, ::Libshit::Lua::Raw<4>)>(::Neptools::DynamicStructBuilderLua<int8_t, int16_t, int32_t, int64_t, float, ::Neptools::Gbnl::OffsetString, ::Neptools::Gbnl::FixStringTag, ::Neptools::Gbnl::PaddingTag>::Add)\n >(\"add\");\n\n }\n static TypeRegister::StateRegister<::DynStructBldBindgbnl> reg_neptools_dynamic_struct_gbnl_builder;\n\n}\n#endif\n" }, { "alpha_fraction": 0.5990513563156128, "alphanum_fraction": 0.6067708134651184, "avg_line_length": 26.35877799987793, "blob_id": "a003bf6c4be4d67ce3e3bf7cd71471b449d8152c", "content_id": "c2760026c2dcc66c0ff9c9c5253c7499d18d7eab", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10752, "license_type": "permissive", "max_line_length": 105, "num_lines": 393, "path": "/src/source.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"source.hpp\"\n#include \"sink.hpp\"\n\n#include <libshit/char_utils.hpp>\n#include <libshit/except.hpp>\n#include <libshit/lua/function_call.hpp>\n#include <libshit/platform.hpp>\n\n#include <fstream>\n#include <iostream>\n\n#if !LIBSHIT_OS_IS_WINDOWS\n# include <unistd.h>\n#endif\n\n#include <libshit/doctest.hpp>\n\n#define LIBSHIT_LOG_NAME \"source\"\n#include <libshit/logger_helper.hpp>\n\nnamespace Neptools\n{\n TEST_SUITE_BEGIN(\"Neptools::Source\");\n\n namespace\n {\n\n template <typename T>\n struct UnixLike : public Source::Provider\n {\n UnixLike(Libshit::LowIo io, boost::filesystem::path file_name,\n FilePosition size)\n : Source::Provider{Libshit::Move(file_name), size},\n io{Libshit::Move(io)} {}\n\n void Destroy() noexcept;\n\n void Pread(FilePosition offs, Byte* buf, FileMemSize len) override;\n void EnsureChunk(FilePosition i);\n\n Libshit::LowIo io;\n };\n\n struct MmapProvider final : public UnixLike<MmapProvider>\n {\n MmapProvider(Libshit::LowIo&& fd, boost::filesystem::path file_name,\n FilePosition size);\n ~MmapProvider() noexcept override { Destroy(); }\n\n static FileMemSize CHUNK_SIZE;\n void* ReadChunk(FilePosition offs, FileMemSize size);\n void DeleteChunk(size_t i);\n };\n\n struct UnixProvider final : public UnixLike<UnixProvider>\n {\n //using UnixLike::UnixLike;\n // workaround clang bug...\n UnixProvider(Libshit::LowIo&& io, boost::filesystem::path file_name,\n FilePosition size)\n : UnixLike{Libshit::Move(io), Libshit::Move(file_name), size} {}\n ~UnixProvider() noexcept override { Destroy(); }\n\n static FileMemSize CHUNK_SIZE;\n void* ReadChunk(FilePosition offs, FileMemSize size);\n void DeleteChunk(size_t i);\n };\n\n struct StringProvider final : public Source::Provider\n {\n StringProvider(boost::filesystem::path file_name, std::string str)\n : Source::Provider(Libshit::Move(file_name), str.size()),\n str{Libshit::Move(str)}\n {\n LruPush(reinterpret_cast<const Byte*>(this->str.data()),\n 0, this->str.size());\n }\n\n void Pread(FilePosition, Byte*, FileMemSize) override\n { LIBSHIT_UNREACHABLE(\"StringProvider Pread\"); }\n\n std::string str;\n };\n\n struct UniquePtrProvider final : public Source::Provider\n {\n UniquePtrProvider(boost::filesystem::path file_name,\n std::unique_ptr<char[]> data, std::size_t len)\n : Source::Provider(Libshit::Move(file_name), len),\n data{Libshit::Move(data)}\n { LruPush(reinterpret_cast<const Byte*>(this->data.get()), 0, len); }\n\n void Pread(FilePosition, Byte*, FileMemSize) override\n { LIBSHIT_UNREACHABLE(\"UniquePtrProvider Pread\"); }\n\n std::unique_ptr<char[]> data;\n };\n\n }\n\n\n Source Source::FromFile(const boost::filesystem::path& fname)\n {\n LIBSHIT_ADD_INFOS(return FromFile_(fname), \"File name\", fname.string());\n }\n\n Source Source::FromFile_(const boost::filesystem::path& fname)\n {\n Libshit::LowIo io{fname.c_str(), Libshit::LowIo::Permission::READ_ONLY,\n Libshit::LowIo::Mode::OPEN_ONLY};\n\n FilePosition size = io.GetSize();\n\n Libshit::SmartPtr<Provider> p;\n try { p = Libshit::MakeSmart<MmapProvider>(Libshit::Move(io), fname, size); }\n catch (const Libshit::SystemError& e)\n {\n WARN << \"Mmap failed, falling back to normal reading: \"\n << Libshit::PrintException(Libshit::Logger::HasAnsiColor())\n << std::endl;\n p = Libshit::MakeSmart<UnixProvider>(Libshit::Move(io), fname, size);\n }\n return Libshit::MakeNotNull(Libshit::Move(p));\n }\n\n Source Source::FromFd(\n boost::filesystem::path fname, Libshit::LowIo::FdType fd, bool owning)\n {\n Libshit::LowIo io{fd, owning};\n auto size = io.GetSize();\n return {Libshit::MakeSmart<UnixProvider>(\n Libshit::Move(io), Libshit::Move(fname), size)};\n }\n\n Source Source::FromMemory(boost::filesystem::path fname, std::string str)\n {\n return {Libshit::MakeSmart<StringProvider>(\n Libshit::Move(fname), Libshit::Move(str))};\n }\n\n Source Source::FromMemory(boost::filesystem::path fname,\n std::unique_ptr<char[]> data, std::size_t len)\n {\n return {Libshit::MakeSmart<UniquePtrProvider>(\n Libshit::Move(fname), Libshit::Move(data), len)};\n }\n\n\n void Source::Pread_(FilePosition offs, Byte* buf, FileMemSize len) const\n {\n offs += offset;\n while (len)\n {\n if (p->LruGet(offs))\n {\n auto& x = p->lru[0];\n auto buf_offs = offs - x.offset;\n auto to_cpy = std::min<FilePosition>(len, x.size - buf_offs);\n memcpy(buf, x.ptr + buf_offs, to_cpy);\n offs += to_cpy;\n buf += to_cpy;\n len -= to_cpy;\n }\n else\n return p->Pread(offs, buf, len);\n }\n }\n\n std::string Source::PreadCString(FilePosition offs) const\n {\n std::string ret;\n std::string_view e;\n size_t len;\n do\n {\n e = GetChunk(offs);\n len = strnlen(e.data(), e.size());\n ret.append(e.data(), len);\n offs += e.size();\n } while (len == e.size());\n return ret;\n }\n\n Source::BufEntry Source::GetTemporaryEntry(FilePosition offs) const\n {\n if (p->LruGet(offs)) return p->lru[0];\n p->Pread(offs, nullptr, 0);\n LIBSHIT_ASSERT(p->lru[0].offset <= offs &&\n p->lru[0].offset + p->lru[0].size > offs);\n return p->lru[0];\n }\n\n std::string_view Source::GetChunk(FilePosition offs) const\n {\n LIBSHIT_ASSERT(offs < size);\n auto e = GetTemporaryEntry(offs + offset);\n auto eoffs = offs + offset - e.offset;\n auto size = std::min(e.size - eoffs, GetSize() - offs);\n return { reinterpret_cast<const char*>(e.ptr + eoffs), std::size_t(size) };\n }\n\n\n void Source::Provider::LruPush(\n const Byte* ptr, FilePosition offset, FileMemSize size)\n {\n memmove(&lru[1], &lru[0], sizeof(BufEntry)*(lru.size()-1));\n lru[0].ptr = ptr;\n lru[0].offset = offset;\n lru[0].size = size;\n }\n\n bool Source::Provider::LruGet(FilePosition offs)\n {\n for (size_t i = 0; i < lru.size(); ++i)\n {\n auto x = lru[i];\n if (x.offset <= offs && x.offset + x.size > offs)\n {\n LIBSHIT_ASSERT(x.ptr);\n memmove(&lru[1], &lru[0], sizeof(BufEntry)*i);\n lru[0] = x;\n return true;\n }\n }\n return false;\n }\n\n template <typename T>\n void UnixLike<T>::Destroy() noexcept\n {\n for (size_t i = 0; i < lru.size(); ++i)\n if (lru[i].size)\n static_cast<T*>(this)->DeleteChunk(i);\n }\n\n template <typename T>\n void UnixLike<T>::Pread(FilePosition offs, Byte* buf, FileMemSize len)\n {\n if (len > static_cast<T*>(this)->CHUNK_SIZE)\n return io.Pread(buf, len, offs);\n\n if (len == 0) EnsureChunk(offs); // TODO: GetTemporaryEntry hack\n while (len)\n {\n EnsureChunk(offs);\n auto buf_offs = offs - lru[0].offset;\n auto to_cpy = std::min<FilePosition>(len, lru[0].size - buf_offs);\n memcpy(buf, lru[0].ptr + buf_offs, to_cpy);\n buf += to_cpy;\n offs += to_cpy;\n len -= to_cpy;\n }\n }\n\n template <typename T>\n void UnixLike<T>::EnsureChunk(FilePosition offs)\n {\n auto const CHUNK_SIZE = static_cast<T*>(this)->CHUNK_SIZE;\n auto ch_offs = offs/CHUNK_SIZE*CHUNK_SIZE;\n if (LruGet(offs)) return;\n\n auto size = std::min<FilePosition>(CHUNK_SIZE, this->size-ch_offs);\n auto x = static_cast<T*>(this)->ReadChunk(ch_offs, size);\n static_cast<T*>(this)->DeleteChunk(lru.size()-1);\n LruPush(static_cast<Byte*>(x), ch_offs, size);\n }\n\n FileMemSize MmapProvider::CHUNK_SIZE = MMAP_CHUNK;\n MmapProvider::MmapProvider(\n Libshit::LowIo&& io, boost::filesystem::path file_name, FilePosition size)\n : UnixLike{{}, Libshit::Move(file_name), size}\n {\n std::size_t to_map = size < MMAP_LIMIT ? size : MMAP_CHUNK;\n\n io.PrepareMmap(false);\n void* ptr = io.Mmap(0, to_map, false).Release();\n#if !LIBSHIT_OS_IS_WINDOWS\n if (to_map == size) io.Reset();\n#endif\n this->io = Libshit::Move(io);\n\n lru[0].ptr = static_cast<Byte*>(ptr);\n lru[0].offset = 0;\n lru[0].size = to_map;\n }\n\n void* MmapProvider::ReadChunk(FilePosition offs, FileMemSize size)\n {\n return io.Mmap(offs, size, false).Release();\n }\n\n void MmapProvider::DeleteChunk(size_t i)\n {\n if (lru[i].ptr)\n Libshit::LowIo::Munmap(const_cast<Byte*>(lru[i].ptr), lru[i].size);\n }\n\n FileMemSize UnixProvider::CHUNK_SIZE = MEM_CHUNK;\n\n void* UnixProvider::ReadChunk(FilePosition offs, FileMemSize size)\n {\n std::unique_ptr<Byte[]> x{new Byte[size]};\n io.Pread(x.get(), size, offs);\n return x.release();\n }\n\n void UnixProvider::DeleteChunk(size_t i)\n {\n delete[] lru[i].ptr;\n }\n\n void Source::Inspect(std::ostream& os) const\n {\n os << \"neptools.source.from_memory(\"\n << Libshit::Quoted(GetFileName().string()) << \", \"\n << Quoted(*this) << \")\";\n }\n\n std::string Source::Inspect() const\n {\n std::stringstream ss;\n Inspect(ss);\n return ss.str();\n }\n\n void Source::Dump(Sink& sink) const\n {\n FilePosition offset = 0;\n auto size = GetSize();\n while (offset < size)\n {\n auto chunk = GetChunk(offset);\n sink.Write(chunk);\n offset += chunk.size();\n }\n }\n\n void DumpableSource::Inspect_(std::ostream& os, unsigned) const\n {\n os << \"neptools.dumpable_source(\";\n src.Inspect(os);\n os << ')';\n }\n\n std::string to_string(const Source& src)\n {\n std::stringstream ss;\n ss << src.GetFileName() << \", pos: \" << src.Tell();\n return ss.str();\n }\n\n#if LIBSHIT_WITH_LUA\n\n LIBSHIT_LUAGEN(name=\"read\")\n static Libshit::Lua::RetNum LuaRead(\n Libshit::Lua::StateRef vm, Source& src, FileMemSize len)\n {\n std::unique_ptr<char[]> ptr{new char[len]};\n src.Read<Libshit::Check::Throw>(ptr.get(), len);\n lua_pushlstring(vm, ptr.get(), len);\n return {1};\n }\n\n LIBSHIT_LUAGEN(name=\"pread\")\n static Libshit::Lua::RetNum LuaPread(\n Libshit::Lua::StateRef vm, Source& src, FilePosition offs, FileMemSize len)\n {\n std::unique_ptr<char[]> ptr{new char[len]};\n src.Pread<Libshit::Check::Throw>(offs, ptr.get(), len);\n lua_pushlstring(vm, ptr.get(), len);\n return {1};\n }\n\n#endif\n\n TEST_CASE(\"small source\")\n {\n char buf[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};\n std::ofstream os{\"tmp\", std::ios_base::binary};\n os.write(buf, 16);\n os.close();\n\n auto src = Source::FromFile(\"tmp\");\n char buf2[16];\n src.ReadGen(buf2);\n REQUIRE(memcmp(buf, buf2, 16) == 0);\n CHECK(src.Inspect() ==\n R\"(neptools.source.from_memory(\"tmp\", \"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\a\\b\\t\\n\\v\\f\\r\\x0e\\x0f\"))\");\n }\n TEST_SUITE_END();\n}\n\n#include \"source.binding.hpp\"\n" }, { "alpha_fraction": 0.5753122568130493, "alphanum_fraction": 0.587803065776825, "avg_line_length": 24.360248565673828, "blob_id": "b23d509d30874274a4d8c667161d11d0be484e5b", "content_id": "75a352a58f9744146ced8fd50ae2a5e15c1c6724", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4083, "license_type": "permissive", "max_line_length": 87, "num_lines": 161, "path": "/src/vita_plugin/plugin.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"version.hpp\"\n#include \"vita_plugin/cpk.hpp\"\n\n#include <libshit/except.hpp>\n#include <libshit/memory_utils.hpp>\n#include <libshit/options.hpp>\n#include <libshit/vita_fixup.h>\n\n#include <fstream>\n#include <memory>\n#include <psp2/appmgr.h>\n#include <psp2/io/dirent.h>\n#include <psp2/kernel/modulemgr.h>\n#include <psp2/kernel/processmgr.h>\n#include <unistd.h>\n#include <vector>\n\n#define LIBSHIT_LOG_NAME \"tai\"\n#include <libshit/logger_helper.hpp>\n\nnamespace Neptools::VitaPlugin\n{\n\n static void Uncaught()\n {\n printf(\"Terminate handler\\n\");\n printf(\"Caught: %s\\n\", Libshit::ExceptionToString(false).c_str());\n\n abort();\n }\n\n static bool CheckPath(const char* buf, const char*& out)\n {\n SceIoStat stat;\n auto ret = sceIoGetstat(buf, &stat);\n if (ret == 0 && SCE_S_ISDIR(stat.st_mode))\n {\n out = buf;\n return true;\n }\n return false;\n }\n\n static void my_strlcpy(char* dst, const char* str, size_t n)\n {\n while (--n && (*dst++ = *str++));\n *dst = 0;\n }\n\n static int FindDir(char* out_base_fname, char* out_data_fname, char* out_cache_fname)\n {\n char log_buf[32];\n log_buf[0] = 0;\n\n char buf[] = \"____:neptools/_________\";\n constexpr size_t off = sizeof(\"____:neptools/\")-1;\n int ret = sceAppMgrAppParamGetString(sceKernelGetProcessId(), 12, buf+off, 10);\n if (ret < 0) return ret; // can't log anything here...\n\n // same order as repatch\n const char* base_path = nullptr;\n bool cache_td = false;\n for (const auto& x : {\"ux0\", \"uma0\", \"imc0\", \"grw0\", \"xmc0\"})\n {\n size_t len = strlen(x);\n memcpy(buf + 4 - len, x, len);\n if (CheckPath(buf + 4 - len, base_path))\n {\n my_strlcpy(log_buf, base_path, buf+off+1-base_path);\n break;\n }\n }\n if (!base_path && CheckPath(\"app0:neptools\", base_path)) cache_td = true;\n if (!base_path) return -1;\n my_strlcpy(out_data_fname, base_path, 32);\n\n // check for ioplus bug\n if (!cache_td)\n {\n ret = sceIoDopen(base_path);\n if (ret >= 0) sceIoDclose(ret);\n else cache_td = true;\n }\n\n char td_buf[16];\n if (cache_td)\n {\n ret = sceAppMgrWorkDirMount(0xc9, td_buf);\n if (ret < 0) return ret;\n }\n if (!log_buf[0]) strcpy(log_buf, td_buf);\n\n if (cache_td)\n {\n strcpy(out_cache_fname, td_buf);\n strcat(out_cache_fname, \"neptools_cache\");\n }\n else\n {\n my_strlcpy(out_cache_fname, base_path, strlen(base_path) - 9 + 1);\n strcat(out_cache_fname, \"cache\");\n }\n\n strcpy(out_base_fname, log_buf);\n auto pos = log_buf + strlen(log_buf);\n strcpy(pos, \"log_out.txt\");\n freopen(log_buf, \"w\", stdout);\n strcpy(pos, \"log_err.txt\");\n freopen(log_buf, \"w\", stderr);\n\n return 0;\n }\n\n extern \"C\" int _start() __attribute__ ((weak, alias (\"module_start\")));\n\n extern \"C\" int module_start(SceSize, const void*);\n extern \"C\" int module_start(SceSize, const void*)\n {\n char base_fname[32], data_fname[32], cache_fname[32];\n if (FindDir(base_fname, data_fname, cache_fname) < 0)\n return SCE_KERNEL_START_FAILED;\n\n std::set_terminate(Uncaught);\n\n LibshitInitVita();\n\n std::vector<std::string> argv;\n {\n strcat(base_fname, \"/command_line.txt\");\n std::ifstream is{base_fname};\n while (is.good())\n {\n std::string s;\n std::getline(is, s);\n if (!s.empty()) argv.push_back(std::move(s));\n }\n }\n\n int argc = argv.size() + 1;\n\n auto cargv = Libshit::MakeUnique<const char*[]>(\n argc + 2, Libshit::uninitialized);\n cargv[0] = \"\";\n for (int i = 1; i < argc; ++i) cargv[i] = argv[i-1].c_str();\n cargv[argc+1] = nullptr;\n\n auto& pars = Libshit::OptionParser::GetGlobal();\n pars.SetVersion(\"NepTools vita plugin v\" NEPTOOLS_VERSION);\n pars.SetUsage(\"[--options]\");\n pars.FailOnNonArg();\n\n try { pars.Run(argc, cargv.get()); }\n catch (const Libshit::Exit& e) { _exit(!e.success); }\n\n INF << pars.GetVersion() << \" initializing...\" << std::endl;\n Init(data_fname, cache_fname);\n\n return SCE_KERNEL_START_SUCCESS;\n }\n\n}\n" }, { "alpha_fraction": 0.6586538553237915, "alphanum_fraction": 0.7323718070983887, "avg_line_length": 47, "blob_id": "2cc134b5d4aa2a0e7ddfa284fe122d8fabd2edab", "content_id": "d490e02b5e0e1e4d11013cc6197263ee750592de", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 624, "license_type": "permissive", "max_line_length": 76, "num_lines": 13, "path": "/tools/ci_conf.clang-msvc64.sh", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "source tools/ci_conf_wincommon.sh\n\nrun export CFLAGS=\"-target x86_64-pc-windows-msvc18 -march=x86-64 \\\n -fms-compatibility-version=18 \\\n -Xclang -internal-isystem -Xclang /mnt/msvc/vc12/include\n -Xclang -internal-isystem -Xclang /mnt/msvc/vc12/win_sdk/include/um\n -Xclang -internal-isystem -Xclang /mnt/msvc/vc12/win_sdk/include/shared\"\nrun export CXXFLAGS=\"$CFLAGS -DDOCTEST_CONFIG_COLORS_ANSI\"\nrun export LINKFLAGS=\"-target x86_64-pc-windows-msvc18 -march=x86-64 \\\n -fuse-ld=lld \\\n -L/mnt/msvc/vc12/lib/amd64 \\\n -L/mnt/msvc/vc12/win_sdk/lib/winv6.3/um/x64\"\nrun export WINRC=x86_64-w64-mingw32-windres\n" }, { "alpha_fraction": 0.687417209148407, "alphanum_fraction": 0.7006622552871704, "avg_line_length": 28.038461685180664, "blob_id": "6002e3ef3e8ad060b6ac4a6edbdb02c6dec0afe4", "content_id": "5abed653049a2e57963a6e61baa37cfa82a459f3", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2265, "license_type": "permissive", "max_line_length": 83, "num_lines": 78, "path": "/src/format/context.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_C2DF26B7_DE7D_47B8_BAEE_9F6EEBB12891\n#define UUID_C2DF26B7_DE7D_47B8_BAEE_9F6EEBB12891\n#pragma once\n\n#include \"item.hpp\"\n#include \"../dumpable.hpp\"\n\n#include <boost/intrusive/set.hpp>\n#include <string>\n#include <map>\n\nnamespace Neptools\n{\n\n class Context : public ItemWithChildren\n {\n LIBSHIT_LUA_CLASS;\n public:\n Context();\n ~Context() override;\n\n void Fixup() override;\n\n template <typename T, typename... Args>\n LIBSHIT_NOLUA Libshit::NotNull<Libshit::SmartPtr<T>> Create(Args&&... args)\n {\n return Libshit::MakeSmart<T>(\n Item::Key{}, *this, std::forward<Args>(args)...);\n }\n\n Libshit::NotNull<LabelPtr> GetLabel(const std::string& name) const;\n Libshit::NotNull<LabelPtr> CreateLabel(std::string name, ItemPointer ptr);\n Libshit::NotNull<LabelPtr> CreateLabelFallback(\n const std::string& name, ItemPointer ptr);\n Libshit::NotNull<LabelPtr> CreateLabelFallback(\n const std::string& name, FilePosition pos)\n { return CreateLabelFallback(name, GetPointer(pos)); }\n\n Libshit::NotNull<LabelPtr> CreateOrSetLabel(std::string name, ItemPointer ptr);\n Libshit::NotNull<LabelPtr> GetOrCreateDummyLabel(std::string name);\n\n Libshit::NotNull<LabelPtr> GetLabelTo(ItemPointer ptr);\n Libshit::NotNull<LabelPtr> GetLabelTo(FilePosition pos)\n { return GetLabelTo(GetPointer(pos)); }\n\n Libshit::NotNull<LabelPtr> GetLabelTo(\n FilePosition pos, const std::string& name);\n\n ItemPointer GetPointer(FilePosition pos) const noexcept;\n\n void Dispose() noexcept override;\n\n protected:\n void SetupParseFrom(Item& item);\n\n private:\n friend class Item;\n\n // properties needed: stable pointers\n using LabelsMap = boost::intrusive::set<\n Label,\n boost::intrusive::base_hook<LabelNameHook>,\n boost::intrusive::constant_time_size<false>,\n boost::intrusive::key_of_value<LabelKeyOfValue>>;\n LabelsMap labels;\n\n // properties needed: sorted\n using PointerMap = std::map<FilePosition, Item*>;\n PointerMap pmap;\n };\n\n struct PrintLabelStruct { const Label* label; };\n std::ostream& operator<<(std::ostream& os, PrintLabelStruct label);\n inline PrintLabelStruct PrintLabel(const LabelPtr& label)\n { return {label.get()}; }\n}\n\n#endif\n" }, { "alpha_fraction": 0.7188951969146729, "alphanum_fraction": 0.7204439640045166, "avg_line_length": 51.35135269165039, "blob_id": "735d939f0ef8dc1eb80dc68c694c9ea9206a7f03", "content_id": "26b55be52189ef870415b15a8e10dec75ddfd87b", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3874, "license_type": "permissive", "max_line_length": 232, "num_lines": 74, "path": "/src/format/stcm/collection_link.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Stcm::CollectionLinkHeaderItem::TYPE_NAME[] = \"neptools.stcm.collection_link_header_item\";\n\nconst char ::Neptools::Stcm::CollectionLinkItem::TYPE_NAME[] = \"neptools.stcm.collection_link_item\";\n\nconst char ::Neptools::Stcm::CollectionLinkItem::LinkEntry::TYPE_NAME[] = \"neptools.stcm.collection_link_item.link_entry\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.stcm.collection_link_header_item\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::CollectionLinkHeaderItem>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stcm::CollectionLinkHeaderItem, ::Neptools::Item>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::CollectionLinkHeaderItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::Libshit::NotNull<::Neptools::LabelPtr>>>\n >(\"new\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::CollectionLinkHeaderItem & (*)(::Neptools::ItemPointer)>(::Neptools::Stcm::CollectionLinkHeaderItem::CreateAndInsert)\n >(\"create_and_insert\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::CollectionLinkHeaderItem, ::Libshit::NotNull<::Neptools::LabelPtr>, &::Neptools::Stcm::CollectionLinkHeaderItem::data>\n >(\"get_data\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stcm::CollectionLinkHeaderItem, ::Libshit::NotNull<::Neptools::LabelPtr>, &::Neptools::Stcm::CollectionLinkHeaderItem::data>\n >(\"set_data\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::CollectionLinkHeaderItem> reg_neptools_stcm_collection_link_header_item;\n\n // class neptools.stcm.collection_link_item\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::CollectionLinkItem>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stcm::CollectionLinkItem, ::Neptools::Item>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::CollectionLinkItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::CollectionLinkItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::Neptools::Source>, LuaGetRef<::uint32_t>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::CollectionLinkItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<Libshit::AT<std::vector<::Neptools::Stcm::CollectionLinkItem::LinkEntry> >>>\n >(\"new\");\n bld.AddFunction<\n &::Libshit::Lua::GetSmartOwnedMember<::Neptools::Stcm::CollectionLinkItem, std::vector<::Neptools::Stcm::CollectionLinkItem::LinkEntry>, &::Neptools::Stcm::CollectionLinkItem::entries>\n >(\"get_entries\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::CollectionLinkItem> reg_neptools_stcm_collection_link_item;\n\n // class neptools.stcm.collection_link_item.link_entry\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::CollectionLinkItem::LinkEntry>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::CollectionLinkItem::LinkEntry, ::Neptools::LabelPtr, &::Neptools::Stcm::CollectionLinkItem::LinkEntry::name_0>\n >(\"get_name_0\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::CollectionLinkItem::LinkEntry, ::Neptools::LabelPtr, &::Neptools::Stcm::CollectionLinkItem::LinkEntry::name_1>\n >(\"get_name_1\");\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::CollectionLinkItem::LinkEntry>::Make<LuaGetRef<::Neptools::LabelPtr>, LuaGetRef<::Neptools::LabelPtr>>\n >(\"new\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::CollectionLinkItem::LinkEntry> reg_neptools_stcm_collection_link_item_link_entry;\n\n}\n#endif\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6046421527862549, "avg_line_length": 23.619047164916992, "blob_id": "ef1c19661c4b29b1e0fb32db45a794bc19187b12", "content_id": "8708aa9e9a779f5614f5d20411afd69cc61040aa", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2585, "license_type": "permissive", "max_line_length": 82, "num_lines": 105, "path": "/src/format/stcm/exports.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"exports.hpp\"\n#include \"data.hpp\"\n#include \"header.hpp\"\n#include \"instruction.hpp\"\n#include \"../context.hpp\"\n#include \"../../sink.hpp\"\n\n#include <libshit/char_utils.hpp>\n#include <libshit/container/vector.lua.hpp>\n#include <iostream>\n\nnamespace Neptools::Stcm\n{\n\n void ExportsItem::Entry::Validate(FilePosition file_size) const\n {\n#define VALIDATE(x) LIBSHIT_VALIDATE_FIELD(\"Stcm::ExportsItem::Entry\", x)\n VALIDATE(type == Type::CODE || type == Type::DATA);\n VALIDATE(name.is_valid());\n VALIDATE(offset < file_size);\n#undef VALIDATE\n }\n\n ExportsItem::ExportsItem(Key k, Context& ctx, Source src, uint32_t export_count)\n : Item{k, ctx}\n {\n ADD_SOURCE(Parse_(ctx, src, export_count), src);\n }\n\n void ExportsItem::Parse_(Context& ctx, Source& src, uint32_t export_count)\n {\n entries.reserve(export_count);\n auto size = ctx.GetSize();\n for (uint32_t i = 0; i < export_count; ++i)\n {\n auto e = src.ReadGen<Entry>();\n e.Validate(size);\n entries.push_back(\n Libshit::MakeSmart<EntryType>(\n static_cast<Type>(static_cast<uint32_t>(e.type)),\n e.name,\n ctx.CreateLabelFallback(e.name.c_str(), e.offset)));\n }\n }\n\n ExportsItem& ExportsItem::CreateAndInsert(\n ItemPointer ptr, uint32_t export_count)\n {\n auto x = RawItem::GetSource(ptr, export_count*sizeof(Entry));\n\n auto& ret = x.ritem.SplitCreate<ExportsItem>(\n ptr.offset, x.src, export_count);\n\n for (const auto& e : ret.entries)\n switch (e->type)\n {\n case Type::CODE:\n MaybeCreate<InstructionItem>(e->lbl->GetPtr());\n break;\n case Type::DATA:\n MaybeCreate<DataItem>(e->lbl->GetPtr());\n break;\n }\n return ret;\n }\n\n void ExportsItem::Dispose() noexcept\n {\n entries.clear();\n Item::Dispose();\n }\n\n void ExportsItem::Dump_(Sink& sink) const\n {\n Entry ee;\n\n for (auto& e : entries)\n {\n ee.type = e->type;\n ee.name = e->name;\n ee.offset = ToFilePos(e->lbl->GetPtr());\n sink.WriteGen(ee);\n }\n }\n\n void ExportsItem::Inspect_(std::ostream& os, unsigned indent) const\n {\n Item::Inspect_(os, indent);\n\n os << \"exports{\\n\";\n for (auto& e : entries)\n {\n Indent(os, indent+1)\n << '{' << e->type << \", \" << Libshit::Quoted(e->name.c_str()) << \", \"\n << PrintLabel(e->lbl) << \"},\\n\";\n }\n Indent(os, indent) << '}';\n }\n\n}\n\nLIBSHIT_STD_VECTOR_LUAGEN(\n stcm_exports_item_entry_type, Libshit::NotNull<Libshit::RefCountedPtr<\n Neptools::Stcm::ExportsItem::EntryType>>);\n#include \"exports.binding.hpp\"\n" }, { "alpha_fraction": 0.7011083364486694, "alphanum_fraction": 0.7124469876289368, "avg_line_length": 78.58943176269531, "blob_id": "56b8d3dea6ca70c8592d7bf99d638d4d9b6cf2d5", "content_id": "4bb2938a3e38a74ca357765b94f17080458ed2a3", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 19579, "license_type": "permissive", "max_line_length": 338, "num_lines": 246, "path": "/src/format/stcm/instruction.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Stcm::InstructionItem::TYPE_NAME[] = \"neptools.stcm.instruction_item\";\n\nconst char ::Neptools::Stcm::InstructionItem::Param48::TYPE_NAME[] = \"neptools.stcm.instruction_item.param48\";\nconst char ::Libshit::Lua::TypeName<::Neptools::Stcm::InstructionItem::Param48::Type>::TYPE_NAME[] =\n \"neptools.stcm.instruction_item.param48.type\";\n\nconst char ::Neptools::Stcm::InstructionItem::Param::TYPE_NAME[] = \"neptools.stcm.instruction_item.param\";\n\nconst char ::Neptools::Stcm::InstructionItem::Param::MemOffset::TYPE_NAME[] = \"neptools.stcm.instruction_item.param.mem_offset\";\n\nconst char ::Neptools::Stcm::InstructionItem::Param::Indirect::TYPE_NAME[] = \"neptools.stcm.instruction_item.param.indirect\";\nconst char ::Libshit::Lua::TypeName<::Neptools::Stcm::InstructionItem::Param::Type>::TYPE_NAME[] =\n \"neptools.stcm.instruction_item.param.type\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.stcm.instruction_item\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::InstructionItem>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stcm::InstructionItem, ::Neptools::ItemWithChildren>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::InstructionItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::InstructionItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::Neptools::Source>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::InstructionItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::Libshit::NotNull<::Neptools::LabelPtr>>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::InstructionItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::Libshit::NotNull<::Neptools::LabelPtr>>, LuaGetRef<Libshit::AT<std::vector<::Neptools::Stcm::InstructionItem::Param> >>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::InstructionItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::uint32_t>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::InstructionItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::uint32_t>, LuaGetRef<Libshit::AT<std::vector<::Neptools::Stcm::InstructionItem::Param> >>>\n >(\"new\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::InstructionItem & (*)(::Neptools::ItemPointer)>(::Neptools::Stcm::InstructionItem::CreateAndInsert)\n >(\"create_and_insert\");\n bld.AddFunction<\n static_cast<bool (::Neptools::Stcm::InstructionItem::*)() const noexcept>(&::Neptools::Stcm::InstructionItem::IsCall)\n >(\"is_call\");\n bld.AddFunction<\n static_cast<::uint32_t (::Neptools::Stcm::InstructionItem::*)() const>(&::Neptools::Stcm::InstructionItem::GetOpcode)\n >(\"get_opcode\");\n bld.AddFunction<\n static_cast<void (::Neptools::Stcm::InstructionItem::*)(::uint32_t) noexcept>(&::Neptools::Stcm::InstructionItem::SetOpcode)\n >(\"set_opcode\");\n bld.AddFunction<\n static_cast<::Libshit::NotNull<::Neptools::LabelPtr> (::Neptools::Stcm::InstructionItem::*)() const>(&::Neptools::Stcm::InstructionItem::GetTarget)\n >(\"get_target\");\n bld.AddFunction<\n static_cast<void (::Neptools::Stcm::InstructionItem::*)(::Libshit::NotNull<::Neptools::LabelPtr>) noexcept>(&::Neptools::Stcm::InstructionItem::SetTarget)\n >(\"set_target\");\n bld.AddFunction<\n &::Libshit::Lua::GetSmartOwnedMember<::Neptools::Stcm::InstructionItem, std::vector<::Neptools::Stcm::InstructionItem::Param>, &::Neptools::Stcm::InstructionItem::params>\n >(\"get_params\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::InstructionItem> reg_neptools_stcm_instruction_item;\n\n // class neptools.stcm.instruction_item.param48\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::InstructionItem::Param48>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::InstructionItem::Param48>::Make<LuaGetRef<::Neptools::Context &>, LuaGetRef<::uint32_t>>\n >(\"new\");\n bld.AddFunction<\n static_cast<::uint32_t (::Neptools::Stcm::InstructionItem::Param48::*)() const noexcept>(&::Neptools::Stcm::InstructionItem::Param48::Dump)\n >(\"dump\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::InstructionItem::Param48::Type (::Neptools::Stcm::InstructionItem::Param48::*)() const noexcept>(&::Neptools::Stcm::InstructionItem::Param48::GetType)\n >(\"get_type\");\n bld.AddFunction<\n static_cast<decltype(std::declval<::Neptools::Stcm::InstructionItem::Param48>().Get<Neptools::Stcm::InstructionItem::Param48::Type::MEM_OFFSET>()) (::Neptools::Stcm::InstructionItem::Param48::*)() const>(&::Neptools::Stcm::InstructionItem::Param48::Get<Neptools::Stcm::InstructionItem::Param48::Type::MEM_OFFSET>)\n >(\"get_mem_offset\");\n bld.AddFunction<\n static_cast<decltype(std::declval<::Neptools::Stcm::InstructionItem::Param48>().Get<Neptools::Stcm::InstructionItem::Param48::Type::IMMEDIATE>()) (::Neptools::Stcm::InstructionItem::Param48::*)() const>(&::Neptools::Stcm::InstructionItem::Param48::Get<Neptools::Stcm::InstructionItem::Param48::Type::IMMEDIATE>)\n >(\"get_immediate\");\n bld.AddFunction<\n static_cast<decltype(std::declval<::Neptools::Stcm::InstructionItem::Param48>().Get<Neptools::Stcm::InstructionItem::Param48::Type::INDIRECT>()) (::Neptools::Stcm::InstructionItem::Param48::*)() const>(&::Neptools::Stcm::InstructionItem::Param48::Get<Neptools::Stcm::InstructionItem::Param48::Type::INDIRECT>)\n >(\"get_indirect\");\n bld.AddFunction<\n static_cast<decltype(std::declval<::Neptools::Stcm::InstructionItem::Param48>().Get<Neptools::Stcm::InstructionItem::Param48::Type::READ_STACK>()) (::Neptools::Stcm::InstructionItem::Param48::*)() const>(&::Neptools::Stcm::InstructionItem::Param48::Get<Neptools::Stcm::InstructionItem::Param48::Type::READ_STACK>)\n >(\"get_read_stack\");\n bld.AddFunction<\n static_cast<decltype(std::declval<::Neptools::Stcm::InstructionItem::Param48>().Get<Neptools::Stcm::InstructionItem::Param48::Type::READ_4AC>()) (::Neptools::Stcm::InstructionItem::Param48::*)() const>(&::Neptools::Stcm::InstructionItem::Param48::Get<Neptools::Stcm::InstructionItem::Param48::Type::READ_4AC>)\n >(\"get_read_4ac\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::InstructionItem::Param48 (*)(std::variant_alternative_t<static_cast<size_t>(::Neptools::Stcm::InstructionItem::Param48::Type::MEM_OFFSET), ::Neptools::Stcm::InstructionItem::Param48::Variant>)>(::Neptools::Stcm::InstructionItem::Param48::New<Neptools::Stcm::InstructionItem::Param48::Type::MEM_OFFSET>)\n >(\"new_mem_offset\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::InstructionItem::Param48 (*)(std::variant_alternative_t<static_cast<size_t>(::Neptools::Stcm::InstructionItem::Param48::Type::IMMEDIATE), ::Neptools::Stcm::InstructionItem::Param48::Variant>)>(::Neptools::Stcm::InstructionItem::Param48::New<Neptools::Stcm::InstructionItem::Param48::Type::IMMEDIATE>)\n >(\"new_immediate\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::InstructionItem::Param48 (*)(std::variant_alternative_t<static_cast<size_t>(::Neptools::Stcm::InstructionItem::Param48::Type::INDIRECT), ::Neptools::Stcm::InstructionItem::Param48::Variant>)>(::Neptools::Stcm::InstructionItem::Param48::New<Neptools::Stcm::InstructionItem::Param48::Type::INDIRECT>)\n >(\"new_indirect\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::InstructionItem::Param48 (*)(std::variant_alternative_t<static_cast<size_t>(::Neptools::Stcm::InstructionItem::Param48::Type::READ_STACK), ::Neptools::Stcm::InstructionItem::Param48::Variant>)>(::Neptools::Stcm::InstructionItem::Param48::New<Neptools::Stcm::InstructionItem::Param48::Type::READ_STACK>)\n >(\"new_read_stack\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::InstructionItem::Param48 (*)(std::variant_alternative_t<static_cast<size_t>(::Neptools::Stcm::InstructionItem::Param48::Type::READ_4AC), ::Neptools::Stcm::InstructionItem::Param48::Variant>)>(::Neptools::Stcm::InstructionItem::Param48::New<Neptools::Stcm::InstructionItem::Param48::Type::READ_4AC>)\n >(\"new_read_4ac\");\nbld.TaggedNew();\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::InstructionItem::Param48> reg_neptools_stcm_instruction_item_param48;\n\n // class neptools.stcm.instruction_item.param48.type\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::InstructionItem::Param48::Type>::Register(TypeBuilder& bld)\n {\n\n bld.Add(\"MEM_OFFSET\", ::Neptools::Stcm::InstructionItem::Param48::Type::MEM_OFFSET);\n bld.Add(\"IMMEDIATE\", ::Neptools::Stcm::InstructionItem::Param48::Type::IMMEDIATE);\n bld.Add(\"INDIRECT\", ::Neptools::Stcm::InstructionItem::Param48::Type::INDIRECT);\n bld.Add(\"READ_STACK\", ::Neptools::Stcm::InstructionItem::Param48::Type::READ_STACK);\n bld.Add(\"READ_4AC\", ::Neptools::Stcm::InstructionItem::Param48::Type::READ_4AC);\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::InstructionItem::Param48::Type> reg_neptools_stcm_instruction_item_param48_type;\n\n // class neptools.stcm.instruction_item.param\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::InstructionItem::Param>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n static_cast<void (::Neptools::Stcm::InstructionItem::Param::*)(::Neptools::Sink &) const>(&::Neptools::Stcm::InstructionItem::Param::Dump)\n >(\"dump\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::InstructionItem::Param::Type (::Neptools::Stcm::InstructionItem::Param::*)() const noexcept>(&::Neptools::Stcm::InstructionItem::Param::GetType)\n >(\"get_type\");\n bld.AddFunction<\n static_cast<decltype(std::declval<::Neptools::Stcm::InstructionItem::Param>().Get<Neptools::Stcm::InstructionItem::Param::Type::MEM_OFFSET>()) (::Neptools::Stcm::InstructionItem::Param::*)() const>(&::Neptools::Stcm::InstructionItem::Param::Get<Neptools::Stcm::InstructionItem::Param::Type::MEM_OFFSET>)\n >(\"get_mem_offset\");\n bld.AddFunction<\n static_cast<decltype(std::declval<::Neptools::Stcm::InstructionItem::Param>().Get<Neptools::Stcm::InstructionItem::Param::Type::INDIRECT>()) (::Neptools::Stcm::InstructionItem::Param::*)() const>(&::Neptools::Stcm::InstructionItem::Param::Get<Neptools::Stcm::InstructionItem::Param::Type::INDIRECT>)\n >(\"get_indirect\");\n bld.AddFunction<\n static_cast<decltype(std::declval<::Neptools::Stcm::InstructionItem::Param>().Get<Neptools::Stcm::InstructionItem::Param::Type::READ_STACK>()) (::Neptools::Stcm::InstructionItem::Param::*)() const>(&::Neptools::Stcm::InstructionItem::Param::Get<Neptools::Stcm::InstructionItem::Param::Type::READ_STACK>)\n >(\"get_read_stack\");\n bld.AddFunction<\n static_cast<decltype(std::declval<::Neptools::Stcm::InstructionItem::Param>().Get<Neptools::Stcm::InstructionItem::Param::Type::READ_4AC>()) (::Neptools::Stcm::InstructionItem::Param::*)() const>(&::Neptools::Stcm::InstructionItem::Param::Get<Neptools::Stcm::InstructionItem::Param::Type::READ_4AC>)\n >(\"get_read_4ac\");\n bld.AddFunction<\n static_cast<decltype(std::declval<::Neptools::Stcm::InstructionItem::Param>().Get<Neptools::Stcm::InstructionItem::Param::Type::INSTR_PTR0>()) (::Neptools::Stcm::InstructionItem::Param::*)() const>(&::Neptools::Stcm::InstructionItem::Param::Get<Neptools::Stcm::InstructionItem::Param::Type::INSTR_PTR0>)\n >(\"get_instr_ptr0\");\n bld.AddFunction<\n static_cast<decltype(std::declval<::Neptools::Stcm::InstructionItem::Param>().Get<Neptools::Stcm::InstructionItem::Param::Type::INSTR_PTR1>()) (::Neptools::Stcm::InstructionItem::Param::*)() const>(&::Neptools::Stcm::InstructionItem::Param::Get<Neptools::Stcm::InstructionItem::Param::Type::INSTR_PTR1>)\n >(\"get_instr_ptr1\");\n bld.AddFunction<\n static_cast<decltype(std::declval<::Neptools::Stcm::InstructionItem::Param>().Get<Neptools::Stcm::InstructionItem::Param::Type::COLL_LINK>()) (::Neptools::Stcm::InstructionItem::Param::*)() const>(&::Neptools::Stcm::InstructionItem::Param::Get<Neptools::Stcm::InstructionItem::Param::Type::COLL_LINK>)\n >(\"get_coll_link\");\n bld.AddFunction<\n static_cast<decltype(std::declval<::Neptools::Stcm::InstructionItem::Param>().Get<Neptools::Stcm::InstructionItem::Param::Type::EXPANSION>()) (::Neptools::Stcm::InstructionItem::Param::*)() const>(&::Neptools::Stcm::InstructionItem::Param::Get<Neptools::Stcm::InstructionItem::Param::Type::EXPANSION>)\n >(\"get_expansion\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::InstructionItem::Param (*)(std::variant_alternative_t<static_cast<size_t>(::Neptools::Stcm::InstructionItem::Param::Type::MEM_OFFSET), ::Neptools::Stcm::InstructionItem::Param::Variant>)>(::Neptools::Stcm::InstructionItem::Param::New<Neptools::Stcm::InstructionItem::Param::Type::MEM_OFFSET>),\n static_cast<::Neptools::Stcm::InstructionItem::Param (*)(::Libshit::NotNull<::Neptools::LabelPtr>, Libshit::AT<::Neptools::Stcm::InstructionItem::Param48>, Libshit::AT<::Neptools::Stcm::InstructionItem::Param48>)>(::Neptools::Stcm::InstructionItem::Param::NewMemOffset)\n >(\"new_mem_offset\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::InstructionItem::Param (*)(std::variant_alternative_t<static_cast<size_t>(::Neptools::Stcm::InstructionItem::Param::Type::INDIRECT), ::Neptools::Stcm::InstructionItem::Param::Variant>)>(::Neptools::Stcm::InstructionItem::Param::New<Neptools::Stcm::InstructionItem::Param::Type::INDIRECT>),\n static_cast<::Neptools::Stcm::InstructionItem::Param (*)(::uint32_t, Libshit::AT<::Neptools::Stcm::InstructionItem::Param48>)>(::Neptools::Stcm::InstructionItem::Param::NewIndirect)\n >(\"new_indirect\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::InstructionItem::Param (*)(std::variant_alternative_t<static_cast<size_t>(::Neptools::Stcm::InstructionItem::Param::Type::READ_STACK), ::Neptools::Stcm::InstructionItem::Param::Variant>)>(::Neptools::Stcm::InstructionItem::Param::New<Neptools::Stcm::InstructionItem::Param::Type::READ_STACK>)\n >(\"new_read_stack\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::InstructionItem::Param (*)(std::variant_alternative_t<static_cast<size_t>(::Neptools::Stcm::InstructionItem::Param::Type::READ_4AC), ::Neptools::Stcm::InstructionItem::Param::Variant>)>(::Neptools::Stcm::InstructionItem::Param::New<Neptools::Stcm::InstructionItem::Param::Type::READ_4AC>)\n >(\"new_read_4ac\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::InstructionItem::Param (*)(std::variant_alternative_t<static_cast<size_t>(::Neptools::Stcm::InstructionItem::Param::Type::INSTR_PTR0), ::Neptools::Stcm::InstructionItem::Param::Variant>)>(::Neptools::Stcm::InstructionItem::Param::New<Neptools::Stcm::InstructionItem::Param::Type::INSTR_PTR0>)\n >(\"new_instr_ptr0\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::InstructionItem::Param (*)(std::variant_alternative_t<static_cast<size_t>(::Neptools::Stcm::InstructionItem::Param::Type::INSTR_PTR1), ::Neptools::Stcm::InstructionItem::Param::Variant>)>(::Neptools::Stcm::InstructionItem::Param::New<Neptools::Stcm::InstructionItem::Param::Type::INSTR_PTR1>)\n >(\"new_instr_ptr1\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::InstructionItem::Param (*)(std::variant_alternative_t<static_cast<size_t>(::Neptools::Stcm::InstructionItem::Param::Type::COLL_LINK), ::Neptools::Stcm::InstructionItem::Param::Variant>)>(::Neptools::Stcm::InstructionItem::Param::New<Neptools::Stcm::InstructionItem::Param::Type::COLL_LINK>)\n >(\"new_coll_link\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::InstructionItem::Param (*)(std::variant_alternative_t<static_cast<size_t>(::Neptools::Stcm::InstructionItem::Param::Type::EXPANSION), ::Neptools::Stcm::InstructionItem::Param::Variant>)>(::Neptools::Stcm::InstructionItem::Param::New<Neptools::Stcm::InstructionItem::Param::Type::EXPANSION>)\n >(\"new_expansion\");\nbld.TaggedNew();\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::InstructionItem::Param> reg_neptools_stcm_instruction_item_param;\n\n // class neptools.stcm.instruction_item.param.mem_offset\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::InstructionItem::Param::MemOffset>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::InstructionItem::Param::MemOffset, ::Libshit::NotNull<::Neptools::LabelPtr>, &::Neptools::Stcm::InstructionItem::Param::MemOffset::target>\n >(\"get_target\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::InstructionItem::Param::MemOffset, ::Neptools::Stcm::InstructionItem::Param48, &::Neptools::Stcm::InstructionItem::Param::MemOffset::param_4>\n >(\"get_param_4\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::InstructionItem::Param::MemOffset, ::Neptools::Stcm::InstructionItem::Param48, &::Neptools::Stcm::InstructionItem::Param::MemOffset::param_8>\n >(\"get_param_8\");\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::InstructionItem::Param::MemOffset>::Make<LuaGetRef<::Libshit::NotNull<::Neptools::LabelPtr>>, LuaGetRef<::Neptools::Stcm::InstructionItem::Param48>, LuaGetRef<::Neptools::Stcm::InstructionItem::Param48>>\n >(\"new\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::InstructionItem::Param::MemOffset> reg_neptools_stcm_instruction_item_param_mem_offset;\n\n // class neptools.stcm.instruction_item.param.indirect\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::InstructionItem::Param::Indirect>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::InstructionItem::Param::Indirect, ::uint32_t, &::Neptools::Stcm::InstructionItem::Param::Indirect::param_0>\n >(\"get_param_0\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::InstructionItem::Param::Indirect, ::Neptools::Stcm::InstructionItem::Param48, &::Neptools::Stcm::InstructionItem::Param::Indirect::param_8>\n >(\"get_param_8\");\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::InstructionItem::Param::Indirect>::Make<LuaGetRef<::uint32_t>, LuaGetRef<::Neptools::Stcm::InstructionItem::Param48>>\n >(\"new\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::InstructionItem::Param::Indirect> reg_neptools_stcm_instruction_item_param_indirect;\n\n // class neptools.stcm.instruction_item.param.type\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::InstructionItem::Param::Type>::Register(TypeBuilder& bld)\n {\n\n bld.Add(\"MEM_OFFSET\", ::Neptools::Stcm::InstructionItem::Param::Type::MEM_OFFSET);\n bld.Add(\"INDIRECT\", ::Neptools::Stcm::InstructionItem::Param::Type::INDIRECT);\n bld.Add(\"READ_STACK\", ::Neptools::Stcm::InstructionItem::Param::Type::READ_STACK);\n bld.Add(\"READ_4AC\", ::Neptools::Stcm::InstructionItem::Param::Type::READ_4AC);\n bld.Add(\"INSTR_PTR0\", ::Neptools::Stcm::InstructionItem::Param::Type::INSTR_PTR0);\n bld.Add(\"INSTR_PTR1\", ::Neptools::Stcm::InstructionItem::Param::Type::INSTR_PTR1);\n bld.Add(\"COLL_LINK\", ::Neptools::Stcm::InstructionItem::Param::Type::COLL_LINK);\n bld.Add(\"EXPANSION\", ::Neptools::Stcm::InstructionItem::Param::Type::EXPANSION);\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::InstructionItem::Param::Type> reg_neptools_stcm_instruction_item_param_type;\n\n}\n#endif\n" }, { "alpha_fraction": 0.6473379135131836, "alphanum_fraction": 0.6589351892471313, "avg_line_length": 40.239131927490234, "blob_id": "0882c76f5e23fc3f7d9e30c9524c37f950f70fe3", "content_id": "dcf074ecfd8218c764c2623d9b4331ee851939cb", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1897, "license_type": "permissive", "max_line_length": 204, "num_lines": 46, "path": "/src/format/stcm/data.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Stcm::DataItem::TYPE_NAME[] = \"neptools.stcm.data_item\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.stcm.data_item\n template<>\n void TypeRegisterTraits<::Neptools::Stcm::DataItem>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stcm::DataItem, ::Neptools::ItemWithChildren>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stcm::DataItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::uint32_t>, LuaGetRef<::uint32_t>, LuaGetRef<::uint32_t>>\n >(\"new\");\n bld.AddFunction<\n static_cast<::Neptools::Stcm::DataItem & (*)(::Neptools::ItemPointer)>(::Neptools::Stcm::DataItem::CreateAndInsert)\n >(\"create_and_insert\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::DataItem, ::uint32_t, &::Neptools::Stcm::DataItem::type>\n >(\"get_type\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stcm::DataItem, ::uint32_t, &::Neptools::Stcm::DataItem::type>\n >(\"set_type\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::DataItem, ::uint32_t, &::Neptools::Stcm::DataItem::offset_unit>\n >(\"get_offset_unit\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stcm::DataItem, ::uint32_t, &::Neptools::Stcm::DataItem::offset_unit>\n >(\"set_offset_unit\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stcm::DataItem, ::uint32_t, &::Neptools::Stcm::DataItem::field_8>\n >(\"get_field_8\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stcm::DataItem, ::uint32_t, &::Neptools::Stcm::DataItem::field_8>\n >(\"set_field_8\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stcm::DataItem> reg_neptools_stcm_data_item;\n\n}\n#endif\n" }, { "alpha_fraction": 0.6382070183753967, "alphanum_fraction": 0.6485236287117004, "avg_line_length": 30.584270477294922, "blob_id": "1281f1fe0848337a8f521de1fcda1573cf662cfa", "content_id": "61beefd5beb4463ca2e504bfb05de2aa64f51f52", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2811, "license_type": "permissive", "max_line_length": 79, "num_lines": 89, "path": "/src/format/stcm/header.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"header.hpp\"\n#include \"collection_link.hpp\"\n#include \"expansion.hpp\"\n#include \"exports.hpp\"\n#include \"../context.hpp\"\n#include \"../../sink.hpp\"\n#include \"../../utils.hpp\"\n\n#include <libshit/char_utils.hpp>\n#include <stdexcept>\n#include <iostream>\n\nnamespace Neptools::Stcm\n{\n\n void HeaderItem::Header::Validate(FilePosition file_size) const\n {\n#define VALIDATE(x) LIBSHIT_VALIDATE_FIELD(\"Stcm::HeaderItem::Header\", x)\n VALIDATE(memcmp(magic, \"STCM2\", 5) == 0);\n VALIDATE(endian == 'L');\n VALIDATE(msg.is_valid());\n VALIDATE(export_offset < file_size - 0x28*export_count);\n VALIDATE(collection_link_offset < file_size);\n VALIDATE(field_30 == 0);\n VALIDATE(expansion_count == 0 || expansion_offset != 0);\n VALIDATE(expansion_offset < file_size - 0x50*expansion_count);\n#undef VALIDATE\n }\n\n HeaderItem::HeaderItem(Key k, Context& ctx, const Header& hdr)\n : Item{k, ctx}, export_sec{Libshit::EmptyNotNull{}},\n collection_link{Libshit::EmptyNotNull{}}\n {\n hdr.Validate(ctx.GetSize());\n\n msg = hdr.msg;\n export_sec = ctx.CreateLabelFallback(\"exports\", hdr.export_offset);\n collection_link = ctx.CreateLabelFallback(\n \"collection_link_hdr\", hdr.collection_link_offset);;\n if (hdr.expansion_offset != 0)\n expansion = ctx.CreateLabelFallback(\"expansion\", hdr.expansion_offset);\n field_28 = hdr.field_28;\n }\n\n HeaderItem& HeaderItem::CreateAndInsert(ItemPointer ptr)\n {\n auto x = RawItem::Get<Header>(ptr);\n\n auto& ret = x.ritem.SplitCreate<HeaderItem>(ptr.offset, x.t);\n CollectionLinkHeaderItem::CreateAndInsert(ret.collection_link->GetPtr());\n if (ret.expansion)\n ExpansionsItem::CreateAndInsert(ret.expansion->GetPtr(),\n x.t.expansion_count);\n ExportsItem::CreateAndInsert(ret.export_sec->GetPtr(), x.t.export_count);\n return ret;\n }\n\n void HeaderItem::Dump_(Sink& sink) const\n {\n Header hdr{};\n memcpy(hdr.magic, \"STCM2\", 5);\n hdr.endian = 'L';\n hdr.msg = msg;\n hdr.export_offset = ToFilePos(export_sec->GetPtr());\n hdr.export_count = export_sec->GetPtr().As0<ExportsItem>().entries.size();\n hdr.field_28 = field_28;\n hdr.collection_link_offset = ToFilePos(collection_link->GetPtr());\n if (expansion)\n {\n hdr.expansion_offset = ToFilePos(expansion->GetPtr());\n hdr.expansion_count = expansion->GetPtr().As0<ExpansionsItem>().\n GetChildren().size();\n }\n\n sink.WriteGen(hdr);\n }\n\n void HeaderItem::Inspect_(std::ostream& os, unsigned indent) const\n {\n Item::Inspect_(os, indent);\n\n os << \"header(\" << Libshit::Quoted(msg.c_str()) << \", \"\n << PrintLabel(export_sec) << \", \" << PrintLabel(collection_link) << \", \"\n << field_28 << \", \" << PrintLabel(expansion) << \")\";\n }\n\n}\n\n#include \"header.binding.hpp\"\n" }, { "alpha_fraction": 0.6630851626396179, "alphanum_fraction": 0.6784343719482422, "avg_line_length": 31.575000762939453, "blob_id": "7aadfbb4ae5f7ea4a7e07a186c4abb507f3d1230", "content_id": "0832d13eab62eedfb4abefb2644ea99c3ad562e1", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1303, "license_type": "permissive", "max_line_length": 82, "num_lines": 40, "path": "/tools/ci_conf.clang.sh", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "source tools/ci_conf_linuxcommon.sh\n\nopt=\"-march=x86-64 -mtune=generic\"\nlibcxx=\"-stdlib=libc++\"\n\n# sysroot only supported with clang ATM\nsysroot=/opt/sysroot_amd64\nqsysroot=\"$(quot \"$sysroot\")\"\n\nrun clang --version\nrun export AR=llvm-ar\nrun export CC=clang\nrun export CXX=clang++\nrun export CFLAGS=\"--sysroot $qsysroot $opt\"\n# define: old glibc doesn't know about clang\nrun export CXXFLAGS=\"--sysroot $qsysroot $opt $libcxx \\\n-D__extern_always_inline='extern __always_inline __attribute__((__gnu_inline__))'\"\n# -lrt only needed with glibc < 2.17\nrun export LINKFLAGS=\"--sysroot $qsysroot $libcxx -fuse-ld=lld \\\n-static-libstdc++ -Wl,--as-needed -lpthread -lrt -Wl,--no-as-needed\"\n\nrun export PKG_CONFIG_PATH=\"$(join : \"$sysroot\"/usr/lib/{,*/}pkgconfig)\"\nrun export PKG_CONFIG_SYSROOT_DIR=\"$sysroot\"\n\n\nte='build/stcm-editor --xml-output=test'\nts='--test -fc --reporters=libshit-junit,console'\nld=\"LD_LIBRARY_PATH=$(quot \"$(join : \"$sysroot\"/{,usr/}lib/{,*-linux-gnu})\") \\\n$(quot \"$sysroot\"/lib/*/ld-linux*.so*) $te\"\nqemu=\"\\$CC -O2 -shared -o tools/qemu_vdso_fix_linux_amd64.so \\\ntools/qemu_vdso_fix_linux_amd64.c && \\\nqemu-x86_64 -E LD_PRELOAD=$(quot \"$(pwd)/tools/qemu_vdso_fix_linux_amd64.so\") \\\n-E $ld-qemu.xml $ts\"\n\ntests=(\n \"$te-native.xml $ts\"\n \"$ld-ld.xml $ts\"\n \"$qemu\"\n \"$valgrind\"\n)\n" }, { "alpha_fraction": 0.6197478771209717, "alphanum_fraction": 0.7016806602478027, "avg_line_length": 20.636363983154297, "blob_id": "0491e2c47e0225033a17006a3b7e6bd52d25bb48", "content_id": "e820bc6599c2149c89e3c6ca6296d474d84dddb4", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 476, "license_type": "permissive", "max_line_length": 68, "num_lines": 22, "path": "/src/format/eof_item.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_2E2EE447_59EF_4611_B8B5_40180CC6FBCC\n#define UUID_2E2EE447_59EF_4611_B8B5_40180CC6FBCC\n#pragma once\n\n#include \"item.hpp\"\n\nnamespace Neptools\n{\n\n class EofItem final : public Item\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n EofItem(Key k, Context& ctx) : Item{k, ctx} {}\n\n void Dump_(Sink&) const override {}\n void Inspect_(std::ostream& os, unsigned indent) const override;\n FilePosition GetSize() const noexcept override { return 0; }\n };\n\n}\n#endif\n" }, { "alpha_fraction": 0.7266411185264587, "alphanum_fraction": 0.7294023633003235, "avg_line_length": 59.03743362426758, "blob_id": "70581165e2255a247bab91e2c9a21fa24534fb5f", "content_id": "96f3ca593d64f57eb6b7ab9216122a47da3c0c7d", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11227, "license_type": "permissive", "max_line_length": 341, "num_lines": 187, "path": "/src/format/stsc/instruction.binding.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "// Auto generated code, do not edit. See gen_binding in project root.\n#if LIBSHIT_WITH_LUA\n#include <libshit/lua/user_type.hpp>\n\n\nconst char ::Neptools::Stsc::InstructionBase::TYPE_NAME[] = \"neptools.stsc.instruction_base\";\n\nconst char ::Neptools::Stsc::InstructionRndJumpItem::TYPE_NAME[] = \"neptools.stsc.instruction_rnd_jump_item\";\n\nconst char ::Neptools::Stsc::UnimplementedInstructionItem::TYPE_NAME[] = \"neptools.stsc.unimplemented_instruction_item\";\n\nconst char ::Neptools::Stsc::InstructionJumpIfItem::TYPE_NAME[] = \"neptools.stsc.instruction_jump_if_item\";\n\nconst char ::Neptools::Stsc::InstructionJumpIfItem::Node::TYPE_NAME[] = \"neptools.stsc.instruction_jump_if_item.node\";\n\nconst char ::Neptools::Stsc::InstructionJumpSwitchItemNoire::TYPE_NAME[] = \"neptools.stsc.instruction_jump_switch_item_noire\";\n\nconst char ::Neptools::Stsc::InstructionJumpSwitchItemNoire::Expression::TYPE_NAME[] = \"neptools.stsc.instruction_jump_switch_item_noire.expression\";\n\nconst char ::Neptools::Stsc::InstructionJumpSwitchItemPotbb::TYPE_NAME[] = \"neptools.stsc.instruction_jump_switch_item_potbb\";\n\nnamespace Libshit::Lua\n{\n\n // class neptools.stsc.instruction_base\n template<>\n void TypeRegisterTraits<::Neptools::Stsc::InstructionBase>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stsc::InstructionBase, ::Neptools::Item>();\n\n bld.AddFunction<\n static_cast<::Neptools::Stsc::InstructionBase & (*)(::Neptools::ItemPointer, ::Neptools::Stsc::Flavor)>(::Neptools::Stsc::InstructionBase::CreateAndInsert)\n >(\"create_and_insert\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::InstructionBase, const ::uint8_t, &::Neptools::Stsc::InstructionBase::opcode>\n >(\"get_opcode\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stsc::InstructionBase> reg_neptools_stsc_instruction_base;\n\n // class neptools.stsc.instruction_rnd_jump_item\n template<>\n void TypeRegisterTraits<::Neptools::Stsc::InstructionRndJumpItem>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stsc::InstructionRndJumpItem, ::Neptools::Stsc::InstructionBase>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stsc::InstructionRndJumpItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::uint8_t>, LuaGetRef<::Neptools::Source>>\n >(\"new\");\n bld.AddFunction<\n &::Libshit::Lua::GetSmartOwnedMember<::Neptools::Stsc::InstructionRndJumpItem, std::vector<::Libshit::NotNull<::Neptools::LabelPtr> >, &::Neptools::Stsc::InstructionRndJumpItem::tgts>\n >(\"get_tgts\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stsc::InstructionRndJumpItem> reg_neptools_stsc_instruction_rnd_jump_item;\n\n // class neptools.stsc.unimplemented_instruction_item\n template<>\n void TypeRegisterTraits<::Neptools::Stsc::UnimplementedInstructionItem>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stsc::UnimplementedInstructionItem, ::Neptools::Stsc::InstructionBase>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stsc::UnimplementedInstructionItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::uint8_t>, LuaGetRef<const ::Neptools::Source &>>\n >(\"new\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stsc::UnimplementedInstructionItem> reg_neptools_stsc_unimplemented_instruction_item;\n\n // class neptools.stsc.instruction_jump_if_item\n template<>\n void TypeRegisterTraits<::Neptools::Stsc::InstructionJumpIfItem>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stsc::InstructionJumpIfItem, ::Neptools::Stsc::InstructionBase>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stsc::InstructionJumpIfItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::uint8_t>, LuaGetRef<::Neptools::Source>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stsc::InstructionJumpIfItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::uint8_t>, LuaGetRef<::Libshit::NotNull<::Neptools::LabelPtr>>, LuaGetRef<std::vector<::Neptools::Stsc::InstructionJumpIfItem::Node>>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stsc::InstructionJumpIfItem>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::Libshit::Lua::StateRef>, LuaGetRef<::uint8_t>, LuaGetRef<::Libshit::NotNull<::Neptools::LabelPtr>>, LuaGetRef<::Libshit::Lua::RawTable>>\n >(\"new\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::InstructionJumpIfItem, ::Libshit::NotNull<::Neptools::LabelPtr>, &::Neptools::Stsc::InstructionJumpIfItem::tgt>\n >(\"get_tgt\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stsc::InstructionJumpIfItem, ::Libshit::NotNull<::Neptools::LabelPtr>, &::Neptools::Stsc::InstructionJumpIfItem::tgt>\n >(\"set_tgt\");\n bld.AddFunction<\n &::Libshit::Lua::GetSmartOwnedMember<::Neptools::Stsc::InstructionJumpIfItem, std::vector<::Neptools::Stsc::InstructionJumpIfItem::Node>, &::Neptools::Stsc::InstructionJumpIfItem::tree>\n >(\"get_tree\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stsc::InstructionJumpIfItem> reg_neptools_stsc_instruction_jump_if_item;\n\n // class neptools.stsc.instruction_jump_if_item.node\n template<>\n void TypeRegisterTraits<::Neptools::Stsc::InstructionJumpIfItem::Node>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::InstructionJumpIfItem::Node, ::uint8_t, &::Neptools::Stsc::InstructionJumpIfItem::Node::operation>\n >(\"get_operation\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::InstructionJumpIfItem::Node, ::uint32_t, &::Neptools::Stsc::InstructionJumpIfItem::Node::value>\n >(\"get_value\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::InstructionJumpIfItem::Node, ::size_t, &::Neptools::Stsc::InstructionJumpIfItem::Node::left>\n >(\"get_left\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::InstructionJumpIfItem::Node, ::size_t, &::Neptools::Stsc::InstructionJumpIfItem::Node::right>\n >(\"get_right\");\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stsc::InstructionJumpIfItem::Node>::Make<>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stsc::InstructionJumpIfItem::Node>::Make<LuaGetRef<::uint8_t>, LuaGetRef<::uint32_t>, LuaGetRef<::size_t>, LuaGetRef<::size_t>>\n >(\"new\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stsc::InstructionJumpIfItem::Node> reg_neptools_stsc_instruction_jump_if_item_node;\n\n // class neptools.stsc.instruction_jump_switch_item_noire\n template<>\n void TypeRegisterTraits<::Neptools::Stsc::InstructionJumpSwitchItemNoire>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stsc::InstructionJumpSwitchItemNoire, ::Neptools::Stsc::InstructionBase>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stsc::InstructionJumpSwitchItemNoire>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::uint8_t>, LuaGetRef<::Neptools::Source>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stsc::InstructionJumpSwitchItemNoire>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::uint8_t>, LuaGetRef<::uint32_t>, LuaGetRef<bool>, LuaGetRef<Libshit::AT<std::vector<::Neptools::Stsc::InstructionJumpSwitchItemNoire::Expression> >>>\n >(\"new\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::InstructionJumpSwitchItemNoire, ::uint32_t, &::Neptools::Stsc::InstructionJumpSwitchItemNoire::expected_val>\n >(\"get_expected_val\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stsc::InstructionJumpSwitchItemNoire, ::uint32_t, &::Neptools::Stsc::InstructionJumpSwitchItemNoire::expected_val>\n >(\"set_expected_val\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::InstructionJumpSwitchItemNoire, bool, &::Neptools::Stsc::InstructionJumpSwitchItemNoire::last_is_default>\n >(\"get_last_is_default\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stsc::InstructionJumpSwitchItemNoire, bool, &::Neptools::Stsc::InstructionJumpSwitchItemNoire::last_is_default>\n >(\"set_last_is_default\");\n bld.AddFunction<\n &::Libshit::Lua::GetSmartOwnedMember<::Neptools::Stsc::InstructionJumpSwitchItemNoire, std::vector<::Neptools::Stsc::InstructionJumpSwitchItemNoire::Expression>, &::Neptools::Stsc::InstructionJumpSwitchItemNoire::expressions>\n >(\"get_expressions\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stsc::InstructionJumpSwitchItemNoire> reg_neptools_stsc_instruction_jump_switch_item_noire;\n\n // class neptools.stsc.instruction_jump_switch_item_noire.expression\n template<>\n void TypeRegisterTraits<::Neptools::Stsc::InstructionJumpSwitchItemNoire::Expression>::Register(TypeBuilder& bld)\n {\n\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::InstructionJumpSwitchItemNoire::Expression, ::uint32_t, &::Neptools::Stsc::InstructionJumpSwitchItemNoire::Expression::expression>\n >(\"get_expression\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::InstructionJumpSwitchItemNoire::Expression, ::Libshit::NotNull<::Neptools::LabelPtr>, &::Neptools::Stsc::InstructionJumpSwitchItemNoire::Expression::target>\n >(\"get_target\");\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stsc::InstructionJumpSwitchItemNoire::Expression>::Make<LuaGetRef<::uint32_t>, LuaGetRef<::Libshit::NotNull<::Neptools::LabelPtr>>>\n >(\"new\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stsc::InstructionJumpSwitchItemNoire::Expression> reg_neptools_stsc_instruction_jump_switch_item_noire_expression;\n\n // class neptools.stsc.instruction_jump_switch_item_potbb\n template<>\n void TypeRegisterTraits<::Neptools::Stsc::InstructionJumpSwitchItemPotbb>::Register(TypeBuilder& bld)\n {\n bld.Inherit<::Neptools::Stsc::InstructionJumpSwitchItemPotbb, ::Neptools::Stsc::InstructionJumpSwitchItemNoire>();\n\n bld.AddFunction<\n &::Libshit::Lua::TypeTraits<::Neptools::Stsc::InstructionJumpSwitchItemPotbb>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::uint8_t>, LuaGetRef<::Neptools::Source>>,\n &::Libshit::Lua::TypeTraits<::Neptools::Stsc::InstructionJumpSwitchItemPotbb>::Make<LuaGetRef<::Neptools::Item::Key>, LuaGetRef<::Neptools::Context &>, LuaGetRef<::uint8_t>, LuaGetRef<::uint32_t>, LuaGetRef<bool>, LuaGetRef<Libshit::AT<std::vector<::Neptools::Stsc::InstructionJumpSwitchItemNoire::Expression> >>, LuaGetRef<::uint8_t>>\n >(\"new\");\n bld.AddFunction<\n &::Libshit::Lua::GetMember<::Neptools::Stsc::InstructionJumpSwitchItemPotbb, ::uint8_t, &::Neptools::Stsc::InstructionJumpSwitchItemPotbb::trailing_byte>\n >(\"get_trailing_byte\");\n bld.AddFunction<\n &::Libshit::Lua::SetMember<::Neptools::Stsc::InstructionJumpSwitchItemPotbb, ::uint8_t, &::Neptools::Stsc::InstructionJumpSwitchItemPotbb::trailing_byte>\n >(\"set_trailing_byte\");\n\n }\n static TypeRegister::StateRegister<::Neptools::Stsc::InstructionJumpSwitchItemPotbb> reg_neptools_stsc_instruction_jump_switch_item_potbb;\n\n}\n#endif\n" }, { "alpha_fraction": 0.6113795042037964, "alphanum_fraction": 0.644659161567688, "avg_line_length": 29.04838752746582, "blob_id": "7dcf8b3da19c360f0973bcf405bab25acac19732", "content_id": "cf8aeb9046dc52d7d1b0e251382b6b6c6991f1ac", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1863, "license_type": "permissive", "max_line_length": 78, "num_lines": 62, "path": "/src/format/stcm/gbnl.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_C8313FD1_2CD9_4882_BDAD_E751A14AA2DF\n#define UUID_C8313FD1_2CD9_4882_BDAD_E751A14AA2DF\n#pragma once\n\n#include \"../item.hpp\"\n#include \"../gbnl.hpp\"\n#include \"file.hpp\"\n\nnamespace Neptools { class RawItem; }\n\nnamespace Neptools::Stcm\n{\n\n class GbnlItem final : public Item, public Gbnl\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n GbnlItem(Key k, Context& ctx, Source src)\n : Item{k, ctx}, Gbnl{std::move(src)}\n { PostCtor(ctx); }\n GbnlItem(Key k, Context& ctx, Endian endian, bool is_gstl, uint32_t flags,\n uint32_t field_28, uint32_t field_30,\n Libshit::AT<Gbnl::Struct::TypePtr> type)\n : Item{k, ctx},\n Gbnl{endian, is_gstl, flags, field_28, field_30, std::move(type)}\n { PostCtor(ctx); }\n#if LIBSHIT_WITH_LUA\n GbnlItem(\n Key k, Context& ctx, Libshit::Lua::StateRef vm, Endian endian,\n bool is_gstl, uint32_t flags, uint32_t field_28, uint32_t field_30,\n Libshit::AT<Gbnl::Struct::TypePtr> type,\n Libshit::Lua::RawTable messages)\n : Item{k, ctx},\n Gbnl{vm, endian, is_gstl, flags, field_28, field_30, std::move(type),\n messages}\n { PostCtor(ctx); }\n#endif\n\n void Dispose() noexcept override;\n\n static GbnlItem& CreateAndInsert(ItemPointer ptr);\n\n void Fixup() override { Gbnl::Fixup(); }\n FilePosition GetSize() const noexcept override { return Gbnl::GetSize(); }\n\n private:\n void PostCtor(Context& ctx) noexcept\n {\n if (auto file = dynamic_cast<File*>(&ctx))\n file->SetGbnl(*this);\n }\n\n void Dump_(Sink& sink) const override { Gbnl::Dump_(sink); }\n void Inspect_(std::ostream& os, unsigned indent) const override\n { Item::Inspect_(os, indent); Gbnl::InspectGbnl(os, indent); }\n };\n\n inline Libshit::Lua::DynamicObject& GetDynamicObject(GbnlItem& item)\n { return static_cast<Item&>(item); }\n\n}\n#endif\n" }, { "alpha_fraction": 0.634739100933075, "alphanum_fraction": 0.6726232767105103, "avg_line_length": 23.120689392089844, "blob_id": "d55e9f9f5ab261f90e09e433243b417bdcd51e92", "content_id": "19563814105c97ea816842a5197249c1c0d1051e", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1399, "license_type": "permissive", "max_line_length": 79, "num_lines": 58, "path": "/src/format/stsc/file.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_CACA9E02_5122_4C09_9463_73AD33BA5802\n#define UUID_CACA9E02_5122_4C09_9463_73AD33BA5802\n#pragma once\n\n#include \"../context.hpp\"\n#include \"../../source.hpp\"\n#include \"../../txt_serializable.hpp\"\n\nnamespace Neptools::Stsc\n{\n\n enum class LIBSHIT_LUAGEN() Flavor\n {\n#define NEPTOOLS_GEN_STSC_FLAVOR(x, ...) \\\n x(NOIRE, __VA_ARGS__) \\\n x(POTBB, __VA_ARGS__)\n#define NEPTOOLS_GEN_ENUM(x,y) x,\n NEPTOOLS_GEN_STSC_FLAVOR(NEPTOOLS_GEN_ENUM,)\n#undef NEPTOOLS_GEN_ENUM\n };\n\n // not constexpr because it only 5 years to implement c++14 in gcc and broken\n // in <gcc-9: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67026\n inline const char* ToString(Flavor f) noexcept\n {\n switch (f)\n {\n#define NEPTOOLS_GEN_CASE(x,y) case Flavor::x: return #x;\n NEPTOOLS_GEN_STSC_FLAVOR(NEPTOOLS_GEN_CASE,)\n#undef NEPTOOLS_GEN_CASWE\n };\n LIBSHIT_UNREACHABLE(\"Invalid Flavor value\");\n }\n\n class File final : public Context, public TxtSerializable\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n File(Flavor flavor) : flavor{flavor} {}\n File(Source src, Flavor flavor);\n\n Flavor flavor;\n\n protected:\n void Inspect_(std::ostream& os, unsigned indent) const override;\n\n private:\n void Parse_(Source& src);\n\n void WriteTxt_(std::ostream& os) const override;\n void ReadTxt_(std::istream& is) override;\n };\n\n}\n\nLIBSHIT_ENUM(Neptools::Stsc::Flavor);\n\n#endif\n" }, { "alpha_fraction": 0.6417266130447388, "alphanum_fraction": 0.6733812689781189, "avg_line_length": 27.561643600463867, "blob_id": "701837a45467f109f54b701448e5fd01b2e9eeb9", "content_id": "5cb8a42b67370de7baedeccb24ad4f6dd3c157ae", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2085, "license_type": "permissive", "max_line_length": 83, "num_lines": 73, "path": "/src/format/stcm/exports.hpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#ifndef UUID_3260390C_7569_4E66_B6BA_CC5CC7E58F9A\n#define UUID_3260390C_7569_4E66_B6BA_CC5CC7E58F9A\n#pragma once\n\n#include \"../item.hpp\"\n#include \"../../source.hpp\"\n\n#include <libshit/fixed_string.hpp>\n#include <libshit/lua/auto_table.hpp>\n#include <boost/endian/arithmetic.hpp>\n\nnamespace Neptools::Stcm\n{\n\n class HeaderItem;\n class ExportsItem final : public Item\n {\n LIBSHIT_DYNAMIC_OBJECT;\n public:\n enum LIBSHIT_LUAGEN() Type : uint32_t\n {\n CODE = 0,\n DATA = 1,\n };\n\n struct Entry\n {\n boost::endian::little_uint32_t type;\n Libshit::FixedString<0x20> name;\n boost::endian::little_uint32_t offset;\n\n void Validate(FilePosition file_size) const;\n };\n static_assert(sizeof(Entry) == 0x28);\n\n struct EntryType : public RefCounted, public Libshit::Lua::DynamicObject\n {\n Type type;\n Libshit::FixedString<0x20> name;\n Libshit::NotNull<LabelPtr> lbl;\n\n EntryType(Type type, const Libshit::FixedString<0x20>& name,\n Libshit::NotNull<LabelPtr> lbl)\n : type{type}, name{std::move(name)}, lbl{std::move(lbl)} {}\n\n LIBSHIT_DYNAMIC_OBJECT;\n };\n using VectorEntry = Libshit::NotNull<Libshit::RefCountedPtr<EntryType>>;\n\n ExportsItem(Key k, Context& ctx) : Item{k, ctx} {}\n ExportsItem(Key k, Context& ctx, Source src, uint32_t export_count);\n ExportsItem(Key k, Context& ctx, Libshit::AT<std::vector<VectorEntry>> entries)\n : Item{k, ctx}, entries{std::move(entries.Get())} {}\n static ExportsItem& CreateAndInsert(ItemPointer ptr, uint32_t export_count);\n\n FilePosition GetSize() const noexcept override\n { return sizeof(Entry) * entries.size(); }\n\n LIBSHIT_LUAGEN(get=\"::Libshit::Lua::GetSmartOwnedMember\")\n std::vector<VectorEntry> entries;\n\n void Dispose() noexcept override;\n\n private:\n void Dump_(Sink& sink) const override;\n void Inspect_(std::ostream& os, unsigned indent) const override;\n void Parse_(Context& ctx, Source& src, uint32_t export_count);\n};\n\n}\n\nLIBSHIT_ENUM(Neptools::Stcm::ExportsItem::ExportsItem::Type);\n#endif\n" }, { "alpha_fraction": 0.6120907068252563, "alphanum_fraction": 0.6152393221855164, "avg_line_length": 23.060606002807617, "blob_id": "13710e7635e5c570ffc8c3da8aa64d48b51715c2", "content_id": "2ca159981a5e020d2a5bf828404a70e48bc60967", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1588, "license_type": "permissive", "max_line_length": 83, "num_lines": 66, "path": "/src/format/stcm/file.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"file.hpp\"\n#include \"gbnl.hpp\"\n#include \"header.hpp\"\n#include \"../eof_item.hpp\"\n#include \"../item.hpp\"\n#include \"../../open.hpp\"\n\nnamespace Neptools::Stcm\n{\n\n File::File(Source src)\n {\n ADD_SOURCE(Parse_(src), src);\n }\n\n void File::Parse_(Source& src)\n {\n auto root = Create<RawItem>(src);\n SetupParseFrom(*root);\n root->Split(root->GetSize(), Create<EofItem>());\n HeaderItem::CreateAndInsert({root.get(), 0});\n }\n\n void File::Inspect_(std::ostream& os, unsigned indent) const\n {\n LIBSHIT_ASSERT(GetLabels().empty());\n os << \"neptools.stcm.file()\";\n InspectChildren(os, indent);\n }\n\n void File::SetGbnl(GbnlItem& gbnl) noexcept\n {\n LIBSHIT_ASSERT(&gbnl.GetUnsafeContext() == this);\n if (!first_gbnl) first_gbnl = &gbnl;\n }\n\n void File::Gc() noexcept\n {\n for (auto it = GetChildren().begin(); it != GetChildren().end(); )\n if (dynamic_cast<RawItem*>(&*it) && it->GetLabels().empty())\n it = GetChildren().erase(it);\n else\n ++it;\n }\n\n void File::WriteTxt_(std::ostream& os) const\n { if (first_gbnl) first_gbnl->WriteTxt(os); }\n\n void File::ReadTxt_(std::istream& is)\n { if (first_gbnl) first_gbnl->ReadTxt(is); }\n\n static OpenFactory stcm_open{[](const Source& src) -> Libshit::SmartPtr<Dumpable>\n {\n if (src.GetSize() < sizeof(HeaderItem::Header)) return nullptr;\n char buf[4];\n src.PreadGen(0, buf);\n if (memcmp(buf, \"STCM\", 4) == 0)\n return Libshit::MakeSmart<File>(src);\n else\n return nullptr;\n }};\n\n}\n\n#include <libshit/lua/table_ret_wrap.hpp>\n#include \"file.binding.hpp\"\n" }, { "alpha_fraction": 0.5974426865577698, "alphanum_fraction": 0.5987654328346252, "avg_line_length": 23.518918991088867, "blob_id": "db6b67b3c64f58aaf7fcbda5a9bead4974cada6a", "content_id": "7df60d549196d11cba4c1f96f63ca90de701d327", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4536, "license_type": "permissive", "max_line_length": 79, "num_lines": 185, "path": "/src/format/context.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"context.hpp\"\n#include \"item.hpp\"\n#include \"../utils.hpp\"\n\n#include <libshit/except.hpp>\n#include <libshit/char_utils.hpp>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n\nnamespace Neptools\n{\n\n Context::Context()\n : ItemWithChildren{Key{}, *this}\n {}\n\n Context::~Context()\n {\n Context::Dispose();\n }\n\n void Context::SetupParseFrom(Item& item)\n {\n pmap[0] = &item;\n GetChildren().push_back(item); // noexcept\n }\n\n void Context::Fixup()\n {\n pmap.clear();\n\n FilePosition pos = 0;\n for (auto& c : GetChildren())\n {\n c.UpdatePosition(pos);\n pos += c.GetSize();\n }\n // todo? size = pos;\n }\n\n\n Libshit::NotNull<LabelPtr> Context::GetLabel(const std::string& name) const\n {\n auto it = labels.find(name);\n if (it == labels.end())\n LIBSHIT_THROW(std::out_of_range, \"Context::GetLabel\",\n \"Affected label\", name);\n return MakeNotNull(const_cast<Label*>(&*it));\n }\n\n Libshit::NotNull<LabelPtr> Context::CreateLabel(\n std::string name, ItemPointer ptr)\n {\n auto lbl = new Label{std::move(name), ptr};\n auto pair = labels.insert(*lbl);\n if (!pair.second)\n {\n name = std::move(lbl->name);\n delete lbl;\n LIBSHIT_THROW(std::out_of_range, \"label already exists\",\n \"Affected label\", std::move(name));\n }\n\n ptr->labels.insert(*pair.first);\n return MakeNotNull(&*pair.first);\n }\n\n Libshit::NotNull<LabelPtr> Context::CreateLabelFallback(\n const std::string& name, ItemPointer ptr)\n {\n LabelsMap::insert_commit_data commit;\n std::string str = name;\n\n auto pair = labels.insert_check(str, commit);\n for (int i = 1; !pair.second; ++i)\n {\n std::stringstream ss;\n ss << name << '_' << i;\n str = ss.str();\n pair = labels.insert_check(str, commit);\n }\n\n auto it = labels.insert_commit(*new Label{std::move(str), ptr}, commit);\n\n ptr->labels.insert(*it);\n return MakeNotNull(&*it);\n }\n\n Libshit::NotNull<LabelPtr> Context::CreateOrSetLabel(\n std::string name, ItemPointer ptr)\n {\n LabelsMap::insert_commit_data commit;\n auto [it, insertable] = labels.insert_check(name, commit);\n\n if (insertable)\n {\n auto it = labels.insert_commit(*new Label{std::move(name), ptr}, commit);\n ptr->labels.insert(*it);\n return MakeNotNull(&*it);\n }\n else\n {\n if (it->ptr != nullptr) it->ptr->labels.remove_node(*it);\n it->ptr = ptr;\n ptr->labels.insert(*it);\n return MakeNotNull(&*it);\n }\n }\n\n Libshit::NotNull<LabelPtr> Context::GetOrCreateDummyLabel(std::string name)\n {\n LabelsMap::insert_commit_data commit;\n auto [it, insertable] = labels.insert_check(name, commit);\n\n if (insertable)\n it = labels.insert_commit(\n *new Label{std::move(name), {nullptr,0}}, commit);\n return MakeNotNull(const_cast<Label*>(&*it));\n }\n\n Libshit::NotNull<LabelPtr> Context::GetLabelTo(ItemPointer ptr)\n {\n auto& lctr = ptr.item->labels;\n auto it = lctr.find(ptr.offset);\n if (it != lctr.end()) return MakeNotNull(&*it);\n\n std::stringstream ss;\n ss << \"loc_\" << std::setw(8) << std::setfill('0') << std::hex\n << ptr.item->GetPosition() + ptr.offset;\n return CreateLabelFallback(ss.str(), ptr);\n }\n\n Libshit::NotNull<LabelPtr> Context::GetLabelTo(\n FilePosition pos, const std::string& name)\n {\n auto ptr = GetPointer(pos);\n auto& lctr = ptr.item->labels;\n auto it = lctr.find(ptr.offset);\n if (it != lctr.end()) return MakeNotNull(&*it);\n\n return CreateLabelFallback(name, ptr);\n }\n\n ItemPointer Context::GetPointer(FilePosition pos) const noexcept\n {\n auto it = pmap.upper_bound(pos);\n LIBSHIT_ASSERT_MSG(it != pmap.begin(), \"file position out of range\");\n --it;\n LIBSHIT_ASSERT(it->first == it->second->GetPosition());\n return {it->second, pos - it->first};\n }\n\n void Context::Dispose() noexcept\n {\n pmap.clear();\n struct Disposer\n {\n void operator()(Label* l)\n {\n auto& item = l->ptr.item;\n if (item)\n {\n item->labels.erase(item->labels.iterator_to(*l));\n item = nullptr;\n }\n l->RemoveRef();\n }\n };\n labels.clear_and_dispose(Disposer{});\n GetChildren().clear();\n\n ItemWithChildren::Dispose();\n }\n\n std::ostream& operator<<(std::ostream& os, PrintLabelStruct l)\n {\n if (l.label == nullptr)\n return os << \"nil\";\n return os << \"l(\" << Libshit::Quoted(l.label->GetName()) << ')';\n }\n\n}\n\n#include \"context.binding.hpp\"\n" }, { "alpha_fraction": 0.6406926512718201, "alphanum_fraction": 0.6406926512718201, "avg_line_length": 14.399999618530273, "blob_id": "de958448741d525549a51f14f4659329e52a06ec", "content_id": "ea1c502ed48e0aaa88d38be3dfe14e69d5a7d233", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 231, "license_type": "permissive", "max_line_length": 65, "num_lines": 15, "path": "/src/format/eof_item.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"eof_item.hpp\"\n#include \"context.hpp\"\n\nnamespace Neptools\n{\n\n void EofItem::Inspect_(std::ostream& os, unsigned indent) const\n {\n Item::Inspect_(os, indent);\n os << \"eof()\";\n }\n\n}\n\n#include \"eof_item.binding.hpp\"\n" }, { "alpha_fraction": 0.6437768340110779, "alphanum_fraction": 0.6490224003791809, "avg_line_length": 20.61855697631836, "blob_id": "9116558c307a347a4c13650c3c3fd5018c47d6f0", "content_id": "483c8dff4ce4a2da12069a117b975f0864fc3985", "detected_licenses": [ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2097, "license_type": "permissive", "max_line_length": 83, "num_lines": 97, "path": "/src/dumpable.cpp", "repo_name": "u3shit/neptools", "src_encoding": "UTF-8", "text": "#include \"dumpable.hpp\"\n\n#include \"sink.hpp\"\n\n#include <libshit/platform.hpp>\n\n#include <boost/filesystem/operations.hpp>\n#include <fstream>\n\n#if LIBSHIT_OS_IS_WINDOWS\n# include <vector>\n# define WIN32_LEAN_AND_MEAN\n# define NOMINMAX\n#include <windows.h>\n\nnamespace\n{\n struct DeleteOnExitHelper\n {\n ~DeleteOnExitHelper()\n {\n for (auto& p : pths)\n DeleteFileW(p.c_str());\n }\n\n std::vector<boost::filesystem::path> pths;\n };\n void DeleteOnExit(boost::filesystem::path pth)\n {\n static DeleteOnExitHelper hlp;\n hlp.pths.push_back(std::move(pth));\n }\n}\n#endif\n\nnamespace Neptools\n{\n\n Libshit::NotNullSharedPtr<TxtSerializable>\n Dumpable::GetDefaultTxtSerializable(\n const Libshit::NotNullSharedPtr<Dumpable>& thiz)\n { LIBSHIT_THROW(Libshit::DecodeError, \"Not txt-serializable file\"); }\n\n void Dumpable::Dump(const boost::filesystem::path& path) const\n {\n#if LIBSHIT_OS_IS_VITA\n // no unique_path on vita\n Dump(*Sink::ToFile(path, GetSize()));\n#else\n auto path2 = path;\n {\n auto sink = Sink::ToFile(path2+=boost::filesystem::unique_path(), GetSize());\n Dump(*sink);\n }\n\n#if LIBSHIT_OS_IS_WINDOWS\n if (LIBSHIT_OS_IS_WINDOWS && boost::filesystem::is_regular_file(path))\n {\n auto path3 = path;\n boost::filesystem::rename(path, path3+=boost::filesystem::unique_path());\n if (!DeleteFileW(path3.c_str()) && GetLastError() == ERROR_ACCESS_DENIED)\n DeleteOnExit(std::move(path3));\n }\n#endif\n boost::filesystem::rename(path2, path);\n#endif\n }\n\n void Dumpable::Inspect(const boost::filesystem::path& path) const\n {\n return Inspect(OpenOut(path));\n }\n\n std::ostream& Dumpable::Indent(std::ostream& os, unsigned indent)\n {\n std::ostreambuf_iterator<char> it{os};\n for (size_t i = 0; i < 2*indent; ++i) *it = ' ';\n return os;\n }\n\n\n std::ostream& operator<<(std::ostream& os, const Dumpable& dmp)\n {\n dmp.Inspect(os);\n return os;\n }\n\n std::string Dumpable::Inspect() const\n {\n std::stringstream ss;\n Inspect(ss);\n return ss.str();\n }\n\n}\n\n#include \"dumpable.binding.hpp\"\n" } ]
107
jessebmiller/lifedash
https://github.com/jessebmiller/lifedash
072ebaa449dbfe23cbdd93d2f741b6c41b4be62f
3bb760f767b37ec32c4a3945ad0efb47df02c590
1cb47b159658eab39eb199b311ae099d5ebc2925
refs/heads/master
2021-01-10T09:05:03.947240
2016-02-05T13:38:42
2016-02-05T13:38:42
51,001,523
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5466284155845642, "alphanum_fraction": 0.5810617208480835, "avg_line_length": 20.121212005615234, "blob_id": "9635b41fb7067ef3052ee5d597471e53f5cfe9dc", "content_id": "fa169830d6a9d00ec51451c0b76599bbdb7d448c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 697, "license_type": "permissive", "max_line_length": 64, "num_lines": 33, "path": "/app/test_components.py", "repo_name": "jessebmiller/lifedash", "src_encoding": "UTF-8", "text": "from components import ( \n render,\n Today,\n)\n\nfrom datetime import date\nimport unittest\n\n\nclass TestComponents(unittest.TestCase):\n\n def setUp(self):\n self.today = Today(\n date=date(year=2016, month=2, day=5),\n weather=\"Mockingly cloudy\",\n temp=22,\n )\n\n def tearDown(self):\n pass\n\n def test_today(self):\n expected = \"\"\" \n <div class=\"today\">\n <time datetime=\"2016-02-05\">Friday February 05 2016</time>\n <span class=\"weather\">Mockingly cloudy</span>\n <span class=\"temp\">22</span>\n </div>\n \"\"\"\n self.assertEqual(render(self.today), expected)\n\n def test_can_pass(self):\n assert True\n" }, { "alpha_fraction": 0.7948718070983887, "alphanum_fraction": 0.7948718070983887, "avg_line_length": 18.5, "blob_id": "1d95a2df2cfe1afa6e9ba0b38185cd0bf15dec90", "content_id": "1944c02173a1c1f9a8372bde93057e4f453d569f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 39, "license_type": "permissive", "max_line_length": 27, "num_lines": 2, "path": "/README.md", "repo_name": "jessebmiller/lifedash", "src_encoding": "UTF-8", "text": "# lifedash\nA dashboard for my mornings\n" }, { "alpha_fraction": 0.5510203838348389, "alphanum_fraction": 0.5918367505073547, "avg_line_length": 11.933333396911621, "blob_id": "149aaf7e96e9dbf91df7ae6105e3429528634858", "content_id": "e08b5bf3ed1f288685a100432f35408dc2f1b2a8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 196, "license_type": "permissive", "max_line_length": 44, "num_lines": 15, "path": "/app/__main__.py", "repo_name": "jessebmiller/lifedash", "src_encoding": "UTF-8", "text": "from bottle import (\n route,\n run,\n template,\n)\n\nfrom components import (\n render,\n)\n\n@route('/')\ndef index():\n return render(index)\n\nrun(host=\"0.0.0.0\", port=\"8000\", debug=True)\n \n" }, { "alpha_fraction": 0.5874999761581421, "alphanum_fraction": 0.5874999761581421, "avg_line_length": 21.325580596923828, "blob_id": "2fa5767dfc931fb9b188e2130443826d62eecb6d", "content_id": "56873e150a998489294afdaff15ecc9591649208", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 960, "license_type": "permissive", "max_line_length": 78, "num_lines": 43, "path": "/app/components.py", "repo_name": "jessebmiller/lifedash", "src_encoding": "UTF-8", "text": "from datetime import date\nfrom functools import singledispatch\n\nfrom pyrsistent import (\n PRecord,\n field,\n)\n\n\n@singledispatch\ndef render(data):\n raise TypeError(\"no render function found for type {}\".format(type(data)))\n\n@render.register(list)\ndef _(xs):\n return \"<ul>{}</ul>\".format(\n ''.join([\"<li>{}</li>\".format(render(x)) for x in xs])\n )\n\n@render.register(date)\ndef _(d):\n return '<time datetime=\"{}\">{}</time>'.format(\n # YYYY-MM-DD Weekday Month DD YYYY\n d.isoformat(), d.strftime(\"%A %B %d %Y\"))\n\nclass Today(PRecord):\n date = field(type=date)\n weather = field(type=str)\n temp = field(type=int)\n\n@render.register(Today)\ndef _(today):\n return \"\"\" \n <div class=\"today\">\n {date}\n <span class=\"weather\">{weather}</span>\n <span class=\"temp\">{temp}</span>\n </div>\n \"\"\".format(\n date=render(today['date']),\n weather=today.weather,\n temp=today.temp,\n )\n" }, { "alpha_fraction": 0.692307710647583, "alphanum_fraction": 0.692307710647583, "avg_line_length": 13.857142448425293, "blob_id": "310206ff044acc17e3f4161a756434626ad9aa04", "content_id": "81951ff73f4656fe1ab967e05a5d00349b31210b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 104, "license_type": "permissive", "max_line_length": 35, "num_lines": 7, "path": "/app/test_main.py", "repo_name": "jessebmiller/lifedash", "src_encoding": "UTF-8", "text": "import unittest\n\n\nclass MainTests(unittest.TestCase):\n\n def test_can_pass(self):\n assert True\n" }, { "alpha_fraction": 0.6441717743873596, "alphanum_fraction": 0.6564416885375977, "avg_line_length": 15.300000190734863, "blob_id": "28f2fb2ae11d9977dea62c46b38820ad0255717f", "content_id": "18c5d04fffa59d7f062221d9dfd7993d946df190", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 163, "license_type": "permissive", "max_line_length": 28, "num_lines": 10, "path": "/Dockerfile", "repo_name": "jessebmiller/lifedash", "src_encoding": "UTF-8", "text": "from frolvlad/alpine-python3\nmaintainer Jesse Miller (jessea@jessebmiller.com)\n\nrun pip install bottle \\\n pyrsistent\n \nrun mkdir /app\nadd app /app\n\ncmd python3 -u app\n" } ]
6
MOMOJMOGG/Repository
https://github.com/MOMOJMOGG/Repository
c361fb6f976df616d9a83a99e4082a70e4da61ed
7b73eb22f8b5656266e61e20d899351a61ea4d59
82f1782f9184556b809f1886d3f97a5c676a1078
refs/heads/master
2023-04-16T08:07:31.105471
2021-04-18T15:30:30
2021-04-18T15:30:30
359,180,593
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.2978801131248474, "alphanum_fraction": 0.31469297409057617, "avg_line_length": 30.45977020263672, "blob_id": "99089363cc711d0d61c1ab266b95daacd2df77c5", "content_id": "83efe58ddb243dcb9af37c748a27d228b00eaca7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2736, "license_type": "no_license", "max_line_length": 72, "num_lines": 87, "path": "/main.py", "repo_name": "MOMOJMOGG/Repository", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom data import get_data\n\ndef pattern_solution(arr):\n arr_len = len(arr)\n edge_dict = {}\n min_val = np.min(arr)\n\n min_pos = np.where(arr == min_val)[0][0]\n print(f'Min Pos: {min_pos}, val: {arr[min_pos]}')\n edge_dict['Min'] = [min_pos, arr[min_pos]]\n \n # top pos\n top_edge_pos = -1\n for i in range(min_pos, -1, -1):\n if arr[i] < 100:\n pass\n else:\n if i!=0:\n if arr[i-1] - arr[i] >= 10:\n pass\n else:\n top_edge_pos = i\n break\n else:\n top_edge_pos = 0\n edge_dict['Top'] = [top_edge_pos, arr[top_edge_pos]]\n print(f'Top Pos: {top_edge_pos}, val: {arr[top_edge_pos]}')\n \n # first peak\n peak_dict = {}\n cur_val = 0\n slop = 1\n peak_cnt = 0\n for i in range(min_pos, arr_len):\n if peak_cnt == 4:\n break\n else:\n if slop == 1:\n if i != arr_len-1:\n if arr[i+1] >= arr[i]:\n pass\n else:\n if peak_cnt == 0:\n if arr[i] < 200:\n pass\n else:\n peak_dict['first_peak'] = [i, arr[i]]\n slop = -1\n peak_cnt += 1\n elif peak_cnt == 2:\n if arr[i] < 200:\n pass\n else:\n peak_dict['second_peak'] = [i, arr[i]]\n slop = -1\n peak_cnt += 1\n else:\n if i != arr_len-1:\n if arr[i+1] <= arr[i]:\n pass\n else:\n if peak_cnt == 1:\n if arr[i] > 200:\n pass\n else:\n peak_dict['first_valley'] = [i, arr[i]]\n slop = 1\n peak_cnt += 1\n elif peak_cnt == 3:\n if arr[i] > 200:\n pass\n else:\n peak_dict['second_valley'] = [i, arr[i]]\n slop = 1\n peak_cnt += 1\n \n \n \n print(peak_dict)\n edge_dict['peak'] = peak_dict\n print(edge_dict)\n\ntest_a, test_b = get_data()\n\npattern_solution(test_a)\npattern_solution(test_b)" } ]
1
Mashfy/portfolioweb
https://github.com/Mashfy/portfolioweb
e8142a594253c9306f6e420724d53863dfb61975
78083686abdfd28c701e8f73ba2e58a6a9857e65
2075b12e9f01e636fd802818b20fcd7a3008dc2a
refs/heads/master
2023-09-05T04:54:12.320442
2021-11-18T02:51:46
2021-11-18T02:51:46
355,140,327
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8014705777168274, "alphanum_fraction": 0.8014705777168274, "avg_line_length": 44.33333206176758, "blob_id": "39c0b42d33bd796f9b75d9c7754c71f5bc82e374", "content_id": "b823744a1b21ba834da471dca7ed8a505464fb12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 136, "license_type": "no_license", "max_line_length": 67, "num_lines": 3, "path": "/README.md", "repo_name": "Mashfy/portfolioweb", "src_encoding": "UTF-8", "text": "# portfolioweb\nthis is the same portfolio in here https://mashfy.github.io/Mashfy/\nbut implemented in django with contact page working.\n" }, { "alpha_fraction": 0.6736842393875122, "alphanum_fraction": 0.6766917109489441, "avg_line_length": 30.714284896850586, "blob_id": "6bb35c067537aa46bedc72c90719b32a6b60495e", "content_id": "8a13b3f8dd5a73d5b8f017e822c87f1c649a748f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 665, "license_type": "no_license", "max_line_length": 67, "num_lines": 21, "path": "/app/views.py", "repo_name": "Mashfy/portfolioweb", "src_encoding": "UTF-8", "text": "from django.core.checks import messages\nfrom django.shortcuts import render\nfrom .models import Contact\nfrom django.http import HttpResponse\n# Create your views here.\n\ndef index(request):\n if request.method==\"POST\":\n contact=Contact()\n name=request.POST.get('name')\n email=request.POST.get('email')\n subject=request.POST.get('subject')\n message=request.POST.get('message')\n contact.name=name\n contact.email=email\n contact.subject=subject\n contact.message=message\n contact.save()\n return HttpResponse(\"<h1>Thank you for contacting me</h1>\")\n\n return render(request, 'app/index.html')" } ]
2
LuisGabrielLiscanoLovera/ScraPreseach
https://github.com/LuisGabrielLiscanoLovera/ScraPreseach
8156d2995309593cbd6ef19aa02bd83306471758
09b3cdfd456475abf087c00aceb97f857b6c5bb8
1fd7d3222c577b15b95dd8337d0032dbf75709b6
refs/heads/master
2020-04-19T13:42:41.382979
2019-03-14T19:31:52
2019-03-14T19:31:52
168,224,279
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6554160118103027, "alphanum_fraction": 0.6593406796455383, "avg_line_length": 11.435546875, "blob_id": "88dfc3fa894629751fcb149ebda3f4310ebe9b21", "content_id": "3374e2ad89d80aba1f63188056dcf0391fce9cd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6532, "license_type": "no_license", "max_line_length": 47, "num_lines": 512, "path": "/preseash.py", "repo_name": "LuisGabrielLiscanoLovera/ScraPreseach", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport time\nimport pyautogui \n\n#time.sleep(3)\npalabras=[\n\"abad\",\n\"abalanzarse\",\n\"abatir\",\n\"blandar\",\n\"abolengo\",\n\"abrasar\",\n\"abrupto\",\n\"acefalo\",\n\"acobardar\",\n\"acrobata\",\n\"adoptivo\",\n\"afianzar\",\n\"agitación\",\n\"agrónomo\",\n\"ahinco\",\n\"albedrío\",\n\"alcázar\",\n\"alcoholismo\",\n\"ejado\",\n\"álgebr\",\n\"altísimo\",\n\"ambigüedad\",\n\"amenizar\",\n\"ampolla\",\n\"análogo\",\n\"andén\",\n\"anfibio\",\n\"antepenúltimo\",\n\"antipático\"\n\"antologia\",\n\"antroponímicos\",\n\"añejo\",\n\"apabullado\",\n\"apedrear\",\n\"apogeo\",\n\"apóstol\",\n\"aprehensión\",\n\"aprovechable\",\n\"arábigo\",\n\"arbitraje\",\n\"archipiélago\",\n\"arcilla\",\n\"argüir\",\n\"aristocracia\",\n\"armazón\",\n\"arpía\",\n\"arraiga\",\n\"arremeter\",\n\"arribo\",\n\"arrodillarse\",\n\"arropar\",\n\"arrullo\",\n\"artificio\",\n\"arzobispado\",\n\"asado\",\n\"ascenso\",\n\"asfixiante\",\n\"asmático\",\n\"aspaviento\",\n\"aspereza\",\n\"astrónomo\",\n\"ateísmo\",\n\"aterrizaje\",\n\"atravieso\",\n\"atrocidad\",\n\"autodidacta\",\n\"avemaría\",\n\"ávidamente\",\n\"ayuntamiento\",\n\"baca\",\n\"bajorrelieve\",\n\"balancear\",\n\"bálsamo\",\n\"baluarte\",\n\"bancarrota\",\n\"banderín\",\n\"barítono\",\n\"barrendero\",\n\"barullo\",\n\"batracio\",\n\"bazo\",\n\" CONCURSO DE ORTOGRAFÍA 8VO GRADO\",\n\"beneplácito\",\n\"benigno\",\n\"berro\",\n\"bibliófilo\",\n\"bienhechor\",\n\"bimotor\",\n\"binomio\",\n\"bípedo\",\n\"bizco\",\n\"blanquear\",\n\"bobada\",\n\"bolillo\",\n\"bombo\",\n\"bordón\",\n\"borrico\",\n\"bota\",\n\"bovino\",\n\"bravucón\",\n\"brazada\",\n\"bribón\",\n\"brocha\",\n\"brújula\",\n\"buhonero\",\n\"butaca\",\n\"buzón\",\n\"caballerosidad\",\n\"cabe\",\n\"cabecilla\",\n\"cacería\",\n\"cacique\",\n\"cadáveres\",\n\"calabozo\",\n\"calcetines\",\n\"calizo\",\n\"calvario\",\n\"camilla\",\n\"candil\",\n\"cántaro\",\n\"caótico\",\n\"caperuza\",\n\"carey\",\n\"carmín\",\n\"carruaje\",\n\"casar\",\n\"catálogo\",\n\"cauce\",\n\"cavidad\",\n\"cazo\",\n\"ceder\",\n\"cédula\",\n\"cegar\",\n\"celada\",\n\"célibe\",\n\"cenicero\",\n\"ceñirse\",\n\"certeza\",\n\"cesta\",\n\"cetáceo\",\n\"chantaje\",\n\"chaparrón\",\n\"chequeo\",\n\"chícharo\",\n\"chillido\",\n\"chispazo\",\n\"churro\",\n\"chusma\",\n\"cicatriz\",\n\"cigüeña\",\n\"cínico\",\n\"circunloquio\",\n\"circunstancia\",\n\"cirujano\",\n\"clarividente\",\n\"claustrofobia\",\n\"cleptómano\",\n\"climatológico\",\n\"coadyuvar\",\n\"cobijar\",\n\"cocido\",\n\"código\",\n\"coetáneos\",\n\"coherente\",\n\"cohibir\",\n\"cólico\",\n\"colon\",\n\"combatiente\",\n\"comensal\",\n\"comité\",\n\"compaginar\",\n\"compensación\",\n\"compungido\",\n\"cóncavo\",\n\"concebir\",\n\"concienzudamente\",\n\"confabularse\",\n\"congénito\",\n\"contorsionista\",\n\"convicción\",\n\"cónyuges\",\n\"cotización\",\n\"crédulo\",\n\"curvilíneo\",\n\"dádiva\",\n\"decisivo\",\n\"delinquir\",\n\"desaliñado\",\n\"desamparado\",\n\"descarrilar\",\n\"desembolso\",\n\"dicción\",\n\"diéresis\",\n\"diestro\",\n\"dilapidar\",\n\"dócil\",\n\"dramático\",\n\"dúo\",\n\"ébano\",\n\"echado\",\n\"egolatría\",\n\"ejercer\",\n\"elixir\",\n\"embadurnar\",\n\"embelesado\",\n\"embrollo\",\n\"embustero\",\n\"emisario\",\n\"empanada\",\n\"enarbolar\",\n\"encarecimiento\",\n\"enclenque\",\n\"encorajinarse\",\n\"enhebrar\",\n\"entereza\",\n\"entremés\",\n\"entumecerse\",\n\"epístola\",\n\"equívoco\",\n\"ermita\",\n\"errado\",\n\"escarabajo\",\n\"escoba\",\n\"escuálido\",\n\"espeluznante\",\n\"estirpe\",\n\"estorbo\",\n\"estupefaciente\",\n\"evasiva\",\n\"exánime\",\n\"exasperar\",\n\"excelso\",\n\"exento\",\n\"exhortación\",\n\"éxitos\",\n\"expirar\",\n\"extradición\",\n\"factible\",\n\"falaz\",\n\"farándula\",\n\"fascículo\",\n\"férreo\",\n\"festejo\",\n\"fidedigno\",\n\"fiereza\",\n\"fiscal\",\n\"fláccido\",\n\"fluye\",\n\"forcejear\",\n\"forraje\",\n\"forzadamente\",\n\"fracción\",\n\"frivolidad\",\n\"fruncir\",\n\"fútbol\",\n\"gabacha\",\n\"gangrena\",\n\"garrotear\",\n\"geriatra\",\n\"germicida\",\n\"giratorio\",\n\"glasear\",\n\"globalizar\",\n\"gobernador\",\n\"góndola\",\n\"gozoso\",\n\"grabación\",\n\"gragea\",\n\"grandísimo\",\n\"gravedad\",\n\"guanábana\",\n\"guarnición\",\n\"güero\",\n\"guisante\",\n\"guitarra\",\n\"habichuela\",\n\"habilitado\",\n\"hacinar\",\n\"hastiar\",\n\"hazmerreír\",\n\"hebreo\",\n\"hectárea\",\n\"helio\",\n\"hemofilia\",\n\"hendidura\",\n\"héroe\",\n\"herrero\",\n\"hervor\",\n\"hidalgo\",\n\"hidrología\",\n\"higo\",\n\"histérico\",\n\"hojear\",\n\"hospicio\",\n\"hostigar\",\n\"hoyo\",\n\"humareda\",\n\"húngaro\",\n\"husmear\",\n\"idilio\",\n\"ilícito\",\n\"impedir\",\n\"improviso\",\n\"inciso\",\n\"increpar\",\n\"índole\",\n\"injerto\",\n\"intemperie\",\n\"iracundo\",\n\"irrisorio\",\n\"jaboncillo\",\n\"japonés\",\n\"jazmín\",\n\"jején\",\n\"joroba\",\n\"jovialidad\",\n\"judaísmo\",\n\"jurisprudencia\",\n\"juzgar\",\n\"kilómetro\",\n\"kiosco\",\n\"labia\",\n\"lanzada\",\n\"lapicero\",\n\"lavadero\",\n\"laxo\",\n\"legislativo\",\n\"lengüetazo\",\n\"levantamiento\",\n\"ley\",\n\"lícito\",\n\"lija\",\n\"limpiabotas\",\n\"lingüista\",\n\"llavín\",\n\"llenura\",\n\"lluvioso\",\n\"loable\",\n\"lóbrego\",\n\"lozanía\",\n\"lucero\",\n\"lunático\",\n\"madrinazgo\",\n\"magnánimo\",\n\"maizales\",\n\"majestuosidad\",\n\"malhechor\",\n\"malversación\",\n\"mandíbula\",\n\"mecedor\",\n\"megáfono\",\n\"mezquino\",\n\"minucioso\",\n\"misérrimo\",\n\"mixto\",\n\"monótono\",\n\"muchachada\",\n\"mujeriego\",\n\"muñequera\",\n\"nácar\",\n\"navaja\",\n\"negligencia\",\n\"neologismo\",\n\"nexo\",\n\"níveo\",\n\"nostalgia\",\n\"nudillo\",\n\"nupcias\",\n\"objeción\",\n\"oblicuo\",\n\"oboe\",\n\"obstinado\",\n\"ocio\",\n\"octogenario\",\n\"oligarca\",\n\"onza\",\n\"opresivo\",\n\"oquedad\",\n\"orfandad\",\n\"origen\",\n\"ornamento\",\n\"pálido\",\n\"pantorrilla\",\n\"papagayo\",\n\"paracaídas\",\n\"patilla\",\n\"payasada\",\n\"pedazo\",\n\"pedrería\",\n\"perfidia\",\n\"permisiva\",\n\"picaresco\",\n\"piromanía\",\n\"plasticidad\",\n\"pleitesía\",\n\"plumífero\",\n\"podología\",\n\"podredumbre\",\n\"ponzoña\",\n\"portavoz\",\n\"precario\",\n\"profecía\",\n\"prórroga\",\n\"pureza\",\n\"quehacer\",\n\"quemadura\",\n\"querubín\",\n\"quinquenio\",\n\"quintillizos\",\n\"quirúrgico\",\n\"racial\",\n\"radiografía\",\n\"rallador\",\n\"reajuste\",\n\"rebasar\",\n\"reduzca\",\n\"referéndum\",\n\"refrigerio\",\n\"rencilla\",\n\"resurgir\",\n\"revertir\",\n\"revolver\",\n\"ribera\",\n\"rompeolas\",\n\"rubor\",\n\"rugido\",\n\"acerdotisa\",\n\"ahumerio\",\n\"anción\",\n\"azón\",\n\"egador\",\n\"emáforo\",\n\"eptuagésima\",\n\"ervidumbre\",\n\"ien\",\n\"ilabear\",\n\"ilbido\",\n\"imulación\",\n\"infonía\",\n\"obornar\",\n\"obresdrújula\",\n\"omnolencia\",\n\"osiego\",\n\"ubyugar\",\n\"ugerencia\",\n\"usurrar\",\n\"tácito\",\n\"tajada\",\n\"tarántula\",\n\"taxímetro\",\n\"tejedor\",\n\"tempestad\",\n\"tersura\",\n\"titánico\",\n\"titubear\",\n\"tómbola\",\n\"tornavoz\",\n\"tozudo\",\n\"traba\",\n\"triza\",\n\"tromba\",\n\"tubérculo\",\n\"turbulento\",\n\"turrón\",\n\"ultratumba\",\n\"ungüento\",\n\"urgente\",\n\"urgir\",\n\"utilización\",\n\"utopía\",\n\"vagabundo\",\n\"vahído\",\n\"valentía\",\n\"vasija\",\n\"vástago\",\n\"vate\",\n\"vergel\",\n\"versículo\",\n\"vicisitudes\",\n\"vigilia\",\n\"víspera\",\n\"víveres\",\n\"vocablo\",\n\"voluble\",\n\"vos\",\n\"vulgaridad\"\n]\n\n\n\ncantidad= (len(palabras))\nprint (cantidad)\nwhile True:\n for x in range(0, cantidad):\n print(palabras[x])\n pyautogui.moveTo(762,408, duration = 2)\n pyautogui.click()\n pyautogui.click()\n pyautogui.click()\n pyautogui.typewrite(palabras[x])\n pyautogui.moveTo(971,415, duration = 2)\n pyautogui.click()\n time.sleep(10)\n pyautogui.moveTo(17,78, duration = 2)\n pyautogui.click()\n\n\n\n" }, { "alpha_fraction": 0.5897436141967773, "alphanum_fraction": 0.6043051481246948, "avg_line_length": 38.5, "blob_id": "1f03c7ef11c29c57ecf9a415a9fb95f8630ecf67", "content_id": "73709be66fe7d1ed21a0b4c83fb0dccf37df8107", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3159, "license_type": "no_license", "max_line_length": 125, "num_lines": 78, "path": "/Scrap5win.py", "repo_name": "LuisGabrielLiscanoLovera/ScraPreseach", "src_encoding": "UTF-8", "text": "import time as t\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\n#from selenium.webdriver.firefox.firefox_binary import FirefoxBinary\r\npalabras=[\r\n\"abad\"]\r\nimport sqlite3\r\nconn = sqlite3.connect('seccion.db')\r\nc = conn.cursor()\r\n#leer bien----\t\r\n\"\"\"c.execute('''DROP TABLE acceso''')\r\n\r\n#c.execute('''CREATE TABLE acceso\r\n (id integer auto_increment primary key, email text, password text)''')\r\n#Insert a row of data\r\nc.execute(\"INSERT INTO acceso VALUES (1,'luisthemaster3@gmail.com','H1cc$43*')\")\r\nconn.commit()\r\n#Save (commit) the changes\r\nc.execute(\"INSERT INTO acceso VALUES (2,'ccidbcomputacion12@gmail.com','H1cc$43*')\")\r\nconn.commit()\r\n# We can also close the connection if we are done with it.\r\n# Just be sure any changes have been committed or they will be lost.\r\n#c.execute(\"SELECT * FROM acceso\")\r\n#print (c.fetchone))\r\n\"\"\"\r\n#for row in c.execute('SELECT * FROM acceso'):print ({row[0]:{'users':row[1],'password':row[2]}})\r\nseccion=dict()\r\nfor row in c.execute('SELECT * FROM acceso'):seccion.update({row[0]:{'users':row[1],'password':row[2]}})\r\n#row[0]=id, row[1]=usuario row[2]=password\r\n#print(seccion)\r\n#print(seccion[1]['users'])\r\n#print(seccion[1]['password'])\r\nconn.close()\r\n #binary = FirefoxBinary('/usr/bin/firefox')\r\n #driver = webdriver.Firefox(firefox_binary=binary)\r\n #abrir navegador\r\ndef main():\r\n driver = webdriver.Chrome()\r\n driver.set_window_position(-3000, 0)\r\n driver.get(\"https://www.presearch.org/login\")\r\n print(\"Thanks for play XD\")\r\n def buscar(): \r\n cantidad= (len(palabras))\r\n for x in range(0, cantidad):\r\n t.sleep(2)\r\n cb = driver.find_element_by_name(\"term\")\r\n cb.send_keys(palabras[x])\r\n t.sleep(2)\r\n bn = driver.find_element_by_css_selector(\"button.rounded\").click()\r\n driver.back()\r\n driver.refresh()\r\n t.sleep(2)\r\n for x in seccion:\r\n username_field = driver.find_element_by_name(\"email\")\r\n password_field = driver.find_element_by_name(\"password\")\r\n login_button = driver.find_element_by_css_selector('button.btn-primary') \r\n username_field.send_keys(seccion[x]['users'])\r\n t.sleep(2)\r\n password_field.send_keys(seccion[x]['password'])\r\n t.sleep(2)\r\n login_button.click()\r\n t.sleep(2)\r\n elem = driver.find_elements_by_class_name(\"tour-balance\") \r\n for inicioBalance in elem:print(\"Inicio \"+\"Usuario:=> \"+seccion[x]['users']+\" Acomulado: {\"+(inicioBalance.text)+\"}\")\r\n buscar()\r\n elemD = driver.find_elements_by_class_name(\"tour-balance\") \r\n for finalBalance in elemD:\r\n print(\"Final \"+\"Usuario:=> \"+seccion[x]['users']+\" Acomulado: {\"+(finalBalance.text)+\"}\")\r\n print(\"Total tokens Faltante\")\r\n str = finalBalance.text\r\n print(1000.00-(int(float(str.replace(\"PRE\", \"\", 3))))) \r\n driver.close()\r\n t.sleep(2)\r\n driver = webdriver.Chrome()\r\n driver.set_window_position(-3000, 0)\r\n driver.get(\"https://www.presearch.org/login\") \r\n driver.close() \r\nmain()\r\n" }, { "alpha_fraction": 0.6412053108215332, "alphanum_fraction": 0.6521840691566467, "avg_line_length": 39.38679122924805, "blob_id": "dfc55c5e9da4d0f8bea38ad6569fdd10ebcc997b", "content_id": "542afd0ec8bf23d3bd70aa8d1a871f1db1c0377c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4281, "license_type": "no_license", "max_line_length": 424, "num_lines": 106, "path": "/scap5v2", "repo_name": "LuisGabrielLiscanoLovera/ScraPreseach", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport time as t\nimport sqlite3\nfrom selenium import webdriver\nfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinary\nfrom selenium.webdriver.firefox.options import Options\nfrom numpy import asarray as np\nfrom random import randint as rd\nfrom json import load as js\n\n#print(rN())\n#print(megaFaker())\n\n\n#from pyvirtualdisplay import DisplayDisplay\nprint(\"*****--------------Thanks for play XD--------------*****\\n\")\nconn = sqlite3.connect('seccion.db')\nc = conn.cursor()\n\"\"\" c.execute('''DROP TABLE acceso''')\nc.execute('''CREATE TABLE acceso (id integer auto_increment primary key, email text, password text)''')\nc.execute(\"INSERT INTO acceso VALUES (1,'luisthemaster3@gmail.com','H1cc$43*')\")\nconn.commit()\nc.execute(\"INSERT INTO acceso VALUES (2,'ccidbcomputacion12@gmail.com','H1cc$43*')\")\nconn.commit()\n \"\"\"\nseccion=dict()\nfor row in c.execute('SELECT * FROM acceso'):\n\tprint(row[1])\n\tseccion.update({row[0]:{'users':row[1],'password':row[2]}})\nconn.close()\n\n#palabras =[\t\"php\",\t\"python\",\t\"larvel\",\t\"crane\",\t\"vue\",\t\"vuetify\",\t\"java\",\t\"devOps\",\t\"jenkins\",\t\"javascript\",\t\"ccs\",\t\"sass\",\t\"software\",\t\"develoment\",\t\"codificacion\",\t\"integracion\",\t\"pruebas Unitarias\",\t\"Despliege\",\t\"fomentar la cultura de programacion agil\",\t\"integracion continua\",\t\"kotlin\",\t\"android\",\t\"red\",\t\"try\",\t\"css\",\t\"sass\",\t\"webpack\",\t\"refactorize\",\t\"replase\",\t\"inner join\",\t\"sql manager\",\t\"capitalize\",\t\"station\"]\n\ndef main():\n\ttry:\n\t\tdef rN():\n\t\t\treturn (rd(150,350)*2+9)\n\t\t\t\n\t\tdef megaFaker():\n\t\t\twith open('1000.json', 'r') as handle:\n\t\t\t\tmilSemillas=js(handle) \t\n\t\t\t\n\t\t\tpalabras = [\"como \",\"cuando \",\"donde queda \",\"como encontrar \",\"que hacer en \",\"obtener \"]\n \t\t\n\t\t\tcategoria = [\"animal\",\"carmodle\",\"moviesTitle\",\"NameOfCompany\",\"Drug\",\"uni\",\"apps\"] \t\t\n\t\t\t\n\t\t\trCategoria = (str(categoria[rd(0,6)]))\n \t\t\n\t\t\trSemilla = (np(milSemillas)[rd(1,100)][rCategoria])\n \t\t\n\t\t\trPalabras = (str(palabras[rd(0,5)]))\n \t\t\n\t\t\treturn(str(rPalabras+rSemilla))\n\t\t\n\t\t#options = Options()#<--------------------Hiden Browser\n\t\t#options.add_argument(\"--headless\")\n\t\t#driver = webdriver.Firefox(options=options,executable_path='/usr/local/bin/geckodriver',firefox_binary='/usr/bin/firefox')\n\t\tdriver = webdriver.Firefox(executable_path='/usr/local/bin/geckodriver',firefox_binary='/usr/bin/firefox')\n\t\tdriver.get(\"https://www.presearch.org/login\");\n\t\t#cantidad = (len(palabras))\n\t\t\n\t\tdef buscar():\n\t\t\tfor x in range(0, 30):\n\t\t\t\telemT = driver.find_elements_by_class_name(\"tour-balance\") \t\t\t\n\t\t\t\tfor inicioBalance in elemT:print(\"-----------------------++:\\n\"+(inicioBalance.text))\n\t\t\t\tcb = driver.find_element_by_name(\"term\")\n\t\t\t\t#cb.send_keys(palabras[x])\n\t\t\t\tcb.send_keys(megaFaker())\n\t\t\t\tt.sleep(2)\n\t\t\t\tbn = driver.find_element_by_css_selector(\"button.rounded\").click()\n\t\t\t\tdriver.back()\n\t\t\t\tdriver.refresh()\n\t\t\t\tt.sleep(2)\n\t\t\n\n\t\tfor x in seccion:\n\t\t\tusername_field = driver.find_element_by_name(\"email\");password_field = driver.find_element_by_name(\"password\")\n\t\t\tlogin_button = driver.find_element_by_css_selector('button.btn-primary')\n\t\t\tusername_field.send_keys(seccion[x]['users'])\n\t\t\tt.sleep(2)\n\t\t\tpassword_field.send_keys(seccion[x]['password'])\n\t\t\tt.sleep(3)\n\t\t\tlogin_button.click()\n\t\t\tt.sleep(3)\n\t\t\telem = driver.find_elements_by_class_name(\"tour-balance\") \n\t\t\t\n\t\t\tfor inicioBalance in elem:print(\"-----------------------\\n\"+str(x)+\")Usuario: [\"+seccion[x]['users']+\"] Acomulado: {\"+(inicioBalance.text)+\"}\")\t\n\t\t\tbuscar()\n\t\t\telemD = driver.find_elements_by_class_name(\"tour-balance\") \n \t\t\t\n\t\t\tfor finalBalance in elemD:\n\t\t\t\tf = finalBalance.text\n\t\t\t\tfinal=1000.00-(float(f.replace(\"PRE\", \"\", 3)))\n\t\t\t\tprint(\"Final obtenido: {\"+(finalBalance.text)+\"}\")\n\t\t\t\tprint(\"Total tokens Faltante: {\"+str(final)+\"}\")\n\t\t\t#driver.close();driver = webdriver.Firefox(options=options,executable_path='/usr/local/bin/geckodriver',firefox_binary='/usr/bin/firefox');driver.get(\"https://www.presearch.org/login\")\n\t\t\tdriver.close();driver = webdriver.Firefox(executable_path='/usr/local/bin/geckodriver',firefox_binary='/usr/bin/firefox');driver.get(\"https://www.presearch.org/login\")\n\n\t\tdriver.close()\n\t\t\n\texcept Exception as e: print(e)\nif __name__ == '__main__':\n\tmain()\n#descaomentar para mostrar el contenido de la paguina \n#html = driver.page_source\n" }, { "alpha_fraction": 0.4071460962295532, "alphanum_fraction": 0.4146563410758972, "avg_line_length": 28.09933853149414, "blob_id": "fb1a3df678a151b8f03703e8c82771e64f21b90b", "content_id": "43bbc94ca2d7d62a52bf02b5e16ad7cbc5e1c27f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4395, "license_type": "no_license", "max_line_length": 88, "num_lines": 151, "path": "/apiJson1000simillas.py", "repo_name": "LuisGabrielLiscanoLovera/ScraPreseach", "src_encoding": "UTF-8", "text": "from random import randint as rd\nfrom json import load as js\ntry: \n from numpy import asarray as np\nexcept Exception as e:\n import subprocess,sys \n print (\"**** instalando lib Numpy ****\")\n subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", \"numpy\" ])\n from numpy import asarray as np\n\ndef megaFaker():\n try: \n with open('1000.json', 'r') as milSemillas:\n milSemillas=js(milSemillas)\n except Exception as e:\n print (str(e)+\"< Archivo no existe!\")\n exit() \n \n categoria =[\n \"animal\",\n \"carmodle\",\n \"moviesTitle\",\n \"NameOfCompany\",\n \"uni\",\n \"apps\"\n ]\n rCategoria = (str(categoria[rd(0,(len(categoria))-1)])) \n #####################Entrenar IA mejor dese txt#############\n if(rCategoria==\"animal\"):\n palabras=[\n \"donde encontar \",\n \"habita \",\n \"comida \",\n \"peloigro de extinción \",\n \"venenoso \",\n \"composicion osea \",\n ] \n elif(rCategoria==\"carmodle\"):\n palabras=[\n \"que es \",\n \"a que sabe \",\n \"donde queda \",\n \"como encontrar \",\n \"ver \"] \n elif(rCategoria==\"moviesTitle\"):\n palabras=[\n \"fecha de lanzamiento de \",\n \"reparto en \",\n \"secuelas de \",\n \"resumen \",\n \"protagonista en \",\n \"elenco de \",\n \"descargar de \",\n \"animacion de \",\n \"calidad de \" ,\n \"cinematic de \",\n \"musica de \" ,\n \"esenario en \", \n \"Historia en\" ,\n \"catetgoria de la \" ,\n \"errores de la \" ,\n \"trama de\" ,\n \"arte de \" ,\n \"libro de \" ,\n \"escritor de \" ,\n \"gion de \" ,\n \"etapas de \",\n ] \n elif(rCategoria==\"NameOfCompany\"):\n palabras=[\n \"fecha de creacion \",\n \"competencia de la \",\n \"estrategia de la \",\n \"vision de la \",\n \"mision de la \",\n \"capacidad de trabajadores \",\n \"beneficios de la \",\n ] \n elif(rCategoria==\"uni\"):\n palabras=[\n \"requisitos para entara en \",\n \"carrera \",\n \"donde queda la \",\n \"como encontrar la \",\n \"que hacer en la \",\n \"obtener beca en la \"\n ] \n if(rCategoria==\"apps\"):\n palabras=[\n \"Version \",\n \"git \",\n \"licencia \",\n \"como encontrar \",\n \"que hacer en la \",\n \"animacion \",\n \"keys \",\n \"free \",\n \"gratis \",\n \"obtener \",\n \"descargar \"\n ] \n \n rSemilla = np(milSemillas)[rd(0,999)][rCategoria]\n rPalabras = str(palabras[rd(0,(len(palabras))-1)]) \n \n \n \n #################### Documentacion #######################\n global rn \n doc=\"\"\"\n --------------------Thankas for play!-----------\n \n Al azar python3\n Tiempo segunso = [{}] \n Tiempo minutos = [{}]\n Tema = [{}]\n Categoria = [{}] \n Accion a concatenar = [{}] \n cantidad de palabras = [{}]\n ------------------------------------------------\n \"\"\".format(rn(),(str(rn()/60)),rCategoria,rSemilla,rPalabras,(len(milSemillas))) \n print (doc)\n ########################################################## \n palaGenerada=str(rPalabras+rSemilla)\n \n #lis.append(palaGenerada)\n return(str(rPalabras+rSemilla))\n\n#tiempo\nrn=lambda:int(rd(50,350)*2+9)+(rd(0,100)/3+100)\nprint(megaFaker())\n\n#### para evitar palabra repetidas\ndef verif():\n global A\n return str(A+1)\n # lis=[]\n # lis.append(\"megaFaker()\")\n # lis.append(\"megaFaker()\")\n # print(lis)\n # def all_indices(value, qlist):\n # indices = []\n # idx = -1\n # while True:\n # try:\n # idx = qlist.index(value, idx+1)\n # indices.append(idx)\n # except ValueError:\n # break\n # return indices\n # print(all_indices(\"megaFaker()\", lis))\n" }, { "alpha_fraction": 0.6237194538116455, "alphanum_fraction": 0.6335697174072266, "avg_line_length": 35.25714111328125, "blob_id": "ebfe519ca27b2437781074a4e8b5718f26372743", "content_id": "481467d540811c309d9f17d12cf29b639a782dfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2538, "license_type": "no_license", "max_line_length": 104, "num_lines": 70, "path": "/scrapeWin.py", "repo_name": "LuisGabrielLiscanoLovera/ScraPreseach", "src_encoding": "UTF-8", "text": "import time as t\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n#from selenium.webdriver.firefox.firefox_binary import FirefoxBinary\nemail = \"luisthemaster3@gmail.com\"\npassword = \"H1cc$43*\"\npalabras=[\n\"abad\"]\nimport sqlite3\nconn = sqlite3.connect('seccion.db')\nc = conn.cursor()\n#leer bien----\t\n\"\"\"c.execute('''DROP TABLE acceso''')\n\n#c.execute('''CREATE TABLE acceso\n (id integer auto_increment primary key, email text, password text)''')\n#Insert a row of data\nc.execute(\"INSERT INTO acceso VALUES (1,'luisthemaster3@gmail.com','H1cc$43*')\")\nconn.commit()\n#Save (commit) the changes\nc.execute(\"INSERT INTO acceso VALUES (2,'ccidbcomputacion12@gmail.com','H1cc$43*')\")\nconn.commit()\n# We can also close the connection if we are done with it.\n# Just be sure any changes have been committed or they will be lost.\n#c.execute(\"SELECT * FROM acceso\")\n#print (c.fetchone))\n\"\"\"\nseccion=dict()\nfor row in c.execute('SELECT * FROM acceso'):seccion.update({row[0]:{'users':row[1],'password':row[2]}})\n#row[0]=id, row[1]=usuario row[2]=password\n#print(seccion)\n#print(seccion[1]['users'])\n#print(seccion[1]['password'])\nconn.close()\n #binary = FirefoxBinary('/usr/bin/firefox')\n #driver = webdriver.Firefox(firefox_binary=binary)\n #abrir navegador\ndef main():\n driver = webdriver.Chrome()\n driver.get(\"https://www.presearch.org/login\")\n print(\"iniciandoooooooooooo\")\n def buscar():\n cantidad= (len(palabras))\n for x in range(0, cantidad):\n t.sleep(2)\n cb = driver.find_element_by_name(\"term\")\n cb.send_keys(palabras[x])\n t.sleep(2)\n bn = driver.find_element_by_css_selector(\"button.rounded\").click()\n driver.back()\n driver.refresh()\n t.sleep(2) \n for x in seccion:\n username_field = driver.find_element_by_name(\"email\")\n password_field = driver.find_element_by_name(\"password\")\n login_button = driver.find_element_by_css_selector('button.btn-primary') \n #print(seccion[x]['users'],(seccion[x]['password']))\n elem = driver.find_elements_by_class_name(\"tour-balance\") \n for banlance in elem:print (seccion[x]['users']+banlance.text)\n username_field.send_keys(seccion[x]['users'])\n t.sleep(2)\n password_field.send_keys(seccion[x]['password'])\n t.sleep(2)\n login_button.click()\n buscar()\n driver.close()\n t.sleep(2)\n driver = webdriver.Chrome()\n driver.get(\"https://www.presearch.org/login\") \nmain()\n" }, { "alpha_fraction": 0.6177818775177002, "alphanum_fraction": 0.6471127271652222, "avg_line_length": 53.54999923706055, "blob_id": "cee0d749fe89913c235465ac2cd4a959f57758a5", "content_id": "e228ba1ccd23cdfb4281a661d7a6794d9279652f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2182, "license_type": "no_license", "max_line_length": 134, "num_lines": 40, "path": "/apyConsumers.py", "repo_name": "LuisGabrielLiscanoLovera/ScraPreseach", "src_encoding": "UTF-8", "text": "from numpy import asarray as np;from random import randint as rd;from json import load as js\ndef rN():return (rd(150,350)*2+9)\ndef megaFaker():\n with open('1000.json', 'r') as handle:\n milSemillas=js(handle)\n palabras=[\"como \",\"cuando \",\"donde queda \",\"como encontrar \",\"que hacer en \",\"obtener \"]\n categoria=[\"animal\",\"carmodle\",\"moviesTitle\",\"NameOfCompany\",\"Drug\",\"uni\",\"apps\"]\n rCategoria = (str(categoria[rd(0,6)]))\n rSemilla = (np(milSemillas)[rd(1,100)][rCategoria])\n rPalabras = (str(palabras[rd(0,5)]))\n return(str(rPalabras+rSemilla))\nprint(rN())\nprint(megaFaker())\n\"\"\"import json,urllib.request\nlibrosApi=\"http://api.nytimes.com/svc/books/v2/lists/overview.json?published_date=2013-01-01&api-key=76363c9e70bc401bac1e6ad88b13bd1d\"\nErgastApi=\"http://ergast.com/api/f1/2004/1/results.json\"\ndata = urllib.request.urlopen(librosApi).read()\noutput = json.loads(data)\ndataG = urllib.request.urlopen(ErgastApi).read()\nErgastJson = json.loads(dataG)\npalabrasR=[\"como\",\"cuando\",\"donde\",\"hacer\"]\nbooks=[]\nErgast=[]\nfor i in range(len(output)):\n for x in range(21):\n books.append(output['results']['lists'][x]['books'][i]['title'])\n books.append(output['results']['lists'][x]['books'][i]['description'])\n books.append(output['results']['lists'][x]['books'][i]['sunday_review_link'])\n books.append(output['results']['lists'][x]['books'][i]['buy_links'][0]['name'])\n books.append(output['results']['lists'][x]['books'][i]['buy_links'][0]['url']) \nfor i in range(len(ErgastJson)):\n for z in range(19): \n Ergast.append(\"nombre => \" + ErgastJson['MRData']['RaceTable']['Races'][0]['Results'][z]['Driver']['givenName'])\n Ergast.append(\"apellido => \" + ErgastJson['MRData']['RaceTable']['Races'][0]['Results'][z]['Driver']['familyName'])\n Ergast.append(\"fe_nacimiento => \"+ ErgastJson['MRData']['RaceTable']['Races'][0]['Results'][z]['Driver']['dateOfBirth'])\nlibros=json.dumps(books, indent=4, sort_keys=True)\npilotosRacer=json.dumps(Ergast, indent=4, sort_keys=True)\nprint(libros,pilotosRacer,palabrasR)\n#print(libros, end='', flush=True)\n\"\"\"\n" }, { "alpha_fraction": 0.560491681098938, "alphanum_fraction": 0.5713784098625183, "avg_line_length": 30.291208267211914, "blob_id": "3b1601d3cdd8ab45c8db35e2f539aefb1519bea1", "content_id": "1ab263da05af6b0329fa03ec7c096626cb276a50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5696, "license_type": "no_license", "max_line_length": 186, "num_lines": 182, "path": "/scra5.py", "repo_name": "LuisGabrielLiscanoLovera/ScraPreseach", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport time as t\nimport sqlite3\nfrom selenium import webdriver\nfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinary\nfrom selenium.webdriver.firefox.options import Options\nfrom numpy import asarray as np\nfrom random import randint as rd\nfrom json import load as js\n\n\nprint(\"*****--------------Thanks for play XD--------------*****\\n\")\nconn = sqlite3.connect('seccion.db')\nc = conn.cursor()\n\n\n##############################################Se cargan los usuarios #####################################\n#c.execute('''DROP TABLE acceso''')\n#c.execute('''CREATE TABLE acceso (id integer auto_increment primary key, email text, password text)''')\n#c.execute(\"INSERT INTO acceso VALUES (1,'lgnome35@gmail.com','H1cc$43*')\")\n#conn.commit()\n#c.execute(\"INSERT INTO acceso VALUES (2,'ccidbcomputacion12@gmail.com','H1cc$43*')\")\n#conn.commit()\n##########################################################################################################\n\nseccion=dict()\nfor row in c.execute('SELECT * FROM acceso'):\n\t#print(row[1])>Usuario\n\t#print(row[2])>Password\n\tseccion.update({row[0]:{'users':row[1],'password':row[2]}})\nconn.close()\n\n\ndef main():\n\t###############tiempo random!##################\n\tTR=lambda:int(rd(50,350)*2+9)+(rd(0,100)/3+100)\n\t###############################################\n\ttry:\n\t\t\n\t\tdef megaFaker():\t\t\t\n\t\t\twith open('1000.json', 'r') as milSemillas:\n\t\t\t\tmilSemillas=js(milSemillas)\n\t\t\tcategoria =[\n\t\t\t\t\t\"animal\",\n\t\t\t\t\t\"carmodle\",\n\t\t\t\t\t\"moviesTitle\",\n\t\t\t\t\t\"NameOfCompany\",\n\t\t\t\t\t\"uni\",\n\t\t\t\t\t\"apps\"\n\t\t\t\t\t]\n\t\t\trCategoria = (str(categoria[rd(0,(len(categoria))-1)])) \n\t\t\t#####################Entrenar IA mejor dese txt#############\n\t\t\tif(rCategoria==\"animal\"):\n\t\t\t\tpalabras=[\n\t\t\t\t\t\"donde encontar \",\n\t\t\t\t\t\"habita \",\n\t\t\t\t\t\"comida \",\n\t\t\t\t\t\"peloigro de extinción \",\n\t\t\t\t\t\"venenoso \",\n\t\t\t\t\t\"composicion osea \",\n\t\t\t\t\t] \n\t\t\telif(rCategoria==\"carmodle\"):\n\t\t\t\tpalabras=[\n\t\t\t\t\t\"que es \",\n\t\t\t\t\t\"a que sabe \",\n\t\t\t\t\t\"donde queda \",\n\t\t\t\t\t\"como encontrar \",\n\t\t\t\t\t\"ver \"] \n\t\t\telif(rCategoria==\"moviesTitle\"):\n\t\t\t\tpalabras=[\n\t\t\t\t\t\"fecha de lanzamiento de \",\n\t\t\t\t\t\"reparto en \",\n\t\t\t\t\t\"secuelas de \",\n\t\t\t\t\t\"resumen \",\n\t\t\t\t\t\"protagonista en \",\n\t\t\t\t\t\"elenco de \",\n\t\t\t\t\t\"descargar de \",\n\t\t\t\t\t\"animacion de \",\n\t\t\t\t\t\"calidad de \" ,\n\t\t\t\t\t\"cinematic de \",\n\t\t\t\t\t\"musica de \" ,\n\t\t\t\t\t\"esenario en \", \n\t\t\t\t\t\"Historia en\" ,\n\t\t\t\t\t\"catetgoria de la \" ,\n\t\t\t\t\t\"errores de la \" ,\n\t\t\t\t\t\"trama de\" ,\n\t\t\t\t\t\"arte de \" ,\n\t\t\t\t\t\"libro de \" ,\n\t\t\t\t\t\"escritor de \" ,\n\t\t\t\t\t\"gion de \" ,\n\t\t\t\t\t\"etapas de \",\n\t\t\t\t\t] \n\t\t\telif(rCategoria==\"NameOfCompany\"):\n\t\t\t\tpalabras=[\n\t\t\t\t\t\"fecha de creacion \",\n\t\t\t\t\t\"competencia de la \",\n\t\t\t\t\t\"estrategia de la \",\n\t\t\t\t\t\"vision de la \",\n\t\t\t\t\t\"mision de la \",\n\t\t\t\t\t\"capacidad de trabajadores \",\n\t\t\t\t\t\"beneficios de la \",\n\t\t\t\t\t] \n\t\t\telif(rCategoria==\"uni\"):\n\t\t\t\tpalabras=[\n\t\t\t\t\t\"requisitos para entara en \",\n\t\t\t\t\t\"carrera \",\n\t\t\t\t\t\"donde queda la \",\n\t\t\t\t\t\"como encontrar la \",\n\t\t\t\t\t\"que hacer en la \",\n\t\t\t\t\t\"obtener beca en la \"\n\t\t\t\t\t] \n\t\t\tif(rCategoria==\"apps\"):\n\t\t\t\tpalabras=[\n\t\t\t\t\t\"Version \",\n\t\t\t\t\t\"git \",\n\t\t\t\t\t\"licencia \",\n\t\t\t\t\t\"como encontrar \",\n\t\t\t\t\t\"que hacer en la \",\n\t\t\t\t\t\"animacion \",\n\t\t\t\t\t\"keys \",\n\t\t\t\t\t\"free \",\n\t\t\t\t\t\"gratis \",\n\t\t\t\t\t\"obtener \",\n\t\t\t\t\t\"descargar \"\n\t\t\t\t\t] \n\t\t\t \n\t\t\trSemilla = np(milSemillas)[rd(0,999)][rCategoria]\n\t\t\trPalabras = str(palabras[rd(0,(len(palabras))-1)])\t\t\t\n\t\t\treturn(str(rPalabras+rSemilla))\n\t\t\n\t\toptions = Options()#<--------------------Hiden Browser\n\t\toptions.add_argument(\"--headless\")\n\t\tdriver = webdriver.Firefox(options=options,executable_path='/usr/local/bin/geckodriver',firefox_binary='/usr/bin/firefox')\n\t\t#driver = webdriver.Firefox(executable_path='/usr/local/bin/geckodriver',firefox_binary='/usr/bin/firefox')\n\t\tdriver.get(\"https://www.presearch.org/login\");\n\t\t#cantidad = (len(palabras))\n\t\t\n\t\tdef buscar():\n\t\t\tfor x in range(0, 30):\n\t\t\t\telemT = driver.find_elements_by_class_name(\"tour-balance\") \t\t\t\n\t\t\t\tfor inicioBalance in elemT:print(\"-----------------------++:\\n\"+(inicioBalance.text))\n\t\t\t\tcb = driver.find_element_by_name(\"term\")\n\t\t\t\tcb.send_keys(megaFaker())\n\t\t\t\tt.sleep((TR()/60)/2)\n\t\t\t\tbn = driver.find_element_by_css_selector(\"button.rounded\").click()\n\t\t\t\tt.sleep(TR()/60)\n\t\t\t\tdriver.back()\n\t\t\t\tdriver.refresh()\n\t\t\t\tt.sleep(2)\t\n\n\t\tfor x in seccion:\n\t\t\tusername_field = driver.find_element_by_name(\"email\");password_field = driver.find_element_by_name(\"password\")\n\t\t\tlogin_button = driver.find_element_by_css_selector('button.btn-primary')\n\t\t\tusername_field.send_keys(seccion[x]['users'])\n\t\t\tt.sleep(2)\n\t\t\tpassword_field.send_keys(seccion[x]['password'])\n\t\t\tt.sleep(3)\n\t\t\tlogin_button.click()\n\t\t\tt.sleep(3)\n\t\t\telem = driver.find_elements_by_class_name(\"tour-balance\") \n\t\t\t\n\t\t\tfor inicioBalance in elem:\n\t\t\t\tprint(\"-----------------------\\n\"+str(x)+\")Usuario: [\"+seccion[x]['users']+\"] Acomulado: {\"+(inicioBalance.text)+\"}\")\t\n\t\t\tbuscar()\n\t\t\telemD = driver.find_elements_by_class_name(\"tour-balance\") \n \t\t\t\n\t\t\tfor finalBalance in elemD:\n\t\t\t\tf = finalBalance.text\n\t\t\t\tfinal=1000.00-(float(f.replace(\"PRE\", \"\", 3)))\n\t\t\t\tprint(\"Final obtenido: {\"+(finalBalance.text)+\"}\")\n\t\t\t\tprint(\"Total tokens Faltante: {\"+str(final)+\"}\")\n\t\t\tdriver.close();driver = webdriver.Firefox(options=options,executable_path='/usr/local/bin/geckodriver',firefox_binary='/usr/bin/firefox');driver.get(\"https://www.presearch.org/login\")\n\t\t\t#driver.close();driver = webdriver.Firefox(executable_path='/usr/local/bin/geckodriver',firefox_binary='/usr/bin/firefox');driver.get(\"https://www.presearch.org/login\")\n\n\t\tdriver.close()\n\t\t\n\texcept Exception as e: print(e)\nif __name__ == '__main__':\n\tmain()\n#descaomentar para mostrar el contenido de la paguina \n#html = driver.page_source\n" } ]
7
tdebusschere/RecommendationEngine
https://github.com/tdebusschere/RecommendationEngine
fd5425bbc0e3118b70c3368c1b0158ec044562a1
3387d631414fb97b03275f08c52c769ff9ac9f9a
c6c15ac97fb60c2d31b2b502125b81d42e034c49
refs/heads/master
2022-12-07T05:52:23.147937
2020-09-11T10:17:00
2020-09-11T10:17:00
294,610,827
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6025640964508057, "alphanum_fraction": 0.621082603931427, "avg_line_length": 26.25242805480957, "blob_id": "91603e98ae960b3acac70e716df0c3d463a8a747", "content_id": "9f8d2bb2c4df385278eca39f0a19cefb97d73099", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2808, "license_type": "no_license", "max_line_length": 124, "num_lines": 103, "path": "/RecommendationEngine_R/Additional/Integration.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "library(RODBC)\nlibrary(testthat)\nlibrary(optparse)\n##integration test\nsource('Code/Connect_To_SQL.R')\n\noption_list = list(\n make_option(c(\"-d\", \"--directory\"), type=\"character\", default=\"\", \n help=\"directory\", metavar=\"character\"),\n make_option(c(\"-c\", \"--commit\"), type='character',default=\"\",\n help=\"commit\", metavar=\"character\"),\n make_option(c(\"-b\", \"--branch\"), type='character',default=\"staging\",\n help=\"staging\", metavar=\"character\"))\nopt_parser = OptionParser(option_list=option_list);\nopt = parse_args(opt_parser);\n\n\nfail= function(mess)\n{\n a = (paste0(\"\\\"C:\\\\Program Files\\\\R\\\\R-3.5.1\\\\bin\\\\Rscript.exe\\\" .\\\\Additional\\\\Write_Mail.R --directory \",\n opt$directory,\" --branch \", opt$branch, \" --commit \", opt$commit, \" --message \", mess))\n system(a)\n}\n\n#1: Test database versus production database\ntryCatch({\n conn = getHandle(new('connect_to_productionMSSQL'))\n date = sqlQuery(conn,'select max(date) from datascientist.dbo.intelligentgame')[[1]]\n}, error = function(e){\n fail('fail:DatabaseConnection')\n })\n\ntryCatch({\nproddate = sqlQuery(conn,paste0(\"select * from datascientist.dbo.intelligentgame where date ='\",date,\"' order by GameCode\"))\n}, error = function(e){\n fail('fail:Drawing data')\n })\n\n\n\n#2a: comma's, check if updated\ncommas = rep(0,10)\nfor (k in c(1:10))\n{\n commas[k] = sum( grep(',',proddate[,paste0('Top',k,'Game')]) > 0)/ dim(proddate)[1]\n}\nif (sum(commas) <10)\n{\n fail(\"fail:incompatible\")\n}\n\n#2b: are there any NA's\ntryCatch(\n {\nrawdatatypes = sqlQuery(conn,paste0(\"select count(*) from datascientist.dbo.intelligentgame where date ='\",\n date,\"' and Rawdatatype=0\"))\n}, error =function(e){ rawdatatypes = 0})\n\nkm = rep(0,10)\ngm = rep(0,10)\nfor (k in c(1:10))\n{\n km[k] = unlist(sqlQuery(conn,paste0(\"select count(*) from datascientist.dbo.intelligentgame where date ='\",\n date,\"' and Top\",k,\"Game='NA' \"))[1])\n gm[k] = unlist(sqlQuery(conn,paste0(\"select count(*) from datascientist.dbo.intelligentgame where date ='\",\n date,\"' and Top\",k,\"Game is NULL \"))[1])\n}\nif (( rawdatatypes + sum(km) + sum(gm)) > 0)\n{\n fail(\"fail:updates_top_insert\")\n}\n\n#3: look at summarylog\ntryCatch(\n { \n query = sqlQuery(conn,\"select * from [Datascientist].[dbo].[RunningRecord] where Date = '\",date,\"' \n and Environment = 'production'\")\n\ncompleted = grep('Completed',query[1]$Status)\nif (completed != 1)\n{\n fail(\"fail:incomplete\")\n}\n\n#3.1: compatability, amount of files\ngames = strsplit(query[1]$Status,':')[2]\nif (games != dim(proddate)[1])\n{\n fail('fail:gamecount')\n}\n },\nerror = function(msg){fail(\"No_Log\") }\n)\n\n\n\n#4: diversity\n#4.1: same category\n#todo\n#4.2: same datalabel\n#todo\n#4.3: hot\n#todo\n\n" }, { "alpha_fraction": 0.6955063939094543, "alphanum_fraction": 0.6968477368354797, "avg_line_length": 30.04166603088379, "blob_id": "b430fb91a24996089b8a9af64ac0efe193d9329f", "content_id": "085a98342d37dfc16b2aa88cf0a6f0f7aed5080a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1491, "license_type": "no_license", "max_line_length": 103, "num_lines": 48, "path": "/RecommendationEngine_R/GlobalConfig.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "library(\"optparse\")\nlibrary('logging')\nlibrary('RODBC')\nlibrary('coop')\nrequire('dplyr')\nrequire('Matrix')\nrequire('pryr')\nrequire('testthat')\nrequire('methods') \n\nbasicConfig()\naddHandler(writeToFile, logger=\"highlevel\", file=\".//logging//Time_Tracing\")\naddHandler(writeToFile, logger='debugger', file='.//logging//Debug_Tracing')\n\ntryLoadFile = function(str){\n loginfo(paste0(\"loading \",str),logger='debugger.module')\n tryCatch({source(str)},\n error=function(msg){\n logerror(paste0(\"Couldn't load the \",str, toString(msg),sep=''), logger='debugger.module')\n },\n warning=function(msg){source(str);logwarn(toString(msg),logger='debugger.module')})\n}\n\ntryLoadFile('Code/Log_To_Database.R')\n\noption_list = list(\n make_option(c(\"-p\", \"--production\"), type=\"character\", default=\"TRUE\", \n help=\"production environment\", metavar=\"character\")\n);\nopt_parser = OptionParser(option_list=option_list);\nopt = parse_args(opt_parser);\n\nif (is.null(opt$production)){\n print_help(opt_parser)\n stop(\"At least one argument must be supplied (input file).n\", call.=FALSE)\n} else if (tolower(opt$production) == 'false') {\n opt$production = FALSE\n} else {\n opt$production = TRUE\n}\n\ntryLoadFile('Code/Initializer.R')\ntryLoadFile('Code/Connect_To_SQL.R')\ntryLoadFile(\"Code/Data_Counts_In.R\")\ntryLoadFile('Code/Preprocessing.R')\ntryLoadFile('Code/Distance_Calculator.R')\ntryLoadFile('Code/postprocessing.R')\ntryLoadFile('Code/Write_To_Db_Refactored.R')\n\n" }, { "alpha_fraction": 0.7041860222816467, "alphanum_fraction": 0.7116279006004333, "avg_line_length": 37.39285659790039, "blob_id": "b593df9228f365a6a932e3bb7927d2ed9d61a519", "content_id": "fd8e90a01028e0d022b7b263ffe8a62c0674ab4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1075, "license_type": "no_license", "max_line_length": 113, "num_lines": 28, "path": "/RecommendationEngine_R/Code/Connect_To_SQL.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "\nsetClass('connect_to_MSSQL', representation(dbhandle= 'RODBC'))\nsetClass('connect_to_testMSSQL',contains='connect_to_MSSQL',representation(dbhandle='RODBC'))\nsetClass('connect_to_productionMSSQL',contains='connect_to_MSSQL',representation(dbhandle='RODBC'))\n\n\nsetMethod('initialize','connect_to_testMSSQL',function(.Object, DB='JG\\\\MSSQLSERVER2016', User = 'DS.Tom' )\n{\n Password <- keyring::keyget('JG',username=User)\t\n dbhandle <- odbcDriverConnect(paste('driver={SQL Server};server=',DB,';uid=',User,';pwd=',Password,';',sep=''))\n .Object@dbhandle = dbhandle\n return(.Object) \n}\n)\n\nsetMethod('initialize','connect_to_productionMSSQL', function(.Object, DB='JG\\\\MSSQLSERVER2016', User = 'DS.Tom')\n{\n Password <- keyring::keyget('JG',username=User)\t\n dbhandle <- odbcDriverConnect(paste('driver={SQL Server};server=',DB,';uid=',User,';pwd=',Password,';',sep=''))\n .Object@dbhandle = dbhandle\n return(.Object)\n}\n)\n\n\nsetGeneric('getHandle', function(.Object){return('RODBC')})\nsetMethod('getHandle','connect_to_MSSQL',function(.Object){\n return(.Object@dbhandle)\n})" }, { "alpha_fraction": 0.6242568492889404, "alphanum_fraction": 0.6385255455970764, "avg_line_length": 36.05882263183594, "blob_id": "b85a87b998133b0a1407a7ad6bcb5f91dc45b693", "content_id": "6c5453c6e78ebd991a9bfc11cde46801f3c6b32d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2523, "license_type": "no_license", "max_line_length": 101, "num_lines": 68, "path": "/RecommendationEngine_R/Additional/validation_split_out.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "\n\nsets = assign_to_sets(dmm)\n\nprepare_sparse_matrix = function(valset,recommend4)\n{\n valset = valset[ valset$key %in% games,]\n valset$cat <- as.numeric(as.factor(valset$MemberId))\n gamelookup = unique(recommend4[,c('key','gtd')])\n gamelookup = gamelookup[order(gamelookup$gtd),]\n valset =valset %>% inner_join(gamelookup,by='key')\n return(valset) \n}\n\n###Proposed Games\nvalset = prepare_sparse_matrix(valset,recommend4)\ntset = prepare_sparse_matrix(tset,recommend4)\n\nsparse_valset = sparseMatrix(i=valset$cat,j=valset$gtd,x=valset$count, \n dims = c(max(valset$cat) , max(recommend4$gtd)))\nsparse_tset = sparseMatrix(i=as.integer(tset$cat),j=as.integer(tset$gtd),x=tset$count,\n dims = c(max(tset$cat) , max(recommend4$gtd)))\n\nSelection = c(1:games_to_select)\nfor (k in c(1:games_to_select))\n{\n Selection[k] = length(sort(unique(unlist(result_final[,c(2:(k+1))])))) / length(games)\n}\nplot(Selection)\ntext(Selection,labels=c(1:games_to_select))\n\n\n\n###Sensitivity / Precision:\nco_occurrences = as.matrix(crossprod(sparse_valset))\nranks = t(apply(co_occurrences,2, order, decreasing=TRUE))\nfirst_zero = apply(co_occurrences,2, function(x){ return( min(which(x == 0)))})\nmultimod = function(x,y){return(min(1 + games_to_select,which(x %in% y)))}\nres = mapply( multimod, split(ranks,row(ranks)),first_zero)\nfind_targets = function(x,y){\n returnvector = rep(0,games_to_select);\n if (y> 1){returnvector[c(1:(y-1))] = x[c(1:(y-1))]; returnvector[c(1:(y-1))] = games[returnvector]}\n return(returnvector)\n}\ntargets = t(mapply(find_targets, split(ranks,row(ranks)), res))\n\n\nmap_to_precision_game = function(intargets, predictions)\n{\n return( sum(as.character(unlist(predictions)) %in% intargets) )\n}\n\nmap_to_recall_game = function(targets, predictions)\n{\n return(sum( targets %in% as.character(unlist(predictions ))))\n}\n\nprecision = c(1:games_to_select)\nrecall = c(1:games_to_select)\nfor (k in c(2:games_to_select))\n{\n precision[k] = sum(mapply(map_to_precision_game, \n split(targets[,c(1:(games_to_select ))],row(targets)), \n split(result_final[,c(2:(k+1))], row(result_final))) / \n length(unlist(result_final[,c(2:k+1)])))\n recall[k] = sum(mapply(map_to_recall_game, \n split(targets[,c(1:(games_to_select ))],row(targets)), \n split(result_final[,c(2:(k+1))], row(result_final)))) / \n sum(targets[,c(1:(games_to_select))] > 0)\n}\n\n" }, { "alpha_fraction": 0.582229495048523, "alphanum_fraction": 0.597667932510376, "avg_line_length": 39.68500900268555, "blob_id": "7fe9e9d686595fcab0f95f0895f5b1353a9f8cf9", "content_id": "ed8541cfdee22ded5aea23f6d4d9d1ddf5be307a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21456, "license_type": "no_license", "max_line_length": 151, "num_lines": 527, "path": "/RecommendationEngine_Python/PythonProduction/Process_Function.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport time\nimport logging\nimport scipy.sparse as sparse\n#from scipy.sparse import csr_matrix\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn import metrics\nfrom surprise import SVD, Reader, Dataset\nimport asyncio\nimport nest_asyncio\nnest_asyncio.apply()\nlogging.basicConfig(filename= 'run.log', level = logging.ERROR) #loggin設定\npd.set_option('display.max_columns', None)\n\n'''\nFunction Zone\n'''\n#Normalization Function\ndef min_max_normalize(x):\n min = x.min()\n max = x.max()\n result = np.float64((x- min) / (max- min))\n return result\n\ndef get_data(IP, DailyQueryTable, start, end):\n declare = \"DECLARE @Start_Date DATETIME, @End_Date DATETIME SET @Start_Date = '{}' SET @End_Date = '{}'\".format(start, end)\n sqlquery = \" SELECT [siteid], [gameaccount], [gametypesourceid], Sum([commissionable]) [Commissionable], Count(1) [Dates] \\\n FROM \\\n (SELECT CONVERT(DATE, [dateplayed]) DAY, [gameaccount],\\\n [siteid], [gametypesourceid], Sum([commissionable]) [Commissionable] \\\n FROM {table} (nolock) \\\n WHERE [dateplayed] >= @Start_Date AND [dateplayed] <= @End_Date \\\n GROUP BY CONVERT(DATE, [dateplayed]), [gameaccount], [siteid], [gametypesourceid])Y \\\n GROUP BY [siteid], [gameaccount], [gametypesourceid]\\\n order by [gametypesourceid],[gameaccount],[siteid]\".format(table=DailyQueryTable)\n FullString = declare + sqlquery\n data = IP.ExecQuery(FullString)\n return data\n\ndef Pre_processing(df):\n result = df.copy()\n #Change columns name\n result.columns = ['SiteID', 'Member', 'Game', 'Commissionable', 'Dates']\n \n result['SiteID'] = result['SiteID'].astype('object')\n result['Member'] = result['Member'].astype('object')\n result['Game'] = result['Game'].astype('object')\n result['Commissionable'] = result['Commissionable'].astype('float64')\n result['Dates'] = result['Dates'].astype('int64')\n \n return result\n\n\ndef Pre_processing_train(df):\n result = df.copy()\n \n # Exclude the following freak conditions\n Condition1 = result['Commissionable'] > 0\n Condition2 = result['Dates'] > 0 \n result = result[Condition1 | Condition2]\n\n ## Exclude the just play one game people( Noise and it can't give our model any help) \n group = result.groupby('Member', as_index=False).agg({'Game': ['count']})\n group.columns = ['Member', 'count']\n group = group[group['count'] != 1]\n group = group.reset_index(drop=True)\n result = result[result.Member.isin(group.Member)]\n result = result.reset_index(drop=True)\n result['Membercode'] = list(zip(result['SiteID'], result['Member']))\n\n \n return result\n\n#Define the hot game for the newuser or the user not in train data\ndef Hot_Game(df, feature='Commissionable', n=15):\n if feature == 'Commissionable':\n FindHotGame = df.groupby('Game', as_index=False).agg({'Commissionable': ['sum']})\n FindHotGame.columns = ['Game', 'feature']\n\n elif feature == 'Member':\n FindHotGame = df.groupby('Game', as_index=False).agg({'Member': ['count']})\n FindHotGame.columns = ['game_id', 'feature']\n '''\n else:\n print('Not Defined')\n FindHotGame = pd.DataFrame(columns=['game_id', 'feature'])\n '''\n FindHotGame = FindHotGame.sort_values(by = ['feature'], ascending = False).reset_index(drop = True)\n HotGame = list(FindHotGame.Game[0:n])\n return HotGame\n\ndef Encoding_RS(users, games):\n \n userid2idx = {o:i for i,o in enumerate(users)}\n gameid2idx = {o:i for i,o in enumerate(games)}\n userid2Rraw = {i:o for i,o in enumerate(users)}\n gameid2iraw = {i:o for i,o in enumerate(games)}\n\n return (userid2idx, userid2Rraw, gameid2idx, gameid2iraw)\n\n\ndef Encoding_TrainData(train_data, userid2idx, gameid2idx):\n \n tmp = train_data.copy()\n tmp.loc[:, 'Member_encoding'] = tmp['Membercode'].apply(lambda x: userid2idx[x])\n tmp.loc[:, 'Game_encoding'] = tmp['Game'].apply(lambda x: gameid2idx[x])\n\n return tmp\n\n\ndef get_Trainset(df):\n \n Trainset = df[['Member_encoding', 'Game_encoding', 'Dates', 'Commissionable']].copy()\n Trainset = Trainset.sort_values(by=['Member_encoding', 'Game_encoding'], ascending=True).reset_index(drop=True)\n \n zmm1 = min_max_normalize(Trainset[['Commissionable']])\n zmm2 = min_max_normalize(Trainset[['Dates']])\n zmm = 0.5 * zmm1 + 0.5 * zmm2\n Trainset.loc[:, 'score'] = zmm\n \n return Trainset\n\n\n'''\nModel - Cosine Similarity\n'''\ndef get_sparse(Trainset):\n \n #model of the cosine similarity\n members = list(Trainset.Member_encoding.unique()) # Get our unique members\n games = list(Trainset.Game_encoding.unique()) # Get our unique games that were purchased\n score_list = list(Trainset.score) # All of our score\n # Get the associated row, column indices\n cols = Trainset.Member_encoding.astype('category',\n categories = members).cat.codes\n rows = Trainset.Game_encoding.astype('category',\n categories = games).cat.codes\n sparse_df = sparse.csr_matrix((score_list, (rows, cols)),\n shape=(len(games), len(members)))\n\n return sparse_df\n\n\n# what does the 30 come from? 95% percentile\ndef Recommendation_cosine(Trainset, sparse_df, games, N = 30):\n cosine_sim = cosine_similarity(sparse_df, sparse_df)\n cosine_sim = pd.DataFrame(data = cosine_sim, index=games, columns=games)\n ## get the neighbor 30 game of every user\n gamelist = np.array(cosine_sim.columns)\n gamesplayed = Trainset.groupby(['Member_encoding'])['Game_encoding'].apply(list).reset_index(name='games')\n gamesmax = np.array(gamesplayed.games.map(lambda x: ((cosine_sim.loc[x,:].values).max(axis=0))))\n def Get_neighbor_30(x):\n # x[x>0.99] = 0.0\n return (gamelist[np.flip(np.argsort(x, axis=0))[0:N, ]])\n filtered = list(map(Get_neighbor_30, gamesmax))\n filtered_array = np.array(filtered)\n filtered_array = filtered_array.reshape(filtered_array.shape[0] * filtered_array.shape[1], -1)\n filtered_array = filtered_array.reshape(-1,)\n Neighbor_result = pd.DataFrame({'Member_encoding': np.repeat(np.array(np.unique(Trainset.Member_encoding)), N, axis=0),\n 'Game_encoding': filtered_array})\n\n Neighbor_only_result = Neighbor_result.merge(Trainset[['Member_encoding', 'Game_encoding', 'score']],\n how = 'left',\n on = ['Member_encoding', 'Game_encoding'])\n Neighbor_only_result.score = np.where(Neighbor_only_result.score.isna(), 0, Neighbor_only_result.score)\n #sorted by the normalized expect return in training data\n Neighbor_only_result = Neighbor_only_result.sort_values(by = ['Member_encoding', 'score'], ascending = False)\n Neighbor_only_result = Neighbor_only_result.groupby('Member_encoding').head(12)\n \n return Neighbor_only_result, Neighbor_result\n\n'''\nModel\n'''\ndef Calculate_Similarity(Trainset): #, N = 30):\n reader = Reader()\n Trainset_changetype = Dataset.load_from_df(Trainset[['Member_encoding', 'Game_encoding', 'score']], reader)\n\n Trainset_changetype_result = Trainset_changetype.build_full_trainset()\n svd = SVD(n_factors = 20,\n n_epochs = 20,\n lr_all = 0.01,#0.0001,\n random_state = 1234)\n svd.fit(Trainset_changetype_result)\n\n games = list(Trainset.Game_encoding.unique()) # Get our unique games that were purchased\n \n\n #s = time.time()\n chunk = 300\n\n tmp2 = np.zeros([len(games), len(games)]) \n norms = dict()\n cut0 = np.zeros((np.shape(svd.pu)[0],chunk))\n cut1 = np.zeros((np.shape(svd.pu)[0],chunk))\n\n \n for k in range(0, np.shape(tmp2)[0]// chunk +1):\n minxindex = k * chunk\n maxxindex = ((k+1) * chunk)\n \n if k == np.shape(tmp2)[0]// chunk :\n maxxindex = np.shape(tmp2)[1] + 1\n cut0 = np.zeros((np.shape(svd.pu)[0],(maxxindex-minxindex - 1)))\n\n np.dot(svd.pu, np.transpose(svd.qi[minxindex:maxxindex,:]),out=cut0)\n norms[str(minxindex)] = np.linalg.norm(cut0, axis = 0)\n\n\n for l in range(0,k+1):\n #s = time.time() \n minyindex = l * chunk \n maxyindex = ((l+1) * chunk) #- 1\n if l == np.shape(tmp2)[0]// chunk:\n maxyindex = np.shape(tmp2)[1] + 1\n if (minxindex == minyindex) & (maxxindex == maxyindex):\n cut1 = np.copy(cut0)\n else: \n np.dot(svd.pu, np.transpose(svd.qi[minyindex:maxyindex,:]), out= cut1)\n \n if( str(minyindex) not in norms):\n norms[str(minyindex)] = np.linalg.norm(cut1,axis=0)\n #tmp3[minxindex:maxxindex,minyindex:maxyindex] = cosine_similarity(np.transpose(cut0), np.transpose(cut1))\n \n tmp2[minxindex:maxxindex,minyindex:maxyindex] = np.dot(np.transpose(cut0), cut1) / \\\n np.outer(norms[str(minxindex)] , norms[str(minyindex)])\n tmp2[minyindex:maxyindex,minxindex:maxxindex] = np.transpose(tmp2[minxindex:maxxindex,minyindex:maxyindex] )\n \n #e = time.time()\n print(str((k, l)) + '_end')\n #print(e- s) \n \n #model SVD_New\n cosine_sim_x = pd.DataFrame(data = tmp2, \n index = games,\n columns = games)\n \n return cosine_sim_x\n\n\ndef Cosine_Similarity(Trainset):\n \n similarity = Calculate_Similarity(Trainset)\n\n return similarity\n\n\ndef Exclude_Game(BalanceCenter_190, category_exclude, games, gameid2idx):\n #exclude by user\n #will be added in the future\n \n \n #exclude the game that can be connect directly: category ('視訊', '體育', '彩票')\n sqlquery = \"SELECT a.[GameTypeSourceId], \\\n a.[Type], \\\n b.[Category] \\\n FROM [BalanceOutcome].[dbo].[lookuptable] a \\\n LEFT JOIN (SELECT [RawDataType] type, \\\n [Category] \\\n FROM [DataPool].[dbo].[dbo.vw_gamelookup] \\\n GROUP BY [RawDataType], \\\n [Category]) b \\\n ON a.type = b.type\"\n data_category = BalanceCenter_190.ExecQuery( sqlquery )\n data_category.columns = ['GameTypeSourceId', 'Type', 'Category']\n connect_indirectly = data_category[(data_category.Category.isin(category_exclude)) & \\\n (~data_category.Category.isna()) &\\\n (~data_category.GameTypeSourceId.isna())]\n \n connect_indirectly['GameTypeSourceId'] = connect_indirectly['GameTypeSourceId'].astype('int64')\n connect_indirectly = connect_indirectly[connect_indirectly.GameTypeSourceId.isin(games)].reset_index(drop=True)\n connect_indirectly.loc[:, 'Game_encoding'] = connect_indirectly['GameTypeSourceId'].apply(lambda x: gameid2idx[x]) \n #connect_indirectly = list(np.int64(connect_indirectly)) \n exclude_game_list_raw = list(connect_indirectly.GameTypeSourceId)\n exclude_list = list(connect_indirectly.Game_encoding)\n \n return (exclude_game_list_raw, exclude_list)\n\n\ndef Summarized_cosine_sim_df(cosine_sim, gameid2iraw, current, connect_indirectly, n = 100):\n \n df = cosine_sim.copy()\n df.loc[:, 'Game'] = df.index\n cosine_sim2 = pd.melt(df, \n id_vars=['Game'],\n var_name='CorrespondGame', \n value_name='CS')\n cosine_sim2['CorrespondGame'] = cosine_sim2['CorrespondGame'].astype('int64')\n\n cosine_sim2 = cosine_sim2[cosine_sim2.Game != cosine_sim2.CorrespondGame]\n cosine_sim2 = cosine_sim2.reset_index(drop=True)\n\n cosine_sim3 = cosine_sim2.copy() \n cosine_sim3.loc[:, 'Game_raw'] = cosine_sim3['Game'].apply(lambda x: gameid2iraw[x])\n cosine_sim3.loc[:, 'CorrespondGame_raw'] = cosine_sim3['CorrespondGame'].apply(lambda x: gameid2iraw[x])\n cosine_sim3 = cosine_sim3[~cosine_sim3.CorrespondGame_raw.isin(connect_indirectly)].reset_index(drop=True) \n\n cosine_sim3 = cosine_sim3.sort_values(by = ['Game_raw', 'CS'],\n ascending = [True, False])\n cosine_sim3 = cosine_sim3.reset_index(drop=True) \n cosine_sim3 = cosine_sim3.groupby('Game_raw').head(n).reset_index(drop=True)\n\n cosine_sim_final = cosine_sim3[['Game_raw', 'CorrespondGame_raw', 'CS']]\n \n cosine_sim_final.loc[:, 'UpdateTime'] = current\n cosine_sim_final.columns = ['Game', 'CorrespondGame', 'CosineSimilarity', 'UpdateTime']\n \n return cosine_sim_final\n\n'''\ndef SVD_surprise_only_tom(Trainset, N = 30, top = 12):\n similarity = Calculate_Similarity(Trainset)\n xmm = asyncio.get_event_loop()\n data = xmm.run_until_complete( find_top_K(Trainset, similarity, N, step=1000))\n return (similarity, data)\n \ndef Get_svd_neighbor(Trainset, similarity, N = 30, top = 12):\n \n xmm = asyncio.get_event_loop()\n data = xmm.run_until_complete( find_top_K(Trainset, similarity, N, step=1000) )\n \n return (data)\n\ndef Original_Similarity(Trainset):\n reader = Reader()\n Trainset_changetype = Dataset.load_from_df(Trainset[['Member_encoding', 'Game_encoding', 'score']], reader)\n Trainset_changetype_result = Trainset_changetype.build_full_trainset()\n svd = SVD(n_factors = 20,\n n_epochs = 20,\n lr_all = 0.01,#0.0001,\n random_state = 1234)\n svd.fit(Trainset_changetype_result)\n\n games = list(Trainset.Game_encoding.unique()) # Get our unique games that were purchased\n data = np.transpose(np.dot(svd.pu, np.transpose(svd.qi)))\n x = cosine_similarity(data, data)\n cosine_sim = pd.DataFrame(data = x, \n index=games,\n columns=games)\n\n return(cosine_sim)\n\n\n\nasync def find_top_K(Trainset, cosine_sim, K = 30, step = 10000):\n start = time.time()\n loop = asyncio.get_event_loop()\n keys, values = Trainset.loc[:,['Member_encoding','Game_encoding']].values.T \n ukeys, index = np.unique(keys,True)\n arrays = np.split(values, index[1:])\n gamesplayed = pd.DataFrame({'a':ukeys,\n 'b':[list(a) for a in arrays]})\n gamesplayed.columns = ['Member_encoding','games']\n print(\"--- %s seconds ---\" % (time.time() - start))\n \n \n #gamesplayed = Trainset.groupby(['Member_encoding'])['Game_encoding'].apply(lambda x: list(x)).reset_index(name='games')\n cosine2 = cosine_sim.to_numpy()\n coskeys = np.array(cosine_sim.index)\n coskey_col = np.array(cosine_sim.columns)\n \n print(\"--- %s seconds ---\" % (time.time() - start))\n lup = dict()\n for key in range(np.shape(cosine2)[0]):\n lup[coskeys[key]]= cosine2[key,:]\n\n totalsize = np.shape(gamesplayed)[0]\n\n batches = totalsize // step\n tasks = []\n \n for k in range(batches):\n l = k + 1\n batch = gamesplayed.iloc[ k*step:l*step,: ]\n tasks.append(loop.create_task(process(batch, lup, k*step, coskeys, coskey_col,step, K)))\n laststep = batches *step\n\n try:\n lastbatch = gamesplayed.iloc[ laststep : (totalsize),:]\n tasks.append(loop.create_task(process(lastbatch,lup,laststep,coskeys, coskey_col,step,K)))\n except:\n pass\n res = await asyncio.gather(*tasks)\n filtered_array = np.vstack(res)\n filtered_array = filtered_array[0:(totalsize),:]\n filtered_array = filtered_array[filtered_array[:,0].argsort()]\n user = filtered_array[:,0]\n filtered_array = filtered_array[:,1:(K+1)]\n filtered_array = filtered_array.reshape( filtered_array.shape[0] * filtered_array.shape[1], -1)\n\n SVD_Neighbor = pd.DataFrame({'Member_encoding': np.repeat(user, K), \n 'Game_encoding': filtered_array[:,0]})\n \n SVD_Neighbor['Member_encoding'] = SVD_Neighbor['Member_encoding'].astype('int64')\n SVD_Neighbor['Game_encoding'] = SVD_Neighbor['Game_encoding'].astype('int64')\n \n return (SVD_Neighbor) \n\n\n \nasync def process(batch, lup, startindex, coskeys, coskey_col, batchsize, K):\n lookup = batch.games.to_numpy()\n indx = 0\n goal = np.zeros((batchsize,K+1))\n for key in lookup: \n #print(key)\n res = [ lup[val] for val in key ]\n #added by jy on 11/18 --start\n position_boolean = np.isin(coskey_col, key)\n position = np.where(position_boolean == True)\n for j in position:\n for b in range(len(res)):\n res[b][j] = 0\n #added by jy on 11/18 --end\n \n results = np.max(res, axis=0).argsort()[::-1][0:K]\n \n goal[indx,1:(K+1)] = coskey_col[results]\n goal[indx,0] = startindex + indx\n indx = indx + 1\n return (goal)\n\n\n\ndef summarized_data_tosql(SVD_Neighbor, userid2Rraw, current):\n SVD_Neighbor_result = SVD_Neighbor.copy()\n\n final_df = pd.DataFrame(np.array(SVD_Neighbor_result.Game_encoding).reshape(SVD_Neighbor_result.Member_encoding.nunique(), 12))\n final_df.columns = ['Game1', 'Game2', 'Game3', 'Game4', 'Game5', 'Game6', 'Game7', 'Game8', 'Game9', 'Game10', 'Game11', 'Game12']\n final_df.loc[:, 'Member_encoding'] = np.unique(SVD_Neighbor_result.Member_encoding)\n final_df.loc[:, 'Member'] = final_df['Member_encoding'].apply(lambda x: userid2Rraw[x])\n final_df = final_df.reset_index(drop=True)\n\n y = pd.DataFrame(list(final_df.Member))\n y.columns = ['SiteId', 'GameAccount']\n final_df.loc[:, 'SiteId'] = y.SiteId\n final_df.loc[:, 'GameAccount'] = y.GameAccount\n \n final_df.loc[:, 'Updatetime'] = current\n final_df_tosql = final_df[['SiteId', 'GameAccount', 'Game1', 'Game2', 'Game3',\\\n 'Game4', 'Game5', 'Game6', 'Game7', 'Game8', 'Game9', 'Game10', \\\n 'Game11', 'Game12', 'Updatetime']]\n final_df_tosql = final_df_tosql.reset_index(drop=True)\n \n return final_df_tosql\n'''\n\n\n'''\nEvaluation metric\n'''\ndef NDCG(input_df, test_df):\n def get_Testset_score(df):\n temp = df.copy()\n temp = temp.sort_values(by=['MemberCode', 'Game'], ascending=True).reset_index(drop=True)\n \n zmm1 = min_max_normalize(temp[['Commissionable']])\n zmm2 = min_max_normalize(temp[['Dates']])\n zmm = 0.5 * zmm1 + 0.5 * zmm2\n temp.loc[:, 'score'] = zmm\n return temp\n\n def DCG(df):\n data = df.copy()\n data['dcg_rank'] = list(range(2, 14)) * int(data.shape[0] / 12)\n data.loc[:, 'dcg'] = (2 ** data['score'] - 1)/ np.log2(data['dcg_rank'])\n \n dcg = data.groupby('MemberCode', as_index=False)['dcg'].sum()\n return dcg\n \n def iDCG(df):\n data = df.copy()\n data = data.sort_values(by=['MemberCode', 'score'], ascending=False)\n data['dcg_rank'] = list(range(2, 14)) * int(data.shape[0] / 12)\n\n data.loc[:, 'idcg'] = (2 ** data['score'] - 1)/ np.log2(data['dcg_rank'])\n idcg = data.groupby('MemberCode', as_index=False)['idcg'].sum()\n return idcg\n \n df = input_df.copy()\n test = get_Testset_score(test_df)\n member_list = np.unique(test.MemberCode)\n df = df[df.MemberCode.isin(member_list)]\n df = df[['MemberCode', 'Game']].merge(test[['MemberCode', 'Game', 'score']],\n how = 'left',\n on = ['MemberCode', 'Game']).fillna(0)\n dcg = DCG(df)\n idcg = iDCG(df)\n ndcg = dcg.merge(idcg, on='MemberCode', how='left')\n ndcg['NDCG'] = ndcg['dcg']/ndcg['idcg']\n ndcg.NDCG = np.where(ndcg.NDCG.isna(), 0, ndcg.NDCG)\n \n NDCG_value = np.mean(ndcg.NDCG)\n \n return NDCG_value\n\ndef Get_AUC_intrain(input_df, test_df):\n #hot game must be a list and there were 12 container.\n test_data = test_df.copy()\n df = input_df.copy()\n member_list = np.unique(test_data.MemberCode)\n df = df[df.MemberCode.isin(member_list)]\n df = df[['MemberCode', 'Game']].merge(test_data[['MemberCode', 'Game', 'Commissionable']],\n how = 'left',\n on = ['MemberCode', 'Game'])\n df.Commissionable = np.where(df.Commissionable.isna(), 0, 1) #play as TP\n df.columns = ['Member', 'Game', 'TP']\n df.loc[:,'FP'] = 1 - df.TP\n\n aggregated = df[['Member', 'TP']].groupby('Member', as_index=False).sum()\n aggregated.loc[:,'FP_n'] = 12 - aggregated.TP\n aggregated.columns = ['Member', 'TP_n', 'FP_n']\n grade0_memberid = aggregated[aggregated.TP_n == 0].Member\n grade1_memberid = aggregated[aggregated.TP_n == 12].Member\n \n \n tmp = df[(~df.Member.isin(grade0_memberid)) & (~df.Member.isin(grade1_memberid))]\n #tmp = df[~df.member_id.isin(grade1_memberid)]\n tmp = tmp.merge(aggregated, how='left', on='Member')\n tmp.loc[:,'TPR'] = tmp.TP / tmp.TP_n\n tmp.loc[:,'FPR'] = tmp.FP / tmp.FP_n\n auc_df = tmp[['Member', 'TPR', 'FPR']].groupby(['Member']).apply(lambda x:metrics.auc(np.cumsum(x.FPR), np.cumsum(x.TPR)))\n \n auc_score = (auc_df.sum()+ 1*len(grade1_memberid))/len(np.unique(df.Member))\n \n return auc_score" }, { "alpha_fraction": 0.7312520146369934, "alphanum_fraction": 0.7553910613059998, "avg_line_length": 46.07575607299805, "blob_id": "ede92c5bb82e55ae9c9b5ecedd1b941333789338", "content_id": "ba6e0b4b4e133010f58b3f091f8ceede866dabdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 3107, "license_type": "no_license", "max_line_length": 135, "num_lines": 66, "path": "/RecommendationEngine_R/tests/test_initialization.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "library(testthat)\ncontext(\"Test Initalizer\")\nsetwd(\"..\")\nsource(\"GlobalConfig.R\")\n\n##initalization\ntest_that(\n 'initialization',\n {\n expect_s4_class(new('Recommendation_Configuration'),'Recommendation_Configuration')\n expect_s4_class(new('Recommendation_Configuration',valpct= 101),'Recommendation_Configuration')\n expect_s4_class(new('Recommendation_Configuration',valpct= 10),'Recommendation_Configuration')\n expect_s4_class(new('Recommendation_Configuration',valpct= -10),'Recommendation_Configuration')\n expect_s4_class(new('Recommendation_Configuration',testpct= 10),'Recommendation_Configuration') \n expect_s4_class(new('Recommendation_Configuration',testpct= 101),'Recommendation_Configuration')\n expect_s4_class(new('Recommendation_Configuration',testpct= -10),'Recommendation_Configuration')\n expect_s4_class(new('Recommendation_Configuration',validation= FALSE),'Recommendation_Configuration')\n expect_error( new('Recommendation_Configuration',validation= 1))\n expect_error( new('Recommendation_Configuration',production= 1))\n expect_s4_class(new('Recommendation_Configuration',production= TRUE),'Recommendation_Configuration')\n expect_error( new('Recommendation_Configuration',games_to_select= -11))\n expect_error( new('Recommendation_Configuration',cutoff= -11))\n expect_error( new('Recommendation_Configuration',banana= -11))\n \n }\n)\n\n##test_validation\n\ntest_that(\n 'testValidation',\n {\n expect_equal(testValidation(new('Recommendation_Configuration')),FALSE)\n expect_equal(testValidation(new('Recommendation_Configuration', validation = FALSE)),FALSE)\n expect_equal(testValidation(new('Recommendation_Configuration', validation = TRUE)),TRUE)\n }\n)\n\ntest_that(\n 'getParameters',\n {\n tv = new('Recommendation_Configuration')\n expect_equal(getParameters(tv)$validation , NULL)\n expect_equal(getParameters(tv)$test , NULL)\n tv = new('Recommendation_Configuration', validation=TRUE)\n expect_equal(getParameters(tv)$validation , 10)\n expect_equal(getParameters(tv)$test , 5)\n tv = new('Recommendation_Configuration', validation=TRUE, valpct = 15, testpct = 8)\n expect_equal(getParameters(tv)$validation , 15)\n expect_equal(getParameters(tv)$test , 8)\n }\n)\n\n\ntest_that(\n 'getPostProcessingSettings',\n {\n expect_equal(getPostProcessingSettings(new('Recommendation_Configuration'))$cutoff,0.1)\n expect_equal(getPostProcessingSettings(new('Recommendation_Configuration'))$games_to_select,10)\n expect_equal(getPostProcessingSettings(new('Recommendation_Configuration',cutoff= 0.5))$cutoff,0.5)\n expect_equal(getPostProcessingSettings(new('Recommendation_Configuration',games_to_select= 5))$games_to_select,5)\n expect_equal(getPostProcessingSettings(new('Recommendation_Configuration',games_to_select= 5.9))$games_to_select,5)\n expect_equal(getPostProcessingSettings(new('Recommendation_Configuration',games_to_select= 5.1))$games_to_select,5)\n expect_equal(getPostProcessingSettings(new('Recommendation_Configuration',games_to_select= 4.99999999999999999))$games_to_select,5)\n }\n)\n" }, { "alpha_fraction": 0.5428714156150818, "alphanum_fraction": 0.6131604909896851, "avg_line_length": 33.28205108642578, "blob_id": "072eec5687ccd0f04d2d25ae9bf046bbd3a393b4", "content_id": "734c24968ccff1ea71d0d768f1d8c0bd8736954e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 4012, "license_type": "no_license", "max_line_length": 202, "num_lines": 117, "path": "/RecommendationEngine_R/tests/test_write_to_db.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "context(\"Write_To_Data_Base\")\nrequire(RODBC)\nsetwd(\"..\")\n\nsource('Write_To_Db_Refactored.R')\nsource(\"postprocessing.R\")\n\ntest_that(\n 'initialization',\n {\n expect_s4_class(new('write_to_db',production = TRUE,setdate = '2012-05-05'), 'write_to_db')\n expect_s4_class(new('write_to_db',production = FALSE,setdate = '2018-05-05'), 'write_to_db')\n expect_error(new('write_to_db'))\n expect_error(new('write_to_db', production = TRUE))\n expect_error(new('write_do_db', production = FALSE,setdate = 'appel'))\n expect_error(new('write_do_db', production = FALSE,setdate = '0'))\n expect_error(new('write_do_db', production = FALSE,setdate = '258-011-14'))\n }\n)\n\ntest_that(\n 'cleanup_past',\n {\n outputmachine = new('write_to_db',production = FALSE,setdate = '2012-05-05')\n expect_match(cleanup_past(outputmachine,5),'2012-04-30')\n expect_match(cleanup_past(outputmachine,6),'2012-04-29')\n expect_match(cleanup_past(outputmachine,4),'2012-05-01')\n expect_equal(cleanup_past(outputmachine,-10),0)\n expect_match(cleanup_past(outputmachine,4), 'delete from ')\n expect_match(cleanup_past(outputmachine,4), 'where Date <=')\n }\n)\n\ntest_that(\n 'cleanup_today',\n {\n outputmachine = new('write_to_db',production = FALSE,setdate = '2012-05-05')\n expect_match(cleanup_today(outputmachine),'2012-05-05')\n expect_match(cleanup_today(outputmachine),'delete from')\n }\n)\n\n\nzm = \n rbind(\n c(5, 0, 0, 0, 3, 0, 4, 2, 0, 0),\n c(3, 3, 0, 4, 0, 5, 4, 0, 0, 2),\n c(1, 0, 4, 4, 3, 0, 0, 5, 0, 0),\n c(0, 0, 0, 0, 0, 0, 0, 4, 1, 0),\n c(0, 0, 0, 0, 0, 0, 0, 0, 1, 5),\n c(0, 0, 4, 0, 0, 0, 0, 0, 0, 0)\n )\n\ndemodata = cbind(1,'2012-05-05',c(1:6),zm)\ncolnames(demodata) = c('SN','Date','Game','Top1Game','Top2Game','Top3Game','Top4Game', 'Top5Game', 'Top6Game',\n 'Top7Game','Top8Game','Top9Game','Top10Game')\n\n\n\ntest_that(\n 'insert_into_table',\n {\n outputmachine = new('write_to_db',production = FALSE,setdate = '2012-05-05')\n amm = insert_into_table(outputmachine,demodata)\n expect_match(amm[5],'2012-05-05')\n expect_match(amm[3],'2012-05-05')\n expect_match(amm[2],\",0,\")\n expect_length(amm,6)\n expect_match(amm[4],\"insert into\")\n expect_equal(amm[1],\"insert into [DataScientist].[dbo].[IntelligentGame] values ('2012-05-05',0,'1','5','0','0','0','3','0','4','2','0','0')\")\n }\n)\n\ntest_that(\n 'update_Tables',\n {\n outputmachine = new('write_to_db',production = FALSE,setdate = '2012-05-05')\n amm = updateTables(outputmachine)\n expect_match(amm,'2012-05-05')\n for (n in c(1:9))\n {\n expect_match(amm,paste0('Top',as.character(n),'Game = gt.key2'))\n expect_match(amm,paste0(\"',',ig.Top\",as.character(n),\"Game\")) \n }\n expect_match(amm,\"update ig set ig.Top1Game = gt.key2 from\")\n }\n)\n\ntest_that(\n 'update_keys',\n {\n outputmachine = new('write_to_db',production = FALSE,setdate = '2012-05-05')\n output = updateKeys(outputmachine)\n expect_equal(output,\"update ig set ig.rawdatatype = gt.category, ig.gamecode = gt.[id] from DataScientist.dbo.IntelligentGame ig join ##tmp5848 gt on ig.GameCode = gt.[key] where date='2012-05-05'\")\n }\n)\n\ntest_that(\n 'createTempDB',\n {\n outputmachine = new('write_to_db',production = FALSE,setdate = '2012-05-05')\n output = createTempDB(outputmachine)\n expect_match(output,\"select a.GameCode as id,a.RawDataType as category,b.id as\")\n expect_match(output,\" group by a.RawDataType,a.GameCode,b.id order by a.RawDataType\")\n }\n)\n\ntest_that(\n 'write_to_table',\n {\n outputmachine = new('write_to_db',production = FALSE,setdate = '2012-05-05')\n expect_equal(write_to_table(outputmachine,demodata),0)\n }\n)\n\nswitcher = odbcDriverConnect(connection = \"driver={SQL Server};server=JG\\\\MSSQLSERVER2016;uid=DS.Jimmy;pwd=4wvb%ECX;\")== -1\nif (switcher) skip(\"No usable Database Connection\")\n\n" }, { "alpha_fraction": 0.6837607026100159, "alphanum_fraction": 0.7029914259910583, "avg_line_length": 28.0625, "blob_id": "1eea1309c23d97767cd9c44de3d81daaf9888be5", "content_id": "242ad9a8cf9c49d616f956ebe6d73ddb623f8caf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 468, "license_type": "no_license", "max_line_length": 99, "num_lines": 16, "path": "/RecommendationEngine_Python/PythonProduction/Tables.SQL", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": " /*190 DS_RecommenderSystem_CosineSimilarity */\n create table [DataScientist].dbo.[DS_RecommenderSystem_CosineSimilarity]\n ( \n\trns int IDENTITY(1,1), \n\tgame int,\n\tcorrespondgame int,\n\tcosinesimilarity float,\n\tupdatetime datetime\n )\n\n create table DS_RecommenderSystem_TemporaryUserData ( indx int not NULL IDENTITY(1,1) PRIMARY KEY,\n\t\t\t\t\t gameaccount nvarchar(20),\n\t\t\t\t\t siteid int,\n\t\t\t\t\t gametypesourceid int,\n\t\t\t\t\t last_executed datetime \n )\n\n" }, { "alpha_fraction": 0.7415730357170105, "alphanum_fraction": 0.745208203792572, "avg_line_length": 35.45783233642578, "blob_id": "2eaf5477b25a25eeee29e090fab8e4bdad06d81b", "content_id": "355f16f43b0c56176e506976940bdd0b71d364b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 3026, "license_type": "no_license", "max_line_length": 103, "num_lines": 83, "path": "/RecommendationEngine_R/Additional/Experiments.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "rm(list = ls())\n\nlibrary(logging)\nrequire(pryr)\n\nbasicConfig()\naddHandler(writeToFile, logger=\"highlevel\", file=\".//logging//Time_Tracing\")\naddHandler(writeToFile, logger='debugger', file='.//logging//Debug_Tracing')\n\nloginfo(\"Starting to process:\",logger='highlevel.module')\ntryLoadFile = function(str){\n loginfo(paste0(\"loading \",str),logger='debugger.module')\n tryCatch({source(str)},\n error=function(msg){\n logerror(paste0(\"Couldn't load the \",str, toString(msg),sep=''), logger='debugger.module')\n },\n warning=function(msg){source(str);logwarn(toString(msg),logger='debugger.module')})\n}\n\ntryLoadFile('Initializer.R')\ntryLoadFile('Preprocessing.R')\ntryLoadFile('Distance_Calculator.R')\ntryLoadFile('postprocessing.R')\ntryLoadFile('Write_To_Db_Refactored.R')\n\nconfig = new('Recommendation_Configuration')\nloginfo(toString(names(unlist(attributes(config)))), logger='debugger.module')\nloginfo(toString(unlist(attributes(config))), logger='debugger.module')\n\n\ndmm = new('preprocessing_counts')\nloginfo(\"Starting to process:\",logger='highlevel.module')\ndmm = getvalidatedDataSets(dmm, config@production)\ndmm = preprocess(dmm)\nloginfo(\"Data Successfully removed from the database:\",logger='highlevel.module')\nloginfo(paste(\"Current required memory:\",pryr::mem_used() / 10^6,sep=''),logger='highlevel.module')\nGames = getGames(dmm)\nMembers = getMembers(dmm)\nDatasets = getRecommendation(dmm)\nparameters = dist\n\n\n###to implement\nif(testValidation(config)){ \n dist = getParameters(config)\n sets = assign_to_sets(Games = Games,Members = Members, Datasets = Datasets, parameters = dist)\n Dataset = toSparse(sets$Recommendationset)\n} else {\n dist = FALSE\n Dataset = getSparse(dmm)\n}\nloginfo(\"Data Successfully assigned to sets:\",logger='highlevel.module')\nloginfo(paste(\"Current required memory:\",pryr::mem_used() / 10^6,sep=''),logger='highlevel.module')\n\n\nlast_updated = getTimeLastUpdated(dmm)\n\nControlset = getControl(dmm)\nGames = getGames(dmm)\nHot = getHot(dmm)\n\nDistance = new('CosineDistancecalculator')\ndistance_matrix = calculate_distance(Distance,Dataset,Games)\nloginfo(\"Distance matrix calculated:\",logger='highlevel.module')\nloginfo(paste(\"Current required memory:\",pryr::mem_used() / 10^6,sep=''),logger='highlevel.module')\n\n#how to deal with games that are removed from the dataset by sampling the dataset\npost_processing_settings = getPostProcessingSettings(config)\noutputmatrix = new('post_processing',post_processing_settings,Hot, last_updated)\nrecommendations = postProcess(outputmatrix, distance_matrix, Controlset)\n\n###to implement\nif(testValidation(config)){ \n new('Validator', dataset= sets$Validationset, target = recommendations)\n validation = new('Validator', dataset= sets$Validationset, target = recommendations)\n get_games_width(validation, post_processing_settings)\n} \n\n\n\nwrite_out = new('write_to_db', config@production, last_updated)\nwrite_to_table(write_out,recommendations)\nloginfo(\"Process Completed:\",logger='highlevel.module')\n" }, { "alpha_fraction": 0.3311637043952942, "alphanum_fraction": 0.5800788998603821, "avg_line_length": 49.65999984741211, "blob_id": "6330877be80105a95d265da0ffa856fe12f88176", "content_id": "ae1b494908debcef3b4b66010c97e2a81465c092", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 5070, "license_type": "no_license", "max_line_length": 127, "num_lines": 100, "path": "/RecommendationEngine_R/tests/test_post_processing.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "context(\"PostProcessing\")\nsetwd(\"..\")\n\nsource(\"GlobalConfig.R\")\n\n\nhot = data.frame(cbind(id = c('4607','6416','5517','1047','316','2948','162','4645','3057','4785'),\n counts = c(200905,161377,141317,139639,128142,100860,94932,87617,86158,77712)),stringsAsFactors = FALSE)\n\ngames = c(1,2,3,4,5,6,7,8,9,10,11)\n\ndistance_matrix = data.frame(cbind(\n c(10.0000000,0.5070926,0.1195229,0.4780914,0.7171372,0.5070926,0.9561829,0.3779645,0.0000000,0.1883294,0.7559289),\n c(0.5070926 ,10.0000000,0.000000,0.7071068,0.0000000,1.0000000,0.7071068,0.0000000,0.0000000,0.3713907,0.0000000),\n c(0.1195229 ,0.0000000 ,10.00000,0.5000000,0.5000000,0.0000000,0.0000000,0.5270463,0.0000000,0.0000000,0.3162278),\n c(0.4780914 ,0.7071068,0.5000000,10.000000,0.5000000,0.7071068,0.5000000,0.5270463,0.0000000,0.2626129,0.0000000),\n c(0.7171372 ,0.0000000,0.5000000,0.5000000,10.000000,0.0000000,0.5000000,0.7378648,0.0000000,0.0000000,0.6324555),\n c(0.5070926 ,1.0000000,0.0000000,0.7071068,0.0000000,10.000000,0.7071068,0.0000000,0.0000000,0.3713907,0.0000000),\n c(0.9561829 ,0.7071068,0.0000000,0.5000000,0.5000000,0.7071068,10.000000,0.2108185,0.0000000,0.2626129,0.6324555),\n c(0.3779645 ,0.0000000,0.5270463,0.5270463,0.7378648,0.0000000,0.2108185,10.000000,0.4216370,0.0000000,0.2666667),\n c(0.0000000 ,0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.4216370,10.000000,0.6565322,0.0000000),\n c(0.1883294 ,0.3713907,0.0000000,0.2626129,0.0000000,0.3713907,0.2626129,0.0000000,0.6565322,10.000000,0.0000000),\n c(0.7559289 ,0.0000000,0.3162278,0.0000000,0.6324555,0.0000000,0.6324555,0.2666667,0.0000000,0.0000000,10.000000)))\n\ncolnames(distance_matrix) = games\nrow.names(distance_matrix) = games\nvects = t(apply(distance_matrix, 2, order, decreasing=T))\n\n\n\n\ncontrol = data.frame(cbind(\n id = c('alm','alk','all','alp','alq','qls'),\n category = c('a','ab','a','ab','a','ab'),\n RawDataType = c('4','8','2','4','1','2','3','4','2','1','3','4'),\n key = c(1,2,3,4,5,6,7,8,9,10,11,15),\n Exclusions = c(0,0,0,0,0,0,0,0,1,0,0,0)\n),stringsAsFactors = FALSE)\n\ntest_that(\n 'initialization',\n {\n expect_s4_class(new('post_processing', configuration =list(cutoff = 0.1, games_to_select = 10),hot=hot,\n lastupdated='2018-11-03'),'post_processing')\n }\n)\n\ntest_that(\n 'filtercategory',\n {\n post_processor = new('post_processing', configuration =list(cutoff = 0.1, games_to_select = 10), hot = hot,\n lastupdated='2018-11-03')\n \n for (k in c(1:dim(distance_matrix)[1]))\n {\n expect_equal(vects[k,], order(as.numeric(distance_matrix[k,]),decreasing = TRUE))\n }\n \n \n output = c(2,7,8,3,8,7,2,5,10,7,8)\n for (k in c(1:dim(distance_matrix)[1]))\n {\n expect_equal(as.character(output[k]),filter_category(ordered_row = vects[k,],distance_row = distance_matrix[k,], \n active_game = games[k], updated_control = control, \n games_to_select = 1, cutoff = 0.1, hot = hot)[2])\n expect_equal(as.character(games[k]), filter_category(ordered_row = vects[k,],distance_row = distance_matrix[k,], \n active_game = games[k], updated_control = control, \n games_to_select = 1, cutoff = 0.1, hot = hot)[1])\n }\n \n k = 5\n expect_equal(c(\"5\",\"8\",\"4\",\"1\",\"11\",\"3\"),filter_category(ordered_row = vects[k,],distance_row = distance_matrix[k,], \n active_game = games[k], updated_control = control, \n games_to_select = 5, cutoff = 0.1, hot = hot))\n expect_equal(c(\"5\",\"4607\",\"6416\",\"5517\",\"1047\",\"316\"),filter_category(ordered_row = vects[k,],\n distance_row = distance_matrix[k,], \n active_game = games[k], updated_control = control, \n games_to_select = 5, cutoff = 0.8, hot = hot))\n expect_equal(c('5','8','4','1','11','3','7','4607','6416','5517','1047'),\n filter_category(ordered_row = vects[k,],distance_row = distance_matrix[k,], \n active_game = games[k], updated_control = control, \n games_to_select = 10, cutoff = 0.3, hot = hot))\n \n }\n)\n\ntest_that(\n 'postProcess',\n {\n ppc = new('post_processing', configuration =list(cutoff = 0.1, games_to_select = 1),hot=hot,\n lastupdated='2018-11-03')\n outp = postProcess(ppc,dataset = distance_matrix,games = control)\n expect_equal(outp[1,1],1)\n expect_equal(outp[1,'Date'],as.factor(\"2018-11-03\"))\n expect_equal(outp[1,'Game'],'1')\n cols = c('SN','Date','Game','Top1Game','Top2Game','Top3Game', 'Top4Game','Top5Game', 'Top6Game', 'Top7Game','Top8Game',\n 'Top9Game','Top10Game')\n expect_equal(cols, colnames(outp))\n }\n)\n\n\n\n\n" }, { "alpha_fraction": 0.5904191732406616, "alphanum_fraction": 0.6377245783805847, "avg_line_length": 29.83333396911621, "blob_id": "03b42d4e3d3736007048a3eb36a198a3660b36ce", "content_id": "f59086d27e45f0c4375fb12203662d08fa810b23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1670, "license_type": "no_license", "max_line_length": 264, "num_lines": 54, "path": "/RecommendationEngine_Python/Optimization/DS_SQLGetDF_191.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 15 17:23:28 2019\n@author: DS.Tom\n\"\"\"\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport datetime\nimport time\nimport DS_SQLGetDF_function as func\n\nServer_list = ['10.80.16.191', '10.80.16.192', '10.80.16.193', '10.80.16.194']\nServer = Server_list[0]\nIP = func.DB('SQL Server Native Client 11.0', Server, 'DS.Reader', '8sGb@N3m')\n\n#main parameter\nnow = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:00:00.000\") #UTC+0\ncurrent = datetime.datetime.now().strftime(\"%Y-%m-%d %H:00:00.000\") \nSQLQuery_df = func.select_from_sql(now, current, Server)\nJG = func.DB('SQL Server Native Client 11.0', 'JG\\MSSQLSERVER2016', 'DS.Jimmy', keyring::get_password('DS.Jimmy'))\n\n#print(SQLQuery_df)\n\n\n#solution\nerr = []\ntime_list = []\nstart_for = time.time()\ndata = pd.DataFrame([],columns=['Dateplayed','GameAccount','SiteId','GameTypeSourceId','Commissionable','WagersCount'])\nfor i in range(SQLQuery_df.shape[0]):\n #print(i)\n s = time.time()\n \n sqlquery = SQLQuery_df['Sqlquery'][i]\n\n \n try:\n df = IP.ExecQuery(sqlquery)\n \n if not df.empty:\n #print(df)\n #print(data)\n data =pd.concat([data,df])\n #pass # JG.Executemany(\"insert into DataScientist.dbo.DS_RecommenderSystemDailyQuery([DatePlayed], [GameAccount], [SiteId], [GameTypeSourceId], [Commissionable], [WagersCount]) values (?,?,?,?,?,?)\", df.apply(lambda x: tuple(x.values), axis=1).tolist())\n except:\n err.append(SQLQuery_df.GameTypeSourceId[i])\n continue\n finally:\n e = time.time()\n time_list.append(e-s)\nend_for = time.time()\nprint(end_for- start_for)\n \n" }, { "alpha_fraction": 0.575995922088623, "alphanum_fraction": 0.604205846786499, "avg_line_length": 33.597633361816406, "blob_id": "93fcc21c9bfd3b77ace9b2c7370e3dec51c45252", "content_id": "488e7fcedc9e5b6e21be76fba17036219ae88002", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5849, "license_type": "no_license", "max_line_length": 124, "num_lines": 169, "path": "/RecommendationEngine_Python/Optimization/Process_optimization.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 29 09:39:27 2019\n\n@author: DS.Tom\n\"\"\"\npath = \"C:/Users/DS.Tom/.spyder-py3/db/\"\n\nimport numpy as np\nimport os\nimport pandas as pd\nimport time\nos.chdir(path)\nimport DS_function as func\nimport asyncio\nimport nest_asyncio\nimport keyring\nnest_asyncio.apply()\n\n\n\nasync def main():\n\n #import matplotlib.pyplot as plt\n start = time.time() \n\n '''\n Variable zone\n '''\n JG = func.DB('SQL Server Native Client 11.0', 'JG\\MSSQLSERVER2016', 'DS.Jimmy', keyring.get_password('JG','DS.Jimmy'))\n train_start = '2019-10-10 00:00:00.000' \n train_end = '2019-10-30 23:59:59.999'\n test_start = '2019-10-21 00:00:00.000' \n test_end = '2019-10-21 23:59:59.999'\n\n #Get train & test with sql & ODBC\n train = func.get_data(JG, train_start, train_end)\n\n test = func.get_data(JG, test_start, test_end)\n\n print(\"--- %s seconds ---\" % (time.time() - start))\n '''\n Exclude_rawdatatype = [35, 67, 68, 136]# Mako said that there aren't unique gameaccount in these gamehall(rawdatatype)\n train = train[~train.RawDataType.isin(Exclude_rawdatatype)]\n '''\n\n sql_end = time.time() \n python_start = sql_end\n\n\n '''\n PreProcessing\n '''\n train_data = func.Pre_processing(train)\n test_data = func.Pre_processing(test)\n del(train)\n del(test)\n print(\"--- %s seconds ---\" % (time.time() - start))\n '''\n train_data = train_data[train_data.SiteID == 154].reset_index()\n test_data = test_data[test_data.SiteID == 154].reset_index()\n '''\n\n\n\n# filter & Exclude the just play one game people (Noise and it can't give our model any help)\n train_data = func.Pre_processing_train(train_data)\n\n# Define the hotgame list\n HotGame_inTrain = func.Hot_Game(train_data, \n feature='Commissionable',\n n=15)\n print(\"--- %s seconds ---\" % (time.time() - start))\n\n users = train_data.Member.unique()\n games = train_data.Game.unique()\n userid2idx = {o:i for i,o in enumerate(users)}\n gameid2idx = {o:i for i,o in enumerate(games)}\n userid2Rraw = {i:o for i,o in enumerate(users)}\n gameid2iraw = {i:o for i,o in enumerate(games)}\n\n print(\"--- %s seconds ---\" % (time.time() - start))\n\n train_data.loc[:, 'Member_encoding'] = train_data['Member'].apply(lambda x: userid2idx[x])\n train_data.loc[:, 'Game_encoding'] = train_data['Game'].apply(lambda x: gameid2idx[x])\n Trainset = func.get_Trainset(train_data)\n\n cosine_sim = func.SVD_surprise_only_tom(Trainset) # pd.read_csv(\"C:/Users/DS.Tom/Desktop/cosine_sim.csv\", index_col = 0)\n #print(cosine_sim)\n print( \"Cosine sim:\" + str(np.shape(cosine_sim)))\n res = await find_top_K(Trainset,cosine_sim,30,50000)\n filtered_array = np.vstack(res)\n\n filtered_array = filtered_array[filtered_array[:,0].argsort()]\n users = filtered_array[:,0]\n filtered_array = filtered_array[:,1:31]\n filtered_array = filtered_array.reshape( filtered_array.shape[0] * filtered_array.shape[1], -1)\n \n SVD_Neighbor = pd.DataFrame({'Member_encoding': np.repeat(users, 30), \n 'Game_encoding': filtered_array[:,0]})\n \n #SVD_Neighbor_result = SVD_Neighbor.groupby('member_id').head(12)\n SVD_Neighbor_result = SVD_Neighbor.merge(Trainset[['Member_encoding', 'Game_encoding', 'score']],\n how = 'left',\n on = ['Member_encoding', 'Game_encoding'])\n SVD_Neighbor_result.score = np.where(SVD_Neighbor_result.score.isna(), 0, SVD_Neighbor_result.score)\n SVD_Neighbor_result = SVD_Neighbor_result.sort_values(by = ['Member_encoding', 'score'], ascending = False)\n SVD_Neighbor_result = SVD_Neighbor_result.groupby('Member_encoding').head(12)\n print(len(users))\n print(SVD_Neighbor_result)\n print(\"--- %s seconds ---\" % (time.time() - start))\n\n\n #print(np.shape(res[0]))\n #print(res[0])\n\nasync def find_top_K(Trainset, cosine_sim, K = 30, step = 10000):\n start = time.time()\n loop = asyncio.get_event_loop()\n keys,values = Trainset.loc[:,['Member_encoding','Game_encoding']].values.T \n ukeys, index = np.unique(keys,True)\n arrays = np.split(values, index[1:])\n gamesplayed = pd.DataFrame({'a':ukeys,'b':[list(a) for a in arrays]})\n gamesplayed.columns = ['Member_encoding','games']\n print(\"--- %s seconds ---\" % (time.time() - start))\n \n #gamesplayed = Trainset.groupby(['Member_encoding'])['Game_encoding'].apply(lambda x: list(x)).reset_index(name='games')\n cosine2 = cosine_sim.to_numpy()\n #print(\"--- %s seconds ---\" % (time.time() - start))\n \n lup = dict()\n for key in range(np.shape(cosine2)[0]):\n lup[key]= cosine2[key,:]\n goal = np.zeros((np.shape(gamesplayed)[0],K))\n\n totalsize = np.shape(gamesplayed)[0]\n\n batches = totalsize // step\n tasks = []\n \n for k in range(batches):\n l = k + 1\n batch = gamesplayed.iloc[ k*step:l*step,: ]\n tasks.append(loop.create_task(process(batch,lup,k*step, step,K)))\n laststep = batches *step\n\n try:\n #pass\n lastbatch = gamesplayed.iloc[ laststep : (totalsize-1),:]\n tasks.append(loop.create_task(process(lastbatch,lup,laststep,step,K)))\n except:\n pass\n res = await asyncio.gather(*tasks)\n print(\"--- %s seconds ---\" % (time.time() - start))\n return(res) \n \nasync def process(batch, lup, startindex, batchsize,K):\n lookup = batch.games.to_numpy()\n indx = 0\n goal = np.zeros((batchsize,31))\n for key in lookup:\n res = [ lup[val] for val in key ]\n results = np.max(res,axis=0).argsort()[::-1][0:K]\n goal[indx,1:31] = results\n goal[indx,0] = startindex + indx\n indx = indx + 1\n return(goal)\n\nasyncio.run(main())\n\n\n" }, { "alpha_fraction": 0.5903863310813904, "alphanum_fraction": 0.6030178070068359, "avg_line_length": 43.32461929321289, "blob_id": "2c7491dff2a27dc9f68551e88dd320594453f205", "content_id": "c9bc4062bc9b7c5ae929aa248c5aac398d1e20e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20412, "license_type": "no_license", "max_line_length": 140, "num_lines": 459, "path": "/RecommendationEngine_Python/ModelResearch/DS_Model_function.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport scipy.sparse as sparse\nfrom scipy.sparse import csr_matrix\nfrom sparsesvd import sparsesvd\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn import metrics\nfrom surprise import SVD, Reader, Dataset\n\n'''\nNormalization Function\n'''\ndef min_max_normalize(x):\n min = x.min()\n max = x.max()\n result = np.float64((x- min) / (max- min))\n return result\n\ndef StandardScaler(x):\n mean = x.mean()\n std = x.std()\n result = np.float64((x- mean)/ std)\n return result\n\ndef Mean_normalize(x):\n min = x.min()\n max = x.max()\n mean = x.mean()\n result = np.float64((x- mean)/ (max- min))\n return result \n\n'''\nPre_processing\n'''\ndef Pre_processing(df):\n result = df.copy()\n result['member_id'] = result['member_id'].astype('int64')\n result['dates'] = result['dates'].astype('int64')\n result['game_id'] = result['game_id'].astype('int64')\n result['bet_amount'] = result['bet_amount'].astype('float64')\n result['payoff'] = result['payoff'].astype('float64')\n result['commissionable'] = result['commissionable'].astype('float64')\n result['Expect_earning_ratio'] = result['Expect_earning_ratio'].astype('float64')\n result['gamecode'] = result['gamecode'].astype('category')\n # We will multiply the ratio from the gamehall in the future but the information we haven't received yet.\n # and assume every gamehall keep the same ==1\n result.insert(11, 'expect_earn', result['commissionable'] * result['Expect_earning_ratio'])\n #result.insert(12, 'expect_earn_per_day', result['expect_earn'] / result['dates'])\n result.insert(12, 'expect_earn_per_day', result['commissionable'] )#/ result['dates']\n result.insert(13, 'key', list(zip(result['RawDataType'], result['gamecode'])))\n return(result)\n\n\n## filter & Exclude the just play one game people( Noise and it can't give our model any help)\ndef Pre_processing_train(df):\n x = df.copy()\n x = x[(x['dates'] > 0) & (x['bet_amount'] > 0) & (x['commissionable'] > 0)]\n group = x.groupby('member_id', as_index=False).agg({'game_name': ['count']})\n group.columns = ['member_id', 'count']\n group = group[group['count'] != 1]\n group = group.reset_index(drop=True)\n x = x[x.member_id.isin(group.member_id)]\n x = x.reset_index(drop = True)\n return(x)\n\n#Define the hot game for the newuser or the user not in train data\ndef Hot_Game(df, feature = 'commissionable', n = 12):\n if feature == 'commissionable':\n FindHotGame = df.groupby('game_id', as_index=False).agg({'commissionable': ['sum']})\n FindHotGame.columns = ['game_id', 'feature']\n elif feature == 'member_id':\n FindHotGame = df.groupby('game_id', as_index=False).agg({'member_id': ['count']})\n FindHotGame.columns = ['game_id', 'feature']\n else:\n print('Not Defined')\n FindHotGame = pd.DataFrame(columns=['game_id', 'feature'])\n FindHotGame = FindHotGame.sort_values(by = ['feature'], ascending = False).reset_index(drop = True)\n HotGame = list(FindHotGame.game_id[0:n])\n return HotGame\n\n\ndef get_Trainset(df):\n Trainset = df[['member_id', 'game_id', 'dates', 'expect_earn_per_day','payoff']].copy()\n Trainset = Trainset.sort_values(by=['member_id', 'game_id'], ascending=True).reset_index(drop=True)\n \n zmm1 = min_max_normalize(Trainset[['expect_earn_per_day']])#min_max_normalize(Trainset[['expect_earn_per_day']])\n zmm2 = min_max_normalize(Trainset[['dates']])#min_max_normalize(Trainset[['dates']])\n zmm = 0.5 * zmm1 + 0.5 * zmm2\n Trainset.loc[:, 'score'] = zmm\n \n return Trainset\n\n'''\nModel -Cosine Similarity\n'''\ndef get_sparse(Trainset):\n #model of the cosine similarity\n members = list(Trainset.member_id.unique()) # Get our unique members\n games = list(Trainset.game_id.unique()) # Get our unique games that were purchased\n score_list = list(Trainset.score) # All of our score\n # Get the associated row, column indices\n cols = Trainset.member_id.astype('category',\n categories = members).cat.codes\n rows = Trainset.game_id.astype('category',\n categories = games).cat.codes\n sparse_df = sparse.csr_matrix((score_list, (rows, cols)),\n shape=(len(games), len(members)))\n '''\n print('num of members : {}\\nnum of games : {}\\nnum of score : {}'.format(len(members),\n len(games), len(score_list)))\n print(\"shape of record_sparse: \", sparse_df.shape)\n '''\n return sparse_df\n\n\n# what does the 30 come from? 95% percentile\ndef Recommendation_cosine(Trainset, sparse_df, games, N = 30):\n cosine_sim = cosine_similarity(sparse_df, sparse_df)\n cosine_sim = pd.DataFrame(data = cosine_sim, index=games, columns=games)\n ## get the neighbor 30 game of every user\n gamelist = np.array(cosine_sim.columns)\n gamesplayed = Trainset.groupby(['member_id'])['game_id'].apply(list).reset_index(name='games')\n gamesmax = np.array(gamesplayed.games.map(lambda x: ((cosine_sim.loc[x,:].values).max(axis=0))))\n def Get_neighbor_30(x):\n # x[x>0.99] = 0.0\n return (gamelist[np.flip(np.argsort(x, axis=0))[0:N, ]])\n filtered = list(map(Get_neighbor_30, gamesmax))\n filtered_array = np.array(filtered)\n filtered_array = filtered_array.reshape(filtered_array.shape[0] * filtered_array.shape[1], -1)\n filtered_array = filtered_array.reshape(-1,)\n Neighbor_result = pd.DataFrame({'member_id': np.repeat(np.array(np.unique(Trainset.member_id)), N, axis=0),\n 'game_id': filtered_array})\n\n Neighbor_only_result = Neighbor_result.merge(Trainset[['member_id', 'game_id', 'score']], how = 'left', on = ['member_id', 'game_id'])\n Neighbor_only_result.score = np.where(Neighbor_only_result.score.isna(), 0, Neighbor_only_result.score)\n #sorted by the normalized expect return in training data\n Neighbor_only_result = Neighbor_only_result.sort_values(by = ['member_id', 'score'], ascending = False)\n Neighbor_only_result = Neighbor_only_result.groupby('member_id').head(12)\n \n return Neighbor_only_result, Neighbor_result\n\n\n'''\nModel - SVD_new\n'''\ndef SVD_surprise_only(Trainset, N = 30):\n reader = Reader()\n Trainset_changetype = Dataset.load_from_df(Trainset[['member_id', 'game_id', 'score']], reader)\n Trainset_changetype_result = Trainset_changetype.build_full_trainset()\n svd = SVD(n_factors = 20,\n n_epochs = 20,\n lr_all = 0.01,#0.0001,\n random_state = 1234)\n svd.fit(Trainset_changetype_result)\n\n games = list(Trainset.game_id.unique()) # Get our unique games that were purchased\n\n #model SVD_New\n data = np.transpose(np.dot(svd.pu, np.transpose(svd.qi)))\n x = cosine_similarity(data, data)\n cosine_sim_x = pd.DataFrame(data = x, \n index=games,\n columns=games)\n gamesplayed = Trainset.groupby(['member_id'])['game_id'].apply(list).reset_index(name='games')\n gamesmax = np.array(gamesplayed.games.map(lambda x: ((cosine_sim_x.loc[x,:].values).max(axis=0))))\n gamelist = np.array(cosine_sim_x.columns)\n \n def Get_neighbor_30(x):\n # x[x>0.99] = 0.0\n return (gamelist[np.flip(np.argsort(x, axis=0))[0:N, ]])\n filtered = list(map(Get_neighbor_30, gamesmax))\n filtered_array = np.array(filtered)\n filtered_array = filtered_array.reshape(filtered_array.shape[0] * filtered_array.shape[1], -1)\n filtered_array = filtered_array.reshape(-1,)\n SVD_Neighbor = pd.DataFrame({'member_id': np.repeat(np.array(np.unique(Trainset.member_id)), N, axis=0), 'game_id': filtered_array})\n #SVD_Neighbor_result = SVD_Neighbor.groupby('member_id').head(12)\n SVD_Neighbor_result = SVD_Neighbor.merge(Trainset[['member_id', 'game_id', 'score']], how = 'left', on = ['member_id', 'game_id'])\n SVD_Neighbor_result.score = np.where(SVD_Neighbor_result.score.isna(), 0, SVD_Neighbor_result.score)\n SVD_Neighbor_result = SVD_Neighbor_result.sort_values(by = ['member_id', 'score'], ascending = False)\n SVD_Neighbor_result = SVD_Neighbor_result.groupby('member_id').head(12)\n \n return SVD_Neighbor, SVD_Neighbor_result\n\n\n'''\nModel - SVD, Bind Model\n'''\ndef SVD_surprise(Trainset):\n reader = Reader()\n Trainset_changetype = Dataset.load_from_df(Trainset[['member_id', 'game_id', 'score']], reader)\n Trainset_changetype_result = Trainset_changetype.build_full_trainset()\n svd = SVD(n_factors = 20,\n n_epochs = 20,\n lr_all = 0.01,#0.0001,\n random_state = 1234)\n svd.fit(Trainset_changetype_result)\n\n\n members = list(Trainset.member_id.unique()) # Get our unique members\n games = list(Trainset.game_id.unique()) # Get our unique games that were purchased\n \n #model SVD\n Latent_result = pd.DataFrame(data = np.dot(svd.pu, np.transpose(svd.qi)),\n index = members,\n columns = games)\n Latent_result_array = np.array(Latent_result)\n Latent_result_array = Latent_result_array.reshape(Latent_result.shape[0] * Latent_result.shape[1], -1)\n Latent_result_array = Latent_result_array.reshape(-1, ) \n Latent_result_df = pd.DataFrame({'member_id':np.repeat(np.array(Latent_result.index.unique()),\n len(games),\n axis = 0),\n 'game_id':games * len(members),\n 'Pred_Return':Latent_result_array})\n Latent_only = Latent_result_df.sort_values(by = ['member_id', 'Pred_Return'], ascending = False)\n Latent_only_result = Latent_only.groupby('member_id').head(12)\n \n return Latent_only_result, Latent_result_df\n\n'''\nModel -SparseSVD\n'''\ndef get_sparse_matrix(Trainset):\n members = list(Trainset.member_id.unique()) # Get our unique members\n games = list(Trainset.game_id.unique()) # Get our unique games that were purchased\n score_list = list(Trainset.score) # All of our dates\n #print('num of members : {}\\nnum of games : {}\\nnum of score : {}'.format(len(members),\n # len(games), len(score_list)))\n\n # Get the associated row,column indices\n rows = Trainset.member_id.astype('category', categories=members).cat.codes\n cols = Trainset.game_id.astype('category', categories=games).cat.codes\n sparse_df = sparse.csc_matrix((score_list, (rows, cols)), shape=(len(members), len(games)))\n #print(\"shape of record_sparse: \", sparse_df.shape)\n return sparse_df\n\n\ndef computeSVD(urm, K):\n\tU, s, Vt = sparsesvd(urm, K)\n\n\tdim = (len(s), len(s))\n\tS = np.zeros(dim, dtype=np.float32)\n\tfor i in range(0, len(s)):\n\t\tS[i,i] = s[i]\n\n\tU = csr_matrix(np.transpose(U), dtype=np.float32)\n\tS = csr_matrix(S, dtype=np.float32)\n\tVt = csr_matrix(Vt, dtype=np.float32)\n\n\treturn U, S, Vt\n\ndef get_threshold(array, percentage):\n denom = sum(elem ** 2 for elem in array)\n k = 0\n sums = 0\n for elem in array:\n sums += elem ** 2\n k += 1\n if sums >= percentage * denom:\n return k\n\ndef Dim_reduction(sparse_df):\n #Original SVD\n U_, S_, Vt_ = computeSVD(sparse_df, min(sparse_df.shape[0], sparse_df.shape[1])-1)\n k = get_threshold(S_.diagonal(), 0.9)\n return k\n\n\n#V = (S*Vt).T\ndef get_neighbor(V, distance, Trainset, games, test_data, N = 30):\n from sklearn.metrics import pairwise_distances\n similarity_matrix = pairwise_distances(V, V, metric = distance)\n similarity_matrix = pd.DataFrame(data = similarity_matrix, index = games, columns = games)\n gamelist = np.array(Trainset.game_id.unique())\n gamesplayed = Trainset.groupby(['member_id'])['game_id'].apply(list).reset_index(name='games')\n gamesmin = np.array(gamesplayed.games.map(lambda x: ((similarity_matrix.loc[x,:].values).min(axis=0))))\n\n def Get_neighbor_30(x):\n # x[x>0.99] = 0.0\n return (gamelist[np.flip(np.argsort(-x, axis=0))[0:N, ]])\n\n filtered = list(map(Get_neighbor_30, gamesmin))\n\n filtered_array = np.array(filtered)\n filtered_array = filtered_array.reshape(filtered_array.shape[0]* filtered_array.shape[1],-1)\n filtered_array = filtered_array.reshape(-1, ) #將30*n的數組轉成(-1,)維的陣列\n\n Neighbor_result = pd.DataFrame({'member_id':np.repeat(np.array(np.unique(Trainset.member_id)),\n N,\n axis=0),\n 'game_id': filtered_array}) #給定每個玩家在每款遊戲的名單\n Neighbor_result['recommend'] = 1\n Neighbor_only_result = Neighbor_result.merge(Trainset[['member_id', 'game_id', 'score']],\n how = 'left',\n on = ['member_id', 'game_id']) #把每個人的SCORE收集起來\n Neighbor_only_result.score = np.where(Neighbor_only_result.score.isna(), 0, Neighbor_only_result.score)\n #sorted by the normalized expect return in training data\n Neighbor_only_result = Neighbor_only_result.sort_values(by = ['member_id', 'score'], ascending = False)\n Neighbor_only_result = Neighbor_only_result.groupby('member_id').head(12)\n Neighbor_only_result.loc[:, 'Order'] = list(range(1,13)) * len(np.unique(Neighbor_only_result.member_id))\n \n Neighbor_only_result = Neighbor_only_result.drop(['recommend'], axis=1)\n \n return Neighbor_only_result\n\n'''\nModel - Bagging\n'''\ndef Bagging(Bagging_df, Trainset):\n #value_counts() set assending =False as default.\n Bagging_df_groupby = Bagging_df.groupby(['member_id']).apply(lambda x: pd.DataFrame(x.game_id.value_counts().index).iloc[0:12, ])\n Bagging_result_12 = pd.DataFrame(Bagging_df_groupby)\n Bagging_result_12.columns = ['game_id']\n Bagging = pd.DataFrame({'member_id':np.repeat(np.array(np.unique(Trainset.member_id)), 12, axis=0),\n 'game_id': Bagging_result_12.game_id}).reset_index(drop=True)\n \n Bagging_result = Bagging.merge(Trainset[['member_id', 'game_id', 'score']], how = 'left', on = ['member_id', 'game_id'])\n Bagging_result.score = np.where(Bagging_result.score.isna(), 0, Bagging_result.score)\n \n Bagging_result = Bagging_result.sort_values(by = ['member_id', 'score'], ascending = False) \n \n return Bagging_result\n\n\n'''\nEvaluation metric\n'''\ndef NDCG(input_df, test_df):\n def get_Testset_score(df):\n temp = df.copy()\n temp = temp.sort_values(by=['member_id', 'game_id'], ascending=True).reset_index(drop=True)\n \n zmm1 = min_max_normalize(temp[['expect_earn_per_day']])\n zmm2 = min_max_normalize(temp[['dates']])\n zmm = 0.5 * zmm1 + 0.5 * zmm2\n temp.loc[:, 'score'] = zmm\n return temp\n\n def DCG(df):\n data = df.copy()\n data['dcg_rank'] = list(range(2, 14)) * int(data.shape[0] / 12)\n from math import log\n data['dcg'] = data.apply(lambda row: (2 ** row.score - 1) / log(row.dcg_rank, 2), axis=1)\n dcg = data.groupby('member_id', as_index=False)['dcg'].sum()\n return dcg\n \n def iDCG(df):\n data = df.copy()\n data = data.sort_values(by=['member_id', 'score'], ascending=False)\n data['dcg_rank'] = list(range(2, 14)) * int(data.shape[0] / 12)\n from math import log\n data['idcg'] = data.apply(lambda row: (2 ** row.score - 1) / log(row.dcg_rank, 2), axis=1)\n idcg = data.groupby('member_id', as_index=False)['idcg'].sum()\n return idcg\n \n df = input_df.copy()\n test = get_Testset_score(test_df)\n member_list = np.unique(test.member_id)\n df = df[df.member_id.isin(member_list)]\n df = df[['member_id', 'game_id']].merge(test[['member_id', 'game_id', 'score']],\n how = 'left',\n on = ['member_id', 'game_id']).fillna(0)\n dcg = DCG(df)\n idcg = iDCG(df)\n ndcg = dcg.merge(idcg, on='member_id', how='left')\n ndcg['NDCG'] = ndcg['dcg']/ndcg['idcg']\n ndcg.NDCG = np.where(ndcg.NDCG.isna(), 0, ndcg.NDCG)\n \n NDCG_value = np.mean(ndcg.NDCG)\n \n return NDCG_value\n\ndef Get_AUC_intrain(input_df, test_df):\n #hot game must be a list and there were 12 container.\n test_data = test_df.copy()\n df = input_df.copy()\n member_list = np.unique(test_data.member_id)\n df = df[df.member_id.isin(member_list)]\n df = df[['member_id', 'game_id']].merge(test_data[['member_id', 'game_id', 'commissionable']],\n how = 'left',\n on = ['member_id', 'game_id'])\n df.commissionable = np.where(df.commissionable.isna(), 0, 1) #play as TP\n df.columns = ['member_id', 'game_id', 'TP']\n df.loc[:,'FP'] = 1 - df.TP\n\n aggregated = df[['member_id', 'TP']].groupby('member_id', as_index=False).sum()\n aggregated.loc[:,'FP_n'] = 12 - aggregated.TP\n aggregated.columns = ['member_id', 'TP_n', 'FP_n']\n grade0_memberid = aggregated[aggregated.TP_n == 0].member_id\n\n tmp = df[~df.member_id.isin(grade0_memberid)]\n tmp = tmp.merge(aggregated, how='left', on='member_id')\n tmp.loc[:,'TPR'] = tmp.TP / tmp.TP_n\n tmp.loc[:,'FPR'] = tmp.FP / tmp.FP_n\n auc_df = tmp[['member_id', 'TPR', 'FPR']].groupby(['member_id']).apply(lambda x:metrics.auc(np.cumsum(x.FPR), np.cumsum(x.TPR)))\n \n auc_score = auc_df.sum()/len(np.unique(df.member_id))\n \n return auc_score\n\ndef Get_AUC_notintrain(input_df, test_df, HotGame):\n #hot game must be a list and there were 12 container.\n test_data = test_df.copy()\n raw = test_data[['member_id']].drop_duplicates().merge(input_df[['member_id', 'game_id']],\n how = 'left',\n on = ['member_id'])\n NotIntrain = raw[raw.game_id.isna()].member_id\n df = pd.DataFrame({'member_id': np.repeat(np.array(NotIntrain), 12, axis=0),\n 'game_id': HotGame * len(NotIntrain)})\n df['game_id'] = df['game_id'].astype('int64')\n #df = pd.concat([df, NotIntraindata])\n\n df = df.merge(test_data[['member_id', 'game_id', 'commissionable']],\n how = 'left',\n on = ['member_id', 'game_id'])\n df.commissionable = np.where(df.commissionable.isna(), 0, 1) #play as TP\n df.columns = ['member_id', 'game_id', 'TP']\n df.loc[:,'FP'] = 1 - df.TP\n\n aggregated = df[['member_id', 'TP']].groupby('member_id', as_index=False).sum()\n aggregated.loc[:,'FP_n'] = 12 - aggregated.TP\n aggregated.columns = ['member_id', 'TP_n', 'FP_n']\n grade0_memberid = aggregated[aggregated.TP_n == 0].member_id\n\n tmp = df[~df.member_id.isin(grade0_memberid)]\n tmp = tmp.merge(aggregated, how='left', on='member_id')\n tmp.loc[:,'TPR'] = tmp.TP / tmp.TP_n\n tmp.loc[:,'FPR'] = tmp.FP / tmp.FP_n\n auc_df = tmp[['member_id', 'TPR', 'FPR']].groupby(['member_id']).apply(lambda x:metrics.auc(np.cumsum(x.FPR), np.cumsum(x.TPR)))\n \n auc_score = auc_df.sum()/len(np.unique(df.member_id))\n \n return (auc_score)\n\n\ndef Get_Precision(df, test_df):\n data = df.copy()\n data = data.merge(test_df[['member_id', 'game_id', 'commissionable']],\n how = 'left',\n on = ['member_id', 'game_id'])\n data.commissionable = np.where(data.commissionable.isna(), 0, 1)\n \n Precision = sum(data.commissionable)/len(data.commissionable)\n\n return Precision\n\ndef Get_Recall(df, test_df):\n data = df.copy()\n test = test_df.copy()\n test_intrain = test[test.member_id.isin(data.member_id)]\n data.loc[:, 'Recommend'] = 1\n test_intrain = test_intrain.merge(data[['member_id', 'game_id', 'Recommend']],\n how = 'left',\n on = ['member_id', 'game_id'])\n test_intrain.Recommend = np.where(test_intrain.Recommend.isna(), 0, 1)\n group = test_intrain[['member_id', 'game_id', 'Recommend']].groupby(['member_id']).apply(lambda x:(sum(x.Recommend))/(len(x.member_id)))\n \n Recall = sum(group)/len(np.unique(test_intrain.member_id))#sum(test_intrain.Recommend)/len(test_intrain.Recommend)\n \n return Recall\n\n" }, { "alpha_fraction": 0.5795847773551941, "alphanum_fraction": 0.5967622399330139, "avg_line_length": 42.9782600402832, "blob_id": "3dbe69b1c9d8627ec23fa4a8f2988aba3f612864", "content_id": "37532fcd4a545ac11ffee3b95ec60e251e861423", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8102, "license_type": "no_license", "max_line_length": 156, "num_lines": 184, "path": "/RecommendationEngine_Python/Optimization/DS_SQLGetDF_function.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 16 08:51:28 2019\n\n@author: DS.Tom\n\"\"\"\n\nimport pyodbc\nimport pandas as pd\nimport logging\nimport time\nimport datetime\nfrom dateutil.relativedelta import relativedelta\n'''\nfrom sklearn.utils import resample\nfrom scipy.spatial.distance import cdist\nfrom functools import reduce\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.application import MIMEApplication\nfrom email.mime.multipart import MIMEMultipart\n'''\n\n\n'''\nFunction Zone\n'''\n\nclass DB:\n def __init__(self, driver, server, uid, pwd):\n self.driver = driver\n self.server = server\n self.uid = uid\n self.pwd = pwd\n self.conn = None\n self.cur = self.__getConnect()\n \n def __getConnect(self):\n try:\n self.conn = pyodbc.connect(driver=self.driver,\n server=self.server,\n uid=self.uid,\n pwd=self.pwd, ApplicationIntent='READONLY')\n cur = self.conn.cursor()\n except Exception as ex:\n logging.error('SQL Server connecting error, reason is: {}'.format(str(ex)))\n return cur\n \n def ExecQuery(self, sql):\n #cur = self.cur #__getConnect()\n try:\n df = pd.read_sql_query(sql,self.conn)\n except pyodbc.Error as ex:\n logging.error('SQL Server.Error: {}'.format(str(ex)))\n #cur.close()\n #self.conn.close() \n return df\n \n def Executemany(self, sql, obj):\n cur = self.__getConnect()\n try:\n cur.executemany(sql, obj)\n self.conn.commit()\n except pyodbc.Error as ex:\n logging.error('SQL Server.Error: {}'.format(str(ex)))\n cur.close()\n self.conn.close()\n \n def ExecNoQuery(self, sql):\n cur = self.__getConnect()\n try:\n cur.execute(sql)\n self.conn.commit()\n except pyodbc.Error as ex:\n logging.error('SQL Server.Error: {}'.format(str(ex)))\n cur.close()\n self.conn.close()\n\n\ndef to_sql_set(gametypesourceid):\n string = 'select {} as gametypesourceid'.format(gametypesourceid[0])\n S = gametypesourceid[1:]\n for elem in S:\n string += ' union select {}'.format(elem)\n return string\n\n#讀取對照表\ndef select_from_sql(now, current_day, serverip):\n def get_target():\n IP191 = DB('SQL Server Native Client 11.0', '10.80.16.191', 'DS.Reader', keyring.get_password('191','DS.Tom'))\n chart = IP191.ExecQuery(\"select * from [BalanceOutcome].[dbo].[LookUpTable]\")\n Exclude_rawdatatype = [35, 67, 68, 136]# Mako said that there aren't unique gameaccount in these gamehall(rawdatatype)\n\n target = chart[~chart['GameTypeSourceId'].isin(Exclude_rawdatatype)].copy()\n target = target[target['ServerIP'] == serverip].reset_index()\n\n target['DBName_sql'] = target.apply(lambda row: \n str(row['DBName'])\n + now[2:4]\n + now[5:7] if row['MonthDB'] else row['DBName'], axis=1)\n previous_month = (datetime.datetime.strptime(now, \"%Y-%m-%d %H:00:00.000\") \n - relativedelta(months=1)).strftime(\"%Y-%m-%d %H:00:00.000\")\n target['DBName_sql_previous_month'] = target.apply(lambda row: \n str(row['DBName'])\n + previous_month[2:4]\n + previous_month[5:7] if row['MonthDB'] else row['DBName'], axis=1)\n return target\n \n def SQL_timezone_sqlstring(row):\n DBName_sql = row['DBName_sql']\n RawDataType = row['Type']\n return \"SELECT [Timezone] FROM {DB}.[dbo].[VW_RawDataInfo] \\\n where type = {type}\".format(DB = DBName_sql, type = RawDataType)\n \n def SQL_timezone_value(row):\n Server = row['ServerIP']\n IP = DB('SQL Server Native Client 11.0', Server, 'DS.Reader', '8sGb@N3m')\n sqlstring = row['timezone_sqlstring']\n df = IP.ExecQuery(sqlstring)\n #result = df.Timezone\n return df['Timezone'].iloc[0]\n\n def SQL_EndTime(row, nowutc):\n Delta = row['timezone_value']\n End_time = (datetime.datetime.strptime(nowutc, \"%Y-%m-%d %H:00:00.000\") + datetime.timedelta(hours = Delta)).strftime(\"%Y-%m-%d %H:00:00.000\")\n return End_time\n \n def SQL_StartTime(row, delta):\n End_time = row['End_Table_time']\n Start_time = (datetime.datetime.strptime(End_time, \"%Y-%m-%d %H:00:00.000\") + datetime.timedelta(hours = delta)).strftime(\"%Y-%m-%d %H:00:00.000\")\n return Start_time\n\n def SQL_data(row, current_day):\n #variable zone\n game = row['GameTypeSourceId']\n current_db = row['DBName_sql']\n previous_db = row['DBName_sql_previous_month']\n table_name = 'VW_'+row['TableName']\n endtime = row['End_Table_time']\n starttime = row['Start_Table_time']\n \n Start_time = datetime.datetime.strptime(row['Start_Table_time'], \"%Y-%m-%d %H:00:00.000\")\n End_time = datetime.datetime.strptime(row['End_Table_time'], \"%Y-%m-%d %H:00:00.000\")\n Condition1 = (Start_time.month != End_time.month)\n Condition2 = row['MonthDB']\n if Condition1 & Condition2:\n sqlquery = \"SELECT '{date}' [Dateplayed], [GameAccount], [SiteId], {game} [GameTypeSourceId],\\\n Sum([Commissionable]) [Commissionable], Sum([WagersCount]) [WagersCount] \\\n FROM (SELECT [GameAccount], [SiteId], Isnull(Sum([betamount]), 0) [Commissionable], Count(1) [WagersCount]\\\n FROM {current_db}.[dbo].{table_name} (nolock) \\\n WHERE [wagerstime] >= '{starttime}' AND [wagerstime] <= '{endtime}' AND [gametypesourceid] = {game} \\\n GROUP BY [gameaccount], [siteid] HAVING Sum([betamount]) > 0\\\n UNION ALL SELECT [GameAccount], [SiteId], Isnull(Sum([betamount]), 0) \\\n [Commissionable], Count(1) [WagersCount] FROM {previous_db}.[dbo].{table_name} (nolock) \\\n WHERE [wagerstime] >= '{starttime}' AND [wagerstime] <= '{endtime}' AND [gametypesourceid] = {game} \\\n GROUP BY [gameaccount], [siteid] HAVING Sum([betamount]) > 0 )X GROUP BY [gameaccount], [siteid]\".\\\n format(date=current_day, game=game, current_db= current_db, table_name= table_name, \\\n endtime = endtime, starttime = starttime, previous_db= previous_db)\n else:\n sqlquery = \"SELECT '{date}' [Dateplayed], [GameAccount], [SiteId], [GameTypeSourceId],\\\n Isnull(Sum([betamount]), 0) [Commissionable], Count(1) [WagersCount] \\\n FROM {current_db}.dbo.{table_name} (nolock)\\\n WHERE [wagerstime] >= '{starttime}' AND [wagerstime] <= '{endtime}' and [gametypesourceid] = {game} \\\n GROUP BY [gameaccount], [siteid], [gametypesourceid] \\\n HAVING Sum([betamount]) > 0\".format(date=current_day, game=game, current_db= current_db,\\\n table_name= table_name, endtime = endtime, starttime = starttime)\n\n return sqlquery \n target = get_target()\n target_GroupByType = target[['ServerIP', 'Type', 'DBName_sql']].drop_duplicates()\n target_GroupByType = target_GroupByType.reset_index(drop = True)\n #target_GroupByType['timezone_sqlstring'], target_GroupByType['timezone_value'] = zip(*target_GroupByType.apply(lambda row: SQL_timezone2(row), axis=1))\n \n target_GroupByType.loc[:, 'timezone_sqlstring'] = target_GroupByType.apply(lambda row: SQL_timezone_sqlstring(row), axis=1)\n target_GroupByType.loc[:, 'timezone_value'] = target_GroupByType.apply(lambda row: SQL_timezone_value(row), axis=1)\n \n target = target.merge(target_GroupByType[['Type', 'timezone_value']],\n how = 'left',\n on = 'Type')\n target.loc[:, 'End_Table_time'] = target.apply(lambda row: SQL_EndTime(row, nowutc = now), axis=1)\n target.loc[:, 'Start_Table_time'] = target.apply(lambda row: SQL_StartTime(row, delta = -1), axis=1)\n target.loc[:, 'Sqlquery'] = target.apply(lambda row: SQL_data(row, current_day), axis=1)\n \n return target\n" }, { "alpha_fraction": 0.5259245038032532, "alphanum_fraction": 0.5437291860580444, "avg_line_length": 43.45217514038086, "blob_id": "0e5d1d1059466fe61ede7e531098e213779180c4", "content_id": "419d1c5cf18ef18fd91439dc4a82e94bf3338e4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5111, "license_type": "no_license", "max_line_length": 147, "num_lines": 115, "path": "/RecommendationEngine_Python/PythonProduction/Process_GetFinalResult.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport time\nimport datetime\nimport Connect_SQL as Connect_SQL\nimport Process_Function as func\nimport Parameter as parameter\nimport Judge_dailyquery_status as step1\n#import asyncio\npd.set_option('max_columns', None)\n\n\n'''\nVariable zone\n'''\nstart = time.time() \nJG = Connect_SQL.JG(); BalanceCenter_190 = Connect_SQL.BalanceCenter_190()\ntrain_start = (datetime.datetime.now()+datetime.timedelta(days = -parameter.Get_Finallist_Delta)).strftime(\"%Y-%m-%d 13:00:00.000\") \ntrain_end = datetime.datetime.now().strftime(\"%Y-%m-%d %H:00:00.000\")\ncurrent = datetime.datetime.now().strftime(\"%Y-%m-%d %H:00:00.000\") \n\nstep1.Judge_dailyquery_status(parameter.StatsTable_bytype,\n train_start,\n train_end, \n JG, \n sleep_sec=30, \n last_sec=30*60)\n \n# status table of CosineSimilarity\nRunning = pd.DataFrame({'Status_Result':'Running',\n 'Status_Default':'Running',\n 'UpDateTime':current}, index=[0])\n\nBalanceCenter_190.Executemany(\"insert into {table}(\\\n [Status_Result],[Status_Default], [UpDateTime]) values (?,?,?)\".format(table=parameter.ResultTable_Status), Running)\n \n\n#Get train & test with sql & ODBC\ntrain = func.get_data(BalanceCenter_190,\n parameter.DailyQueryTable_190,\n train_start,\n train_end)\ntrain_data = func.Pre_processing(train)\ndel(train)\n\n\n\n# filter & Exclude the just play one game people (Noise and it can't give our model any help)\ntrain_data = func.Pre_processing_train(train_data)\ngames = train_data.Game.unique()\ngameid2idx = {o:i for i,o in enumerate(games)}\n\n\n# Exclude the gamelist, connect_indirectly so far.\nexclude_game_list_raw, exclude_game_list = func.Exclude_Game(BalanceCenter_190,\n parameter.category_exclude,\n games,\n gameid2idx)\n\n\n# Define the hotgame list\ntrain_data_exclude = train_data[~train_data.Game.isin(exclude_game_list_raw)].reset_index(drop=True)\nHotGame_inTrain = func.Hot_Game(train_data_exclude, \n feature='Commissionable',\n n = 12)\nHotGame_df = pd.DataFrame({'Rank':range(1, 13),\n 'Game':HotGame_inTrain,\n 'UpDateTime':current})\n\nBalanceCenter_190.Executemany(\"insert into {table}(\\\n [Rank], [Game], [UpDateTime]) \\\n values (?,?,?)\".format(table=parameter.ResultTable_Default), HotGame_df)\nBalanceCenter_190.ExecNoQuery(\"UPDATE {table}\\\n SET Status_Default = 'Success' \\\n where UpDateTime = '{uptime}' and Status_Default = 'Running'\".format(table=parameter.ResultTable_Status,\n uptime=current))\n\nexe_time = (time.time() -start)\n\n\n'''\nvariable zone\n'''\n\ncs = BalanceCenter_190.ExecQuery(\"SELECT max(updatetime) updatetime FROM DataScientist.dbo.DS_RecommenderSystem_CSStatus\")\ncsupdate_time = cs.updatetime.iloc[0].strftime(\"%Y-%m-%d %H:00:00.000\")\n\n\nhotgame_ = BalanceCenter_190.ExecQuery(\" select max(updatetime) updatetime from {table}\".format(table=parameter.ResultTable_Default))\nhotgame_time = hotgame_.updatetime.iloc[0].strftime(\"%Y-%m-%d %H:00:00.000\")\n\n\nExecution_time = train_end\nKG = Connect_SQL.BalanceCenter_190()\nids = KG.ExecQuery(\" exec [Resultpool].[dbo].[RecommendationGeneratePersonalList] \\\n @execution_time='{execution_time}'\".format(execution_time=Execution_time))\n\nfor k in ids.firstletters: #@execution_time datetime, @selectinfo int, @hotgame_time datetime\n ids = KG.ExecNoQuery(\" exec [Resultpool].[dbo].[RecommendationGenerateResultPortion] \\\n @execution_time='{execution_time}',\\\n @selectinfo={letter},\\\n @hotgame_time='{hotgame_time}',\\\n @csupdate_time = '{csupdate_time}'\".format(\n letter = int(k), \n hotgame_time = hotgame_time, \n execution_time = Execution_time,\n csupdate_time = csupdate_time))\n print(k)\nExe_Time = (time.time() - start)\n\n\nBalanceCenter_190.ExecNoQuery(\"UPDATE {table} \\\n SET Status_Result = 'Success', [Exe_Time_sec] = {Exe_Time} \\\n where UpDateTime = '{uptime}' and Status_Result = 'Running'\".format(table=parameter.ResultTable_Status,\n Exe_Time=Exe_Time,\n uptime=current))" }, { "alpha_fraction": 0.6378485560417175, "alphanum_fraction": 0.6579772233963013, "avg_line_length": 34.988094329833984, "blob_id": "6117ccb370dc60c41a6852c374c42494178c91aa", "content_id": "414da851f291fe87bd77b9b0f116a98341b1f44d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 6061, "license_type": "no_license", "max_line_length": 140, "num_lines": 168, "path": "/RecommendationEngine_R/Code/Write_To_Db_Refactored.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "setClass('write_to_db',representation(conn ='RODBC',domain='logical', setdate = 'character'))\n\nsetMethod('initialize', 'write_to_db', function(.Object, production, setdate)\n{\n if (production == TRUE) {dbhandle = getHandle(new('connect_to_productionMSSQL'))}\n else { dbhandle = getHandle(new('connect_to_productionMSSQL')) }\n .Object@conn = dbhandle\n .Object@domain = production\n .Object@setdate = as.character(as.Date(setdate,'%Y-%m-%d'))\n return(.Object)\n})\n\nsetGeneric(\"cleanup_past\",function(Object,days){return(integer)})\nsetMethod(\"cleanup_past\",'write_to_db',function(Object,days)\n{\n if( days < 0) { return(0)}\n query = paste0(\"delete from [DataScientist].[dbo].[IntelligentGame] where Date <= CONVERT(char(10),'\",\n as.character(as.Date(Object@setdate,'%Y-%m-%d')-days),\"',126)\")\n if (Object@domain == TRUE) {\n sqlQuery(Object@conn, query)\n return(1)\n } else {\n query = gsub('IntelligentGame','IntelligentGame_test',query)\n sqlQuery(Object@conn, query)\n return(query)\n }\n})\n\nsetGeneric(\"cleanup_today\",function(Object){return()})\nsetMethod(\"cleanup_today\",'write_to_db',function(Object)\n{\n query = paste0(\"delete from [DataScientist].[dbo].[IntelligentGame] where Date = '\",as.character(Object@setdate),\"'\")\n if (Object@domain == TRUE)\n {\n sqlQuery(Object@conn, query)\n } else {\n query = gsub('IntelligentGame','IntelligentGame_test',query)\n sqlQuery(Object@conn, query)\n return(query)\n }\n})\n\nsetGeneric('createTempDB',function(Object){return(integer)})\nsetMethod('createTempDB','write_to_db',function(Object){\n if (dim(sqlQuery(Object@conn,\"select * from tempdb..sysobjects where name='##tmp5848'\"))[1]==1)\n {\n sqlQuery(Object@conn,\"drop table ##tmp5848\")\n }\n tmp = Object@setdate\n query = c(\"select a.GameCode as id,a.RawDataType as category,b.id as [key],\n convert(nvarchar(20),a.RawDataType) + ',' + convert(nvarchar(20),a.GameCode) as [key2]\n into ##tmp5848 from [DataScientist].[dbo].[BetRecordMonthlySystemCodeGame] as a left join [DataScientist].[dbo].[GameType] as b\n on a.RawDataType=b.RawDataType and a.GameCode=b.GameCode\n group by a.RawDataType,a.GameCode,b.id order by a.RawDataType\")\n if( Object@domain == TRUE)\n {\n res = sqlQuery(Object@conn,query)\n return(1)\n } else {\n return(query)\n }\n \n})\n\n\n\nsetGeneric('updateKeys',function(Object){return(integer)})\nsetMethod('updateKeys','write_to_db',function(Object)\n{\n\n #CONVERT(char(10), GetDate(),126)\n query2 =paste(c(\"update ig set ig.rawdatatype = gt.category, ig.gamecode = gt.[id]\n from DataScientist.dbo.IntelligentGame ig join ##tmp5848 gt on ig.GameCode = gt.[key] where \n rawdatatype = 0 and date='\",as.character(Object@setdate),\"'\"),sep='',collapse='')\n if(Object@domain == TRUE)\n {\n res = sqlQuery(Object@conn,query2)\n } else {\n query2 = gsub('IntelligentGame','IntelligentGame_test',query2)\n res = sqlQuery(Object@conn,query2)\n return(query2)\n }\n return(1) \n})\n\n\nsetGeneric('insert_into_table',function(Object,gmm){return(integer)})\nsetMethod('insert_into_table','write_to_db',function(Object,gmm)\n{\n sqlString = \"insert into [DataScientist].[dbo].[IntelligentGame] values \"\n body = paste(paste(\"('\",gmm[,2],\"',0,'\",gmm[,3],\"','\",\n apply( gmm[,c(4:13)],1,paste,sep=\"\",collapse=\"','\"),\"')\",sep=\"\"),sep=\"\",collapse=\",\")\n FullString = paste0(sqlString,body)\n if (Object@domain == TRUE)\n {\n sqlQuery(Object@conn, FullString)\n return(1)\n } else {\n FullString = gsub('IntelligentGame','IntelligentGame_test',FullString)\n sqlQuery(Object@conn, FullString)\n return(FullString)\n }\n})\n\nsetGeneric('write_to_table', function(Object,Dataset){ return(integer)})\nsetMethod('write_to_table','write_to_db',function(Object,Dataset)\n{\n cleanup_today(Object)\n cleanup_past(Object,10)\n times=ceiling(nrow(Dataset)/1000)\n for (i in 1:times) {\n #1000 records at a time\n if(i!=times){gmm = Dataset[c((i*1000-999):(i*1000)),]}\n else{gmm=Dataset[c((i*1000-999):nrow(Dataset)),]}\n tryCatch({insert_into_table(Object,gmm)}, error= function(e){\n loginfo(paste0(\"Error in inserting the data:\",e), logger='highlevel.module')\n })\n }\n createTempDB(Object)\n updateKeys(Object)\n updateTables(Object)\n return(1)\n})\n\nsetGeneric('createTempDB',function(Object){return(integer)})\nsetMethod('createTempDB','write_to_db',function(Object)\n{\n if (dim(sqlQuery(Object@conn,\"select * from tempdb..sysobjects where name='##tmp5848'\"))[1]==1)\n {\n sqlQuery(Object@conn,\"drop table ##tmp5848\")\n }\n tmp = Object@setdate\n query = c(\"select a.GameCode as id,a.RawDataType as category,b.id as [key],\n convert(nvarchar(20),a.RawDataType) + ',' + convert(nvarchar(20),a.GameCode) as [key2]\n into ##tmp5848 from [DataScientist].[dbo].[BetRecordMonthlySystemCodeGame] as a left \tjoin [DataScientist].[dbo].[GameType] as b\n on a.RawDataType=b.RawDataType and a.GameCode=b.GameCode\n group by a.RawDataType,a.GameCode,b.id order by a.RawDataType\")\n if (Object@domain == TRUE)\n {\n res = sqlQuery(Object@conn,query)\n } else {\n query = gsub('IntelligentGame','IntelligentGame_test',query)\n sqlQuery(Object@conn, query)\n return(query)\n } \n})\n\n\n\nsetGeneric('updateTables', function(Object,Dataset){ return(integer)})\nsetMethod('updateTables','write_to_db',function(Object)\n{\n updatequery = paste(\"update ig set ig.Top\",c(1:10),\"Game = gt.key2 from DataScientist.dbo.IntelligentGame ig\n join ##tmp5848 gt on ig.Top\",c(1:10),\"Game = gt.[key] where \n ig.Date='\", Object@setdate,\"' \n and charindex(',',ig.Top\",c(1:10),\"Game) = 0;\",sep='',collapse='')\n sqlQuery(Object@conn,updatequery)\n if (Object@domain == TRUE)\n {\n res = sqlQuery(Object@conn,updatequery)\n return(1) \n } else {\n updatequery = gsub('IntelligentGame','IntelligentGame_test',updatequery)\n sqlQuery(Object@conn, updatequery)\n return(updatequery)\n }\n} \n) \n\n\n" }, { "alpha_fraction": 0.547831118106842, "alphanum_fraction": 0.5806824564933777, "avg_line_length": 48.68390655517578, "blob_id": "ad515dbb5bb13a14f3a14d00a9fa63e0e7e00cb8", "content_id": "bc1972604403dc22ff218d5ee011c39dcb2e82f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 8645, "license_type": "no_license", "max_line_length": 205, "num_lines": 174, "path": "/RecommendationEngine_R/Code/Data_Counts_In.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "\nsetClass('getMSSQL_counts_data',representation( conn='RODBC', domain = 'logical', mock = 'logical', timestamp = \"character\"))\nsetGeneric('getRecommendationSet', function(object,...){ return(data.frame)})\nsetGeneric('getControlSet', function(object,...){return(data.frame)})\nsetGeneric(\"getHotSet\",function(object,...){return(data.frame)})\nsetGeneric(\"getTimeLastUpdatedDB\",function(object,...){return(character)})\nsetGeneric(\"setTimeLastUpdatedDB\",function(object,...){return(object)})\n\n\n\nsetMethod('initialize', 'getMSSQL_counts_data', function(.Object, production, mock=FALSE )\n{\n if (mock == TRUE) \n {\n a =0\n attr(a,'class') = 'RODBC'\n .Object@domain = production\n .Object@mock = TRUE\n .Object@conn = a\n .Object@timestamp = '2018-11-03'\n return(.Object)\n }\n if (production == TRUE) {dbhandle = getHandle(new('connect_to_productionMSSQL'))}\n else { dbhandle = getHandle(new('connect_to_testMSSQL')) }\n .Object@conn = dbhandle\n .Object@domain = production\n return(.Object)\n})\n\nsetGeneric('mock_getRecommendationSet',function(object,days){return(data.frame())})\nsetGeneric('mock_getControlSet',function(object,days){return(data.frame())})\nsetGeneric('mock_getHotSet',function(object,days){return(data.frame())})\nsetGeneric('getExcludedCategories', function(object){return(data.frame())})\n\n\nsetMethod('getRecommendationSet',signature ='getMSSQL_counts_data', function(object, days = 30)\n{\n if (class(days) != 'numeric'){ return(data.frame())}\n if (days %%1 != 0){ return(data.frame())}\n \n if (object@domain != FALSE){\n recommend=sqlQuery(object@conn, \n paste0(\"select convert(int,rank() over( order by( convert(nvarchar(30),a.MemberId) + a.Systemcode))) MemberId,a.CategoryId,a.GameCode as GameTypeId , b.id as [key], a.Counts as count\n from [DataScientist].[dbo].[BetRecordMonthlySystemCodeGame] as a left join [DataScientist].[dbo].[GameType] as b\n on a.RawDataType=b.RawDataType and a.GameCode=b.GameCode where a.First30Days='\", as.character(object@timestamp),\n \"' AND b.id IS NOT NULL order by a.MemberId\"))\n } else {\n recommend=sqlQuery(object@conn, paste0(\"select convert(int,rank() over( order by( convert(nvarchar(30),a.MemberId) + a.Systemcode))) MemberId,a.CategoryId,a.GameCode as GameTypeId ,\n b.id as [key], a.Counts as count,a.RawDataType\n from [DataScientist].[dbo].[BetRecordMonthlySystemCodeGame] as a left join [DataScientist].[dbo].[GameType] as b\n on a.RawDataType=b.RawDataType and a.GameCode=b.GameCode where a.First30Days='\", as.character(object@timestamp),\n \"' AND b.id IS NOT NULL order by a.MemberId\"))\n }\n recommend[,'MemberId'] = as.integer(recommend[,'MemberId'])\n print( class(recommend[,'MemberId']) )\n return(recommend[,c('MemberId','key','count')])\n })\n\nsetMethod('mock_getRecommendationSet',signature = 'getMSSQL_counts_data',function(object,days=30)\n{\n recommendation = data.frame(\n rbind(\n c(1,1,5),\n c(1,3,3),\n c(1,5,4),\n c(1,6,2),\n c(1,9,4),\n c(2,1,3),\n c(2,2,4),\n c(2,4,5),\n c(2,5,4),\n c(2,8,2),\n c(2,10,3),\n c(3,1,1),\n c(3,2,4),\n c(3,3,3),\n c(3,6,5),\n c(3,11,4),\n c(4,7,1),\n c(4,6,4),\n c(5,7,1),\n c(5,8,5),\n c(6,9,2),\n c(6,11,4),\n c(7,10,2)))\n colnames(recommendation) = c('MemberId','key','count')\n recommendation$key = as.factor(recommendation$key)\n return(recommendation)\n})\t\t\t\n\n\nsetMethod('getControlSet', signature ='getMSSQL_counts_data',\n function(object, days = 30)\n {\n if (class(days) != 'numeric'){ return(data.frame())}\n if (days %%1 != 0){ return(data.frame())}\n if (object@domain == FALSE){\n control=sqlQuery(object@conn, paste0(\"select distinct a.GameCode as id,a.CategoryId as category,b.id as [key],a.RawDataType \n from [DataScientist].[dbo].[BetRecordMonthlySystemCodeGame] as a left join [DataScientist].[dbo].[GameType] as b\n on a.RawDataType=b.RawDataType and a.GameCode=b.GameCode where First30Days= '\", as.character(object@timestamp),\n \"' and b.id is not NULL order by a.CategoryId\"))\n } else {\n control=sqlQuery(object@conn, paste0(\"select distinct a.GameCode as id,a.CategoryId as category,b.id as [key],a.RawDataType \n from [DataScientist].[dbo].[BetRecordMonthlySystemCodeGame] as a left join [DataScientist].[dbo].[GameType] as b\n on a.RawDataType=b.RawDataType and a.GameCode=b.GameCode where First30Days= '\", as.character(object@timestamp),\n \"' and b.id is not NULL order by a.CategoryId\"))\n } \n return(control[,c('id','category','key','RawDataType')])\n }\n )\n\nsetMethod('mock_getControlSet', signature = 'getMSSQL_counts_data',function(object,days=30)\n{\n return(data.frame(cbind(\n id = c('alm','alk','all','alp','alq','qls'),\n category = c('a','ab','a','ab','a','ab'),\n key = c(1,2,3,4,5,6,7,8,9,10,11,15),\n RawDataType= c('1','2','1','3','3','4','5','4','3','9','8','5')\n )))\n})\t\t\n\n\nsetMethod('getHotSet', signature='getMSSQL_counts_data',\n function(object,days=30)\n {\n if(class(days) != 'numeric'){return(data.frame())}\n if(days %%1 != 0){return(data.frame())}\n if (object@domain != FALSE)\n {\n hot = sqlQuery(object@conn, paste0(\"select a.[CategoryId],a.GameCode ,b.id, a.[counts] from (select top 10 CategoryId,[RawDataType],[GameCode],COUNT(*) as [counts]\n from [DataScientist].[dbo].[BetRecordMonthlySystemCodeGame] where First30Days = '\",as.character(object@timestamp),\"' \n and RawDataType not in (1,2,3,4,16,17,22,23,24,28,29,36,42,79,80)\n group by CategoryId,[RawDataType],[GameCode]\n order by [counts] desc) as a left join [DataScientist].[dbo].[GameType] as b\n on a.RawDataType=b.RawDataType and a.GameCode=b.GameCode and b.id is not NULL order by a.[counts] desc\") ) \n } else {\n hot = sqlQuery(object@conn, paste0(\"select a.[CategoryId],a.GameCode ,b.id, a.[counts] from (select top 10 CategoryId,[RawDataType],[GameCode],COUNT(*) as [counts]\n from [DataScientist].[dbo].[BetRecordMonthlySystemCodeGame] where First30Days = '\",as.character(object@timestamp),\"'\n and and RawDataType not in (1,2,3,4,16,17,22,23,24,28,29,36,42,79,80)\n group by CategoryId,[RawDataType],[GameCode]\n order by [counts] desc) as a left join [DataScientist].[dbo].[GameType] as b\n on a.RawDataType=b.RawDataType and a.GameCode=b.GameCode and b.id is not NULL order by a.[counts] desc\") ) \n }\n return(hot[,c('id','counts')])\n })\n\t\t \nsetMethod('mock_getHotSet',signature='getMSSQL_counts_data',function(object,days=30)\n{\n return( data.frame(cbind( id= c(6,4,3,2,5,8,9,10,11,1),counts=c(11,9,8,7,6,5,4,3,2,1)))) \n})\t\n\nsetMethod(\"setTimeLastUpdatedDB\",signature='getMSSQL_counts_data',function(object)\n{\n\tdata = sqlQuery(object@conn,\"SELECT max(First30Days) as date FROM [DataScientist].[dbo].[BetRecordMonthlySystemCodeGame]\")\n\tobject@timestamp = as.character(data[[1]])\n\treturn(object)\n})\n\nsetMethod(\"getTimeLastUpdatedDB\",signature='getMSSQL_counts_data',function(object)\n{\n time = object@timestamp\n\treturn(time)\n})\n\nsetMethod(\"getExcludedCategories\", signature='getMSSQL_counts_data', function(object)\n{\n return(data.frame(\n gamesupplier = c(1,1,1,1,1,1,6,6,6,6,9,9,9,11,11),\n rawdatatype = c(1,2,3,4,42,79,16,17,36,80,22,23,24,28,29),\n urltext = c('BB','BB','BB','BB','BB','BB','AG','AG','AG','AG','MG','MG','MG','PT','PT'),\n discountname = c('BBINbbsport', 'BBINvideo','BBINprobability','BBINlottery','BBINFish30','BBINFish38',\n 'AgBr','AgEbr','AgHsr','AgYoPlay','Mg2Real','Mg2Slot','Mg2Html5','Pt2Real','Pt2Slot')\n ))\n}\n)" }, { "alpha_fraction": 0.6079874038696289, "alphanum_fraction": 0.6200735569000244, "avg_line_length": 45.414634704589844, "blob_id": "75d2d845fc5889d5745c4c3e37108134826391dc", "content_id": "5aa82750bef7f3949057fe705c6522214b841288", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1903, "license_type": "no_license", "max_line_length": 106, "num_lines": 41, "path": "/RecommendationEngine_R/Code/Initializer.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "setClass('Recommendation_Configuration', representation( validation = 'logical', valpct = 'numeric', \n testpct = 'numeric', games_to_select = 'numeric',\n cutoff = 'numeric', production = 'logical'))\n\nsetMethod('initialize', 'Recommendation_Configuration', function(.Object, validation = FALSE, valpct= 10, \n testpct = 5, games_to_select = 10,\n cutoff = 0.1, production = TRUE)\n{\n validObject(.Object)\n if(valpct > 100){ print(\"Validation over 100\")}\n if(valpct < 0) {print(\"Validation can't be negative\")}\n if(testpct > 100) {print(\"Testpct over 100\")}\n if(testpct < 0) {print(\"Testpct can't be negative\")}\n if(games_to_select < 0) {stop(\"cannot be negative\")}\n \n if(cutoff < 0) {stop(\"cannot be negative\")}\n .Object@validation = validation\n .Object@valpct = valpct\n .Object@testpct = testpct\n .Object@games_to_select = floor(games_to_select)\n .Object@cutoff = cutoff\n .Object@production = production\n validObject(.Object)\n return(.Object)\n})\n\nsetGeneric('testValidation', function(object){return(boolean)})\nsetMethod('testValidation','Recommendation_Configuration', function(object){return(object@validation)})\n\nsetGeneric('getParameters', function(object){return(boolean)})\nsetMethod('getParameters','Recommendation_Configuration', \n function(object){\n if (testValidation(object))\n { return(list(validation = object@valpct, test = object@testpct))}})\n\n\nsetGeneric('getPostProcessingSettings', function(object){return(list)})\nsetMethod('getPostProcessingSettings', 'Recommendation_Configuration', function(object)\n{\n return(list('games_to_select' = object@games_to_select, 'cutoff' = object@cutoff))\n})\n" }, { "alpha_fraction": 0.7524725794792175, "alphanum_fraction": 0.7612937688827515, "avg_line_length": 42.488372802734375, "blob_id": "831694c6af7af9ff9da87747875a9614e4ea3ed5", "content_id": "1d55133bcbc12e60d2d2911b19862e53d02bc35c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 3741, "license_type": "no_license", "max_line_length": 112, "num_lines": 86, "path": "/RecommendationEngine_R/Introduce.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "rm(list = ls())\n\nsource('GlobalConfig.R')\nlogger_database = new('Log_To_Database','Recommendation_Engine',opt$production)\n\nloginfo(\"Starting to process:\",logger='highlevel.module')\n\nconfig = new('Recommendation_Configuration', cutoff = 0.1, production = opt$production)\nloginfo(toString(names(unlist(attributes(config)))), logger='debugger.module')\nloginfo(toString(unlist(attributes(config))), logger='debugger.module')\n\ndmm = new('preprocessing_counts')\nloginfo(\"Starting to process:\",logger='highlevel.module')\ndmm = getvalidatedDataSets(dmm,TRUE)\nlogger_database = set_timestamp(logger_database,getTimeLastUpdated(dmm))\nlog_to_database(logger_database,paste0(\"Processing: Queried\"))\ndmm = preprocess(dmm)\nloginfo(\"Data Successfully removed from the database:\",logger='highlevel.module')\nloginfo(paste(\"Current required memory:\",pryr::mem_used() / 10^6,sep=''),logger='highlevel.module')\nGames = getGames(dmm)\nExcludedlist = getExcluded(dmm)\nlog_to_database(logger_database,paste0(\"PreProcessed:\",length(Games)))\n\nMembers = getMembers(dmm)\nDatasets = getRecommendation(dmm)\n\nlast_updated = getTimeLastUpdated(dmm)\nControlset = getControl(dmm)\nHot = getHot(dmm)\n\n###to implement\nif(testValidation(config)){ \n dist = getParameters(config)\n sets = assign_to_sets(Games = Games,Members = Members, Datasets = Datasets, parameters = dist)\n Dataset = toSparse(sets$Recommendationset)\n} else {\n dist = FALSE\n Dataset = getSparse(dmm)\n}\n\nloginfo(\"Data Successfully assigned to sets:\",logger='highlevel.module')\nloginfo(paste(\"Current required memory:\",pryr::mem_used() / 10^6,sep=''),logger='highlevel.module')\n\nrm(dmm)\nrm(Datasets)\nloginfo(\"Deleted dmm\",logger='debugger.module')\nloginfo(paste(\"Current required memory:\",pryr::mem_used() / 10^6,sep=''),logger='debugger.module')\nlog_to_database(logger_database,paste0(\"Assigned_Sets:\",length(Games)))\n\nDistance = new('CosineDistancecalculator')\ndistance_matrix = calculate_distance(Distance,Dataset,Games)\nloginfo(\"Distance matrix calculated:\",logger='highlevel.module')\nloginfo(paste(\"Current required memory:\",pryr::mem_used() / 10^6,sep=''),logger='highlevel.module')\nloginfo(paste0(\"Dimension of distance matrix:\",toString(dim(distance_matrix))), logger='debugger.module')\nlog_to_database(logger_database,paste0(\"Distances:\",dim(distance_matrix[1])))\n\n\n#how to deal with games that are removed from the dataset by sampling the dataset\npost_processing_settings = getPostProcessingSettings(config)\noutputmatrix = new('post_processing',post_processing_settings,Hot, last_updated)\nrecommendations = postProcess(outputmatrix, distance_matrix, Controlset)\nlog_to_database(logger_database,paste0(\"post_processed:\",dim(outputmatrix)[1]))\n\n\nrm(distance_matrix)\nrm(Dataset)\nloginfo(\"Postprocessing is done:\",logger='debugger.module')\nloginfo(paste(\"Current required memory:\",pryr::mem_used() / 10^6,sep=''),logger='debugger.module')\n\n\n###to implement\nif(testValidation(config)){ \n\n validation = new('Validator', dataset= toSparse(sets$Validationset), target = recommendations)\n coverage = get_games_width(validation, post_processing_settings)\n outputstats = SensitivityRec(validation, post_processing_settings)\n loginfo(paste0(\"Validation,coverage:\",paste0(coverage,collapse=',')), logger='highlevel.module')\n loginfo(paste0(\"Validation,precision:\",paste0(outputstats$precision,collapse=',')), logger='highlevel.module')\n loginfo(paste0(\"Validation,recall:\",paste0(outputstats$recall,collapse=',')), logger='highlevel.module')\n} \n\n\nwrite_out = new('write_to_db', config@production, last_updated)\nwrite_to_table(write_out,recommendations)\nloginfo(\"Process Completed:\",logger='highlevel.module')\nlog_to_database(logger_database,paste0(\"Completed:\",dim(recommendations)[1]))\n\n" }, { "alpha_fraction": 0.6089359521865845, "alphanum_fraction": 0.6434822678565979, "avg_line_length": 28.351350784301758, "blob_id": "5215377cfc20f515dd9c9b4c185c7898ee651cb1", "content_id": "a558a9e35c292f717024c48e75dc34f6883a8a06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2171, "license_type": "no_license", "max_line_length": 91, "num_lines": 74, "path": "/RecommendationEngine_Python/Optimization/Optimization_Queue.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "import asyncio\nimport time\n\n\nimport os\n#os.chdir('C://Users//DS.Jimmy//Desktop//Project//RecommenderSystem')\nimport datetime\nimport DS_SQLGetDF_function as func\n\n\nstarted_at = time.monotonic()\n\nServer_list = ['10.80.16.191', '10.80.16.192', '10.80.16.193', '10.80.16.194']\nServer = Server_list[3]\n\n#main parameter\nnow = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:00:00.000\") #UTC+0\ncurrent = datetime.datetime.now().strftime(\"%Y-%m-%d %H:00:00.000\") \nSQLQuery_df = func.select_from_sql(now, current, Server)\nJG = func.DB('SQL Server Native Client 11.0', 'JG\\MSSQLSERVER2016', 'DS.Jimmy', '4wvb%ECX')\nIP = func.DB('SQL Server Native Client 11.0', Server, 'DS.Reader', '8sGb@N3m')\n\n\n\n\nasync def worker(name, queue):\n IP = func.DB('SQL Server Native Client 11.0', Server, 'DS.Reader', '8sGb@N3m')\n while True:\n # Get a \"work item\" out of the queue.\n sleep_for = await queue.get()\n print(queue.qsize())\n # Sleep for the \"sleep_for\" seconds.\n try:\n df = IP.ExecQuery(sleep_for)\n except:\n pass\n #print(df)\n # Notify the queue that the \"work item\" has been processed.\n queue.task_done()\n\n\n\nasync def main():\n # Create a queue that we will use to store our \"workload\".\n queue = asyncio.Queue()\n\n # Generate random timings and put them into the queue.\n total_sleep_time = 0\n for index in SQLQuery_df.Sqlquery:\n queue.put_nowait(index)\n\n # Create three worker tasks to process the queue concurrently.\n tasks = []\n for i in range(3):\n task = asyncio.create_task(worker(f'worker-{i}', queue))\n tasks.append(task)\n\n # Wait until the queue is fully processed.\n started_at = time.monotonic()\n await queue.join()\n total_slept_for = time.monotonic() - started_at\n\n # Cancel our worker tasks.\n for task in tasks:\n task.cancel()\n # Wait until all worker tasks are cancelled.\n await asyncio.gather(*tasks, return_exceptions=True)\n\n print('====')\n print(f'3 workers slept in parallel for {total_slept_for:.2f} seconds')\n print(f'total expected sleep time: {total_sleep_time:.2f} seconds')\n\n\nasyncio.run(main())" }, { "alpha_fraction": 0.6994985342025757, "alphanum_fraction": 0.7035670280456543, "avg_line_length": 39.953487396240234, "blob_id": "f38134e7a05f2ca78c99f08dda3ef2282b9fbc58", "content_id": "2725176249c506fdb43e08139cde7efa4929b8ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 10569, "license_type": "no_license", "max_line_length": 130, "num_lines": 258, "path": "/RecommendationEngine_R/Code/Preprocessing.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "###Ideally Use A singleton Pattern For DataAccess\n\n\n\nsetClass('preprocessing', representation(Recommendationset = \"data.frame\", control = \"data.frame\",\n Hot = \"data.frame\",timestamp=\"character\", Exclusions = 'data.frame',\n Members = 'vector', Games = 'vector', Sparse = 'dgCMatrix'))\nsetClass('preprocessing_counts', contains = 'preprocessing' )\n\nsetMethod('initialize','preprocessing',function(.Object){\n .Object@Recommendationset = data.frame(MemberId = integer(),\n key = factor(),\n count = numeric(),\n stringsAsFactors = TRUE)\n .Object@Hot = data.frame(id = integer(), counts=integer())\n .Object@control = data.frame(id = integer(), category = factor(), key = factor(),RawDataType=factor(), stringsAsFactors = FALSE)\n .Object@Exclusions = data.frame(gamesupplier = integer(), rawdatatype = integer(),urltext = factor(), discountname=factor(),\n stringsAsFactors = FALSE)\n .Object@Members = vector()\n .Object@Games = vector()\n return(.Object)\n})\n\n\nsetGeneric('validateData', function(object,recommendation,control,Hot){ return(object)})\nsetGeneric('validateRecommendation',function(object,recommendation) {return(object)})\nsetGeneric('validateControl',function(object,recommendation,control){return(object)})\nsetGeneric('validateHot',function(object,recommendation,Hot){return(object)})\n\n\nsetMethod('validateRecommendation','preprocessing_counts',function(object,recommendation){\n if (!(sum(colnames(recommendation) == colnames(object@Recommendationset)\n ) == length(colnames(recommendation))))\n { \n loginfo(\"Headers recommendation incompatible\", logger='debugger.module')\n }\n #for (i in c(1:length(recommendation)))\n #{\n # if (class(object@Recommendationset[,i]) != class(recommendation[,i]))\n # {\n # loginfo(\"classes recommendation incompatible\", logger='debugger.module')\n # }\n #}\n if (length(unique(recommendation$key)) <= 1 ) \n {\n loginfo(\"Recommendationset has at most one game, what's the point\", logger='debugger.module')\n }\n object@Recommendationset = recommendation\n return(object)\n})\n\n\nsetMethod('validateControl','preprocessing_counts',function(object,recommendation,control)\n{\n if (!(sum(colnames(control) == colnames(object@control)) == length(colnames(control))))\n {\n\t loginfo(\"Headers Control incompatible\", logger='debugger.module')\n }\n #for (i in c(1:length(colnames(control))))\n #{\n # if (class(object@control[,i]) != class(control[,i]))\n # {\n\t # loginfo(\"classes control incompatible\", logger='debugger.module')\n # }\n #}\n if(sum(recommendation$key %in% control$key)==length(unique(recommendation$key)))\n {\n loginfo(\"Keys in Recommendation that are not in control\", logger='debugger.module')\n }\n if(sum(control$key %in% recommendation$key)==length(unique(recommendation$key)))\n {\n loginfo(\"Keys in Control that are not in Recommendation\", logger='debugger.module')\n }\n if(length(unique(control$category)) <=1)\n {\n loginfo(\"Only one key in control\", logger='debugger.module')\n }\n object@control = control\n return(object)\n})\n\n\n\nsetMethod('validateHot','preprocessing_counts',function(object,recommendation,Hot)\n{\n if (!(sum(colnames(Hot) == colnames(object@Hot)\n ) == length(colnames(Hot))))\n {\n \tloginfo(\"Headers Hot incompatible\",logger='debugger.module')\n }\n #for (i in c(1:length(Hot)))\n #{\n # if (class(object@Hot[,i]) != class(Hot[,i]))\n # {\n # loginfo(\"object Hot incompatible\",logger='debugger.module')\n\t # }\n #}\n if (length(Hot) > length(unique(recommendation$key)))\n {\n loginfo(\"Cannot have more Hot than movies in Recommendation\", logger='debugger.module') \n } else if (sum(!Hot$id %in% recommendation$key) > 1)\n {\n loginfo(\"Recommendations in Hot that are not Recommendations\", logger='debugger.module')\n }\n object@Hot = Hot\n return(object)\n})\n\n\nsetMethod('validateData', 'preprocessing_counts', function(object,recommendation,control,Hot){\n object = validateRecommendation(object,recommendation)\n object = validateControl(object,recommendation,control)\n object = validateHot(object,recommendation,Hot)\n return(object)\n})\n\n\n\nsetGeneric('getvalidatedDataSets', function(object,...){ return(object)})\nsetMethod('getvalidatedDataSets','preprocessing_counts', function(object, production){\n tryCatch({\n\tprocessor = new('getMSSQL_counts_data', production)\n }, error = function(e){\n logerror(\"Couldn't initialize a 'getMSSQL_counts_data' object\",logger='highlevel.module')\n\t return(\"object\")\n })\n tryCatch({ processor = setTimeLastUpdatedDB(processor)}, error = \n function(e) {logerror(\"Error in setting timestamp\", logger='highlevel.module'); stop()})\n tryCatch({ timestamp = getTimeLastUpdatedDB(processor)}, \n error = function(e) {logerror(\"error in getting timestamp\",logger='highlevel.module'); stop();})\n tryCatch({ recommendation = getRecommendationSet(processor) }, \n error = function(e) { print(\"error in getting recommendation data\",logger='highlevel.module'); stop();})\n tryCatch({ control = getControlSet(processor)}, \n error=function(e) {print(\"error in getting control data\",logger='highlevel.module'); stop();})\n tryCatch({ hot = getHotSet(processor)}, \n error = function(e) {print(\"error in getting hot data\", logger='highlevel.module'); stop();})\n tryCatch({ exclusions = getExcludedCategories(processor)}, \n error = function(e) {print(\"error in getting hot data\", logger='highlevel.module'); stop();})\n \n object@timestamp = timestamp\n #object@control = control\n #object@Recommendationset = recommendation\n #object@Hot = hot\n loginfo(paste(\"Object controls dim: \",toString(dim(control)),sep=\"\"),logger='debugger.module')\n loginfo(paste(\"Object Recommendations dim: \",toString(dim(recommendation)),sep=\"\"),logger='debugger.module')\n loginfo(paste(\"Object Hot dim: \",toString(dim(hot)),sep=\"\"),logger='debugger.module')\n loginfo(paste(\"currently required memory:\"),pryr::mem_used() / 10^6,logger='debugger.module')\n object = validateData(object,recommendation,control, hot)\n object@Exclusions = exclusions\n return(object)\n})\n\nsetGeneric('preprocess', function(object,...){ return(object)})\nsetMethod('preprocess','preprocessing_counts', function(object)\n{\n loginfo('preprocessing:_______________', logger='debugger.module')\n recommend = object@Recommendationset\n recommend1=recommend %>% group_by(MemberId) %>% dplyr::summarise(game=length(key))\n recommend1=recommend1[recommend1$game>1,] \n recommend4 =data.frame(left_join(recommend1,recommend,by='MemberId'))\n recommend4$key = as.character(recommend4$key)\n control = object@control\n loginfo(paste0('Reformatting Complete; Currently required memory',pryr::mem_used() / 10^6), logger='debugger.module')\n\n recommend4$cat <- as.numeric(as.factor(recommend4$MemberId))\n recommend4$gtd <- as.numeric(as.factor(recommend4$key))\n object@Members = sort(unique(recommend4$MemberId))\n object@Recommendationset = recommend4\n object@Games = sort(unique(recommend4$key))\n control$key=as.character(control$key)\n \n sparse_version = sparseMatrix(i=recommend4$cat,j=recommend4$gtd,x=as.numeric(recommend4$count))\n loginfo(paste0('Sparse Matrix Constructed; Currently required memory',pryr::mem_used() / 10^6), logger='debugger.module')\n loginfo(paste0(\"Dimension of the sparse matrix =\", dim(sparse_version)), logger='debugger.module')\n loginfo(paste0(\"Number of games =\", length(object@Games)), logger='debugger.module')\n loginfo(paste0(\"Number of games in control =\", length(object@control$key)), logger='debugger.module')\n loginfo(paste0(\"Amount of members =\", length(object@Members)), logger='debugger.module')\n object@Recommendationset = recommend4\n object@Sparse = sparse_version\n object@control = control[control$key %in% object@Games,]\n object@control = object@control[order(object@control$key),]\n object@control$idx = rownames(object@control)\n object@control[,'Exclusions'] = 0\n object@control[ object@control[,'RawDataType'] %in% object@Exclusions[,'rawdatatype'],'Exclusions'] = 1\n return(object)\n})\n\n\nsetGeneric('getRecommendation', function(object,...){ return(data.frame)})\nsetMethod('getRecommendation','preprocessing_counts', function(object)\n{\n return(object@Recommendationset)\n})\n\nsetGeneric('getSparse', function(object,...){ return(matrix)})\nsetMethod('getSparse','preprocessing_counts', function(object)\n{\n return(object@Sparse) \n})\n\nsetGeneric('getControl', function(object,...){ return(data.frame)})\nsetMethod('getControl','preprocessing_counts', function(object)\n{\n return(object@control)\n})\n\nsetGeneric('getGames', function(object,...){return(data.frame)})\nsetMethod('getGames','preprocessing_counts',function(object)\n{\n return(object@Games)\n})\n\nsetGeneric('getMembers', function(object,...){return(data.frame)})\nsetMethod('getMembers','preprocessing_counts',function(object)\n{\n return(object@Members)\n})\n\nsetGeneric('getHot', function(object,...){return(data.frame)})\nsetMethod('getHot', 'preprocessing_counts',function(object)\n{\n return(object@Hot)\n})\n\nsetGeneric(\"getTimeLastUpdated\", function(object,...){return(character)})\nsetMethod(\"getTimeLastUpdated\", 'preprocessing_counts',function(object)\n{\n return(object@timestamp)\n})\n\nsetGeneric(\"getExcluded\", function(object){return(data.frame)})\nsetMethod(\"getExcluded\", 'preprocessing_counts', function(object)\n{\n return(object@Exclusions) \n}\n)\n\nsetGeneric('mock_getvalidatedDataSets',function(object,production){return(object)})\nsetMethod('mock_getvalidatedDataSets','preprocessing_counts', function(object,production)\n{\n coll = new('getMSSQL_counts_data',TRUE,TRUE)\n object@timestamp = getTimeLastUpdatedDB(coll)\n object@Recommendationset = mock_getRecommendationSet(coll)\n object@control = mock_getControlSet(coll)\n object@Hot = mock_getHotSet(coll)\n object@Exclusions = getExcludedCategories(coll)\n return(object)\n})\n\nsetGeneric('mock_preprocessed',function(object){return(list)})\nsetMethod('mock_preprocessed','preprocessing_counts',function(object)\n{\n\tobject = mock_getvalidatedDataSets(object)\n\tobject = preprocess(object)\n\treturn(list(Games = object@Games, Sparse = object@Sparse, Recommendationset = object@Recommendationset, \n\t\t\t\tcontrol = object@control, Hot = object@Hot, timestamp = object@timestamp, Excludedlist = object@Exclusions))\n}\n)\n\n\n\n" }, { "alpha_fraction": 0.5166451334953308, "alphanum_fraction": 0.5339354872703552, "avg_line_length": 37.37623596191406, "blob_id": "2f6895bab265dcd9ce22a5c65a23312c504b8a34", "content_id": "60da75b70e8265d4928ad6c123b6d13285d70e9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3875, "license_type": "no_license", "max_line_length": 136, "num_lines": 101, "path": "/RecommendationEngine_Python/PythonProduction/Process_CosineSimilarity.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "import os\n\nimport pandas as pd\nimport time\nimport datetime\nimport Connect_SQL as Connect_SQL\nimport Parameter as parameter\nimport Process_Function as func\nimport Judge_dailyquery_status as step1\n#import asyncio\nimport nest_asyncio\nnest_asyncio.apply()\npd.set_option('max_columns', None)\n\n'''\nVariable zone\n'''\nJG, BalanceCenter_190 = Connect_SQL.JG(), Connect_SQL.BalanceCenter_190()\ntrain_start = (datetime.datetime.now()+ datetime.timedelta(days = -parameter.CS_Delta)).strftime(\"%Y-%m-%d 01:00:00.000\") \ntrain_end = datetime.datetime.now().strftime(\"%Y-%m-%d %H:00:00.000\")\ncurrent = datetime.datetime.now().strftime(\"%Y-%m-%d %H:00:00.000\") \n\n\n'''\nProcessing\n'''\n#Judge_dailyquery_status\nstart = time.time()\nstep1.Judge_dailyquery_status(parameter.StatsTable_bytype,\n train_start,\n train_end, \n JG, \n sleep_sec=30, \n last_sec=30*60)\n\n# status table of CosineSimilarity\nRunning = pd.DataFrame({'Status_CS':'Running',\n 'UpDateTime':current}, index=[0])\nBalanceCenter_190.Executemany(\"insert into {table}(\\\n [Status_CS], [UpDateTime]) values (?,?)\".format(table=parameter.MedianTable_CSStatusTable), Running)\n \n\n#Get data\ntrain = func.get_data(BalanceCenter_190,\n parameter.DailyQueryTable_190,\n train_start,\n train_end)\n\n#PreProcessing\ntrain_data = func.Pre_processing(train)\ndel(train)\n\n\n# filter & Exclude the just play one game people (Noise and it can't give our model any help)\ntrain_data = func.Pre_processing_train(train_data)\n\n#change to encoding\nusers, games = train_data.Membercode.unique(), train_data.Game.unique()\nuserid2idx, userid2Rraw, gameid2idx, gameid2iraw = func.Encoding_RS(users, games)\n\ntrain_data = func.Encoding_TrainData(train_data,\n userid2idx,\n gameid2idx)\n\nTrainset = func.get_Trainset(train_data)\ndel(train_data)\nprint(\"---GetData & PreProcessing cost %s seconds ---\" %(time.time() - start))\n\n\n#get cosine_sim dataframe\ncosine_sim = func.Cosine_Similarity(Trainset)\n\n# Exclude the gamelist, connect_indirectly so far.\nexclude_game_list_raw, exclude_game_list = func.Exclude_Game(BalanceCenter_190,\n parameter.category_exclude,\n games,\n gameid2idx)\n\ncosine_sim.drop(exclude_game_list,\n axis=1,\n inplace=True) \n\ncosine_sim_final = func.Summarized_cosine_sim_df(cosine_sim,\n gameid2iraw,\n current,\n exclude_game_list,\n n=12)\n\n#Insert result \nBalanceCenter_190.Executemany(\"insert into {table}(\\\n [Game], [CorrespondGame], [CosineSimilarity], [UpdateTime]) \\\n values (?,?,?,?)\".format(table=parameter.MedianTable_CSTable),\n cosine_sim_final)\n\nexe_time = ( time.time()- start )\nBalanceCenter_190.ExecNoQuery(\"UPDATE {table}\\\n SET Exe_Time_sec = {exe_time}, Status_CS = 'Success' \\\n where UpDateTime = '{uptime}' and Status_CS = 'Running'\".format(table=parameter.MedianTable_CSStatusTable,\n exe_time=exe_time, \n uptime=current))\nprint(\"----Total cost %s seconds ---\" % (exe_time))" }, { "alpha_fraction": 0.7718411684036255, "alphanum_fraction": 0.8144404292106628, "avg_line_length": 91.4000015258789, "blob_id": "7b2163be9ba0dc564144171d24704f6c988645cb", "content_id": "6fc6dba162dd4fc73f81b3da6c0a5325e7a45883", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1385, "license_type": "no_license", "max_line_length": 379, "num_lines": 15, "path": "/RecommendationEngine_R/Research/links.md", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "# Evaluation / Validation:\n\n## research papers\n1. [Common pitfalls in training and evaluating recommender\nsystems](https://www.kdd.org/exploration_files/19-1-Article3.pdf)\n2. [Evaluating Collaborative Filtering\nRecommender Systems](https://grouplens.org/site-content/uploads/evaluating-TOIS-20041.pdf)\n3. [Beyond Accuracy: Evaluating Recommender Systems \nby Coverage and Serendipity](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.464.8494&rep=rep1&type=pdf)\n4. [Evaluating Recommender Systems from the user's perspective, Survey of the state of the art](https://www.researchgate.net/profile/Pearl_Pu2/publication/257671650_Evaluating_recommender_systems_from_the_user's_perspective_Survey_of_the_state_of_the_art/links/541824cb0cf25ebee98807f5/Evaluating-recommender-systems-from-the-users-perspective-Survey-of-the-state-of-the-art.pdf)\n5. [A Survey of Accuracy Evaluation Metrics of Recommendation Tasks](http://jmlr.csail.mit.edu/papers/volume10/gunawardana09a/gunawardana09a.pdf)\n\n## quora answers\n1. [What offline evaluation metric for recommender systems better correlates with online AB test results](https://www.quora.com/What-offline-evaluation-metric-for-recommender-systems-better-correlates-with-online-AB-test-results)\n2. [What metrics are used for evaluating recommender systems](https://www.quora.com/What-metrics-are-used-for-evaluating-recommender-systems)" }, { "alpha_fraction": 0.6578086018562317, "alphanum_fraction": 0.668014645576477, "avg_line_length": 44.139129638671875, "blob_id": "d252b3195414c565a8ea310a7cd020034cc30e86", "content_id": "9394723bd0bd3079d2b61e7c84142b1af9383b21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 5193, "license_type": "no_license", "max_line_length": 161, "num_lines": 115, "path": "/RecommendationEngine_R/Code/postprocessing.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "setClass('post_processing',representation(cutoff ='numeric', games_to_select = 'integer', \n hot = 'data.frame', lastupdated='character',\n Excluded = 'data.frame'))\n\nsetMethod('initialize', 'post_processing', function(.Object, configuration, hot, lastupdated)\n{\n if (!is.numeric(configuration['games_to_select']) || (!is.numeric(confiration['cutoff'])))\n {\n .Object@cutoff = 0.1\n .Object@games_to_select = as.integer(10)\n .Object@hot = hot\n .Object@lastupdated = lastupdated\n return(.Object)\n }\n if(round(configuration['games_to_select']) == configuration['games_to_select'])\n {\n .Object@games_to_select = as.integer(configuration['games_to_select'])\n }\n .Object@cutoff = confiration['cutoff']\n return(.Object)\n})\n\nsetGeneric('postProcess',function(.Object,dataset,...){return(data.frame)})\nsetMethod('postProcess','post_processing', function(.Object, dataset, games)\n{\n vects = t(apply(dataset, 2, order, decreasing=T))\n result5 = matrix(0,nrow = dim(vects)[1], ncol = 11)\n for (k in c(1:dim(vects)[1]))\n {\n tryCatch({\n result5[k,] = filter_category(vects[k,],dataset[k,],games[k,'key'],games,\n .Object@games_to_select,.Object@cutoff,.Object@hot)\n },error = function(msg) {\n logerror(paste0('fall-back to hot in row:',k), logger='debugger.module')\n logerror(paste0(mgs),logger='debugger.module')\n result5[k,] = Object@hot[c(1:.Object@games_to_select),'id']\n }\n )\n } \n result_final=data.frame(result5,stringsAsFactors = FALSE)[,c(1:(.Object@games_to_select+1))]\n result_final2=data.frame(rep(1:nrow(result_final)),.Object@lastupdated,result_final[,1:(.Object@games_to_select+1)])\n cnames = paste('Top',c(1:.Object@games_to_select),'Game',sep='')\n colnames(result_final2)=c(\"SN\",\"Date\",\"Game\", cnames)\n return(result_final2)\n})\n\nfilter_category = function(ordered_row, distance_row, active_game, updated_control,games_to_select, cutoff, hot)\n{\n results = rep(0,games_to_select)\n ##Exclude Categories\n ##1 fill with other categories, not in excluded\n results = filterCategory(ordered_row, active_game, updated_control,games_to_select,results)\n ##2 Cleanup\n results = cleanupStep(results, distance_row, cutoff, active_game, games_to_select, updated_control)\n if ( length(results) > games_to_select) { return(results) }\n \n ##Exclude RawDataType, Include Categories\n results = filterCategory(ordered_row, active_game, updated_control,games_to_select,results,'2') \n ##2 Cleanup\n results = cleanupStep(results, distance_row, cutoff, active_game, games_to_select, updated_control)\n if ( length(results) > games_to_select) { return(results) }\n \n ##Include RawDataType, Include Categories\n results = filterCategory(ordered_row, active_game, updated_control,games_to_select,results,'3')\n ##2 Cleanup\n results = cleanupStep(results, distance_row, cutoff, active_game, games_to_select, updated_control)\n if ( length(results) > games_to_select) { return(results) }\n \n ###Fill the rest with hot\n filled_portion = filled_portion = max(c(0,which(distance_row[results] > cutoff)))\n results = updated_control[results,'key']\n results[c((filled_portion + 1):games_to_select)] = hot[!hot[,'id'] %in% results,'id'][c(1:(games_to_select - filled_portion))]\n return(as.character(c(active_game,results)))\n}\n\n\n#cleanup\ncleanupStep = function(results, distance_row, cutoff, active_game, games_to_select, updated_control)\n{\n filled_portion = max(c(0,which(distance_row[results] > cutoff)))\n #RawDataType\n if(filled_portion == games_to_select) {\n results = updated_control[results,'key'] \n return(as.character(c(active_game,results)))\n }\n else {\n results[c((filled_portion+1):games_to_select)] = 0\n return(results)\n }\n} \n\n#filterCategory\nfilterCategory = function(ordered_row, active_game, updated_control, games_to_select, results, type_filter='1')\n{\n filled_portion = sum(results != 0)\n offset = 0\n active_category = updated_control[updated_control[,c('key')] == active_game,'category']\n active_datatype = updated_control[updated_control[,c('key')] == active_game,'RawDataType']\n if (type_filter == '1') {\n filterCategory = (updated_control[,'category'] != active_category & updated_control[,'Exclusions'] == 0)\n } else if (type_filter == '2') {\n filterCategory = (updated_control[,'category'] == active_category & updated_control[,'Exclusions'] == 0 & updated_control[,'RawDataType'] != active_datatype)\n } else {\n filterCategory = (updated_control[,'category'] == active_category & updated_control[,'Exclusions'] == 0 & updated_control[,'RawDataType'] == active_datatype)\n offset = 1\n }\n if(sum(filterCategory) == 0){return(results)}\n orderedIndicesFiltered = ordered_row %in% which(filterCategory)\n maxindex = min(c(games_to_select-filled_portion,length(ordered_row[orderedIndicesFiltered]) - offset))\n if (maxindex > 0)\n {\n results[c((filled_portion+1):(filled_portion+maxindex))] = ordered_row[orderedIndicesFiltered] [c((1+offset):(maxindex+offset))]\n }\n return( results )\n}\n\n\n" }, { "alpha_fraction": 0.6694200038909912, "alphanum_fraction": 0.6866582632064819, "avg_line_length": 42.85039520263672, "blob_id": "06cb06ecac219aacc6e2563b862430d443c4e7aa", "content_id": "6bce6830dfe607a8faadb3c8f7a2c24f1b012821", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5575, "license_type": "no_license", "max_line_length": 136, "num_lines": 127, "path": "/RecommendationEngine_Python/ModelResearch/DS_Model.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "\"\"\"\n@author: Jimmy\n\"\"\"\nimport pandas as pd\nimport os\nfrom sklearn.metrics import pairwise_distances\nos.chdir('C:/Users/Admin/Desktop/Project/RecommendSystem') #cd\npd.set_option('display.max_columns', None)\nimport DS_Model_function as func\n\n'''\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.distplot(Trainset.score,\n hist=True, \n color = 'red').set(xlim=(0, 1))\n'''\n\n# Customer play record and exclude the recommend game(In SQL) because it is off line test\nnames = ['member_id', 'dates', 'game_id', 'game_name','game_category','bet_amount',\n 'payoff','commissionable','RawDataType','gamecode', 'Expect_earning_ratio']\n#train = pd.read_csv('TrainData_1101To1124.csv', header = 0, names = names) ##11/01~11/24 as training dataset\n\ntrain = pd.read_csv('TrainData_1118To1124.csv',\n header = 0,\n names = names) ##11/01~11/24 as training dataset\ntest = pd.read_csv('TestData_1125To1130.csv', \n header = 0,\n names = names) ##11/25~11/30 as test dataset\n\n\n# 預處理\ntrain_data = func.Pre_processing(train)\ntest_data = func.Pre_processing(test)\n\n# filter & Exclude the just play one game people (Noise and it can't give our model any help)\ntrain_data = func.Pre_processing_train(train_data)\n\n\n# Define the hotgame list\nHotGame_inTrain = func.Hot_Game(train_data, \n feature='commissionable',\n n=12)\n\n# get the train set, i.e., define the feature (or score namely) for recommending\nTrainset = func.get_Trainset(train_data)\ngames = list(Trainset.game_id.unique())\n\n# get sparse matrix\nsparse_df = func.get_sparse(Trainset)\n\n#cosine similarity\nNeighbor_only_result, Neighbor_result = func.Recommendation_cosine(Trainset, sparse_df, games, N = 45)\n\n#surprise svd\nLatent_only_result, Latent_result_df = func.SVD_surprise(Trainset)\nSVD_Neighbor, SVD_Neighbor_result = func.SVD_surprise_only(Trainset, 75)\n\n# model of the bind result\nResult_BindLatentandNeighbor = Neighbor_result.merge(Latent_result_df,\n how = 'left',\n on = ['member_id', 'game_id'])\nResult_BindLatentandNeighbor = Result_BindLatentandNeighbor.sort_values(by = ['member_id', 'Pred_Return'],\n ascending=False).reset_index(drop=True)\nBind_result = Result_BindLatentandNeighbor.groupby('member_id').head(12)\n\n#sparseSVD\n#k = func.Dim_reduction(func.get_sparse_matrix(Trainset))=590\nU, S, Vt = func.computeSVD(func.get_sparse_matrix(Trainset), 590)\nsimilarity_matrix = pairwise_distances((S*Vt).T, (S*Vt).T, metric = 'cosine')\nNeighbor_only_result_ = func.get_neighbor((S*Vt).T, 'cosine', Trainset, games, test_data, 50)\n\n#bagging the model\nBagging_df = pd.concat([SVD_Neighbor, Neighbor_only_result_[['member_id', 'game_id']]], axis = 0)\nBagging_result = func.Bagging(Bagging_df, Trainset)\n\n\n'''\nEvaluate metrics\n'''\n#Hot Game\nauc_notintrain = func.Get_AUC_notintrain(Neighbor_only_result, test_data, HotGame_inTrain)\n\n#AUC\nauc_Bagging = func.Get_AUC_intrain(Bagging_result, test_data)\nauc_SVD_new = func.Get_AUC_intrain(SVD_Neighbor_result, test_data)\nauc_cosinesimilarity = func.Get_AUC_intrain(Neighbor_only_result, test_data)\nauc_SparseSVD = func.Get_AUC_intrain(Neighbor_only_result_, test_data)\nauc_BindModel = func.Get_AUC_intrain(Bind_result, test_data)\nauc_SVD = func.Get_AUC_intrain(Latent_only_result, test_data)\n\n#NDCG\nndcg_Bagging = func.NDCG(Bagging_result, test_data)\nndcg_SVD_new = func.NDCG(SVD_Neighbor_result, test_data)\nndcg_cosinesimilarity = func.NDCG(Neighbor_only_result, test_data)\nndcg_SparseSVD = func.NDCG(Neighbor_only_result_, test_data)\nndcg_BindModel = func.NDCG(Bind_result, test_data)\nndcg_SVD = func.NDCG(Latent_only_result, test_data)\n\n#Precision\nPrecision_Bagging = func.Get_Precision(Bagging_result, test_data)\nPrecision_SVD_new = func.Get_Precision(SVD_Neighbor_result, test_data)\nPrecision_cosinesimilarity = func.Get_Precision(Neighbor_only_result, test_data)\nPrecision_SparseSVD = func.Get_Precision(Neighbor_only_result_, test_data)\nPrecision_BindModel = func.Get_Precision(Bind_result, test_data)\nPrecision_SVD = func.Get_Precision(Latent_only_result, test_data)\n\n#Recall\nRecall_Bagging = func.Get_Recall(Bagging_result, test_data)\nRecall_SVD_new = func.Get_Recall(SVD_Neighbor_result, test_data)\nRecall_cosinesimilarity = func.Get_Recall(Neighbor_only_result, test_data)\nRecall_SparseSVD = func.Get_Recall(Neighbor_only_result_, test_data)\nRecall_BindModel = func.Get_Recall(Bind_result, test_data)\nRecall_SVD = func.Get_Recall(Latent_only_result, test_data)\n\n#Summary table\nsummary_dict = {'Bagging': [auc_Bagging, ndcg_Bagging, Precision_Bagging, Recall_Bagging],\n 'SVD_new': [auc_SVD_new, ndcg_SVD_new, Precision_SVD_new, Recall_SVD_new],\n 'Cosine Similarity': [auc_cosinesimilarity, ndcg_cosinesimilarity, Precision_cosinesimilarity, Recall_cosinesimilarity],\n 'SparseSVD': [auc_SparseSVD, ndcg_SparseSVD, Precision_SparseSVD, Recall_SparseSVD],\n 'DNN': [0.80, 0.76, 0.23, 0.611],\n 'Bind Model': [auc_BindModel, ndcg_BindModel, Precision_BindModel, Recall_BindModel],\n 'SVD': [auc_SVD, ndcg_SVD, Precision_SVD, Recall_SVD],\n 'Sales Model': [0.32, 0.19, 0.039, 0.11]}\nsummary_df = pd.DataFrame(summary_dict, index = ['AUC', 'NDCG', 'Precision', 'Recall'])\nprint(summary_df)\nsummary_df.to_csv('recommender_result.csv')\n" }, { "alpha_fraction": 0.570890486240387, "alphanum_fraction": 0.6039817333221436, "avg_line_length": 47.59477233886719, "blob_id": "2d536dab40dcb8a0b236e0303b25efd44ddc1880", "content_id": "cf25c17d2d5905956d66e21f776654269b2ad354", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7434, "license_type": "no_license", "max_line_length": 160, "num_lines": 153, "path": "/RecommendationEngine_Python/ModelResearch/DS_Tuning.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "\"\"\"\n@author: Jimmy\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport os \nimport random\nimport scipy.sparse as sparse\nfrom scipy.sparse.linalg import spsolve\nfrom sklearn.metrics.pairwise import linear_kernel, cosine_similarity\nfrom surprise import Reader, Dataset, evaluate, Dataset, accuracy\nfrom surprise import SVD, SVDpp, SlopeOne, NMF, NormalPredictor, KNNBaseline, KNNBasic\nfrom surprise import KNNWithMeans, KNNWithZScore, BaselineOnly, CoClustering\nfrom surprise.model_selection import cross_validate, train_test_split, GridSearchCV\nfrom sklearn import metrics\nos.chdir('C:/Users/ADMIN/Desktop/Project/RecommendSystem') #cd\n\n## function zone\ndef Pre_processing(df): \n result = df.copy()\n result['member_id'] = result['member_id'].astype('int64')\n result['dates'] = result['dates'].astype('int64')\n result['game_id'] = result['game_id'].astype('int64')\n result['bet_amount'] = result['bet_amount'].astype('float64')\n result['payoff'] = result['payoff'].astype('float64')\n result['commissionable'] = result['commissionable'].astype('float64')\n result['Expect_earning_ratio'] = result['Expect_earning_ratio'].astype('float64')\n result['gamecode'] = result['gamecode'].astype('category')\n # We will multiply the ratio from the gamehall in the future but the information we haven't received yet.\n # and assume every gamehall keep the same ==1\n result.insert(11, 'expect_earn', result['commissionable'] * result['Expect_earning_ratio'])\n result.insert(12, 'expect_earn_per_day', result['expect_earn'] / result['dates'])\n #result.insert(12, 'expect_earn_per_day', result['commissionable'] / result['dates'])\n result.insert(13, 'key', list(zip(result['RawDataType'], result['gamecode'])))\n return(result)\n \n## filter & Exclude the just play one game people( Noise and it can't give our model any help)\ndef Pre_processing_train(x): \n x = x[(x['dates'] > 0) & (x['bet_amount'] > 0) & (x['commissionable'] > 0)]\n group = x.groupby('member_id', as_index=False).agg({'game_name': ['count']})\n group.columns = ['member_id', 'count']\n group = group[group['count'] != 1]\n group = group.reset_index(drop=True)\n x = x[x.member_id.isin(group.member_id)]\n x = x.reset_index(drop = True)\n return(x)\n\n#Define the hot game for the newuser or the user not in train data \ndef Hot_Game(df, feature = 'commissionable', n = 12): \n if feature == 'commissionable':\n FindHotGame = train_data.groupby('game_id', as_index=False).agg({'commissionable': ['sum']}) \n elif feature == 'member_id':\n FindHotGame = train_data.groupby('game_id', as_index=False).agg({'member_id': ['count']})\n else:\n print('Not Defined') \n FindHotGame.columns = ['game_id', 'feature']\n FindHotGame = FindHotGame.sort_values(by = ['feature'], ascending = False).reset_index(drop = True)\n HotGame = list(FindHotGame.game_id[0:n])\n return(HotGame)\n\n# what does the 30 come from? 95% percentile\ndef Get_neighbor_30(x): \n #x[x>0.99] = 0.0\n return(gamelist[np.flip(np.argsort(x,axis=0))[0:30,]])\n \ndef Get_AUC(input_df, HotGame): \n #hot game must be a list and there were 12 container.\n df = test_data[['member_id']].drop_duplicates().merge(input_df[['member_id', 'game_id']], \n how = 'left',\n on = ['member_id'])\n NotIntrain = df[df.game_id.isna()].member_id\n NotIntraindata = pd.DataFrame({'member_id': np.repeat(np.array(NotIntrain), 12, axis=0),\n 'game_id': HotGame * len(NotIntrain)})\n df = df[~df.game_id.isna()]\n df['game_id'] = df['game_id'].astype('int64')\n df = pd.concat([df, NotIntraindata])\n \n df = df.merge(test_data[['member_id', 'game_id', 'commissionable']], \n how = 'left', \n on = ['member_id', 'game_id'])\n df.commissionable = np.where(df.commissionable.isna(), 0, 1) #play as TP\n df.columns = ['member_id', 'game_id', 'TP']\n df.loc[:,'FP'] = 1 - df.TP\n \n aggregated = df[['member_id', 'TP']].groupby('member_id', as_index=False).sum()\n aggregated.loc[:,'FP_n'] = 12 - aggregated.TP\n aggregated.columns = ['member_id', 'TP_n', 'FP_n']\n grade0_memberid = aggregated[aggregated.TP_n == 0].member_id\n\n tmp = df[~df.member_id.isin(grade0_memberid)]\n tmp = tmp.merge(aggregated, how='left', on='member_id')\n tmp.loc[:,'TPR'] = tmp.TP / tmp.TP_n\n tmp.loc[:,'FPR'] = tmp.FP / tmp.FP_n\n auc_df = tmp[['member_id', 'TPR', 'FPR']].groupby(['member_id']).apply(lambda x:metrics.auc(np.cumsum(x.FPR), np.cumsum(x.TPR))) \n auc_score = auc_df.sum()/len(np.unique(df.member_id))\n return(auc_score)\n \n## Customer play record and exclude the recommend game(In SQL) because it is off line test\nnames = ['member_id', 'dates', 'game_id', 'game_name','game_category','bet_amount', \n 'payoff','commissionable','RawDataType','gamecode', 'Expect_earning_ratio']\ntrain = pd.read_csv('TrainData_1101To1124.csv', header = 0, names = names) ##11/01~11/24 as training dataset\ntest = pd.read_csv('TestData_1125To1130.csv', header = 0, names = names) ##11/25~11/30 as test dataset \n \n## Pre_processing(define the feature type)\ntrain_data = Pre_processing(train)\ntest_data = Pre_processing(test)\n\n## filter & Exclude the just play one game people( Noise and it can't give our model any help)\ntrain_data = Pre_processing_train(train_data)\n\n\nTrainset = train_data[['member_id','game_id','dates', 'expect_earn_per_day']].sort_values(by = ['member_id', 'game_id'], ascending=True).reset_index(drop=True)\n\n\n#zmm = ( Trainset.loc[:,'expect_earn_per_day'] - np.median(Trainset.loc[:,'expect_earn_per_day']) ) / np.std(Trainset.loc[:,'expect_earn_per_day'])\nmin = Trainset[['expect_earn_per_day']].min()\nmax = Trainset[['expect_earn_per_day']].max()\nzmm = np.float64((Trainset[['expect_earn_per_day']] - min) / (max - min))\nTrainset.loc[:, 'score'] = zmm\n\n\n\n# =============================================================================\n# Use the cv to find the hyperParameter\nreader = Reader()\nTrainset_changetype = Dataset.load_from_df(Trainset[['member_id', 'game_id', 'score']], reader)\n# =============================================================================\n# param_grid = {'n_factors': [16, 32 , 64, 128, 256], \n# 'n_epochs': [20, 50 , 80, 100, 130, 150 , 180, 200], \n# 'lr_all': [0.0001,0.0003,0.0005,0.00065,0.0008, 0.001, 0.002]}\n# =============================================================================\nparam_grid = {'n_factors': [32,64,128], \n 'n_epochs': [20, 50 , 80, 100, 130, 150 , 180, 200], \n 'lr_all': [0.0001,0.0003,0.0005,0.00065,0.0008, 0.001, 0.002],\n 'biased':[True, False],\n 'reg_all':[0.005, 0.01, 0.015, 0.02],\n 'random_state':[1234],\n 'verbose':[True]}\n\ngs = GridSearchCV(SVD,\n param_grid, \n measures = ['rmse'],\n cv = 5,\n return_train_measures = True)\ngs.fit(Trainset_changetype)\n\n# Best RMSE score, parameters\nprint(gs.best_score['rmse'])\nprint(gs.best_params['rmse'])\nresults_df = pd.DataFrame.from_dict(gs.cv_results)\nresults_df\nresults_df.iloc[np.array(results_df.mean_test_rmse).argmin(0), :].params\nresults_df.to_csv('surprise_result.csv', index = 0)" }, { "alpha_fraction": 0.5918023586273193, "alphanum_fraction": 0.5974171757698059, "avg_line_length": 30.803571701049805, "blob_id": "c20f159ea22f24d93167dbf98a18a9ede98bcdf7", "content_id": "7bb7bc492dce1a7a37af2755de8c8d665192341d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1781, "license_type": "no_license", "max_line_length": 107, "num_lines": 56, "path": "/RecommendationEngine_R/Additional/Write_Mail.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "library(mailR)\nlibrary(optparse)\n\noption_list = list(\n make_option(c(\"-d\", \"--directory\"), type=\"character\", default=\"\", \n help=\"directory\", metavar=\"character\"),\n make_option(c(\"-c\", \"--commit\"), type='character',default=\"\",\n help=\"commit\", metavar=\"character\"),\n make_option(c(\"-b\", \"--branch\"), type='character',default=\"staging\",\n help=\"staging\", metavar=\"character\"),\n make_option(c(\"-m\", \"--message\"), type='character', default='',\n help=\"message\")\n);\nopt_parser = OptionParser(option_list=option_list)\nopt = parse_args(opt_parser)\n\nbody = paste0('problem with commit:', opt$commit,\" on branch:\",opt$branch,\", please find the logs included,\n the problem was located at \", opt$message)\n\ndirectory = paste0(opt$directory)\nprint(directory)\n#setwd(directory)\ndata = list.files(directory,all.files=TRUE)\n\n\nattachmentObjects = vector()\nattachmentNames = vector()\nattachmentDescriptions=vector()\ncounter = 1\nfor (x in data){\n if(nchar(x)>2)\n {\n attachmentObjects[counter] = paste0(directory,'//',x)\n attachmentNames[counter] = x\n attachmentDescriptions[counter] = x\n counter = counter + 1\n }\n}\n\n\nsender <- \"xinwangds@gmail.com\"\nrecipients <- c(\"tom_tong@xinwang.com.tw\",\" jimmy_yin@xinwang.com.tw\")\nsend.mail(from = sender,\n to = recipients,\n cc= sender,\n subject = \"Build of staging has failed\",\n body = body,\n encoding = \"utf-8\",\n smtp = list(host.name = \"smtp.gmail.com\", port = 465, \n user.name = \"xinwangds@gmail.com\", \n passwd = '', ssl = TRUE),\n authenticate = TRUE,\n send = TRUE,\n attach.files = attachmentObjects,\n attach.names = attachmentNames,\n attach.descriptions = attachmentDescriptions)\n" }, { "alpha_fraction": 0.8765432238578796, "alphanum_fraction": 0.8765432238578796, "avg_line_length": 39.5, "blob_id": "92e1ef35cde1d623ed5b21609561020e791faa04", "content_id": "d492cfe48eebeb507930107c90f75273eef878a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 81, "license_type": "no_license", "max_line_length": 57, "num_lines": 2, "path": "/README.md", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "# RecommendationEngine\ncontains several versions of geming recommendation engine\n" }, { "alpha_fraction": 0.5721271634101868, "alphanum_fraction": 0.6102689504623413, "avg_line_length": 33.52542495727539, "blob_id": "8a49033b7434d93b3f10f8e14690400a5298ceae", "content_id": "71cb33404e0947a004c09391181ff1f5eaff0188", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2045, "license_type": "no_license", "max_line_length": 104, "num_lines": 59, "path": "/RecommendationEngine_Python/Optimization/Optimization_Parallel.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "\nimport asyncio\nimport aioodbc\nfrom concurrent.futures import ThreadPoolExecutor\n\nimport time\nimport os\nimport datetime\nimport DS_SQLGetDF_function as func\nimport numpy as np\nimport pandas as pd\n\nasync def connect_db(loop):\n#dsn = 'Driver=SQL Server Native Client 11.0;Server=10.80.16.191;User=DS.Reader;Password=8sGb@N3m'\n conn = await aioodbc.create_pool(dsn = 'DRIVER={SQL Server Native Client 11.0};SERVER=10.80.16.191;\\\n UID=DS.Reader;PWD=8sGb@N3m;ApplicationIntent=READONLY;',\n executor=ThreadPoolExecutor(max_workers=4),\n loop = loop)\n return(conn)\n \nasync def queryDAT( pool, sql):\n async with pool.acquire() as conn:\n cursor = await conn.execute(sql)\n rows = await cursor.fetchall()\n colList = []\n for colInfo in cursor.description:\n colList.append(colInfo[0]) \n resultList = []\n for row in rows:\n resultList.append(list(row))\n data = pd.DataFrame(resultList, columns=colList)\n # except:\n # data = None\n return(data)\n\nasync def main_connect(loop):\n pool = await connect_db(loop)\n started_at = time.monotonic()\n Server_list = ['10.80.16.191', '10.80.16.192', '10.80.16.193', '10.80.16.194']\n Server = Server_list[0]\n\n #main parameter\n now = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:00:00.000\") #UTC+0\n current = datetime.datetime.now().strftime(\"%Y-%m-%d %H:00:00.000\") \n SQLQuery_df = func.select_from_sql(now, current, Server)\n #print(SQLQuery_df)\n \n tasklist = np.unique(SQLQuery_df.Sqlquery).tolist()\n print(tasklist)\n print(len(tasklist))\n tasks = [ queryDAT( pool ,x ) for x in tasklist ]\n results = await asyncio.gather(*tasks)\n zm = pd.concat(results)\n print(zm)\n print(len(results))\n print(time.monotonic() - started_at)\n\n\nloop = asyncio.get_event_loop() \nloop.run_until_complete(main_connect(loop))\n\n\n\n " }, { "alpha_fraction": 0.5661579370498657, "alphanum_fraction": 0.5789568424224854, "avg_line_length": 39.89189147949219, "blob_id": "cf9061241fe9f9dd54819d609a43ca379ced4add", "content_id": "7d6113776edea1aefe535f60a30a123ed45044ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16642, "license_type": "no_license", "max_line_length": 127, "num_lines": 407, "path": "/RecommendationEngine_Python/Optimization/DS.Function_opt.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "import pyodbc\nimport pandas as pd\nimport numpy as np\nimport time\nimport logging\nimport sys\nimport scipy.sparse as sparse\n#from scipy.sparse import csr_matrix\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn import metrics\nfrom surprise import SVD, Reader, Dataset\nimport asyncio\n\n'''\nFunction zone\n'''\n\n'''\nConnect Function\n'''\nclass DB:\n def __init__(self, driver, server, uid, pwd):\n self.driver = driver\n self.server = server\n self.uid = uid\n self.pwd = pwd\n \n def __getConnect(self):\n try:\n self.conn = pyodbc.connect(driver=self.driver,\n server=self.server,\n uid=self.uid,\n pwd=self.pwd, ApplicationIntent='READONLY')\n cur = self.conn.cursor()\n except Exception as ex:\n logging.error('SQL Server connecting error, reason is: {}'.format(str(ex)))\n sys.exit()\n return cur\n \n def ExecQuery(self, sql):\n cur = self.__getConnect()\n try:\n cur.execute(sql)\n rows = cur.fetchall()\n colList = []\n for colInfo in cur.description:\n colList.append(colInfo[0]) \n resultList = []\n for row in rows:\n resultList.append(list(row))\n df = pd.DataFrame(resultList, columns=colList)\n except pyodbc.Error as ex:\n logging.error('SQL Server.Error: {}'.format(str(ex)))\n sys.exit()\n cur.close()\n self.conn.close()\n return df\n \n def Executemany(self, sql, obj):\n cur = self.__getConnect()\n try:\n cur.executemany(sql, obj)\n self.conn.commit()\n except pyodbc.Error as ex:\n logging.error('SQL Server.Error: {}'.format(str(ex)))\n cur.close()\n self.conn.close()\n \n def ExecNoQuery(self, sql):\n cur = self.__getConnect()\n try:\n cur.execute(sql)\n self.conn.commit()\n except pyodbc.Error as ex:\n logging.error('SQL Server.Error: {}'.format(str(ex)))\n cur.close()\n self.conn.close()\n\n'''\nNormalization Function\n'''\ndef min_max_normalize(x):\n min = x.min()\n max = x.max()\n result = np.float64((x- min) / (max- min))\n return result\n\ndef get_data(JG, start, end):\n declare = \"DECLARE @Start_Date DATETIME, @End_Date DATETIME SET @Start_Date = '{}' SET @End_Date = '{}'\".format(start, end)\n sqlquery = \" SELECT [siteid], [gameaccount], [gametypesourceid], Sum([commissionable]) [Commissionable], \\\n Count(1) [Dates] FROM \\\n (SELECT CONVERT(DATE, [dateplayed]) DAY, [gameaccount], [siteid], [gametypesourceid], \\\n Sum([commissionable]) [Commissionable] \\\n FROM [DataScientist].[dbo].[ds_recommendersystemdailyquery] (nolock) \\\n WHERE [dateplayed] >= @Start_Date AND \\\n [dateplayed] <= @End_Date \\\n GROUP BY CONVERT(DATE, [dateplayed]), [gameaccount], [siteid], [gametypesourceid])Y \\\n GROUP BY [siteid], [gameaccount], [gametypesourceid]\"\n FullString = declare + sqlquery\n data = JG.ExecQuery(FullString)\n return data\n\ndef Pre_processing(df):\n result = df.copy()\n #Change columns name\n result.columns = ['SiteID', 'Member', 'Game', 'Commissionable', 'Dates']\n \n result['SiteID'] = result['SiteID'].astype('object')\n result['Member'] = result['Member'].astype('object')\n result['Game'] = result['Game'].astype('object')\n result['Commissionable'] = result['Commissionable'].astype('float64')\n result['Dates'] = result['Dates'].astype('int64')\n \n return result\n\n\ndef Pre_processing_train(df):\n result = df.copy()\n \n # Exclude the following freak conditions\n Condition1 = result['Commissionable'] > 0\n Condition2 = result['Dates'] > 0 \n result = result[Condition1 | Condition2]\n\n ## Exclude the just play one game people( Noise and it can't give our model any help) \n group = result.groupby('Member', as_index=False).agg({'Game': ['count']})\n group.columns = ['Member', 'count']\n group = group[group['count'] != 1]\n group = group.reset_index(drop=True)\n result = result[result.Member.isin(group.Member)]\n result = result.reset_index(drop=True)\n \n return result\n\n#Define the hot game for the newuser or the user not in train data\ndef Hot_Game(df, feature = 'Commissionable', n = 15):\n if feature == 'Commissionable':\n FindHotGame = df.groupby('Game', as_index=False).agg({'Commissionable': ['sum']})\n FindHotGame.columns = ['Game', 'feature']\n '''\n elif feature == 'member_id':\n FindHotGame = df.groupby('game_id', as_index=False).agg({'member_id': ['count']})\n FindHotGame.columns = ['game_id', 'feature']\n else:\n print('Not Defined')\n FindHotGame = pd.DataFrame(columns=['game_id', 'feature'])\n '''\n FindHotGame = FindHotGame.sort_values(by = ['feature'], ascending = False).reset_index(drop = True)\n HotGame = list(FindHotGame.Game[0:n])\n return HotGame\n\n\ndef get_Trainset(df):\n Trainset = df[['Member_encoding', 'Game_encoding', 'Dates', 'Commissionable']].copy()\n Trainset = Trainset.sort_values(by=['Member_encoding', 'Game_encoding'], ascending=True).reset_index(drop=True)\n \n zmm1 = min_max_normalize(Trainset[['Commissionable']])\n zmm2 = min_max_normalize(Trainset[['Dates']])\n zmm = 0.5 * zmm1 + 0.5 * zmm2\n Trainset.loc[:, 'score'] = zmm\n \n return Trainset\n\n'''\nModel - Cosine Similarity\n'''\ndef get_sparse(Trainset):\n #model of the cosine similarity\n members = list(Trainset.Member_encoding.unique()) # Get our unique members\n games = list(Trainset.Game_encoding.unique()) # Get our unique games that were purchased\n score_list = list(Trainset.score) # All of our score\n # Get the associated row, column indices\n cols = Trainset.Member_encoding.astype('category',\n categories = members).cat.codes\n rows = Trainset.Game_encoding.astype('category',\n categories = games).cat.codes\n sparse_df = sparse.csr_matrix((score_list, (rows, cols)),\n shape=(len(games), len(members)))\n '''\n print('num of members : {}\\nnum of games : {}\\nnum of score : {}'.format(len(members),\n len(games), len(score_list)))\n print(\"shape of record_sparse: \", sparse_df.shape)\n '''\n return sparse_df\n\n\n# what does the 30 come from? 95% percentile\ndef Recommendation_cosine(Trainset, sparse_df, games, N = 30):\n cosine_sim = cosine_similarity(sparse_df, sparse_df)\n cosine_sim = pd.DataFrame(data = cosine_sim, index=games, columns=games)\n ## get the neighbor 30 game of every user\n gamelist = np.array(cosine_sim.columns)\n gamesplayed = Trainset.groupby(['Member_encoding'])['Game_encoding'].apply(list).reset_index(name='games')\n gamesmax = np.array(gamesplayed.games.map(lambda x: ((cosine_sim.loc[x,:].values).max(axis=0))))\n def Get_neighbor_30(x):\n # x[x>0.99] = 0.0\n return (gamelist[np.flip(np.argsort(x, axis=0))[0:N, ]])\n filtered = list(map(Get_neighbor_30, gamesmax))\n filtered_array = np.array(filtered)\n filtered_array = filtered_array.reshape(filtered_array.shape[0] * filtered_array.shape[1], -1)\n filtered_array = filtered_array.reshape(-1,)\n Neighbor_result = pd.DataFrame({'Member_encoding': np.repeat(np.array(np.unique(Trainset.Member_encoding)), N, axis=0),\n 'Game_encoding': filtered_array})\n\n Neighbor_only_result = Neighbor_result.merge(Trainset[['Member_encoding', 'Game_encoding', 'score']],\n how = 'left',\n on = ['Member_encoding', 'Game_encoding'])\n Neighbor_only_result.score = np.where(Neighbor_only_result.score.isna(), 0, Neighbor_only_result.score)\n #sorted by the normalized expect return in training data\n Neighbor_only_result = Neighbor_only_result.sort_values(by = ['Member_encoding', 'score'], ascending = False)\n Neighbor_only_result = Neighbor_only_result.groupby('Member_encoding').head(12)\n \n return Neighbor_only_result, Neighbor_result\n\n'''\nModel - SVD_new\n'''\ndef SVD_surprise_only(Trainset, N = 30):\n reader = Reader()\n Trainset_changetype = Dataset.load_from_df(Trainset[['Member_encoding', 'Game_encoding', 'score']], reader)\n Trainset_changetype_result = Trainset_changetype.build_full_trainset()\n svd = SVD(n_factors = 20,\n n_epochs = 20,\n lr_all = 0.01,#0.0001,\n random_state = 1234)\n svd.fit(Trainset_changetype_result)\n\n games = list(Trainset.Game_encoding.unique()) # Get our unique games that were purchased\n\n #model SVD_New\n data = np.transpose(np.dot(svd.pu, np.transpose(svd.qi)))\n x = cosine_similarity(data, data)\n cosine_sim_x = pd.DataFrame(data = x, \n index=games,\n columns=games)\n gamesplayed = Trainset.groupby(['Member_encoding'])['Game_encoding'].apply(list).reset_index(name='games')\n gamesmax = np.array(gamesplayed.games.map(lambda x: ((cosine_sim_x.loc[x,:].values).max(axis=0))))\n gamelist = np.array(cosine_sim_x.columns)\n \n def Get_neighbor_30(x):\n # x[x>0.99] = 0.0\n return (gamelist[np.flip(np.argsort(x, axis=0))[0:N, ]])\n filtered = list(map(Get_neighbor_30, gamesmax))\n filtered_array = np.array(filtered)\n filtered_array = filtered_array.reshape(filtered_array.shape[0] * filtered_array.shape[1], -1)\n filtered_array = filtered_array.reshape(-1,)\n SVD_Neighbor = pd.DataFrame({'Member_encoding': np.repeat(np.array(np.unique(Trainset.Member_encoding)), N, axis=0), \n 'Game_encoding': filtered_array})\n #SVD_Neighbor_result = SVD_Neighbor.groupby('member_id').head(12)\n SVD_Neighbor_result = SVD_Neighbor.merge(Trainset[['Member_encoding', 'Game_encoding', 'score']],\n how = 'left',\n on = ['Member_encoding', 'Game_encoding'])\n SVD_Neighbor_result.score = np.where(SVD_Neighbor_result.score.isna(), 0, SVD_Neighbor_result.score)\n SVD_Neighbor_result = SVD_Neighbor_result.sort_values(by = ['Member_encoding', 'score'], ascending = False)\n SVD_Neighbor_result = SVD_Neighbor_result.groupby('Member_encoding').head(12)\n \n return SVD_Neighbor, SVD_Neighbor_result\n\ndef SVD_surprise_only_tom(Trainset): #, N = 30):\n reader = Reader()\n Trainset_changetype = Dataset.load_from_df(Trainset[['Member_encoding', 'Game_encoding', 'score']], reader)\n\n Trainset_changetype_result = Trainset_changetype.build_full_trainset()\n svd = SVD(n_factors = 20,\n n_epochs = 20,\n lr_all = 0.01,#0.0001,\n random_state = 1234)\n svd.fit(Trainset_changetype_result)\n\n games = list(Trainset.Game_encoding.unique()) # Get our unique games that were purchased\n\n s = time.time()\n chunk = 300\n\n tmp2 = np.zeros([len(games), len(games)]) \n norms = dict()\n cut0 = np.zeros((np.shape(svd.pu)[0],chunk))\n cut1 = np.zeros((np.shape(svd.pu)[0],chunk))\n\n # changed type\n #s = time.time() \n \n for k in range(0, np.shape(tmp2)[0]// chunk +1):\n minxindex = k * chunk\n maxxindex = ((k+1) * chunk)\n \n if k == np.shape(tmp2)[0]// chunk :\n maxxindex = np.shape(tmp2)[1] + 1\n cut0 = np.zeros((np.shape(svd.pu)[0],(maxxindex-minxindex - 1)))\n\n np.dot(svd.pu, np.transpose(svd.qi[minxindex:maxxindex,:]),out=cut0)\n norms[str(minxindex)] = np.linalg.norm(cut0, axis = 0)\n\n\n for l in range(0,k+1):\n #s = time.time() \n minyindex = l * chunk \n maxyindex = ((l+1) * chunk) #- 1\n if l == np.shape(tmp2)[0]// chunk:\n maxyindex = np.shape(tmp2)[1] + 1\n if (minxindex == minyindex) & (maxxindex == maxyindex):\n cut1 = np.copy(cut0)\n else: \n np.dot(svd.pu, np.transpose(svd.qi[minyindex:maxyindex,:]), out= cut1)\n \n if( str(minyindex) not in norms):\n norms[str(minyindex)] = np.linalg.norm(cut1,axis=0)\n #tmp3[minxindex:maxxindex,minyindex:maxyindex] = cosine_similarity(np.transpose(cut0), np.transpose(cut1))\n \n tmp2[minxindex:maxxindex,minyindex:maxyindex] = np.dot(np.transpose(cut0), cut1) / \\\n np.outer(norms[str(minxindex)] , norms[str(minyindex)])\n tmp2[minyindex:maxyindex,minxindex:maxxindex] = np.transpose(tmp2[minxindex:maxxindex,minyindex:maxyindex] )\n \n e = time.time()\n print(str((k, l)) + '_end')\n print(e- s) \n \n e1 = time.time()\n \n #model SVD_New\n cosine_sim_x = pd.DataFrame(data = tmp2, \n index = games,\n columns = games)\n return(cosine_sim_x)\n\n\n'''\nEvaluation metric\n'''\ndef NDCG(input_df, test_df):\n def get_Testset_score(df):\n temp = df.copy()\n temp = temp.sort_values(by=['Member', 'Game'], ascending=True).reset_index(drop=True)\n \n zmm1 = min_max_normalize(temp[['Commissionable']])\n zmm2 = min_max_normalize(temp[['Dates']])\n zmm = 0.5 * zmm1 + 0.5 * zmm2\n temp.loc[:, 'score'] = zmm\n return temp\n\n def DCG(df):\n data = df.copy()\n data['dcg_rank'] = list(range(2, 14)) * int(data.shape[0] / 12)\n #from math import log\n #data['dcg'] = data.apply(lambda row: (2 ** row.score - 1) / log(row.dcg_rank, 2), axis=1)\n data.loc[:, 'dcg'] = (2 ** data['score'] - 1)/ np.log2(data['dcg_rank'])\n \n dcg = data.groupby('Member', as_index=False)['dcg'].sum()\n return dcg\n \n def iDCG(df):\n data = df.copy()\n data = data.sort_values(by=['Member', 'score'], ascending=False)\n data['dcg_rank'] = list(range(2, 14)) * int(data.shape[0] / 12)\n #from math import log\n #data['idcg'] = data.apply(lambda row: (2 ** row.score - 1) / log(row.dcg_rank, 2), axis=1)\n data.loc[:, 'idcg'] = (2 ** data['score'] - 1)/ np.log2(data['dcg_rank'])\n idcg = data.groupby('Member', as_index=False)['idcg'].sum()\n return idcg\n \n df = input_df.copy()\n test = get_Testset_score(test_df)\n member_list = np.unique(test.Member)\n df = df[df.Member.isin(member_list)]\n df = df[['Member', 'Game']].merge(test[['Member', 'Game', 'score']],\n how = 'left',\n on = ['Member', 'Game']).fillna(0)\n dcg = DCG(df)\n idcg = iDCG(df)\n ndcg = dcg.merge(idcg, on='Member', how='left')\n ndcg['NDCG'] = ndcg['dcg']/ndcg['idcg']\n ndcg.NDCG = np.where(ndcg.NDCG.isna(), 0, ndcg.NDCG)\n \n NDCG_value = np.mean(ndcg.NDCG)\n \n return NDCG_value\n\ndef Get_AUC_intrain(input_df, test_df):\n #hot game must be a list and there were 12 container.\n test_data = test_df.copy()\n df = input_df.copy()\n member_list = np.unique(test_data.Member)\n df = df[df.Member.isin(member_list)]\n df = df[['Member', 'Game']].merge(test_data[['Member', 'Game', 'Commissionable']],\n how = 'left',\n on = ['Member', 'Game'])\n df.Commissionable = np.where(df.Commissionable.isna(), 0, 1) #play as TP\n df.columns = ['Member', 'Game', 'TP']\n df.loc[:,'FP'] = 1 - df.TP\n\n aggregated = df[['Member', 'TP']].groupby('Member', as_index=False).sum()\n aggregated.loc[:,'FP_n'] = 12 - aggregated.TP\n aggregated.columns = ['Member', 'TP_n', 'FP_n']\n grade0_memberid = aggregated[aggregated.TP_n == 0].Member\n grade1_memberid = aggregated[aggregated.TP_n == 12].Member\n \n \n tmp = df[(~df.Member.isin(grade0_memberid)) & (~df.Member.isin(grade1_memberid))]\n #tmp = df[~df.member_id.isin(grade1_memberid)]\n tmp = tmp.merge(aggregated, how='left', on='Member')\n tmp.loc[:,'TPR'] = tmp.TP / tmp.TP_n\n tmp.loc[:,'FPR'] = tmp.FP / tmp.FP_n\n auc_df = tmp[['Member', 'TPR', 'FPR']].groupby(['Member']).apply(lambda x:metrics.auc(np.cumsum(x.FPR), np.cumsum(x.TPR)))\n \n auc_score = (auc_df.sum()+ 1*len(grade1_memberid))/len(np.unique(df.Member))\n \n return auc_score" }, { "alpha_fraction": 0.5919888019561768, "alphanum_fraction": 0.6180717349052429, "avg_line_length": 33.03174591064453, "blob_id": "1893774dc521fa3ef8c10ec7c45ffaf5c4907b14", "content_id": "e0b3bb8c41d2109e619f7d533649a56b636a3f1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2147, "license_type": "no_license", "max_line_length": 129, "num_lines": 63, "path": "/RecommendationEngine_Python/Optimization/Cont_Optimization.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "\nimport asyncio\nimport aioodbc\nfrom concurrent.futures import ThreadPoolExecutor\n\nimport time\nimport os\nimport datetime\nimport DS_SQLGetDF_function as func\nimport numpy as np\nimport pandas as pd\n\nasync def connect_db(loop,Server):\n conn = await aioodbc.create_pool(dsn = \"DRIVER={SQL Server Native Client 11.0};SERVER=\" + \\\n '{Server};UID=DS.Reader;PWD=8sGb@N3m;ApplicationIntent=READONLY;'.format(Server = Server),\n executor=ThreadPoolExecutor(max_workers=4),\n loop = loop)\n return(conn)\n \nasync def queryDAT( pool, sql):\n async with pool.acquire() as conn:\n cursor = await conn.execute(sql)\n rows = await cursor.fetchall()\n colList = []\n for colInfo in cursor.description:\n colList.append(colInfo[0]) \n resultList = []\n for row in rows:\n resultList.append(list(row))\n data = pd.DataFrame(resultList, columns=colList)\n print(\"done with task \")\n return(data)\n\n\nasync def query_all(Server, now, current, loop):\n pool = await connect_db(loop, Server)\n SQLQuery_df = func.select_from_sql(now, current, Server)\n tasklist = np.unique(SQLQuery_df.Sqlquery).tolist()\n\n tasks = [ asyncio.create_task(queryDAT( pool ,x )) for x in tasklist ]\n results = await asyncio.gather(*tasks )\n zm = pd.concat(results)\n pool.close()\n await pool.wait_closed()\n print(str(Server) + \" Done\")\n return(zm)\n\nasync def main_connect(loop):\n started_at = time.monotonic()\n #main parameter\n now = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:00:00.000\") #UTC+0\n current = datetime.datetime.now().strftime(\"%Y-%m-%d %H:00:00.000\") \n\n Server_list = ['10.80.16.191', '10.80.16.192', '10.80.16.193', '10.80.16.194']\n Data = [asyncio.create_task(query_all(k,now,current,loop)) for k in Server_list]\n results = await asyncio.gather(*Data)\n print(results)\n print(time.monotonic() - started_at)\n \n \n\n\nloop = asyncio.get_event_loop() \nloop.run_until_complete(main_connect(loop)) " }, { "alpha_fraction": 0.6884580850601196, "alphanum_fraction": 0.6884580850601196, "avg_line_length": 36.61016845703125, "blob_id": "cedab5fb7263b30b8f42fb3dd37dcb8c69d39e71", "content_id": "b0435e097afa045056a1cb10dc8a1b43ce01fc5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2218, "license_type": "no_license", "max_line_length": 123, "num_lines": 59, "path": "/RecommendationEngine_R/TestConfiguration.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "library(testthat)\nrm(list=ls())\nif (.Platform$OS.type == 'Windows')\n{\n##test_log_todatabase\ntest_file(path=\".//tests//test_Log_To_Database.R\", \n reporter = JunitReporter$new(file=\".//Reports//test_Log_To_Database.xml\"))\n\n##test_initialization\ntest_file(path=\".//tests//test_initialization.R\", reporter = JunitReporter$new(file=\".//Reports//test_initialization.xml\"))\n\n##test_connection\ntest_file(path=\".//tests//test_DB.R\", reporter = JunitReporter$new(file=\".//Reports//test_db.xml\"))\n\n##getMSSQL_counts_data\ntest_file(path=\".//tests//test_get_data.R\", reporter = JunitReporter$new(file = \".//Reports//test_get_data.xml\"))\n\n##Test_preprocessing\ntest_file(path=\".//tests//test_preprocessing.R\", \n reporter = JunitReporter$new(file=\".//Reports//test_preprocessing.xml\"))\n\n##Test_calculate_Distance\ntest_file(path=\".//tests//test_Distance_Cosine.R\", \n reporter = JunitReporter$new(file=\".//Reports//test_distance_cosine.xml\"))\n\t\t \n##Test_Post_Processing\ntest_file(path=\".//tests//test_post_processing.R\",\n reporter = JunitReporter$new(file=\".//Reports//test_post_processing.xml\"))\n\n#test_database\ntest_file(path=\".//tests//test_write_to_db.R\",\n reporter = JunitReporter$new(file=\"./Reports/test_write_to_db.xml\"))\n\n} else {\n\ntest_file(path=\"./tests/test_Log_To_Database.R\", \n reporter = JunitReporter$new(file=\"./Reports/test_Log_To_Database.xml\"))\n \n \ntest_file(path=\"./tests/test_initialization.R\", reporter = JunitReporter$new(file=\"./Reports/test_initialization.xml\"))\n \n##test_connection\ntest_file(path=\"./tests/test_DB.R\", reporter = JunitReporter$new(file=\"./Reports/test_db.xml\"))\n \n##getMSSQL_counts_data\ntest_file(path=\"./tests/test_get_data.R\", reporter = JunitReporter$new(file = \"./Reports/test_get_data.xml\"))\n\n##preprocessing\ntest_file(path=\"./tests/test_preprocessing.R\", \n reporter = JunitReporter$new(file=\"./Reports/test_preprocessing.xml\"))\n\n##Test_calculate_Distance\ntest_file(path=\"./tests/test_Distance_Cosine.R\", \n reporter = JunitReporter$new(file=\"./Reports/test_distance_cosine.xml\"))\n\ntest_file(path=\"./tests/test_write_to_db.R\",\n reporter = JunitReporter$new(file=\"./Reports/test_write_to_db.xml\"))\n\n}" }, { "alpha_fraction": 0.4801255166530609, "alphanum_fraction": 0.4989539682865143, "avg_line_length": 38.75, "blob_id": "63c631fffebfde4b6f0b8890c913c782b1a4ac37", "content_id": "b002b8b2bf993020ee2b8e930cf0d1b5a1563d78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 960, "license_type": "no_license", "max_line_length": 105, "num_lines": 24, "path": "/RecommendationEngine_Python/Monitor/Judge_dailyquery_status.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "import os\npath = \"C://Users//DS.Jimmy//Desktop//Project//RecommenderSystem//Run_Model_對帳//opt//V2\"\nos.chdir(path)\nimport sys\nimport time\n\n\ndef Judge_dailyquery_status(StatsTable_bytype, train_start, train_end, JG, sleep_sec=30, last_sec=30*60):\n last = int(last_sec/sleep_sec)\n\n for k in range(0, last):\n print(k)\n sqlquery = \"SELECT * FROM {table} \\\n where [UpDateTime] <= '{train_end}' and [UpDateTime] >= '{train_start}'\\\n and [Status] not in ('Success', 'Empty')\".format(table=StatsTable_bytype,\n train_start=train_start,\n train_end=train_end)\n df = JG.ExecQuery(sqlquery)\n if df.empty:\n break\n elif((df.shape[0] == 0) & (k == 59)):\n sys.exit()\n else:\n time.sleep(30)#stop 30sec, last to 30 min " }, { "alpha_fraction": 0.6157945990562439, "alphanum_fraction": 0.6371123790740967, "avg_line_length": 41.14285659790039, "blob_id": "a6b96ebcfd6e2d1df25460317bc04b9269f53d18", "content_id": "87ca3d2c3d6b5db8cec1a2b84c0dfcf575a90370", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2068, "license_type": "no_license", "max_line_length": 111, "num_lines": 49, "path": "/RecommendationEngine_Python/CreateSalesReference/Sales_ndcg.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport itertools\nimport numpy as np\nimport multiprocessing as mp\nimport time\n\nstart = time.time()\n\npd.set_option('display.max_columns', None)\ndf = pd.read_csv('C:/Users/ADMIN/PycharmProjects/Recommender system/sales_model.csv')\ntest = pd.read_csv('C:/Users/ADMIN/PycharmProjects/Recommender system/test.csv') ##11/25~11/30 as test dataset\ntest = test.sort_values(by=['memberid', 'Commissionable'], ascending=False)\ntest = test.groupby('memberid', as_index=False).head(12)\ntest['rel'] = test.groupby('memberid')['Commissionable'].rank(ascending=False)\n\nmemberlist = test.memberid.unique().tolist()\nmemberlist = list(itertools.chain.from_iterable(itertools.repeat(x, 12) for x in memberlist))\n\n\ndef NDCG_calculation(i):\n print('第{}批'.format(i+1))\n gamelist = df.iloc[i].tolist() * (len(memberlist) // 12)\n DF = pd.DataFrame(np.column_stack([memberlist, gamelist]), columns=['memberid', 'gametypeid'])\n DF = DF.merge(test[['memberid', 'gametypeid', 'rel']], how='left', on=['memberid', 'gametypeid'])\n DF.rel = np.where(DF.rel.isna(), 0, DF.rel) # play as TP\n DF.columns = ['member_id', 'game_id', 'rel']\n DF['i+1'] = list(range(2,14)) * (DF.shape[0] // 12)\n from math import log\n DF['dcg'] = DF.apply(lambda row: (2 ** row['rel'] - 1) / log(row['i+1'], 2), axis=1)\n DCG = DF.groupby('member_id', as_index=False)['dcg'].sum()\n DF_ = DF.sort_values(by=['member_id', 'rel'], ascending=False)\n DF_['i+1'] = list(range(2, 14)) * (DF_.shape[0] // 12)\n DF_['idcg'] = DF_.apply(lambda row: (2 ** row['rel'] - 1) / log(row['i+1'], 2), axis=1)\n iDCG = DF_.groupby('member_id', as_index=False)['idcg'].sum()\n NDCG = DCG.merge(iDCG, on='member_id', how='left')\n NDCG['ndcg'] = NDCG['dcg'] / NDCG['idcg']\n NDCG.ndcg = np.where(NDCG.ndcg.isna(), 0, NDCG.ndcg)\n return NDCG.ndcg.mean()\n\n\ndef multicore():\n pool = mp.Pool()\n result = pool.map(NDCG_calculation, range(500))\n print(result)\n print(sum(result) / len(result))\n\nif __name__=='__main__':\n multicore()\n print(time.time() - start)" }, { "alpha_fraction": 0.5951110124588013, "alphanum_fraction": 0.6344478726387024, "avg_line_length": 29.663793563842773, "blob_id": "6c708f4a45f031910abd5d5838b53dcd1b46446a", "content_id": "4792dc04885fd7d207add5737d472736f729a548", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3559, "license_type": "no_license", "max_line_length": 123, "num_lines": 116, "path": "/RecommendationEngine_Python/Optimization/Get_Top30members.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 29 09:39:27 2019\n\n@author: DS.Tom\n\"\"\"\nimport numpy as np\nimport os\nimport pandas as pd\nimport time\nimport DS_function as func\nimport asyncio\n\n\nstart = time.time() \n\n'''\nVariable zone\n'''\nJG = func.DB('SQL Server Native Client 11.0', 'JG\\MSSQLSERVER2016', 'DS.Tom', keyring::get_password('JG','DS_Tom'))\ntrain_start = '2019-10-15 00:00:00.000' \ntrain_end = '2019-10-20 23:59:59.999'\ntest_start = '2019-10-21 00:00:00.000' \ntest_end = '2019-10-21 23:59:59.999'\n\n#Get train & test with sql & ODBC\ntrain = func.get_data(JG, train_start, train_end)\ntest = func.get_data(JG, test_start, test_end)\n'''\nExclude_rawdatatype = [35, 67, 68, 136]# Mako said that there aren't unique gameaccount in these gamehall(rawdatatype)\ntrain = train[~train.RawDataType.isin(Exclude_rawdatatype)]\n'''\n\nsql_end = time.time() \npython_start = sql_end\n\n'''\nPreProcessing\n'''\ntrain_data = func.Pre_processing(train)\ntest_data = func.Pre_processing(test)\n\n'''\ntrain_data = train_data[train_data.SiteID == 154].reset_index()\ntest_data = test_data[test_data.SiteID == 154].reset_index()\n'''\n\n# filter & Exclude the just play one game people (Noise and it can't give our model any help)\ntrain_data = func.Pre_processing_train(train_data)\n\n# Define the hotgame list\nHotGame_inTrain = func.Hot_Game(train_data, \n feature='Commissionable',\n n=15)\n\nusers = train_data.Member.unique()\ngames = train_data.Game.unique()\nuserid2idx = {o:i for i,o in enumerate(users)}\ngameid2idx = {o:i for i,o in enumerate(games)}\nuserid2Rraw = {i:o for i,o in enumerate(users)}\ngameid2iraw = {i:o for i,o in enumerate(games)}\n\ntrain_data.loc[:, 'Member_encoding'] = train_data['Member'].apply(lambda x: userid2idx[x])\ntrain_data.loc[:, 'Game_encoding'] = train_data['Game'].apply(lambda x: gameid2idx[x])\nTrainset = func.get_Trainset(train_data)\n\ncosine_sim = pd.read_csv(\"C:/Users/DS.Tom/Desktop/cosine_sim.csv\", index_col = 0)\n\nasync def main():\n print(\"--- %s seconds ---\" % (time.time() - start))\n\n gamesplayed = Trainset.groupby(['Member_encoding'])['Game_encoding'].apply(lambda x: list(x)).reset_index(name='games')\n cosine2 = cosine_sim.to_numpy()\n print(\"--- %s seconds ---\" % (time.time() - start))\n\n \n lup = dict()\n for key in range(np.shape(cosine2)[0]):\n lup[key]= cosine2[key,:]\n goal = np.zeros((np.shape(gamesplayed)[0],30))\n print( np.shape(goal))\n\n totalsize = np.shape(gamesplayed)[0]\n step = 100000\n \n batches = int(np.floor(totalsize/step))\n tasks = []\n K = 30\n for k in range(batches):\n l = k + 1\n batch = gamesplayed.iloc[ k*step:l*step,: ]\n tasks.append(asyncio.create_task(process(batch,lup,k*step, step,K)))\n laststep = batches *step\n print(str(laststep) + ' ' + str(totalsize) + ' ' + str(totalsize))\n try:\n lastbatch = gamesplayed.iloc[ laststep : totalsize,:]\n tasks.append(asyncio.create_task(process(lastbatch,lup,laststep,step,K)))\n except:\n pass\n res = await asyncio.gather(*tasks)\n print(\"--- %s seconds ---\" % (time.time() - start))\n \n \nasync def process(batch, lup, startindex, batchsize,K):\n lookup = batch.games.to_numpy()\n indx = 0\n goal = np.zeros((batchsize,31))\n for key in lookup:\n res = [ lup[val] for val in key ]\n results = np.max(res,axis=0).argsort()[::-1][0:K]\n goal[indx,1:31] = results\n goal[indx,0] = startindex + indx\n indx = indx + 1\n return(goal)\n\nasyncio.run(main())\n\n\n" }, { "alpha_fraction": 0.6780793070793152, "alphanum_fraction": 0.680167019367218, "avg_line_length": 41.01754379272461, "blob_id": "834f259929d61fa41ffb938e3c23142e401bcc97", "content_id": "ef29d547d191c840988b13ab5aebbb83200450a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2395, "license_type": "no_license", "max_line_length": 110, "num_lines": 57, "path": "/RecommendationEngine_R/Code/Log_To_Database.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "setClass('Log_To_Database', representation(dbhandle= 'RODBC', process='character',environment='logical', \n starttime='POSIXlt', lastupdate ='Date'))\n\nsetMethod('initialize','Log_To_Database',function(.Object, process, environment)\n{\n if (environment == TRUE) {dbhandle = getHandle(new('connect_to_productionMSSQL'))}\n else { dbhandle = getHandle(new('connect_to_testMSSQL')) }\n .Object@dbhandle = dbhandle\n .Object@environment = environment\n .Object@process = process\n .Object@starttime = as.POSIXlt(Sys.time())\n .Object@lastupdate\n insert_to_database(.Object)\n return(.Object) \n}\n)\n\nsetGeneric('insert_to_database',function(object){return(string)})\nsetMethod('insert_to_database',signature ='Log_To_Database', function(object)\n{\n string = paste0(\"insert into [Datascientist].[dbo].[RunningRecord] select '\", \n as.character(as.Date(as.POSIXlt(object@starttime))),\"','\",\n as.character(object@starttime),\"','','Initialized','\",\n getEnvironment(object),\"'\")\n object@lastupdate = as.Date(object@starttime)\n sqlQuery(object@dbhandle,string)\n})\n\nsetGeneric('log_to_database',function(object,update){return(string)})\nsetMethod('log_to_database',signature ='Log_To_Database', function(object, update)\n{\n if (length(grep('Completed',update)) > 0)\n { finishtime = as.POSIXlt(Sys.time())}\n else {finishtime=''}\n string = paste0(\"update [Datascientist].[dbo].[RunningRecord] set Endtime='\",as.character(finishtime),\n \"',Status='\",update,\"' where Starttime='\", as.character(object@starttime),\"' and Date = '\",\n as.character(object@lastupdate),\"'\")\n sqlQuery(object@dbhandle,string)\n return(1)\n})\n \nsetGeneric('set_timestamp',function(object,timestamp){return(string)})\nsetMethod('set_timestamp',signature='Log_To_Database', function(object,timestamp)\n{\n object@lastupdate = as.Date(timestamp)\n string = paste0(\"Update [Datascientist].[dbo].[RunningRecord] set Date ='\", as.character(object@lastupdate),\n \"' where starttime ='\", as.character(object@starttime),\"'\")\n sqlQuery(object@dbhandle,string)\n return(object)\n})\n\nsetGeneric('getEnvironment', function(object){return(string)})\nsetMethod('getEnvironment', signature='Log_To_Database', function(object)\n {\n if (object@environment == TRUE){return('production')}\n else { return('staging')}\n})\n" }, { "alpha_fraction": 0.738070011138916, "alphanum_fraction": 0.740190863609314, "avg_line_length": 33.77777862548828, "blob_id": "0cc73428cf54f0a2b86a60cfa458be9fcf580a79", "content_id": "7fa8e80be07c1ed183f9bccffed9ef6db8c1179c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 943, "license_type": "no_license", "max_line_length": 87, "num_lines": 27, "path": "/RecommendationEngine_R/Code/Distance_Calculator.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "\nsetClass('Distancecalculator')\nsetClass('CosineDistancecalculator',contains = c('Distancecalculator'))\n\nsetMethod('initialize', 'Distancecalculator', function(.Object)\n{\n return(.Object) \n})\n\n\n\nsetGeneric('calculate_distance', function(object,input,labels,...){return(data.frame)})\nsetMethod('calculate_distance','Distancecalculator', function(object,input,labels){\n return(calculate_distance(new('CosineDistancecalculator'),input,labels))\n}\n)\nsetMethod('calculate_distance','CosineDistancecalculator',function(object,input,labels)\n{\n self_inner = as.matrix(crossprod(input, input))\n cd_marginal_cumulative = colSums(input * input)\n cd_norms = (sqrt(cd_marginal_cumulative) %*% t(sqrt(cd_marginal_cumulative)))\n cos_distancematrix = as.matrix(self_inner / cd_norms)\n row.names(cos_distancematrix)= labels\n colnames(cos_distancematrix) = labels\n diag(cos_distancematrix)= 10\n return(cos_distancematrix) \n}\n)\n\n\n\n" }, { "alpha_fraction": 0.690891444683075, "alphanum_fraction": 0.7044573426246643, "avg_line_length": 32.32258224487305, "blob_id": "1bb5e52be60c1c2823df6e3e952d7ceb7366b400", "content_id": "59031ea13ea3c38e0cc48ec42437e881f4b613d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1032, "license_type": "no_license", "max_line_length": 129, "num_lines": 31, "path": "/RecommendationEngine_R/tests/test_DB.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "context(\"test_db_connection\")\nsetwd('..')\nsource('GlobalConfig.R')\n\nswitcher = odbcDriverConnect(connection = \"driver={SQL Server};server=JG\\\\MSSQLSERVER2016;uid=DS.Jimmy;pwd=4wvb%ECX;\")== -1\nif (switcher) skip(\"No usable Database Connection\")\n\n##basic properties\ntest_that(\n 'test_db_connection',\n {\n skip_if(switcher)\n expect_s4_class(new(\"connect_to_testMSSQL\"),'connect_to_MSSQL')\n expect_s4_class(new(\"connect_to_productionMSSQL\"),'connect_to_MSSQL')\n expect_s3_class(new(\"connect_to_testMSSQL\")@dbhandle,'RODBC')\n ##we need to be able to select data\n expect_gt(dim(sqlQuery(new(\"connect_to_productionMSSQL\")@dbhandle,'select name from sys.databases'))[1],1)\n }\n)\n\n\n###is the object usable\ntest_that(\n 'getHandle',\n {\n skip_if(switcher)\n expect_gt(dim(sqlQuery(new(\"connect_to_productionMSSQL\")@dbhandle,'select name from sys.databases'))[1],1)\n expect_s3_class(getHandle(new('connect_to_productionMSSQL')),'RODBC')\n expect_s3_class(getHandle(new('connect_to_testMSSQL')),'RODBC')\n }\n)" }, { "alpha_fraction": 0.7489325404167175, "alphanum_fraction": 0.7583262324333191, "avg_line_length": 42.37036895751953, "blob_id": "c1b4c9c4544dedef5dd22472f5230d11130ebf4a", "content_id": "2c4912cf1a91f27c14c7386b4bbdb568f9f09e3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1183, "license_type": "no_license", "max_line_length": 98, "num_lines": 27, "path": "/RecommendationEngine_Python/PythonProduction/Parameter.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "CS_Delta = 7\nGet_Finallist_Delta = 7\n#sql table in balance center 190\nLookUptable_statustable = \"[BalanceOutcome].[dbo].[DS_LookUptableStatus_STATUS]\"\nBalance190_lookuptablename = \"[BalanceOutcome].[dbo].[LookUpTable]\"\nlookuptable_col = ['LinkServerName', 'GameTypeSourceId', 'DBName', 'MonthDB', 'TableName', 'Type']\n\nDailyQueryTable_190 = \"[BalanceCenterSummarize ].[dbo].[DS_BalanceCenterDailyQuery]\"\nResultTable_Default = \"[ResultPool].[dbo].[DS_RecommenderSystem_DefaultGame]\"\nResultTable_Status = \"[ResultPool].[dbo].[DS_RecommenderSystem_ResultStatus]\"\nMedianTable_CSTable = \"[DataScientist].[dbo].[DS_RecommenderSystem_CosineSimilarity]\"\nMedianTable_CSStatusTable = \"[DataScientist].[dbo].[DS_RecommenderSystem_CSStatus]\"\n\n#sql table in JG\nStatsTable_bytype = \"[DataScientist].[dbo].[DS_BalanceCenterDailyQueryStatus_byType]\"\nStatsTable_bytype_col = ['Server', 'Type', 'Status', 'Exe_Time_sec', 'UpDateTime']\n\n\nCosineSimilarity_Statustable = \"[DataScientist].[dbo].[DS_RecommenderSystem_CSStatus]\"\nDailyQueryTable = \"[DataScientist].[dbo].[DS_BalanceCenterDailyQuery]\"\n\n\n\n\n# Exclude the gamelist, connect_indirectly so far.\n\ncategory_exclude = ['彩票', '視訊', '體育']\n" }, { "alpha_fraction": 0.6831082701683044, "alphanum_fraction": 0.6952328681945801, "avg_line_length": 38, "blob_id": "78eb307058af9f5a42f13ad3308bd828b4943aa0", "content_id": "90b7e50a297a39c86ceaad41600da0d66d2032c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 3629, "license_type": "no_license", "max_line_length": 124, "num_lines": 93, "path": "/RecommendationEngine_R/Code/Validation.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "\nassign_to_sets = function(Members,Games,Datasets,parameters)\n{\n if( parameters == FALSE) {return(list(Recommendationset = Datasets,validationset = data.frame(),testset=data.frame()))}\n else{\n members = sample(Members,(parameters$test + parameters$validation)*length(Members ) / 100 )\n basicmembers = Members [!Members %in% members]\n testmembers = sample(members,(parameters$test)/(parameters$test + parameters$validation) * length(members))\n validationmembers = sample(members,parameters$validation/(parameters$test + parameters$validation) * length(members))\n basicset = Datasets[Datasets$MemberId %in% basicmembers,]\n testset = Datasets[Datasets$MemberId %in% testmembers,]\n validationset = Datasets[Datasets$MemberId %in% validationmembers,]\n return(list(Recommendationset = basicset, Validationset = validationset, Testset = testset))\n }\n}\n\ntoSparse = function(matrix, games)\n{\n return(sparseMatrix(i=as.integer(factor(matrix$MemberId)),j=as.integer(matrix$gtd),x=matrix$count))\n}\n\nsetClass('Validator', representation(dataset = \"dgCMatrix\", target = \"data.frame\"))\nsetMethod('initialize','Validator',function(.Object,dataset,target){\n .Object@dataset = dataset\n .Object@target = target\n return(.Object)\n})\n\n\n##Proposed Games\nsetGeneric('get_games_width', function(object, post_processing_settings){ return(object)})\nsetMethod('get_games_width', 'Validator',function(object,post_processing_settings)\n{\n games_to_select = post_processing_settings['games_to_select'][[1]]\n Selection = c(1:games_to_select)\n for (k in c(1:games_to_select))\n {\n Selection[k] = length(sort(unique(unlist(object@target[,c(4:(k+3))])))) / dim(object@target)[1]\n }\n print(Selection)\n plot(Selection)\n text(Selection,labels=c(1:games_to_select))\n return(Selection)\n}\n)\n\n###Sensitivity / Precision:\nsetGeneric('SensitivityRec', function(object,post_processing_settings){return(object)})\nsetMethod('SensitivityRec','Validator', function(object,post_processing_settings)\n{\n games_to_select = post_processing_settings['games_to_select'][[1]]\n co_occurrences = as.matrix(crossprod(object@dataset))\n diag(co_occurrences) <- max(co_occurrences) +4\n ranks = t(apply(co_occurrences,2, order, decreasing=TRUE))\n Games = object@target[,'Game']\n first_zero = apply(co_occurrences,2, function(x){ return( min(which(x == 0)))})\n multimod = function(x,y){return(min(1 + games_to_select,which(x %in% y)))}\n targets = object@target[,c(4:13)]\n res = mapply( multimod, split(ranks,row(ranks)),first_zero)\n precision = rep(0,games_to_select)\n recall = rep(0,games_to_select)\n for (k in c(1:games_to_select))\n {\n for (cm in c(1:dim(targets)[1]))\n {\n precision[k] = precision[k] + map_to_precision_game(targets[cm,c(1:(games_to_select ))],Games[ranks[cm,c(2:(k+1))]])\n recall[k] = recall[k] + map_to_recall_game(targets[cm,c(1:games_to_select )],Games[ranks[cm,c(2:(k+1))]])\n }\n precision[k] = 1.0*precision[k] / length(unlist(targets[,c(1:(games_to_select))]))\n recall[k] = 1.0* recall[k] / sum(sapply(res - 1 ,function(s,k){return(min(c(s,k)))},k))\n }\n return(list(precision=precision, recall = recall))\n})\n\nfind_targets = function(x,y){\n returnvector = rep(0,games_to_select);\n if (y> 1)\n { \n returnvector[c(1:(y-1))] = x[c(1:(y-1))]; \n returnvector[c(1:(y-1))] = games[returnvector]\n }\n return(returnvector)\n}\n\n\nmap_to_precision_game = function(intargets, predictions)\n{\n return( sum(as.character(unlist(predictions)) %in% intargets) )\n}\n\nmap_to_recall_game = function(targets, predictions)\n{\n return(sum( targets %in% as.character(unlist(predictions ))))\n}\n\n" }, { "alpha_fraction": 0.6453264951705933, "alphanum_fraction": 0.6683738827705383, "avg_line_length": 22, "blob_id": "6975f16c0f5e1c3df83f4a52de895c14c1e709b8", "content_id": "ef325dc5da99e700a5f8651f19b8ed469d06a0bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 781, "license_type": "no_license", "max_line_length": 81, "num_lines": 34, "path": "/RecommendationEngine_R/tests/test_Distance_Cosine.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "context(\"Distance Calculator\")\n\nsetwd(\"..\")\nsource('GlobalConfig.R')\n\n\ntester = mock_preprocessed(new('preprocessing_counts'))\n\ntest_that(\n 'initialization',\n {\n expect_s4_class(new('CosineDistancecalculator'), 'Distancecalculator')\n expect_s4_class(new('CosineDistancecalculator'), 'CosineDistancecalculator')\n }\n)\n\ntest_that(\n 'cosine_similarity',\n {\n tmm = tester$Sparse\n reference = coop::cosine(tmm)\n \n totest = calculate_distance(new('CosineDistancecalculator'),tmm,tester$Games)\n expect_equal(colnames(totest), tester$Games)\n expect_equal(rownames(totest), tester$Games)\n expect_lt(diag(totest)[1]-10,0.0001)\n diag(totest) = 0\n for (k in c(1:dim(totest)[1]))\n {\n expect_lt(sum(totest[k,]- reference[k,]),0.0001)\n }\n \n }\n)" }, { "alpha_fraction": 0.5796050429344177, "alphanum_fraction": 0.5919259190559387, "avg_line_length": 42.018798828125, "blob_id": "f0bc7a6447c9a669329f0ebd4ab7d23146939141", "content_id": "c14ca936aab3151c69994c911fc2cd18b55c786d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11444, "license_type": "no_license", "max_line_length": 171, "num_lines": 266, "path": "/RecommendationEngine_Python/Optimization/DS_function.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "import pyodbc\nimport pandas as pd\nimport numpy as np\nimport logging\nimport sys\nimport scipy.sparse as sparse\n#from scipy.sparse import csr_matrix\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn import metrics\nfrom surprise import SVD, Reader, Dataset\n\n'''\nFunction zone\n'''\n\n'''\nConnect Function\n'''\nclass DB:\n def __init__(self, driver, server, uid, pwd):\n self.driver = driver\n self.server = server\n self.uid = uid\n self.pwd = pwd\n \n def __getConnect(self):\n try:\n self.conn = pyodbc.connect(driver=self.driver,\n server=self.server,\n uid=self.uid,\n pwd=self.pwd, ApplicationIntent='READONLY')\n cur = self.conn.cursor()\n except Exception as ex:\n logging.error('SQL Server connecting error, reason is: {}'.format(str(ex)))\n sys.exit()\n return cur\n \n def ExecQuery(self, sql):\n cur = self.__getConnect()\n try:\n cur.execute(sql)\n rows = cur.fetchall()\n colList = []\n for colInfo in cur.description:\n colList.append(colInfo[0]) \n resultList = []\n for row in rows:\n resultList.append(list(row))\n df = pd.DataFrame(resultList, columns=colList)\n except pyodbc.Error as ex:\n logging.error('SQL Server.Error: {}'.format(str(ex)))\n sys.exit()\n cur.close()\n self.conn.close()\n return df\n \n def Executemany(self, sql, obj):\n cur = self.__getConnect()\n try:\n cur.executemany(sql, obj)\n self.conn.commit()\n except pyodbc.Error as ex:\n logging.error('SQL Server.Error: {}'.format(str(ex)))\n cur.close()\n self.conn.close()\n \n def ExecNoQuery(self, sql):\n cur = self.__getConnect()\n try:\n cur.execute(sql)\n self.conn.commit()\n except pyodbc.Error as ex:\n logging.error('SQL Server.Error: {}'.format(str(ex)))\n cur.close()\n self.conn.close()\n\n'''\nNormalization Function\n'''\ndef min_max_normalize(x):\n min = x.min()\n max = x.max()\n result = np.float64((x- min) / (max- min))\n return result\n\ndef get_data(JG, start, end, system):\n declare = \"DECLARE @Start_Date DateTime, @End_Date DateTime, @sys nvarchar(50) set @Start_Date = '{}' set @End_Date = '{}' set @sys = '{}' \".format(start, end, system)\n sqlquery = \" SELECT [SystemCode], [MemberId], [RawDataType], [Code], \\\n COUNT(DAY) dates, SUM([CommissionableSum]) [CommissionableSum], SUM([WagersCount]) [WagersCount] \\\n FROM ( \\\n SELECT [SystemCode], [MemberId], CONVERT(date, DATE) DAY, [RawDataType], [Code], \\\n SUM([CommissionableSum]) [CommissionableSum], SUM([WagersCount]) [WagersCount] \\\n FROM [DataPool].[dbo].[DS_VW_BetRecordQueryGameSum] \\\n where DATE >= @Start_Date and DATE <= @End_Date \\\n GROUP BY [SystemCode], [MemberId], CONVERT(date, DATE), [RawDataType], [Code] ) day \\\n GROUP BY [SystemCode], [MemberId], [RawDataType], [Code]\"\n FullString = declare + sqlquery\n data = JG.ExecQuery(FullString)\n return data\n\ndef Pre_processing(df):\n result = df.copy()\n \n result['SystemCode'] = result['SystemCode'].astype('object')\n result['MemberId'] = result['MemberId'].astype('object')\n result['RawDataType'] = result['RawDataType'].astype('int64')\n result['Code'] = result['Code'].astype('object')\n result['dates'] = result['dates'].astype('int64')\n result['CommissionableSum'] = result['CommissionableSum'].astype('float64')\n result['WagersCount'] = result['WagersCount'].astype('float64')\n\n result.insert(7, 'Member', list(zip(result['SystemCode'], result['MemberId'])) )\n result.insert(8, 'Game', list(zip(result['RawDataType'], result['Code'])))\n return(result)\n\n\ndef Pre_processing_train(df):\n x = df.copy()\n x = x[(x['dates'] > 0) & (x['CommissionableSum'] > 0)]\n group = x.groupby('Member', as_index=False).agg({'Game': ['count']})\n\n group.columns = ['Member', 'count']\n group = group[group['count'] != 1]\n group = group.reset_index(drop=True)\n x = x[x.Member.isin(group.Member)]\n x = x.reset_index(drop = True)\n return(x)\n\n#Define the hot game for the newuser or the user not in train data\ndef Hot_Game(df, feature = 'CommissionableSum', n = 15):\n if feature == 'CommissionableSum':\n FindHotGame = df.groupby('Game', as_index=False).agg({'CommissionableSum': ['sum']})\n FindHotGame.columns = ['Game', 'feature']\n '''\n elif feature == 'member_id':\n FindHotGame = df.groupby('game_id', as_index=False).agg({'member_id': ['count']})\n FindHotGame.columns = ['game_id', 'feature']\n else:\n print('Not Defined')\n FindHotGame = pd.DataFrame(columns=['game_id', 'feature'])\n '''\n FindHotGame = FindHotGame.sort_values(by = ['feature'], ascending = False).reset_index(drop = True)\n HotGame = list(FindHotGame.Game[0:n])\n return HotGame\n\n\ndef get_Trainset(df):\n Trainset = df[['Member_encoding', 'Game_encoding', 'dates', 'CommissionableSum']].copy()\n Trainset = Trainset.sort_values(by=['Member_encoding', 'Game_encoding'], ascending=True).reset_index(drop=True)\n \n zmm1 = min_max_normalize(Trainset[['CommissionableSum']])\n zmm2 = min_max_normalize(Trainset[['dates']])\n zmm = 0.5 * zmm1 + 0.5 * zmm2\n Trainset.loc[:, 'score'] = zmm\n \n return Trainset\n\n'''\nModel - Cosine Similarity\n'''\ndef get_sparse(Trainset):\n #model of the cosine similarity\n members = list(Trainset.Member_encoding.unique()) # Get our unique members\n games = list(Trainset.Game_encoding.unique()) # Get our unique games that were purchased\n score_list = list(Trainset.score) # All of our score\n # Get the associated row, column indices\n cols = Trainset.Member_encoding.astype('category',\n categories = members).cat.codes\n rows = Trainset.Game_encoding.astype('category',\n categories = games).cat.codes\n sparse_df = sparse.csr_matrix((score_list, (rows, cols)),\n shape=(len(games), len(members)))\n '''\n print('num of members : {}\\nnum of games : {}\\nnum of score : {}'.format(len(members),\n len(games), len(score_list)))\n print(\"shape of record_sparse: \", sparse_df.shape)\n '''\n return sparse_df\n\n\n# what does the 30 come from? 95% percentile\ndef Recommendation_cosine(Trainset, sparse_df, games, N = 30):\n cosine_sim = cosine_similarity(sparse_df, sparse_df)\n cosine_sim = pd.DataFrame(data = cosine_sim, index=games, columns=games)\n ## get the neighbor 30 game of every user\n gamelist = np.array(cosine_sim.columns)\n gamesplayed = Trainset.groupby(['Member_encoding'])['Game_encoding'].apply(list).reset_index(name='games')\n gamesmax = np.array(gamesplayed.games.map(lambda x: ((cosine_sim.loc[x,:].values).max(axis=0))))\n def Get_neighbor_30(x):\n # x[x>0.99] = 0.0\n return (gamelist[np.flip(np.argsort(x, axis=0))[0:N, ]])\n filtered = list(map(Get_neighbor_30, gamesmax))\n filtered_array = np.array(filtered)\n filtered_array = filtered_array.reshape(filtered_array.shape[0] * filtered_array.shape[1], -1)\n filtered_array = filtered_array.reshape(-1,)\n Neighbor_result = pd.DataFrame({'Member_encoding': np.repeat(np.array(np.unique(Trainset.Member_encoding)), N, axis=0),\n 'Game_encoding': filtered_array})\n\n Neighbor_only_result = Neighbor_result.merge(Trainset[['Member_encoding', 'Game_encoding', 'score']],\n how = 'left',\n on = ['Member_encoding', 'Game_encoding'])\n Neighbor_only_result.score = np.where(Neighbor_only_result.score.isna(), 0, Neighbor_only_result.score)\n #sorted by the normalized expect return in training data\n Neighbor_only_result = Neighbor_only_result.sort_values(by = ['Member_encoding', 'score'], ascending = False)\n Neighbor_only_result = Neighbor_only_result.groupby('Member_encoding').head(12)\n \n return Neighbor_only_result, Neighbor_result\n\n'''\nModel - SVD_new\n'''\ndef SVD_surprise_only(Trainset, N = 30):\n reader = Reader()\n Trainset_changetype = Dataset.load_from_df(Trainset[['Member_encoding', 'Game_encoding', 'score']], reader)\n Trainset_changetype_result = Trainset_changetype.build_full_trainset()\n svd = SVD(n_factors = 20,\n n_epochs = 20,\n lr_all = 0.01,#0.0001,\n random_state = 1234)\n svd.fit(Trainset_changetype_result)\n\n games = list(Trainset.Game_encoding.unique()) # Get our unique games that were purchased\n \n x = np.zeros([len(games), len(games)])\n \n \n for k in range(0, round(np.shape(x)[0]/200)+1):\n for l in range(0, round(np.shape(x)[0]/200)+1):\n minxindex = k*200 \n minyindex = l*200\n maxxindex = ((k+1) * 200) #- 1\n maxyindex = ((l+1) * 200) #- 1\n if k == round(np.shape(x)[0]/200):\n maxxindex = np.shape(x)[1] + 1\n if l == round(np.shape(x)[0]/200):\n maxyindex = np.shape(x)[1] + 1\n cut0 = np.dot(svd.pu, np.transpose(svd.qi[minxindex:maxxindex,:]))\n cut1 = np.dot(svd.pu, np.transpose(svd.qi[minyindex:maxyindex,:]))\n x[minxindex:maxxindex,minyindex:maxyindex] = cosine_similarity(np.transpose(cut0), np.transpose(cut1))\n\n #model SVD_New\n cosine_sim_x = pd.DataFrame(data = x, \n index=games,\n columns=games)\n gamesplayed = Trainset.groupby(['Member_encoding'])['Game_encoding'].apply(list).reset_index(name='games')\n gamesmax = np.array(gamesplayed.games.map(lambda x: ((cosine_sim_x.loc[x,:].values).max(axis=0))))\n gamelist = np.array(cosine_sim_x.columns)\n \n def Get_neighbor_30(x):\n # x[x>0.99] = 0.0\n return (gamelist[np.flip(np.argsort(x, axis=0))[0:N, ]])\n filtered = list(map(Get_neighbor_30, gamesmax))\n filtered_array = np.array(filtered)\n filtered_array = filtered_array.reshape(filtered_array.shape[0] * filtered_array.shape[1], -1)\n filtered_array = filtered_array.reshape(-1,)\n SVD_Neighbor = pd.DataFrame({'Member_encoding': np.repeat(np.array(np.unique(Trainset.Member_encoding)), N, axis=0), \n 'Game_encoding': filtered_array})\n #SVD_Neighbor_result = SVD_Neighbor.groupby('member_id').head(12)\n SVD_Neighbor_result = SVD_Neighbor.merge(Trainset[['Member_encoding', 'Game_encoding', 'score']],\n how = 'left',\n on = ['Member_encoding', 'Game_encoding'])\n SVD_Neighbor_result.score = np.where(SVD_Neighbor_result.score.isna(), 0, SVD_Neighbor_result.score)\n SVD_Neighbor_result = SVD_Neighbor_result.sort_values(by = ['Member_encoding', 'score'], ascending = False)\n SVD_Neighbor_result = SVD_Neighbor_result.groupby('Member_encoding').head(12)\n \n return SVD_Neighbor, SVD_Neighbor_result\n\n" }, { "alpha_fraction": 0.597152829170227, "alphanum_fraction": 0.6103895902633667, "avg_line_length": 45.034481048583984, "blob_id": "1d51b8f8f270a925c67d8db865404aa2c22d88e6", "content_id": "c5c226ed77af8fecb323440d431b5bc6e1100a1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 4004, "license_type": "no_license", "max_line_length": 132, "num_lines": 87, "path": "/RecommendationEngine_R/tests/test_Log_To_Database.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "context(\"test_Log_To_Database\")\nsetwd('..')\nsource('GlobalConfig.R')\nswitcher = odbcDriverConnect(connection = \"driver={SQL Server};server=JG\\\\MSSQLSERVER2016;uid=DS.Jimmy;pwd=4wvb%ECX;\")== -1\nif (switcher) stop(\"No usable Database Connection\")\n\nprod = new('Log_To_Database', 'recommendation',TRUE)\ntest = new('Log_To_Database', 'recommendation',FALSE)\n\n\ntest_that(\n 'initialization',\n {\n skip_if(switcher)\n expect_s4_class(prod,'Log_To_Database')\n expect_error(new('Log_To_Database','recommendation','production'))\n expect_s4_class(test,'Log_To_Database')\n }\n)\n\ntest_that(\n 'initializedb',\n {\n skip_if(switcher)\n expect_equal(sqlQuery(prod@dbhandle,paste0(\"select starttime from [Datascientist].[dbo].[RunningRecord] where starttime = '\",\n as.character(prod@starttime),\"'\"))[1],data.frame('starttime'=as.character(prod@starttime)))\n expect_equal(sqlQuery(test@dbhandle,paste0(\"select starttime from [Datascientist].[dbo].[RunningRecord] where starttime = '\",\n as.character(test@starttime),\"'\"))[1],data.frame('starttime'=as.character(test@starttime)))\n expect_equal(sqlQuery(test@dbhandle,paste0(\"select Environment from [Datascientist].[dbo].[RunningRecord] where starttime = '\",\n as.character(test@starttime),\"'\"))[1],data.frame('Environment'='staging'))\n expect_equal(sqlQuery(prod@dbhandle,paste0(\"select Environment from [Datascientist].[dbo].[RunningRecord] where starttime = '\",\n as.character(prod@starttime),\"'\"))[1],data.frame('Environment'='production'))\n expect_equal(sqlQuery(prod@dbhandle,paste0(\"select Status from [Datascientist].[dbo].[RunningRecord] where starttime = '\",\n as.character(prod@starttime),\"'\"))[1],data.frame('Status'='initialized'))\n expect_equal(sqlQuery(test@dbhandle,paste0(\"select Status from [Datascientist].[dbo].[RunningRecord] where starttime = '\",\n as.character(test@starttime),\"'\"))[1],data.frame('Status'='initialized'))\n }\n)\n\ntest_that(\n 'logtodb',\n {\n skip_if(switcher)\n log_to_database(test,'Working...')\n expect_equal(sqlQuery(test@dbhandle,paste0(\"select Status from [Datascientist].[dbo].[RunningRecord] \n where starttime = '\",\n as.character(test@starttime),\"'\"))[1],data.frame('Status'='Working...'))\n log_to_database(test,'Completed')\n expect_equal(sqlQuery(test@dbhandle,paste0(\"select Status from [Datascientist].[dbo].[RunningRecord] \n where starttime = '\",\n as.character(test@starttime),\"'\"))[1],data.frame('Status'='Completed'))\n expect(as.POSIXlt(sqlQuery(test@dbhandle,paste0(\"select endtime from [Datascientist].[dbo].[RunningRecord] \n where starttime = '\",\n as.character(test@starttime),\"'\"))[1]$endtime) > test@starttime)\n \n \n }\n)\n\n\ntest_that(\n 'set_timestamp',\n {\n skip_if(switcher)\n test = set_timestamp(test,'2018-11-04')\n expect_equal(sqlQuery(test@dbhandle,paste0(\"select Date from [Datascientist].[dbo].[RunningRecord] \n where starttime = '\",\n as.character(test@starttime),\"'\"))[1],data.frame('Date'='2018-11-04'))\n \n expect_equal(test@lastupdate,'2018-11-04')\n }\n)\n\ntest_that(\n 'getEnvironment',\n {\n skip_if(switcher)\n expect_equal('staging',getEnvironment(test))\n expect_equal('production',getEnvironment(prod))\n }\n)\n\nsqlQuery(prod@dbhandle,paste0(\"delete from [Datascientist].[dbo].[RunningRecord] where starttime = '\", \n as.character(prod@starttime),\"'\"))\n\nsqlQuery(test@dbhandle,paste0(\"delete from [Datascientist].[dbo].[RunningRecord] where starttime = '\", \n as.character(test@starttime),\"'\"))" }, { "alpha_fraction": 0.642688512802124, "alphanum_fraction": 0.6546513438224792, "avg_line_length": 39.98064422607422, "blob_id": "1a646b9534ae6813fb96650cf42beb357bf3e9fd", "content_id": "2402483db3900e502a421967253f334c3b7c5586", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 6353, "license_type": "no_license", "max_line_length": 171, "num_lines": 155, "path": "/RecommendationEngine_R/tests/test_get_data.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "\ncontext(\"test_get_data\")\nsetwd(\"..\")\nsource(\"GlobalConfig.R\")\n\n\n\nswitcher = odbcDriverConnect(connection = \"driver={SQL Server};server=JG\\\\MSSQLSERVER2016;uid=DS.Jimmy;pwd=4wvb%ECX;\")== -1\nif (switcher) skip(\"No usable Database Connection\")\n\n\n###conformity of the database\ntest_that(\n 'database_conformity',\n {\n expect_s3_class(new(\"getMSSQL_counts_data\",TRUE)@conn,'RODBC')\n expect_s3_class(new(\"getMSSQL_counts_data\",FALSE)@conn,'RODBC')\n target_db = data.frame(name = 'DataScientist')\n expect_equal( dim(sqlQuery(new('getMSSQL_counts_data',TRUE)@conn,\n \"select name from sys.databases where name = 'DataScientist'\"))[1],1)\n #expect_equal( sqlQuery(new('getMSSQL_counts_data',FALSE)@conn,\n # \"select name from sys.databases where name = 'DataScientist'\"),target)\n \n }\n)\n\ncontext(\"table_conformity\")\ntest_that(\n 'table_conformity',\n {\n queryobj = new('getMSSQL_counts_data',TRUE)@conn\n sqlQuery(queryobj,\"use DataScientist;\")\n target_table = data.frame(name = c('IntelligentGame','GameType','BetRecordMonthlySystemCodeGame'))\n target_table$name = sort(target_table$name)\n expect_equal(sqlQuery(queryobj,\"select name from sys.tables where name IN ('IntelligentGame','GameType','BetRecordMonthlySystemCodeGame') order by name\"),target_table)\n }\n)\n\ntest_that(\n 'IntelligentGame_Conformity',\n {\n queryobj = new('getMSSQL_counts_data',TRUE)@conn\n sqlQuery(queryobj,\"use DataScientist;\")\n expect_equal(dim(sqlQuery(queryobj,\"select column_name from information_schema.columns where\n table_name ='IntelligentGame' and column_name in ('Date','RawDataType',\n 'GameCode','Top1Game','Top2Game','Top3Game','Top4Game','Top5Game',\n 'Top6Game','Top7Game','Top8Game','Top9Game','Top10Game')\"))[1], 13)\n expect_equal(dim(sqlQuery(queryobj,\"select count(*), date, rawdatatype, gamecode from \n datascientist.dbo.intelligentgame group by date,rawdatatype,gamecode having\n count(*) > 1\"))[1],0)\n for (i in c(1:10))\n {\n expect_equal(dim(sqlQuery(queryobj,paste(\"select Top\",i,\"Game from datascientist.dbo.intelligentgame where Top\",i,\"Game not like '%,%'\",\n collapse='',sep='')))[1],0)\n }\n }\n )\n\ntest_that(\n 'GameType_Conformity',\n {\n queryobj = new('getMSSQL_counts_data',TRUE)@conn\n sqlQuery(queryobj,\"use DataScientist;\")\n expect_equal(dim(sqlQuery(queryobj,\"select column_name from information_schema.columns where\n table_name = 'GameType' AND column_name in ('Id','RawDataType','GameCode')\"))[1],3)\n expect_is(sqlQuery(queryobj,\"select top 100 id from datascientist.dbo.gametype\")[1,1],\"integer\")\n expect_gt(dim(sqlQuery(queryobj,\"select id from datascientist.dbo.gametype\"))[1],100)\n \n }\n)\n\ntest_that(\n 'BetRecordMonthlySystemCodeGame_Conformity',\n {\n queryobj = new('getMSSQL_counts_data',TRUE)@conn\n sqlQuery(queryobj,\"use DataScientist;\")\n expect_equal(dim(sqlQuery(queryobj,\"select column_name from information_schema.columns where\n table_name = 'BetRecordMonthlySystemCodeGame' and column_name in ('Id','First30Days','SystemCode',\n 'MemberId','CategoryId','RawDataType','GameCode','Counts')\"))[1],8)\n \n }\n )\n\ntest_that(\n 'Test if there are games not in DataScientist.dbo.gametype',\n {\n queryobj = new('getMSSQL_counts_data',TRUE)@conn\n sqlQuery(queryobj,\"use DataScientist;\")\n expect_equal(dim(sqlQuery(queryobj,\"select * from ( select distinct Categoryid, rawdatatype,gamecode from \n BetRecordMonthlySystemCodeGame ) x left join gametype y on x.gamecode = y.gamecode and x.rawdatatype = y.rawdatatype\n where y.id is NULL\"))[1],0)\n \n }\n )\n\ntest_that(\n 'Test if date of last_update > 5 days ago and on the same day',\n {\n queryobj = new('getMSSQL_counts_data',TRUE)@conn\n sqlQuery(queryobj,\"use DataScientist;\")\n expect_gt(5,abs(as.numeric(as.Date(sqlQuery(queryobj,\"select max(First30Days) from BetRecordMonthlySystemCodeGame\")[[1]],'%Y-%m-%d') - Sys.Date())))\n expect_gt(as.numeric(Sys.Date() - as.Date(sqlQuery(queryobj,\"select max(First30Days) from BetRecordMonthlySystemCodeGame\")[[1]],'%Y-%m-%d')),0)\n expect_gt(5,abs(as.numeric(as.Date(sqlQuery(queryobj,\"select max(date) from IntelligentGame\")[[1]],'%Y-%m-%d') - Sys.Date())))\n expect_gt(as.numeric(Sys.Date() - as.Date(sqlQuery(queryobj,\"select max(date) from IntelligentGame\")[[1]],'%Y-%m-%d')),0)\n ##will indicate that it didn't run after update though\n expect_equal( abs(as.numeric(as.Date(sqlQuery(queryobj,\"select max(date) from IntelligentGame\")[[1]],'%Y-%m-%d'))),\n abs(as.numeric(as.Date(sqlQuery(queryobj,\"select max(First30Days) from BetRecordMonthlySystemCodeGame\")[[1]],'%Y-%m-%d') )))\n }\n)\n\ncontext(\"test_get_data_performance\")\ntest_that( \n 'Test actual data processing of this module:data',\n {\n object = new('getMSSQL_counts_data',TRUE)\n object = setTimeLastUpdatedDB(object)\n expect_s3_class(as.Date(getTimeLastUpdatedDB(object),'%Y-%m-%d'),'Date')\n expect_gt(0,as.numeric(as.Date(getTimeLastUpdatedDB(object),'%Y-%m-%d') - Sys.Date()))\n }\n)\n\ntest_that(\n \"Test actual data processing of this module: recommendations\",\n {\n object = new('getMSSQL_counts_data',TRUE)\n object = setTimeLastUpdatedDB(object)\n Recs = getRecommendationSet(object)\n expect_gt(dim(Recs)[1],50)\n expect_is(Recs$MemberId, 'integer')\n expect_is(Recs$key,'integer')\n Control= getControlSet(object)\n expect_equal(sum(Control$key %in% unique(Recs$key)),length(Control$key))\n }\n)\n\ntest_that(\n \"Test actual data processing of this module: control\",\n {\n object = new('getMSSQL_counts_data',TRUE)\n object = setTimeLastUpdatedDB(object)\n Control= getControlSet(object)\n expect_gt(dim(Control)[1],50)\n expect_is(Control$key,'integer')\n }\n)\n\ntest_that(\n \"Test actual data processing of this module: Hot\",\n {\n object = new('getMSSQL_counts_data',TRUE)\n object = setTimeLastUpdatedDB(object)\n Hot= getHotSet(object)\n expect_equal(dim(Hot)[1],10)\n expect_is(Hot$id,'integer')\n }\n)\n" }, { "alpha_fraction": 0.6327616572380066, "alphanum_fraction": 0.6579933166503906, "avg_line_length": 28.15517234802246, "blob_id": "6919855b260ec1f6150a0d2119b721fa51b2e0f4", "content_id": "753a41e55b175cb1802a17dc21b05e20d9f05794", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 5073, "license_type": "no_license", "max_line_length": 95, "num_lines": 174, "path": "/RecommendationEngine_R/tests/test_preprocessing.R", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "library(testthat)\ncontext(\"Preprocessing_Tests\")\n\nsetwd(\"..\")\nsource('GlobalConfig.R')\n\n\n\n##basic properties\ntest_that(\n 'initialization',\n {\n expect_s4_class(new(\"preprocessing\"),'preprocessing')\n expect_s4_class(new(\"preprocessing_counts\"),'preprocessing_counts')\n expect_s3_class(new(\"preprocessing_counts\")@Recommendationset, 'data.frame')\n expect_s3_class(new(\"preprocessing_counts\")@control, 'data.frame')\n expect_equal(new(\"preprocessing_counts\")@Members, vector())\n expect_equal(new(\"preprocessing_counts\")@Games, vector())\n #expect_equal(new(\"preprocessing_counts\")@Hot, data.frame())\n }\n)\n\n\n\n###is the object usable\ntest_that(\n 'getvalidatedDataSets',\n {\n ##mock resulted dataset\n coll = new('getMSSQL_counts_data',TRUE,TRUE)\n obj = new('preprocessing_counts')\n\tobj@timestamp = getTimeLastUpdatedDB(coll)\n \n \n obj@Recommendationset = mock_getRecommendationSet(coll)\n obj@control = mock_getControlSet(coll)\n obj@Hot = mock_getHotSet(coll)\n obj = validateData(obj,obj@Recommendationset,obj@control,obj@Hot)\n\tobj@Recommendationset$key = as.numeric(obj@Recommendationset$key)\n\tvalidateData(obj,rbind(obj@Recommendationset, c(1,50,3)), obj@control, obj@Hot)\n }\n)\n\n\ntest_that(\n\t'getvalidatedRecommendation',\n\t{\n\t coll = new('getMSSQL_counts_data',TRUE,TRUE)\n\t\tobj = new('preprocessing_counts')\n\t\tobj@timestamp = getTimeLastUpdatedDB(coll) \n\t\tzm = mock_getRecommendationSet(coll)\n\t\tvalidateRecommendation(obj,zm)\n\t\texpect_equal(zm,getRecommendation(validateRecommendation(obj,zm)))\n\t\t\n\t\tzm$key = 'a0'\n\t\t#expect_message(validateRecommendation(obj,zm),'classes recommendation incompatible')\n\t\t#stub add further tests\n\t}\n)\n\t\ntest_that(\n\t'getvalidatedControl',\n\t{\n\t coll = new('getMSSQL_counts_data',TRUE,TRUE)\n\t\tobj = new('preprocessing_counts')\n\t\tobj@timestamp = getTimeLastUpdatedDB(coll) \n\t\tzm = mock_getRecommendationSet(coll)\n\t\tctr = mock_getControlSet(coll)\n\t\tvalidateControl(obj,zm,ctr)\n\t\texpect_equal(ctr,getControl(validateControl(obj,zm,ctr)))\n\t\t\n\t\tzm$key = 'a0'\n\t\t#expect_message(validateRecommendation(obj,zm),'classes recommendation incompatible')\n\t\t#stub add further tests\n\t}\n)\t\n\t\nzm = \nrbind(\nc(5, 0, 0, 0, 3, 0, 4, 2, 0, 0, 4),\nc(3, 3, 0, 4, 0, 5, 4, 0, 0, 2, 0),\nc(1, 0, 4, 4, 3, 0, 0, 5, 0, 0, 0),\nc(0, 0, 0, 0, 0, 0, 0, 4, 1, 0, 0),\nc(0, 0, 0, 0, 0, 0, 0, 0, 1, 5, 0),\nc(0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 2)\n)\n\ntest_that(\n 'preprocessing',\n {\n test = mock_getvalidatedDataSets(new('preprocessing_counts'))\n preprocess_result = preprocess(test)\n expect_s4_class(preprocess_result@Sparse,'dgCMatrix')\n expect_equal(preprocess_result@Members,c(1,2,3,4,5,6))\n expect_equal(preprocess_result@Games,c('1','10','11','2','3','4','5','6','7','8','9'))\n expect_equal(sum(as.matrix(preprocess_result@Sparse) - zm), 0)\n }\n)\n\n\ntest_that(\n 'getRecommendation',\n {\n coll = new('getMSSQL_counts_data',TRUE,TRUE)\n test = mock_getvalidatedDataSets(new('preprocessing_counts'))\n preprocess_result = preprocess(test)\n expect_s3_class(getRecommendation(preprocess_result), 'data.frame')\n expect_equal(getRecommendation(preprocess_result),mock_getRecommendationSet(coll) )\n expect_equal(sum(as.matrix(preprocess_result@Sparse) - zm), 0)\n }\n)\n\ntest_that(\n 'getSparse',\n {\n coll = new('getMSSQL_counts_data',TRUE,TRUE)\n test = mock_getvalidatedDataSets(new('preprocessing_counts'))\n preprocess_result = preprocess(test)\n expect_s4_class(getSparse(preprocess_result),'dgCMatrix')\n expect_equal(sum(as.matrix(preprocess_result@Sparse) - zm), 0)\n }\n)\n\ntest_that(\n 'getGames',\n {\n coll = new('getMSSQL_counts_data',TRUE,TRUE)\n test = mock_getvalidatedDataSets(new('preprocessing_counts'))\n preprocess_result = preprocess(test)\n expect_is(getGames(preprocess_result),'character')\n expect_equal(getGames(preprocess_result),c('1','10','11','2','3','4','5','6','7','8','9') )\n }\n)\n\ntest_that(\n 'getmembers',\n {\n coll = new('getMSSQL_counts_data',TRUE,TRUE)\n test = mock_getvalidatedDataSets(new('preprocessing_counts'))\n preprocess_result = preprocess(test)\n expect_is(getMembers(preprocess_result),'numeric')\n expect_equal(getMembers(preprocess_result),c(1,2,3,4,5,6))\n }\n)\n\ntest_that(\n 'getHot',\n {\n coll = new('getMSSQL_counts_data',TRUE,TRUE)\n test = mock_getvalidatedDataSets(new('preprocessing_counts'))\n preprocess_result = preprocess(test)\n expect_is(getHot(preprocess_result),'data.frame')\n }\n)\n\ntest_that(\n 'getControl',\n {\n coll = new('getMSSQL_counts_data',TRUE,TRUE)\n test = mock_getvalidatedDataSets(new('preprocessing_counts'))\n preprocess_result = preprocess(test)\n expect_is(getControl(preprocess_result),'data.frame')\n }\n)\n\ntest_that(\n\t'getTimeLastUpdated',\n\t{\n\t\tcoll = new('getMSSQL_counts_data',TRUE,TRUE)\n\t\ttest = getTimeLastUpdatedDB(coll)\n\t\texpect_equal(test,'2018-11-03')\n\t\t\n\t}\n)\n" }, { "alpha_fraction": 0.5899964570999146, "alphanum_fraction": 0.6024656295776367, "avg_line_length": 48.98591613769531, "blob_id": "424521fb86f80debf76de00f98e1efe0b4f5cb0b", "content_id": "6d8eed1a1362dfe188dc546c8fbcf88077cc45e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14195, "license_type": "no_license", "max_line_length": 160, "num_lines": 284, "path": "/RecommendationEngine_Python/ModelResearch/DS_RecommendSystem.py", "repo_name": "tdebusschere/RecommendationEngine", "src_encoding": "UTF-8", "text": "\"\"\"\n@author: Jimmy\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport os \nimport random\nimport scipy.sparse as sparse\nfrom scipy.sparse.linalg import spsolve\nfrom sklearn.metrics.pairwise import linear_kernel, cosine_similarity\nfrom surprise import Reader, Dataset, evaluate, Dataset, accuracy\nfrom surprise import SVD, SVDpp, SlopeOne, NMF, NormalPredictor, KNNBaseline, KNNBasic\nfrom surprise import KNNWithMeans, KNNWithZScore, BaselineOnly, CoClustering\nfrom surprise.model_selection import cross_validate, train_test_split, GridSearchCV\nfrom sklearn import metrics\nos.chdir('C:/Users/ADMIN/Desktop/Project/RecommendSystem') #cd\n\n## function zone\ndef Pre_processing(df): \n result = df.copy()\n result['member_id'] = result['member_id'].astype('int64')\n result['dates'] = result['dates'].astype('int64')\n result['game_id'] = result['game_id'].astype('int64')\n result['bet_amount'] = result['bet_amount'].astype('float64')\n result['payoff'] = result['payoff'].astype('float64')\n result['commissionable'] = result['commissionable'].astype('float64')\n result['Expect_earning_ratio'] = result['Expect_earning_ratio'].astype('float64')\n result['gamecode'] = result['gamecode'].astype('category')\n # We will multiply the ratio from the gamehall in the future but the information we haven't received yet.\n # and assume every gamehall keep the same ==1\n result.insert(11, 'expect_earn', result['commissionable'] * result['Expect_earning_ratio'])\n #result.insert(12, 'expect_earn_per_day', result['expect_earn'] / result['dates'])\n result.insert(12, 'expect_earn_per_day', result['commissionable'] )#/ result['dates']\n result.insert(13, 'key', list(zip(result['RawDataType'], result['gamecode'])))\n return(result)\n \n## filter & Exclude the just play one game people( Noise and it can't give our model any help)\ndef Pre_processing_train(x): \n x = x[(x['dates'] > 0) & (x['bet_amount'] > 0) & (x['commissionable'] > 0)]\n group = x.groupby('member_id', as_index=False).agg({'game_name': ['count']})\n group.columns = ['member_id', 'count']\n group = group[group['count'] != 1]\n group = group.reset_index(drop=True)\n x = x[x.member_id.isin(group.member_id)]\n x = x.reset_index(drop = True)\n return(x)\n\n#Define the hot game for the newuser or the user not in train data \ndef Hot_Game(df, feature = 'commissionable', n = 12): \n if feature == 'commissionable':\n FindHotGame = train_data.groupby('game_id', as_index=False).agg({'commissionable': ['sum']}) \n elif feature == 'member_id':\n FindHotGame = train_data.groupby('game_id', as_index=False).agg({'member_id': ['count']})\n else:\n print('Not Defined') \n FindHotGame.columns = ['game_id', 'feature']\n FindHotGame = FindHotGame.sort_values(by = ['feature'], ascending = False).reset_index(drop = True)\n HotGame = list(FindHotGame.game_id[0:n])\n return(HotGame)\n\n# what does the 30 come from? 95% percentile\ndef Get_neighbor_30(x): \n #x[x>0.99] = 0.0\n return(gamelist[np.flip(np.argsort(x,axis=0))[0:30,]])\n \ndef Get_AUC_intrain(input_df): \n #hot game must be a list and there were 12 container.\n df = test_data[['member_id']].drop_duplicates().merge(input_df[['member_id', 'game_id']], \n how = 'left',\n on = ['member_id'])\n df = df[~df.game_id.isna()]\n df['game_id'] = df['game_id'].astype('int64')\n\n \n df = df.merge(test_data[['member_id', 'game_id', 'commissionable']], \n how = 'left', \n on = ['member_id', 'game_id'])\n df.commissionable = np.where(df.commissionable.isna(), 0, 1) #play as TP\n df.columns = ['member_id', 'game_id', 'TP']\n df.loc[:,'FP'] = 1 - df.TP\n \n aggregated = df[['member_id', 'TP']].groupby('member_id', as_index=False).sum()\n aggregated.loc[:,'FP_n'] = 12 - aggregated.TP\n aggregated.columns = ['member_id', 'TP_n', 'FP_n']\n grade0_memberid = aggregated[aggregated.TP_n == 0].member_id\n\n tmp = df[~df.member_id.isin(grade0_memberid)]\n tmp = tmp.merge(aggregated, how='left', on='member_id')\n tmp.loc[:,'TPR'] = tmp.TP / tmp.TP_n\n tmp.loc[:,'FPR'] = tmp.FP / tmp.FP_n\n auc_df = tmp[['member_id', 'TPR', 'FPR']].groupby(['member_id']).apply(lambda x:metrics.auc(np.cumsum(x.FPR), np.cumsum(x.TPR))) \n auc_score = auc_df.sum()/len(np.unique(df.member_id))\n return(auc_score)\n\ndef Get_AUC_notintrain(HotGame): \n #hot game must be a list and there were 12 container.\n raw = test_data[['member_id']].drop_duplicates().merge(Trainset[['member_id', 'game_id']], \n how = 'left',\n on = ['member_id'])\n NotIntrain = raw[raw.game_id.isna()].member_id\n df = pd.DataFrame({'member_id': np.repeat(np.array(NotIntrain), 12, axis=0),\n 'game_id': HotGame * len(NotIntrain)})\n df['game_id'] = df['game_id'].astype('int64')\n #df = pd.concat([df, NotIntraindata])\n \n df = df.merge(test_data[['member_id', 'game_id', 'commissionable']], \n how = 'left', \n on = ['member_id', 'game_id'])\n df.commissionable = np.where(df.commissionable.isna(), 0, 1) #play as TP\n df.columns = ['member_id', 'game_id', 'TP']\n df.loc[:,'FP'] = 1 - df.TP\n \n aggregated = df[['member_id', 'TP']].groupby('member_id', as_index=False).sum()\n aggregated.loc[:,'FP_n'] = 12 - aggregated.TP\n aggregated.columns = ['member_id', 'TP_n', 'FP_n']\n grade0_memberid = aggregated[aggregated.TP_n == 0].member_id\n\n tmp = df[~df.member_id.isin(grade0_memberid)]\n tmp = tmp.merge(aggregated, how='left', on='member_id')\n tmp.loc[:,'TPR'] = tmp.TP / tmp.TP_n\n tmp.loc[:,'FPR'] = tmp.FP / tmp.FP_n\n auc_df = tmp[['member_id', 'TPR', 'FPR']].groupby(['member_id']).apply(lambda x:metrics.auc(np.cumsum(x.FPR), np.cumsum(x.TPR))) \n auc_score = auc_df.sum()/len(np.unique(df.member_id))\n return(auc_score)\n \n## Customer play record and exclude the recommend game(In SQL) because it is off line test\nnames = ['member_id', 'dates', 'game_id', 'game_name','game_category','bet_amount', \n 'payoff','commissionable','RawDataType','gamecode', 'Expect_earning_ratio']\ntrain = pd.read_csv('TrainData_1101To1124.csv', header = 0, names = names) ##11/01~11/24 as training dataset\ntest = pd.read_csv('TestData_1125To1130.csv', header = 0, names = names) ##11/25~11/30 as test dataset \n \n## Pre_processing(define the feature type)\ntrain_data = Pre_processing(train)\ntest_data = Pre_processing(test)\n\n## filter & Exclude the just play one game people( Noise and it can't give our model any help)\ntrain_data = Pre_processing_train(train_data)\n# =============================================================================\n# test_memberid = np.unique(test_data.member_id)\n# train_data_memberid = np.unique(train_data.member_id)\n# test_notintrain = test_data[~test_data.member_id.isin(train_data_memberid)]\n# test_intrain = test_data[test_data.member_id.isin(train_data_memberid)]\n# print(len(np.unique(test_notintrain.member_id)), len(np.unique(test_intrain.member_id)), \n# len(np.unique(test_data.member_id)))\n# nb_choice = train_data.groupby('member_id', as_index = False).agg({'game_id': ['count']})\n# nb_choice.columns = ['member_id', 'countgame']\n# nb_choice = nb_choice.sort_values(by = ['countgame'], ascending = False).reset_index(drop = True)\n# nb_choice.countgame.describe()\n# np.percentile(nb_choice.countgame, [95])\n# =============================================================================\n\n\n#Define the hot game for the newuser or the user not in train data \nHotGame_inTrain = Hot_Game(train_data,\n feature = 'commissionable',\n n = 12)\n\n\nTrainset = train_data[['member_id','game_id','dates', 'expect_earn_per_day']].sort_values(by = ['member_id', 'game_id'], ascending=True).reset_index(drop=True)\n\n\n#zmm = ( Trainset.loc[:,'expect_earn_per_day'] - np.median(Trainset.loc[:,'expect_earn_per_day']) ) / np.std(Trainset.loc[:,'expect_earn_per_day'])\nmin_expect_earn_per_day = Trainset[['expect_earn_per_day']].min()\nmax_expect_earn_per_day = Trainset[['expect_earn_per_day']].max()\nmin_dates = Trainset[['dates']].min()\nmax_dates = Trainset[['dates']].max()\n\nzmm1 = np.float64((Trainset[['expect_earn_per_day']] - min_expect_earn_per_day) / (max_expect_earn_per_day - min_expect_earn_per_day))\nzmm2 = np.float64((Trainset[['dates']] - min_dates) / (max_dates - min_dates))\nzmm = 0.5 * zmm1 + 0.5 * zmm2\n#zmm = ( Trainset.loc[:,'expect_earn_per_day'] - np.median(Trainset.loc[:,'expect_earn_per_day']) ) / np.std(Trainset.loc[:,'expect_earn_per_day'])\nTrainset.loc[:, 'score'] = zmm\n\n\n#model of the cosine similarity\nmembers = list(Trainset.member_id.unique()) # Get our unique members\ngames = list(Trainset.game_id.unique()) # Get our unique games that were purchased\nscore_list = list(Trainset.score) # All of our score\n\n# Get the associated row, column indices\ncols = Trainset.member_id.astype('category', \n categories = members).cat.codes\nrows = Trainset.game_id.astype('category', \n categories = games).cat.codes \nsparse_df = sparse.csr_matrix((score_list, (rows, cols)), \n shape=(len(games), len(members)))\nprint('num of members : {}\\nnum of games : {}\\nnum of score : {}'.format(len(members), \n len(games), len(score_list)))\nprint(\"shape of record_sparse: \" , sparse_df.shape)\n\n\ncosine_sim = cosine_similarity(sparse_df, sparse_df) \ncosine_sim = pd.DataFrame(data = cosine_sim,\n index = games,\n columns = games)\n\n## get the neighbor 30 game of every user \ngamelist = np.array(cosine_sim.columns)\ngamesplayed = Trainset.groupby(['member_id'])['game_id'].apply(list).reset_index(name='games')\ngamesmax = np.array(gamesplayed.games.map(lambda x: ((cosine_sim.loc[x,:].values).max(axis=0))))\nfiltered = list(map(Get_neighbor_30, gamesmax))\n\nfiltered_array = np.array(filtered)\nfiltered_array = filtered_array.reshape(filtered_array.shape[0]* filtered_array.shape[1],-1)\nfiltered_array = filtered_array.reshape(-1, )\n\n\nNeighbor_result = pd.DataFrame({'member_id':np.repeat(np.array(np.unique(Trainset.member_id)), \n 30,\n axis=0),\n 'game_id': filtered_array})\nNeighbor_only_result = Neighbor_result.groupby('member_id').head(12)\nNeighbor_only_result = Neighbor_only_result.merge(Trainset[['member_id', 'game_id', 'score']], \n how = 'left', \n on = ['member_id', 'game_id'])\nNeighbor_only_result.score = np.where(Neighbor_only_result.score.isna(), 0, Neighbor_only_result.score)\n#sorted by the normalized expect return in training data\nNeighbor_only_result = Neighbor_only_result.sort_values(by = ['member_id', 'score'], ascending = False)\n\n# =============================================================================\n# Use the cv to find the hyperParameter\n# reader = Reader()\n# Trainset_changetype = Dataset.load_from_df(Trainset[['member_id', 'game_id', 'score']], reader)\n# Trainset[['member_id', 'game_id', 'score']].dtypes\n# \n# param_grid = {'n_factors': [20], \n# 'n_epochs': [20], \n# 'lr_all': [0.0008,0.001]}\n# gs = GridSearchCV(SVD, \n# param_grid, \n# measures = ['rmse'],\n# cv = 3)\n# gs.fit(Trainset_changetype)\n# \n# # Best RMSE score\n# print(gs.best_score['rmse'])\n# \n# # combination of parameters that gave the best RMSE score\n# print(gs.best_params['rmse'])\n# =============================================================================\n\n# model of the latent factor\nreader = Reader()\nTrainset_changetype = Dataset.load_from_df(Trainset[['member_id', 'game_id', 'score']], reader)\nTrainset_changetype_result = Trainset_changetype.build_full_trainset()\nsvd = SVD(n_factors = 20,\n n_epochs = 20,\n lr_all = 0.0001,\n random_state = 1234)\nsvd.fit(Trainset_changetype_result)\n\n\nmembers = list(Trainset.member_id.unique()) # Get our unique members\ngames = list(Trainset.game_id.unique()) # Get our unique games that were purchased\nLatent_result = pd.DataFrame(data = np.dot(svd.pu, np.transpose(svd.qi)),\n index = members,\n columns = games)\nLatent_result_array = np.array(Latent_result)\nLatent_result_array = Latent_result_array.reshape(Latent_result.shape[0] * Latent_result.shape[1], -1)\nLatent_result_array = Latent_result_array.reshape(-1, )\n\nLatent_result_df = pd.DataFrame({'member_id':np.repeat(np.array(Latent_result.index.unique()), \n len(games), \n axis = 0), \n 'game_id':games * len(members),\n 'Pred_Return':Latent_result_array}) \nLatent_only = Latent_result_df.sort_values(by = ['member_id', 'Pred_Return'], ascending = False)\nLatent_only_result = Latent_only.groupby('member_id').head(12)\n\n\n# model of the bind result\nResult_BindLatentandNeighbor = Neighbor_result.merge(Latent_result_df, \n how = 'left',\n on = ['member_id', 'game_id']) \nResult_BindLatentandNeighbor = Result_BindLatentandNeighbor.sort_values(by = ['member_id', 'Pred_Return'], ascending=False).reset_index(drop=True) \nBind_result = Result_BindLatentandNeighbor.groupby('member_id').head(12)\n\n\n#Result\nauc = Get_AUC_intrain(Bind_result[['member_id', 'game_id']])\nauc2 = Get_AUC_intrain(Latent_only_result[['member_id', 'game_id']])\nauc3 = Get_AUC_intrain(Neighbor_only_result[['member_id', 'game_id']])\nauc_notintrain = Get_AUC_notintrain(HotGame_inTrain)\nprint(auc, auc2, auc3, auc_notintrain)" } ]
46
AnkushCh/Hackerrank_Codes
https://github.com/AnkushCh/Hackerrank_Codes
d26c2df354a9436f21fe32d0bfdde88ab8d65d7a
28034f6a878d967719835decd6376bc45c7fd545
887ef38e405db2a69fe15f6a4eeced472f128b17
refs/heads/master
2023-04-19T18:39:01.936968
2021-04-07T18:33:32
2021-04-07T18:33:32
350,703,618
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.3976493775844574, "alphanum_fraction": 0.41429969668388367, "avg_line_length": 15.050000190734863, "blob_id": "62932801a14a8d9b759dc469813d1370f944f005", "content_id": "7d8d61c916706869d85d831600b6d69e97b01c3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1021, "license_type": "no_license", "max_line_length": 69, "num_lines": 60, "path": "/graph_bfs.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\n#define pb push_back\r\n#define f(i,n) for(int i = 0; i < n; i++)\r\n#define v vector<int>\r\n#define vv vector<vector<int>>\r\nusing namespace std;\r\n\r\nvector<bool> bol;\r\nvv g;\r\n\r\nvoid edge(int a, int b)\r\n{\r\n g[a].pb(b);\r\n g[b].pb(a);\r\n}\r\n\r\nvoid bfs(int u)\r\n{\r\n queue<int> q;\r\n \r\n q.push(u);\r\n bol[u] = true;\r\n \r\n while (!q.empty()) {\r\n \r\n int f = q.front();\r\n q.pop();\r\n \r\n cout << f << \" \";\r\n\r\n for (auto i = g[f].begin(); i != g[f].end(); i++) {\r\n if (!bol[*i]) {\r\n q.push(*i);\r\n bol[*i] = true;\r\n }\r\n }\r\n }\r\n}\r\nint main()\r\n{\r\n int n = 5;\r\n bol.assign(n,false); // marking visited element false initially\r\n g.assign(n,vector<int>()); // creating adjancy list of graph\r\n\r\n edge(0, 1);\r\n edge(0, 4);\r\n edge(1, 2);\r\n edge(1, 3);\r\n edge(1, 4);\r\n edge(2, 3);\r\n edge(3, 4);\r\n \r\n f(i,n)\r\n {\r\n if(!bol[i])\r\n bfs(i);\r\n }\r\n\r\n return 0;\r\n}" }, { "alpha_fraction": 0.3640211522579193, "alphanum_fraction": 0.41904762387275696, "avg_line_length": 20.5238094329834, "blob_id": "9dcd8cd644ab1c2980d3b2705cd2429f048db76a", "content_id": "44a99a2f6cadc09a67b47e73fbc57f49712152f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 945, "license_type": "no_license", "max_line_length": 71, "num_lines": 42, "path": "/vctr.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include <iostream> \r\n#include <vector> \r\n#include<algorithm>\r\n#include<cmath>\r\n \r\nusing namespace std; \r\n \r\nint main() \r\n{ \r\n// vector<int> g1{4,2,1,5,6,9,7,8,3}; \r\n \r\n// cout << \"Output of begin and end: \"; \r\n// for (auto i = g1.begin(); i != g1.end(); ++i) \r\n// cout << *i << \" \"; \r\n// long long int abc = 322327778234567877;\r\n// cout << \" Number of digit :\" << floor(log10(abc))+1 << endl;\r\n// cout << \"gcd :\" << __gcd(2,8);\r\n// reverse(g1.begin(),g1.end());\r\n// cout <<\"Reverse : \";\r\n\r\n// for(int i = 0; i < g1.size(); i++)\r\n// cout << g1[i] << \" \";\r\n\r\n// cout << \"Sort :\";\r\n\r\n// sort(g1.begin(),g1.end());\r\n// for(int i = 0; i < g1.size(); i++)\r\n// cout << g1[i] << \" \";\r\n \r\n int a[6] = {0};\r\n\r\n// iota(a,a+6,1);\r\n \r\n int x = sizeof(a)/a[0];\r\n cout << \"size of a : \" << x;\r\n for(int i = 0; i < x; i++)\r\n {\r\n cout << a[i] << \" \" << endl;\r\n }\r\n \r\n return 0; \r\n} " }, { "alpha_fraction": 0.42540791630744934, "alphanum_fraction": 0.4463869333267212, "avg_line_length": 15.510204315185547, "blob_id": "053ca58b98c27330cb7b32c7f3bab7b4319c56b7", "content_id": "0a4f7788620dfeb48dfc8e0d4657223e3880fbd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 858, "license_type": "no_license", "max_line_length": 44, "num_lines": 49, "path": "/graphs_dfs.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\n#define v vector<int>\r\n#define vv vector<vector<int>>\r\n#define f(i,n) for(int i = 0; i < n; i++)\r\n#define pb push_back\r\nusing namespace std;\r\n\r\nvoid edge(v adj[], int u, int vi)\r\n{\r\n adj[u].pb(vi);\r\n adj[vi].pb(u);\r\n}\r\nvoid dfsutil(int u, v adj[], vector<bool>&b)\r\n{\r\n b[u] = true;\r\n cout << u <<\" \";\r\n for(int i = 0; i < adj[u].size(); i++)\r\n {\r\n if(b[adj[u][i]] == false)\r\n dfsutil(adj[u][i],adj,b);\r\n }\r\n}\r\n\r\nvoid dfs(v adj[], int n)\r\n{\r\n vector<bool>b(n,false);\r\n f(u,n)\r\n {\r\n if(b[u] == false)\r\n dfsutil(u,adj,b);\r\n }\r\n}\r\n\r\nint main()\r\n{\r\n int n = 5;\r\n v adj[n];\r\n edge(adj, 0, 1);\r\n edge(adj, 0, 4);\r\n edge(adj, 1, 2);\r\n edge(adj, 1, 3);\r\n edge(adj, 1, 4);\r\n edge(adj, 2, 3);\r\n edge(adj, 3, 4);\r\n dfs(adj,n);\r\n \r\n return 0;\r\n\r\n}\r\n" }, { "alpha_fraction": 0.4000000059604645, "alphanum_fraction": 0.4218390882015228, "avg_line_length": 16.553192138671875, "blob_id": "6079ab833998003b979c55ee96b9446701daccc3", "content_id": "751181c090d6ee8786ab4a0cfce459d6b8f57d89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 870, "license_type": "no_license", "max_line_length": 43, "num_lines": 47, "path": "/quicksort.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\nvoid swap(int *a,int *b)\r\n{\r\n int t = *a;\r\n *a = *b;\r\n *b = t;\r\n}\r\nint part(int arr[], int low,int high)\r\n{\r\n int pivot = arr[high];\r\n int i = low - 1;\r\n for(int j = low; j < high; j++)\r\n {\r\n if(pivot >= arr[j])\r\n {\r\n i++;\r\n swap(&arr[i], &arr[j]);\r\n }\r\n }\r\n swap(&arr[i+1],&arr[high]);\r\n return(i+1);\r\n}\r\nvoid quicksort(int arr[],int low, int high)\r\n{\r\n if(high > low)\r\n {\r\n int pi = part(arr,low,high);\r\n quicksort(arr,low,pi-1);\r\n quicksort(arr,pi+1,high);\r\n }\r\n}\r\n\r\nint main()\r\n{\r\n // quick sort\r\n int arr[] = {9,8,7,6,5,4,3,2,1};\r\n int n = sizeof(arr)/sizeof(arr[0]);\r\n cout << n;\r\n quicksort(arr,0,n-1);\r\n for(int i = 0; i < n; i++)\r\n {\r\n cout << arr[i] << \" \";\r\n } \r\n return 0;\r\n\r\n}" }, { "alpha_fraction": 0.5206611752510071, "alphanum_fraction": 0.5289255976676941, "avg_line_length": 15.428571701049805, "blob_id": "d408cd9b4173ad7a69b5d94af0271c74fe69bddf", "content_id": "63a485dc0e94086240318b4326d1c27def76201e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 242, "license_type": "no_license", "max_line_length": 34, "num_lines": 14, "path": "/data_str/count.py", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "# from collections import Counter\r\n# c = Counter(input())\r\n# print(len(c.values()))\r\n# print((c.keys()))\r\nl = list()\r\nfor _ in range(5):\r\n n = input()\r\n l.append(n)\r\nprint(l)\r\n\r\nx = l.pop()\r\nprint(l[-1])\r\nif 'a' in l:\r\n print(\"Yes\")" }, { "alpha_fraction": 0.41329479217529297, "alphanum_fraction": 0.45375722646713257, "avg_line_length": 15.399999618530273, "blob_id": "f3de7ac65b3f54728fa7dbf05a3b00289f9eb769", "content_id": "79c1f3d0573be73fa89aac581cf03d80b299c087", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 346, "license_type": "no_license", "max_line_length": 32, "num_lines": 20, "path": "/insert.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<vector>\r\n#include<algorithm>\r\n#include<string>\r\nusing namespace std;\r\nint main()\r\n{\r\n int bin[32];\r\n int num = 74434;\r\n int i = 0;\r\n while(num > 0)\r\n {\r\n bin[i] = num % 2;\r\n num = num / 2;\r\n i++;\r\n }\r\n for(int j = i-1; j >=0; j--)\r\n cout << bin[j] <<\" \";\r\n return 0;\r\n}" }, { "alpha_fraction": 0.48062342405319214, "alphanum_fraction": 0.48062342405319214, "avg_line_length": 18.842105865478516, "blob_id": "32e652452173261d9819c4d38fde3e78bf155635", "content_id": "b6aa3299051b163514d2c5236a6d998e9e3fb4a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2374, "license_type": "no_license", "max_line_length": 69, "num_lines": 114, "path": "/treetraverse.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nstruct TreeNode\r\n{\r\n int data;\r\n TreeNode *left;\r\n TreeNode *right;\r\n TreeNode(int data)\r\n {\r\n this-> data = data;\r\n left = right = NULL;\r\n }\r\n};\r\n\r\nTreeNode *insert(TreeNode *root, int item)\r\n{\r\n if(root == NULL)\r\n {\r\n struct TreeNode * node = new TreeNode(item);\r\n return node;\r\n }\r\n if(item < root -> data)\r\n {\r\n root -> left = insert(root->left,item);\r\n }\r\n else root -> right = insert(root->right,item);\r\n\r\n return root;\r\n}\r\n\r\nvoid search(TreeNode * &cur,TreeNode* &parent, int item)\r\n{\r\n while(cur != NULL && cur -> data != item)\r\n {\r\n parent = cur;\r\n if(item < cur -> data)\r\n cur = cur -> left;\r\n else cur = cur -> right;\r\n }\r\n}\r\n\r\nTreeNode* findMin(TreeNode *curr)\r\n{\r\n while(curr -> left != NULL)\r\n curr = curr -> left;\r\n return curr;\r\n}\r\n\r\nTreeNode* delete_Node(TreeNode * &root, int item)\r\n{\r\n TreeNode* parent = NULL;\r\n TreeNode* curr = NULL;\r\n search(curr,parent,item);\r\n if(curr -> left == NULL && curr -> right == NULL)\r\n {\r\n if(curr != root)\r\n {\r\n if(parent -> left==NULL)\r\n parent -> left == NULL;\r\n else parent -> right == NULL;\r\n }\r\n else root = NULL;\r\n free(root);\r\n }\r\n else if(curr -> left && curr -> right)\r\n {\r\n TreeNode* succ = findMin(curr -> right);\r\n int val = succ -> data;\r\n delete_Node(root,val);\r\n curr -> data = val;\r\n }\r\n else{\r\n TreeNode* child = curr -> left ? curr -> left: curr -> right;\r\n if(curr != root)\r\n {\r\n if(curr == parent -> left)\r\n parent -> left = child;\r\n else parent -> right = child;\r\n }\r\n else root = child;\r\n free(curr);\r\n }\r\n}\r\n\r\nvoid inorder(TreeNode *root)\r\n{\r\n if (root == NULL)\r\n return;\r\n inorder(root->left);\r\n cout << root->data << \" \";\r\n inorder(root->right);\r\n}\r\nvoid preorder(TreeNode *root)\r\n{\r\n if (root == NULL)\r\n return;\r\n cout << root->data << \" \";\r\n preorder(root->left);\r\n preorder(root->right);\r\n}\r\n\r\nvoid postorder(TreeNode *root)\r\n{\r\n if (root == NULL)\r\n return;\r\n postorder(root->left);\r\n postorder(root->right);\r\n cout << root->data << \" \";\r\n}\r\n\r\nint main()\r\n{\r\n}" }, { "alpha_fraction": 0.30203720927238464, "alphanum_fraction": 0.3321523368358612, "avg_line_length": 14.632352828979492, "blob_id": "a362082174fd5820c1897fd3ea914c49bff4be2d", "content_id": "53d6436290f3c03bbe8fb0d99e5e2570a45a5d2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1129, "license_type": "no_license", "max_line_length": 39, "num_lines": 68, "path": "/prim.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nvoid merge(int arr[],int l,int m,int r)\r\n{\r\n int n1 = m -l;\r\n int n2 = r-m;\r\n int L[n1];\r\n int R[n2];\r\n for(int i = 0; i < n1; i++)\r\n {\r\n L[i] = arr[l+i];\r\n }\r\n for(int i = 0; i < n2; i++)\r\n {\r\n R[i] = arr[m + i];\r\n }\r\n int i = 0;\r\n int j = 0;\r\n int k = 0;\r\n while(i < n1 && j < n2)\r\n {\r\n if(L[i] <= R[j])\r\n {\r\n arr[k] = L[i];\r\n i++;\r\n }\r\n else\r\n {\r\n arr[k] = R[j];\r\n j++;\r\n }\r\n k++;\r\n }\r\n while(i < n1)\r\n {\r\n arr[k] = L[i];\r\n i++;\r\n }\r\n while(j < n2)\r\n {\r\n arr[k] = R[j];\r\n j++;\r\n }\r\n}\r\nvoid mergesort(int arr[],int l,int r)\r\n{\r\n if(l < r)\r\n {\r\n int m = (l + r)/2;\r\n mergesort(arr,l,m);\r\n mergesort(arr,m+1,r);\r\n merge(arr,l,m,r);\r\n }\r\n}\r\n\r\nint main()\r\n{\r\nint arr[] = {8,0,5,3,4,2,5,0,1,1};\r\nint l = 0; \r\nint r = sizeof(arr)/sizeof(arr[0]) - 1;\r\nmergesort(arr,l,r);\r\nfor(int i = 0; i < 10; i++)\r\n{\r\n cout << arr[i] << \" \";\r\n} \r\nreturn 0; \r\n}" }, { "alpha_fraction": 0.5666666626930237, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 19.100000381469727, "blob_id": "27965994a4f8aab540b143dd88ebd169a68753b6", "content_id": "a99ff2c12e5cad11c3fd2d8eeba2552b73d17505", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 420, "license_type": "no_license", "max_line_length": 30, "num_lines": 20, "path": "/hell.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\n#include<string.h>\r\nusing namespace std;\r\nint main()\r\n{\r\nstring s = \"This is a string\";\r\n// cout << \"Enter your name:\";\r\n// getline(cin,s);\r\n// s.push_back('c');\r\n// s.append(\" choudhary\");\r\ncout << s << endl;\r\ncout << s.capacity() << endl;\r\ns.resize(s.length() - 3);\r\ncout << s.capacity()<<endl;\r\ncout << s<<endl;\r\ns.shrink_to_fit();\r\ncout << s.capacity()<<endl;\r\ncout << s<<endl;\r\nreturn 0;\r\n}" }, { "alpha_fraction": 0.4109589159488678, "alphanum_fraction": 0.41438356041908264, "avg_line_length": 16.375, "blob_id": "dbb1970c0fa129ec96ac510854f6cc2eb7eb33b7", "content_id": "5ef3e15b57b786dd7f8f4be0812298ff55a65c75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 292, "license_type": "no_license", "max_line_length": 46, "num_lines": 16, "path": "/regexx.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\nusing namespace std;\r\nint main()\r\n{\r\n int n;\r\n map<string,string>m;\r\n string k,v;\r\n cin >> n;\r\n for(int i = 0; i < n; i++)\r\n {\r\n cin >> k >> v;\r\n m[k] = v; \r\n }\r\n for(auto i : m)\r\n cout << i.first <<\" \" << i.second << endl;\r\n}" }, { "alpha_fraction": 0.40246912837028503, "alphanum_fraction": 0.4493827223777771, "avg_line_length": 14.279999732971191, "blob_id": "bd243d734e25d547dc61d40bbcaeaeca7e2b716a", "content_id": "7abda4dc8cd6eac0069a9b53efc63a1e7e61894e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 405, "license_type": "no_license", "max_line_length": 40, "num_lines": 25, "path": "/shutdown.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstdlib>\r\n#include<cstring>\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n string st1 = \"gfg\";\r\n string st2 = \"ggf\";\r\n int count1[256] = {0};\r\n int count2[256];\r\n \r\n for(int i = 0; i < st1.length();i++)\r\n {\r\n count1[st1[i]]++;\r\n\r\n }\r\n for(int i = 0; i < st1.length();i++)\r\n {\r\n cout << count1[i] << \" \";\r\n \r\n }\r\n\r\n return 0;\r\n}" }, { "alpha_fraction": 0.2577720284461975, "alphanum_fraction": 0.34585490822792053, "avg_line_length": 18.91891860961914, "blob_id": "d4c97b667401deb0ff5166179d61a4c8d5a0ded5", "content_id": "09a1e6da39bb9806c620969232df885565781ddd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 772, "license_type": "no_license", "max_line_length": 112, "num_lines": 37, "path": "/binr.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\nusing namespace std;\r\nint main()\r\n{\r\n vector<int>v{53,5,45,2,63,7,3,6,5,2,45,2,5,32,3,23,54,65,4,7,484,54,32,56,76,54,67,6,543,45,7,654,3456,765};\r\n sort(v.begin(),v.end());\r\n for(int i = 0; i < v.size(); i++)\r\n {\r\n cout << v[i] << \" \" << endl;\r\n }\r\n int x;\r\n cin >> x;\r\n int mid,f = 0,b = v.size()-1;\r\n mid = (f+b)/2;\r\n\r\n while(x != v[mid] && f < b)\r\n {\r\n if(x == v[mid])\r\n {\r\n cout << x << \" Found at \" << mid << \"position\"<<endl;\r\n break;\r\n }\r\n else\r\n {\r\n if(x < v[mid])\r\n {\r\n b = mid-1;\r\n }\r\n else\r\n {\r\n f = mid + 1;\r\n }\r\n }\r\n mid = (f + b)/2;\r\n }\r\n return 0;\r\n}" }, { "alpha_fraction": 0.4828973710536957, "alphanum_fraction": 0.4869215190410614, "avg_line_length": 15.785714149475098, "blob_id": "d76ce30804c225e357881a93c62c2817c6d29343", "content_id": "c0f99a52ff7d24fc9785e6d9b47ef98621db3ed0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 994, "license_type": "no_license", "max_line_length": 65, "num_lines": 56, "path": "/stack.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\r\n int duration;\r\n int num_of_intersections;\r\n int num_of_streets;\r\n int num_of_cars;\r\n int bonos_pts;\r\n\r\n cin >> duration;\r\n cin >> num_of_intersections;\r\n cin >> num_of_streets;\r\n cin >> num_of_cars;\r\n cin >> bonos_pts;\r\n\r\n vector<string>street_discp_name;\r\n \r\n int start;\r\n int end;\r\n string street_discp;\r\n int time_taken;\r\n\r\n for(int i = 0; i < num_of_streets; i++)\r\n {\r\n cin >> start;\r\n cin >> end;\r\n cin >> street_discp;\r\n street_discp_name[i] = street_discp;\r\n cin >> time_taken;\r\n\r\n }\r\n\r\n int P; //- the number of streets that the car wants to travel\r\n for(int i = 0; i < num_of_cars; i++)\r\n {\r\n cin >> P;\r\n vector<string>street_names;\r\n string names;\r\n for(int j = 0; j < P; j++)\r\n {\r\n cin >> names;\r\n street_names[i] = names;\r\n } \r\n }\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n return 0;\r\n}" }, { "alpha_fraction": 0.3382570147514343, "alphanum_fraction": 0.3530280590057373, "avg_line_length": 23.58490562438965, "blob_id": "5bd8e76505ef39ec00d81d6a8a51302a08a21cf2", "content_id": "18dc8c9b7a8a75a634c5a21357520d6ada5e7068", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1354, "license_type": "no_license", "max_line_length": 55, "num_lines": 53, "path": "/asci.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<vector>\r\n#include<algorithm>\r\nusing namespace std;\r\nint main()\r\n{\r\n vector<int>v{1,2,3,4,5,6,7,8,9};\r\n //sort(v.begin(),v.end());\r\n // int f = 0;\r\n // for(int i = 0; i < v.size(); i++)\r\n // {\r\n // cout << v[i] << \" \";\r\n // }\r\n // cout << endl;\r\n // int l = v.size() - 1;\r\n // int mid = (f+l)/2;\r\n // int x = 12;\r\n // if(binary_search(v.begin(),v.end(),x))\r\n // {\r\n // cout << x << \" present\"<< endl;\r\n // }\r\n // else{\r\n // cout << x << \" not present\";\r\n // }\r\n auto upr = upper_bound(v.begin(),v.end(),7);\r\n auto lw = lower_bound(v.begin(),v.end(),7);\r\n cout << \"Upper bound: \" << *upr << endl;\r\n cout << \"lower bound: \" << *lw << endl;\r\n\r\n cout << \"Upper bound: \" << upr - v.begin() << endl;\r\n cout << \"lower bound: \" << lw - v.begin() << endl;\r\n // cout << endl;\r\n // while(f <= l && v[mid] != x)\r\n // {\r\n // mid = (f+l)/2;\r\n\r\n // if(v[mid] == x)\r\n // {\r\n // cout << x << \" present at \" << mid;\r\n // break;\r\n // }\r\n // else if(v[mid] < x)\r\n // {\r\n // f = mid+1;\r\n // }\r\n // else{l = mid-1;}\r\n // if(f == l && v[mid] != x)\r\n // {\r\n // cout << x << \" not present \";\r\n // break;\r\n // }\r\n // }\r\n}" }, { "alpha_fraction": 0.3993288576602936, "alphanum_fraction": 0.4161073863506317, "avg_line_length": 14.666666984558105, "blob_id": "f88a7dd580cf783814e0a15445dc1af97b3ff472", "content_id": "5ab9a107114b455e224d369aee04803ba331e3eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 298, "license_type": "no_license", "max_line_length": 30, "num_lines": 18, "path": "/stackc.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<stack>\r\nusing namespace std;\r\nint main()\r\n{\r\n stack<int>s;\r\n for(int i = 0; i < 5; i++)\r\n {\r\n s.push(i);\r\n }\r\n for(int i = 0; i < 5; i++)\r\n {\r\n cout << s.top()<<endl;\r\n s.pop();\r\n }\r\n cout <<\"Size \"<< s.size();\r\nreturn 0;\r\n}" }, { "alpha_fraction": 0.44121915102005005, "alphanum_fraction": 0.4542815685272217, "avg_line_length": 14, "blob_id": "7723e14ada39015da3cb2f63c5901c3bc382e8aa", "content_id": "65151bc49265e41fc51628a48bf8e8a53bc98099", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 689, "license_type": "no_license", "max_line_length": 42, "num_lines": 43, "path": "/class1.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstring>\r\nusing namespace std;\r\n\r\nclass animals\r\n{\r\n char *name;\r\n int len;\r\n public:\r\n void naming(void);\r\n void printName();\r\n};\r\nvoid animals:: naming()\r\n{\r\n char *s;\r\n s = new char[20];\r\n cout << \"Enter the name of animal: \";\r\n cin >> s;\r\n len = strlen(s);\r\n name = new char[len + 1];\r\n strcpy(name,s);\r\n}\r\nvoid animals:: printName()\r\n{\r\n cout << \"Name : \" << name<<endl;\r\n}\r\n\r\nint main()\r\n{\r\n animals *a[3];\r\n for(int i = 0; i < 3; i++)\r\n {\r\n a[i] = new animals;\r\n a[i]->naming();\r\n }\r\n for(int i = 0; i < 3; i++)\r\n {\r\n a[i]->printName();\r\n }\r\n\r\n return 0;\r\n\r\n} " }, { "alpha_fraction": 0.3879221975803375, "alphanum_fraction": 0.405322402715683, "avg_line_length": 17.979591369628906, "blob_id": "26f67a2fed3aa0537f21f26ce414eb41ebe4613f", "content_id": "0a3ade8ab817117f01c3c44c54b3f7ae7fbdcaaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 977, "license_type": "no_license", "max_line_length": 52, "num_lines": 49, "path": "/stick.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <iomanip>\r\n#include <cassert>\r\n#include <cmath>\r\n#include <cstdio>\r\n#include <cstring>\r\n#include <cstdlib>\r\n#include <map>\r\n#include <set>\r\n#include <queue>\r\n#include <stack>\r\n#include <vector>\r\n#include <chrono>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n vector<int>v = {5,4,4,2,2,8};\r\n\r\n // int n = v.size();\r\n // sort(v.begin(),v.end());\r\n // for(int i = 0; i < n; i++)\r\n // {\r\n // cout << v.size();\r\n // v[i] = v[i] - v[0];\r\n // if(v[i] != 0)\r\n // v.push_back(v[i]);\r\n\r\n // for(auto j =v.begin() ; j < v.end(); j++)\r\n // {\r\n // v[*j] = v[*j] = v[0];\r\n // if(v[*j] == 0)\r\n // v.erase(j);\r\n // }\r\n\r\n // string s = \"ankush\";\r\n // string s1;\r\n // s1 = s;\r\n // cout << s;\r\n // for(int i = 0; i < s1.size(); i++)\r\n // {\r\n // char c = s1[i];\r\n // s.push_back(s[i]);\r\n // }\r\n \r\n return 0; \r\n}" }, { "alpha_fraction": 0.4937106966972351, "alphanum_fraction": 0.49685534834861755, "avg_line_length": 12.545454978942871, "blob_id": "199a7d782921d502282412794b0fcdd8ba5a68e9", "content_id": "46a0d35eba20360f38831b02e597f621c8614145", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 318, "license_type": "no_license", "max_line_length": 39, "num_lines": 22, "path": "/programersday.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nclass node{\r\n public:\r\n int data;\r\n node*left,*right;\r\n};\r\nnode *newnode(int data)\r\n{\r\n node* temp = new node;\r\n temp ->data = data;\r\n temp -> left = temp ->right = NULL;\r\n return temp;\r\n}\r\nint main(){\r\n \r\n \r\n \r\n \r\n return 0;\r\n}" }, { "alpha_fraction": 0.5068870782852173, "alphanum_fraction": 0.5371900796890259, "avg_line_length": 26.076923370361328, "blob_id": "2e389fd24c338507d8ba56e65611b0b9d515f34e", "content_id": "a4dd6c55c6c6dc80f267046ba7f33acf00278acc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 363, "license_type": "no_license", "max_line_length": 58, "num_lines": 13, "path": "/nested_logic.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\nusing namespace std;\r\nint main()\r\n{\r\n int day,month,year;\r\n int dday,dmonth,dyear;\r\n scanf(\"%d\", \"%d\",\"%d\",&day,&month,&year);\r\n scanf(\"%d\", \"%d\",\"%d\",&dday,&dmonth,&dyear);\r\n if(year != dyear) cout << \"10000\";\r\n else if(month != dmonth) cout << (dmonth - month)*500;\r\n else cout << (dday - day)*15;\r\n return 0;\r\n}" }, { "alpha_fraction": 0.47113165259361267, "alphanum_fraction": 0.487297922372818, "avg_line_length": 16.913043975830078, "blob_id": "9be11b9acf14c0cb60ac48e7fc30d2795b0153c1", "content_id": "467fd9814c4810c0c4fb0e8cbe450471e4673ddb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 433, "license_type": "no_license", "max_line_length": 36, "num_lines": 23, "path": "/quiz.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\nclass Node{\r\n public:\r\n int data;\r\n Node* left,*right;\r\n Node(int x)\r\n {\r\n data = x;\r\n left = right = 0;\r\n }\r\n};\r\n\r\nint main()\r\n{\r\n Node *root = new Node(10);\r\n root->left = new Node(2);\r\n root ->right = new Node(13);\r\n printf(\"%d\\n\",root->data);\r\n printf(\"%d\\n\",root->left->data);\r\n printf(\"%d\",root->right->data);\r\n return 0;\r\n}" }, { "alpha_fraction": 0.25278809666633606, "alphanum_fraction": 0.2552664279937744, "avg_line_length": 23.28125, "blob_id": "3814b1511e24bc7c0d33bfedde81ad4d5645b658", "content_id": "7f91c1a51de637b6d8596e6ba4fd773feb51acdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 807, "license_type": "no_license", "max_line_length": 69, "num_lines": 32, "path": "/stackarray.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<stack>\r\nusing namespace std;\r\nint main()\r\n{\r\n string str = \"{{(([])[])[]]}\";\r\n stack<char>a;\r\n for(int j = 0; j < str.length();j++)\r\n {\r\n if((str[j] == '(') || (str[j] == '{') || (str[j] == '['))\r\n { \r\n // cout << str[j];\r\n a.push(str[j]);\r\n }\r\n else if((str[j] == ')') && (a.top() == '('))\r\n {\r\n a.pop();\r\n\r\n }\r\n else if((str[j] == '}') && ('{' == a.top()))\r\n {\r\n a.pop();\r\n }\r\n else if((str[j] == ']') && ('[' == a.top()))\r\n a.pop();\r\n }\r\n if(a.empty())\r\n cout << \"YES\";\r\n else cout <<\"NO\";\r\n\r\n return 0;\r\n}" }, { "alpha_fraction": 0.42533937096595764, "alphanum_fraction": 0.479638010263443, "avg_line_length": 16.58333396911621, "blob_id": "da2e94001cbc62c7b571b7be8914891adc5a7581", "content_id": "874b74fa137deecfcb9ab1741af1bbb3335c5b2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 221, "license_type": "no_license", "max_line_length": 46, "num_lines": 12, "path": "/data_str/hash.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n \r\n vector<int>v1 = {5,-4,-7,6,8,3,-2};\r\n sort(v1.begin(),v1.end(), greater<int>());\r\n for(auto i : v1)\r\n cout << i << \" \";\r\n return 0;\r\n}" }, { "alpha_fraction": 0.392070472240448, "alphanum_fraction": 0.40969163179397583, "avg_line_length": 17.826086044311523, "blob_id": "5b0de3313dd9380b9b4b755c5069978f830295dc", "content_id": "047dca0c8121f8759047f678f193c01914731689", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 454, "license_type": "no_license", "max_line_length": 38, "num_lines": 23, "path": "/arraypointers.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstring>\r\nusing namespace std;\r\nint main()\r\n{\r\n char* str = \"poooop\";\r\n int len = strlen(str) - 1;\r\n int flag = 0;\r\n for(int i = 0; i < len/2; i++)\r\n {\r\n if(str[i] == str[len-i])\r\n {\r\n flag = 0; \r\n }\r\n else flag = 1;\r\n }\r\n if(flag == 0)\r\n {\r\n cout << \"String is palidrome\";\r\n }\r\n else cout << \"not palidrome\";\r\n return 0;\r\n}" }, { "alpha_fraction": 0.4711246192455292, "alphanum_fraction": 0.4954407215118408, "avg_line_length": 22.370370864868164, "blob_id": "584df5bff857d216e82acac5ceb6a45a6215fabd", "content_id": "51a18472188610a61c46a37d6658ac0cfcecdd88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 658, "license_type": "no_license", "max_line_length": 63, "num_lines": 27, "path": "/pointers.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\nint main()\r\n{\r\n int *ptr,**ptr2,a = 4;\r\n ptr = &a;\r\n cout <<\"Address of a is \"<<ptr <<endl;\r\n cout <<\"Value of a is \"<< *ptr<<endl;\r\n ptr ++;\r\n cout <<\"Address of a after incrementation \"<<ptr <<endl;\r\n cout << *ptr<<endl;\r\n ptr2 = & ptr;\r\n cout <<\"Address of ptr2 is \"<<ptr2<<endl;\r\n cout << *ptr2<<endl;\r\n cout <<\"Value of ptr2 is \"<< **ptr2<<endl;\r\n ptr2++;\r\n cout <<\"Address of ptr after incrementation \"<<ptr2 <<endl;\r\n cout << *ptr2 <<endl;\r\n cout << **ptr2 <<endl;\r\n\r\n int *x, y = 35;\r\n x = &y;\r\n cout << x <<endl;\r\n cout << *x/5;\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4542124569416046, "alphanum_fraction": 0.45787546038627625, "avg_line_length": 11.095237731933594, "blob_id": "6f81a3ed3310c2770dba899b998252ba95bb16b6", "content_id": "6f122ac5ed01de91e7d70ec446bfc52ead4e649e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 273, "license_type": "no_license", "max_line_length": 25, "num_lines": 21, "path": "/data_str/class1.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nclass Pet{\r\npublic:\r\n string n;\r\n Pet(string name)\r\n {\r\n n = name;\r\n }\r\n void printname()\r\n {\r\n cout << n;\r\n }\r\n};\r\n\r\nint main(){\r\n Pet p = Pet(\"Doggo\");\r\n p.printname();\r\n return 0;\r\n}" }, { "alpha_fraction": 0.3614457845687866, "alphanum_fraction": 0.3935742974281311, "avg_line_length": 17.230770111083984, "blob_id": "5893fc97fd933ef104f0f6c48e85c45b71f6dfd0", "content_id": "64270f6a63eee22e57396f0929a561ef0f55a627", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 498, "license_type": "no_license", "max_line_length": 42, "num_lines": 26, "path": "/data_str/anagram.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n string s1 = \"string\";\r\n string s2 = \"storm\";\r\n // sort(s1.begin(),s1.end());\r\n // cout << s2.compare(s1);\r\n int cnt = 0;\r\n for (int i = 0; i < s1.size(); i++)\r\n {\r\n if(s1.find(s2[i]) != string::npos)\r\n cnt++;\r\n }\r\n cout << cnt;\r\n // int n = 5;\r\n // int res;\r\n // for(int i = 1; i <= 5; i++)\r\n // {\r\n // res = (res*i) % 2;\r\n // }\r\n // cout << res;\r\n return 0;\r\n}" }, { "alpha_fraction": 0.3813559412956238, "alphanum_fraction": 0.4124293923377991, "avg_line_length": 16.6842098236084, "blob_id": "bed5af239797feab1c149d0f98086ed78d5d04e2", "content_id": "6509fdbea7bb369046f7d1fdfbfbc552e5abfb74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 354, "license_type": "no_license", "max_line_length": 51, "num_lines": 19, "path": "/new.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n#define watch(x) cout << (#x) << \" is \" << x <<endl\r\nint main()\r\n{ \r\n int a[6] = {0};\r\n \r\n// int x = sizeof(a)/a[0];\r\n// cout << \" hello\";\r\n// cout << \"size of a : \" << x;\r\n\r\n for(int i = 0; i < 6; i++)\r\n {\r\n cout << a[i] << \" \" << endl;\r\n }\r\n int x = 43434;\r\n watch(x);\r\n return 0; \r\n} " }, { "alpha_fraction": 0.3390410840511322, "alphanum_fraction": 0.36986300349235535, "avg_line_length": 15.600000381469727, "blob_id": "3231e975f6d5bb001b8062e2d9060bca9c50959e", "content_id": "33aaff2493f126bb7720ddefd99c17371b8a7a49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 292, "license_type": "no_license", "max_line_length": 47, "num_lines": 15, "path": "/subset.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\nint main()\r\n{\r\n map<int,int>m1;\r\n for(int i = 0; i < 5; i++)\r\n {\r\n m1[i] = i+10;\r\n }\r\n for(auto i : m1)\r\n {\r\n cout << i.first<<\" \" << i.second<<endl;\r\n }\r\n cout << m1.at(4);\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.2919354736804962, "alphanum_fraction": 0.31129032373428345, "avg_line_length": 15.222222328186035, "blob_id": "056eaf49ee0f8bf68369501b9fe28722bd695c82", "content_id": "7d19a599b075d3d774f55ec1f34af8e7a2ed9ec6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 620, "license_type": "no_license", "max_line_length": 37, "num_lines": 36, "path": "/inset.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<vector>\r\nusing namespace std;\r\nint main()\r\n{\r\n vector<int>v;\r\n int x;\r\n for(int i = 0; i < 5; i++)\r\n {\r\n cin >> x;\r\n v.push_back(x);\r\n }\r\n for(int i = 0; i < 5; i++)\r\n {\r\n cout << v[i] << \" \";\r\n }\r\n cout << endl;\r\n\r\n\r\n for(int i = 1; i < v.size(); i++)\r\n {\r\n int j = i - 1;\r\n int key = v[i];\r\n while(j >= 0 && v[j] > key)\r\n {\r\n v[j+1] = v[j]; \r\n j--;\r\n }\r\n v[j+1] = key;\r\n }\r\n for(int i = 0; i < 5; i++)\r\n {\r\n cout << v[i] << \" \";\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3086419701576233, "alphanum_fraction": 0.34567901492118835, "avg_line_length": 16.11111068725586, "blob_id": "b810b4626c3d369bd9bcdb757f408e458297120c", "content_id": "76340eb0723d9010d77ca227e94a3279f93e67ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 324, "license_type": "no_license", "max_line_length": 30, "num_lines": 18, "path": "/removedup.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\nusing namespace std;\r\nint main()\r\n{\r\n int arr[] = {1,2,2,3,3,4};\r\n int i = 0;\r\n for(int j = 1; j < 6; j++)\r\n {\r\n if(arr[j] != arr[i]){\r\n arr[++i] = arr[j];\r\n }\r\n }\r\n for(int i = 0; i < 6; i++)\r\n {\r\n cout << arr[i] << \" \";\r\n }\r\n return 0;\r\n}" }, { "alpha_fraction": 0.4627329111099243, "alphanum_fraction": 0.4751552939414978, "avg_line_length": 12.727272987365723, "blob_id": "75cddadbf8b1655a66812bbf0cc9845cc15d06aa", "content_id": "cd1949f8995b0f9e2c745fbd211672cf8cf00915", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 322, "license_type": "no_license", "max_line_length": 32, "num_lines": 22, "path": "/funpointers.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstring>\r\nusing namespace std;\r\n\r\ntypedef void (*funptr)(int,int);\r\nvoid add(int a,int b)\r\n{\r\n cout <<\"a + b = \" << a + b;\r\n}\r\nvoid sub(int a,int b)\r\n{\r\n cout <<\" a - b = \" << a - b;\r\n}\r\n\r\nint main()\r\n{\r\n funptr ptr;\r\n ptr = &add;\r\n ptr(1,5);\r\n ptr = &sub;\r\n ptr (5,2);\r\n}" }, { "alpha_fraction": 0.40430623292922974, "alphanum_fraction": 0.40909090638160706, "avg_line_length": 12.482758522033691, "blob_id": "db34fe013bbe8da3b9a408926ed4a9936984b1ba", "content_id": "3b9fea0f0df7bb841d0f4bca7fc887aacb146a47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 418, "license_type": "no_license", "max_line_length": 42, "num_lines": 29, "path": "/exp.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\n#define fr(i,n) for(int i = 0; i < n; i++)\r\n#define l long \r\n#define pb push_back\r\n// typedef vector<int> v;\r\n\r\nint main()\r\n{\r\n l n;\r\n vector<int> v;\r\n cin >> n;\r\n fr(i,n)\r\n {\r\n int x;\r\n cin >> x;\r\n v.pb(x);\r\n }\r\n \r\n reverse(v.begin(),v.end());\r\n\r\n fr(i,n)\r\n {\r\n cout << v[i] << \" \";\r\n }\r\n return 0;\r\n}" }, { "alpha_fraction": 0.30733945965766907, "alphanum_fraction": 0.3302752375602722, "avg_line_length": 17.04347801208496, "blob_id": "7dd6eecf4706cdc1ae658e7a6fa8b2cda81139e0", "content_id": "2196c32fc800cf7c38665c50bcc0c2dea5e7890d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 436, "license_type": "no_license", "max_line_length": 43, "num_lines": 23, "path": "/selct.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n vector<int>v{4,1,3,8,7,2};\r\n\r\n for(int i = 0; i < v.size(); i++)\r\n {\r\n int min = i;\r\n for(int j = i+1; j < v.size(); j++)\r\n {\r\n if(v[min] > v[j])\r\n {\r\n min = j;\r\n }\r\n }\r\n swap(v[min],v[i]);\r\n }\r\n for(int i = 0; i < v.size(); i++)\r\n cout << v[i] << \" \";\r\n return 0;\r\n}" }, { "alpha_fraction": 0.3322475552558899, "alphanum_fraction": 0.35179153084754944, "avg_line_length": 12.714285850524902, "blob_id": "2731101637e60f9fe229d7144f8aa62337a52454", "content_id": "b4fb9d0ddd1d55d43f88519bbd484bf668dfa5da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 307, "license_type": "no_license", "max_line_length": 39, "num_lines": 21, "path": "/data_str/pairing.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\nvoid pairing(int n)\r\n{\r\n int i = 0;\r\n while(i < n)\r\n {\r\n int j = 0;\r\n while(j < n)\r\n {\r\n cout << i <<\" \"<< j <<endl;\r\n j = j+1;\r\n }\r\n i++;\r\n }\r\n}\r\nint main()\r\n{\r\n pairing(10);\r\n return 0;\r\n}" }, { "alpha_fraction": 0.451200008392334, "alphanum_fraction": 0.46133333444595337, "avg_line_length": 15.857142448425293, "blob_id": "632873ceeb53dd0e34c0a06f1d79a7f23fb1d67a", "content_id": "691d46758e393139d73545c405548f0b8844c48d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1875, "license_type": "no_license", "max_line_length": 38, "num_lines": 105, "path": "/dblylnk.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\nusing namespace std;\r\nclass node{\r\n public:\r\n int data;\r\n node *next;\r\n node *prev;\r\n};\r\nvoid inst(node **head,int data)\r\n{\r\n node *temp = new node();\r\n temp -> data = data;\r\n temp -> next = *head;\r\n temp -> prev = NULL;\r\n *head -> prev = temp;\r\n *head = temp;\r\n}\r\n\r\n// void mid(node **head,int data)\r\n// {\r\n// node *temp = new node();\r\n// node *tr = *head;\r\n// while(tr -> data != 14)\r\n// {\r\n// tr = tr -> next;\r\n// }\r\n// temp ->data = data;\r\n// temp -> next = tr -> next;\r\n// tr -> next = temp;\r\n// }\r\n// void last(node **head,int data)\r\n// {\r\n// node *temp = new node();\r\n// node *tr = *head;\r\n// while(tr -> next != NULL)\r\n// {\r\n// tr = tr -> next;\r\n// }\r\n// temp -> data = data;\r\n// temp -> next = NULL;\r\n// tr -> next = temp;\r\n// }\r\n// void del(node **head,int x)\r\n// {\r\n// node *temp = *head;\r\n// node *prev;\r\n// while(temp -> data != x)\r\n// {\r\n// prev = temp;\r\n// temp = temp -> next;\r\n// }\r\n// prev -> next = temp -> next;\r\n// free(temp);\r\n// }\r\n\r\nvoid print(node *ptr)\r\n{ \r\n node *last;\r\n cout <<\" In Forward direction: \";\r\n while(ptr != NULL)\r\n {\r\n cout << ptr -> data <<\" \";\r\n last = ptr;\r\n ptr = ptr -> next;\r\n }\r\n cout << \"\\nIn backward direction: \";\r\n while(last != NULL)\r\n {\r\n cout << last -> data << \" \";\r\n last = last -> prev;\r\n }\r\n}\r\nint main()\r\n{\r\n node *head = NULL;\r\n node *sec = NULL;\r\n node *third = NULL;\r\n\r\nhead = new node();\r\nsec = new node();\r\nthird = new node();\r\n\r\nhead -> data = 12;\r\nhead -> next = sec;\r\nhead -> prev = NULL;\r\n\r\nsec -> data = 14;\r\nsec -> next = third;\r\nsec -> prev = head;\r\n\r\nthird -> data = 19;\r\nthird -> next = NULL;\r\nthird -> prev = sec;\r\n\r\ninst(&head,8);\r\n// mid(&head,15);\r\n// last(&head,20);\r\n// del(&head,15);\r\n// del(&head,8);\r\n// del(&head,20);\r\n\r\nprint(head);\r\n\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.5072711706161499, "alphanum_fraction": 0.5183917880058289, "avg_line_length": 17.847457885742188, "blob_id": "71903aad00cd8132d4b8f651255fbde5d7198b03", "content_id": "bfcdd3fbcc9499745f84cfe6e824ab41765b25ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1169, "license_type": "no_license", "max_line_length": 75, "num_lines": 59, "path": "/game.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <iomanip>\r\n#include <cassert>\r\n#include <cmath>\r\n#include <cstdio>\r\n#include <cstring>\r\n#include <cstdlib>\r\n#include <map>\r\n#include <set>\r\n#include <queue>\r\n#include <stack>\r\n#include <vector>\r\n#include <chrono>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\n#define int long long\r\n#define pb push_back\r\n\r\n#define all(con) con.begin(), con.end()\r\n#define fi first\r\n#define se second\r\n#define sz(x) (int)x.size()\r\ntypedef long double ld;\r\ntypedef long long ll;\r\ntypedef pair<int, int> pii;\r\ntypedef vector<int> vi;\r\n#define rp(i, n) for (int i = 0; i < n; i++)\r\n#define fr(i, n) for (int i = 1; i <= n; i++)\r\n#define ff(i, a, b) for (int i = a; i <= b; i++)\r\n\r\n\r\n// int rev(int num)\r\n// {\r\n// int revnum = 0;\r\n// while(num > 0)\r\n// {\r\n// revnum = revnum*10 + num % 10;\r\n// num /= 10;\r\n// }\r\n// return revnum;\r\n// }\r\nsigned main()\r\n{\r\n int x,indx = 1;\r\n map<int,int>m;\r\n rp(i,5)\r\n {\r\n cin >> x;\r\n m[x] = indx++;\r\n\r\n }\r\n for(auto i = m.begin(); i != m.end();i++)\r\n {\r\n cout <<\"Key : \"<< i -> first << \" Value : \" << i -> second <<endl; \r\n }\r\n return 0;\r\n}" }, { "alpha_fraction": 0.35686275362968445, "alphanum_fraction": 0.4117647111415863, "avg_line_length": 14.0625, "blob_id": "f3b32e619ea983451f41159b2281a766d754079d", "content_id": "138b9c793cf7e9e3b22fc01dfe62f09376f73c3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 255, "license_type": "no_license", "max_line_length": 25, "num_lines": 16, "path": "/cntnum.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\nusing namespace std;\r\nint main()\r\n{\r\n int n = 124212;\r\n int cnt = 0;\r\n int c = log10(n) + 1;\r\n cout << c << endl;\r\n while(n > 0)\r\n {\r\n n = n / 10;\r\n cnt++;\r\n }\r\n cout << cnt;\r\n return 0;\r\n}" }, { "alpha_fraction": 0.38297873735427856, "alphanum_fraction": 0.4000000059604645, "avg_line_length": 12.8125, "blob_id": "e97207866a244a6ae3953001b9069594d20a236a", "content_id": "bd8be7c021df4d16488c673fe641c103df242f08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 235, "license_type": "no_license", "max_line_length": 31, "num_lines": 16, "path": "/data_str/deque.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\nusing namespace std;\r\nint main()\r\n{\r\n deque<int>dq;\r\n for(int i = 0; i < 10; i++)\r\n {\r\n dq.push_back(i);\r\n }\r\n for(int i:dq)\r\n {\r\n cout << i <<\" \";\r\n }\r\n \r\n return 0;\r\n}" }, { "alpha_fraction": 0.4755120277404785, "alphanum_fraction": 0.5022261738777161, "avg_line_length": 14.969696998596191, "blob_id": "7bb39ee6f94f10891e12f5a42e0752886f847c6f", "content_id": "a47cf754b95ef9ba6c3863f307dea3c6b0ccc0ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1123, "license_type": "no_license", "max_line_length": 83, "num_lines": 66, "path": "/testclass.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\n\r\nclass testclass1;\r\nclass testclass\r\n{\r\nprivate:\r\n int hrs;\r\n int mins;\r\npublic:\r\n void fun(int x,int y);\r\n void print()\r\n {\r\n cout << \"value of hrs is :\" << hrs <<\" value of min is : \" << mins << endl;\r\n }\r\n void sum(testclass,testclass);\r\n friend void swap(testclass&,testclass1&);\r\n};\r\nvoid testclass::fun(int x,int y)\r\n{\r\n hrs = x;\r\n mins = y;\r\n}\r\nvoid testclass::sum(testclass t1,testclass t2)\r\n{\r\n mins = t1.mins + t2.mins;\r\n hrs = mins / 60;\r\n mins = mins % 60;\r\n hrs = hrs + t1.hrs + t2.hrs; \r\n\r\n}\r\nclass testclass1{\r\n int x;\r\n int y;\r\n public:\r\n void setvalue()\r\n {\r\n x = 24;\r\n }\r\n void shw()\r\n {\r\n cout << \"value of x is :\" <<x<<endl;\r\n }\r\n friend void swap(testclass&,testclass1&);\r\n};\r\nvoid swap(testclass& a,testclass1& b)\r\n{\r\n int temp = a.hrs;\r\n a.hrs = b.x;\r\n b.x = temp;\r\n\r\n}\r\nint main()\r\n{\r\n testclass t1;\r\n testclass1 t2;\r\n t1.fun(1,2);\r\n t2.setvalue();\r\n t1.print();\r\n t2.shw();\r\n swap(t1,t2);\r\n t1.print();\r\n t2.shw();\r\n\r\n}\r\n " }, { "alpha_fraction": 0.3013100326061249, "alphanum_fraction": 0.31703057885169983, "avg_line_length": 13.712328910827637, "blob_id": "e3a7b147d1d34d81ce240759b8d5018debef6867", "content_id": "cb1899cd4431d709b9098c9e6f9a801636833815", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1145, "license_type": "no_license", "max_line_length": 74, "num_lines": 73, "path": "/stringfu.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstring>\r\n#include<cmath>\r\n\r\n#define fr(i,n) for(int i = 0; i < n; i++)\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n\r\n char arr[85];\r\n cin >> arr;\r\n \r\n cout <<arr<<endl;\r\n\r\n char *str = arr;\r\n \r\n int cnt = 0;\r\n\r\n while(*str != '\\0')\r\n {\r\n cnt++;\r\n str++;\r\n }\r\n\r\n cout << cnt<<endl;\r\n\r\n float sq = sqrt(cnt);\r\n cout << sq<<endl;\r\n int r = floor(sq);\r\n int c = ceil(sq);\r\n cout << r << \" \" << c << endl;\r\n \r\n while(r*c < cnt)\r\n {\r\n if(r < c) {r++;}\r\n else {c++;}\r\n }\r\n cout << r << \" \" << c << endl;\r\n char enc[r][c];\r\n\r\n int k = 0;\r\n\r\n fr(i,r)\r\n {\r\n fr(j,c)\r\n {\r\n enc[i][j] = arr[k++];\r\n }\r\n\r\n }\r\nfr(i,r)\r\n {\r\n fr(j,c)\r\n {\r\n if(enc[i][j] != '\\0' && (enc[i][j] >= 97 && enc[i][j] <= 122))\r\n cout << enc[i][j];\r\n }\r\n cout <<endl;\r\n }\r\n\r\n fr(i,c)\r\n {\r\n fr(j,r)\r\n {\r\n if(enc[i][j] != '\\0' && (enc[i][j] >= 97 && enc[i][j] <= 122))\r\n cout << enc[j][i];\r\n }\r\n cout <<' ';\r\n }\r\n\r\n}" }, { "alpha_fraction": 0.32263514399528503, "alphanum_fraction": 0.3429054021835327, "avg_line_length": 14.971428871154785, "blob_id": "6ef980132d7ae50c847c0eadf9e9959034bd77b1", "content_id": "fd1fab497bc8093ae6e9fde3c20afb3bfde8e108", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 592, "license_type": "no_license", "max_line_length": 56, "num_lines": 35, "path": "/data_str/num.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n vector<int> v;\r\n for (int i = 0; i < 5; i++)\r\n {\r\n v.push_back(i + 1);\r\n }\r\n\r\n for (auto x : v)\r\n {\r\n cout << x << \" \";\r\n }\r\n cout << \"\\n\";\r\n\r\n int last = v[4];\r\n int n = 4;\r\n for (int i = 0; i < 5; i++)\r\n {\r\n v[n - i] = v[n - 1 - i ];\r\n }\r\n v[0] = last;\r\n\r\n // unique(v.begin(),v.end());\r\n // // v.erase(unique(v.begin(),v.end()),v.end());\r\n // cout<<endl;\r\n for(int i = 0; i < 5; i++)\r\n {\r\n cout << v[i] <<\" \";\r\n }\r\n return 0;\r\n}" }, { "alpha_fraction": 0.4117647111415863, "alphanum_fraction": 0.4271099865436554, "avg_line_length": 13.720000267028809, "blob_id": "96ae441f971ffa90195339f53d6c0021c5c07a66", "content_id": "a88f6aeaf375882831afcc4bfbfbea72134ed03e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 391, "license_type": "no_license", "max_line_length": 44, "num_lines": 25, "path": "/dynarr.c", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid fun(int **arr)\r\n{\r\n int *xyz = (int*)malloc(sizeof(int)*3);\r\n \r\n printf(\"Enter the elements of array: \");\r\n for(int i = 0; i < 3; i++)\r\n {\r\n scanf(\"%d\",&arr[i]);\r\n }\r\n\r\n}\r\nint main()\r\n{\r\n int *arr = NULL;\r\n fun(&arr);\r\n\r\n for(int i = 0; i < 3; i++)\r\n {\r\n printf(\"%d \",arr[i]);\r\n }\r\n return 0;\r\n}" }, { "alpha_fraction": 0.42401501536369324, "alphanum_fraction": 0.4399624764919281, "avg_line_length": 13.940298080444336, "blob_id": "34c7a60e70d3bb2ce9465406fef0ac0acb5b9311", "content_id": "702222277d22208bceefd7b4981d83915fa43a5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1066, "license_type": "no_license", "max_line_length": 40, "num_lines": 67, "path": "/stringfun.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstring>\r\nusing namespace std;\r\n\r\nstruct student\r\n{\r\n char name[20];\r\n int roll;\r\n float marks;\r\n void hello()\r\n {\r\n cout << \" hello function\";\r\n }\r\n};\r\n\r\nclass Node\r\n{\r\n public:\r\n int data;\r\n Node *next;\r\n};\r\n\r\nvoid push(Node **head_ref, int data)\r\n{\r\n Node *ptr1 = new Node();\r\n Node *temp = *head_ref;\r\n ptr1 ->data = data;\r\n ptr1 ->next = *head_ref;\r\n\r\n if(*head_ref != NULL)\r\n {\r\n while(temp -> next != *head_ref)\r\n {\r\n temp = temp -> next;\r\n temp -> next = ptr1;\r\n }\r\n }\r\n else \r\n {\r\n ptr1 ->next = ptr1;\r\n *head_ref = ptr1;\r\n }\r\n}\r\n\r\nvoid printlist(Node *head)\r\n{\r\n Node *temp = head;\r\n if(head != NULL)\r\n {\r\n do{\r\n cout << temp->data<<\" \";\r\n temp = temp -> next;\r\n }while(temp != head);\r\n }\r\n}\r\n\r\nint main()\r\n{\r\n Node *head = NULL;\r\n push(&head,12);\r\n push(&head,34);\r\n push(&head,3);\r\n push(&head,31);\r\n printlist(head);\r\n\r\n return 0; \r\n}" }, { "alpha_fraction": 0.4898388087749481, "alphanum_fraction": 0.5031534433364868, "avg_line_length": 14.788235664367676, "blob_id": "ed5bdb0ad54d7b8f5ded36d0244936e0376fc00c", "content_id": "fe745e42bd26de4c49ac082c055c09e170630dd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1427, "license_type": "no_license", "max_line_length": 31, "num_lines": 85, "path": "/pintr.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\nusing namespace std;\r\nclass node{\r\n public:\r\n int data;\r\n node *next;\r\n};\r\nvoid inst(node **head,int data)\r\n{\r\n node *temp;\r\n temp = new node();\r\n temp -> data = data;\r\n temp -> next = *head;\r\n *head = temp;\r\n\r\n}\r\n\r\nvoid mid(node **head,int data)\r\n{\r\n node *temp = new node();\r\n node *tr = *head;\r\n while(tr -> data != 14)\r\n {\r\n tr = tr -> next;\r\n }\r\n temp ->data = data;\r\n temp -> next = tr -> next;\r\n tr -> next = temp;\r\n}\r\nvoid last(node **head,int data)\r\n{\r\n node *temp = new node();\r\n node *tr = *head;\r\n while(tr -> next != NULL)\r\n {\r\n tr = tr -> next;\r\n }\r\n temp -> data = data;\r\n temp -> next = NULL;\r\n tr -> next = temp;\r\n}\r\nvoid del(node **head,int x)\r\n{\r\n node *temp = *head;\r\n node *prev;\r\n while(temp -> data != x)\r\n {\r\n prev = temp;\r\n temp = temp -> next;\r\n }\r\n prev -> next = temp -> next;\r\n free(temp);\r\n}\r\nvoid print(node *ptr)\r\n{\r\n while(ptr -> data != NULL)\r\n {\r\n cout << ptr -> data <<\" \";\r\n ptr = ptr -> next;\r\n }\r\n}\r\nint main()\r\n{\r\n node *head = NULL;\r\n node *first = NULL;\r\n node *third = NULL;\r\nhead = new node();\r\nfirst = new node();\r\nthird = new node();\r\nhead -> data = 12;\r\nhead -> next = first;\r\nfirst -> data = 14;\r\nfirst -> next = third;\r\nthird -> data = 19;\r\nthird -> next = NULL;\r\ninst(&head,8);\r\nmid(&head,15);\r\nlast(&head,20);\r\ndel(&head,15);\r\ndel(&head,8);\r\ndel(&head,20);\r\nprint(head);\r\n\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.48172757029533386, "alphanum_fraction": 0.485049843788147, "avg_line_length": 16.9375, "blob_id": "ea25113f64bcce0652d7764153d12fd912ec263e", "content_id": "95650c3a93e22add6646396ae6cea12fdb60bfaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 301, "license_type": "no_license", "max_line_length": 63, "num_lines": 16, "path": "/data_str/arrptr.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n string s = \"ankush choudhary\";\r\n unordered_map<char,int>u;\r\n map<char,int>m;\r\n\r\n for(auto i : s)u[i]++;\r\n for(auto i : s)m[i]++;\r\n\r\n for(auto i : u) cout << i.first << \" \" << i.second << \"\\n\";\r\n cout << NULL\r\n return 0;\r\n}" }, { "alpha_fraction": 0.40258920192718506, "alphanum_fraction": 0.42942848801612854, "avg_line_length": 18.577922821044922, "blob_id": "a1aeda93909f16070219586bafe1b4245f29d643", "content_id": "78534f4927e1eeefe845b8d2db48d947b1c955e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3167, "license_type": "no_license", "max_line_length": 64, "num_lines": 154, "path": "/mytemplates.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\nusing namespace std;\r\n#define f(i, n) for (int i = 0; i < (int)(n); ++i)\r\n#define for1(i, n) for (int i = 1; i <= (int)(n); ++i) \r\n#define forc(i, l, r) for (int i = (int)(l); i <= (int)(r); ++i)\r\n#define forr0(i, n) for (int i = (int)(n) - 1; i >= 0; --i) \r\n#define forr1(i, n) for (int i = (int)(n); i >= 1; --i)\r\n#define pb push_back\r\n#define fi first\r\n#define se second\r\n#define all(x) (x).begin(), (x).end() Eg: find(all(c),42)\r\n#define rall(x) (x).rbegin, (x).rend()\r\n#define present(c,x) ((c).find(x) != (c).end()) //O(N)\r\n#define cpresent(c,x) (find(all(c),x) != (c).end()) // O(logn)\r\n#define sz(a) int((a).size())\r\n#define all(v) v.B, v.E\r\n#define S size()\r\n#define E end()\r\n#define B begin()\r\n#define L length()\r\n#define endl \"\\n\"\r\n#define gcd __gcd\r\n#define search binary_search //bool\r\n#define mod1 1000000007\r\n#define mod2 998244353\r\n#define INF LLONG_MAX\r\n#define PI 3.1415926535897932384\r\n#define deci(n) fixed << setprecision(n)\r\n\r\ntypedef vector<int> vi;\r\ntypedef vector<vi> vvi;\r\ntypedef pair<int, int> ii;\r\ntypedef vector<ii> vii;\r\ntypedef long long ll;\r\ntypedef vector<ll> vll;\r\ntypedef vector<vll> vvll;\r\ntypedef double ld;\r\ntypedef unsigned long long int ull;\r\ntypedef long double ldb;\r\ntypedef pair<ll, ll> pll;\r\ntypedef pair<int, int> pii;\r\n\r\n\r\nll arraySum(ll a[], ll n)\r\n{\r\n int initial_sum = 0;\r\n return accumulate(a, a + n, initial_sum);\r\n}\r\n/////////////////////////////////\r\nbool isprime(ll n)\r\n{\r\n ll flagi = 1;\r\n for (ll i = 2; i <= sqrt(n); i++)\r\n {\r\n if (n % i == 0)\r\n {\r\n flagi = 0;\r\n break;\r\n }\r\n }\r\n if (n <= 1)\r\n {\r\n flagi = 0;\r\n }\r\n else if (n == 2)\r\n {\r\n flagi = 1;\r\n }\r\n \r\n if (flagi == 1)\r\n {\r\n return true;\r\n }\r\n else\r\n {\r\n return false;\r\n }\r\n}\r\n/////////////////////////////////\r\nstring decimaltobinary(ll A)\r\n{\r\n string ans;\r\n ll i, rem;\r\n if (A == 0)\r\n {\r\n return \"0\";\r\n }\r\n \r\n while (A > 0)\r\n {\r\n rem = A % 2;\r\n \r\n ans.push_back(char('0' + rem));\r\n \r\n A = A / 2;\r\n }\r\n \r\n reverse(ans.begin(), ans.end());\r\n return ans;\r\n}\r\nbool sortbysec(const pair<ll, ll> &a,\r\n const pair<ll, ll> &b)\r\n{\r\n return (a.second > b.second);\r\n}\r\n///////////////////////////////////////////\r\nvector<ll> res;\r\nvoid factorize(ll n)\r\n{\r\n for (ll i = 2; i * i <= n; ++i)\r\n {\r\n while (n % i == 0)\r\n {\r\n res.push_back(i);\r\n n /= i;\r\n }\r\n }\r\n if (n != 1)\r\n {\r\n res.push_back(n);\r\n }\r\n}\r\n/////////////////////////////////\r\nvector<ll> divs;\r\nvoid divisor(ll n)\r\n{\r\n for (ll i = 2; i <= sqrt(n); i++)\r\n {\r\n if (n % i == 0)\r\n {\r\n divs.pb(i);\r\n if (n / i != i)\r\n {\r\n divs.pb(n / i);\r\n }\r\n }\r\n }\r\n divs.pb(1);\r\n if (n != 1)\r\n {\r\n divs.pb(n);\r\n }\r\n}\r\n/////////////////////////////\r\n\r\nint main()\r\n{\r\n // vi a = {1,2,3,4,5,5,6,7}; \r\n // int s = arraySum(a, 8);\r\n // cout << s;\r\n int a = 5;\r\n printf(\"%d, %d, %d\",++a,a++,a);\r\n return 0;\r\n}" }, { "alpha_fraction": 0.43538767099380493, "alphanum_fraction": 0.4592445194721222, "avg_line_length": 19.04166603088379, "blob_id": "86ae8bb58fe6bbb48be764a28aa4d0e69e561a9f", "content_id": "6269b992e78b9163c760d3d53aac64b2fc8d3d3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 503, "license_type": "no_license", "max_line_length": 41, "num_lines": 24, "path": "/data_str/vect.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\nusing namespace std;\r\nint main()\r\n{\r\n vector<int>v{1,2,3,4,5};\r\n cout<<v.at(0)<<endl;\r\n v.push_back(3);\r\n cout << v.at(v.size()-1)<<endl;\r\n auto itr = v.begin();\r\n v.insert(itr,0);\r\n cout << v.at(0)<<endl;\r\n for(auto i:v)\r\n {\r\n cout << v[i]<<\" \";\r\n }\r\n cout <<endl;\r\n itr = find(v.begin(),v.end(),4);\r\n if(itr != v.end())\r\n {\r\n cout << \"Element present\";\r\n }\r\n else{cout << \"Elemennt not present\";}\r\n return 0;\r\n}" }, { "alpha_fraction": 0.323369562625885, "alphanum_fraction": 0.36141303181648254, "avg_line_length": 16.5, "blob_id": "e83b4c76268923685a0b86c5eebddae7f6295934", "content_id": "b0647ab52002271a574cf6df217578b57d2cf871", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 368, "license_type": "no_license", "max_line_length": 43, "num_lines": 20, "path": "/bubb.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\nusing namespace std;\r\nint main()\r\n{\r\n vector<int>v{4,3,1,4,6,2,8,6,4};\r\n for(int i = 0; i < v.size()-1; i++)\r\n {\r\n for(int j = i+1; j < v.size(); j++)\r\n {\r\n if(v[i] > v[j])\r\n swap(v[i],v[j]);\r\n }\r\n }\r\n for(int i = 0; i < v.size(); i++)\r\n cout << v[i] << \" \";\r\n\r\n return 0;\r\n\r\n\r\n}" }, { "alpha_fraction": 0.4747292399406433, "alphanum_fraction": 0.505415141582489, "avg_line_length": 21.16666603088379, "blob_id": "3672a9863b68fe7138e9eb83b3d1e7ef1538b218", "content_id": "9fdb8158ce1a7d59b729db223fb12ca66b629ef0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 554, "license_type": "no_license", "max_line_length": 68, "num_lines": 24, "path": "/dic.py", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "# x = \"1\"\r\n# s = \"\"\r\n# while(x):\r\n# x = input()\r\n# s+=x\r\n# print(s)\r\n# s = \"loda singh\"\r\n# n = \"\".join(sorted(s,reverse=True))\r\n# # x = lambda a: n = \"\".join(sorted(a,reverse=True)) \r\n# print(n)\r\n# se = set([1,11,1,1,1,1,1,1])\r\n# print(se)\r\nl = [\"ank\",\"bbush\",\"cchou\"]\r\nl1 = [\"ush\",\"dhary\",\"select\"]\r\n# print(list(map(lambda x: x[-3:-1],l)))\r\n# print(\", \".join(l))\r\n# print(list(filter(lambda x: True if x[:2] == \"an\" else False, l)))\r\n\r\n# print(list(zip(l,l1)))\r\n# print(list(zip(*(l,l1))))\r\n# print(list(enumerate(l1)))\r\n\r\nx = l.pop()\r\nprint(x)" }, { "alpha_fraction": 0.4529411792755127, "alphanum_fraction": 0.45588234066963196, "avg_line_length": 14.285714149475098, "blob_id": "5810ac758f46f35dae9983e4b4a79e4b4609c988", "content_id": "f1c273832283754a7e255d5ca135f8528bb32f26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 340, "license_type": "no_license", "max_line_length": 41, "num_lines": 21, "path": "/data_str/enun.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\nint main()\r\n{\r\n enum gen{\r\n male,female\r\n };\r\n gen g = male;\r\n switch (g)\r\n {\r\n case male:\r\n cout<< \"Male\";\r\n break;\r\n case female:\r\n cout << \"Female\";\r\n break;\r\n default:\r\n cout<<\"Should be male or female\";\r\n }\r\n return 0;\r\n}" }, { "alpha_fraction": 0.4581005573272705, "alphanum_fraction": 0.46927374601364136, "avg_line_length": 14.454545021057129, "blob_id": "0038d72e86f356a3a6123bc41e0bd9ed654eaedd", "content_id": "ba978086ce71f4a12cfac1cd73b68c197e35848a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 179, "license_type": "no_license", "max_line_length": 32, "num_lines": 11, "path": "/mapc.cpp", "repo_name": "AnkushCh/Hackerrank_Codes", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\r\nusing namespace std;\r\nint main()\r\n{\r\n map<string,int>str;\r\n int x;\r\n for(int i = 0; i < 5; i++){\r\n cin >> x;\r\n str.insert(x);\r\n }\r\n}" } ]
51
unyosFact/RasPi_DigitalCamera
https://github.com/unyosFact/RasPi_DigitalCamera
4408ac7abe2577bd2cc7c73f59aecbb0d8e4f0f2
3c61428aa2b58e726aa2748973a01a1d01aac89f
154defc3e96cb8d6faeb0ebd567196218244ae26
refs/heads/master
2021-01-20T00:51:01.834443
2017-04-24T06:05:14
2017-04-24T06:05:14
89,197,708
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5002816915512085, "alphanum_fraction": 0.5138028264045715, "avg_line_length": 31.870370864868164, "blob_id": "9d69e1ca25e33d090d0886b3c870711b09367503", "content_id": "a422d7e925c24806bb2de4f6258c53ef89d30ac6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1775, "license_type": "no_license", "max_line_length": 100, "num_lines": 54, "path": "/work/camera_1/ts_setup1.sh", "repo_name": "unyosFact/RasPi_DigitalCamera", "src_encoding": "UTF-8", "text": "#----------------------------------------------------------------\n# /etc/udev/rules.d/95-ft6236.rules Wrote\n#\tSUBSYSTEM==\"input\", KERNEL==\"event[0-9]*\", ATTRS{name}==\"ft6236*\", SYMLINK+=\"input/touchscreen\"\n#\n# /etc/udev/rules.d/95-stmpe.rules Wrote\n#\tSUBSYSTEM==\"input\", ATTRS{name}==\"stmpe-ts\", ENV{DEVNAME}==\"*event*\", SYMLINK+=\"input/touchscreen\"\n#----------------------------------------------------------------\n\n#----------------------------------------------------------------\n# install tslib\n#----------------------------------------------------------------\n\nsudo sudo apt-get install -y tslib libts-bin\n# sudo wget -O /usr/bin/ts_test http://tronnes.org/downloads/ts_test\n# sudo chmod +x /usr/bin/ts_test\n\n\n#----------------------------------------------------------------\n# Set environment variables\n#----------------------------------------------------------------\n# tslib environment variables\n\ncat <<EOF | sudo tee /etc/profile.d/tslib.sh\nexport TSLIB_TSDEVICE=/dev/input/touchscreen\nexport TSLIB_FBDEVICE=/dev/fb1\nEOF\n\ncat <<EOF | sudo tee /etc/sudoers.d/tslib\nDefaults env_keep += \"TSLIB_TSDEVICE TSLIB_FBDEVICE\"\nEOF\n\nsudo chmod 0440 /etc/sudoers.d/tslib\n\n# SDL environment variables\n\ncat <<EOF | sudo tee /etc/profile.d/sdl.sh\nexport SDL_VIDEODRIVER=fbcon\nexport SDL_FBDEV=/dev/fb1\nif [[ -e /dev/input/touchscreen ]]; then\n export SDL_MOUSEDRV=TSLIB\n export SDL_MOUSEDEV=/dev/input/touchscreen\nfi\nEOF\n\ncat <<EOF | sudo tee /etc/sudoers.d/sdl\nDefaults env_keep += \"SDL_VIDEODRIVER SDL_FBDEV SDL_MOUSEDRV SDL_MOUSEDEV\"\nEOF\n\nsudo chmod 0440 /etc/sudoers.d/tslib\n\n#----------------------------------------------------------------\n# copy TouchPanel Calibration Data \nsudo cp pointercal /etc/\n#----------------------------------------------------------------\n" }, { "alpha_fraction": 0.5932203531265259, "alphanum_fraction": 0.6779661178588867, "avg_line_length": 13.5, "blob_id": "a72b6bb533090c3d71f5e5873434dd0eb8026b1b", "content_id": "838521b3b7522d245860589785bad53d0849e2c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 59, "license_type": "no_license", "max_line_length": 21, "num_lines": 4, "path": "/digicame.sh", "repo_name": "unyosFact/RasPi_DigitalCamera", "src_encoding": "UTF-8", "text": "#!/bin/bash\ncd ~/work/camera_1\npython3 camera_093.py\ncd ~\n\n" }, { "alpha_fraction": 0.39449542760849, "alphanum_fraction": 0.44342508912086487, "avg_line_length": 24.153846740722656, "blob_id": "2820e2e29786c91bfc631341d00e377d2ebc272f", "content_id": "fe97258944fcd60c692716c04cd5261f301b0b07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 355, "license_type": "no_license", "max_line_length": 57, "num_lines": 13, "path": "/README.md", "repo_name": "unyosFact/RasPi_DigitalCamera", "src_encoding": "UTF-8", "text": "# RasPi_DigitalCamera\nデジタルカメラ を作成: Raspberry Pi 向け\n\n---------------------------------------------------------\n\tRaspberry Pi3 ( or Zero ) \n\t\t+ Official Camera ( V2 )\n\t\t+ LCD ( 320x240, in Touch Panel ) \n\t\t+ KSY Power Control Board\n\n 2017/04/18\n---------------------------------------------------------\n\nRead setup_digicame.txt\n" }, { "alpha_fraction": 0.5050686001777649, "alphanum_fraction": 0.5489382147789001, "avg_line_length": 26.875761032104492, "blob_id": "6825bddab1bd47bcb311e6cbcf2eed24aae7790e", "content_id": "e3477d2ac0ea550bc68d33164db8df80fb337a60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22886, "license_type": "no_license", "max_line_length": 97, "num_lines": 821, "path": "/work/camera_1/camera_093.py", "repo_name": "unyosFact/RasPi_DigitalCamera", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# coding: utf-8\n#----------------------------------------------------------------\n#\n#\tDital Camera for RaspberryPi Zero + PiCamera(V2) + LCD\n#\t\t\t\t\t\t\t\t\t\t\t\t + Power Board\n#\ttest App Ver 0.93:\t\t2017/04/12\n#\n#----------------------------------------------------------------\n\nimport atexit\nimport errno\nimport time\nimport picamera\nimport fnmatch\nimport io\nimport os\nimport os.path\nimport pygame\nimport stat\nimport threading\nfrom pygame.locals import *\n\n# for Power Board\nimport RPi.GPIO as GPIO\n\n\n#----------------------------------------------------------\n\nprint(\" \")\nprint(\"Pi Camera-Test Ver0.93\")\nprint(\" \")\nprint(\" \")\n\n\n#----------------------------------------------------------\n# const Data 1\n\n_PAGE_TOP\t\t= 3\t\t# Start Page Top\n\n\t\t\t\t\t\t# View Resolution\n_NORMAL_RESO\t= ( 320, 240 )\n\niconPath\t\t= 'iconsX'\n\t\t\t\t\t\t# PNG directory\n\n# GPIO Number\nO_PULSE_NUM\t\t= 27\t# Out - Check Run Pulse\nI_REQ_POFF \t= 22\t# In - Low BATT & OFF Request\n\n\n\n#=========================================================#\n# Class Define\nclass Icon:\n\n\tdef __init__( self, name ):\n\t self.name\t\t= name\n\t try:\n\t self.bmp\t= pygame.image.load( iconPath + '/' + name + '.png')\n\t except:\n\t \tself.bmp\t= None\n\n#----------------------------------------------------------\ndef\tIsRectArea( rect, pos ):\n\tx1 = rect[0]\n\ty1 = rect[1]\n\tx2 = x1 + rect[2] - 1\n\ty2 = y1 + rect[3] - 1\n\n\tif(( pos[0] >= x1 ) and ( pos[0] <= x2 ) and\n\t ( pos[1] >= y1 ) and ( pos[1] <= y2 )\t):\n\t return True\n\treturn\tFalse\n\nclass Button:\n\n\tdef __init__( self, rect, **args ):\n\t self.rect = rect # Rect Area\n\t self.iconBk = None # Back Icon\n\t self.iconFr = None # Fore Icon\n\t self.bkName = None # Back Icon name\n\t self.frName = None # Fore Icon name\n\t self.callback = None # Callback function\n\t self.value = None # Callback args\n\n#\t Python2.7\n#\t for key, value in args.iteritems():\n\n#\t Python3 \n\t for key, value in args.items():\n\t if key == 'bkName'\t: self.bkName\t= value\n\t elif key == 'frName'\t: self.frName\t= value\n\t elif key == 'call'\t\t: self.callback\t= value\n\t elif key == 'value'\t\t: self.value\t= value\n#\t elif key == 'color'\t\t: self.color\t= value\n\n\n\t# -------------------------\n\tdef OnSelected( self, pos ):\n#\t x1 = self.rect[0]\n#\t y1 = self.rect[1]\n#\t x2 = x1 + self.rect[2] - 1\n#\t y2 = y1 + self.rect[3] - 1\n#\t if ((pos[0] >= x1) and (pos[0] <= x2) and\n#\t (pos[1] >= y1) and (pos[1] <= y2)):\n#\t if self.rect.collidepoint( pos ):\n\t if IsRectArea( self.rect, pos ):\n\t if self.callback:\n\t if self.value is None: self.callback()\n\t else: self.callback( self.value )\n\t return True\n\t return False\n\n\n\t# -------------------------\n\tdef OnDraw( self, screen ):\n\t if self.iconBk:\n\t screen.blit( self.iconBk.bmp,\n\t ( self.rect[0]+(self.rect[2]-self.iconBk.bmp.get_width())/2,\n\t self.rect[1]+(self.rect[3]-self.iconBk.bmp.get_height())/2 ) )\n\t if self.iconFr:\n\t screen.blit( self.iconFr.bmp,\n\t ( self.rect[0]+(self.rect[2]-self.iconFr.bmp.get_width())/2,\n\t self.rect[1]+(self.rect[3]-self.iconFr.bmp.get_height())/2 ) )\n\n\n\t# -------------------------\n\tdef setIconBk( self, name ):\n\t if name is None:\n\t self.iconBk = None\n\t else:\n\t for i in icons:\n\t if name == i.name:\n\t self.iconBk = i\n\t break\n\n\t# -------------------------\n\tdef setIconFr( self, name ):\n\t if name is None:\n\t self.iconFr = None\n\t else:\n\t for i in icons:\n\t if name == i.name:\n\t self.iconFr = i\n\t break\n\n#----------------------------------------------------------\n# callback Functions --------------------------------------\n#----------------------------------------------------------\n# Setting \n# \t_pos = +1: next setting type\n#\t\t -1: prev setting type\ndef settingCallback( _pos ):\n\tglobal dispMode\n\n\tenb = False\n\t_max = len( buttons )\n\n\twhile enb is False:\n\t dispMode += _pos\n\t if dispMode <= _PAGE_TOP:\t\tdispMode = _max - 1\n\t elif dispMode >= _max:\t\tdispMode = _PAGE_TOP+1\n\n\t # Check Disp Mode Enable \n\t enb = disp_mode_enb[ dispMode ]\n\n\n#----------------------------------------------------------\n# Quit button\ndef quitCallback(): \n\tprint(\" bye \")\n\tprint(\" \")\n\traise SystemExit\n\n\n#----------------------------------------------------------\n# Display Normal Area\ndef normCallback( _disp ): \n\tglobal loadIdx, scaled, dispMode, old_dispMode, settingMode, storeMode\n\n\tif _disp is 0:\t\t# Setting icon (settings)\n\t dispMode\t\t\t= settingMode # last setting Pos\n\n\telif _disp is 1:\t# Play icon ( disp Saved Image File )\n\n\t if scaled: \t\t# Last photo is already in memory\n\t loadIdx\t\t\t= saveIdx\n\t dispMode\t\t= 0 # Disp Image \n\t old_dispMode\t= -1 # Update Display\n\n\t else: \t\t# Load image\n\t num = get_imgMinMax( pathData[ storeMode ] )\n\t if num: showImage( num[ 1 ] )\t# Show max image Number in directory\n\t else: dispMode\t= 2 \t\t\t# Not Saved Image Files\n\n\telse: \t\t\t\t# Shutter Picture\n\t takePicture()\n\n\n#----------------------------------------------------------\n# back Normal View\ndef backCallback(): \n\tglobal dispMode, settingMode\n\tif dispMode > _PAGE_TOP:\n\t settingMode\t= dispMode\n\tdispMode = _PAGE_TOP # Switch back to viewfinder mode\n\n#----------------------------------------------------------\n# _pos = +1: next image to screen\n#\t\t -1: prev image to screen\n#\t \t 0: request delete now screen image\ndef imageCallback( _pos ): \n\tglobal dispMode\n\tif _pos is 0:\n\t dispMode\t= 1\t# Check Delete Image\n\telse:\n\t showNextImage( _pos )\n\n\n#----------------------------------------------------------\n# Delete Callback\ndef deleteCallback( _reqDelete ): \n\tglobal loadIdx, scaled, dispMode, storeMode\n\tdispMode\t\t= 0\n\told_dispMode\t= -1\t# Update Display\n\tif _reqDelete is True:\n\t os.remove( pathData[ storeMode ] + '/Image_' + '%04d' % loadIdx + '.JPG' )\n\n\t if( get_imgMinMax( pathData[ storeMode ] )):\n\t screen.fill(0)\n\t pygame.display.update()\n\t showPrevImage()\n\n\t else:\t\t# No image \n\t dispMode\t= 2\n\t scaled\t\t= None\n\t loadIdx\t\t= -1\n\n#----------------------------------------------------------\n# Picture Size setting\ndef sizeModeCallback( _pos ): \n\tglobal sizeMode\n\n\t# unselect Pos x \n\tbuttons[ _PAGE_TOP + 1 ][ sizeMode + 3 ].setIconBk('unsel_size')\n\n\t# New Select Pos [x] \n\tsizeMode = _pos\n\tbuttons[ _PAGE_TOP + 1 ][ sizeMode + 3 ].setIconBk('sel_size')\n\t_NORMAL_RESO\t\t= sizeData[ sizeMode ][ 1 ]\n\tcamera.resolution\t= _NORMAL_RESO\n\n#=========================================================#\n# Global Area\ndispMode\t\t= _PAGE_TOP\t# display Mode\nold_dispMode\t= -1\t\t# display Mode old Value\n\nsettingMode\t\t= 4\t\t\t# Last-used settings mode (default = size)\n\nstoreMode\t\t= 0\t\t\t# Storage mode; default = Photos folder\nold_storeMode\t= -1\t\t# old storage Mode\n\nsizeMode\t\t= 2\t\t\t# Image size; default = Medium\nisoMode\t\t\t= 0\t\t\t# ISO settingl default = Auto\nsaveIdx\t\t\t= -1\t\t# Image index for saving (-1 = none set yet)\nloadIdx\t\t\t= -1\t\t# Image index for loading\n\nscaled\t\t\t= None\t\t# pygame Surface\n\nicons\t\t\t= []\t\t# This list gets populated at startupbuttons\n\nbusy\t\t\t= False\t\t# for Thread Display Working Flag\nspinText\t\t= ''\n\nuid\t\t\t\t= 0\ngid\t\t\t\t= 0\t\t\t\n\n\n# -------------------------------------------------------\n# const Data \n\nsizeData = [ # Camera parameters for different size settings\n\t\t\t # Full res , In Camera, Crop window ( Not Used )\n#Camera-V1.3\n#\t\t\t [(2592, 1944), (320, 240), (0.0 , 0.0 , 1.0 , 1.0 )], # Large\n#\t\t\t [(1920, 1080), (320, 180), (0.1296, 0.2222, 0.7408, 0.5556)], # Med\n#\t\t\t [(1440, 1080), (320, 240), (0.2222, 0.2222, 0.5556, 0.5556)] # Small\n\n#Camera-V2.1\n\t\t\t [(3240, 2430), (320, 240), (0.0 , 0.0 , 1.0 , 1.0 )], # Large\t\t 4:3\n\t\t\t [(1920, 1080), (320, 192), (0.2037, 0.2778, 0.5926, 0.4444)], # 1080p\t\t16:9\n\t\t\t [(1440, 1080), (320, 240), (0.2778, 0.2778, 0.4444, 0.4444)], # Medium\t\t 4:3\n\t\t\t [(1280, 720), (320, 192), (0.3025, 0.3519, 0.3950, 0.2962)], # 720p\t\t16:9\n\t\t\t [(640, 480), (320, 240), (0.4012, 0.4012, 0.1976, 0.1976)] # Small\t\t 4:3\n\t\t ]\n\n# Take picture on directory Position\npathData = [\n '/home/pi/Photos',\t# Path for storeMode = 0 (Photos directory)\n '/home/pi/Pictures']\t# Path for storeMode = 1 (Pictures directory)\n\n# Display mode allow\ndisp_mode_enb = [\t\n\t\t\t\t\tTrue,\t# disp mode - 0:\tdisp Saved photo\n\t\t\t\t\tTrue,\t# disp mode - 1:\tdelete Saved photo\n\t\t\t\t\tTrue,\t# disp mode - 2:\tEmpty Saved photo\n\t\t\t\t\tTrue,\t# disp mode - 3:\tdisp in Camera \n\t\t\t\t\tTrue,\t# disp mode - 4:\tImage Size Setting\n\t\t\t\t\tFalse,\t# disp mode - 5:\tImage Effect Setting\n\t\t\t\t\tFalse,\t# disp mode - 6:\tCamera ISO Setting\n\t\t\t\t\tTrue,\t# disp mode - 7:\tApp Quit\n\t\t\t\t]\n\nbuttons = [\n\t# disp mode 0 - disp Saved photo\n\t[\n\t\tButton(( 0,188,320, 52), bkName='back' , call=backCallback),\n\t\tButton(( 0, 0, 80, 52), bkName='prev' , call=imageCallback, value=-1),\n\t\tButton((240, 0, 80, 52), bkName='next' , call=imageCallback, value= 1),\n\t\tButton((240, 0, 80, 52), ),\t\t\t# for dummy\n\t\tButton(( 88, 70,157, 40)), \t\t\t\t# 'loading...' label ( used only )\n\t\tButton((130,115, 60, 60)), \t\t\t\t# 'Spin-x' label ( used only )\n\t\tButton((121, 0, 78, 52), bkName='trash', call=imageCallback, value= 0)\n\t],\n\n\t# disp mode 1 - delete Saved Photo\n\t[\n\t\tButton(( 0,35,320, 33), bkName='del_image'),\n\t\tButton(( 32,86,120,100), bkName='bk_yesno', frName='fg_yes', call=deleteCallback, value=True),\n\t\tButton((168,86,120,100), bkName='bk_yesno', frName='fg_no', call=deleteCallback, value=False)\n\t],\n\n\t# disp mode 2 - Empty Photo on Screen\n\t[\n\t\tButton((0, 0,320,240), call=backCallback),\t\t# Full screen = button\n\t\tButton((0,188,320, 52), bkName='back'),\t\t\t# Fake 'Done' button\n\t\tButton((0, 53,320, 80), bkName='empty')\t\t\t# 'Empty' message\n\t],\n\n\t# disp mode 3 - in Camera Image\n\t[\n\t\tButton(( 0,188,104, 52), bkName='setting2', call=normCallback, value=0),\n\t\tButton((108,188,104, 52), bkName='play2' , call=normCallback, value=1),\n\t\tButton((216,188,104, 52), bkName='power2' , call=quitCallback ),\n\t\tButton(( 0, 0,320,240) , call=normCallback, value=2),\n\t\tButton(( 88, 51,157, 40)),\t\t\t\t# 'Saving...' label ( used only )\n\t\tButton((130, 95, 60, 60))\t\t\t\t# 'Spin-x' label ( used only )\n\t],\n\n\n\t# -- settings modes --\n\t# disp mode 4 - Image size setting\n\t[\n\t\tButton(( 0,188,320, 52), bkName='back', call=backCallback),\n\t\tButton(( 0, 0, 80, 52), bkName='prev', call=settingCallback, value=-1),\n\t\tButton((240, 0, 80, 52), bkName='next', call=settingCallback, value= 1),\n\n\t\tButton(( 2, 58,100,60), bkName='unsel_size', frName='size_0', call=sizeModeCallback, value=0),\n\t\tButton((110, 58,100,60), bkName='unsel_size', frName='size_1', call=sizeModeCallback, value=1),\n\t\tButton((218, 58,100,60), bkName='sel_size', frName='size_2', call=sizeModeCallback, value=2),\n\t\tButton(( 2,122,100,60), bkName='unsel_size', frName='size_3', call=sizeModeCallback, value=3),\n\t\tButton((110,122,100,60), bkName='unsel_size', frName='size_4', call=sizeModeCallback, value=4),\n\n\t\tButton(( 0, 10,320, 29), bkName='size')\n\t],\n\n#### Not Used ####\n\t# disp mode 5 - Image effect Setting\n\t[\n\t\tButton(( 0,188,320, 52), bkName='back', call=backCallback),\n\t\tButton(( 0, 0, 80, 52), bkName='prev', call=settingCallback, value=-1),\n\t\tButton((240, 0, 80, 52), bkName='next', call=settingCallback, value= 1)\n\t],\n##################\n\n#### Not Used ####\n\t# disp mode 6 - Camera ISO Setting\n\t[\n\t\tButton(( 0,188,320, 52), bkName='back', call=backCallback),\n\t\tButton(( 0, 0, 80, 52), bkName='prev', call=settingCallback, value=-1),\n\t\tButton((240, 0, 80, 52), bkName='next', call=settingCallback, value= 1),\n\t],\n##################\n\n\t# disp mode 7 - App quit\n\t[\n\t\tButton(( 0,188,320, 52), bkName='back' , call=backCallback),\n\t\tButton(( 0, 0, 80, 52), bkName='prev' , call=settingCallback, value=-1),\n\t\tButton((240, 0, 80, 52), bkName='next' , call=settingCallback, value= 1),\n\n\t\tButton((110, 60,100,120), bkName='quit-ok', call=quitCallback),\n\t\tButton(( 0, 10,320, 35), bkName='quit')\n\t]\n]\n\n\n#=========================================================#\n#-- Initialize PyGame --#\ndef Init_PyGame():\n\tglobal screen, rgb\n\n\t# Init framebuffer/touchscreen environment variables\n\t#\n\t# under setting is tslib install \n#\tos.putenv('SDL_VIDEODRIVER', 'fbcon')\n#\tos.putenv('SDL_FBDEV' , '/dev/fb1')\n#\tos.putenv('SDL_MOUSEDRV' , 'TSLIB')\n#\tos.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen')\n\n\t# Get user & group IDs for file & directory creation\n\ts = os.getenv(\"SUDO_UID\")\n\tuid = int( s ) if s else os.getuid()\n\ts = os.getenv(\"SUDO_GID\")\n\tgid = int( s ) if s else os.getgid()\n\n\t# Input Camera buffer data\n\trgb = bytearray( 320 * 240 * 3 )\n\n\t# Init PyGame and screen setting\n\tpygame.init()\n\tpygame.mouse.set_visible( True )\t# false: mouse position --> not mouse X,Y\n\tscreen = pygame.display.set_mode(( 0,0 ), pygame.FULLSCREEN )\n\n\n#-- Initialize Camera --#\ndef Init_Camera():\n\tglobal camera\n\tcamera = picamera.PiCamera()\n\tatexit.register( camera.close )\n\n\t# Initial Setting #\n#\tcamera.vflip\t\t= True\n#\tcamera.hflip\t\t= True\n\tcamera.vflip\t\t= False\n\tcamera.hflip\t\t= False\n\tcamera.resolution\t= _NORMAL_RESO\t# for ViewMode\n\tcamera.ISO\t\t\t= 0\t\t\t\t# for ISO = AUTO\n\tcamera.framerate\t= 30\n\n\n#-- Initialize Icon --#\ndef Init_Icon():\n\t# Load all icons on startup.\n\tfor file in os.listdir( iconPath ):\n\t if fnmatch.fnmatch( file, '*.png' ):\n\t icons.append( Icon( file.split('.')[0] ))\n\n\t# Set Button.icon --> link icons\n\tfor btns in buttons:\t\t\t# btns = buttons[ dispmode ]\n\t for btn in btns:\t\t\t\t# btn = buttons[ dispmode ][ x ]\n\t for i in icons:\t\t\t\t# i = icons[ n ]\n\t if btn.bkName == i.name:\t# match iconBk name \n\t btn.iconBk\t= i\t\t\t# link btn.iconBk\n\t btn.bkName\t= None\t\t# clear icon name( not used after program: garbage collection )\n\t if btn.frName == i.name:\t# match iconFr name \n\t btn.iconFr\t= i\t\t\t# link btn.iconFr\n\t btn.frName\t= None\t\t#\tclear icon name\n\n#-- Initialize GPIO --#\ndef Init_GPIO():\n\t# Run Pulse Control GPIO27\n\tGPIO.setwarnings( False )\n\tGPIO.setmode( GPIO.BCM ) \t\t # GPIO Number\n\tGPIO.setup ( O_PULSE_NUM, GPIO.OUT ) # GPIO27 Output\n\tGPIO.output( O_PULSE_NUM, 1 ) # GPIO27 = HIGH\n\n\t# Low-BATT status on GPIO22:\tInput PullUP\n\tGPIO.setup ( I_REQ_POFF, GPIO.IN, pull_up_down=GPIO.PUD_UP ) \n\n\tatexit.register( GPIO.cleanup )\n\n\n#-- Initialize System --#\ndef Init_System():\n\tInit_PyGame()\n\tInit_Camera()\n\tInit_Icon()\n\tInit_GPIO()\n\n\n#=========================================================#\n#-- Check Image File Number:\tReturn min, max --#\ndef get_imgMinMax( _path ):\n\tmin = 9999\n\tmax = 0\n#\tprint( '%s : ' %_path )\n\n\ttry:\n\t for file in os.listdir( _path ):\n#\t print( '%s : ' %file )\n\t if fnmatch.fnmatch(file, 'Image_[0-9][0-9][0-9][0-9].JPG'):\n\t i = int(file[6:10])\n\t if(i < min): min = i\n\t if(i > max): max = i\n#\t print( 'num=%d : (%d < %d ) ' % ( i, min, max ))\n\tfinally:\n\t return None if min > max else (min, max)\n\n#------------------------------------------------\n# Busy Wait indicator.\n# wait global 'busy' Flag.\ndef spinner():\n\tglobal busy, dispMode, old_dispMode, spinText\n\n\tbuttons[ dispMode ][ 4 ].setIconBk( spinText )\n\tbuttons[ dispMode ][ 4 ].OnDraw( screen )\n\tpygame.display.update()\n\n\tbusy = True\n\tn = 0\n\twhile busy is True:\n\t buttons[ dispMode ][ 5 ].setIconBk('spin-' + str( n ))\n\t buttons[ dispMode ][ 5 ].OnDraw( screen )\n\t pygame.display.update()\n\t n = (n + 1) % 6\n\t time.sleep( 0.133 )\n\n\tbuttons[ dispMode ][ 4 ].setIconBk( None )\n\tbuttons[ dispMode ][ 5 ].setIconBk( None )\n\told_dispMode = -1 # Force refresh\n\n\n#------------------------------------------------\n#-- Save JPEG Image. Auto File Name --#\ndef takePicture():\n\tglobal busy, gid, uid, scaled, sizeMode, storeMode, old_storeMode\n\tglobal loadIdx, saveIdx, spinText\n\n\t# not find Picture directory\n\tif not os.path.isdir( pathData[ storeMode ] ):\n\t try:\n\t os.makedirs( pathData[ storeMode ] )\n\t # Set new directory ownership : chmode to 755\n\t os.chown( pathData[ storeMode ], uid, gid )\n\t os.chmod( pathData[ storeMode ],\n\t stat.S_IRUSR | stat.S_IXUSR | stat.S_IWUSR |\n\t stat.S_IRGRP | stat.S_IXGRP |\n\t stat.S_IROTH | stat.S_IXOTH )\n\n\t except OSError as e:\n\t # errno = 2 if can't create directory\n\t print( errno.errorcode[ e.errno ] )\n\t return\n\n\n\t#----------------------------------------------------\n\t# get max image index Number, start at next pos.\n\tif storeMode != old_storeMode:\n\t r = get_imgMinMax( pathData[ storeMode ] )\n\t if r is None:\n\t saveIdx = 1\n\t else:\n\t saveIdx = r[ 1 ] + 1\n\t if saveIdx > 9999:\n\t saveIdx = 0\t\t# 0000 --> 9999 -> 0000 -> ...\n\t old_storeMode = storeMode\n\n\n\n\t#----------------------------------------------------\n\t# Scan for next image Name\n\tcnt = 0\n\twhile True:\n\t filename = pathData[ storeMode ] + '/Image_' + '%04d' % saveIdx + '.JPG'\n\t if not os.path.isfile( filename ): \tbreak\n\t saveIdx\t+= 1\n\t if saveIdx > 9999: saveIdx = 0\n\n\t # Check always loop ( not break )\n\t cnt\t\t+= 1\n\t if cnt > 9999:\tbreak;\n\n\n\t#----------------------------------------------------\n\t# saving job Display Thread Start \n\tscaled = None\n\n\tspinText = 'saving'\n\tt = threading.Thread( target=spinner )\n\tt.start()\n\n\tcamera.resolution = sizeData[ sizeMode ][ 0 ]\n\n\ttry:\n\t\tRec_Picture( filename )\n\t\t# Set image file: chmode to 644\n\t\tos.chmod( filename,\n\t\t\tstat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH )\n\t\timg = pygame.image.load( filename )\n\t\tscaled = pygame.transform.scale( img, sizeData[ sizeMode ][1] )\n\n\tfinally:\n\t # Add error handling\n\t camera.resolution = _NORMAL_RESO\n#\t camera.crop = (0.0, 0.0, 1.0, 1.0)\n\n\t# end of Thread\n\tbusy = False\n\tt.join()\n\n\tif scaled:\n\t if scaled.get_height() < 240:\t# clear screen on small image\n\t screen.fill( 0 )\n\n\t screen.blit( scaled, (( 320 - scaled.get_width() ) / 2,\n\t\t\t\t \t\t ( 240 - scaled.get_height()) / 2 ))\n\t pygame.display.update()\n\t time.sleep( 2.5 )\n\t loadIdx = saveIdx\n\n\n#----------------------------------------------\n#-- Display Next Image --#\n# _dir =\t+1:\tnext image num\n#\t\t\t-1:\tprev image num\ndef showNextImage( _dir ):\n\tglobal busy, loadIdx, spinText\n\n\t# job Display Thread Start \n\tspinText = 'loading'\n\tt = threading.Thread( target=spinner )\n\tt.start()\n\n\tcnt = 0\n\tnum = loadIdx\n\twhile True:\n\t num += _dir\n\t if( num > 9999 ): num = 0\n\t elif( num < 0 ): num = 9999\n\t if os.path.exists( pathData[ storeMode ]+'/Image_'+'%04d'%num+'.JPG'):\n\t drawImage( num )\n\t break\n\n\t # Check always loop ( not break )\n\t cnt\t\t+= 1\n\t if cnt > 9999:\n\t break;\n\n\t# end of Thread\n\tbusy = False\n\tt.join()\n\n\n#----------------------------------------------\ndef showPrevImage():\n\tshowNextImage( -1 )\n\n\n#----------------------------------------------\ndef showImage( _num ):\n\tglobal busy, dispMode, old_dispMode, spinText\n\n\tspinText = 'loading'\n\tt = threading.Thread( target=spinner )\n\tt.start()\n\n\tdrawImage( _num )\n\n\tbusy\t= False\n\tt.join()\n\n\tdispMode\t\t= 0 # Photo playback\n\told_dispMode\t= -1 # Force screen refresh\n\n\ndef drawImage( _num ):\n\tglobal busy, loadIdx, scaled, dispMode, old_dispMode, sizeMode, storeMode\n\n\timg\t\t= pygame.image.load(\n\t pathData[ storeMode ] + '/Image_' + '%04d' % _num + '.JPG')\n\tscaled\t= pygame.transform.scale( img, sizeData[ sizeMode ][ 1 ] )\n\tloadIdx\t= _num\n\n\n#=========================================================#\n#-- Record Picture --#\ndef Rec_Picture( fname ):\n\tglobal camera\n\tcamera.capture( fname )\n\n#-- Record Movie --#\ndef Rec_Movie_sec( fname, sec ):\n\tglobal camera\n\tcamera.start_recording( fname )\n\ttime.sleep( sec )\n\tcamera.stop_recording()\n\n\t# Start Preview #\n\tcamera.start_preview()\n\n\n#=========================================================#\n# Start App:\tSimple Start --------------------------\ndef start1():\n\tInit_System()\n\n\t# Wait 10sec ( 1sec x 10 cycle )\n#\tfor n in range(10):\n#\t time.sleep(1)\n\n\t# Record Image #\n\t#\tRec_Picture( 'image.jpg' )\n\n\t# Record Movie #\n\t# Rec_Movie_sec( 'video.h264', 5 )\n\n\n#=========================================================#\n# Update Display -----------------------------------------\n#=========================================================#\ndebugText = None\t\t\t\t# for DEBUG\n\ndef updateDisp():\n\tglobal screen, rgb, scaled\n\tglobal dispMode, old_dispMode\n\tglobal debugText\t\t\t# for DEBUG \n\n\t# disp Mode #\n\tif dispMode >= _PAGE_TOP:\t# disp In Camera Image\n\t stream = io.BytesIO()\t\t# Capture into in-memory stream\n\t camera.capture( stream, use_video_port=True, format='rgb' )\n\t stream.seek( 0 )\n\t stream.readinto( rgb )\t# stream -> RGB buffer\n\t stream.close()\n\t img = pygame.image.frombuffer( rgb[ 0:\n\t\t( sizeData[ sizeMode ][1][0] * sizeData[ sizeMode ][1][1] * 3 )],\n\t\t sizeData[ sizeMode ][1], 'RGB')\n\n\telif dispMode < 2:\t\t\t# display load Image\n\t img = scaled\t\t\t\t# Show last-loaded image\n\n\t# ----------- #\n\telse:\n\t img = None\t\t\t\t# none Image\n\n ###############\n\n\t\t\t\t\t\t\t\t# clear screen on ( small Image / non Image )\n\tif img is None or img.get_height() < 240: \n\t\tscreen.fill( 0 )\n\n\tif img:\n\t\tscreen.blit( img,(( 320 - img.get_width() ) / 2,\n\t\t\t\t\t\t ( 240 - img.get_height()) / 2 ))\n\n\t# for DEBUG #\n\tif debugText:\n\t\tscreen.blit( debugText,[ 20, 20 ] ) # Debug Text\n\t#############\n\n\t# Overlay buttons on display and update\n\tfor i,b in enumerate( buttons[ dispMode ] ):\n\t b.OnDraw( screen )\n\tpygame.display.update()\n\told_dispMode = dispMode\n\n\n#=========================================================#\n# Main loop ----------------------------------------------\ndef mainLoop():\n\tglobal debugText\t\t\t\t# for DEBUG\n\n\t_frameCnt \t = 0\n\t_finish_Flag = 0\n\tpls\t\t\t = 0\n\n\tfont = pygame.font.Font( None, 24 )\n\n\twhile( _finish_Flag == 0):\n\n\t # Process touchscreen input\n\t while True:\n\t for event in pygame.event.get():\n\t if( event.type is MOUSEBUTTONDOWN ):\n#\t _finish_Flag = 1\t# for DEBUG\n#\t break\t\t\t\t#\t ,,\n\n\t # Job Mouse Event\n\t pos = pygame.mouse.get_pos()\n\n\t # for DEBUG #\n#\t debugText = font.render( 'X=' + '%03d' % pos[0] + ' Y=' + '%03d' % pos[1] \n#\t \t\t\t\t\t\t\t, True, (255,255,255))\n\t #############\n\n\t for b in buttons[ dispMode ]:\n\t if b.OnSelected( pos ): break\n\n\t # If in viewfinder or settings modes, stop processing touchscreen\n\t # and refresh the display to show the live preview. In other modes\n\t # (image playback, etc.), stop and refresh the screen only when\n\t # dispMode changes.\n\t if dispMode >= _PAGE_TOP or dispMode != old_dispMode: break\n\n\t # Update Display\t# refresh Freq = 7.5 Hz ( for Idle: Measure GPIO27: 2017/04/12 )\n\t updateDisp()\n#\t _finish_Flag = 1\n#\t time.sleep( 3 )\n#\t _frameCnt += 1\n\t if( _frameCnt >= 50000 ):\n\t _finish_Flag = 1\n\t time.sleep( 3 )\n\t print( \"Timeout Finish !\" )\n\n\t #-- Use Power Board --\n\t GPIO.output( O_PULSE_NUM, pls )\n\t pls ^= 0x01\n\t not_ReqPoff = GPIO.input( I_REQ_POFF )\n\t if not_ReqPoff == 0:\n\t _finish_Flag = 1\n\t time.sleep( 3 )\n\t print( \"Req PowerOff Finish !\" )\n\n#=========================================================#\n\nif __name__==\"__main__\":\n\tstart1()\n\tmainLoop()\n\n#=========================================================#\n" } ]
4
nchronas/SpyTeddy
https://github.com/nchronas/SpyTeddy
30c7f03662e543fee66bdd5278633d9eb5783789
c533c3edf309a949ee0de10a57e129fb518c2a56
db34794e516b02529188e115b3536321f715064f
refs/heads/master
2016-09-11T11:42:49.286960
2015-06-05T12:38:47
2015-06-05T12:38:47
34,117,262
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6643046736717224, "alphanum_fraction": 0.6672571301460266, "avg_line_length": 21.885135650634766, "blob_id": "0d0672dd330cdd4a35c12283820851ccea0d0d80", "content_id": "9aa3b699ec6e80236f81ed480b56749e11e4d121", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3387, "license_type": "no_license", "max_line_length": 85, "num_lines": 148, "path": "/wifi/start.py", "repo_name": "nchronas/SpyTeddy", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport pyconnman\nimport dbus\nimport time\nimport pprint\nimport subprocess\nimport dbus.mainloop.glib\nimport gobject\nimport pickle\n\nserver_started = False\n\ndef start_server():\n\tprint '* starting web server'\n\tp = subprocess.Popen(['python', '/app/wifi/server.py'])\n\n\n#ConnManager.SIGNAL_SERVICES_CHANGED event handler\ndef on_scan_done(signal, callback, *args):\n\t# print '\\n========================================================='\n\t# print '>>>>>', signal, '<<<<<'\n\t# print args\n\t# print '========================================================='\n\n\tprint '* got SIGNAL_SERVICES_CHANGED event'\n\n\t#manager.remove_signal_receiver(pyconnman.ConnManager.SIGNAL_SERVICES_CHANGED)\n\n\tcallback()\n\n#called by on_scan_done\n#when scan is done, this event is triggered, wireless networks available can be saved\ndef get_services():\n\tglobal server_started\n\tservices = manager.get_services()\n\n\twireless_networks = {}\n\twireless_ssids = ''\n\n\tfor i in services:\n\t\t(path, params) = i\n\t\tif path.find('wifi') > -1:\n\t\t\twireless_networks[str(path)] = str(params['Name'])\n\t\t\twireless_ssids += str(params['Name']) + ' '\n\n\tprint '* wireless networks found: ', wireless_ssids\n\n\tif len(wireless_networks) > 0:\n\t\tprint '* saving wireless networks in /data/ssids.p'\n\n\t\t#save\n\t\twith open( '/data/ssids.p', 'wb' ) as f:\n\t\t\tpickle.dump(wireless_networks, f)\n\n\t\tif server_started == False:\n\t\t \t#need wifi credentials\n\t\t \t#start AP\n\t\t \tsubprocess.call(['python', '/app/wifi/setup_ap.py'])\n\n\t\t\tserver_started = True\n\t\t\tstart_server()\n\ndef try_connect():\n\tprint \"* try to connect\"\n\n\treturn_code = -100\n\n\ttry:\n\t\twifi_creds = pickle.load(open( '/data/creds.p', 'rb' ))\n\n\t\tprint \"* wifi credentials found. Connecting...\"\n\n\t\tpconnect = subprocess.Popen(\n\t\t\t\t\t\t\t['python',\n\t\t\t\t\t\t\t'/app/wifi/connect.py',\n\t\t\t\t\t\t\tstr(wifi_creds['path']),\n\t\t\t\t\t\t\tstr(wifi_creds['psk'])])\n\n\t\tpconnect.wait()\n\n\t\treturn_code = pconnect.returncode\n\n\t\tprint '* connect script returned ', return_code\n\n\texcept:\n\t\tprint \"* wifi credentials not found\"\n\n\treturn return_code == 0;\n\ndef wifi_reset(tech):\n\tprint \"* resetting the wifi adapter\"\n\n\t#reset wifi adapter (power off and on)\n\tif tech.get_property('Powered') == True:\n\t\ttech.set_property('Powered', False)\n\n\ttry:\n\t\ttech.set_property('Powered', True)\n\texcept dbus.exceptions.DBusException:\n\t\tprint 'Unable power up wifi adapter:', sys.exc_info()\n\n\n\nif __name__ == '__main__':\n\n\tdbus.mainloop.glib.DBusGMainLoop(set_as_default=True)\n\n\tmanager = pyconnman.ConnManager()\n\n\ttry:\n\t\t#while scanning ConnManager.SIGNAL_SERVICES_CHANGED event would be triggered\n\t\tmanager.add_signal_receiver(on_scan_done,\n\t\t\t\t\t\t\t\t\tpyconnman.ConnManager.SIGNAL_SERVICES_CHANGED,\n\t\t\t\t\t\t\t\t\tget_services)\n\texcept dbus.exceptions.DBusException:\n\t\tprint 'Unable to complete:', sys.exc_info()\n\n\ttech = pyconnman.ConnTechnology('/net/connman/technology/wifi')\n\n\ttry:\n\t\t#reset wifi adapter\n\t\twifi_reset(tech)\n\texcept dbus.exceptions.DBusException:\n\t\tprint '* reset timed out'\n\t\tprint '* sleep for 10s'\n\t\ttime.sleep(10)\n\t\t# retry\n\t\twifi_reset(tech)\n\n\ttry:\n\n\t\t# connect\n\t\tif try_connect():\n\t\t\t#succesfully connected\n\t\t\tsys.exit()\n\t\telse:\n\t\t\t#scanning for wireless networks\n\t\t\t#found wifis are saved in /data/ssids.p\n\t\t\tprint \"* scanning for available wireless networks\"\n\t\t\ttech.scan()\n\n\n\texcept dbus.exceptions.DBusException:\n\t\tprint 'Unable to complete:', sys.exc_info()\n\n\tmainloop = gobject.MainLoop()\n\tmainloop.run()\n" }, { "alpha_fraction": 0.6870925426483154, "alphanum_fraction": 0.6994785070419312, "avg_line_length": 25.016948699951172, "blob_id": "84f03fb49d6b5f992e94c9748f836d29b3bded82", "content_id": "20f71ccfee16f9034da1b10de8db41f430b78228", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1534, "license_type": "no_license", "max_line_length": 85, "num_lines": 59, "path": "/wifi/setup_ap.py", "repo_name": "nchronas/SpyTeddy", "src_encoding": "UTF-8", "text": "# starts an AP with ssid and psk given\n# usage python setup_ap.py <ssid> <psk>\n\nimport os\nimport sys\nimport dbus\nimport time\nimport subprocess\n\n# from ENV or default\nssid = os.environ.get('SSID', 'ResinAP')\npsk = os.environ.get('PASSPHRASE', '12345678')\n\ntech_type = 'wifi'\npath = '/net/connman/technology/' + tech_type\ntry:\n\tbus = dbus.SystemBus()\n\n\ttech = dbus.Interface(bus.get_object('net.connman', path), 'net.connman.Technology')\n\n\tif tech == None:\n\t\tprint '* no %s technology available' % tech_type\n\t sys.exit(1)\n\n\tproperties = tech.GetProperties()\n\n\tif properties['Tethering']:\n\t print '* interface already tethering. Resetting'\n\t tech.SetProperty('Tethering', dbus.Boolean(0))\n\t # FIXME: If we don't wait connman complains later.\n\t # We should be listening for events instead of waiting\n\t # a fixed amount of time\n\t time.sleep(10)\n\n\tprint '* setting SSID to: %s' % (ssid)\n\ttech.SetProperty('TetheringIdentifier', ssid)\n\n\tprint '* setting Passphrase to: %s' % (psk)\n\ttech.SetProperty('TetheringPassphrase', psk)\n\n\tprint '* enabling tethering on %s' % tech_type\n\ttech.SetProperty('Tethering', dbus.Boolean(1))\n\n\t# setup captive portal using iptables\n\t# 8080 - port of the local web server where users would be redirected\n\tprint '* setting up captive portal redirect'\n\n\t#sleep 10\n\ttime.sleep(10)\n\n\tsubprocess.call(['/app/wifi/setup-iptables.sh', 'ADD', '8080'])\n\n\tprint '* done starting AP'\n\n\tsys.exit(0)\n\nexcept dbus.exceptions.DBusException:\n\tprint 'Unable to complete:', sys.exc_info()\n\tsys.exit(1)" }, { "alpha_fraction": 0.591549277305603, "alphanum_fraction": 0.6136820912361145, "avg_line_length": 28.176469802856445, "blob_id": "81e868b3a31712634c00d7b355aa63881b706f59", "content_id": "cc32adde71682ff6339d859e675a48706a464f4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 497, "license_type": "no_license", "max_line_length": 148, "num_lines": 17, "path": "/wifi/setup-iptables.sh", "repo_name": "nchronas/SpyTeddy", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# remove all DNAT rules\necho -e '\\t* removing all DNAT rules'\nfor i in $(iptables -t nat -L -n --line-numbers | grep ^[1-9].*DNAT | awk '{ print $1 }' | tac); do echo $i; iptables -t nat -D PREROUTING $i; done\n\nif [ $1 == \"ADD\" ]\n\tthen\n\t\t# forward all 80 to local tether\n\t\ttether_ip=$(ifconfig tether | awk '/inet addr/{print substr($2,6)}')\n\n\t\trun=\"iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination $tether_ip:$2\"\n\n\t\techo -e \"\\t* running: $run\"\n\n\t\t`$run`\nfi\n\n" }, { "alpha_fraction": 0.6519274115562439, "alphanum_fraction": 0.6530612111091614, "avg_line_length": 17.76595687866211, "blob_id": "cf4849485117acb9cc5da1c0f16ffee395603486", "content_id": "c06ecabf4c6ba9a44eb91c23db63bc32ea29b79f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 882, "license_type": "no_license", "max_line_length": 62, "num_lines": 47, "path": "/wifi/server.py", "repo_name": "nchronas/SpyTeddy", "src_encoding": "UTF-8", "text": "import web\nimport pickle\nimport pprint\nimport subprocess\n\n\nurls = (\n\t'/.*', 'index'\n)\n\napp = web.application(urls, globals())\n\nrender = web.template.render('/app/wifi/templates/')\n\nwireless_networks = pickle.load(open( '/data/ssids.p', 'rb' ))\n\n\nclass index:\n\tdef GET(self):\n\t\treturn render.index(wireless_networks = wireless_networks)\n\n\tdef POST(self):\n\t\tdata = web.input(_method='post')\n\n\t\tprint '* launching connect procedure'\n\n\t\tp = subprocess.Popen(\n\t\t\t\t\t\t['python',\n\t\t\t\t\t\t'/app/wifi/connect.py',\n\t\t\t\t\t\tstr(data.path),\n\t\t\t\t\t\tstr(data.psk)])\n\t\tp.wait()\n\n\t\tif p.returncode == 0:\n\t\t\t#succefully connected\n\t\t\t#stop the server\n\t\t\tapp.stop()\n\t\telse:\n\t\t\t#connection failed, we should restart the AP\n\t\t\tsubprocess.call(['python', '/app/wifi/setup_ap.py'])\n\n\t\treturn render.index(wireless_networks = wireless_networks)\n\n\nif __name__ == '__main__':\n\tprint '* starting server'\n\tapp.run()\n" }, { "alpha_fraction": 0.6787479519844055, "alphanum_fraction": 0.6824547052383423, "avg_line_length": 22.57281494140625, "blob_id": "5ddcb1878696b40033a207d94bc2632c043a4247", "content_id": "510a8b6f1979ebf7ce985d2b4940be6469f59df4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2428, "license_type": "no_license", "max_line_length": 71, "num_lines": 103, "path": "/wifi/connect.py", "repo_name": "nchronas/SpyTeddy", "src_encoding": "UTF-8", "text": "# connect to service path using the psk\n#usage python connect.py <service_path> <psk>\n\nimport dbus\nimport pyconnman\nimport dbus.mainloop.glib\nimport gobject\nimport sys\nimport pickle\nimport pprint\nimport time\nimport subprocess\n\n# service path\nservice_path = sys.argv[1]\n\n# psk\npsk = sys.argv[2]\n\n#available wireless networks\nwireless_networks = pickle.load(open( '/data/ssids.p', 'rb' ))\n\n\nif __name__ == '__main__':\n\ttry:\n\t\tprint '* trying to connect to ', service_path, 'using psk: ', psk\n\n\t\tdbus.mainloop.glib.DBusGMainLoop(set_as_default=True)\n\n\t\tmanager = pyconnman.ConnManager()\n\n\t\tparams = {'name': None,\n\t\t\t\t'ssid': wireless_networks[service_path],\n\t\t\t\t'identity': None,\n\t\t\t\t'username': None,\n\t\t\t\t'password': None,\n\t\t\t\t'passphrase': psk,\n\t\t\t\t'wpspin': None }\n\n\t\tprint '* registering authentication agent'\n\n\t\tagent_path = '/resin/agent'\n\n\t\tagent = pyconnman.SimpleWifiAgent(agent_path)\n\t\tagent.set_service_params('*',\n\t\tparams['name'],\n\t\tparams['ssid'],\n\t\tparams['identity'],\n\t\tparams['username'],\n\t\tparams['password'],\n\t\tparams['passphrase'],\n\t\tparams['wpspin'])\n\n\t\tmanager.register_agent(agent_path)\n\t\tprint '* auth agent has been registered'\n\n\t\ttech = pyconnman.ConnTechnology('/net/connman/technology/wifi')\n\n\t\tprint '* clean iptables'\n\t\tsubprocess.call(['/app/wifi/setup-iptables.sh', 'R'])\n\n\t\ttethering = tech.get_property('Tethering')\n\t\tprint '* currently tethering? ', tethering\n\n\t\tif tethering:\n\t\t\tprint '* disable tethering'\n\t\t\ttech.set_property('Tethering', False)\n\n\t\t\t# TODO: change this hardcoded sleep time\n\t\t\tprint '* sleeping for 15s'\n\t\t\ttime.sleep(15)\n\n\t\tprint '* linking to service: ', service_path\n\t\tservice = pyconnman.ConnService(service_path)\n\n\t\tprint '* connection state:', service.State\n\n\t\tif service.State != 'ready':\n\t\t\tconnected = service.connect()\n\n\t\t\tprint '* connect returned: ',connected\n\n\t\t\tprint '* connection state after connect:', service.State\n\n\t\t\t#TODO: only save if succesful\n\t\t\t# save credentials\n\t\t\tif connected == None:\n\t\t\t\tprint '* connected succefully, saving credentials in /data/creds.p'\n\t\t\t\twith open('/data/creds.p', 'wb') as f:\n\t\t\t\t\tpickle.dump({'path': service_path, 'psk': psk}, f)\n\t\t\telse:\n\t\t\t\tprint '* could not connect'\n\t\t\t\tsys.exit(1)\n\t\telse:\n\t\t\tprint '* already connected'\n\n\t\t# succefully connected or already connected\n\t\tsys.exit(0)\n\n\texcept dbus.exceptions.DBusException:\n\t\tprint '* unable to complete:', sys.exc_info()\n\t\tprint '* exit connect'\n\t\tsys.exit(1)\n" }, { "alpha_fraction": 0.6733167171478271, "alphanum_fraction": 0.6982543468475342, "avg_line_length": 22.58823585510254, "blob_id": "687d2f2ab1c7c43650277a4d82651ed9f9c2e428", "content_id": "ebd23addac5da17bb5fd43f1cbb0431c07994b49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 401, "license_type": "no_license", "max_line_length": 66, "num_lines": 17, "path": "/demo.py", "repo_name": "nchronas/SpyTeddy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport time\nimport picamera\n\nwith picamera.PiCamera() as camera:\n\n camera.resolution = (320, 240)\n # Camera warm-up time\n time.sleep(2)\n camera.capture('image.jpg')\n\n# this infinite loop just allows us to keep the container running\n# so we can use the webterminal to ssh in and check that the image\n# was saved in /data\nwhile 1:\n print 'waiting...'\n time.sleep(30)\n" }, { "alpha_fraction": 0.6968698501586914, "alphanum_fraction": 0.7424492239952087, "avg_line_length": 30.96491241455078, "blob_id": "dcad05ba8c0007adf00fd2341a4fa6a6376a7e5a", "content_id": "b53f456095f120314f51be61528a590b031e7327", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 1821, "license_type": "no_license", "max_line_length": 134, "num_lines": 57, "path": "/Dockerfile", "repo_name": "nchronas/SpyTeddy", "src_encoding": "UTF-8", "text": "FROM resin/rpi-raspbian:jessie\n\nENV INITSYSTEM on\n\nRUN echo \"deb http://vontaene.de/raspbian-updates/ . main\" >> /etc/apt/sources.list\n\n\n# Install Python, pip and the camera module firmware\nRUN apt-get update && apt-get install -y --force-yes python \\\npython-dev \\\nlibraspberrypi-bin \\\npython-pip \\\npython-dbus \\\niptables \\\npython-gobject \\\nnet-tools \\\ndropbear \\\nnano \\\ngit \\\nwget \\\ntar \\\nusbutils \\\nlibjpeg8-dev \\\nimagemagick \\\nsubversion \\\n&& apt-get clean && rm -rf /var/lib/apt/lists/*\n\n# Install picamera python module using pip\nRUN pip install picamera pyconnman web.py\n\n# add the root dir to the /app dir in the container env\nCOPY . /app\n\nRUN mkdir /opt/mjpg-streamer && cd /opt/mjpg-streamer/ && svn co https://svn.code.sf.net/p/mjpg-streamer/code/mjpg-streamer/ . && make\n\n#RUN wget https://www.ffmpeg.org/releases/ffmpeg-snapshot.tar.bz2 && \\\n#tar xvf ffmpeg-snapshot.tar.bz2 && \\\n#cd ffmpeg && \\\n#./configure && \\\n#make && \\\n#make install\n\n#libgstreamer1.0-0 libgstreamer1.0-0-dbg libgstreamer1.0-dev \\\n#liborc-0.4-0 liborc-0.4-0-dbg liborc-0.4-dev liborc-0.4-doc \\\n#gir1.2-gst-plugins-base-1.0 gir1.2-gstreamer-1.0 \\\n#gstreamer1.0-alsa gstreamer1.0-doc gstreamer1.0-omx gstreamer1.0-plugins-bad \\\n#gstreamer1.0-plugins-bad-dbg gstreamer1.0-plugins-bad-doc \\\n#gstreamer1.0-plugins-base gstreamer1.0-plugins-base-apps \\\n#gstreamer1.0-plugins-base-dbg gstreamer1.0-plugins-base-doc gstreamer1.0-plugins-good \\\n#gstreamer1.0-plugins-good-dbg gstreamer1.0-plugins-good-doc gstreamer1.0-plugins-ugly \\\n#gstreamer1.0-plugins-ugly-dbg gstreamer1.0-plugins-ugly-doc gstreamer1.0-pulseaudio \\\n#gstreamer1.0-tools gstreamer1.0-x libgstreamer-plugins-bad1.0-0 \\\n#libgstreamer-plugins-bad1.0-dev libgstreamer-plugins-base1.0-0 \\\n#libgstreamer-plugins-base1.0-dev \\\n\nCMD modprobe bcm2835-v4l2\nCMD [\"bash\", \"/app/start.sh\"]" } ]
7
Suraj0019/Library_System
https://github.com/Suraj0019/Library_System
68a3c741d639c762a94c1178cdde7379b0014b9b
2fe1c5938011299ffbe9385f912b00276c1329fc
ce407ae46230c4155794f5796dab0310183c400a
refs/heads/master
2022-07-16T15:52:33.017660
2020-05-12T11:03:42
2020-05-12T11:03:42
263,310,655
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5555555820465088, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 29.5, "blob_id": "552062dff09b8866a637dea723213b7f81182848", "content_id": "03b614ad0912d4083399c20a8ff6e349f946d9a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 126, "license_type": "no_license", "max_line_length": 43, "num_lines": 4, "path": "/book.py", "repo_name": "Suraj0019/Library_System", "src_encoding": "UTF-8", "text": "class Book:\r\n def __init__(self, book_id, book_name):\r\n self.book_id = book_id\r\n self.book_name = book_name\r\n" }, { "alpha_fraction": 0.6113989353179932, "alphanum_fraction": 0.6113989353179932, "avg_line_length": 36.599998474121094, "blob_id": "3fcf2a8ba351059ba2b0b07f4f8fe428b048219a", "content_id": "bf67d2fe81e42d080fb28e38b2102f24a56abbdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 193, "license_type": "no_license", "max_line_length": 60, "num_lines": 5, "path": "/member.py", "repo_name": "Suraj0019/Library_System", "src_encoding": "UTF-8", "text": "class Member:\r\n def __init__(self, member_id, member_name, book_issued):\r\n self.member_id = member_id\r\n self.member_name = member_name\r\n self.book_issued = book_issued\r\n" }, { "alpha_fraction": 0.8085106611251831, "alphanum_fraction": 0.8085106611251831, "avg_line_length": 46, "blob_id": "de4664f608a698b53dcf75c057c6ebfb93905735", "content_id": "02ccfa7a42ff5f0a4d02bd9c42bd9332fd1ab58e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 94, "license_type": "no_license", "max_line_length": 76, "num_lines": 2, "path": "/README.md", "repo_name": "Suraj0019/Library_System", "src_encoding": "UTF-8", "text": "# Library_System\nThis is a very simple and straight forward Python Project on Library System.\n" }, { "alpha_fraction": 0.528451144695282, "alphanum_fraction": 0.5376371741294861, "avg_line_length": 26.398550033569336, "blob_id": "7d6f49874b485937faad6ac483820519fcb6b4c3", "content_id": "11a848ca8991d5116ee6dd30602d318e606cf4e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3919, "license_type": "no_license", "max_line_length": 98, "num_lines": 138, "path": "/application.py", "repo_name": "Suraj0019/Library_System", "src_encoding": "UTF-8", "text": "import random\r\n\r\nsession_name = ''\r\nsession_id = ''\r\n\r\nmembers = {\r\n '007': 'admin',\r\n}\r\n\r\nmembers_record = {\r\n '007': 'settled'\r\n}\r\n\r\nbooks = {\r\n '1': 'Da Vinci Code',\r\n '2': 'Angels and Demons',\r\n '3': 'Fifty Shades of Grey'\r\n}\r\n\r\nbooks_status = {\r\n '1': 'available',\r\n '2': 'available',\r\n '3': 'available',\r\n}\r\n\r\n\r\ndef id_issue():\r\n Id = random.randint(1001, 1999)\r\n if Id in members:\r\n id_issue()\r\n else:\r\n return Id\r\n\r\n\r\ndef to_borrow_a_book():\r\n print('List of Books with their S.no')\r\n print(books)\r\n book_no = input('Enter the S.no of the book which you want to borrow:')\r\n if book_no in books:\r\n if books_status[book_no] == 'available':\r\n if members_record[session_id] == 'settled':\r\n books_status[book_no] = 'unavailable'\r\n members_record[session_id] = 'pending'\r\n print('Book Issued')\r\n else:\r\n print(\"We can't issue you a book sir. You already have one book to return.\")\r\n else:\r\n print('Sorry Sir! The book is currently unavailable')\r\n else:\r\n print('WRONG S.No')\r\n\r\n\r\ndef to_return_a_book():\r\n print('List of Books with their S.no')\r\n print(books)\r\n book_no = input('Which book do you want to return?')\r\n\r\n if book_no in books:\r\n if books_status[book_no] == 'unavailable':\r\n if members_record[session_id] == 'pending':\r\n books_status[book_no] = 'available'\r\n members_record[session_id] = 'settled'\r\n print('Book Returned')\r\n else:\r\n print(\"You must have mistaken sir. All your accounts are settled\")\r\n else:\r\n print(\"There is some mistake. Please check the book's serial number again\")\r\n else:\r\n print('WRONG S.No')\r\n\r\n\r\ndef to_entry_a_new_book():\r\n if session_id == '007' and session_name == 'admin':\r\n print('Howdy, ' + session_name)\r\n book_no = input('Enter the S.no of the Book:')\r\n book_name = input('Enter the name of the Book:')\r\n if book_no in books:\r\n print('This serial no is already available and can not be assigned to any other book')\r\n else:\r\n books[book_no] = book_name\r\n books_status[book_no] = 'available'\r\n\r\n else:\r\n print(\"You don't have access to this area\")\r\n\r\n\r\nprint('Welcome to \"World of Wisdom\"')\r\nuser_status = input('Do you have your membership card?(yes/no)')\r\n\r\nchoice = '0'\r\n\r\nif user_status == 'yes':\r\n mem_id = input('Enter your member id:')\r\n mem_name = input('Enter your name:')\r\n if mem_id in members:\r\n if mem_name == members[mem_id]:\r\n print('Welcome ' + mem_name)\r\n session_id = mem_id\r\n session_name = mem_name\r\n else:\r\n print('Wrong Username')\r\n choice = '4'\r\n else:\r\n print('Wrong ID or username')\r\n choice = '4'\r\n\r\n\r\nelif user_status == 'no':\r\n print('We need some details to issue you a membership card.')\r\n name = input('Tell me your name:')\r\n Id = str(id_issue())\r\n members[Id] = name\r\n members_record[Id] = 'settled'\r\n print('Your card is issued with ' + name + ' as your name and ' + Id + ' as your Id.')\r\n session_name = name\r\n session_id = Id\r\n\r\nelse:\r\n print('Wrong Input')\r\n choice = '4'\r\n\r\nwhile choice != '4':\r\n print('So, what do you want to do now?')\r\n print('Press \"1\" to BORROW a book')\r\n print('Press \"2\" to RETURN a book')\r\n print('Press \"3\" to ENTER a new book')\r\n print('Press \"4\" to LEAVE the \"World of Wisdom\"')\r\n choice = input()\r\n if choice == '1':\r\n to_borrow_a_book()\r\n elif choice == '2':\r\n to_return_a_book()\r\n elif choice == '3':\r\n to_entry_a_new_book()\r\n elif choice == '4':\r\n print('Goodbye, ' + session_name)\r\n else:\r\n print('WRONG INPUT. Try again!')\r\n" } ]
4
Autumn-Chrysanthemum/Gabiste
https://github.com/Autumn-Chrysanthemum/Gabiste
88d572625fe2f6d068b55e058a23a9b7a309b697
65545fbcbfcd4553e2030db0be6462d33a9ead4d
67003b097450341c07fa2ff0530493a1f96ff7c1
refs/heads/master
2022-12-09T04:37:46.478798
2018-07-23T00:45:54
2018-07-23T00:45:54
75,902,997
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3964497148990631, "alphanum_fraction": 0.6627218723297119, "avg_line_length": 13.166666984558105, "blob_id": "f0d033e7428fd7574db90b8c35c6d413d164780f", "content_id": "6b1668947bc93b25174d902e9645fb433d3c7685", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 169, "license_type": "no_license", "max_line_length": 18, "num_lines": 12, "path": "/requirements.txt", "repo_name": "Autumn-Chrysanthemum/Gabiste", "src_encoding": "UTF-8", "text": "attrs==17.4.0\ncertifi==2018.4.16\nchardet==3.0.4\nidna==2.6\npluggy==0.6.0\npy==1.5.3\npytest==3.5.0\nrequests==2.18.4\nselenium==3.11.0\nsix==1.11.0\nurllib3==1.22\nFaker==0.8.13" }, { "alpha_fraction": 0.7699680328369141, "alphanum_fraction": 0.7827476263046265, "avg_line_length": 25.16666603088379, "blob_id": "f34157e77ca01e3acbe6d63c9f02e5cf4155305c", "content_id": "18111530c62a62a9be321fe11cc72179e0aa675c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 313, "license_type": "no_license", "max_line_length": 103, "num_lines": 12, "path": "/Simple_scripts/implicitWait.py", "repo_name": "Autumn-Chrysanthemum/Gabiste", "src_encoding": "UTF-8", "text": "from selenium import webdriver\n\ndriver = webdriver.Firefox()\n\ndriver.implicitly_wait(15)\n\ndriver.get(\"https://www.google.com\")\n\n# if webdriver coundn't find webelement the test will fail after 15 minutes with NoSuchElementException\nsearchField = driver.find_element_by_css_selector(\"input[name=n]\")\n\ndriver.quit()" }, { "alpha_fraction": 0.6789076924324036, "alphanum_fraction": 0.6845574378967285, "avg_line_length": 29.342857360839844, "blob_id": "1d21e035f8b61a63e15c437817cf29720125a48a", "content_id": "44f25481c281de6b1b8b77fa7bd837409cef5fc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1062, "license_type": "no_license", "max_line_length": 125, "num_lines": 35, "path": "/Simple_scripts/switchToFrame.py", "repo_name": "Autumn-Chrysanthemum/Gabiste", "src_encoding": "UTF-8", "text": "import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\n# from selenium.webdriver.common.by import By\nimport time\n\n\nclass SwitchToFrame(unittest.TestCase):\n\n def setUp(self):\n global driver\n driver = webdriver.Firefox()\n driver.get(\"http://www.w3schools.com/js/tryit.asp?filename=tryjs_confirm\")\n driver.maximize_window()\n\n\n def test_switchToFrame(self):\n # Locators\n iFrameID = \"iframeResult\"\n tryItButtonLocator = \"//button[.='Try it']\"\n\n iFrameElement = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_id(iFrameID))\n # need to switch focus to iFrame before clicking on button inside of iFrame\n driver.switch_to.frame(iFrameElement)\n\n tryItButtonElement = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath(tryItButtonLocator))\n tryItButtonElement.click()\n\n # time.sleep(1)\n\n def tearDown(self):\n driver.quit()\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.6832740306854248, "alphanum_fraction": 0.6868327260017395, "avg_line_length": 32.4523811340332, "blob_id": "e088664afb3d9c94621d3157d0552dc36ba21dcc", "content_id": "8d23489caa6a93e27f24a62f4f34b352ed883025", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1405, "license_type": "no_license", "max_line_length": 123, "num_lines": 42, "path": "/Simple_scripts/clickSubmenu.py", "repo_name": "Autumn-Chrysanthemum/Gabiste", "src_encoding": "UTF-8", "text": "import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.action_chains import ActionChains\n\n\nclass ClickSubmenu(unittest.TestCase):\n\n def setUp(self):\n global driver\n driver= webdriver.Firefox()\n driver.get(\"http://travelingtony.weebly.com/\")\n\n # TODO: FIND RIGHT LOCATOR. WE HAVE DINAMIC MENU HERE:\n # driver.get(\"https://travelingtony.weebly.com/store/p1/Leatherback_Turtle_Picture.html\")\n\n driver.maximize_window()\n\n\n def test_clickSubmenu(self):\n # Locators\n africaMenuLocator = \"//a[.='Africa']\"\n gabonSubmenuLocator = \"//a[contains(@href, 'gabon')]\"\n impalaDivLocator = \"//div[@class='wsite-header']\"\n africaMenuElement = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath(africaMenuLocator))\n\n actions = ActionChains(driver)\n actions.move_to_element(africaMenuElement)\n actions.click(driver.find_element_by_xpath(gabonSubmenuLocator))\n actions.perform()\n\n WebDriverWait(driver, 10). \\\n until(lambda driver: driver.find_element_by_xpath(impalaDivLocator))\n\n def tearDown(self):\n driver.quit()\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.6603235006332397, "alphanum_fraction": 0.6631779074668884, "avg_line_length": 24.634145736694336, "blob_id": "8872a65d218c25ef6823f3327efe3d72e35b3004", "content_id": "af77b19c3690e8c1880bc9f2c7f0edbab800a0ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1051, "license_type": "no_license", "max_line_length": 125, "num_lines": 41, "path": "/Simple_scripts/switchToAlert.py", "repo_name": "Autumn-Chrysanthemum/Gabiste", "src_encoding": "UTF-8", "text": "import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\n# from selenium.webdriver.common.by import By\n# from selenium.webdriver.support.select import Select\n# import time\n\n\nclass SwitchToAlert(unittest.TestCase):\n\n def setUp(self):\n global driver\n driver = webdriver.Firefox()\n driver.get(\"http://www.tizag.com/javascriptT/javascriptconfirm.php\")\n driver.maximize_window()\n\n def test_switchToAlert(self):\n\n # Locators\n leaveButtonLocator = \"//input[@value='Leave Tizag.com']\"\n\n leaveButtonElement = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath(leaveButtonLocator))\n leaveButtonElement.click()\n\n # alert will be displayed and we need to switch to alert\n alert = driver.switch_to.alert\n\n # to accept\n alert.accept()\n\n # to dismiss\n # alert.dismiss()\n\n # time.sleep(5)\n\n def tearDown(self):\n driver.quit()\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.6882160305976868, "alphanum_fraction": 0.6914893388748169, "avg_line_length": 28.095237731933594, "blob_id": "b0c44b2245b0ae954c89a33e9a281319dc743090", "content_id": "23affc95d76fa00502140d4e9669c299acb965c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1222, "license_type": "no_license", "max_line_length": 122, "num_lines": 42, "path": "/Simple_scripts/selectOption.py", "repo_name": "Autumn-Chrysanthemum/Gabiste", "src_encoding": "UTF-8", "text": "from selenium import webdriver\n\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nfrom selenium.webdriver.common.by import By\n\nfrom selenium.webdriver.common.action_chains import ActionChains\n\nfrom selenium.webdriver.common.keys import Keys\n\nimport unittest\n\nimport time\n\n\nclass selectOption(unittest.TestCase):\n\n def setUp(self):\n global driver\n driver = webdriver.Chrome()\n driver.get(\"http://travelingtony.weebly.com/store/p1/Leatherback_Turtle_Picture.html\")\n driver.maximize_window()\n\n def test_selectOption(self):\n # Locators\n dropDownID = \"wsite-com-product-option-Quantity\"\n dropDownElement = WebDriverWait(driver, 10). \\\n until(lambda driver: driver.find_element_by_id(dropDownID))\n\n actions = ActionChains(driver)\n actions.send_keys_to_element(dropDownElement, Keys.ENTER)\n actions.send_keys(Keys.ARROW_DOWN)\n actions.send_keys(Keys.ARROW_DOWN)\n actions.perform()\n # Just using time.sleep() so that you can see the last webdriver action. I do not recommend using it in your tests\n time.sleep(5)\n\n def tearDown(self):\n driver.quit()\n\nif __name__ == \"__main__\":\n unittest.main()\n" }, { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.776068389415741, "avg_line_length": 35.4375, "blob_id": "e84f1b2e0afb910a9dfddf44b4d920606148e7e1", "content_id": "d961c97ed16cb9c09e9b931b074ec49f84618681", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 585, "license_type": "no_license", "max_line_length": 146, "num_lines": 16, "path": "/Simple_scripts/explicitWait.py", "repo_name": "Autumn-Chrysanthemum/Gabiste", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n\ndriver = webdriver.Firefox()\n\ndriver.get(\"https://www.google.com\")\n\nfLocator = \"input[name=q]\"\n\ntry:\n # webdriver will wait for max 10 sec, if element during this time present on the page - will return element. Otherwise TimeoutException thrown\n searchField = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, fLocator)))\nfinally:\n driver.quit()\n\n\n" }, { "alpha_fraction": 0.6788296103477478, "alphanum_fraction": 0.6833046674728394, "avg_line_length": 38.79452133178711, "blob_id": "16db3e8027e65056e9c64a3aa058e17067299686", "content_id": "0a63c3dc320141bfe705ee39d565a3eaa758d644", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2905, "license_type": "no_license", "max_line_length": 114, "num_lines": 73, "path": "/Simple_scripts/switchToWindow.py", "repo_name": "Autumn-Chrysanthemum/Gabiste", "src_encoding": "UTF-8", "text": "import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.select import Select\n\n\nclass SwitchToWindow(unittest.TestCase):\n\n\n def setUp(self):\n global driver\n driver = webdriver.Firefox()\n driver.get(\"http://travelingtony.weebly.com/store/p3/Asala_Loadge.html\")\n driver.maximize_window()\n\n def test_switchToFacebookWindow(self):\n\n # Locators\n facebookSharingLinkLocator = \"a.wsite-com-product-social-facebook\"\n facebookUsernameFieldID = \"email\"\n facebookPasswordFieldID = \"pass\"\n facebookLoginButtonName = \"login\"\n facebookShareLinkButtonXpath = \"//span[contains(text(), 'Post to Facebook')]\"\n\n # Facebook credentials.\n facebookUsername = \"tutorys123@gmail.com\"\n facebookPassword = \"year2014\"\n\n fbSharingLinkElement = WebDriverWait(driver, 10).\\\n until(lambda driver: driver.find_element_by_css_selector(facebookSharingLinkLocator))\n\n # Get the main Window handle\n # in order to remember main window we will catch it into variable \\\n # before clicking on the button which open a new window. It will be a list of 1 element\n mainWindowHandle = driver.window_handles\n print (\"main Window handle: %s\" %mainWindowHandle)\n\n # Click the \"Facebook sharing\" link, switch to the Facebook login window and log in\n fbSharingLinkElement.click()\n\n # New window will be open now and we need to switch to it. We need to catch all windows in variable\\\n # it will be a list on handles. List is not ordered\n allWindowsHandlesList = driver.window_handles\n print (\"all window handles: %s\" %allWindowsHandlesList)\n # chooshing the new window, by excludidng main window\n for handle in allWindowsHandlesList:\n if handle != mainWindowHandle[0]:\n driver.switch_to.window(handle)\n break\n\n facebookUsernameFieldElement = WebDriverWait(driver, 10). \\\n until(lambda driver: driver.find_element_by_id(facebookUsernameFieldID))\n\n facebookPasswordFieldElement = WebDriverWait(driver, 10). \\\n until(lambda driver: driver.find_element_by_id(facebookPasswordFieldID))\n\n facebookLoginButtonElement = WebDriverWait(driver, 10). \\\n until(lambda driver: driver.find_element_by_name(facebookLoginButtonName))\n\n facebookUsernameFieldElement.send_keys(facebookUsername)\n facebookPasswordFieldElement.send_keys(facebookPassword)\n facebookLoginButtonElement.click()\n\n WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath(facebookShareLinkButtonXpath))\n\n\n def tearDown(self):\n driver.quit()\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.6879505515098572, "alphanum_fraction": 0.6930999159812927, "avg_line_length": 34.907405853271484, "blob_id": "8655cc48b6b1b472af123e4a6402562ca6ff4155", "content_id": "89fa0f00acd8552c645e7ffd4856a0c9ee836bab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1942, "license_type": "no_license", "max_line_length": 90, "num_lines": 54, "path": "/Simple_scripts/selectingProduct.py", "repo_name": "Autumn-Chrysanthemum/Gabiste", "src_encoding": "UTF-8", "text": "from selenium import webdriver\n\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nfrom selenium.webdriver.common.by import By\n\nfrom selenium.webdriver.support.select import Select\n\nimport unittest\n\n\nclass SelectingProduct(unittest.TestCase):\n\n def setUp(self):\n global driver\n driver = webdriver.Firefox()\n driver.get(\"http://travelingtony.weebly.com\")\n driver.maximize_window()\n\n def test_SelectingProduct(self):\n # Locators\n searchFieldLocator = \"q\"\n searchButtonLocator = \"span.wsite-search-button\"\n turtlePictureLocator = \"//span[@title='Leatherback Turtle Picture']\"\n quantityDropDownLocator = \"wsite-com-product-option-Quantity\"\n\n # Finding the search field by name\n searchFieldElement = WebDriverWait(driver, 10). \\\n until(lambda driver: driver.find_element_by_name(searchFieldLocator))\n\n # Entering word \"leatherback\" into the search field and clicking the search button\n searchFieldElement.send_keys(\"leatherback\")\n searchButtonElement = WebDriverWait(driver, 10). \\\n until(lambda driver: driver.find_element_by_css_selector(searchButtonLocator))\n searchButtonElement.click()\n\n # Finding the \"Leatherback Turtle Picture\" product by title using Xpath\n pictureProductElement = WebDriverWait(driver, 10). \\\n until(lambda driver: driver.find_element_by_xpath(turtlePictureLocator))\n\n # Clicking the \"Leatherback Turtle Picture\" product\n pictureProductElement.click()\n\n # Finding the \"Quantity\" drop-down by id and selecting option \"3\"\n quantityDropDownElement = WebDriverWait(driver, 10). \\\n until(lambda driver: driver.find_element_by_id(quantityDropDownLocator))\n Select(quantityDropDownElement).select_by_visible_text(\"3\")\n\n def tearDown(self):\n driver.quit()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n\n\n" }, { "alpha_fraction": 0.6791277527809143, "alphanum_fraction": 0.6843198537826538, "avg_line_length": 30.09677505493164, "blob_id": "46076818ca67a527cefaeb985cff7c9196199163", "content_id": "3d63ca8f328e33ad93fa45e30c88b4b75a342a49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 963, "license_type": "no_license", "max_line_length": 125, "num_lines": 31, "path": "/Simple_scripts/BasicActions.py", "repo_name": "Autumn-Chrysanthemum/Gabiste", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nimport unittest\nimport time\n\nclass BasicActions(unittest.TestCase):\n\n def setUp(self):\n global driver\n driver = webdriver.Firefox()\n driver.get(\"http://travelingtony.weebly.com\")\n driver.maximize_window()\n\n def test_BasicAction(self):\n contactMenuLocator = \"//a[.='Contact']\"\n nameFieldLocator = \"//input[contains(@name, 'first')]\"\n\n contactMenuElement = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath(contactMenuLocator))\n contactMenuElement.click()\n\n nameFieldElement = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath(nameFieldLocator))\n nameFieldElement.send_keys(\"George\")\n # time.sleep(5)\n\n\n def tearDown(self):\n driver.quit()\n\nif __name__== \"__main__\":\n unittest.main()" }, { "alpha_fraction": 0.6778411269187927, "alphanum_fraction": 0.6825343370437622, "avg_line_length": 37.74026107788086, "blob_id": "5af06b8db608af27d0e21e5ad46f3c911eb389c7", "content_id": "fe53999a5d297dba1ab3266485e5816e5b86890c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2983, "license_type": "no_license", "max_line_length": 108, "num_lines": 77, "path": "/Simple_scripts/shareOnTwitter.py", "repo_name": "Autumn-Chrysanthemum/Gabiste", "src_encoding": "UTF-8", "text": "import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.select import Select\nimport time\n\n\nclass SwitchToWindow(unittest.TestCase):\n\n\n def setUp(self):\n global driver\n driver = webdriver.Firefox()\n driver.get(\"http://travelingtony.weebly.com/store/p1/Leatherback_Turtle_Picture.html\")\n driver.maximize_window()\n\n def test_switchToFacebookWindow(self):\n\n # Locators\n twitterSharingLinkLocator = \"a.wsite-com-product-social-twitter\"\n twitterUsernameFieldXPATH = \"//label[@for='username_or_email']\"\n twitterPasswordFieldXPATH = \"//label[@for='password']\"\n twitterSignInButtonCSS = \"input[type=submit]\"\n twitterSubmitButtonID = \"email_challenge_submit\"\n\n # Twitter test account credentials.\n twitterUsername = \"tutorys123@gmail.com\"\n twitterPassword = \"year2014\"\n\n\n twSharingLinkElement = WebDriverWait(driver, 10).\\\n until(lambda driver: driver.find_element_by_css_selector(twitterSharingLinkLocator))\n\n # Get the main Window handle\n # in order to remember main window we will catch it into variable \\\n # before clicking on the button which open a new window. It will be a list of 1 element\n mainWindowHandle = driver.window_handles\n print (\"main Window handle: %s\" %mainWindowHandle)\n\n # Click the \"Facebook sharing\" link, switch to the Facebook login window and log in\n twSharingLinkElement.click()\n\n # New window will be open now and we need to switch to it. We need to catch all windows in variable\\\n # it will be a list on handles. List is not ordered\n allWindowsHandlesList = driver.window_handles\n print (\"all window handles: %s\" %allWindowsHandlesList)\n # chooshing the new window, by excludidng main window\n for handle in allWindowsHandlesList:\n if handle != mainWindowHandle[0]:\n driver.switch_to.window(handle)\n break\n\n twitterUsernameFieldElement = WebDriverWait(driver, 10). \\\n until(lambda driver: driver.find_element_by_xpath(twitterUsernameFieldXPATH))\n\n twitterPasswordFieldElement = WebDriverWait(driver, 10). \\\n until(lambda driver: driver.find_element_by_xpath(twitterPasswordFieldXPATH))\n\n twitterLoginButtonElement = WebDriverWait(driver, 10). \\\n until(lambda driver: driver.find_element_by_css_selector(twitterSignInButtonCSS))\n\n time.sleep(5)\n\n twitterUsernameFieldElement.send_keys(twitterUsername)\n twitterPasswordFieldElement.send_keys(twitterPassword)\n twitterLoginButtonElement.click()\n\n WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_id(twitterSubmitButtonID))\n\n\n def tearDown(self):\n driver.quit()\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.7032967209815979, "alphanum_fraction": 0.7064363956451416, "avg_line_length": 25.54166603088379, "blob_id": "397258a645936b82c8f79cb3ed95f9f2542331bc", "content_id": "284607cb328fd527f00bb4a72d08b16e06668edb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 637, "license_type": "no_license", "max_line_length": 80, "num_lines": 24, "path": "/Simple_scripts/assertTitle.py", "repo_name": "Autumn-Chrysanthemum/Gabiste", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nimport unittest\n\n\nclass WaitForElements(unittest.TestCase):\n\n def setUp(self):\n global driver\n driver = webdriver.Firefox()\n driver.implicitly_wait(10)\n driver.get(\"https://travelingtony.weebly.com\")\n\n def test_AssertTitle(self):\n self.assertEqual(driver.title, \"Traveling Tony's Photography - Welcome\")\n\n def tearDown(self):\n driver.quit()\n\n\nif __name__ == '__main__':\n unittest.main()\n" } ]
12
ParthJai/trashnet
https://github.com/ParthJai/trashnet
4e847aa8f1c1ec736c162e98d0e23216b9caa7e7
87ed98a3d9086a061131a9569be3f60a6693c89f
167a72ea4b7d786fd84f835b98ea79db64a441b8
refs/heads/master
2022-11-06T16:24:14.828519
2020-06-27T14:49:45
2020-06-27T14:49:45
274,288,392
0
0
MIT
2020-06-23T02:20:53
2020-06-21T16:59:59
2017-04-10T00:54:13
null
[ { "alpha_fraction": 0.5352839827537537, "alphanum_fraction": 0.5438898205757141, "avg_line_length": 24.173913955688477, "blob_id": "31b19c6ff393572facb1fbae7ed944f52681a866", "content_id": "d3d5256939046932b637356535f86b683706f9f1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1162, "license_type": "permissive", "max_line_length": 89, "num_lines": 46, "path": "/data-split.py", "repo_name": "ParthJai/trashnet", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\n\n\n\nimport random,os,shutil\ntrain = 0.7\nvalid = 0.13\ntest = 0.17\npath = \"/notebooks/storage/dataset-resized\"\ntrain_dir = path + '/train'\nvalid_dir = path + '/valid'\nclasses = os.listdir(path + '/dataset-resized/')\ndef create_dir():\n for c in classes:\n os.makedirs(train_dir + '/' + c)\n os.makedirs(valid_dir + '/' + c)\n\ndef move_files():\n for c in classes:\n src = path + '/dataset-resized' + '/' + c #os.path.join(path,'dataset-resized',c)\n filenames = os.listdir(src)\n count = len(filenames)\n num_train_files = int(train * count)\n num_valid_files = int(valid * count)\n for _ in range(num_train_files):\n new_src = os.listdir(src)\t\n choice = random.choice(new_src)\n dest = train_dir +'/'+ c\n print(dest)\n shutil.move(src + '/' + choice, dest)\n for _ in range(num_valid_files):\n new_src = os.listdir(src)\n choice = random.choice(new_src)\n dest = valid_dir + '/' + c\n shutil.move(src + '/' + choice, dest)\n\ncreate_dir()\nmove_files()\n\n\n# In[ ]:\n\n\n\n\n" }, { "alpha_fraction": 0.7471153736114502, "alphanum_fraction": 0.7831730842590332, "avg_line_length": 89.43478393554688, "blob_id": "c65c48d4fc92ecb46258b9be0a3f69d451abe40b", "content_id": "13fbd1b55bcf6a4085eee7cceef5b55e11c271e2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2080, "license_type": "permissive", "max_line_length": 502, "num_lines": 23, "path": "/README.md", "repo_name": "ParthJai/trashnet", "src_encoding": "UTF-8", "text": "# trashnet\nThis is the fastai implementation of [Gary Thung](https://github.com/garythung)'s and [Mindy Yang](http://github.com/yangmindy4)'s final project for [Stanford's CS 229: Machine Learning class](http://cs229.stanford.edu). Original paper is availabe [here](http://cs229.stanford.edu/proj2016/poster/ThungYang-ClassificationOfTrashForRecyclabilityStatus-poster.pdf). The dataset is obtained from the original repo. [Link](https://github.com/garythung/trashnet/blob/master/data/dataset-resized.zip) to the dataset.\n\n## Dataset\n(Dataset description copied \"as it is\" from original repo)\n\nThis repository contains the dataset that we collected. The dataset spans six classes: glass, paper, cardboard, plastic, metal, and trash. Currently, the dataset consists of 2527 images:\n- 501 glass\n- 594 paper\n- 403 cardboard\n- 482 plastic\n- 410 metal\n- 137 trash\n\nThe pictures were taken by placing the object on a white posterboard and using sunlight and/or room lighting. The pictures have been resized down to 512 x 384, which can be changed in `data/constants.py` (resizing them involves going through step 1 in usage). The devices used were Apple iPhone 7 Plus, Apple iPhone 5S, and Apple iPhone SE.\n\nThe size of the original dataset, ~3.5GB, exceeds the git-lfs maximum size so it has been uploaded to Google Drive. If you are planning on using the Python code to preprocess the original dataset, then download `dataset-original.zip` from the link below and place the unzipped folder inside of the `data` folder.\n\n**If you are using the dataset, please give a citation of this repository. The dataset can be downloaded [here](http://drive.google.com/drive/folders/0B3P9oO5A3RvSUW9qTG11Ul83TEE).**\n\n### Model description\nPretrained resnet 50 is trained with the help of fastai library. Model was able to achieve the accuracy of 91.034%(previously 88.5%) with 70/13/17 train/val/test split (as done by original author).\nIn this approach we first train only a couple of layers of resnet 50 while keeping rest of the weights as it is. Then we unfreeze the whole model and train all layers.\n" } ]
2
otobin/CSSI-stuff
https://github.com/otobin/CSSI-stuff
e70cc08a422211a200270f30ae509ccd30015293
e7c6b1aa9934cc751b24eb5b9c7182c8e222d4b4
749289cfb0e97720b07e7e340f8af79db0b23361
refs/heads/master
2020-03-25T06:01:52.330250
2018-08-03T22:56:25
2018-08-03T22:56:25
143,479,787
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.64462810754776, "alphanum_fraction": 0.6511216163635254, "avg_line_length": 26.770492553710938, "blob_id": "0e6a6afeb693fd989407f5221c8dbdb712f5be76", "content_id": "3438175f37e68401d294cc9d87e463d8ddc53ce5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1694, "license_type": "no_license", "max_line_length": 113, "num_lines": 61, "path": "/HTML/hello.html", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "<!DOCTYPE html> <!-- changes the margins and layout to doc -->\n<title>Hello CSSI</title>\n\n<style>\n\nbody{\n background-color: turquoise;\n}\n\n/*This is a comment in CSS */\n.read {\n color: darkgrey;\n text-decoration: line-through;\n}\n\n#welcome{\n color: white;\n font-family: \"Arial\";\n font-weight: lighter;\n font-size: 32px;\n font-style: italic;\n text-decoration: underline\n}\n</style>\n\n\n<h1 id=\"welcome\">Welcome to CSSI</h1> <!-- h is heading -->\n<h1>This is a subtitle</h1>\n<header>Here is another title</header>\n<h6>This is a sub sub sub header</h6> <!-- final h. Smaller font size -->\n\n<a href=\"goodbye.html\"> Goodbye, World</a>\n<div>this is a div</div>\n<div>this is another div</div> <!-- divs create new blocks. -->\n\n<span>This is the start</span> <!-- spans are together -->\n<span>This is the end</span>\n\n<ol> <!-- ordered list. List items are numbered -->\n <li class=\"read\">The Sorcerer's Stone</li> <!-- indentation does not matter with HTML -->\n <li class=\"read\">The Chamber of Secrets</li> <!-- li stands for list item -->\n <li class=\"read\">The Prisoner of Azkaban</li>\n <li>The Goblet of Fire</li>\n</ol>\n\n<ul> <!-- unordered list. List items are bullet points. -->\n <li>USA</li>\n <li>France</li>\n <li>Croatia</li>\n</ul>\n\n\n<p>Hello, world!</p> <!-- p is paragraph -->\n<p>Goodbye, world!</p>\n\n<div id=\"example\">This is an example</div>\n<!-- attributes should always be in quotation marks-->\n<img src=\"monalisa.jpg\" width = \"250\" alt=\"An image of Mona Lisa\"> <!-- image element does not have a closing tag-->\n<!-- download image and then use file name, do not reference image directly -->\n\n<p>CSSI is a program at <a target=\"_blank\" href=\"https://www.google.com/\">Google</a>.</p>\n" }, { "alpha_fraction": 0.5473984479904175, "alphanum_fraction": 0.5609408617019653, "avg_line_length": 24.981481552124023, "blob_id": "9846b1a24c40d2da5e5737d15c2a92725560e7c0", "content_id": "055680e24b6a543c1ecff6e5c0522391d027cedc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2806, "license_type": "no_license", "max_line_length": 114, "num_lines": 108, "path": "/Python/Playground.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "# #!/usr/bin/python\n#\n#\n# # # # print(\"Hello, World!\")\n# # # #\n# # # #\n# # # #\n# # # # i = 0\n# # # #\n# # # # while (i < 3):\n# # # # num = int(input(\"Enter a number\"))\n# # # #\n# # # # if num > 0:\n# # # # print(\"This number is positive\")\n# # # # elif num < 0:\n# # # # print(\"This number is negative\")\n# # # # else:\n# # # # print(\"This number is 0\")\n# # # # i += 1\n# # #\n# # # greeting = \"Hello, World!\"\n# # # for letter in greeting:\n# # # print(letter.upper())\n# # #\n# # #\n# # # for i in range(10, 5, -1):\n# # # print(i)\n# # #\n# # #\n# # # my_name = \"Olivia\"\n# # # friend1 = \"Jess\"\n# # # friend2 = \"Julia\"\n# # # friend3 = \"Ciera\"\n# # # friend4 = \"Matthew\"\n# # #\n# # # print(\"My name is \" + my_name + \" and my friends are \" + friend1 + \" , \")\n# # # print(\"My name is %s and my friends are %s, %s, %s, and %s.\" %(my_name, friend1, friend2, friend3, friend4))\n# # name = str(raw_input(\"Enter your name\"))\n# # adverb = str(raw_input(\"Enter an adverb\"))\n# # plural_noun = str(raw_input(\"Enter a plural noun\"))\n# # noun = str(raw_input(\"Enter another noun\"))\n# # noun2 = str(raw_input(\"Enter another noun\"))\n# # animal = str(raw_input(\"Enter an animal\"))\n#\n#\n#\n# # print((\"One day %s woke up and realized that they had slept through their alarm. %s sprinted to \"\n# # \"the bus stop %s, dragging their %s behind them while shouting at the bus driver to stop. %s leaped over \"\n# # \" a %s and almost bumped into a %s, desperate to not be late to school.\"\n# # \" Alas, the bus driver drove away, leaving %s to ride their %s to school.\")\n# # %(name, name, adverb, plural_noun, name, noun, noun2, name, animal))\n#\n# def greetSecretAgent(first_name, last_name):\n# return (\"%s, %s %s\") %(last_name, first_name, last_name)\n#\n# greeting = greetSecretAgent(\"Olivia\", \"Tobin\")\n# print(greeting)\n\n# def mystery1(a):\n# return a + 5\n#\n# def mystery2(b):\n# return b * 2\n#\n# result = mystery1(mystery2(3))\n#\n#\n# def mystery(word, number):\n# number = number * 2\n# word = word.upper()\n# return word * number #you can't multiply two strings\n#\n# print(mystery(\"2\", \"he\"))\n\n\nfriends = [\"Olivia\", \"Jackelen\",\n \"Phoebe\", \"Savion\"]\nmyName = \"olivia\"\nprint(\"My name is %s and I have %s friends\" %(myName, len(friends)))\nfriends.append(\"Areeta\")\nfriends.insert(1, \"Logan\")\nfriends.remove(\"Areeta\")\n\nprint(\"My friends are: \")\nfor i in range(0,len(friends)):\n if (i == 0):\n print(friends[0]),\n else:\n print(\"and \" + friends[i])\n\nprint(range(4))\n\n\n\n\nfor friend in friends:\n print(friend)\n\n\n# for i in range(0, len(friends)):\n# print(friends[i])\n#\n#\n# tableGroups = [[\"Olivia\", \"Savion\"], [\"Jackelen\", \"Phoebe\"]]\n#\n# for i in range(0, len(tableGroups)):\n# for j in range(0, len(tableGroups[i])):\n# print(tableGroups[i][j])\n" }, { "alpha_fraction": 0.6297968626022339, "alphanum_fraction": 0.6388261914253235, "avg_line_length": 29.204545974731445, "blob_id": "92920461056b92b008fdddbf01359d0bc87adde1", "content_id": "99c4c3e3308b999dd33074c55975535fa5edf47f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1329, "license_type": "no_license", "max_line_length": 81, "num_lines": 44, "path": "/facebook/main.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "import webapp2\nimport jinja2 # import library defined in app.yaml\nimport os\n\nfrom google.appengine.ext import ndb #new data base\n\n#set up jinja environment\nenv = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True)\n\n\nclass Post(ndb.Model):\n name = ndb.StringProperty()\n message = ndb.StringProperty()\n created_time = ndb.DateTimeProperty(auto_now_add = True)\n\nclass MainPage(webapp2.RequestHandler):\n def get(self):\n #2.) REad from or write to the database\n post_query = Post.query()\n post_query= post_query.order(-Post.created_time) #didn't specify an order\n posts = post_query.fetch()\n templateVars = {\n \"posts\": posts\n }\n #3.) Render a response\n template = env.get_template(\"/templates/home.html\")\n self.response.write(template.render(templateVars))\n def post(self):\n #1.) Get info from the user request\n name = self.request.get(\"name\")\n message = self.request.get(\"message\")\n #2.) Read from or write to the database\n post = Post(name =name, message =message)\n #3.) render a response\n post.put()\n self.redirect(\"/\")\n\n\napp = webapp2.WSGIApplication([\n (\"/\", MainPage),\n], debug = True)\n" }, { "alpha_fraction": 0.5862573385238647, "alphanum_fraction": 0.5950292348861694, "avg_line_length": 37.71697998046875, "blob_id": "f6a0c8fbaff8a12140aa8dae68b725cdd85a7713", "content_id": "563c4a47c0e7211e1c3764b06df7f07a798ba830", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2052, "license_type": "no_license", "max_line_length": 201, "num_lines": 53, "path": "/language-api-tester/main.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "import json\nimport argparse\nimport webapp2\nimport urllib\nfrom google.appengine.api import urlfetch\nimport jinja2\nimport os\nimport logging\n\nAPI_KEY = \"AIzaSyD7TnZoyTqVVjD3_Uy1uB7MLE0j9na6T8o\"\nurl = \"https://language.googleapis.com/v1beta2/documents:analyzeSentiment?key=\" + API_KEY\n\n\n\nenv = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True)\n\n#print(result[\"categories\"])\n\nclass MainPage(webapp2.RequestHandler):\n def get(self):\n def getSentiment(url): #url is unique to sentiment function in api\n data = {\n \"document\": {\n \"type\": \"PLAIN_TEXT\",\n \"language\": \"EN\",\n \"content\": \"Google, headquartered in Mountain View, unveiled the new Android phone at the Consumer Electronic Show. Sundar Pichai said in his keynote that users love their new Android phones.\"\n },\n \"encodingType\": \"UTF32\",\n }\n headers = {\n \"Content-Type\" : \"application/json; charset=utf-8\"\n }\n jsondata = json.dumps(data)\n result = urlfetch.fetch(url, method=urlfetch.POST, payload=data,headers=headers)\n python_result = json.loads(result.content)\n string = \"\"\n magnitude = python_result[\"documentSentiment\"][\"magnitude\"]\n score = python_result[\"documentSentiment\"][\"score\"]\n if (score < 0.0):\n string = \"Your resume has a \" + str(score) + \" score and a \" + str(magnitude) + \" magnitude. This reads as negative\"\n elif (score > 0.0 and score < .5):\n string = \"Your resume has a \" + str(score) + \" score and a \" + str(magnitude) + \" magnitude. This reads as neutral\"\n elif (score > .5):\n string = \"Your resume has a \" + str(score) + \" score and a \" + str(magnitude) + \" magnitude. This reads as positive\"\n return string\n print(getSentiment(url))\n\napp = webapp2.WSGIApplication([\n ('/', MainPage),\n], debug=True)\n" }, { "alpha_fraction": 0.5721254348754883, "alphanum_fraction": 0.5811846852302551, "avg_line_length": 20.74242401123047, "blob_id": "ed01baf3b2641cceb9d435b78a230ceb3f6321b2", "content_id": "cda167241597d7db8fb7dd664c569feb6129ad31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1435, "license_type": "no_license", "max_line_length": 84, "num_lines": 66, "path": "/Python/crawler.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "#!/usr/bin/Python\nimport urllib2\nimport time\n\n\nprint(\"Hello, World\")\nurl = \"http://www.example.com\"\n\n\ndef fetch(url):\n response = urllib2.urlopen(url)\n html = response.read()\n return html\n\n\ndef get_anchors(html):\n\n a_start = 0\n a_end = -5\n anchors = []\n while True:\n a_start = html.find(\"<a \", a_end + 5)\n if a_start == -1:\n break\n a_end = html.find(\"</a>\", a_start+3)\n if a_end == -1:\n break\n anchor = html[a_start: a_end + 4]\n anchors.append(anchor)\n return anchors\n\ndef get_url(anchor):\n href_start = anchor.find('href=\"')\n href_end = anchor.find('\"', href_start+6)\n url = anchor[href_start + 6: href_end]\n print url\n return url\n\n\n\ndef get_links(html):\n links = []\n #extract get_links\n anchors = get_anchors(html)\n for anchor in anchors:\n url = get_url(anchor)\n links.append(url)\n return links\n\nurls_visited = []\nurls_to_visit = []\nurls_to_visit.append(\"http://matthewlevine.com/\")\n\nwhile len(urls_to_visit)>0:\n time.sleep(1)\n url = urls_to_visit.pop()\n print(\"Visiting \" + url)\n if (url in urls_visited):\n continue #continue exits the iteration and goes back to the top of the loop\n urls_visited.append(url)\n html = fetch(url)\n links = get_links(html)\n print (\"Got %s links.\" %(len(links)))\n for link in links:\n urls_to_visit.append(link)\n #print(html)\n" }, { "alpha_fraction": 0.6159999966621399, "alphanum_fraction": 0.6197894811630249, "avg_line_length": 29.44871711730957, "blob_id": "d8398598b9a16daa9926d264296c2872d1a5812e", "content_id": "7fcd5e122d1fedb6b7ff5a03e1bc34c6919be702", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2375, "license_type": "no_license", "max_line_length": 87, "num_lines": 78, "path": "/Google-/main.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "import webapp2\nimport jinja2 # import library defined in app.yaml\nimport os\nimport time\nimport logging\nfrom google.appengine.api import users #new data base--application interface\nfrom google.appengine.ext import ndb\n\n\n\n\n\n\n#set up jinja environment\nenv = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True)\n\nclass Person(ndb.Model):\n name = ndb.StringProperty()\n biography = ndb.StringProperty()\n birthday = ndb.DateProperty()\n email = ndb.StringProperty()\n\nclass MainPage(webapp2.RequestHandler):\n def get(self):\n current_user = users.get_current_user()\n if current_user:\n current_email = current_user.email()\n current_person = Person.query().filter(Person.email == current_email).get()\n else:\n current_person = None\n logout_url = users.create_logout_url(\"/\")\n login_url = users.create_login_url(\"/\")\n #Read the request\n\n #Read and write from the database\n people = Person.query().fetch()\n templateVars = {\n \"people\": people,\n \"current_user\": current_user,\n \"login_url\": login_url,\n \"logout_url\": logout_url,\n \"current_person\": current_person,\n }\n template = env.get_template(\"/templates/home.html\")\n self.response.write(template.render(templateVars))\n def post(self):\n name = self.request.get(\"name\")\n biography = self.request.get(\"bio\")\n current_user = users.get_current_user()\n email = current_user.email()\n person = Person(name = name, biography = biography, email = email)\n person.put()\n time.sleep(2)\n self.redirect(\"/\")\nclass Profile(webapp2.RequestHandler):\n def get(self):\n #Get information from the database\n urlsafe_key = self.request.get(\"key\")\n logging.info(urlsafe_key)\n #Read or write from the database\n key = ndb.Key(urlsafe = urlsafe_key)\n person = key.get()\n templateVars = {\n \"person\": person\n }\n #Render a response\n template = env.get_template(\"/templates/profile.html\")\n self.response.write(template.render(templateVars))\n\n\n\napp = webapp2.WSGIApplication([\n (\"/\", MainPage),\n (\"/profile\", Profile),\n], debug = True)\n" }, { "alpha_fraction": 0.7385621070861816, "alphanum_fraction": 0.7559912800788879, "avg_line_length": 35.68000030517578, "blob_id": "b1e57bd10f4c814c42ce59317baf5930259f9cf0", "content_id": "c8ed6735f7678000ade21a4e11661a1db8a8638c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 918, "license_type": "no_license", "max_line_length": 247, "num_lines": 25, "path": "/Google-/apitest.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "\nimport json\nimport requests\nAPI_KEY = \"AIzaSyA7Uo226eyoZjz2H2gQh2eY-pgR5PzbES8\"\n\n\ndata = {\n \"key\": \"AIzaSyA7Uo226eyoZjz2H2gQh2eY-pgR5PzbES8\",\n \"input\": \"California Academy of Sciences\",\n \"inputtype\": \"textquery\"\n}\n\n# #r = requests.post(url = \"https://maps.googleapis.com/maps/api/place/findplacefromtext/output?parameters\", data = data)\n# r = url.fetch(\"https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=Museum%20of%20Contemporary%20Art%20Australia&inputtype=textquery&fields=photos,formatted_address,name,rating,opening_hours,geometry&key=AIzaSyA7Uo226eyoZjz2H2gQh2eY-pgR5PzbES8\")\n#\n#\n# print(response)\n# content = response.content\n#\n# json_result = json.loads(response.content)\n# print(json_result)\n\nresponse = requests.post(url = \"https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=Museum%20of%20Contemporary%20Art%20Australia&inputtype=textquery&fields=photos,formatted_address,name,rating,opening_hours,geometry&key=AIzaSyA7Uo226eyoZjz2H2gQh2eY-pgR5PzbES8\")\n\nprint(response)\nprint(response.text)\n" }, { "alpha_fraction": 0.6528985500335693, "alphanum_fraction": 0.658695638179779, "avg_line_length": 29.66666603088379, "blob_id": "3978db8c79a8e8d57165558347642bd3bd8da356", "content_id": "96ee9778a8129dd50358bbdb896f6e373ae93f89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1380, "license_type": "no_license", "max_line_length": 83, "num_lines": 45, "path": "/quilty/main.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "import webapp2\nimport jinja2 # import library defined in app.yaml\nimport os\n\nfrom google.appengine.ext import ndb #new data base\n\nclass Patch(ndb.Model):\n inner_color = ndb.StringProperty()\n outer_color = ndb.StringProperty()\n created_time = ndb.DateTimeProperty(auto_now_add = True)\n\n#set up jinja environment\nenv = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True)\n\nclass MainPage(webapp2.RequestHandler):\n def get(self):\n patch_query = Patch.query()\n patch_query= patch_query.order(Patch.created_time) #didn't specify an order\n patches = patch_query.fetch()\n templateVars = {\n \"patches\": patches,\n\n }\n template = env.get_template(\"/templates/quilt.html\")\n self.response.write(template.render(templateVars))\n\n\nclass Add(webapp2.RequestHandler):\n def get(self):\n template = env.get_template(\"/templates/add.html\")\n self.response.write(template.render())\n def post(self):\n inner_color = self.request.get(\"inner_color\")\n outer_color = self.request.get(\"outer_color\")\n patch = Patch(inner_color = inner_color, outer_color = outer_color)\n patch.put()\n self.redirect(\"/\")\n\napp = webapp2.WSGIApplication([\n (\"/\", MainPage),\n (\"/add\", Add)\n], debug = True)\n" }, { "alpha_fraction": 0.7239263653755188, "alphanum_fraction": 0.7300613522529602, "avg_line_length": 30.69444465637207, "blob_id": "824c08a0ecfca62c53338594765157af75c27084", "content_id": "234c2132f072ae802d57810e85d5e4b8892e77ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1141, "license_type": "no_license", "max_line_length": 193, "num_lines": 36, "path": "/cssi-test-api/main2.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "import webapp2\nimport jinja2 # import library defined in app.yaml\nimport os\nimport time\nimport logging\nfrom google.appengine.api import users #new data base--application interface\nfrom google.appengine.ext import ndb\nfrom google.appengine.api import urlfetch\nimport json\n\nAPI_KEY = \"AIzaSyA7Uo226eyoZjz2H2gQh2eY-pgR5PzbES8\"\nplace_name = \"Exploratorium\"\nurl = \"https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=%s&inputtype=textquery&fields=photos,formatted_address,name,rating,opening_hours,geometry&key=AIzaSyA7Uo226eyoZjz2H2gQh2eY-pgR5PzbES8\" %(place_name)\n\n\n#set up jinja environment\nenv = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True)\n\n# class Person(ndb.Model):\n# name = ndb.StringProperty()\n# biography = ndb.StringProperty()\n# birthday = ndb.DateProperty()\n# email = ndb.StringProperty()\n\nclass MainPage(webapp2.RequestHandler):\n def get(self):\n response = urlfetch.fetch(url)\n json_result = json.loads(response.content)\n self.response.write(json_result[\"candidates\"])\n\napp = webapp2.WSGIApplication([\n (\"/\", MainPage),\n], debug = True)\n" }, { "alpha_fraction": 0.7689594626426697, "alphanum_fraction": 0.790123462677002, "avg_line_length": 44.36000061035156, "blob_id": "4585afe609d8badc334a4496e78d8c73ca0d5efa", "content_id": "13a9d773f4ab7eabd6041f3f00b5b6d26eea3725", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1134, "license_type": "no_license", "max_line_length": 247, "num_lines": 25, "path": "/cssi-test-api/apitest.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "import json\nimport requests\nAPI_KEY = \"AIzaSyA7Uo226eyoZjz2H2gQh2eY-pgR5PzbES8\"\nurl = \"https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=Museum%20of%20Contemporary%20Art%20Australia&inputtype=textquery&fields=photos,formatted_address,name,rating,opening_hours,geometry&key=%s\" %(API_KEY)\n\n\nresponse = urlfetch.fetch(url)\njson_result = json.loads(response.content)\nprint(json_result)\n\n\n# #r = requests.post(url = \"https://maps.googleapis.com/maps/api/place/findplacefromtext/output?parameters\", data = data)\n# r = url.fetch(\"https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=Museum%20of%20Contemporary%20Art%20Australia&inputtype=textquery&fields=photos,formatted_address,name,rating,opening_hours,geometry&key=AIzaSyA7Uo226eyoZjz2H2gQh2eY-pgR5PzbES8\")\n#\n#\n# print(response)\n# content = response.content\n#\n# json_result = json.loads(response.content)\n# print(json_result)\n\nresponse = requests.post(url = \"https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=Museum%20of%20Contemporary%20Art%20Australia&inputtype=textquery&fields=photos,formatted_address,name,rating,opening_hours,geometry&key=AIzaSyA7Uo226eyoZjz2H2gQh2eY-pgR5PzbES8\")\n\nprint(response)\nprint(response.text)\n" }, { "alpha_fraction": 0.6286799907684326, "alphanum_fraction": 0.6372269988059998, "avg_line_length": 30.909090042114258, "blob_id": "feb1a1bed8ef5cb2e9ac0851b92a35d63c60f1cf", "content_id": "eae121cd335a58bc3af291ef6f47e6b756b3cfda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1053, "license_type": "no_license", "max_line_length": 89, "num_lines": 33, "path": "/fillit/main.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "import jinja2\nimport os\nimport webapp2\n\nenv = jinja2.Environment(\n loader = jinja2.FileSystemLoader(os.path.dirname(__file__)) #__file__ is current file\n )\n\n#the handler section\nclass MainPage(webapp2.RequestHandler):\n def get(self): #for a GET request\n template = env.get_template(\"/templates/home.html\")\n self.response.write(template.render())\n\n\nclass SignUp(webapp2.RequestHandler):\n def post(self):\n age = int(self.request.get(\"age\")) #get all lets you select multiple\n templateVars = {\n \"username\": self.request.get(\"username\"),\n \"password\": self.request.get(\"password\"),\n \"tier\": self.request.get(\"tier\"),\n \"legal\": age > 13,\n \"newsletter\": bool(self.request.get(\"newsletter\")),\n }\n template = env.get_template(\"/templates/signup.html\")\n self.response.write(template.render(templateVars))\n\n\napp = webapp2.WSGIApplication([\n ('/', MainPage),\n (\"/signup\", SignUp) #this maps the root url to the MainPage Handler\n], debug=True)\n" }, { "alpha_fraction": 0.6056673526763916, "alphanum_fraction": 0.6257944703102112, "avg_line_length": 43.9523811340332, "blob_id": "e1d2db3939737ec9900864126f089325d8a82275", "content_id": "faf64c368dc1efcb6d2ce3112e5af1b7204d675f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3776, "license_type": "no_license", "max_line_length": 270, "num_lines": 84, "path": "/language-api-tester/test.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "{u'entities':[ # entities\n\n {u'name': u'Google', u'salience': 0.5345132, u'metadata': {u'mid': u'/m/045c7b', u'wikipedia_url': u'https://en.wikipedia.org/wiki/Google'}, u'mentions': [{u'text': {u'beginOffset': 0, u'content': u'Google'}, u'type': u'PROPER'}], u'type': u'ORGANIZATION'},\n\n {u'name': u'software engineers', u'salience': 0.23102836, u'metadata': {}, u'mentions': [{u'text': {u'beginOffset': 11, u'content': u'software engineers'}, u'type': u'COMMON'}], u'type': u'PERSON'},\n\n {u'name': u'Mountanview', u'salience': 0.13288432, u'metadata': {}, u'mentions': [{u'text': {u'beginOffset': 33, u'content': u'Mountanview'}, u'type': u'PROPER'}], u'type': u'OTHER'},\n\n {u'name': u'California', u'salience': 0.101574115, u'metadata': {u'mid': u'/m/01n7q', u'wikipedia_url': u'https://en.wikipedia.org/wiki/California'}, u'mentions': [{u'text': {u'beginOffset': 46, u'content': u'California'}, u'type': u'PROPER'}], u'type': u'LOCATION'}\n\n], u'language': u'en'}\n\n\n\n{u'sentences': [{ 'text': {u'content': u\"You're a fucking moron\", u'beginOffset': 0},\n u'sentiment': {u'magnitude': 0.9, u'score': -0.9}],\nu'documentSentiment': {u'magnitude': 0.9, u'score': -0.9},\nu'language': u'en'}\n\n\n {u'categories':\n [{\n u'confidence': 0.69, u'name': u'/Science/Computer Science'}, {u'confidence': 0.57, u'name': u'/Computers & Electronics/Programming'}]}\n\nj = dictionary =>\n entities = list =>\n more dictionaries (name, type[proper/common], type[category])\n\n\n\n#functional getCategories\ndef getCategories(url): #url is unique to categories function in api\n data = {\n \"document\": {\n \"type\": \"PLAIN_TEXT\",\n \"language\": \"EN\",\n \"content\": \"Google, headquartered in Mountain View, unveiled the new Android phone at the Consumer Electronic Show. Sundar Pichai said in his keynote that users love their new Android phones.\"\n }\n }\n headers = {\n \"Content-Type\" : \"application/json; charset=utf-8\"\n }\n jsondata = json.dumps(data)\n result = urlfetch.fetch(url, method=urlfetch.POST, payload=data,headers=headers)\n python_result = json.loads(result.content)\n string = \"\"\n for i in range(0, len(python_result[\"categories\"])):\n string += \"Your resume indicates the \"\n string += python_result[\"categories\"][i][\"name\"]\n string += \" category with a \"\n string += str(python_result[\"categories\"][i][\"confidence\"])\n string += \" level of confidence. \\n\"\n return string\nprint(getCategories(url))\n\n\n\n\ndef getSentiment(url): #url is unique to sentiment function in api\n data = {\n \"document\": {\n \"type\": \"PLAIN_TEXT\",\n \"language\": \"EN\",\n \"content\": \"Google, headquartered in Mountain View, unveiled the new Android phone at the Consumer Electronic Show. Sundar Pichai said in his keynote that users love their new Android phones.\"\n },\n \"encodingType\": \"UTF32\",\n }\n headers = {\n \"Content-Type\" : \"application/json; charset=utf-8\"\n }\n jsondata = json.dumps(data)\n result = urlfetch.fetch(url, method=urlfetch.POST, payload=data,headers=headers)\n python_result = json.loads(result.content)\n string = \"\"\n magnitude = python_result[\"documentSentiment\"][\"magnitude\"]\n score = python_result[\"documentSentiment\"][\"score\"]\n if (score < 0.0):\n string = \"Your resume has a \" + str(score) + \" score and a \" + str(magnitude) + \" magnitude. This reads as negative\"\n elif (score > 0.0 and score < .5):\n string = \"Your resume has a \" + str(score) + \" score and a \" + str(magnitude) + \" magnitude. This reads as neutral\"\n elif (score > .5):\n string = \"Your resume has a \" + str(score) + \" score and a \" + str(magnitude) + \" magnitude. This reads as positive\"\n return string\nprint(getSentiment(url))\n" }, { "alpha_fraction": 0.546798050403595, "alphanum_fraction": 0.546798050403595, "avg_line_length": 17.454545974731445, "blob_id": "d253ab134c32eb2a7558c5e2e928d7dedd2961e6", "content_id": "b60cdfc8374b2ecfc3ff6d2dadff153fb41e42b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 203, "license_type": "no_license", "max_line_length": 33, "num_lines": 11, "path": "/fillit/templates/signup.html", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "<p>Username: {{username}}</p>\n<p>Password: {{password}}</p>\n<p>Tier: {{tier}}</p>\n<p>\n{% if legal %}\n You are legal.\n{% else %}\n You are too young.\n{% endif %}\n</p>\n<p>Newsletter: {{newsletter}}</p>\n" }, { "alpha_fraction": 0.6581156849861145, "alphanum_fraction": 0.6651119589805603, "avg_line_length": 27.95945930480957, "blob_id": "2e90e805718ee57f8dc5eda2edbea1300c97f896", "content_id": "624cbf85fe3a0fd3202996280feb923c43000ba4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2144, "license_type": "no_license", "max_line_length": 89, "num_lines": 74, "path": "/adventure/main.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "\nimport webapp2\nimport jinja2 # import library defined in app.yaml\nimport os\n\n#set up jinja environment\nenv = jinja2.Environment(\n loader = jinja2.FileSystemLoader(os.path.dirname(__file__)) #__file__ is current file\n )\n\n\n\nclass MainPage(webapp2.RequestHandler):\n def get(self):\n template = env.get_template(\"templates/start.html\")\n self.response.write(template.render())\n\nclass JumpIn(webapp2.RequestHandler):\n def get(self):\n template = env.get_template(\"templates/jumpin.html\")\n self.response.write(template.render())\n\nclass Run(webapp2.RequestHandler):\n def get(self):\n template = env.get_template(\"templates/run.html\")\n self.response.write(template.render())\n\nclass Email(webapp2.RequestHandler):\n def get(self):\n template = env.get_template(\"templates/email.html\")\n self.response.write(template.render())\n\nclass Ignore(webapp2.RequestHandler):\n def get(self):\n template = env.get_template(\"templates/ignore.html\")\n self.response.write(template.render())\n\nclass Accept(webapp2.RequestHandler):\n def get(self):\n template = env.get_template(\"templates/accept.html\")\n self.response.write(template.render())\n\nclass Reject(webapp2.RequestHandler):\n def get(self):\n template = env.get_template(\"templates/reject.html\")\n self.response.write(template.render())\n\nclass Run(webapp2.RequestHandler):\n def get(self):\n template = env.get_template(\"templates/run.html\")\n self.response.write(template.render())\n\nclass PullOver(webapp2.RequestHandler):\n def get(self):\n template = env.get_template(\"templates/pullover.html\")\n self.response.write(template.render())\n\nclass Drive(webapp2.RequestHandler):\n def get(self):\n template = env.get_template(\"templates/drive.html\")\n self.response.write(template.render())\n\n\n\napp = webapp2.WSGIApplication([\n (\"/\", MainPage),\n (\"/run\", Run),\n (\"/jumpin\", JumpIn),\n (\"/email\", Email),\n (\"/ignore\", Ignore),\n (\"/accept\", Accept),\n (\"/reject\", Reject),\n (\"/pullover\", PullOver),\n (\"/drive\", Drive),\n], debug = True)\n" }, { "alpha_fraction": 0.6829679608345032, "alphanum_fraction": 0.6897132992744446, "avg_line_length": 27.926828384399414, "blob_id": "ef67c596fb2fe870e5a84a66d634089f13ac98ee", "content_id": "3f3465fcd714c1d9b8c0e4ba9bbe1c30bb816e75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1189, "license_type": "no_license", "max_line_length": 51, "num_lines": 41, "path": "/JavaScript/box.js", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "console.log(\"Hello\");\n\n\nlet rightButton = document.querySelector(\"#right\");\nrightButton.addEventListener(\"click\", e=> {\n let box = document.querySelector(\"#box\");\n let currentLeft = box.style.left;\n let newLeft = parseInt(currentLeft) + 10;\n box.style.left = newLeft + \"px\";\n})\n\nlet leftButton = document.querySelector(\"#left\");\nleftButton.addEventListener(\"click\", e=> {\n let box = document.querySelector(\"#box\");\n let currentLeft = box.style.left;\n let newLeft = parseInt(currentLeft) - 10;\n box.style.left = newLeft + \"px\";\n})\n\nlet upButton = document.querySelector(\"#up\");\nupButton.addEventListener(\"click\", e=> {\n let box = document.querySelector(\"#box\");\n let currentTop = box.style.top;\n let newTop = parseInt(currentTop) - 10;\n box.style.top = newTop + \"px\";\n})\n\nlet downButton = document.querySelector(\"#down\");\ndownButton.addEventListener(\"click\", e=> {\n let box = document.querySelector(\"#box\");\n let currentTop = box.style.top;\n let newTop = parseInt(currentTop) + 10;\n box.style.top = newTop + \"px\";\n})\n\n\nlet boxButton = document.querySelector(\"#box\");\nboxButton.addEventListener(\"click\", e=> {\n boxButton.innerText = \"👍 \";\n boxButton.disabled = true;\n})\n" }, { "alpha_fraction": 0.6621140241622925, "alphanum_fraction": 0.6739904880523682, "avg_line_length": 24.515151977539062, "blob_id": "21d22e2f202c0bb7800afa2030d740628aad9dce", "content_id": "387ec56cee1ec6748cf6b5cc1680508b568db0de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1684, "license_type": "no_license", "max_line_length": 232, "num_lines": 66, "path": "/cssi-test-api/main.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "import json\nimport argparse\nimport webapp2\nimport urllib\nfrom google.appengine.api import urlfetch\nfrom google.cloud import language\nfrom google.cloud.language import enums\n\nAPI_KEY = \"AIzaSyDCv38dyT92Kalge4L8ibzHFVcLgvtps9Q\"\nurl = \"https://language.googleapis.com/v1/documents:analyzeEntities?key=\" + API_KEY\n\n\nraw_tx = \"Software engineer, Google, Mountainview California, June 2022 - Present\"\n\ndata = {\n \"document\": {\n object({\n \"type\": enum(PLAIN_TEXT),\n \"language\": string,\n\n # Union field source can be only one of the following:\n \"content\": string,\n # End of list of possible types for union field source.\n })\n },\n \"encodingType\": enum(UTF8),\n}\n\n\n# payload = urllib.urlencode({\n# \"rawtx\": raw_tx\n# })\n#\nresult = urlfetch.fetch(url,\n method=urlfetch.POST,\n payload=data\n)\n\nif result.status_code == 200:\n j = json.loads(result.content)\n txid = j.get('txid')\n print txid, raw_tx\nelse:\n msg = 'Error accessing insight API:'+str(result.status_code)+\" \"+str(result.content)\n print msg\n\nclass MainPage(webapp2.RequestHandler):\n def get(self):\n pass\n\n\n\n# #r = requests.post(url = \"https://maps.googleapis.com/maps/api/place/findplacefromtext/output?parameters\", data = data)\n# r = url.fetch(\"https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=Museum%20of%20Contemporary%20Art%20Australia&inputtype=textquery&fields=photos,formatted_address,name,rating,opening_hours,geometry&key=AIzaSyA7Uo226eyoZjz2H2gQh2eY-pgR5PzbES8\")\n#\n#\n# print(response)\n# content = response.content\n#\n# json_result = json.loads(response.content)\n# print(json_result)\n\n\napp = webapp2.WSGIApplication([\n (\"/\", MainPage),\n], debug = True)\n" }, { "alpha_fraction": 0.6269202828407288, "alphanum_fraction": 0.6335040330886841, "avg_line_length": 27.47916603088379, "blob_id": "425fba5815fd62941e2ada2def9d50485a4db26d", "content_id": "0b65eaf1a152baf28a27943956c1b2dafd182599", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1367, "license_type": "no_license", "max_line_length": 89, "num_lines": 48, "path": "/Python/main.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "import webapp2\nimport jinja2 # import library defined in app.yaml\nimport os\n\n#set up jinja environment\nenv = jinja2.Environment(\n loader = jinja2.FileSystemLoader(os.path.dirname(__file__)) #__file__ is current file\n )\n\nclass MainPage(webapp2.RequestHandler):\n def get(self):\n name = self.request.get(\"name\")\n location = self.request.get(\"location\")\n template = env.get_template(\"templates/profile.html\")\n templateVars = { #dictionary\n \"name\": name,\n \"location\": location\n }\n self.response.write(template.render(templateVars))\n\nclass Friends(webapp2.RequestHandler):\n def get(self):\n template = env.get_template(\"templates/friends.html\")\n self.response.write(template.render())\n\nclass Skills(webapp2.RequestHandler):\n def get(self):\n pass\n #skills and other stuff\n\n\n#can delete later no problem\nclass Students(webapp2.RequestHandler):\n def get(self):\n template = env.get_template(\"templates/students.html\")\n templateVars = {\n \"location\": \"MTV\",\n \"students\": [\"Jackelen\", \"Savion\", \"Olivia\", \"Anyka\"]\n }\n self.response.write(template.render(templateVars))\n\n\napp = webapp2.WSGIApplication([\n (\"/\", MainPage),\n (\"/friends\", Friends),\n (\"/skills\", Skills),\n (\"/students\", Students)\n], debug = True)\n" }, { "alpha_fraction": 0.6400638222694397, "alphanum_fraction": 0.6496408581733704, "avg_line_length": 35.85293960571289, "blob_id": "921859c1ab37d39d12d5cd6a632f4062dd70e2a1", "content_id": "265d8921ebd03914abd5d619443862a0f9b57efc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1253, "license_type": "no_license", "max_line_length": 89, "num_lines": 34, "path": "/Quiz/main.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "import webapp2\nimport jinja2\nimport os\nenv = jinja2.Environment(\n loader = jinja2.FileSystemLoader(os.path.dirname(__file__)) #__file__ is current file\n )\n\n\n\n#the handler section\nclass ShowQuiz(webapp2.RequestHandler):\n def get(self): #for a GET request\n template = env.get_template(\"templates/quiz.html\")\n self.response.write(template.render())\nclass ShowResult(webapp2.RequestHandler):\n def post(self):\n result = self.request.get(\"question1\")\n if result == \"val1\":\n template = env.get_template(\"templates/gryffindor.html\")\n self.response.write(template.render())\n elif result == \"val2\":\n template = env.get_template(\"templates/huffelpuff.html\")\n self.response.write(template.render())\n elif result == \"val3\":\n template = env.get_template(\"templates/ravenclaw.html\")\n self.response.write(template.render())\n elif result == \"val4\":\n template = env.get_template(\"templates/slytherin.html\")\n self.response.write(template.render())\n#the app configuration section\napp = webapp2.WSGIApplication([\n ('/', ShowQuiz),\n ('/result', ShowResult) #this maps the root url to the MainPage Handler\n], debug=True)\n" }, { "alpha_fraction": 0.6239761710166931, "alphanum_fraction": 0.6314221620559692, "avg_line_length": 33.43589782714844, "blob_id": "759828db61df07dd372853288eb216a69c4a2578", "content_id": "16a9ad3cd934c0a1a1b2725289ae660ae6781649", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1343, "license_type": "no_license", "max_line_length": 89, "num_lines": 39, "path": "/Madlibs/main.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "#main.py\n#the import section\nimport webapp2\nimport jinja2\nimport os\nenv = jinja2.Environment(\n loader = jinja2.FileSystemLoader(os.path.dirname(__file__)) #__file__ is current file\n )\n\n\n\n#the handler section\nclass CollectInfo(webapp2.RequestHandler):\n def get(self): #for a GET request\n template = env.get_template(\"templates/collect_info.html\")\n self.response.write(template.render())\nclass Story(webapp2.RequestHandler):\n def post(self):\n template = env.get_template(\"templates/story.html\")\n correct = self.request.get(\"number\")\n total = self.request.get(\"largerNumber\")\n templateVars = {\n \"protagonist\": self.request.get(\"protagonist\"),\n \"event\": self.request.get(\"event\"),\n \"pluralNoun\": self.request.get(\"pluralNoun\"),\n \"name\": self.request.get(\"name\"),\n \"skill\": self.request.get(\"skill\"),\n \"number\": int(correct/total *100),\n \"adjective\": self.request.get(\"adjective\"),\n \"place\": self.request.get(\"place\"),\n \"noun\": self.request.get(\"noun\")\n }\n self.response.write(template.render(templateVars))\n\n#the app configuration section\napp = webapp2.WSGIApplication([\n ('/', CollectInfo),\n ('/story', Story) #this maps the root url to the MainPage Handler\n], debug=True)\n" }, { "alpha_fraction": 0.5840286016464233, "alphanum_fraction": 0.5911799669265747, "avg_line_length": 26.96666717529297, "blob_id": "d4f2f95ec5c49314a1cbac21b24a14e6724ffb16", "content_id": "b4af8a3144a358d520b25776aa29fe293d205e29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 839, "license_type": "no_license", "max_line_length": 68, "num_lines": 30, "path": "/Python/guessing_game.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "import random\nrandom_word_list = [\"programming\", \"cssi\", \"computers\", \"projector\"]\nword = random_word_list[random.randint(0, len(random_word_list)-1)]\nprint(word)\nguesses = \"Guesses: \"\ndisplay = list(\"-\" * len(word))\nfor letter in display:\n print(letter),\nnumGuesses = 0\nmaxGuesses = 5\ngameOver = False\nmatch = False\nwhile(gameOver == False):\n match = False\n guess = raw_input(\"\\nGuess a letter in the mystery word: \")\n for i in range(0, len(word)):\n if (guess == word[i]):\n display[i] = guess\n match = True\n if (match == False):\n guesses += guess\n guesses += \" \"\n numGuesses += 1\n for letter in display:\n print(letter),\n print(\"\\n\" + guesses)\n if (numGuesses > maxGuesses) or (\"-\" not in display):\n gameOver = True\n else:\n gameOver = False\n" }, { "alpha_fraction": 0.5482594966888428, "alphanum_fraction": 0.5822784900665283, "avg_line_length": 17.05714225769043, "blob_id": "10a6230a9fe04e2c513f61f16a7b5505e5caeb07", "content_id": "32d3e818a23cf2605e9d6507774920e0ae66ff71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1264, "license_type": "no_license", "max_line_length": 61, "num_lines": 70, "path": "/Python/functions.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport random\n#Exerise 1\n\n\ndef longest_word(word1, word2, word3):\n if len(word1) > len(word2) and len(word1) > len(word3):\n return word1\n elif len(word2) > len(word1) and len(word2) > len(word3):\n return word2\n else:\n return word3\n\nprint(longest_word(\"apples\", \"bananas\", \"oranges\"))\n\n\n#Exercise 2\n\ndef reverse_string(string):\n new_string = \"\"\n for i in range(len(string)-1, -1, -1):\n new_string += string[i]\n return new_string\n\nprint(reverse_string(\"Olivia\"))\n\n#Exercise 3\ndef sum_to_n(n):\n sum = 0\n for i in range(0, n+1):\n sum += i;\n return sum\n\nprint(sum_to_n(4))\n\n#Exercise 4\n\ndef is_triangle(s1, s2, s3):\n if (s1 + s2 > s3):\n return True\n else:\n return False\n\nprint(is_triangle(4, 5, 9))\n\n#Exercise 5\n\ndef roll_dice(numRolls):\n sum = 0\n for i in range(0, numRolls):\n sum += random.randint(1,6)\n return sum\n\nprint(roll_dice(2))\n\n\n\n\n#Extension 2\ndef snake_case(word):\n new_string = \"\"\n starting_index = 0\n for i in range(0, len(word)):\n if word[i].isupper():\n new_string += word[starting_index: i]\n new_string += \"_\"\n starting_index = i\n return new_string\n\nprint(snake_case(\"ameliaBedelia\"))\n" }, { "alpha_fraction": 0.6545866131782532, "alphanum_fraction": 0.6579841375350952, "avg_line_length": 19.06818199157715, "blob_id": "6eb24a78c858c7721fcee5ab55f96799395d6919", "content_id": "fa92f777bcd8747386273c85515add5148048805", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 883, "license_type": "no_license", "max_line_length": 66, "num_lines": 44, "path": "/giphy/giphy.js", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "console.log(\"Hello!\")\n\n//Make a form for searching\n//Get results for a search Engine\n//Display gifs\n\n\n\n//need an api key\n\n\nlet apiKey = \"ABc4k9V7065fevCrUU5XnsIIJBmSkcNW\";\n\nlet url = \"http://api.giphy.com/v1/gifs/search\";\n\nfunction createImage(url) {\n let image = document.createElement(\"img\");\n image.src = url;\n document.body.appendChild(image);\n console.log(result);\n}\n\nlet go = document.querySelector(\"#go\");\nlet input = document.querySelector(\"#q\");\n\ngo.addEventListener(\"click\", e=> {\n let q = input.value;\n fetchGif(q);\n})\n\nfunction fetchGif(searchTerm) {\n let query = `${url}?api_key=${apiKey}&q=${searchTerm}s&limit=1`;\n console.log(searchTerm);\n window.fetch(query).then(data => {\n return data.json();\n }).then(json => {\n let results = json.data;\n console.log(json.data);\n let result = results[0];\n console.log(result);\n createImage(result.images.downsized.url);\n\n });\n}\n" }, { "alpha_fraction": 0.6578773856163025, "alphanum_fraction": 0.663810133934021, "avg_line_length": 34.27906799316406, "blob_id": "7f859c8f05a6bf8e4925bc0859fc12ef55887f4f", "content_id": "7738c712233a6b4a8579e182d11d20a6b247ca92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1517, "license_type": "no_license", "max_line_length": 97, "num_lines": 43, "path": "/clicker/main.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "import webapp2\nimport jinja2 # import library defined in app.yaml\nimport os\n\n\nfrom google.appengine.ext import ndb\n\n#set up jinja environment\nenv = jinja2.Environment(\n loader = jinja2.FileSystemLoader(os.path.dirname(__file__)) #__file__ is current file\n )\n\nclass ClickCounter(ndb.Model):\n clicks = ndb.IntegerProperty()\n\nclass MainPage(webapp2.RequestHandler):\n def get(self):\n click_counter = ClickCounter.query().get() #give me all models that are type ClickCounter\n #check if its the first click\n if not click_counter: #if click counter is empty\n click_counter = ClickCounter(clicks=0)\n templateVars = {\n \"click_count\": click_counter.clicks,\n }\n template = env.get_template(\"/templates/clicky.html\")\n self.response.write(template.render(templateVars))\n def post(self):\n click_counter = ClickCounter.query().get() #give me all models that are type ClickCounter\n #check if its the first click\n if not click_counter: #if click counter is empty\n click_counter = ClickCounter(clicks=0)\n click_counter.clicks += 1\n click_counter.put() #updated value of clicks-->saves\n templateVars = {\n \"click_count\": click_counter.clicks, #saves value of clicks into template vars\n }\n template = env.get_template(\"templates/clicky.html\")\n self.response.write(template.render(templateVars))\n\napp = webapp2.WSGIApplication([\n (\"/\", MainPage),\n\n], debug = True)\n" }, { "alpha_fraction": 0.7037037014961243, "alphanum_fraction": 0.7037037014961243, "avg_line_length": 12.5, "blob_id": "97d7a7baff496da026c1d7d72ef82da2bd9c917a", "content_id": "d7c73d898386b9435b6d702f81b9cae82ab18f70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 27, "license_type": "no_license", "max_line_length": 13, "num_lines": 2, "path": "/README.md", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "# CSSI-stuff\n# CSSI-things\n" }, { "alpha_fraction": 0.6217331290245056, "alphanum_fraction": 0.6389271020889282, "avg_line_length": 23.610170364379883, "blob_id": "4475398f8107b6c4cadb877433b90a26e9307016", "content_id": "9d02acfda752723af8224c0085cbd7083762c305", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1454, "license_type": "no_license", "max_line_length": 78, "num_lines": 59, "path": "/JavaScript/structure.js", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "\n\nconsole.log(\"Hello!\");\n\n/*\nlet scores = [97, 92, 90, 87, 88, 100, 99, 105];\n\nlet max = scores[0];\nlet total = 0;\nfor (let i = 0; i < scores.length; i ++) {\n total += scores[i];\n if (scores[i] > max) {\n max = scores[i];\n };\n}\nconsole.log(\"The maximum value in the scores array is \" + max)\nconsole.log(\"The total value of all the scores in the array is \" + total);\nconsole.log(\"The average value of all the scores is \" + total/scores.length);\n\nlet names = [\"Savion\", \"Jenny\", \"Olivia\", \"Joshua\"];\n\nnames.forEach(name => { //How to write a for each loop in JavaScript\n console.log(\"Hello, \" + name);\n})\n*/\n\n//let matthew = [\"Matthew\", \"Levine\", \"Dartmouth\", \"Harry Potter\"];\n\n//let yojairo = [\"Yojairo\", \"Morales\", \"USC\", \"Kendrick Lamar\"];\n\n\n//Objects can hold multiple pieces of data, defined by curly braces\n\nlet matthew = {\n \"firstName\": \"Matthew\",\n \"lastName\": \"Levine\",\n \"university\": \"Dartmouth\",\n \"culture\": \"Harry Potter\"\n}\n\nconsole.log(matthew.university);\n\nlet yojairo = {\n \"firstName\": \"Yojairo\",\n \"lastName\": \"Morales\",\n \"university\": \"USC\",\n \"culture\": \"Kendrick Lamar\",\n}\n\nlet people = [matthew, yojairo];\n\npeople.forEach(person => {\n console.log(person.firstName + \" really likes \" + person.culture);\n})\n\n\n//scores.pop() --> pops the last element off the array\n//scores.push() --> pushes a score at the\n\n//scores.splice(1, 1, 94) --> first number is index of added, second number is\n//index of thing deleted, third is the value of added\n" }, { "alpha_fraction": 0.6079469919204712, "alphanum_fraction": 0.6437085866928101, "avg_line_length": 25.89285659790039, "blob_id": "ba15623cce2580eba159e63127917006174b7379", "content_id": "b7fd0f0010efc890a5a925f54b4e0e81370a0115", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 755, "license_type": "no_license", "max_line_length": 85, "num_lines": 28, "path": "/Python/test.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "\n\nstates = {\"California\": \"CA\", \"Arizona\": \"AZ\", \"Arkansas\": \"AK\"}\n\nfor state in states:\n print(\"State: \" + state + \" Abbreviation: \" + states[state])\n\n\nstore_prices = {\"Cereal\": 2.00, \"Bread\": 4.00, \"fiber optic\": 25.00, \"lambo\": 30.00 }\n\nprint(store_prices[\"Cereal\"] + store_prices[\"lambo\"])\n\n\nstore_inventory = {\"Cereal\" : 20, \"Bread\": 30, \"fiber optic\": 40, \"lambo\": 2}\n\n\nprice = str(2 * store_prices[\"Cereal\"] + store_prices[\"lambo\"])\nprint(\"The price of two boxes of cereal and one lambo is: \" + price)\n\nstore_inventory[\"Cereal\"] -= 2\nstore_inventory[\"lambo\"] -= 1\n\nprint(store_inventory[\"Cereal\"])\nprint(store_inventory[\"lambo\"])\n\nfor item in store_prices:\n store_prices[item] *= 1.03\n\nfor item in store_prices:\n print(store_prices[item])\n" }, { "alpha_fraction": 0.6280701756477356, "alphanum_fraction": 0.6330826878547668, "avg_line_length": 32.25, "blob_id": "8b5aedb273ae2d24be8cb62f83c48a6986919295", "content_id": "f075d3577ae69a32cf90ccc017b3ae786ac6b4be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1995, "license_type": "no_license", "max_line_length": 76, "num_lines": 60, "path": "/guestbook/main.py", "repo_name": "otobin/CSSI-stuff", "src_encoding": "UTF-8", "text": "import webapp2\nimport jinja2 # import library defined in app.yaml\nimport os\n\n\nimport logging\nfrom google.appengine.api import users #new data base--application interface\nfrom google.appengine.ext import ndb\n\n#set up jinja environment\nenv = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True)\n\n\nclass Message(ndb.Model):\n email = ndb.StringProperty()\n content = ndb.StringProperty()\n created_time = ndb.DateTimeProperty(auto_now_add = True)\n\nclass MainPage(webapp2.RequestHandler):\n def get(self):\n logging.info(\"This is the main handler\")\n login_url = \"\"\n logout_url = \"\"\n current_user = users.get_current_user()\n #the current user will be a user object or none\n #if nobody is logged in, show a login prompt\n if not current_user:\n login_url = users.create_login_url(\"/\")\n else:\n logout_url = users.create_logout_url(\"/\")\n\n #Read and write from the database:\n message_query = Message.query()\n message_query = message_query.order(-Message.created_time)\n messages = message_query.fetch()\n templateVars = {\n \"current_user\": current_user,\n \"login_url\": login_url,\n \"logout_url\": logout_url,\n \"messages\": messages,\n }\n template = env.get_template(\"templates/guestbook.html\")\n self.response.write(template.render(templateVars))\n def post(self):\n #1.) get information from the request\n current_user = users.get_current_user()\n email = current_user.email()\n content = self.request.get(\"content\")\n #2.) Read/write to the database\n message = Message(email = email, content = content)\n #3.) Render a response\n message.put() #saving the content into the database\n self.redirect(\"/\")\n\napp = webapp2.WSGIApplication([\n (\"/\", MainPage),\n], debug = True)\n" } ]
27
JesseStew/KNN-Clustering
https://github.com/JesseStew/KNN-Clustering
09d1f34c1305cd0d234ec41d4a69099103fe7d88
e7f2bd58ec4fb21236f887ad977bfc864707be67
bdf296f161dcbbbed8342d1e1c3c4bf4dc64525e
refs/heads/master
2021-03-19T14:57:05.272241
2018-03-04T04:59:27
2018-03-04T04:59:27
123,503,049
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6411436796188354, "alphanum_fraction": 0.6508359313011169, "avg_line_length": 36.74311828613281, "blob_id": "a5ef4556e1d7c372775bb98260f0db1a4043d144", "content_id": "55df011dea59838a46845c1be26e3dbe968952e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4127, "license_type": "no_license", "max_line_length": 156, "num_lines": 109, "path": "/KNN.py", "repo_name": "JesseStew/KNN-Clustering", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 1 17:22:29 2018\nJesse Stewart\nCSC 535\nHW2\n\"\"\"\n\nclear = \"\\n\" * 100\n\nfrom statistics import mode\nimport math\nimport csv\n\n# Number of k-items to compare\nnum_k = 3\n\nclass Item(object):\n def __init__(self, contents = None, nearest_neighbors = None, classification = None):\n self.contents = contents\n self.nearest_neighbors = nearest_neighbors\n self.classification = classification\n\n# Takes list of lists and number assigned to k\n# returns list of Item objects\ndef itemize_data(data, num_k):\n item_list = []\n #create list of items\n for itr in range(1,len(data)): #skip first tuple\n item = Item(data[itr], num_k)\n item_list.append(item)\n return item_list\n\n# Assigns classification attribute \n# to list of Item objects\ndef assign_classification(itemized_data):\n for itr in itemized_data:\n itr.classification = itr.contents.pop(0)\n\n# Find euclidean distance measure of two Item objects\n# Input: two lists of numbers which are the same size.\n# Returns: euclidean distance of two lists.\ndef euclidean_dist(train_item_data, test_item_data):\n #print(\"train_item_data[0]: \", train_item_data[0])\n squared_euclidean = []\n euclidean_dist = 0\n if len(train_item_data) != len(test_item_data):\n raise NameError(\"The len(train_item_data) != len(test_item)\\nlen(train_item_data): \", len(train_item_data), \"len(test_item): \", len(test_item_data))\n else:\n for num in range(0,len(train_item_data)):\n train_i = int(train_item_data[num])\n test_i = int(test_item_data[num])\n squared_euclidean.append((train_i-test_i)*(train_i-test_i))\n for num in squared_euclidean:\n euclidean_dist = euclidean_dist + num\n return math.sqrt(euclidean_dist)\n\n# Assigns nearest neighbors to all items in test_data\n# Input: list of training data items, list of test data items, and k\n# No output: assign item.nearest_neighbors internally\ndef assign_nearest_neighbors(train_data, test_data, num_k):\n for num in range(len(test_data)):\n test_data[num].nearest_neighbors = []\n for itr in train_data:\n if len(test_data[num].nearest_neighbors) < num_k:\n test_data[num].nearest_neighbors.append(itr)\n else:\n for item in test_data[num].nearest_neighbors:\n t = test_data[num].contents\n d = itr.contents\n u = item.contents\n sim_t_u = euclidean_dist(t, u)\n sim_t_d = euclidean_dist(t, d)\n if sim_t_u <= sim_t_d:\n test_data[num].nearest_neighbors.remove(item)\n test_data[num].nearest_neighbors.append(itr)\n\n# Assigns classification to all items in test_data\n# Input: list of test data items\n# No output: assign item.classification internally\ndef assign_class_by_nn(test_data):\n for item in test_data:\n classification = []\n for itr in item.nearest_neighbors:\n classification.append(itr.classification)\n item.classification = mode(classification)\n \nwith open('MNIST_train.csv', newline='', encoding='utf_8') as f:\n reader = csv.reader(f)\n train_data = list(reader)\n \nwith open('MNIST_test.csv', newline='', encoding='utf_8') as f:\n reader = csv.reader(f)\n test_data = list(reader)\n\ntest_data = itemize_data(test_data, num_k)\nassign_classification(test_data)\nprint(\"test_data[0].classification: \", test_data[0].classification)\nprint(\"test_data[1].classification: \", test_data[1].classification)\nprint(\"test_data[len(test_data)-1].classification: \", test_data[len(test_data)-1].classification)\n\ntrain_data = itemize_data(train_data, num_k)\nassign_classification(train_data)\nprint(\"\\ntrain_data[0].classification: \", train_data[0].classification)\nprint(\"train_data[1].classification: \", train_data[1].classification)\nprint(\"train_data[len(train_data)-1].classification: \", train_data[len(train_data)-1].classification)\n\nassign_nearest_neighbors(train_data, test_data, num_k)\nassign_class_by_nn(test_data)\n\n " }, { "alpha_fraction": 0.7748749256134033, "alphanum_fraction": 0.7798777222633362, "avg_line_length": 118.86666870117188, "blob_id": "23a25f8ae61469af99f918a2dccf75239875d897", "content_id": "a06b9b545895304f5d023fd09b4380d67a7c082e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1819, "license_type": "no_license", "max_line_length": 525, "num_lines": 15, "path": "/README.md", "repo_name": "JesseStew/KNN-Clustering", "src_encoding": "UTF-8", "text": "# DM_HW2 \nImplement the KNN algorithm as given in the book on page 92. The only difference is that while the book uses simple unweighted voting, you will use weighted voting in your implementation. In simple unweighted voting, once the k nearest neighbors are found, their distances from the test sample do not matter. One neighbor is one vote. In weighted voting, the vote of a neighbor is inversely proportional to its distance to the test sample. You must use Python for your implementation. \nUse the given MNIST_train.cvs as your training data set and MNIST_test.csv as the test data set. There are 10 classes, with labels 0, 1, 2, …, 9, for this data set. The first attribute/column is the class label. Also notice that the first line/row in both data sets is a headers line. Do not modify the given data sets in any way because your code will be graded using them. In your code, you can just skip over the header lines. A description of the MNIST data is available at https://www.kaggle.com/c/digit-recognizer/data \nThe output from your program will display the following:\n•\tvalue of K \n•\tfor each test sample, print both the desired class and the computed class, where desired class, is the class label as given in the data set, and computed class, is what your code produces as the output for the sample. \n•\tthe accuracy rate\n•\tnumber of misclassified test samples, and \n•\ttotal number of test samples \n\nRemarks:\n•\tUse Euclidean distance measure to compute distances.\n•\tYou may use a random sample of the training data to decide on the value of K to use for the algorithm.\n•\tMake sure to use the data sets from the course web site and not any other instance of MNIST\n•\tYou need to use basic Python for implementation. You are not allowed to use IPython (no pandas, numpy, or scikit-learn) \n" } ]
2
gayummy/Discord-Account-Maker
https://github.com/gayummy/Discord-Account-Maker
5be43d07da71870926b739efc652197ada462e06
280098122c55962bf34b7292668a0d53ea8f1d87
5e4fa290c2a7751b8639c3a19a7518a338a27c00
refs/heads/master
2020-06-18T14:01:39.860031
2019-08-27T03:13:49
2019-08-27T03:13:49
196,326,552
2
1
null
null
null
null
null
[ { "alpha_fraction": 0.751884400844574, "alphanum_fraction": 0.7543969750404358, "avg_line_length": 30.84000015258789, "blob_id": "b20b757571d8f8274e474d316cf358b7e229eec3", "content_id": "c8b4e33f83ef8f7995f362fa1b301d1ffba8c220", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1592, "license_type": "permissive", "max_line_length": 119, "num_lines": 50, "path": "/make-email.py", "repo_name": "gayummy/Discord-Account-Maker", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nimport time\nimport names\nimport random\nimport string\n\n# need to run 'pip install names'\n\n# generate a random string of fixed length with\ndef randomString(stringLength=10):\n letters = string.ascii_letters\n return ''.join(random.choice(letters) for i in range(stringLength))+\"!\"\n\n# create chrome driver and open google signup page\nchrome_path = r\"C:\\Users\\samue\\Desktop\\python\\Discord-Account-Maker\\chromedriver.exe\"\ndriver = webdriver.Chrome(chrome_path)\n\n# TODO: pick a different email address than gmail, since they require phone verification\n\ndriver.get('https://accounts.google.com/SignUp')\n\n# generate user data\nfirstName = names.get_first_name()\nlastName = names.get_last_name()\npassword = randomString()\n\nprint(password)\n\n# send name data to form\ndriver.find_element_by_name(\"firstName\").send_keys(firstName)\ndriver.find_element_by_name(\"lastName\").send_keys(lastName)\n\n# wait for form to autogenerate email address\n# TODO: generate own email address from last and first name instead of gmail autogen\ntime.sleep(2.5)\n\n# send password data to form\ndriver.find_element_by_name(\"Passwd\").send_keys(password)\ndriver.find_element_by_name(\"ConfirmPasswd\").send_keys(password)\n\n# record email address generated by google form\nemailAddress = driver.find_element_by_name(\"Username\").get_attribute(\"value\")\n\nprint(emailAddress)\n\n# write email data to text file\nopen(\"emailData.txt\",\"a\").write(firstName + \",\" + lastName + \",\" + emailAddress + \"@gmail.com\" + \",\" + password + \"\\n\")\n\n#click next button\ndriver.find_element_by_id(\"accountDetailsNext\").click()\n" }, { "alpha_fraction": 0.7272727489471436, "alphanum_fraction": 0.7348484992980957, "avg_line_length": 28.05555534362793, "blob_id": "d53d01c2bc07e39cdca1c49f5453fa978b076a55", "content_id": "e93e5f9720ba26af1be66d3863b74c06318c3a93", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 528, "license_type": "permissive", "max_line_length": 124, "num_lines": 18, "path": "/README.md", "repo_name": "gayummy/Discord-Account-Maker", "src_encoding": "UTF-8", "text": "### Discord-Account-Maker\n\n## WORK IN PROGRESS\nMADE BY AFIRE,YOMI,JOE.\n\n\n## REQUIREMENTS\n- Python 3.6+ \n- discord.py (pip install discord.py)\n- Beautiful Soup 4 (pip install bs4)\n- Selenium (pip install selenium)\n- Requests (pip install requests)\n\n## reqs for email generator (WIP)\n\n- names (pip install names)\n- need to download chromedriver for selenium, and proper filepath (included in github)\n > shift+rightclick on chromedriver.exe, then click 'Copy as path' and paset that into the 'chrome_path field in the script\n \n\n\n" }, { "alpha_fraction": 0.7245657444000244, "alphanum_fraction": 0.7344912886619568, "avg_line_length": 18.190475463867188, "blob_id": "c1ebc3e0f2f7376c229b8e61502d1efa16463011", "content_id": "00a3c0f2e12984efcdab9132002fef21dc2e8f5f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 403, "license_type": "permissive", "max_line_length": 39, "num_lines": 21, "path": "/accverifier.py", "repo_name": "gayummy/Discord-Account-Maker", "src_encoding": "UTF-8", "text": "import requests\nimport json\nimport sys\nimport os\nimport poplib\nimport time\nfrom email import parser\nfrom html.parser import HTMLParser\nfrom time import sleep\nsys.path.append(\"././.\")\nfrom config import *\n\naccount_Email = sys.argv[1]\naccount_Password = sys.argv[2]\nPROXY = sys.argv[3]\nTOKEN = sys.argv[4]\nfoundLink = False\nAPI_KEY = captchaAPI\nsite_key = '6Lef5iQTAAAAAKeIvIY-DeexoO3gj7ryl9rLMEnn'\n\n## I'll work on verifier sometime ;) ##\n" }, { "alpha_fraction": 0.6850393414497375, "alphanum_fraction": 0.6981627345085144, "avg_line_length": 22.8125, "blob_id": "bd98241005972f08601d9a715dc3388ec7c5a381", "content_id": "39b770250041fe7dc37af4307a5383dcfea6e0af", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 381, "license_type": "permissive", "max_line_length": 66, "num_lines": 16, "path": "/accountcreator.py", "repo_name": "gayummy/Discord-Account-Maker", "src_encoding": "UTF-8", "text": "import requests\nimport json\nimport sys\nimport os\nfrom time import sleep\nsys.path.append (\"././.\")\nfrom config import *\n\naccount_Email = sys.argv[1]\naccount_Password sys.argv[2]\nPROXY = sys.argv[3]\nAPI_KEY = captchaAPI # Your 2captcha API KEY\nsite_key = '6Lef5iQTAAAAAKeIvIY-DeexoO3gj7ryl9rLMEnn'\nurl = \"https://discordapp.com/api/v6/auth/register\"\n\n### NOT DONE YET ;( (ill work on this later afire and joe ;) ) ###\n" } ]
4
almaszaurbekov/emmessage
https://github.com/almaszaurbekov/emmessage
c931e67009c60a73473711f645afe865cd72c07a
1475d9accff90e645e05f9178f79d8e5306a330a
6dbe59ae1c4a5bce19d00bcd19c881747aa1cb74
refs/heads/master
2023-01-20T17:32:49.229345
2020-11-29T07:46:07
2020-11-29T07:46:07
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7512437701225281, "alphanum_fraction": 0.7611940503120422, "avg_line_length": 24.25, "blob_id": "8a317077ad84b769d2bb373f464c4a9ee23948d1", "content_id": "d2bfc149344cf09b0e8fb57b5b4372ec6c8e1f50", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 201, "license_type": "permissive", "max_line_length": 39, "num_lines": 8, "path": "/app/Dockerfile", "repo_name": "almaszaurbekov/emmessage", "src_encoding": "UTF-8", "text": "FROM python:3.8\nCOPY . /app\nWORKDIR /app\nRUN pip install -r requirements.txt\nRUN python -m nltk.downloader stopwords\nRUN python -m nltk.downloader punkt\nRUN export FLASK_APP=app.py\nCMD [\"flask\", \"run\"]" }, { "alpha_fraction": 0.6121361255645752, "alphanum_fraction": 0.6164411902427673, "avg_line_length": 35.962120056152344, "blob_id": "bbde0f38891c96cff7f2d18a3fe2459c0712d196", "content_id": "31f4f74b39aab1a376128d88a209f8736343caf1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4878, "license_type": "permissive", "max_line_length": 122, "num_lines": 132, "path": "/app/models.py", "repo_name": "almaszaurbekov/emmessage", "src_encoding": "UTF-8", "text": "import re\nimport urllib\nimport json\nimport numpy as np\nimport pandas as pd\nimport csv\nimport nltk\nfrom nltk.stem import SnowballStemmer\nfrom nltk.corpus import stopwords\nfrom nltk import FreqDist\nfrom nltk import classify\nfrom nltk import NaiveBayesClassifier\nimport random\n\nstopwords = stopwords.words(\"english\")\n\nclass Classifier():\n def __init__(self):\n self.classifier = None\n self.df = None\n\n with open('config.json') as config_file:\n data = json.load(config_file)\n \n self.wassa = data[\"WASSA\"]\n self.archive = data[\"archive\"]\n self.corporate = data[\"corporate\"]\n\n self.global_dataset = np.array([])\n self.global_processed_model = {}\n\n self.init_wassa()\n self.init_archive()\n self.init_corporate()\n self.train_model()\n\n \n def clearify_wassa_post(self, post):\n data = list(map(lambda x: x.rstrip(), post.split('\\t')))\n return { \"text\": data[1], \"emotion\": data[2] }\n\n def get_wassa_dataset(self, url):\n file = urllib.request.urlopen(url)\n posts = list(map(lambda x : x.decode(\"utf-8\"), file.readlines()))\n return list(map(self.clearify_wassa_post, posts))\n\n def init_wassa(self):\n for key in self.wassa:\n for dataset_version in self.wassa[key]:\n local_dataset = self.get_wassa_dataset(self.wassa[key][dataset_version])\n self.global_dataset = np.concatenate((self.global_dataset, np.array(local_dataset)))\n \n def clearify_archive_comment(self, comment):\n clear_comment = comment.rstrip().split(';')\n return { \"text\" : clear_comment[0], \"emotion\": clear_comment[1] }\n\n def get_archive_dataset(self, url):\n with open(url) as file:\n data = file.readlines()\n return list(map(self.clearify_archive_comment, data))\n \n def init_archive(self):\n for key in self.archive:\n for dataset_version in self.archive[key]:\n local_dataset = self.get_archive_dataset(self.archive[key][dataset_version])\n self.global_dataset = np.concatenate((self.global_dataset, np.array(local_dataset)))\n \n def clearify_corporate(self, text):\n return { \"text\" : text, \"emotion\" : \"corporate\" }\n\n def init_corporate(self):\n with open(self.corporate, encoding = \"ISO-8859-1\") as csvfile:\n corporate_reader = csv.DictReader(csvfile, delimiter=',')\n reviews = [row['text'] for row in corporate_reader]\n local_dataset = list(map(self.clearify_corporate, reviews))\n self.global_dataset = np.concatenate((self.global_dataset, np.array(local_dataset)))\n \n def remove_noise(self, tokens, stop_words = ()):\n stemmer = SnowballStemmer(\"english\")\n cleaned_tokens = []\n for token in tokens:\n if len(token) > 0 and not re.search(r'[^0-9a-zA-Z]+', token) and token.lower() not in stop_words:\n cleaned_tokens.append(stemmer.stem(token))\n return cleaned_tokens\n\n def get_all_words(self, cleaned_tokens_list):\n for tokens in cleaned_tokens_list:\n for token in tokens:\n yield token\n\n def get_tokens_for_model(self, cleaned_tokens_list):\n for tokens in cleaned_tokens_list:\n yield dict([token, True] for token in tokens)\n \n def process_model(self):\n self.df = pd.DataFrame(list(self.global_dataset))\n\n emotions = self.df['emotion'].drop_duplicates().tolist()\n\n for em in emotions:\n dataset = self.df[self.df['emotion'] == em]['text'].astype('str').to_numpy()\n \n tokens = [nltk.word_tokenize(text) for text in dataset]\n cleaned_tokens = [self.remove_noise(token, stopwords) for token in tokens]\n \n self.global_processed_model[em] = [(text_dict, em) for text_dict in self.get_tokens_for_model(cleaned_tokens)]\n\n def train_model(self):\n self.process_model()\n\n dataset_for_model = []\n for key in self.global_processed_model.keys():\n dataset_for_model += self.global_processed_model[key]\n \n # random.shuffle(dataset_for_model)\n\n # text_count = (self.df.shape[0] * 80) // 100\n\n # train_data = dataset_for_model[:text_count]\n # test_data = dataset_for_model[text_count:]\n\n # print(\"train data:\", len(train_data))\n # print(\"test data:\", len(test_data))\n\n self.classifier = NaiveBayesClassifier.train(dataset_for_model)\n\n # print(\"Accuracy is:\", classify.accuracy(self.classifier, test_data))\n # print(self.classifier.show_most_informative_features(10))\n \n def classify_message(self, text):\n tokens = self.remove_noise(nltk.tokenize.word_tokenize(text))\n return self.classifier.classify(dict([token, True] for token in tokens))" }, { "alpha_fraction": 0.7906976938247681, "alphanum_fraction": 0.7906976938247681, "avg_line_length": 20.5, "blob_id": "8393cb7aaa48f34363408ad605f0245d90f73243", "content_id": "e7afb761197184985a3d487497875f47eb954e62", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 43, "license_type": "permissive", "max_line_length": 30, "num_lines": 2, "path": "/README.md", "repo_name": "almaszaurbekov/emmessage", "src_encoding": "UTF-8", "text": "# emmessage\ndefine the emotion of the text\n" }, { "alpha_fraction": 0.6822810769081116, "alphanum_fraction": 0.6822810769081116, "avg_line_length": 26.33333396911621, "blob_id": "29d1ae2cfb54e78edd1c5258a2e5b24838ff822c", "content_id": "f667652811dcf147b4f1d5db2fad2f5bd206eb58", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 491, "license_type": "permissive", "max_line_length": 68, "num_lines": 18, "path": "/app/routes.py", "repo_name": "almaszaurbekov/emmessage", "src_encoding": "UTF-8", "text": "from flask import render_template, flash, redirect, request, jsonify\nfrom app import app\nfrom models import Classifier\nimport json\n\nclassifier = Classifier()\n\n@app.route('/')\n@app.route('/index')\ndef index():\n return render_template('index.html', title='Index')\n\n@app.route('/emotion/', methods=['GET', 'POST'])\ndef emotion():\n if request.method == 'POST':\n data = json.loads(request.data)\n value = classifier.classify_message(data['value'])\n return jsonify(value)" }, { "alpha_fraction": 0.4265536665916443, "alphanum_fraction": 0.6723163723945618, "avg_line_length": 14.391304016113281, "blob_id": "3f746427b0f480b9283ec476860b538107d05361", "content_id": "99ba839e6d0673c7a4b0caedcb8fcb8acbfdadbf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 354, "license_type": "permissive", "max_line_length": 24, "num_lines": 23, "path": "/app/requirements.txt", "repo_name": "almaszaurbekov/emmessage", "src_encoding": "UTF-8", "text": "astroid==2.4.2\ncertifi==2020.11.8\nclick==7.1.2\nFlask==1.1.2\nisort==5.5.1\nitsdangerous==1.1.0\nJinja2==2.11.2\njoblib==0.17.0\nlazy-object-proxy==1.4.3\nMarkupSafe==1.1.1\nmccabe==0.6.1\nnltk==3.5\nnumpy==1.19.4\npandas==1.1.4\npylint==2.6.0\npython-dateutil==2.8.1\npytz==2020.4\nregex==2020.11.13\nsix==1.15.0\ntoml==0.10.1\ntqdm==4.54.0\nWerkzeug==1.0.1\nwrapt==1.12.1\n" } ]
5
sunkrock/Circular-Binary-Segmentation
https://github.com/sunkrock/Circular-Binary-Segmentation
8ba44365a37ac017e7c0dcbe5ea7accc5b5b7570
6b97cd1d1d5414658954add9874198acf5a32268
90a2a202fc20f281b7c23d84007adaa17325f641
refs/heads/master
2022-04-12T16:42:42.095827
2020-04-05T07:44:01
2020-04-05T07:44:01
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4468575119972229, "alphanum_fraction": 0.47482725977897644, "avg_line_length": 20.418439865112305, "blob_id": "35eaaa3d683488392a99b0230f4b4e2e756d559f", "content_id": "6bdb473891ecd978655ac0bb24d48d6c3937c848", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3039, "license_type": "no_license", "max_line_length": 88, "num_lines": 141, "path": "/cbs_OLD.py", "repo_name": "sunkrock/Circular-Binary-Segmentation", "src_encoding": "UTF-8", "text": "import sys\nimport numpy as np\nimport math\nimport da\nfrom operator import itemgetter\n\n\"\"\"\nImplementation of task 2 in Computational Genomics assignment 2\nKinsey Reeves 18/05/2018\n695705\n\"\"\"\n\nfinal_segs = []\nZ_THRESH = 10\n\ndef print_segs(segs):\n \n if(segs):\n print(\"SEG A\")\n for i in range(0,len(segs[0])):\n print(str(segs[0][i]) + \" \" + str(i) )\n print(\"SEG B\")\n for i in range(0,len(segs[1])):\n print(str(segs[1][i]) + \" \" + str(i) )\n\ndef print_seg(segs):\n for i in segs:\n print(i)\n\n\ndef get_starts_ends(segment):\n return \n\ndef setup(filename):\n \n f = open(filename, 'r')\n f.readline()\n data = []\n for i in f.readlines():\n line = i.strip('\\n').strip('\\r').split(' ')\n line = [line[0]] + [int(x) for x in line[1:]]\n data.append(line)\n\n #Get the first thirds median\n median = np.median([x[3] for x in data][0:int(len(data)*(1.0/3.0))])\n\n for i in range(0,len(data)):\n lr = (math.log(float(data[i][3])/float(median), 2))\n if lr>2 or lr<-5: lr = 0\n data[i][3] = lr\n return data\n\ndef cbs(data):\n sum_i = 0\n found = False\n best = -1*sys.maxsize\n best_i = 0\n best_j = 0\n\n n = len(data)\n sum_n = sum((x[3] for x in data))\n\n for i in range(0, n-1):\n sum_i += data[idx(i,n)][3]\n sum_j = 0\n\n for j in range(i+1, i+n):\n \n sum_j+=data[idx(j,n)][3]\n z = ( (1.0/(j-i)) + (1.0/(n-j+i)) )**(-1.0/2)\n z*= ( ((sum_j-sum_i)/(j-i)) - ((sum_n-sum_j+sum_i)/(n-j+i))) \n z = abs(z)\n \n if(z>=Z_THRESH):\n found = True\n if(z>best):\n best = z\n best_i = i\n best_j = j\n \n if(found):\n segs = splice(best_i, best_j, data)\n cbs(segs[0])\n cbs(segs[1])\n else:\n \n final_segs.append(data)\n return\n\n#safe index\ndef idx(i, n):\n if(i >= n):\n return i-n\n else:\n return i\n\ndef splice(i, j, data):\n \"\"\"\n safe splice\n input the full dataset and the \n i and j coords and it will circularly \n splice the segment and return two new \n segments\n \"\"\"\n n = len(data)\n out = ()\n splice_a = []\n splice_b = []\n i = idx(i, n)\n j = idx(j, n)\n i+=1\n j+=1\n if(i < j):\n splice_a = data[i:j]\n splice_b = data[j:] + data[0:i]\n else:\n splice_a = data[i:] + data[0:j]\n splice_b = data[j:i]\n\n return (splice_a, splice_b)\n \n\ndata = setup(\"tumor.txt\")\na = cbs(data)\nout = []\nfor segment in final_segs:\n\n avg = sum([x[3] for x in segment])/len(segment)\n #if(abs(avg)>0.1):\n out.append(segment[0][0:2] + [segment[-1][2]] + [avg] + [len(segment)])\n \n for line in segment:\n print(line)\n print(\"\\n\\n\\n\\n\\n\"*30)\n\n\nout = sorted(out, key=itemgetter(1))\n\nfor seg in out:\n \n print(\"{0}\\t{1}\\t{2}\\t{3:.2f}\\t+{4}\".format(seg[0], seg[1], seg[2], seg[3], seg[4]))\n \n\n\n\n\n\n \n\n\n\n\n" }, { "alpha_fraction": 0.8074468374252319, "alphanum_fraction": 0.8095744848251343, "avg_line_length": 71.23076629638672, "blob_id": "3d897d7cd658696f608a584957d4f1c4fe0e10bb", "content_id": "73ced6947b63645ae39bf5f0155142e4db58c91e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 940, "license_type": "no_license", "max_line_length": 450, "num_lines": 13, "path": "/README.md", "repo_name": "sunkrock/Circular-Binary-Segmentation", "src_encoding": "UTF-8", "text": "# Circular-Binary-Segmentation\n\n\nPython implementation of circular binary segmentation in Olshen et als Paper. Segments copy number changes into different intervals along the dataset.\nRecursively cuts segments until no segment can find a Z value greater than the threshold.\n\nFirst, the CBS algorithm splices segments and then recursively searches them for further segments with a sufficient Z value. If it does not find one, it will output this whole segment into a staging array. Secondly, from this array segments are discarded if their average absolute log ratio value is less than 0.1. Finally, we must check for contiguous segments in the output as some segments are circularised and therefore spliced out from others. \n\nPaper : Olshen AB, Circular binary segmentation for the analysis of array-based DNA copy number data. Department of Epidemiology and Biostatistics\n\nUsage:\n\n`python cbs.py <input file> <z-threshold> <outputfile>`\n\n" }, { "alpha_fraction": 0.3450099229812622, "alphanum_fraction": 0.5128883123397827, "avg_line_length": 23.819671630859375, "blob_id": "59896c70fa1c1e49867c8caf4f5b3933153523ca", "content_id": "f4527ddec66d9ba8dddb631f698353b961025219", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1513, "license_type": "no_license", "max_line_length": 299, "num_lines": 61, "path": "/test.py", "repo_name": "sunkrock/Circular-Binary-Segmentation", "src_encoding": "UTF-8", "text": "# # def idx(i, n):\n# # if(i >= n):\n# # return i-n\n# # else:\n# # return i\n\n# # print(2**(-(1/2)))\n\n# # print(1/(2**(1/2)))\n\n# #print(idx(22,10))\n# import math\n# import numpy as np\n\n\n# def setup(filename):\n \n# f = open(filename, 'r')\n# f.readline()\n# data = []\n# for i in f.readlines():\n# line = i.strip('\\n').strip('\\r').split(' ')\n# line = [line[0]] + [int(x) for x in line[1:]]\n# data.append(line)\n\n# median = np.median([x[3] for x in data][0:int(len(data)*(1.0/3.0))])\n\n# for i in range(0,len(data)):\n# lr = (math.log(float(data[i][3])/float(median), 2))\n# if lr>2 or lr<-5: lr = 0\n# data[i][3] = lr\n# return data\n\n# a = setup(\"tumor.txt\")\n\n# b= open(\"out.csv\", \"w\")\n\n# for line in a:\n# b.write(str(line[1]) + \",\" + str(line[3]) + \"\\n\")\n\n\na = [['5', 124600000, 124650000, -1.078771272913028], ['5', 124650000, 124700000, -0.9305780554494941], ['5', 124700000, 124750000, -0.748464040846477],['5', 124600000, 124650000, -1.078771272913028], ['5', 124650000, 124700000, -0.9305780554494941], ['5', 124700000, 124750000, -0.748464040846477]]\n\n\ndef split_segs(seg, num):\n step_size = a[1][1]-a[0][1]\n out_segs = []\n for i in seg:\n i.append(num)\n idx = 0\n for i in range(0, len(seg)-1):\n if(seg[i+1][1] - seg[i][1]!=step_size):\n out_segs.append(seg[idx:i+1])\n idx = i+1\n out_segs.append(seg[idx:])\n \n \n return out_segs\n\n\nprint(split_segs(a,1)[1])" }, { "alpha_fraction": 0.5085858702659607, "alphanum_fraction": 0.5348485112190247, "avg_line_length": 22.087718963623047, "blob_id": "7a4cef809d3e44304fad3fc8f608f8c3768ec0a7", "content_id": "aa7d0ef8637c4e1994cc38949d0900db63d253dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3960, "license_type": "no_license", "max_line_length": 101, "num_lines": 171, "path": "/cbs.py", "repo_name": "sunkrock/Circular-Binary-Segmentation", "src_encoding": "UTF-8", "text": "import sys\nimport numpy as np\nimport math\nimport da\nfrom operator import itemgetter\n\n\n\"\"\"\nImplementation of task 2 in Computational Genomics assignment 2\nKinsey Reeves 18/05/2018. \n695705\n\"\"\"\n\nfinal_segs = []\nZ_THRESH = 8\n\ndef cut_contig_segs(seg, num):\n '''\n If a single segment isn't contiguous it cuts\n it into multiple. This is post-processing\n for the output\n '''\n out_segs = []\n if(len(seg)<=1):\n out_segs.append(seg)\n return output_segs\n step_size = seg[1][1]-seg[0][1]\n \n for i in seg:\n i.append(num)\n idx = 0\n for i in range(0, len(seg)-1):\n if(seg[i+1][1] - seg[i][1]!=step_size):\n out_segs.append(seg[idx:i+1])\n idx = i+1\n out_segs.append(seg[idx:])\n \n return out_segs\n\ndef setup(filename):\n '''\n Reads in the file and outputs a list of lists.\n Each item in the list is a row of the bin data.\n '''\n f = open(filename, 'r')\n f.readline()\n data = []\n for i in f.readlines():\n line = i.strip('\\n').strip('\\r').split(' ')\n line = [line[0]] + [int(x) for x in line[1:]]\n data.append(line)\n\n #Get the first thirds median\n median = np.median([x[3] for x in data][0:int(len(data)*(1.0/3.0))])\n\n for i in range(0,len(data)):\n lr = (math.log(float(data[i][3])/float(median), 2))\n if lr>2 or lr<-5: lr = 0\n data[i][3] = lr\n return data\n\n\ndef precompute_sums(data):\n #Precomputes all sums 0 to n\n sums = []\n sum_i = 0\n \n for bi in data:\n sum_i+=bi[3]\n sums.append(sum_i)\n \n return sums\n\ndef cbs(data):\n '''\n 1. Calculates the segment with highest Z score > thresh.\n If a segment is found it recursively does 1 again.\n Otherwise it outputs the segment to the global final_segs array.\n '''\n sum_i = 0\n found = False\n best = -1*sys.maxsize\n best_i = 0\n best_j = 0\n sums = precompute_sums(data)\n\n n = len(data)\n sum_n = sum((x[3] for x in data))\n\n for i in range(0, n-1):\n sum_i = sums[i]\n sum_j = 0\n\n for j in range(i+1, n):\n \n sum_j = sums[j]\n z = ( (1.0/(j-i)) + (1.0/(n-j+i)) )**(-0.5)\n z*= ( ((sum_j-sum_i)/(j-i)) - ((sum_n-sum_j+sum_i)/(n-j+i))) \n z = abs(z)\n \n if(z>=Z_THRESH):\n\n found = True\n if(z>best):\n best = z\n best_i = i\n best_j = j\n if(found):\n segs = splice(best_i, best_j, data)\n cbs(segs[0])\n cbs(segs[1])\n else:\n final_segs.append(data)\n\n\ndef splice(i, j, data):\n \"\"\"\n safe splice\n input the full dataset and the \n i and j coords and it will circularly \n splice the segment and return two new \n segments\n \"\"\"\n n = len(data)\n splice_a = []\n splice_b = []\n i+=1\n j+=1\n splice_a = data[i:j]\n splice_b = data[j:] + data[0:i]\n\n return (splice_a, splice_b)\n \n# Start of program\n\nif(len(sys.argv) < 4):\n print(\"Usage: python cbs.py <input bins> <Z_thresh> <output file>\")\n exit(0)\nelse:\n input_file = sys.argv[1]\n Z_THRESH = int(sys.argv[2])\n output_file = sys.argv[3]\n\noutput_file = open(output_file, \"w\")\ndata = setup(\"tumor.txt\")\nstep_size = data[0][2] - data[0][1]\n\ncbs(data)\noutput_segs = []\n\nidx = 0\n#We now need to cut segments so the indexes don't overlap\nfor j in final_segs:\n output_segs += cut_contig_segs(j, idx)\n idx+=1\n\noutput_segs.sort(key=lambda x: x[0][1])\nout = []\n\n#Get it into a format as given\nfor segment in output_segs:\n\n avg = sum([x[3] for x in segment])/len(segment)\n if(abs(avg)>0.1):\n out.append(segment[0][0:2] + [segment[-1][2]] + [avg] + [segment[0][-1]] + [len(segment)])\n\noutput_file.write(\"CHR\\tSTART\\tEND\\tRATIO\\tSEG NO.\\n\")\nfor seg in out:\n output_file.write(\"{0}\\t{1}\\t{2}\\t{3:.2f}\\t{4}\\n\".format(seg[0], seg[1], seg[2], seg[3], seg[4]))\n\noutput_file.close()\n\n\n\n \n\n\n\n\n" } ]
4
heurteph/PathOfEsthesia
https://github.com/heurteph/PathOfEsthesia
daa602296adaf4abad736b6b8550c2a1eae1b2ac
c269f788cfa2b2c7512fe40a0b94b9f212a8e325
b88786a3766c0559652db9c4585afc284eb063a7
refs/heads/main
2023-02-17T04:20:18.802162
2021-01-14T22:50:23
2021-01-14T22:50:23
329,541,870
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6050704121589661, "alphanum_fraction": 0.6155868768692017, "avg_line_length": 25.361385345458984, "blob_id": "2c5c060e6cb1f4aa9ea084873927e62086cfa315", "content_id": "b6ba00e6ef27ba5638bc0a892bddd5a626ca8f38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5327, "license_type": "no_license", "max_line_length": 112, "num_lines": 202, "path": "/SoA-Unity/Assets/Scripts/Animations/EsthesiaAnimation.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class EsthesiaAnimation : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The reference to the player\")]\n private GameObject player;\n\n [SerializeField]\n [Tooltip(\"Duration of the transition from idle to walk in seconds\")]\n [Range(0.01f, 0.5f)]\n private float idleToWalkDuration = 0.2f; // s\n\n [SerializeField]\n [Tooltip(\"Duration of the transition from walk to idle in seconds\")]\n [Range(0.01f,0.5f)]\n private float walkToIdleDuration = 0.05f; // s\n\n [SerializeField]\n [Tooltip(\"Minimum delay in seconds between two damage animation\")]\n [Range(1, 3)]\n private float delayBetweenDamages;\n private float delay = 0;\n\n [Header(\"Eyes set\")]\n [Space]\n [SerializeField]\n [Tooltip(\"The model of the calm eyes\")]\n private GameObject eyesCalm;\n [SerializeField]\n [Tooltip(\"The model of the happy eyes\")]\n private GameObject eyesHappy;\n [SerializeField]\n [Tooltip(\"The model of the neutral eyes\")]\n private GameObject eyesNeutral;\n [SerializeField]\n [Tooltip(\"The model of the pain eyes\")]\n private GameObject eyesPain;\n [SerializeField]\n [Tooltip(\"The model of the worried eyes\")]\n private GameObject eyesWorry;\n\n private void Awake()\n {\n InitializeAnimationLayers();\n GetComponent<Animator>().SetBool(\"IsDamageAvailable\", true);\n }\n\n // Start is called before the first frame update\n void Start()\n {\n SetEyesNeutral();\n\n if (player == null)\n {\n throw new System.NullReferenceException(\"No reference to the player set in FinishAnimation script\");\n }\n }\n\n // Update is called once per frame\n void Update()\n {\n\n }\n\n public void FinishedDamageAnimation()\n {\n GetComponent<Animator>().SetBool(\"IsDamageAvailable\", false);\n delay = delayBetweenDamages;\n StartCoroutine(\"StartNextDamageAnimationDelay\");\n //player.GetComponent<PlayerFirst>().IsDamagedEars = false;\n //SelectAnimationLayer(0);\n }\n\n /*\n public void SelectBaseLayer()\n {\n SelectAnimationLayer(0);\n }\n\n public void SelectEyesDamageLayer()\n {\n SelectAnimationLayer(1);\n }\n\n public void SelectEarsDamageLayer()\n {\n SelectAnimationLayer(2);\n }\n\n private void SelectAnimationLayer(int index)\n {\n GetComponent<Animator>().SetLayerWeight(0, index == 0 ? 1 : 0);\n GetComponent<Animator>().SetLayerWeight(1, index == 1 ? 1 : 0);\n GetComponent<Animator>().SetLayerWeight(2, index == 2 ? 1 : 0);\n }\n */\n\n public void InitializeAnimationLayers()\n {\n GetComponent<Animator>().SetLayerWeight(0, 1);\n GetComponent<Animator>().SetLayerWeight(1, 0);\n }\n\n public void SelectIdleLayer()\n {\n if (GetComponent<Animator>().GetLayerWeight(1) == 1)\n {\n StartCoroutine(\"WalkToIdleTransition\");\n }\n }\n\n public void SelectWalkLayer()\n {\n if (GetComponent<Animator>().GetLayerWeight(0) == 1)\n {\n StartCoroutine(\"IdleToWalkTransition\");\n }\n }\n\n private IEnumerator IdleToWalkTransition()\n {\n float weight = 0;\n while(weight < 1)\n {\n weight = Mathf.Min(weight + Time.deltaTime / idleToWalkDuration, 1f);\n GetComponent<Animator>().SetLayerWeight(0, 1 - weight);\n GetComponent<Animator>().SetLayerWeight(1, weight);\n yield return null;\n }\n }\n\n private IEnumerator WalkToIdleTransition()\n {\n float weight = 0;\n while (weight < 1)\n {\n weight = Mathf.Min(weight + Time.deltaTime / walkToIdleDuration, 1f);\n GetComponent<Animator>().SetLayerWeight(0, weight);\n GetComponent<Animator>().SetLayerWeight(1, 1 - weight);\n yield return null;\n }\n }\n\n private IEnumerator StartNextDamageAnimationDelay()\n {\n while (delay > 0)\n {\n delay = Mathf.Max(delay - Time.deltaTime, 0);\n yield return null;\n }\n GetComponent<Animator>().SetBool(\"IsDamageAvailable\", true);\n }\n\n private void SetEyesCalm()\n {\n eyesCalm.SetActive(true);\n eyesHappy.SetActive(false);\n eyesNeutral.SetActive(false);\n eyesPain.SetActive(false);\n eyesWorry.SetActive(false);\n }\n\n private void SetEyesHappy()\n {\n eyesCalm.SetActive(false);\n eyesHappy.SetActive(true);\n eyesNeutral.SetActive(false);\n eyesPain.SetActive(false);\n eyesWorry.SetActive(false);\n }\n\n private void SetEyesNeutral()\n {\n eyesCalm.SetActive(false);\n eyesHappy.SetActive(false);\n eyesNeutral.SetActive(true);\n eyesPain.SetActive(false);\n eyesWorry.SetActive(false);\n }\n\n private void SetEyesPain()\n {\n eyesCalm.SetActive(false);\n eyesHappy.SetActive(false);\n eyesNeutral.SetActive(false);\n eyesPain.SetActive(true);\n eyesWorry.SetActive(false);\n }\n\n private void SetEyesWorry()\n {\n eyesCalm.SetActive(false);\n eyesHappy.SetActive(false);\n eyesNeutral.SetActive(false);\n eyesPain.SetActive(false);\n eyesWorry.SetActive(true);\n }\n\n} //FINISH\n" }, { "alpha_fraction": 0.6474428772926331, "alphanum_fraction": 0.6615886688232422, "avg_line_length": 25.257143020629883, "blob_id": "5b8044ffa98f8f0eef71757cb7dca5154e96498d", "content_id": "ee5806d6b48fcfc24994d3abb6bf5e95b569b7fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 921, "license_type": "no_license", "max_line_length": 105, "num_lines": 35, "path": "/SoA-Unity/Assets/LevelStreets/Scripts/AirConditionner.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\n\npublic class AirConditionner : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The mesh of the fan's blades\")]\n private GameObject fanBlades;\n\n [SerializeField]\n [Tooltip(\"The speed of the fan's blades\")]\n [Range(0,1000)]\n private float fanSpeed = 500;\n\n private float fanRotation;\n\n // Start is called before the first frame update\n void Start()\n {\n if(fanBlades == null)\n {\n throw new System.NullReferenceException(\"No blades set for the fan of the air conditionner\");\n }\n fanRotation = fanBlades.transform.localRotation.eulerAngles.y;\n }\n\n // Update is called once per frame\n void Update()\n {\n fanRotation = (fanRotation + fanSpeed * Time.deltaTime) % 360;\n fanBlades.transform.localRotation = Quaternion.Euler(0, 0, fanRotation);\n }\n}\n" }, { "alpha_fraction": 0.5862628221511841, "alphanum_fraction": 0.5862628221511841, "avg_line_length": 25.797101974487305, "blob_id": "519291ff5ca723549018c42d72055a991bee32e1", "content_id": "e780e1173795857091d028ce9fa473fe36e6e5db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1851, "license_type": "no_license", "max_line_length": 77, "num_lines": 69, "path": "/SoA-Unity/Assets/Scripts/Managers/ZoneManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing AK.Wwise;\n\npublic class ZoneManager : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The list of sounds to mute when quitting the park\")]\n private GameObject[] parkSounds;\n\n [SerializeField]\n [Tooltip(\"The list of sounds to mute when entering the park\")]\n private GameObject[] roadSounds;\n\n public enum ZONE { TUTORIAL, ROADS, PARK, RESIDENCES, DOWNTOWN, MARKET };\n private ZONE playerZone;\n public ZONE PlayerZone { get { return playerZone; } }\n\n // Start is called before the first frame update\n void Start()\n {\n playerZone = ZONE.TUTORIAL;\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n private void OnTriggerEnter(Collider other)\n {\n if (other.CompareTag(\"Player\"))\n {\n playerZone = ZONE.PARK;\n\n // activate park sounds\n foreach (GameObject parkSound in parkSounds)\n {\n parkSound.GetComponent<PostWwiseEventObstacle>().Play();\n }\n // deactivate road sounds\n foreach (GameObject roadSound in roadSounds)\n {\n roadSound.GetComponent<PostWwiseEventObstacle>().Stop();\n }\n }\n }\n\n private void OnTriggerExit(Collider other)\n {\n playerZone = ZONE.ROADS;\n\n if (other.CompareTag(\"Player\"))\n {\n // deactivate park sounds\n foreach (GameObject parkSound in parkSounds)\n {\n parkSound.GetComponent<PostWwiseEventObstacle>().Stop();\n }\n // activate road sounds\n foreach (GameObject roadSound in roadSounds)\n {\n roadSound.GetComponent<PostWwiseEventObstacle>().Play();\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6373801827430725, "alphanum_fraction": 0.6373801827430725, "avg_line_length": 20.586206436157227, "blob_id": "a269c9f79079393c191dbde8e61e666de6839186", "content_id": "ecff341968a33bcb521a9030625adaa5f4b31905", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 628, "license_type": "no_license", "max_line_length": 82, "num_lines": 29, "path": "/SoA-Unity/Assets/Scripts/Menus/Fade.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Fade : MonoBehaviour\n{\n GameObject menuManager;\n\n // Start is called before the first frame update\n void Start()\n {\n menuManager = GameObject.FindGameObjectWithTag(\"MenuManager\");\n if (menuManager == null)\n {\n throw new System.NullReferenceException(\"Missing MenuManager object\");\n }\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n public void OnAnimationFinish()\n {\n menuManager.GetComponent<MenuManager>().StartGame();\n }\n}\n" }, { "alpha_fraction": 0.5239397883415222, "alphanum_fraction": 0.5239397883415222, "avg_line_length": 19.885713577270508, "blob_id": "a7be5f199e199b35366bfca3decf4bdfbe01d8c1", "content_id": "5cadab2ca6f1dcebcdfc9da8ab3e0102ba6eb089", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 733, "license_type": "no_license", "max_line_length": 54, "num_lines": 35, "path": "/SoA-Unity/Assets/Scripts/Cutscene/Story.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\nnamespace story\n{\n [System.Serializable]\n public class Story\n {\n public List<Scene> scenes;\n\n [System.Serializable]\n public class Scene\n {\n public List<Action> actions;\n\n [System.Serializable]\n public class Action\n {\n public string type;\n public string metadata;\n public string data;\n };\n };\n\n public Story(string text)\n {\n Deserialize(text);\n }\n public void Deserialize(string text)\n {\n JsonUtility.FromJsonOverwrite(text, this);\n }\n }\n}\n" }, { "alpha_fraction": 0.6170903444290161, "alphanum_fraction": 0.6230394840240479, "avg_line_length": 30.355932235717773, "blob_id": "31a0b93a531a26ec9e24f9e035b59dda544bd755", "content_id": "4379e8724b726f25eb7c96105054ec27c6dc56f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1851, "license_type": "no_license", "max_line_length": 92, "num_lines": 59, "path": "/SoA-Unity/Assets/LevelPark/Scripts/Placements/SpawnBarriers.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "/*\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing Pixelplacement;\n\npublic class SpawnBarriers : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The model of the barrier to spawn\")]\n private GameObject barrierPrefab;\n\n [SerializeField]\n [Tooltip(\"The spline used to spawn the barriers\")]\n private Spline spline;\n\n [SerializeField]\n private Vector3 rotationFixer;\n private Quaternion qRotationFixer;\n\n // Start is called before the first frame update\n void Start()\n {\n if (barrierPrefab == null)\n {\n throw new System.NullReferenceException(\"No prefab set for the barrier\");\n }\n if (spline == null)\n {\n throw new System.NullReferenceException(\"No spline set for the barriers\");\n }\n\n float startPercent = 0.01f;\n float endPercent;\n int i = 0;\n while(i < 10)\n {\n qRotationFixer = Quaternion.Euler(rotationFixer);\n Vector3 startPos = spline.GetPosition(startPercent);\n Vector3 barrierEnd = startPos + spline.GetDirection(startPercent) * 2;\n Debug.Log(\"DIRECTION : \" + spline.GetDirection(startPercent));\n endPercent = spline.ClosestPoint(barrierEnd);\n Vector3 endPos = spline.GetPosition(endPercent);\n Quaternion rot = qRotationFixer * Quaternion.LookRotation(endPos - startPos);\n GameObject barrier = Object.Instantiate(barrierPrefab, startPos, rot);\n barrier.transform.SetParent(transform, true);\n barrier.name = \"Barrier\" + i++.ToString();\n Debug.Log(barrier.name + \", start : \" + startPercent + \", end : \" + endPercent);\n startPercent = endPercent;\n }\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n}\n*/" }, { "alpha_fraction": 0.524489164352417, "alphanum_fraction": 0.6511131525039673, "avg_line_length": 44.16529083251953, "blob_id": "1c00cc0faaf8cbf80f5a4cff4371b33b7ea13c39", "content_id": "1c488eae28c0119297af1d5a30273678b2d0d6ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 16395, "license_type": "no_license", "max_line_length": 101, "num_lines": 363, "path": "/SoA-Unity/Assets/StreamingAssets/Audio/GeneratedSoundBanks/Wwise_IDs.h", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// Audiokinetic Wwise generated include file. Do not edit.\n//\n/////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef __WWISE_IDS_H__\n#define __WWISE_IDS_H__\n\n#include <AK/SoundEngine/Common/AkTypes.h>\n\nnamespace AK\n{\n namespace EVENTS\n {\n static const AkUniqueID PLAY_ARROSAGEAUTO = 3389613819U;\n static const AkUniqueID PLAY_BATTEMENT_COEUR = 235882589U;\n static const AkUniqueID PLAY_BRANCHES_TOMBENT = 2412280354U;\n static const AkUniqueID PLAY_BUS_DOOR_CLOSE = 3232482810U;\n static const AkUniqueID PLAY_BUS_DOOR_OPEN = 2983975038U;\n static const AkUniqueID PLAY_CANARD = 932140571U;\n static const AkUniqueID PLAY_CLAVIER_ASSIGNATION = 1218834549U;\n static const AkUniqueID PLAY_CLAVIER_SUPPRESSION = 4009602722U;\n static const AkUniqueID PLAY_CLIC_SELECTION = 3735763388U;\n static const AkUniqueID PLAY_CLIMATISEUR = 1692441862U;\n static const AkUniqueID PLAY_CRIS_TOUS = 2464503011U;\n static const AkUniqueID PLAY_ECOLE = 1753498456U;\n static const AkUniqueID PLAY_ECRITURE_ANIMATION = 4276677556U;\n static const AkUniqueID PLAY_ECRITURE_ANIMATION_ANGE = 3584937418U;\n static const AkUniqueID PLAY_EGOUT = 869276618U;\n static const AkUniqueID PLAY_ELECTRIQUE_BUZZ = 2500875145U;\n static const AkUniqueID PLAY_HORLOGE = 1086738306U;\n static const AkUniqueID PLAY_HUMAIN_MANGE1 = 3446893022U;\n static const AkUniqueID PLAY_HUMAIN_MANGE2 = 3446893021U;\n static const AkUniqueID PLAY_KLAXONS = 2894920242U;\n static const AkUniqueID PLAY_MARTEAU_PIQUEUR = 3516174833U;\n static const AkUniqueID PLAY_MESSAGES_RADIO = 3366277958U;\n static const AkUniqueID PLAY_MORT = 1615608444U;\n static const AkUniqueID PLAY_MOTEUR_ELAGUEUR = 2314452061U;\n static const AkUniqueID PLAY_MOTEUR_VOITUREELEC = 1403256204U;\n static const AkUniqueID PLAY_MUSIC_APPART = 1625096966U;\n static const AkUniqueID PLAY_MUSIC_CINEMATIQUE = 3134804369U;\n static const AkUniqueID PLAY_MUSIC_CREDIT = 2851404393U;\n static const AkUniqueID PLAY_MUSIC_MAIN_TITLE = 3783189458U;\n static const AkUniqueID PLAY_MUSIC_MENU = 1699343283U;\n static const AkUniqueID PLAY_MUSIC_SAFE_ZONE_HOME = 283912148U;\n static const AkUniqueID PLAY_MUSIC_SAFE_ZONE_PARC = 4079445273U;\n static const AkUniqueID PLAY_MUSIC_SAFE_ZONE_VILLE = 3326642619U;\n static const AkUniqueID PLAY_PARC_CHIEN = 4134052420U;\n static const AkUniqueID PLAY_PARC_EAU_LAC = 865874921U;\n static const AkUniqueID PLAY_PARC_JARDINIER = 1074315535U;\n static const AkUniqueID PLAY_PARC_OISEAUX1 = 3725651506U;\n static const AkUniqueID PLAY_PARC_OISEAUX2 = 3725651505U;\n static const AkUniqueID PLAY_PARC_OISEAUX3 = 3725651504U;\n static const AkUniqueID PLAY_PARC_VENT = 4135899644U;\n static const AkUniqueID PLAY_PIGEON = 2968327968U;\n static const AkUniqueID PLAY_PIGEON_FIXE = 1479939285U;\n static const AkUniqueID PLAY_PLEURE_B_B_ = 4114146970U;\n static const AkUniqueID PLAY_PORTES_CLOSE = 11904902U;\n static const AkUniqueID PLAY_PORTES_GRANDE = 540531537U;\n static const AkUniqueID PLAY_PORTES_OPEN = 2755465042U;\n static const AkUniqueID PLAY_QUEL_MOTEUR = 3518090694U;\n static const AkUniqueID PLAY_RESPIRATION_JOGGUEURF = 1582928683U;\n static const AkUniqueID PLAY_RESPIRATION_JOGGUEURH = 1582928677U;\n static const AkUniqueID PLAY_RESPIRATION_MOUVEMENT = 2860278991U;\n static const AkUniqueID PLAY_RESTORANT = 3628354934U;\n static const AkUniqueID PLAY_SHELTER_BAR_DOOR_CLOSE = 2500736103U;\n static const AkUniqueID PLAY_SHELTER_BAR_DOOR_OPEN = 4211204369U;\n static const AkUniqueID PLAY_SHELTER_HOUSE_DOOR_CLOSE = 736905070U;\n static const AkUniqueID PLAY_SHELTER_HOUSE_DOOR_OPEN = 3075461546U;\n static const AkUniqueID PLAY_SHELTER_PARC_DOOR_CLOSE = 1128126858U;\n static const AkUniqueID PLAY_SHELTER_PARC_DOOR_OPEN = 2116268718U;\n static const AkUniqueID PLAY_SONNETTE_MAGASINS = 2056330270U;\n static const AkUniqueID PLAY_SURVOL = 2105670071U;\n static const AkUniqueID PLAY_TEXTE_ANIM_PARTICULE = 1410339968U;\n static const AkUniqueID PLAY_TEXTURE_PAS = 1047604054U;\n static const AkUniqueID PLAY_TEXTURE_PAS_JOGGER = 482787459U;\n static const AkUniqueID PLAY_TOUCHE_NEXT = 3029881444U;\n static const AkUniqueID PLAY_TRAVAUX = 3782749553U;\n static const AkUniqueID STOP_ALL = 452547817U;\n static const AkUniqueID STOP_ARROSAGEAUTO = 1056565793U;\n static const AkUniqueID STOP_BATTEMENT_COEUR = 383440519U;\n static const AkUniqueID STOP_BRANCHES_TOMBENT = 3668248268U;\n static const AkUniqueID STOP_CANARD = 777875661U;\n static const AkUniqueID STOP_CLAVIER_ASSIGNATION = 3625929623U;\n static const AkUniqueID STOP_CLAVIER_SUPPRESSION = 290161972U;\n static const AkUniqueID STOP_CLIC_SELECTION = 4123225286U;\n static const AkUniqueID STOP_CLIMATISEUR = 1059727820U;\n static const AkUniqueID STOP_ECOLE = 3267333498U;\n static const AkUniqueID STOP_ECRITURE_ANIMATION = 4063390670U;\n static const AkUniqueID STOP_ECRITURE_ANIMATION_ANGE = 426032660U;\n static const AkUniqueID STOP_EGOUT = 623032412U;\n static const AkUniqueID STOP_ELECTRIQUE_BUZZ = 4256011363U;\n static const AkUniqueID STOP_HORLOGE = 725970268U;\n static const AkUniqueID STOP_KLAXONS = 882878844U;\n static const AkUniqueID STOP_MARTEAU_PIQUEUR = 2738893335U;\n static const AkUniqueID STOP_MESSAGES_RADIO = 4004627752U;\n static const AkUniqueID STOP_MORT = 2980414578U;\n static const AkUniqueID STOP_MOTEUR_ELAGUEUR = 1194390427U;\n static const AkUniqueID STOP_MUSIC_APPART = 3531521436U;\n static const AkUniqueID STOP_MUSIC_CINEMATIQUE = 654722903U;\n static const AkUniqueID STOP_MUSIC_CREDIT = 3425086499U;\n static const AkUniqueID STOP_MUSIC_MAIN_TITLE = 3194051996U;\n static const AkUniqueID STOP_MUSIC_MENU = 106912753U;\n static const AkUniqueID STOP_MUSIC_SAFE_ZONE_HOME = 2216282302U;\n static const AkUniqueID STOP_MUSIC_SAFE_ZONE_PARC = 3084927191U;\n static const AkUniqueID STOP_MUSIC_SAFE_ZONE_VILLE = 566110305U;\n static const AkUniqueID STOP_PARC_CHIEN = 2301453854U;\n static const AkUniqueID STOP_PARC_EAU_LAC = 3189001139U;\n static const AkUniqueID STOP_PARC_JARDINIER = 358162889U;\n static const AkUniqueID STOP_PARC_OISEAUX1 = 152275144U;\n static const AkUniqueID STOP_PARC_OISEAUX2 = 152275147U;\n static const AkUniqueID STOP_PARC_OISEAUX3 = 152275146U;\n static const AkUniqueID STOP_PARC_VENT = 2647100474U;\n static const AkUniqueID STOP_PIGEON = 2048920818U;\n static const AkUniqueID STOP_PIGEON_FIXE = 2447347043U;\n static const AkUniqueID STOP_PLEURE_B_B_ = 1235857404U;\n static const AkUniqueID STOP_PORTES_CLOSE = 394956184U;\n static const AkUniqueID STOP_PORTES_GRANDE = 3373826511U;\n static const AkUniqueID STOP_PORTES_OPEN = 2216609116U;\n static const AkUniqueID STOP_QUEL_MOTEUR = 3507864100U;\n static const AkUniqueID STOP_RESTORANT = 970688548U;\n static const AkUniqueID STOP_SHELTER_BAR_DOOR_CLOSE = 2099532353U;\n static const AkUniqueID STOP_SHELTER_BAR_DOOR_OPEN = 3374793443U;\n static const AkUniqueID STOP_SHELTER_HOUSE_DOOR_CLOSE = 2784745848U;\n static const AkUniqueID STOP_SHELTER_HOUSE_DOOR_OPEN = 1068587196U;\n static const AkUniqueID STOP_SHELTER_PARC_DOOR_CLOSE = 3420555944U;\n static const AkUniqueID STOP_SHELTER_PARC_DOOR_OPEN = 788503180U;\n static const AkUniqueID STOP_SONNETTE_MAGASINS = 3549513284U;\n static const AkUniqueID STOP_SURVOL = 507140941U;\n static const AkUniqueID STOP_TEXTE_ANIM_PARTICULE = 2148170426U;\n static const AkUniqueID STOP_TOUCHE_NEXT = 1246565790U;\n static const AkUniqueID STOP_TRAVAUX = 2077251707U;\n } // namespace EVENTS\n\n namespace STATES\n {\n namespace DANS_LIEU_REPOS\n {\n static const AkUniqueID GROUP = 3986250553U;\n\n namespace STATE\n {\n static const AkUniqueID NON = 544973834U;\n static const AkUniqueID NONE = 748895195U;\n static const AkUniqueID OUI = 645492566U;\n } // namespace STATE\n } // namespace DANS_LIEU_REPOS\n\n namespace DANS_TUNNEL\n {\n static const AkUniqueID GROUP = 3460032738U;\n\n namespace STATE\n {\n static const AkUniqueID NON = 544973834U;\n static const AkUniqueID NONE = 748895195U;\n static const AkUniqueID OUI = 645492566U;\n } // namespace STATE\n } // namespace DANS_TUNNEL\n\n namespace MENU_OUI_NON\n {\n static const AkUniqueID GROUP = 2551007772U;\n\n namespace STATE\n {\n static const AkUniqueID MENU_NON = 2651242748U;\n static const AkUniqueID MENU_OUI = 2818768592U;\n static const AkUniqueID NONE = 748895195U;\n } // namespace STATE\n } // namespace MENU_OUI_NON\n\n namespace PROTECTION_OUI_NON\n {\n static const AkUniqueID GROUP = 2773598748U;\n\n namespace STATE\n {\n static const AkUniqueID ACTIVE = 58138747U;\n static const AkUniqueID NONE = 748895195U;\n static const AkUniqueID PAS_ACTIVE = 2270773720U;\n } // namespace STATE\n } // namespace PROTECTION_OUI_NON\n\n } // namespace STATES\n\n namespace SWITCHES\n {\n namespace COURT_MARCHE\n {\n static const AkUniqueID GROUP = 4156334155U;\n\n namespace SWITCH\n {\n static const AkUniqueID COURT = 2871560606U;\n static const AkUniqueID IDLE = 1874288895U;\n static const AkUniqueID MARCHE = 1630799659U;\n } // namespace SWITCH\n } // namespace COURT_MARCHE\n\n namespace DROIT_GAUCHE\n {\n static const AkUniqueID GROUP = 3079589013U;\n\n namespace SWITCH\n {\n static const AkUniqueID DROIT = 2723061045U;\n static const AkUniqueID GAUCHE = 1211705900U;\n } // namespace SWITCH\n } // namespace DROIT_GAUCHE\n\n namespace ETATVOITURE\n {\n static const AkUniqueID GROUP = 3645350675U;\n\n namespace SWITCH\n {\n static const AkUniqueID A_STOP = 129212061U;\n static const AkUniqueID B_DEMARRE = 2409485060U;\n static const AkUniqueID C_IDLE = 1094992157U;\n static const AkUniqueID D_ACCELERE = 4192991124U;\n } // namespace SWITCH\n } // namespace ETATVOITURE\n\n namespace KLAXONS\n {\n static const AkUniqueID GROUP = 310721727U;\n\n namespace SWITCH\n {\n static const AkUniqueID A = 84696446U;\n static const AkUniqueID B = 84696445U;\n static const AkUniqueID C = 84696444U;\n static const AkUniqueID D = 84696443U;\n static const AkUniqueID E = 84696442U;\n } // namespace SWITCH\n } // namespace KLAXONS\n\n namespace PAS_MATIERE\n {\n static const AkUniqueID GROUP = 3869192313U;\n\n namespace SWITCH\n {\n static const AkUniqueID ASPHALT = 4169408098U;\n static const AkUniqueID BETON = 386080821U;\n static const AkUniqueID HERBE = 2495190089U;\n static const AkUniqueID TERRE = 508852877U;\n } // namespace SWITCH\n } // namespace PAS_MATIERE\n\n namespace QUEL_MOTEUR\n {\n static const AkUniqueID GROUP = 2782977595U;\n\n namespace SWITCH\n {\n static const AkUniqueID M1 = 1685527111U;\n static const AkUniqueID M2_MOTO = 3872364728U;\n static const AkUniqueID M3 = 1685527109U;\n static const AkUniqueID M4 = 1685527106U;\n static const AkUniqueID M5 = 1685527107U;\n static const AkUniqueID M6_CAMION = 1022333622U;\n static const AkUniqueID M7_CAMION = 2804710365U;\n static const AkUniqueID M8 = 1685527118U;\n static const AkUniqueID M9_BUS = 3057612808U;\n } // namespace SWITCH\n } // namespace QUEL_MOTEUR\n\n namespace QUELLE_VOIX\n {\n static const AkUniqueID GROUP = 907988530U;\n\n namespace SWITCH\n {\n static const AkUniqueID VOIX_01 = 3348087211U;\n static const AkUniqueID VOIX_02 = 3348087208U;\n static const AkUniqueID VOIX_03 = 3348087209U;\n static const AkUniqueID VOIX_04 = 3348087214U;\n static const AkUniqueID VOIX_05 = 3348087215U;\n } // namespace SWITCH\n } // namespace QUELLE_VOIX\n\n namespace QUI_PARLE\n {\n static const AkUniqueID GROUP = 3375628365U;\n\n namespace SWITCH\n {\n static const AkUniqueID ENFANT = 2779435313U;\n static const AkUniqueID FEMME = 1494689069U;\n static const AkUniqueID HOMME = 4152857849U;\n } // namespace SWITCH\n } // namespace QUI_PARLE\n\n namespace RESPIRATION_EX_OR_IN\n {\n static const AkUniqueID GROUP = 3885082437U;\n\n namespace SWITCH\n {\n static const AkUniqueID EXPIRE = 3370304008U;\n static const AkUniqueID INSPIRE = 567704981U;\n } // namespace SWITCH\n } // namespace RESPIRATION_EX_OR_IN\n\n } // namespace SWITCHES\n\n namespace GAME_PARAMETERS\n {\n static const AkUniqueID QUEL_MOTEUR = 2782977595U;\n static const AkUniqueID RALENTI_ACCELERE = 731750351U;\n static const AkUniqueID VITESSEVEHICULE = 3154243729U;\n static const AkUniqueID VITESSEVOITUREELEC = 428373397U;\n static const AkUniqueID VOLUMEECOUTEPERSO = 133973669U;\n } // namespace GAME_PARAMETERS\n\n namespace BANKS\n {\n static const AkUniqueID INIT = 1355168291U;\n static const AkUniqueID SOUNDBANKPC = 3163481603U;\n } // namespace BANKS\n\n namespace BUSSES\n {\n static const AkUniqueID CINEMATIQUE_MASTER = 2082484861U;\n static const AkUniqueID ENVI_COMMERCE = 772085263U;\n static const AkUniqueID ENVI_PARC = 4151145406U;\n static const AkUniqueID ENVI_VILLE = 3541955170U;\n static const AkUniqueID ENVIRONNEMENT_MASTER = 766198208U;\n static const AkUniqueID MASTER_AUDIO_BUS = 3803692087U;\n static const AkUniqueID MENU_MASTER = 2632566393U;\n static const AkUniqueID MIX_REVERB = 3296604463U;\n static const AkUniqueID MIXPROTECTION = 2740603104U;\n static const AkUniqueID MUSIC_MASTER = 3595451983U;\n static const AkUniqueID NIVEAUECOUTEPERSO = 2734641465U;\n static const AkUniqueID OBSTACLES_COMMERCE = 3564875249U;\n static const AkUniqueID OBSTACLES_MASTER = 1006333898U;\n static const AkUniqueID OBSTACLES_PARC = 3370572728U;\n static const AkUniqueID OBSTACLES_VILLE = 731600268U;\n static const AkUniqueID PERSO_ESTHESIA = 1643398137U;\n static const AkUniqueID PERSO_NPC = 1407902352U;\n static const AkUniqueID PERSONNAGES_MASTER = 1655596517U;\n } // namespace BUSSES\n\n namespace AUX_BUSSES\n {\n static const AkUniqueID EQ_PROTECTION = 3971758071U;\n static const AkUniqueID MIXECOUTEPERSO = 2093609463U;\n static const AkUniqueID REVERB_LIEU_REPOS = 3204322453U;\n static const AkUniqueID REVERB_TUNNEL = 2261546958U;\n } // namespace AUX_BUSSES\n\n namespace AUDIO_DEVICES\n {\n static const AkUniqueID NO_OUTPUT = 2317455096U;\n static const AkUniqueID SYSTEM = 3859886410U;\n } // namespace AUDIO_DEVICES\n\n}// namespace AK\n\n#endif // __WWISE_IDS_H__\n" }, { "alpha_fraction": 0.5734605193138123, "alphanum_fraction": 0.5817436575889587, "avg_line_length": 29.412214279174805, "blob_id": "7af3047b63da7233614fd84f7b914312441964af", "content_id": "3477d7c155905a62ac87aadec95c48f8fb099351", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 11954, "license_type": "no_license", "max_line_length": 116, "num_lines": 393, "path": "/SoA-Unity/Assets/Scripts/Cutscene/MessagesManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing TMPro;\nusing UnityEngine;\nusing UnityEngine.UI;\nusing story;\nusing System.Text.RegularExpressions;\nusing UnityEngine.InputSystem;\n\npublic class MessagesManager : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The cutscene manager\")]\n private GameObject cutsceneManager;\n\n public delegate void MessageHandler();\n public event MessageHandler MessageShownEvent;\n\n //private string text;\n\n public delegate IEnumerator DisplayMessage(string text);\n DisplayMessage del;\n\n [Space]\n\n [SerializeField]\n [Tooltip(\"The message box\")]\n private TextMeshProUGUI messageBoxLower;\n\n [SerializeField]\n [Tooltip(\"The header of the message box\")]\n private Text nameBoxLower;\n\n [Space]\n\n [SerializeField]\n [Tooltip(\"The message box\")]\n private TextMeshProUGUI messageBoxUpper;\n\n [SerializeField]\n [Tooltip(\"The header of the message box\")]\n private Text nameBoxUpper;\n\n [SerializeField]\n [Tooltip(\"The skip button of the message box\")]\n private Image skipButton;\n\n [SerializeField]\n [Tooltip(\"The vibrations of the message\")]\n private ParticleSystem vibrations;\n private ParticleSystem.EmissionModule emissionModule;\n\n [Space]\n [Header(\"Message Animation Options\")]\n\n [SerializeField]\n [Tooltip(\"The delay between two letters\")]\n [Range(1,5)]\n private float messageSpeed = 1;\n\n [SerializeField]\n [Tooltip(\"The number of characters appearing at the same time\")]\n [Range(1, 10)]\n private float rolloverCharacterSpread = 5;\n\n [SerializeField]\n [Tooltip(\"How long it takes for a message to start appearing\")]\n [Range(0f, 5)]\n private float preMessageDuration = 0.5f;\n\n [SerializeField]\n [Tooltip(\"How long a message remains in seconds once it's been displayed\")]\n [Range(0f, 5)]\n private float postMessageDuration = 1.25f;\n\n [SerializeField]\n [Tooltip(\"How long a pause last (dot, comma)\")]\n [Range(0f, 2f)]\n private float shortPauseDuration = 0.25f;\n\n [SerializeField]\n [Tooltip(\"How long a pause last (dot, comma)\")]\n [Range(0f, 2f)]\n private float longPauseDuration = 0.35f;\n\n private TextMeshProUGUI textMesh;\n private Text textName;\n\n private bool useVibrations = false;\n\n private bool skip = false;\n private bool next = false;\n\n private Inputs inputs;\n\n private bool upper = true;\n\n // Start is called before the first frame update\n void Awake()\n {\n inputs = cutsceneManager.GetComponent<CutsceneManager>().GetInputs();\n Debug.Assert(inputs != null, \"Inputs not instantiated\");\n\n textMesh = messageBoxUpper.GetComponent<TextMeshProUGUI>();\n Debug.Assert(textMesh != null, \"No TextMeshProUGUI attached to \" + transform.name);\n\n textMesh.text = string.Empty;\n\n emissionModule = vibrations.emission;\n EndVibrating();\n\n Debug.Assert(skipButton != null, \"Missing reference to skip button in message manager\");\n if(PlayerPrefs.GetString(\"controls\").Equals(\"gamepad\"))\n {\n skipButton.sprite = Resources.Load<Sprite>(\"Cutscene\\\\Images\\\\cutscene 1920\\\\next-button-white\");\n }\n else\n {\n skipButton.sprite = Resources.Load<Sprite>(\"Cutscene\\\\Images\\\\cutscene 1920\\\\next-key-white\");\n }\n\n skipButton.GetComponent<Animation>().Play(\"SkipButtonFadeIn\");\n\n del = new DisplayMessage(RevealLetterByLetter);\n }\n\n\n // Possible runtime change of the display method\n // DisplayMessage del = new DisplayMessage(callback);\n public void WriteMessage(string name, string message /*, callback */)\n {\n if (upper)\n {\n textName = nameBoxUpper;\n }\n else\n {\n textName = nameBoxLower;\n }\n textName.text = name;\n StartCoroutine(del(message));\n }\n\n IEnumerator RevealFade(string text)\n {\n textMesh.text = text;\n textMesh.alpha = 0;\n textMesh.ForceMeshUpdate();\n\n TMP_TextInfo textInfo = textMesh.textInfo;\n Color32[] newVertexColors;\n\n int currentCharacterIndex = 0;\n int startingCharacterIndex = currentCharacterIndex;\n bool isRangeMax = false;\n\n yield return new WaitForSeconds(preMessageDuration);\n\n while (!isRangeMax)\n {\n int characterCount = textInfo.characterCount;\n\n // Spread should not exceed the number of characters.\n //float RolloverCharacterSpread = 5; // how many character appearing at once\n byte fadeSteps = (byte)Mathf.Max(1, 255 / rolloverCharacterSpread);\n\n for (int i = startingCharacterIndex; i < currentCharacterIndex + 1; i++)\n {\n // Skip characters that are not visible\n if (!textInfo.characterInfo[i].isVisible) continue;\n\n // Get the index of the material used by the current character.\n int materialIndex = textInfo.characterInfo[i].materialReferenceIndex;\n\n // Get the vertex colors of the mesh used by this text element (character or sprite).\n newVertexColors = textInfo.meshInfo[materialIndex].colors32;\n\n // Get the index of the first vertex used by this text element.\n int vertexIndex = textInfo.characterInfo[i].vertexIndex;\n\n // Get the current character's alpha value.\n byte alpha = (byte)Mathf.Clamp(newVertexColors[vertexIndex + 0].a + fadeSteps, 0, 255);\n\n // Set new alpha values.\n newVertexColors[vertexIndex + 0].a = alpha;\n newVertexColors[vertexIndex + 1].a = alpha;\n newVertexColors[vertexIndex + 2].a = alpha;\n newVertexColors[vertexIndex + 3].a = alpha;\n\n // Tint vertex colors\n // Note: Vertex colors are Color32 so we need to cast to Color to multiply with tint which is Color.\n //newVertexColors[vertexIndex + 0] = (Color)newVertexColors[vertexIndex + 0] * ColorTint;\n //newVertexColors[vertexIndex + 1] = (Color)newVertexColors[vertexIndex + 1] * ColorTint;\n //newVertexColors[vertexIndex + 2] = (Color)newVertexColors[vertexIndex + 2] * ColorTint;\n //newVertexColors[vertexIndex + 3] = (Color)newVertexColors[vertexIndex + 3] * ColorTint;\n\n if (alpha == 255)\n {\n startingCharacterIndex += 1;\n\n if (startingCharacterIndex == characterCount)\n {\n isRangeMax = true; // Would end the coroutine.\n\n /*\n \n // Update mesh vertex data one last time.\n textMesh.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32);\n\n yield return new WaitForSeconds(1.0f);\n\n // Reset the text object back to original state.\n textMesh.ForceMeshUpdate();\n\n yield return new WaitForSeconds(1.0f);\n\n // Reset our counters.\n currentCharacterIndex = 0;\n startingCharacterIndex = 0;\n\n */\n }\n }\n }\n\n // Upload the changed vertex colors to the Mesh.\n textMesh.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32);\n\n if (currentCharacterIndex + 1 < characterCount) currentCharacterIndex += 1;\n\n yield return new WaitForSeconds(0.01f / messageSpeed);\n }\n\n yield return new WaitForSeconds(postMessageDuration);\n\n MessageShownEvent();\n }\n\n IEnumerator RevealLetterByLetter(string text)\n {\n inputs.Player.SkipDialog.performed += SkipDialog;\n\n if(upper)\n {\n textMesh = messageBoxUpper.GetComponent<TextMeshProUGUI>();\n }\n else\n {\n textMesh = messageBoxLower.GetComponent<TextMeshProUGUI>();\n }\n upper = false;\n\n textMesh.text = text;\n textMesh.maxVisibleCharacters = 0;\n\n skip = false;\n next = false;\n\n float delay;\n textMesh.ForceMeshUpdate(); // update textInfo to get actual characterCount\n\n yield return new WaitForSeconds(preMessageDuration);\n\n for (int i = 0; i < textMesh.textInfo.characterCount; i++)\n {\n textMesh.maxVisibleCharacters = i + 1;\n \n if (!skip)\n {\n if (IsShortPause(textMesh.text[i]))\n {\n if (useVibrations)\n EndVibrating();\n delay = shortPauseDuration;\n }\n else if (IsLongPause(textMesh.text[i]))\n {\n if (useVibrations)\n EndVibrating();\n delay = longPauseDuration;\n }\n else\n {\n // Don't put sound on space characters\n if (textMesh.text[i] != ' ')\n {\n if (textName.text == \"Ange\" || textName.text == \"Zeous\")\n AkSoundEngine.PostEvent(\"Play_Ecriture_Animation_Ange\", gameObject);\n else\n AkSoundEngine.PostEvent(\"Play_Ecriture_Animation\", gameObject);\n }\n\n if (useVibrations)\n StartVibrating();\n delay = 0.1f / (2 * messageSpeed);\n }\n }\n else\n {\n textMesh.maxVisibleCharacters = textMesh.textInfo.characterCount;\n break;\n }\n\n yield return new WaitForSeconds(delay);\n }\n\n if (useVibrations)\n EndVibrating();\n\n // Wait until input from user\n\n inputs.Player.SkipDialog.performed += NextEvent;\n\n while(!next)\n {\n yield return new WaitForEndOfFrame();\n }\n\n // Erase message before next event, maybe in some case it could stay\n textMesh.text = \"\";\n textName.text = \"\";\n\n MessageShownEvent();\n }\n\n IEnumerator RevealWordByWord(string text)\n {\n textMesh.text = text;\n textMesh.maxVisibleWords = 0;\n\n float delay;\n textMesh.ForceMeshUpdate(); // update textInfo to get actual wordCount\n\n yield return new WaitForSeconds(preMessageDuration);\n\n for (int i = 0; i < textMesh.textInfo.wordCount + 1; i++)\n {\n textMesh.maxVisibleWords = i + 1;\n delay = 0.1f / (2 * messageSpeed);\n yield return new WaitForSeconds(delay);\n }\n\n yield return new WaitForSeconds(postMessageDuration);\n\n MessageShownEvent();\n }\n\n public void StartVibrating()\n {\n emissionModule.rateOverTime = 8f;\n }\n\n public void EndVibrating()\n {\n emissionModule.rateOverTime = 0f;\n }\n\n public static bool IsShortPause(char c)\n {\n return c == ',' || c == ':';\n }\n\n public static bool IsLongPause(char c)\n {\n return c == '.' || c == '!';\n }\n\n private void SkipDialog(InputAction.CallbackContext ctx)\n {\n inputs.Player.SkipDialog.performed -= SkipDialog;\n skip = true;\n }\n\n private void NextEvent(InputAction.CallbackContext ctx)\n {\n AkSoundEngine.PostEvent(\"Play_Touche_Next\", gameObject);\n\n inputs.Player.SkipDialog.performed -= NextEvent;\n next = true;\n }\n\n public void HideSkipButton()\n {\n skipButton.enabled = false;\n //skipButton.GetComponent<Animation>().Play(\"SkipButtonFadeOut\");\n }\n\n private void OnDestroy()\n {\n inputs.Player.SkipDialog.performed -= SkipDialog;\n inputs.Player.SkipDialog.performed -= NextEvent;\n }\n}\n" }, { "alpha_fraction": 0.6212888956069946, "alphanum_fraction": 0.6212888956069946, "avg_line_length": 29.021739959716797, "blob_id": "381fe70e627cc33f916b12e375780c08d49cf325", "content_id": "9a392139602a911b751d7fff4ee3b464f1273fa7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1383, "license_type": "no_license", "max_line_length": 105, "num_lines": 46, "path": "/SoA-Unity/Assets/Scripts/Sound/TriggerAmbiance.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic enum AMBIANCE { PARK, CITY, SHELTER, NONE };\n\npublic class TriggerAmbiance : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The type of ambiance that is triggered when crossing this collider\")]\n private AMBIANCE ambiance = AMBIANCE.NONE;\n\n // Start is called before the first frame update\n void Start()\n {\n \n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n private void OnTriggerEnter(Collider other)\n {\n if (other.CompareTag(\"Player\"))\n {\n if(other.GetComponent<PostWwiseAmbiance>() == null)\n {\n throw new System.NullReferenceException(\"No PostWwiseAmbiance script set on the player\");\n }\n\n if (ambiance == AMBIANCE.PARK)\n {\n other.GetComponent<PostWwiseAmbiance>().CityAmbianceEventStop.Post(other.gameObject);\n other.GetComponent<PostWwiseAmbiance>().ParkAmbianceEventPlay.Post(other.gameObject);\n }\n else if (ambiance == AMBIANCE.CITY)\n {\n other.GetComponent<PostWwiseAmbiance>().ParkAmbianceEventStop.Post(other.gameObject);\n other.GetComponent<PostWwiseAmbiance>().CityAmbianceEventPlay.Post(other.gameObject);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6878452897071838, "alphanum_fraction": 0.6878452897071838, "avg_line_length": 23.133333206176758, "blob_id": "95c38602ec56404c9f1c32172bc02dd46dbd08d3", "content_id": "dbb6baff0f3bf713cb7c0e594cdc1180682bb1d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 364, "license_type": "no_license", "max_line_length": 72, "num_lines": 15, "path": "/SoA-Unity/Assets/Resources/Scripts/MeshScript.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class MeshScript : MonoBehaviour\n{\n [SerializeField]\n Color color;\n void Awake()\n {\n Material mat = gameObject.GetComponent<MeshRenderer>().material;\n mat = new Material(mat);\n gameObject.GetComponent<MeshRenderer>().material = mat;\n }\n}\n" }, { "alpha_fraction": 0.6155539155006409, "alphanum_fraction": 0.6241135001182556, "avg_line_length": 25.72549057006836, "blob_id": "c75ac04c8d5176df9403daa7780b19933dfd9dfc", "content_id": "bf0267e6122a26a361c38f1fe725489e92b0052b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4091, "license_type": "no_license", "max_line_length": 352, "num_lines": 153, "path": "/SoA-Unity/Assets/Scripts/PlayerControllerA/PlayerFollow.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class PlayerFollow : MonoBehaviour, IAnimable\n{\n\n private Inputs inputs;\n\n [Space]\n [Header(\"Player settings\")]\n [Space]\n\n [SerializeField]\n private CharacterController characterController;\n\n [SerializeField]\n [Tooltip(\"The camera from which the player's forward direction is given\")]\n private GameObject cameraHolder;\n\n [Space]\n [SerializeField]\n [Range(1.0f, 10.0f)]\n private float normalSpeed = 1;\n\n [SerializeField]\n [Tooltip(\"Speed when the character is losing energy\")]\n [Range(1.0f, 10.0f)]\n private float hurrySpeed = 10;\n\n private float speed;\n\n [SerializeField]\n [Tooltip(\"Time in seconds to transition from hurry state to normal state\")]\n [Range(0, 5)]\n private float delayToNormalState = 3; // s\n\n private float backToNormalSpeedTimer = 0; // s\n\n private bool isHurry;\n public bool IsHurry { get { return isHurry; } }\n\n private bool isProtectingEyes;\n public bool IsProtectingEyes { get { return isProtectingEyes; } set { isProtectingEyes = value; } }\n\n private bool isProtectingEars;\n public bool IsProtectingEars { get { return isProtectingEars; } set { isProtectingEars = value; } }\n\n [SerializeField]\n private Animator anim;\n public Animator Anim { get { return anim; } }\n\n private Vector3 movement;\n\n [SerializeField]\n private Transform groundedPosition;\n\n void Awake()\n {\n // angle = player.transform.rotation.eulerAngles.y;\n inputs = InputsManager.Instance.Inputs;\n\n isHurry = false;\n isProtectingEyes = false;\n IsProtectingEars = false;\n\n movement = Vector3.zero;\n }\n\n // Start is called before the first frame update\n void Start()\n {\n speed = normalSpeed;\n }\n\n // Update is called once per frame\n void Update()\n {\n StickToGround();\n\n if (inputs.Player.Walk != null)\n {\n Walk(inputs.Player.Walk.ReadValue<Vector2>());\n }\n\n characterController.Move(movement);\n movement = Vector3.zero;\n }\n\n void OnEnable()\n {\n inputs.Player.Enable();\n }\n\n void OnDisable()\n {\n inputs.Player.Disable();\n }\n\n void Walk(Vector2 v)\n {\n if (v.magnitude > Mathf.Epsilon)\n {\n transform.rotation = Quaternion.Euler(0, cameraHolder.transform.rotation.eulerAngles.y + Mathf.Rad2Deg * Mathf.Atan2(v.x, v.y), 0); // cartesian to polar, starting from the Y+ axis as it's the one mapped to the camera's forward, thus using tan-1(x,y) and not tan-1(y,x) / No rotationSpeed * Time.deltaTime as it takes absolute orientation\n movement += Vector3.ProjectOnPlane(transform.forward, Vector3.up).normalized * v.magnitude * speed * Time.deltaTime; // projection normalized to have the speed independant from the camera angle\n\n anim.SetBool(\"isWalking\", true);\n }\n else\n {\n anim.SetBool(\"isWalking\", false);\n }\n }\n\n void StickToGround()\n {\n RaycastHit hit;\n LayerMask ground = LayerMask.GetMask(\"Ground\");\n\n if (Physics.Raycast(groundedPosition.position, -Vector3.up, out hit, Mathf.Infinity, ground) || Physics.Raycast(groundedPosition.position, Vector3.up, out hit, Mathf.Infinity, ground))\n {\n movement = (hit.point - groundedPosition.position);\n }\n else\n {\n movement = Vector3.zero;\n }\n }\n\n public void Hurry(float energy)\n {\n isHurry = true;\n backToNormalSpeedTimer = delayToNormalState;\n if (speed != hurrySpeed)\n {\n StartCoroutine(\"TransitionToNormalSpeed\");\n }\n speed = hurrySpeed;\n }\n\n IEnumerator TransitionToNormalSpeed()\n {\n while (backToNormalSpeedTimer > 0)\n {\n backToNormalSpeedTimer -= Time.deltaTime;\n yield return null;\n }\n backToNormalSpeedTimer = 0;\n speed = normalSpeed;\n isHurry = false;\n }\n\n} // FINISH\n" }, { "alpha_fraction": 0.6012269854545593, "alphanum_fraction": 0.6012269854545593, "avg_line_length": 23.04918098449707, "blob_id": "2d85922cec2ab2e24678e052c090083c6d37276e", "content_id": "95ef0592e4739b5ebe5c21c08175409b50ccadc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1469, "license_type": "no_license", "max_line_length": 112, "num_lines": 61, "path": "/SoA-Unity/Assets/Scripts/Managers/SaveManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic enum SHELTER { HOME, SHED, BAR }\npublic class SaveManager : MonoBehaviour\n{\n private static GameObject singleton;\n\n private SHELTER saveShelterIndex;\n public SHELTER SaveShelterIndex { get { return saveShelterIndex; } }\n\n //private GameObject saveShelter;\n //public GameObject SaveShelter { get { return saveShelter; } }\n\n // Start is called before the first frame update\n void Awake()\n {\n // Do not create more than one save manager on reload scene\n if (singleton == null)\n {\n singleton = gameObject;\n DontDestroyOnLoad(gameObject);\n }\n else if (singleton != gameObject)\n {\n Destroy(gameObject);\n return;\n }\n\n saveShelterIndex = SHELTER.HOME;\n }\n\n private void Start()\n {\n\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n public void Save(GameObject shelter)\n {\n if (shelter.CompareTag(\"Bar\") && (saveShelterIndex == SHELTER.HOME || saveShelterIndex == SHELTER.SHED))\n {\n saveShelterIndex = SHELTER.BAR;\n }\n else if (shelter.CompareTag(\"Shed\") && saveShelterIndex == SHELTER.HOME)\n {\n saveShelterIndex = SHELTER.SHED;\n }\n }\n\n public void DestroySingleton()\n {\n singleton = null; // Manually destroy static object\n }\n}\n" }, { "alpha_fraction": 0.5776525735855103, "alphanum_fraction": 0.5851057171821594, "avg_line_length": 32.956790924072266, "blob_id": "e1776349090a26d1db163078f0afda4d0138ffd8", "content_id": "54d49191bf901ff14de231a10518a1e673e53aab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 16505, "license_type": "no_license", "max_line_length": 197, "num_lines": 486, "path": "/SoA-Unity/Assets/LevelStreets/Scripts/Vehicles/StreetUser.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using UnityEngine;\nusing System.Collections;\nusing System.Collections.Generic;\nusing Pixelplacement;\n\npublic class StreetUser : MonoBehaviour\n{\n [SerializeField] [Tooltip(\"The spline used by the object\")]\n private Spline spline;\n public Spline MySpline { get { return spline; } set { spline = value; } }\n\n [SerializeField]\n private bool onStart = true;\n\n [Header(\"Position\")]\n [Space]\n\n [SerializeField] [Range(0, 1)] [Tooltip(\"Initial position on the spline (in percent)\")]\n private float startPercentage = 0;\n private float percentage;\n public float Percentage { get { return percentage; } set { percentage = value; } }\n\n [SerializeField]\n [Tooltip(\"The position of the stop\")]\n [Range(0, 1)]\n private float stopPercentage;\n private bool hasStopped;\n public bool HasStopped { get { return hasStopped; } }\n\n private float speed = 50f;\n public float Speed { get { return speed; } set { speed = value; } }\n\n private float frontSpeed;\n\n public float FrontSpeed { get { return frontSpeed; } set { frontSpeed = value; } }\n\n private float obstaclePercentage;\n public float ObstaclePercentage { get { return obstaclePercentage; } set { obstaclePercentage = value; } }\n\n private float intersectionPercentage;\n public float IntersectionPercentage { get { return intersectionPercentage; } set { intersectionPercentage = value; } }\n\n\n [Header(\"Speed\")]\n [Space]\n\n [SerializeField]\n [Range(0f, 100f)]\n [Tooltip(\"The speed of the object on a FAST section\")]\n private float fastSpeed = 70f;\n\n [SerializeField]\n [Range(0f, 100f)]\n [Tooltip(\"The speed of the object on a NORMAL section\")]\n private float normalSpeed = 60f;\n\n [SerializeField]\n [Range(0f, 100f)]\n [Tooltip(\"The speed of the object on a SLOW section\")]\n private float slowSpeed = 20f;\n\n [SerializeField]\n [Range(0f, 100f)]\n [Tooltip(\"The speed of the object on a CAUTIOUS section\")]\n private float cautiousSpeed = 10f;\n\n [Space]\n\n [SerializeField]\n [Range(1f, 1000f)]\n [Tooltip(\"The acceleration of the object between two speeds\")]\n private float acceleration = 10f;\n\n [SerializeField]\n [Range(1f, 1000f)]\n [Tooltip(\"The deceleration of the object between two speeds\")]\n private float deceleration = 10f;\n\n [SerializeField]\n [Range(1f, 1000f)]\n [Tooltip(\"The deceleration of the object when behind another object\")]\n private float decelerationObstacle = 50f;\n\n [SerializeField]\n [Range(1f, 1000f)]\n [Tooltip(\"The deceleration of the object to full stop\")]\n private float decelerationStop = 50f;\n\n private Dictionary<SPEEDLIMIT, float> speedValues;\n\n [Header(\"Durations\")]\n [Space]\n\n [SerializeField][Range(0f, 10f)][Tooltip(\"The duration of the pause\")]\n private float stopDuration = 0;\n\n [SerializeField][Range(1f, 5f)][Tooltip(\"The duration of the pause\")]\n private float freezeDuration = 3f;\n\n [Header(\"Ground\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"The raycaster\")]\n private Transform raycaster;\n\n [SerializeField]\n [Tooltip(\"The ground level\")]\n private Transform groundLevel;\n private float groundOffset;\n\n [Header(\"VFX\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"VFX to play when loud sound is emitted\")]\n private GameObject loudVFX;\n\n public enum STATE { NORMAL, FREEZE, STAYBEHIND, STOPPING, STOP, PARKED, OFF }\n private STATE movingState;\n public STATE MovingState { get { return movingState; } set { movingState = value; } }\n\n /* Event */\n\n public delegate void AvailableHandler(GameObject sender);\n public event AvailableHandler AvailableEvent;\n\n\n private void Awake()\n {\n groundOffset = transform.position.y - groundLevel.transform.position.y;\n\n InitializeSound();\n \n movingState = STATE.OFF;\n\n Debug.Assert(loudVFX != null);\n loudVFX.GetComponent<ParticleSystem>().Stop();\n }\n private void Start()\n {\n //UserSet();\n }\n\n private void Update()\n {\n UpdateSound();\n\n if (movingState != STATE.FREEZE && movingState != STATE.OFF)\n {\n /* VFX sound */\n if (speed > 10 && loudVFX.GetComponent<ParticleSystem>().isStopped)\n loudVFX.GetComponent<ParticleSystem>().Play();\n else if (speed <= 10 && loudVFX.GetComponent<ParticleSystem>().isPlaying)\n loudVFX.GetComponent<ParticleSystem>().Stop();\n\n if (movingState == STATE.NORMAL)\n {\n /* FIND THE SPEED LIMIT OF THE ZONE */\n\n SPEEDLIMIT speedLimit = SPEEDLIMIT.NORMAL;\n\n SPEEDLIMIT lastZoneSpeedLimit = SPEEDLIMIT.NORMAL;\n float lastZonePercentage = 0;\n\n foreach (KeyValuePair<float, SPEEDLIMIT> nextSpeedZone in spline.GetComponent<StreetMap>().SpeedZones)\n {\n if (percentage >= lastZonePercentage && percentage < nextSpeedZone.Key)\n {\n speedLimit = lastZoneSpeedLimit;//speedZone.Value;\n //Debug.Log(\"Speed Zone : [\" + lastZonePercentage + \",\" + nextSpeedZone.Key + \"]\");\n break;\n }\n lastZonePercentage = nextSpeedZone.Key;\n lastZoneSpeedLimit = nextSpeedZone.Value;\n }\n\n /* UPDATE SPEED */\n\n if (speed < speedValues[speedLimit])\n {\n //speed = Mathf.Min(speed + acceleration * Time.deltaTime / (speedValues[speedLimit] - speed), speedValues[speedLimit]);\n speed = Mathf.Min(speed + acceleration * Time.deltaTime, speedValues[speedLimit]);\n Debug.Log(\"SPEED OF \" + gameObject.name + \" IS \" + speed + \" AND CURRENT LIMIT IS \" + speedValues[speedLimit]);\n //speed = speedValues[speedLimit];\n }\n else if (speed > speedValues[speedLimit])\n {\n //speed = Mathf.Max(speed - deceleration * Time.deltaTime / (speed - speedValues[speedLimit]), speedValues[speedLimit]);\n speed = Mathf.Max(speed - deceleration * Time.deltaTime, speedValues[speedLimit]);\n //speed = speedValues[speedLimit];\n }\n }\n else if (movingState == STATE.STAYBEHIND)\n {\n /* UPDATE SPEED ACCORDING TO THE FRONT VEHICLE'S SPEED AND POSITION */\n\n // TO DO : Use obstaclePercentage to keep moving till it's not reached\n\n // Debug.Log(transform.name + \"IN STAYBEHIND MODE\");\n\n if (speed >= frontSpeed)\n {\n //speed = frontSpeed;\n speed = Mathf.Max(speed - (Mathf.Max(speed, decelerationObstacle) + 10 * (obstaclePercentage - percentage)) * Time.deltaTime, frontSpeed); // deceleration proportionnal to speed\n\n // move towards the target\n /*\n if(speed == frontSpeed && obstaclePercentage > percentage)\n {\n speed += (obstaclePercentage - percentage) * Time.deltaTime;\n }*/\n }\n }\n else if (movingState == STATE.STOP)\n {\n if (speed >= 0)\n {\n //speed = 0;\n speed = Mathf.Max(speed - (Mathf.Max(speed, decelerationStop) - 10 * (intersectionPercentage - percentage)) * Time.deltaTime, 0); // deceleration proportionnal to speed\n\n // move towards the target\n /*\n if (speed == 0 && intersectionPercentage > percentage)\n {\n speed = (intersectionPercentage - percentage) * Time.deltaTime;\n }*/\n }\n }\n\n /* UPDATE PERCENTAGE */\n\n //spline.CalculateLength();\n percentage = Mathf.Min(percentage + (speed * Time.deltaTime) / spline.Length, 1);\n Debug.Log(gameObject.name + \"'S SPEED IS : \" + speed + \" AND TRUE SPEED IS \" + speed * Time.deltaTime / spline.Length);\n Debug.Log(gameObject.name + \"'S PERCENTAGE IS : \" + percentage);\n\n /* UPDATE TRANSFORM */\n\n Vector3 position = spline.GetPosition(percentage);\n transform.position = StickToTheGround(position);\n transform.rotation = Quaternion.LookRotation(spline.GetDirection(percentage));\n\n // Debug.Log(\"PERCENTAGE : \" + percentage + \"!!!!!!!!!!!!!!!!!!!!!!!!!!\");\n\n /* STOP CONDITION */\n\n /*\n if (percentage >= stopPercentage && !hasStopped)\n {\n hasStopped = true;\n if (stopDuration > 0)\n {\n yield return new WaitForSeconds(stopDuration);\n }\n }*/\n\n /* OFF CONDITION */\n\n if (percentage == 1)\n {\n MovingState = STATE.OFF;\n\n //percentage = 0;\n hasStopped = false;\n\n /* Unregister to the previous spline */\n spline.GetComponent<StreetMap>().UnregisterUser(gameObject);\n\n /* Inform the StreetUsersManager that I am available */\n AvailableEvent(gameObject);\n }\n }\n }\n\n public void UserSet()\n {\n // Register to the spline\n spline.GetComponent<StreetMap>().RegisterUser(gameObject);\n spline.CalculateLength();\n\n // Set the initial position\n percentage = startPercentage;\n Vector3 position = spline.GetPosition(percentage);\n transform.position = StickToTheGround(position);\n\n // Set the initial rotation\n transform.rotation = Quaternion.LookRotation(spline.GetDirection(Mathf.Clamp(startPercentage, 0.01f, 0.99f), true)); // initial rotation\n\n // Set the speed according to the zones\n speedValues = new Dictionary<SPEEDLIMIT, float>\n {\n { SPEEDLIMIT.FAST, fastSpeed },\n { SPEEDLIMIT.NORMAL, normalSpeed },\n { SPEEDLIMIT.SLOW, slowSpeed },\n { SPEEDLIMIT.CAUTIOUS, cautiousSpeed }\n };\n\n // Set the initial speed\n\n SPEEDLIMIT lastZoneSpeedLimit = SPEEDLIMIT.NORMAL;\n float lastZonePercentage = 0;\n speed = 0;\n\n foreach (KeyValuePair<float, SPEEDLIMIT> nextSpeedZone in spline.GetComponent<StreetMap>().SpeedZones)\n {\n if (percentage >= lastZonePercentage && percentage < nextSpeedZone.Key)\n {\n speed = speedValues[lastZoneSpeedLimit];\n break;\n }\n lastZonePercentage = nextSpeedZone.Key;\n lastZoneSpeedLimit = nextSpeedZone.Value;\n }\n\n hasStopped = false;\n if (onStart) { movingState = STATE.NORMAL; }\n else { movingState = STATE.OFF; }\n }\n\n public void CommonSet(float acceleration, float deceleration, float decelerationObstacle, float decelerationStop, float freezeDuration)\n {\n this.acceleration = acceleration;\n this.deceleration = deceleration;\n this.decelerationObstacle = decelerationObstacle;\n this.decelerationStop = decelerationStop;\n this.freezeDuration = freezeDuration;\n }\n\n public void SpecificSet(Spline newSpline, float fastSpeed, float normalSpeed, float slowSpeed, float cautiousSpeed)\n {\n /* Register to the spline */\n this.spline = newSpline;\n spline.GetComponent<StreetMap>().RegisterUser(gameObject);\n //spline.CalculateLength();\n\n /* Set initial position */\n\n percentage = 0;\n Vector3 position = spline.GetPosition(percentage);\n transform.position = StickToTheGround(position);\n\n /* Set initial rotation */\n\n transform.rotation = Quaternion.LookRotation(spline.GetDirection(Mathf.Clamp(percentage, 0.01f, 0.99f), true)); // initial rotation\n\n /* Set the speeds according to the zones */\n\n this.fastSpeed = fastSpeed;\n this.normalSpeed = normalSpeed;\n this.slowSpeed = slowSpeed;\n this.cautiousSpeed = cautiousSpeed;\n\n speedValues = new Dictionary<SPEEDLIMIT, float>\n {\n { SPEEDLIMIT.FAST, this.fastSpeed },\n { SPEEDLIMIT.NORMAL, this.normalSpeed },\n { SPEEDLIMIT.SLOW, this.slowSpeed },\n { SPEEDLIMIT.CAUTIOUS, this.cautiousSpeed }\n };\n\n /* Set the initial speed */\n\n SPEEDLIMIT lastZoneSpeedLimit = SPEEDLIMIT.NORMAL;\n float lastZonePercentage = 0;\n speed = 0;\n\n foreach (KeyValuePair<float, SPEEDLIMIT> nextSpeedZone in spline.GetComponent<StreetMap>().SpeedZones)\n {\n if (percentage >= lastZonePercentage && percentage < nextSpeedZone.Key)\n {\n speed = speedValues[lastZoneSpeedLimit];\n break;\n }\n lastZonePercentage = nextSpeedZone.Key;\n lastZoneSpeedLimit = nextSpeedZone.Value;\n }\n\n hasStopped = false;\n movingState = STATE.NORMAL;\n }\n\n public void Trigger()\n {\n if (!onStart && movingState == STATE.OFF) { movingState = STATE.NORMAL; }\n }\n\n /* COUNTDOWNS */\n\n /*\n private IEnumerator FreezeCountdown()\n {\n yield return new WaitForSeconds(freezeDuration);\n movingState = STATE.NORMAL;\n }*/\n\n private IEnumerator CarHornCountdown()\n {\n float delay; // seconds\n float maxDelay = 3; // seconds\n while (movingState == STATE.FREEZE)\n {\n AkSoundEngine.PostEvent(\"Play_Klaxons\", gameObject);\n loudVFX.GetComponent<ParticleSystem>().Play();\n yield return new WaitForSeconds(0.5f); // How long last a car horn ? make a guess\n loudVFX.GetComponent<ParticleSystem>().Stop();\n\n maxDelay = Mathf.Max(maxDelay * 7f/8f, 0);\n delay = Mathf.Max(Random.Range(0, maxDelay), 0.2f); // driver gets annoyed\n yield return new WaitForSeconds(delay);\n }\n }\n\n /* SOUND RELATED FUNCTIONS */\n\n private void InitializeSound()\n {\n // Define which car horn type to use\n AkSoundEngine.SetSwitch(\"Klaxons\", new string[5] { \"A\", \"B\", \"C\", \"D\", \"E\" }[Random.Range(0, 5)], gameObject);\n\n AKRESULT result = AkSoundEngine.SetRTPCValue(\"Quel_Moteur\", Random.Range(0,9), gameObject);\n\n if (result == AKRESULT.AK_Fail)\n {\n throw new System.Exception(\"WWISE : Could not set the type of the engine\");\n }\n\n /*\n result = AkSoundEngine.SetRTPCValue(\"Ralenti_Accelere\", 1f, gameObject);\n\n if (result == AKRESULT.AK_Fail)\n {\n throw new System.Exception(\"WWISE : Could not set the state of the engine\");\n }*/\n }\n\n private void UpdateSound()\n {\n AKRESULT result = AkSoundEngine.SetRTPCValue(\"VitesseVehicule\", speed, gameObject);\n Debug.Log(\"SPEED IS AT : \" + speed);\n\n //AKRESULT result = AkSoundEngine.SetSwitch(\"EtatVoiture\",\"C_IDLE\", gameObject);\n\n if (result == AKRESULT.AK_Fail)\n {\n throw new System.Exception(\"WWISE : Could not set the speed of the vehicule\");\n }\n }\n\n /* PHYSICS RELATED FUNCTIONS */\n\n private Vector3 StickToTheGround(Vector3 position)\n {\n LayerMask mask = LayerMask.GetMask(\"AsphaltGround\") | LayerMask.GetMask(\"GrassGround\") | LayerMask.GetMask(\"SoilGround\");\n if (Physics.Raycast(raycaster.transform.position, Vector3.down, out RaycastHit hit, Mathf.Infinity, mask))\n {\n return new Vector3(position.x, hit.point.y + groundOffset, position.z);\n }\n return position;\n }\n\n private void OnTriggerStay(Collider other)\n {\n if (other.transform.CompareTag(\"Player\"))\n {\n if (movingState != STATE.FREEZE)\n {\n movingState = STATE.FREEZE;\n speed = 0; // TO DO : Find a progressive way\n if (loudVFX.GetComponent<ParticleSystem>().isPlaying)\n {\n loudVFX.GetComponent<ParticleSystem>().Stop();\n }\n StartCoroutine(\"CarHornCountdown\");\n }\n }\n }\n\n private void OnTriggerExit(Collider other)\n {\n if (other.transform.CompareTag(\"Player\"))\n {\n movingState = STATE.NORMAL;\n }\n }\n}\n" }, { "alpha_fraction": 0.6517746448516846, "alphanum_fraction": 0.6567271947860718, "avg_line_length": 30.777050018310547, "blob_id": "e389a0f7770e0b349b0894775d77414aa30d8a56", "content_id": "1ead3ede5d0dcbb083f6eff7471495c4358d6c5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9694, "license_type": "no_license", "max_line_length": 164, "num_lines": 305, "path": "/SoA-Unity/Assets/Scripts/Menus/MenuManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.UI;\nusing AK.Wwise;\nusing UnityEngine.SceneManagement;\nusing UnityEngine.EventSystems;\n\npublic enum MENU_STATE { NONE, CREDITS, CONTROLS }\n\npublic enum CONTROL_STATE { NONE, MOUSEKEYBOARD, GAMEPAD }\n\npublic class MenuManager : MonoBehaviour\n{\n private GameObject creditsPanel;\n private GameObject controlsPanel;\n private GameObject gamepadPanel;\n private GameObject mouseKeyboardPanel;\n private GameObject corePanel;\n //private GameObject extendedPanel;\n\n private GameObject menuFirstButtonSelected;\n\n private GameObject transitions;\n\n private GameObject fade;\n public GameObject Fade { get { return fade; } }\n\n private MENU_STATE menuState;\n public MENU_STATE MenuState { get { return menuState; } }\n\n private CONTROL_STATE controlState;\n public CONTROL_STATE ControlState { get { return controlState; } set { controlState = value; } }\n\n\n // Start is called before the first frame update\n void Awake()\n {\n // Transitions\n transitions = GameObject.FindGameObjectWithTag(\"Transitions\");\n transitions.GetComponent<Transitions>().FadeIn();\n\n menuState = MENU_STATE.NONE;\n\n creditsPanel = GameObject.FindGameObjectWithTag(\"MenuCredits\");\n if (creditsPanel == null)\n {\n throw new System.NullReferenceException(\"Missing credits panel in the menu\");\n }\n creditsPanel.GetComponent<CanvasGroup>().alpha = 0;\n\n fade = GameObject.FindGameObjectWithTag(\"Fade\");\n fade.GetComponent<Image>().color = new Color(fade.GetComponent<Image>().color.r, fade.GetComponent<Image>().color.g, fade.GetComponent<Image>().color.b, 1);\n fade.GetComponent<Animation>().Play(\"TitleFadeIn\");\n\n corePanel = creditsPanel.transform.GetChild(0).gameObject;\n //extendedPanel = creditsPanel.transform.GetChild(1).gameObject;\n\n foreach (Transform child in corePanel.transform)\n {\n child.GetComponent<Text>().color = new Color(1, 1, 1, 0);\n }\n /*\n foreach (Transform child in extendedPanel.transform)\n {\n child.GetComponent<Text>().color = new Color(1, 1, 1, 0);\n }*/\n\n //AkSoundEngine.PostEvent(\"Play_Music_Menu\", gameObject);\n\n controlsPanel = GameObject.FindGameObjectWithTag(\"Controls\");\n if (controlsPanel == null)\n {\n throw new System.NullReferenceException(\"Missing control panel in the menu\");\n }\n controlsPanel.GetComponent<CanvasGroup>().alpha = 0;\n\n mouseKeyboardPanel = GameObject.FindGameObjectWithTag(\"MouseKeyboard\");\n if (mouseKeyboardPanel == null)\n {\n throw new System.NullReferenceException(\"Missing mouse keyboard panel in the menu\");\n }\n\n gamepadPanel = GameObject.FindGameObjectWithTag(\"Gamepad\");\n if (gamepadPanel == null)\n {\n throw new System.NullReferenceException(\"Missing gamepad panel in the menu\");\n }\n\n menuFirstButtonSelected = GameObject.FindGameObjectWithTag(\"FirstSelectedButtonMenu\");\n if (menuFirstButtonSelected == null)\n {\n throw new System.NullReferenceException(\"Missing first selected button in the menu\");\n }\n\n if (PlayerPrefs.HasKey(\"controls\") && PlayerPrefs.GetString(\"controls\").Equals(\"gamepad\"))\n {\n controlState = CONTROL_STATE.GAMEPAD;\n mouseKeyboardPanel.GetComponent<CanvasGroup>().alpha = 0;\n gamepadPanel.GetComponent<CanvasGroup>().alpha = 1;\n }\n else\n {\n controlState = CONTROL_STATE.MOUSEKEYBOARD;\n mouseKeyboardPanel.GetComponent<CanvasGroup>().alpha = 1;\n gamepadPanel.GetComponent<CanvasGroup>().alpha = 0;\n }\n }\n\n private void Start()\n {\n AkSoundEngine.SetState(\"Menu_Oui_Non\", \"Menu_Non\");\n\n AkSoundEngine.PostEvent(\"Play_Music_Main_Title\", gameObject);\n\n // Clear the default selected object and set the first selected item in the menu\n EventSystem.current.SetSelectedGameObject(null);\n EventSystem.current.SetSelectedGameObject(menuFirstButtonSelected);\n\n SetGamepadKeyInteractable(false);\n SetMouseKeyInteractable(false);\n SetKeysInteractable(false);\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n \n public void DisplayControls()\n {\n menuState = MENU_STATE.CONTROLS;\n StartCoroutine(\"FadeInControls\");\n\n // Set first selected UI item according to the current input\n\n if (controlState == CONTROL_STATE.GAMEPAD)\n {\n SetMouseKeyInteractable(true);\n EventSystem.current.SetSelectedGameObject(controlsPanel.transform.GetChild(1).gameObject);\n }\n else\n {\n SetGamepadKeyInteractable(true);\n SetKeysInteractable(true);\n EventSystem.current.SetSelectedGameObject(controlsPanel.transform.GetChild(0).gameObject);\n }\n }\n \n public void HideControls()\n {\n menuState = MENU_STATE.NONE;\n StartCoroutine(\"FadeOutControls\");\n\n SetKeysInteractable(false);\n SetGamepadKeyInteractable(false);\n SetMouseKeyInteractable(false);\n }\n\n IEnumerator FadeInControls()\n {\n controlsPanel.GetComponent<Animation>().Play(\"CreditsFadeIn\");\n yield return new WaitForSeconds(0.01f);\n }\n\n IEnumerator FadeOutControls()\n {\n controlsPanel.GetComponent<Animation>().Play(\"CreditsFadeOut\");\n yield return new WaitForSeconds(0.01f);\n }\n\n public void SwitchToMouseKeyboardControls()\n {\n controlState = CONTROL_STATE.MOUSEKEYBOARD;\n StartCoroutine(\"CrossFadeMouseKeyboardControls\");\n\n // Select the other button\n\n SetMouseKeyInteractable(false);\n SetGamepadKeyInteractable(true);\n SetKeysInteractable(true);\n EventSystem.current.SetSelectedGameObject(controlsPanel.transform.GetChild(0).gameObject);\n }\n\n public void SwitchToGamepadControls()\n {\n controlState = CONTROL_STATE.GAMEPAD;\n StartCoroutine(\"CrossFadeGamepadControls\");\n\n // Select the other button\n\n SetMouseKeyInteractable(true);\n SetGamepadKeyInteractable(false);\n SetKeysInteractable(false);\n EventSystem.current.SetSelectedGameObject(controlsPanel.transform.GetChild(1).gameObject);\n }\n\n IEnumerator CrossFadeMouseKeyboardControls()\n {\n gamepadPanel.GetComponent<Animation>().Play(\"CreditsFadeOut\");\n mouseKeyboardPanel.GetComponent<Animation>().Play(\"CreditsFadeIn\");\n yield return new WaitForSeconds(0.01f);\n }\n\n IEnumerator CrossFadeGamepadControls()\n {\n mouseKeyboardPanel.GetComponent<Animation>().Play(\"CreditsFadeOut\");\n gamepadPanel.GetComponent<Animation>().Play(\"CreditsFadeIn\");\n yield return new WaitForSeconds(0.01f);\n }\n\n public void DisplayCredits()\n {\n menuState = MENU_STATE.CREDITS;\n StartCoroutine(\"FadeInCredits\");\n }\n\n public void HideCredits()\n {\n menuState = MENU_STATE.NONE;\n StartCoroutine(\"FadeOutCredits\");\n }\n\n public void StartGame()\n {\n // Let's get to work !\n // TO DO : Make sure to add the intro when we have one\n //SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);\n StartCoroutine(transitions.GetComponent<Transitions>().FadeOut(\"Intro-EN\")); // Replace with Intro-FR for french version\n AkSoundEngine.PostEvent(\"Stop_Music_Main_Title\", gameObject);\n }\n\n IEnumerator FadeInCredits()\n {\n foreach (Transform child in corePanel.transform)\n {\n child.GetComponent<Animation>().Play(\"CreditsItemFadeIn\");\n yield return new WaitForSeconds(0.01f);\n }\n /*\n foreach (Transform child in extendedPanel.transform)\n {\n child.GetComponent<Animation>().Play(\"CreditsItemFadeIn\");\n yield return new WaitForSeconds(0.01f);\n }*/\n }\n\n IEnumerator FadeOutCredits()\n {\n foreach (Transform child in corePanel.transform)\n {\n child.GetComponent<Animation>().Play(\"CreditsItemFadeOut\");\n yield return new WaitForSeconds(0.01f);\n }\n /*\n foreach (Transform child in extendedPanel.transform)\n {\n child.GetComponent<Animation>().Play(\"CreditsItemFadeOut\");\n yield return new WaitForSeconds(0.01f);\n }*/\n }\n\n public void SetKeysInteractable(bool interactable)\n {\n foreach (GameObject key in GameObject.FindGameObjectsWithTag(\"ControlsKey\"))\n {\n key.GetComponent<Button>().interactable = interactable;\n }\n }\n\n public void SetGamepadKeyInteractable(bool interactable)\n {\n controlsPanel.transform.GetChild(0).gameObject.GetComponent<Button>().interactable = interactable;\n }\n\n public void SetMouseKeyInteractable(bool interactable)\n {\n controlsPanel.transform.GetChild(1).gameObject.GetComponent<Button>().interactable = interactable;\n }\n\n /* Wwise functions */\n\n public void PlayClickSound()\n {\n AkSoundEngine.PostEvent(\"Play_Clic_Selection\", gameObject);\n }\n\n public void PlayHoverSound()\n {\n AkSoundEngine.PostEvent(\"Play_Survol\", gameObject);\n }\n\n public void PlayParticlesSound()\n {\n AkSoundEngine.PostEvent(\"Play_Texte_Anim_Particule\", gameObject);\n }\n\n public void StopParticlesSound()\n {\n AkSoundEngine.PostEvent(\"Stop_Texte_Anim_Particule\", gameObject);\n }\n\n} //FINISH\n" }, { "alpha_fraction": 0.6555023789405823, "alphanum_fraction": 0.6555023789405823, "avg_line_length": 23.115385055541992, "blob_id": "2df1471e4e5ef18dec6dd0865e56a33a0f59afe9", "content_id": "9bf3dc046c97807eac8e7fe69d0200cec096dd9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 629, "license_type": "no_license", "max_line_length": 56, "num_lines": 26, "path": "/SoA-Unity/Assets/Resources/Scripts/Water.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Water : MonoBehaviour\n{\n [SerializeField]\n private GameObject light_prob;\n ReflectionProbe rp;\n Material mat;\n // Start is called before the first frame update\n void Start()\n {\n rp = light_prob.GetComponent<ReflectionProbe>();\n\n mat = GetComponent<MeshRenderer>().material;\n mat.SetTexture(\"_Skybox\",rp.texture);\n }\n\n // Update is called once per frame\n void Update()\n {\n mat = GetComponent<MeshRenderer>().material;\n mat.SetTexture(\"_Skybox\", rp.texture);\n }\n}\n" }, { "alpha_fraction": 0.4560147821903229, "alphanum_fraction": 0.4767951965332031, "avg_line_length": 37.843048095703125, "blob_id": "9eb91a0964d5ffbdd2265ba48687db9ea19878f2", "content_id": "20d717b76c3a3d501c00c9eda277634df91799d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8671, "license_type": "no_license", "max_line_length": 144, "num_lines": 223, "path": "/SoA-Unity/Assets/Resources/Scripts/LightManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class LightManager : MonoBehaviour\n{\n List<Light> lights;\n Light[] ls;\n MeshRenderer[] renderers;\n\n [SerializeField]\n int nb_part;\n // Start is called before the first frame update\n void Start()\n {\n lights = new List<Light>();\n ls = GameObject.FindObjectsOfType<Light>();\n float minx, maxx, minz, maxz;\n minx = maxx = minz = maxz = 0.0f;\n int cmpt = 0;\n foreach(Light l in ls)\n {\n Vector2 pos = new Vector2(l.transform.position.x, l.transform.position.z);\n Debug.Log(\"Ici \" + l);\n if (l.type != LightType.Directional)\n {\n if (cmpt == 0)\n {\n minx = maxx = pos.x;\n minz = maxz = pos.y;\n }\n else\n {\n if (minx > pos.x)\n minx = pos.x;\n if (maxx < pos.x)\n maxx = pos.x;\n if (minz > pos.y)\n minz = pos.y;\n if (maxz < pos.y)\n maxz = pos.y;\n }\n switch (l.type)\n {\n case LightType.Point:\n CapsuleCollider cap = l.gameObject.GetComponent<CapsuleCollider>();\n //if(cap != null)\n // cap.radius = l.range/2.0f;\n //a changer avec intensity\n break;\n case LightType.Spot:\n BoxCollider box = l.gameObject.GetComponent<BoxCollider>();\n if (box != null)\n {\n box.center = new Vector3(0.0f, 0.0f, l.range / 2.0f);\n box.size = new Vector3(l.range / 2.0f, l.range / 2.0f, l.range);\n }\n break;\n default:\n //\n break;\n }\n lights.Add(l);\n cmpt++;\n }\n }\n /*Debug.Log(\"Compteur est de \" + cmpt);\n Debug.Log(\"Minx \"+minx+\" Maxx \"+maxx+\" Minz \"+minz+\" Maxz \"+maxz);\n\n float padding_x, padding_z;\n padding_x = (maxx - minx) / nb_part;\n padding_z = (maxz - minz) / nb_part;\n\n List<Light> [][] tableau;\n tableau = new List<Light>[nb_part][];\n for(int i = 0; i < nb_part; i++)\n {\n tableau[i] = new List<Light>[nb_part];\n }\n\n\n for (int i = 0; i < nb_part; i++)\n {\n float z0 = minz + (i * padding_z);\n float z1 = minz + ((i+1) * padding_z);\n for (int j = 0; j < nb_part; j++)\n {\n float x0 = minx + (j * padding_x);\n float x1 = minx + ((j+1) * padding_x);\n int k = 0;\n tableau[i][j] = new List<Light>();\n while (k < lights.Count )\n {\n Vector2 pos = new Vector2(lights[k].transform.position.x, lights[k].transform.position.z);\n if (pos.x >= x0 && pos.x <= x1 && pos.y >= z0 && pos.y <= z1)\n {\n Debug.Log(i+\" et \"+j+\" Add light\"+lights[k].type);\n tableau[i][j].Add(lights[k]);\n lights.RemoveAt(k);\n }\n else\n k++;\n }\n //Debug.Log(\"X : \" + x0 + \" \" + x1 + \" Z : \" + z0 + \" \" + z1);\n }\n }\n\n //Mesh Renderer\n //tags => static et dynamique\n renderers = GameObject.FindObjectsOfType<MeshRenderer>();\n foreach(MeshRenderer render in renderers)\n {\n Debug.Log(\"Render \"+render.gameObject.name);\n Material[] mat = render.materials;\n List<Vector4> vector_pos = new List<Vector4>();\n List<Vector4> vector_col = new List<Vector4>();\n List<Vector4> vector_dir = new List<Vector4>();\n List<Vector4> vector_opt = new List<Vector4>();\n cmpt = 0;\n\n while (cmpt < 8 && cmpt < ls.Length)\n {\n //4eme argument angles pour spot et -1.0f pour point\n float value = ls[cmpt].range * (ls[cmpt].type == LightType.Point ? -1.0f : 1.0f);\n value = -1.0f;\n\n vector_pos.Add(new Vector4(ls[cmpt].transform.position.x, ls[cmpt].transform.position.y, ls[cmpt].transform.position.z,value));\n vector_col.Add(ls[cmpt].color);\n Vector3 dir = ls[cmpt].transform.rotation.eulerAngles;\n\n //angle\n float outerRad = Mathf.Deg2Rad * 0.5f * ls[cmpt].spotAngle;\n float outerCos = Mathf.Cos(outerRad);\n float outerTan = Mathf.Tan(outerRad);\n float innerCos = Mathf.Cos(Mathf.Atan(((64.0f - 18.0f) / 64.0f) * outerTan));\n float angleRange = Mathf.Max(innerCos - outerCos, 0.001f);\n\n float X = 1.0f / Mathf.Max(ls[cmpt].range * ls[cmpt].range, 0.00001f);\n float Z = 1.0f / angleRange;\n float W = -outerCos * Z;\n\n vector_opt.Add(new Vector4(X, 0.0f, Z, W));\n\n\n Debug.Log(\"Dir est de \" + dir);\n\n vector_dir.Add(new Vector4((dir.x * Mathf.PI) / 180.0f, (dir.y * Mathf.PI) / 180.0f, (dir.z * Mathf.PI) / 180.0f, 0.0f));\n\n\n cmpt++;\n }\n mat[0].SetVectorArray(\"vector_pos\",vector_pos);\n mat[0].SetVectorArray(\"vector_dir\", vector_dir);\n mat[0].SetVectorArray(\"vector_col\", vector_col);\n mat[0].SetVectorArray(\"vector_opt\", vector_opt);\n mat[0].SetFloat(\"vector_lenght\", cmpt);\n }*/\n }\n\n /*void Start()\n {\n \n }*/\n\n //penser a serialiser ce traitement de base pour avoir données au tout débuts sans besoin de recalculer\n //plus penser aussi aux vérification blocs adjacents\n //utilisation de tags => static et dynamique pour différencier traitement et rafraichissement\n //gestion dans les scripts avec vérifications de la positions par rapport aux blocs\n //découpages avec limites de lumières dans blocs\n //et tags aussi pour limiter nombre d'objets a traitement (genre les petits mesh comme serrure)\n\n // Update is called once per frame\n void Update()\n {\n /*foreach (MeshRenderer render in renderers)\n {\n Debug.Log(\"Render \" + render.gameObject.name);\n Material[] mat = render.materials;\n List<Vector4> vector_pos = new List<Vector4>();\n List<Vector4> vector_col = new List<Vector4>();\n List<Vector4> vector_dir = new List<Vector4>();\n List<Vector4> vector_opt = new List<Vector4>();\n int cmpt = 0;\n\n while (cmpt < 8 && cmpt < ls.Length)\n {\n //4eme argument angles pour spot et -1.0f pour point\n float value = ls[cmpt].range * (ls[cmpt].type == LightType.Point ? -1.0f : 1.0f);\n value = -1.0f;\n\n vector_pos.Add(new Vector4(ls[cmpt].transform.position.x, ls[cmpt].transform.position.y, ls[cmpt].transform.position.z, value));\n vector_col.Add(ls[cmpt].color);\n Vector3 dir = ls[cmpt].transform.rotation.eulerAngles;\n\n //angle\n float outerRad = Mathf.Deg2Rad * 0.5f * ls[cmpt].spotAngle;\n float outerCos = Mathf.Cos(outerRad);\n float outerTan = Mathf.Tan(outerRad);\n float innerCos = Mathf.Cos(Mathf.Atan(((64.0f - 18.0f) / 64.0f) * outerTan));\n float angleRange = Mathf.Max(innerCos - outerCos, 0.001f);\n\n float X = 1.0f / Mathf.Max(ls[cmpt].range * ls[cmpt].range, 0.00001f);\n float Z = 1.0f / angleRange;\n float W = -outerCos * Z;\n\n vector_opt.Add(new Vector4(X, 0.0f, Z, W));\n\n\n Debug.Log(\"Dir est de \" + dir);\n\n vector_dir.Add(new Vector4((dir.x * Mathf.PI) / 180.0f, (dir.y * Mathf.PI) / 180.0f, (dir.z * Mathf.PI) / 180.0f, 0.0f));\n\n\n cmpt++;\n }\n mat[0].SetVectorArray(\"vector_pos\", vector_pos);\n mat[0].SetVectorArray(\"vector_dir\", vector_dir);\n mat[0].SetVectorArray(\"vector_col\", vector_col);\n mat[0].SetVectorArray(\"vector_opt\", vector_opt);\n mat[0].SetFloat(\"vector_lenght\", cmpt);\n }*/\n }\n}\n" }, { "alpha_fraction": 0.6119472980499268, "alphanum_fraction": 0.6180620789527893, "avg_line_length": 28.123287200927734, "blob_id": "c2e922dd908c6c1d3211b5d828978ec1b0651d7e", "content_id": "23c1c9e39a14922789f66cd0d7843afdc5e8453a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2128, "license_type": "no_license", "max_line_length": 105, "num_lines": 73, "path": "/SoA-Unity/Assets/Scripts/Managers/ShelterManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class ShelterManager : MonoBehaviour\n{\n [Header(\"Shelters List\")]\n\n [SerializeField]\n [Tooltip(\"List of the shelters' entrances\")]\n private GameObject[] shelterOutsides;\n public GameObject[] ShelterOutsides { get { return shelterOutsides; } }\n\n [SerializeField]\n [Tooltip(\"List of the shelters' insides\")]\n private GameObject[] shelterInsides;\n public GameObject[] ShelterInsides { get { return shelterInsides; } }\n\n [Space]\n [Header(\"Shelter Settings\")]\n\n [SerializeField]\n [Tooltip(\"The maximum distance to open a door\")]\n [Range(0.1f, 10f)]\n private float maxDistanceToDoor = 3.0f;\n public float MaxDistanceToDoor { get { return maxDistanceToDoor; } }\n\n [SerializeField]\n [Tooltip(\"The duration of a transition\")]\n [Range(0.1f,5f)]\n private float transitionDuration = 2.0f;\n public float TransitionDuration { get { return transitionDuration; } }\n\n // Start is called before the first frame update\n void Start()\n {\n if(shelterOutsides.Length != shelterInsides.Length)\n {\n throw new System.SystemException(\"Shelter's entrances and exits list do not match together\");\n }\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n public GameObject GoInside(GameObject o)\n {\n for(int i = 0; i < shelterOutsides.Length; i++)\n {\n if (Object.ReferenceEquals(o, shelterOutsides[i]))\n {\n return shelterInsides[i];\n }\n Debug.Log(o.name + \" not equal to \" + shelterOutsides[i]);\n }\n throw new System.SystemException(o.name + \" not found in the shelter list\");\n }\n\n public GameObject GoOutside(GameObject o)\n {\n for (int i = 0; i < shelterInsides.Length; i++)\n {\n if (Object.ReferenceEquals(o, shelterInsides[i]))\n {\n return shelterOutsides[i];\n }\n }\n throw new System.SystemException(o.name + \" not found in the shelter list\");\n }\n}\n" }, { "alpha_fraction": 0.5849825143814087, "alphanum_fraction": 0.5960419178009033, "avg_line_length": 30.236364364624023, "blob_id": "b66221edf6111e6084a3d186fd9b7bac25063e31", "content_id": "a675893ba9d09413d8f1090ca39fe7a797b71317", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1718, "license_type": "no_license", "max_line_length": 124, "num_lines": 55, "path": "/SoA-Unity/Assets/LevelPark/Scripts/Placements/SpreadSeeds.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class SpreadSeeds : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The prefabs of the flower\")]\n private GameObject[] flowerPrefabs;\n\n [SerializeField]\n [Tooltip(\"Materials\")]\n private Material[] flowerMats;\n\n [SerializeField]\n [Tooltip(\"The number of seed\")]\n private int seedsNumber;\n\n [SerializeField]\n [Tooltip(\"Arbitrary constant\")]\n private int constant;\n\n // Start is called before the first frame update\n void Start()\n {\n float phi = 1.61803f; // golden ratio\n float theta, radius;\n Vector3 position;\n Quaternion rotation;\n for (int i = 0; i < seedsNumber; i++)\n {\n theta = i * 2 * Mathf.PI / (phi * phi);\n radius = constant * Mathf.Sqrt(i);\n position = new Vector3();\n position.y = transform.position.y;\n position.x = transform.position.x + radius * Mathf.Cos(theta);\n position.z = transform.position.z + radius * Mathf.Sin(theta);\n rotation = Quaternion.Euler(0, Random.Range(0, 360), 0);\n GameObject flower = Object.Instantiate(flowerPrefabs[Random.Range(0,flowerPrefabs.Length)], position, rotation);\n MeshRenderer [] mats = flower.GetComponentsInChildren<MeshRenderer>();\n int rand = Random.Range(0, flowerMats.Length);\n foreach(MeshRenderer mat in mats)\n {\n mat.material = new Material(flowerMats[rand]);\n }\n flower.name = transform.name + \" \" + (i + 1).ToString();\n }\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n}\n" }, { "alpha_fraction": 0.6521739363670349, "alphanum_fraction": 0.6521739363670349, "avg_line_length": 27.174999237060547, "blob_id": "28352cc2543317bbe5e8e6f8506a027374729f99", "content_id": "f25e4c19b43319853e4803ae1f47d12ac5ca5925", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1129, "license_type": "no_license", "max_line_length": 149, "num_lines": 40, "path": "/SoA-Unity/Assets/Scripts/Managers/AudioManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing System.Linq;\nusing UnityEngine.SceneManagement;\n\npublic class AudioManager : MonoBehaviour\n{\n private static AudioManager instance;\n public static AudioManager Instance { get { return instance; } private set { instance = value; } }\n\n private GameObject[] gameObjectWithAudioSources;\n public GameObject[] GameObjectWithAudioSources { get { return gameObjectWithAudioSources; } private set { gameObjectWithAudioSources = value; } }\n\n private void Awake()\n {\n if(instance != null && this != instance)\n {\n Destroy(gameObject);\n }\n else\n {\n gameObjectWithAudioSources = FindObjectsOfType<AudioSource>().Select(item => item.gameObject).ToArray(); // TO DO : Change to AkEvent\n Debug.Log(gameObjectWithAudioSources.Length + \" AudioSources\");\n instance = this;\n }\n }\n\n // Start is called before the first frame update\n void Start()\n {\n\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n} // FINISH\n" }, { "alpha_fraction": 0.5879120826721191, "alphanum_fraction": 0.5964835286140442, "avg_line_length": 28.9342098236084, "blob_id": "458f889442919586caffa9804373becb9b0c8473", "content_id": "c81363a12faf81214ab1a57b3e66368d0d5e1fe9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4552, "license_type": "no_license", "max_line_length": 168, "num_lines": 152, "path": "/SoA-Unity/Assets/LevelPark/Scripts/NPC/SplineParkUser.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using UnityEngine;\nusing System.Collections;\nusing System.Collections.Generic;\nusing Pixelplacement;\n\npublic class SplineParkUser : MonoBehaviour\n{\n [SerializeField] [Tooltip(\"The spline used by the user\")]\n private Spline spline;\n\n [Header(\"Position\")]\n [Space]\n\n [SerializeField] [Range(0, 1)] [Tooltip(\"Initial position on the spline (in percent)\")]\n private float startPercentage = 0;\n\n private float percentage;\n\n [Header(\"Move\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"The speed of the user\")]\n private float speed = 10f;\n\n [SerializeField]\n [Tooltip(\"Does the user start moving immediately or wait for a trigger ?\")]\n private bool onStart = true;\n\n [Header(\"Duration\")]\n [Space]\n\n [SerializeField]\n [Range(1f, 5f)]\n [Tooltip(\"The duration of the freeze\")]\n private float freezeDuration = 3f;\n\n [Header(\"Ground\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"The raycaster\")]\n private Transform raycaster;\n\n [SerializeField]\n [Tooltip(\"The ground level\")]\n private Transform groundLevel;\n private float groundOffset;\n\n private enum DIRECTION { FORWARD, BACKWARD }\n [SerializeField]\n private DIRECTION directionState;\n\n public enum STATE { NORMAL, FREEZE }\n private STATE movingState;\n\n private void Start()\n {\n percentage = startPercentage;\n spline.CalculateLength();\n\n if(groundLevel != null) groundOffset = transform.position.y - groundLevel.transform.position.y;\n movingState = STATE.NORMAL;\n\n Vector3 position = Vector3.zero;\n if (directionState == DIRECTION.FORWARD)\n {\n position = spline.GetPosition(percentage);\n transform.rotation = Quaternion.LookRotation(spline.GetDirection(Mathf.Max(percentage, 0.01f), true)); // initial rotation\n }\n else if (directionState == DIRECTION.BACKWARD)\n {\n position = spline.GetPosition(1 - percentage);\n transform.rotation = Quaternion.LookRotation(Quaternion.Euler(0, 180, 0) * spline.GetDirection(Mathf.Min(1 - percentage, 0.99f), true)); // initial rotation\n }\n if (raycaster != null && groundLevel != null) transform.position = StickToTheGround(position);\n else transform.position = position;\n\n if (onStart) { StartCoroutine(\"Move\"); }\n }\n\n public void Trigger()\n {\n if (!onStart) { StartCoroutine(\"Move\"); }\n }\n\n void Update()\n {\n\n }\n\n private IEnumerator Move()\n {\n for(; ;)\n {\n if (movingState != STATE.FREEZE)\n {\n /* UPDATE POSITION */\n\n percentage = Mathf.Min(percentage + speed * Time.deltaTime / spline.Length, 1f);\n\n Vector3 position = Vector3.zero;\n if (directionState == DIRECTION.FORWARD)\n {\n position = spline.GetPosition(percentage);\n transform.rotation = Quaternion.LookRotation(spline.GetDirection(percentage, true));\n }\n else if (directionState == DIRECTION.BACKWARD)\n {\n position = spline.GetPosition(1 - percentage);\n transform.rotation = Quaternion.LookRotation(Quaternion.Euler(0, 180, 0) * spline.GetDirection(1 - percentage, true));\n }\n if(raycaster != null && groundLevel != null) transform.position = StickToTheGround(position);\n else transform.position = position;\n\n if (percentage == 1)\n {\n percentage = 0;\n }\n }\n yield return null;\n }\n }\n\n private IEnumerator ResumeMove()\n {\n yield return new WaitForSeconds(freezeDuration);\n movingState = STATE.NORMAL;\n }\n\n private Vector3 StickToTheGround(Vector3 position)\n {\n LayerMask mask = LayerMask.GetMask(\"AsphaltGround\") | LayerMask.GetMask(\"GrassGround\") | LayerMask.GetMask(\"SoilGround\");\n if(Physics.Raycast(raycaster.transform.position, Vector3.down, out RaycastHit hit, Mathf.Infinity, mask))\n {\n return new Vector3(position.x, hit.point.y + groundOffset, position.z);\n }\n return position;\n }\n\n private void OnTriggerStay(Collider other)\n {\n if(other.transform.CompareTag(\"Player\"))\n {\n if (movingState != STATE.FREEZE)\n {\n movingState = STATE.FREEZE;\n StartCoroutine(\"ResumeMove\");\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6096874475479126, "alphanum_fraction": 0.6214040517807007, "avg_line_length": 50.35293960571289, "blob_id": "6cb2029f972c16bb76fb450768d9a3dab4df8e75", "content_id": "fa67ec125a5ef4f7377a9a2e0058ff42958ca572", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 91668, "license_type": "no_license", "max_line_length": 345, "num_lines": 1785, "path": "/SoA-Unity/Assets/Scripts/PlayerControllerB/CameraFollow.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing UnityEngine;\n\npublic class CameraFollow : MonoBehaviour\n{\n\n private Inputs inputs;\n\n private GameObject gameManager;\n\n [Space]\n [Header(\"Camera Settings\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"The character followed by the camera\")]\n private GameObject player;\n\n private float originalYRotation;\n private Vector3 lastPlayerPosition;\n\n [SerializeField]\n [Range(0,20)]\n private float maxChromaticAberration = 10;\n\n [Space]\n\n [SerializeField]\n [Tooltip(\"Camera's translation offset from the player's position\")]\n private Vector3 cameraOffset = new Vector3(0, 1, -10);\n private Vector3 storedCameraOffset;\n\n [SerializeField]\n [Tooltip(\"Camera's angular offset from the player's orientation\")]\n private Vector3 cameraAngularOffset = Vector3.zero;\n\n [SerializeField]\n [Tooltip(\"Speed at which the camera align itself to the character\")]\n [Range(0.1f, 5)]\n private float alignSpeed = 0.6f;\n\n [Space]\n [Header(\"Look around\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"The held camera (must be a child of the camera holder)\")]\n private GameObject heldCamera;\n\n [SerializeField]\n [Tooltip(\"Max horizontal angle of a look around\")]\n [Range(5, 90)]\n private float maxHorizontalAngle = 45; // degrees\n\n [SerializeField]\n [Tooltip(\"Max vertical angle of a look around\")]\n [Range(5, 90)]\n private float maxVerticalAngle = 45; // degrees\n\n [SerializeField]\n [Tooltip(\"Duration to reach the maxHorizontalLookAroundAngle when the input is pushed at max\")]\n [Range(0.1f, 5)]\n private float horizontalDuration = 0.5f; // seconds\n\n [SerializeField]\n [Tooltip(\"Duration to reach the maxVerticalLookAroundAngle when the input is pushed at max\")]\n [Range(0.1f, 5)]\n private float verticalDuration = 0.5f; // seconds\n\n private Vector2 accumulator = Vector2.zero;\n private Vector2 lastInputVector = Vector2.zero;\n private Vector2 startAccumulator = Vector2.zero;\n private Vector2 smoothAccumulator = Vector2.zero;\n\n // Projective Look-Around\n\n private float projectiveAccumulator = 0;\n private float projectiveDistance = 6; // unused\n [SerializeField]\n [Tooltip(\"Duration to reach the projective position in seconds\")]\n [Range(0.1f,1f)]\n private float projectiveDuration = 0.3f; //s\n [SerializeField]\n private Vector3 projectiveOffset = new Vector3(0f, 5f, 20f);\n\n enum STATE { \n NORMAL,\n HURRY,\n PROTECTED,\n NORMAL_TO_HURRY,\n HURRY_TO_NORMAL,\n HURRY_TO_PROTECTED,\n NORMAL_TO_PROTECTED,\n PROTECTED_TO_NORMAL,\n PROTECTED_TO_HURRY,\n HURRY_TO_GAMEOVER,\n PROTECTED_TO_GAMEOVER,\n GAMEOVER\n };\n STATE cameraState;\n STATE lastCameraState;\n\n [Space]\n [Header(\"Normal Mode\")]\n\n [SerializeField]\n [Tooltip(\"The delay to switch from hurry to normal view, in seconds\")]\n [Range(0.1f, 5)]\n private float timeHurryToNormal = 1.5f;\n\n [SerializeField]\n [Tooltip(\"The delay to switch from protected to normal view, in seconds\")]\n [Range(0.1f, 5)]\n private float timeProtectedToNormal = 0.7f;\n\n [Space]\n [Header(\"Hurry Mode\")]\n\n [SerializeField]\n [Tooltip(\"Z-Offset when player is in hurry mode (-closer, +farther)\")]\n [Range(-10, 10)]\n private float Z_OffsetHurry = 2.5f;\n\n [SerializeField]\n [Tooltip(\"Y-Offset when player is in hurry mode (-closer, +farther)\")]\n [Range(-10, 10)]\n private float Y_OffsetHurry = 0;\n\n [SerializeField]\n [Tooltip(\"The delay to switch from normal to hurry view, in seconds\")]\n [Range(0.1f, 5)]\n private float timeNormalToHurry = 0.7f;\n\n [SerializeField]\n [Tooltip(\"The delay to switch from protected to hurry view, in seconds\")]\n [Range(0.1f, 5)]\n private float timeProtectedToHurry = 0.4f;\n\n [Space]\n [Header(\"Protected Mode\")]\n\n [SerializeField]\n [Tooltip(\"Z-Offset when player is in protected mode (-closer, +farther)\")]\n [Range(-10, 10)]\n private float Z_OffsetProtected = -10f;\n\n [SerializeField]\n [Tooltip(\"Y-Offset when player is in hurry mode (-closer, +farther)\")]\n [Range(-10, 10)]\n private float Y_OffsetProtected = 4;\n\n [SerializeField]\n [Tooltip(\"The delay to switch from normal to protected view, in seconds\")]\n [Range(0.1f, 5)]\n private float timeNormalToProtected = 0.7f;\n\n [SerializeField]\n [Tooltip(\"The delay to switch from hurry to protected view, in seconds\")]\n [Range(0.1f, 5)]\n private float timeHurryToProtected = 0.4f;\n\n [Space]\n [Header(\"Gameover Mode\")]\n\n [SerializeField]\n [Tooltip(\"Z-Offset when game is over (-closer, +farther)\")]\n [Range(-10, 10)]\n private float Z_OffsetGameover = -10f;\n\n [SerializeField]\n [Tooltip(\"Y-Offset when game is over (-closer, +farther)\")]\n [Range(-10, 10)]\n private float Y_OffsetGameover = 4f;\n\n [SerializeField]\n [Tooltip(\"The delay to switch from hurry to game over view, in seconds\")]\n [Range(0.1f, 5f)]\n private float timeHurryToGameover = 1f;\n\n [SerializeField]\n [Tooltip(\"The delay to switch from protected to game over view, in seconds\")]\n [Range(0.1f, 5f)]\n private float timeProtectedToGameover = 1f;\n\n [SerializeField]\n [Tooltip(\"The vertical speed of the camera when it flies into the air\")]\n [Range(0,10)]\n private float flyAwaySpeed = 2f;\n\n private float zoomTimer;\n\n private float angleFromNormalToHorizon = 0;\n private float angleFromHurryToHorizon = 0;\n private float angleFromProtectedToHorizon = 0;\n\n [Space]\n [Header(\"Sway\")]\n\n [SerializeField]\n [Tooltip(\"The sway pivot\")]\n private GameObject cameraSway;\n\n [SerializeField]\n [Tooltip(\"The minimal sway radius when in Normal Mode\")]\n [Range(0.001f, 1f)]\n private float swayNormalRadiusMin = 0.01f;\n\n [SerializeField]\n [Tooltip(\"The maximal sway radius when in Normal Mode\")]\n [Range(0.001f, 1f)]\n private float swayNormalRadiusMax = 0.05f;\n\n private float latitude = 0, longitude = 0, swayRadius = 0;\n\n [SerializeField]\n [Tooltip(\"The minimum sway duration when in Normal Mode\")]\n [Range(2f, 10f)]\n private float swayNormalDurationMin = 4f;\n\n [SerializeField]\n [Tooltip(\"The maximum sway duration when in Normal Mode\")]\n [Range(2f, 10f)]\n private float swayNormalDurationMax = 6f;\n\n [SerializeField]\n [Tooltip(\"The minimal sway radius when in Hurry Mode\")]\n [Range(0.001f, 2f)]\n private float swayHurryRadiusMin = 0.8f;\n\n [SerializeField]\n [Tooltip(\"The maximal sway radius when in Hurry Mode\")]\n [Range(0.001f, 2f)]\n private float swayHurryRadiusMax = 1f;\n\n [SerializeField]\n [Range(0.001f, 1f)]\n [Tooltip(\"The minimum sway duration when in Hurry Mode\")]\n private float swayHurryDurationMin = 0.01f;\n\n [SerializeField]\n [Range(0.001f, 1f)]\n [Tooltip(\"The maximum sway duration when in Hurry Mode\")]\n private float swayHurryDurationMax = 0.02f;\n\n private float swayDuration = 0;\n private float swayTimer = 0;\n\n private float swayDurationMin, swayDurationMax;\n private float swayRadiusMin, swayRadiusMax;\n private float backToNormalRadiusSpeed;\n private float backToNormalRadiusAcceleration;\n\n private Vector3 originalSwayPosition = Vector3.zero;\n private Vector3 targetSwayPosition = Vector3.zero;\n\n // Targeting\n\n private bool isTargeting = false;\n private Vector3 startForward = Vector3.zero;\n private Vector3 endForward = Vector3.zero;\n private Vector3 storedForward = Vector3.zero;\n private Quaternion storedRotation = Quaternion.identity;\n private float targetingTimer = 0;\n private Quaternion initialParentRotation = Quaternion.identity;\n private Quaternion currentParentRotation = Quaternion.identity;\n\n [Space]\n [Header(\"Targeting\")]\n\n [SerializeField]\n private GameObject defaultForward;\n\n [SerializeField]\n [Range(0.5f,5f)]\n [Tooltip(\"The total duration of the targeting (pause included) in seconds\")]\n private float targetingDuration = 5;\n\n [SerializeField]\n [Tooltip(\"The pause on the target in seconds\")]\n [Range(0.5f, 2f)]\n private float targetingPause = 1;\n\n private Vector3 targetPosition = Vector3.zero;\n\n private bool isAvailable;\n public bool IsAvailable { get { return isAvailable; } set { isAvailable = value; } }\n\n private bool isPausingAlign;\n public bool IsPausingAlign { get { return isPausingAlign; } set { isPausingAlign = value; } }\n\n [Space]\n [Header(\"Collisions\")]\n\n [SerializeField]\n [Range(1,10)]\n [Tooltip(\"The minimum distance between the camera and an obstacle along its path\")]\n private float minDistanceToObstacle = 2;\n\n [SerializeField]\n [Range(0.1f,5f)]\n [Tooltip(\"The angle in degrees between the start and end of the LineCasts used to approximate a circular cast\")]\n private float maxDegDelta = 1; // degrees\n\n bool isColliding = false; // TO DO : Remove\n float lastDistanceToCollider = Mathf.Infinity; // TO DO : Remove\n private float collidingAlignSpeed = 20; // TO DO : Remove\n\n private LayerMask noCollision;\n\n private void Awake()\n {\n inputs = InputsManager.Instance.Inputs;\n\n gameManager = GameObject.FindGameObjectWithTag(\"GameManager\");\n\n if(gameManager == null)\n {\n throw new System.NullReferenceException(\"No Game Manager found in the scene\");\n }\n }\n\n // Start is called before the first frame update\n void Start()\n {\n storedCameraOffset = cameraOffset;\n originalYRotation = transform.rotation.eulerAngles.y;\n // TO DO : Start from a higher point like an angel coming down\n transform.position = player.transform.position + player.transform.rotation /* * Quaternion.Euler(0,90,0) */ * cameraOffset;\n UpdateRotation();\n lastPlayerPosition = player.transform.position;\n\n // compute the angle between the camera in normal view and horizon view for the look-around stabilization\n //angleFromNormalToHorizon = Vector3.Angle(Vector3.ProjectOnPlane((player.transform.position - transform.position), Vector3.up).normalized, (player.transform.position - transform.position).normalized);\n //angleFromNormalToHorizon -= cameraAngularOffset.x;\n angleFromNormalToHorizon = cameraAngularOffset.x;\n Debug.Log(\"angleFromNormalToHorizon : \" + angleFromNormalToHorizon);\n\n // compute the angle between the camera in normal view and hurry view for the look-around stabilization\n Vector3 hurryPosition = transform.position - Z_OffsetHurry * Vector3.ProjectOnPlane((player.transform.position - transform.position).normalized, Vector3.up) + Y_OffsetHurry * Vector3.up;\n angleFromHurryToHorizon = Vector3.Angle(Vector3.ProjectOnPlane((player.transform.position - hurryPosition), Vector3.up).normalized, (player.transform.position - hurryPosition).normalized);\n angleFromHurryToHorizon += cameraAngularOffset.x; // TO DO : Check this out\n Debug.Log(\"angleFromHurryToHorizon : \" + angleFromHurryToHorizon);\n\n // compute the angle between the camera in normal view and protected view for the look-around stabilization\n Vector3 protectedPosition = transform.position - Z_OffsetProtected * Vector3.ProjectOnPlane((player.transform.position - transform.position).normalized, Vector3.up) + Y_OffsetProtected * Vector3.up;\n angleFromProtectedToHorizon = Vector3.Angle(Vector3.ProjectOnPlane((player.transform.position - protectedPosition), Vector3.up).normalized, (player.transform.position - protectedPosition).normalized);\n angleFromProtectedToHorizon += cameraAngularOffset.x; // TO DO : Check this out\n Debug.Log(\"angleFromProtectedToHorizon : \" + angleFromProtectedToHorizon);\n\n //FX\n heldCamera.transform.GetChild(0).GetComponent<Render_PostProcess>().shader_actif = true;\n heldCamera.transform.GetChild(0).GetComponent<Render_PostProcess>().coef_blur = 1000;\n heldCamera.transform.GetChild(0).GetComponent<Render_PostProcess>().radius = 5;\n\n\n cameraState = STATE.NORMAL;\n zoomTimer = 0;\n isAvailable = true;\n isPausingAlign = false;\n noCollision = ~ (LayerMask.GetMask(\"NoObstacle\") | LayerMask.GetMask(\"Shelter Entrance\") | LayerMask.GetMask(\"Shelter Exit\"));\n\n if (cameraSway != null)\n {\n InitializeSway();\n StartCoroutine(\"Sway\");\n }\n\n //StartCoroutine(\"AlignWithCharacter\");\n StartCoroutine(\"AlignWithCharacter2\");\n }\n void UpdateFromInspector()\n {\n if (cameraOffset != storedCameraOffset)\n {\n transform.position += (cameraOffset - storedCameraOffset);\n storedCameraOffset = cameraOffset;\n }\n }\n\n public void ResetCameraToFrontView()\n {\n lastPlayerPosition = player.transform.position; // disable following during the warp\n transform.position = player.transform.position + Quaternion.LookRotation(-player.transform.forward, Vector3.up) * cameraOffset;\n\n zoomTimer = 0; // check if correct\n cameraState = STATE.NORMAL;\n\n // do not align until first player move\n isPausingAlign = true;\n }\n\n private void OnEnable()\n {\n // might trigger inputs back during warp to shelter ???\n // inputs.Player.Enable();\n }\n\n private void OnDisable()\n {\n inputs.Player.Disable();\n }\n\n // Update is called once per frame\n void LateUpdate()\n {\n UpdateFX();\n\n if (!player.GetComponent<PlayerFirst>().IsInsideShelter)\n {\n //UpdatePosition();\n\n UpdateRotation();\n\n if (!isTargeting)\n {\n //LookAround(inputs.Player.LookAround.ReadValue<Vector2>());\n //ProjectiveLookAround(inputs.Player.ProjectiveLook.ReadValue<float>());\n //ExtendedLookAround(inputs.Player.LookAround.ReadValue<Vector2>());\n SmoothLookAround(inputs.Player.LookAround.ReadValue<Vector2>());\n //SmoothProjectiveLookAround(inputs.Player.LookAround.ReadValue<Vector2>());\n }\n if (cameraSway != null)\n {\n //Sway(); // Let's try this here\n }\n }\n }\n\n /* Chroma Offset Effect */\n private void UpdateFX()\n {\n float factor = maxChromaticAberration * (1 - player.GetComponent<EnergyBehaviour>().Energy / 1000);\n heldCamera.transform.GetChild(0).GetComponent<Render_PostProcess>().offsetChroma = new Vector3(factor, 0, 0);\n //heldCamera.transform.GetChild(0).GetComponent<Render_PostProcess>().coef_blur = (player.GetComponent<EnergyBehaviour>().Energy / 1000) * 700 + 300;\n }\n\n private void UpdateRotation ()\n {\n if (cameraState == STATE.NORMAL)\n {\n transform.rotation = Quaternion.LookRotation(Vector3.ProjectOnPlane((player.transform.position - transform.position), Vector3.up)); // kind of a lookAt but without the rotation around the x-axis\n\n transform.rotation *= Quaternion.Euler(cameraAngularOffset.x, cameraAngularOffset.y, cameraAngularOffset.z); // TO DO : ONLY IN NORMAL !!!!!\n }\n else if (cameraState == STATE.NORMAL_TO_HURRY) // focus on the character\n {\n Vector3 startPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetHurry + Vector3.up * Y_OffsetHurry) * (timeNormalToHurry - zoomTimer) / timeNormalToHurry; // recreate original position\n Vector3 endPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetHurry + Vector3.up * Y_OffsetHurry) * zoomTimer / timeNormalToHurry; // recreate original position\n Vector3 start = Vector3.ProjectOnPlane((player.transform.position - startPosition), Vector3.up).normalized;\n // TO DO : Check this out\n start = Quaternion.AngleAxis(-cameraAngularOffset.x, Vector3.Cross(start, Vector3.up)).normalized * start;\n Vector3 end = (player.transform.position - endPosition).normalized;\n //float smoothstep = Mathf.SmoothStep(0.0f, 1.0f, (timeToFocus - recoilTimer) / timeToFocus);\n Vector3 current = Vector3.Slerp(start, end, (timeNormalToHurry - zoomTimer) / timeNormalToHurry);\n //Debug.Log(\"Start : \" + start + \", End : \" + end + \", Angle : \" + current + \", timeToFocus : \" + timeToFocus + \", recoilTimer : \" + recoilTimer);\n transform.rotation = Quaternion.LookRotation(current);\n \n\n //heldCamera.GetComponent<Camera>().fieldOfView = 60 - (60 - 50) * (timeToFocus - recoilTimer) / timeToFocus;\n }\n else if (cameraState == STATE.HURRY)\n {\n transform.rotation = Quaternion.LookRotation(player.transform.position - transform.position);\n }\n\n else if (cameraState == STATE.PROTECTED)\n {\n transform.rotation = Quaternion.LookRotation(player.transform.position - transform.position);\n }\n else if (cameraState == STATE.HURRY_TO_NORMAL)\n {\n Vector3 startPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetHurry + Vector3.up * Y_OffsetHurry) * (timeHurryToNormal - zoomTimer) / timeHurryToNormal; // recreate original position\n Vector3 endPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetHurry + Vector3.up * Y_OffsetHurry) * zoomTimer / timeHurryToNormal; // recreate original position\n Vector3 start = (player.transform.position - startPosition).normalized;\n Vector3 end = Vector3.ProjectOnPlane((player.transform.position - endPosition), Vector3.up).normalized;\n // TO DO : Check this out\n end = Quaternion.AngleAxis(-cameraAngularOffset.x, Vector3.Cross(end, Vector3.up)).normalized * end;\n //float smoothstep = Mathf.SmoothStep(0.0f, 1.0f, (timeToNormal - recoilTimer) / timeToNormal);\n Vector3 current = Vector3.Slerp(start, end, (timeHurryToNormal - zoomTimer) / timeHurryToNormal);\n //Debug.Log(\"Start : \" + start + \", End : \" + end + \", Angle : \" + current + \", timeToNormal : \" + timeToNormal + \", recoilTimer : \" + recoilTimer);\n transform.rotation = Quaternion.LookRotation(current);\n\n //heldCamera.GetComponent<Camera>().fieldOfView = 60 - (60 - 50) * recoilTimer / timeToNormal;\n }\n else if (cameraState == STATE.NORMAL_TO_PROTECTED) // focus on the character\n {\n Vector3 startPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetProtected + Vector3.up * Y_OffsetProtected) * (timeNormalToProtected - zoomTimer) / timeNormalToProtected; // recreate original position\n Vector3 endPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetProtected + Vector3.up * Y_OffsetProtected) * zoomTimer / timeNormalToProtected; // recreate original position\n Vector3 start = Vector3.ProjectOnPlane((player.transform.position - startPosition), Vector3.up).normalized;\n // TO DO : Check this out\n start = Quaternion.AngleAxis(-cameraAngularOffset.x, Vector3.Cross(start, Vector3.up)).normalized * start;\n Vector3 end = (player.transform.position - endPosition).normalized;\n //float smoothstep = Mathf.SmoothStep(0.0f, 1.0f, (timeToFocus - recoilTimer) / timeToFocus);\n Vector3 current = Vector3.Slerp(start, end, (timeNormalToProtected - zoomTimer) / timeNormalToProtected);\n //Debug.Log(\"Start : \" + start + \", End : \" + end + \", Angle : \" + current + \", timeToFocus : \" + timeToFocus + \", recoilTimer : \" + recoilTimer);\n transform.rotation = Quaternion.LookRotation(current);\n\n //heldCamera.GetComponent<Camera>().fieldOfView = 60 - (60 - 50) * (timeToFocus - recoilTimer) / timeToFocus;\n }\n else if (cameraState == STATE.PROTECTED_TO_NORMAL)\n {\n Vector3 startPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetProtected + Vector3.up * Y_OffsetProtected) * (timeProtectedToNormal - zoomTimer) / timeProtectedToNormal; // recreate original position\n Vector3 endPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetProtected + Vector3.up * Y_OffsetProtected) * zoomTimer / timeProtectedToNormal; // recreate original position\n Vector3 start = (player.transform.position - startPosition).normalized;\n Vector3 end = Vector3.ProjectOnPlane((player.transform.position - endPosition), Vector3.up).normalized;\n // TO DO : Check this out\n end = Quaternion.AngleAxis(-cameraAngularOffset.x, Vector3.Cross(end, Vector3.up)).normalized * end;\n //float smoothstep = Mathf.SmoothStep(0.0f, 1.0f, (timeToNormal - recoilTimer) / timeToNormal);\n Vector3 current = Vector3.Slerp(start, end, (timeProtectedToNormal - zoomTimer) / timeProtectedToNormal);\n //Debug.Log(\"Start : \" + start + \", End : \" + end + \", Angle : \" + current + \", timeToNormal : \" + timeToNormal + \", recoilTimer : \" + recoilTimer);\n transform.rotation = Quaternion.LookRotation(current);\n\n //heldCamera.GetComponent<Camera>().fieldOfView = 60 - (60 - 50) * recoilTimer / timeToNormal;\n }\n else if (cameraState == STATE.PROTECTED_TO_HURRY)\n {\n // TO DEBUG\n /*\n Vector3 startPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * -(Z_OffsetProtected - Z_OffsetHurry) + Vector3.up * -(Y_OffsetProtected - Y_OffsetHurry)) * (timeProtectedToHurry - zoomTimer) / timeProtectedToHurry; // recreate original position\n Vector3 endPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * -(Z_OffsetProtected - Z_OffsetHurry) + Vector3.up * -(Y_OffsetProtected - Y_OffsetHurry)) * zoomTimer / timeProtectedToHurry; // recreate original position\n Vector3 start = (player.transform.position - startPosition).normalized; // no projection on both start and end\n Vector3 end = (player.transform.position - endPosition).normalized;\n //float smoothstep = Mathf.SmoothStep(0.0f, 1.0f, (timeToFocus - recoilTimer) / timeToFocus);\n Vector3 current = Vector3.Slerp(start, end, (timeProtectedToHurry - zoomTimer) / timeProtectedToHurry);\n //Debug.Log(\"Start : \" + start + \", End : \" + end + \", Angle : \" + current + \", timeToFocus : \" + timeToFocus + \", recoilTimer : \" + recoilTimer);\n transform.rotation = Quaternion.LookRotation(current);\n */\n\n\n transform.rotation = Quaternion.LookRotation(player.transform.position - transform.position);\n //heldCamera.GetComponent<Camera>().fieldOfView = 60 - (60 - 50) * (timeToFocus - recoilTimer) / timeToFocus;\n }\n else if (cameraState == STATE.HURRY_TO_PROTECTED)\n {\n // TO DEBUG\n\n /*\n Vector3 startPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * -(Z_OffsetHurry - Z_OffsetProtected) + Vector3.up * -(Y_OffsetHurry - Y_OffsetProtected)) * (timeHurryToProtected - zoomTimer) / timeHurryToProtected; // recreate original position\n Vector3 endPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * -(Z_OffsetHurry - Z_OffsetProtected) + Vector3.up * -(Y_OffsetHurry - Y_OffsetProtected)) * zoomTimer / timeHurryToProtected; // recreate original position\n Vector3 start = (player.transform.position - startPosition).normalized; // no projection on both start and end\n Vector3 end = (player.transform.position - endPosition).normalized;\n //float smoothstep = Mathf.SmoothStep(0.0f, 1.0f, (timeToFocus - recoilTimer) / timeToFocus);\n Vector3 current = Vector3.Slerp(start, end, (timeHurryToProtected - zoomTimer) / timeHurryToProtected);\n //Debug.Log(\"Start : \" + start + \", End : \" + end + \", Angle : \" + current + \", timeToFocus : \" + timeToFocus + \", recoilTimer : \" + recoilTimer);\n transform.rotation = Quaternion.LookRotation(current);*/\n\n transform.rotation = Quaternion.LookRotation(player.transform.position - transform.position);\n\n //heldCamera.GetComponent<Camera>().fieldOfView = 60 - (60 - 50) * (timeToFocus - recoilTimer) / timeToFocus;\n }\n\n else if (cameraState == STATE.HURRY_TO_GAMEOVER)\n {\n transform.rotation = Quaternion.LookRotation(player.transform.position - transform.position);\n }\n\n else if (cameraState == STATE.PROTECTED_TO_GAMEOVER)\n {\n transform.rotation = Quaternion.LookRotation(player.transform.position - transform.position);\n }\n\n else if (cameraState == STATE.GAMEOVER)\n {\n transform.rotation = Quaternion.LookRotation(player.transform.position - transform.position);\n }\n }\n\n private void UpdatePosition()\n {\n // if values have changed in the inspector\n UpdateFromInspector();\n\n // adapt recoil to normal, hurry or protected mode from the player\n UpdateRecoilPosition();\n\n if (player.transform.position != lastPlayerPosition)\n {\n //Debug.Log(\"Camera moving in \" + transform.position);\n transform.position += (player.transform.position - lastPlayerPosition);\n lastPlayerPosition = player.transform.position;\n }\n }\n\n private bool CheckPlayerMovement()\n {\n return (player.transform.position != lastPlayerPosition);\n }\n\n private IEnumerator AlignWithCharacter()\n {\n for(; ;)\n {\n UpdatePosition(); // called here to avoid desynchronization\n\n float angle = Vector3.SignedAngle(Vector3.ProjectOnPlane(transform.forward, Vector3.up).normalized, player.transform.forward, Vector3.up) % 360;\n\n float smooth = 0.95f * -Mathf.Pow((Mathf.Abs(angle) / 180f - 1), 2) + 1; // [0.05-1]\n\n if (Mathf.Abs(angle) >= alignSpeed * smooth * Time.deltaTime)\n {\n transform.RotateAround(player.transform.position, Vector3.up, Mathf.Sign(angle) * alignSpeed * smooth * Time.deltaTime);\n transform.rotation *= Quaternion.Euler(0, originalYRotation, 0);\n }\n else if (!Mathf.Approximately(angle, 0))\n {\n transform.RotateAround(player.transform.position, Vector3.up, angle);\n transform.rotation *= Quaternion.Euler(0, originalYRotation, 0);\n }\n yield return null;\n }\n }\n\n private IEnumerator AlignWithCharacter2()\n {\n if (!isTargeting) // CHECK IF CORRECT ?? SHOULDN'T IT BE INSIDE THE FOR LOOP ?\n {\n\n float targetAngle, newTargetAngle;\n float thisPercent, previousPercent;\n float thisSinerp, previousSinerp;\n\n // alignSpeed = 50; // ONLY FOR DEBUG\n\n for (; ; )\n {\n while(player.GetComponent<PlayerFirst>().IsInsideShelter)\n { \n yield return null;\n }\n\n while(isTargeting) // Let's try it here, CHECK IF WORKING\n {\n yield return null;\n }\n\n while (isPausingAlign)\n {\n //Debug.Log(\"Align en pause\");\n yield return null;\n if(CheckPlayerMovement())\n {\n //Debug.Log(\"Sorti de pause\");\n isPausingAlign = false;\n }\n }\n\n Vector3 originalPosition = transform.position; // used in LimitAngleToFirstObstacle\n\n targetAngle = Vector3.SignedAngle(Vector3.ProjectOnPlane(transform.forward, Vector3.up).normalized, player.transform.forward, Vector3.up) % 360;\n float lastTargetAngle = targetAngle; // save the last true angle\n Debug.Log(\"My target angle is \" + targetAngle);\n targetAngle = LimitAngleToFirstObstacle(targetAngle, originalPosition);\n Debug.Log(\"My target angle, taking obstacle into account, is \" + targetAngle);\n\n float factor = 1;\n\n // if camera not aligned with the closest position to be aligned with the character\n\n if (!Mathf.Approximately(targetAngle, 0.0f))\n {\n Debug.Log(\"Start of an interpolation, angle : \" + targetAngle);\n\n Vector3 startForward = Vector3.ProjectOnPlane(transform.forward, Vector3.up).normalized;\n thisPercent = 0;\n thisSinerp = 0;\n previousPercent = 0;\n\n float debugSum = 0;\n\n // Launch an interpolation\n\n while (thisPercent != 1.0f)\n {\n UpdatePosition(); // called here to avoid desynchronization \n\n // Compute the angle from the current camera position to the align with the new character position\n\n newTargetAngle = Vector3.SignedAngle(startForward, player.transform.forward, Vector3.up);\n if (Mathf.Abs(newTargetAngle - lastTargetAngle) < 0.001f) // discard computationnal errors\n {\n newTargetAngle = lastTargetAngle;\n }\n lastTargetAngle = newTargetAngle;\n\n // SignedAngle's return value is in domain [-180;180], so extend it\n\n if (Mathf.Sign(newTargetAngle) != Mathf.Sign(targetAngle))\n {\n if((targetAngle - newTargetAngle) > 180)\n {\n newTargetAngle += 360;\n Debug.Log(\"Warp newAngle : \" + newTargetAngle);\n }\n else if ((newTargetAngle - targetAngle) > 180)\n {\n newTargetAngle -= 360;\n Debug.Log(\"Warp newAngle : \" + newTargetAngle);\n }\n }\n\n // Next, check if there is a collision along the new rotation path\n\n newTargetAngle = LimitAngleToFirstObstacle(newTargetAngle, originalPosition);\n\n Debug.Log(\"New angle is : \" + newTargetAngle + \", last one was \" + targetAngle);\n\n if (!Mathf.Approximately(newTargetAngle, targetAngle))\n {\n // Get the original [0-1] from the smooth [0-1] updated with the angle modification, need clamping because Asin's domain is [-1,1]\n\n if (!Mathf.Approximately(newTargetAngle, 0)) // avoid dividing by zero\n {\n Debug.Log(\"New angle is different, remapping the percentage ...\");\n thisPercent = InverseSinerp(thisSinerp * Mathf.Abs(targetAngle / newTargetAngle)); // Mathf.Abs to handle change in sign during interpolation\n }\n else\n {\n thisPercent = 1;\n }\n }\n previousPercent = thisPercent; // VERY IMPORTANT !!!!! NOT THE TRUE PREVIOUS PERCENT, THE ONE RECOMPUTED ACCORDING TO THE NEW ANGLE !!!!\n\n // Hurry up if there's an obstacle between the camera and the character\n\n if(Physics.Linecast(transform.position, player.transform.position, out RaycastHit hit, noCollision))\n {\n if( ! hit.transform.CompareTag(\"Player\"))\n {\n //Debug.Log(\"COLLISION WITH : \" + hit.transform.name);\n factor = Mathf.Min(factor + 10 * Time.deltaTime, 3);\n }\n else\n {\n factor = Mathf.Max(factor - 10 * Time.deltaTime, 1);\n }\n }\n\n // TO DO : Equivalent for behind when the character is facing the camera\n\n // Increment to next position\n\n Debug.Log(\"Linear evolution this frame : \" + factor + \" * \" + alignSpeed + \" * \" + Time.deltaTime + \" = \" + factor * alignSpeed * Time.deltaTime * Mathf.Abs(newTargetAngle) / 180f);\n thisPercent = Mathf.Min(thisPercent + factor * alignSpeed * Time.deltaTime, 1.0f); // TO CHECK : Dependant to angle gives quite another gamefeel\n\n //previousSinerp = thisSinerp;\n previousSinerp = Sinerp(previousPercent); // HOW IS IT DIFFERENT FROM THE LINE ABOVE ????\n thisSinerp = Sinerp(thisPercent);\n\n //Debug.Log(\"Rotation delta : \" + angle * (thisSinerp - previousSinerp) + \" from angle=\" + angle + \", thisSinerp=\" + thisSinerp + \", previousSinerp=\" + previousSinerp + \", thisFrame=\" + thisFrame + \", previousFrame=\" + previousFrame);\n debugSum += newTargetAngle * (thisSinerp - previousSinerp);\n\n transform.RotateAround(player.transform.position, Vector3.up, newTargetAngle * (thisSinerp - previousSinerp)); // <-- ERROR, THE SUM OF THE FRACTIONS DOESNT RESULT IN newAngle AT THE END\n transform.rotation *= Quaternion.Euler(0, originalYRotation, 0);\n\n Debug.Log(\"Angle interpolation is at t = \" + thisSinerp + \", (\" + (newTargetAngle * thisSinerp) + \" /\" + newTargetAngle + \")\");\n\n targetAngle = newTargetAngle;\n\n yield return null;\n }\n Debug.Log(\"End of the interpolation, angle : \" + targetAngle);\n Debug.Log(\"True angle done : \" + debugSum);\n Debug.Log(\"---------------------------------------------\");\n }\n else\n {\n UpdatePosition(); // called here to avoir desynchronization\n\n /* Test for collisions */\n\n yield return null;\n }\n }\n }\n }\n\n private float LimitAngleToFirstObstacle(float targetAngle, Vector3 originalPosition)\n {\n float startAngle = 0; // degrees\n Vector3 startPosition = originalPosition,\n startForward = startPosition - player.transform.position;\n\n float endAngle = 0; // degrees\n Vector3 endPosition = originalPosition,\n endForward = endPosition - player.transform.position;\n\n int i_forward = 0;\n\n while (Mathf.Abs(startAngle) < Mathf.Abs(targetAngle)) // SIGN !!!!!\n {\n endAngle = Mathf.Sign(targetAngle) > 0 ? Mathf.Min(startAngle + maxDegDelta, targetAngle) : Mathf.Max(startAngle - maxDegDelta, targetAngle);\n endForward = Quaternion.Euler(0, endAngle - startAngle, 0) * startForward;\n endPosition = player.transform.position + endForward;\n\n // Hit once, on the first obstacle met\n RaycastHit hit;\n if (Physics.Linecast(startPosition, endPosition, out hit, noCollision))\n {\n Vector3 obstaclePosition = hit.point;\n float distanceToObstacle = ArcLength(endForward.magnitude, Vector3.Angle(startPosition - player.transform.position, obstaclePosition - player.transform.position));\n\n int i_backward = 0;\n bool visibility = true;\n\n if (Physics.Linecast(startPosition, player.transform.position, out hit, noCollision)) // CHECK if childs should be on layer Play as well\n {\n if (hit.transform.CompareTag(\"Player\")){ visibility = true; }\n else { visibility = false; /*Debug.Log(\"OCCLUSION WITH \" + hit.transform.name + \" INSIDE \" + hit.transform.parent.name + \" INSIDE \" + hit.transform.parent.parent.name);*/}\n }\n\n // Backward tracking if too close to the obstacle, use arc-length for the distances\n\n while ((distanceToObstacle < minDistanceToObstacle\n || visibility == false)\n && Mathf.Abs(endAngle) < 180) // No backtrack under -180 or above 180 // startAngle or endAngle ??????\n {\n // Backtrack to 0, SPECIAL CASE : WHAT HAPPEN WHEN EVEN 0 IS NOT ENOUGH TO RESPECT THE MINDISTANCE !!!!!!!!!!!!!!\n\n endAngle = Mathf.Sign(targetAngle) > 0 ? Mathf.Max(startAngle - maxDegDelta, -180) : Mathf.Min(startAngle + maxDegDelta, 180);\n endForward = Quaternion.Euler(0, endAngle - startAngle, 0) * startForward;\n endPosition = player.transform.position + endForward;\n\n distanceToObstacle = ArcLength(endForward.magnitude, Vector3.Angle(obstaclePosition - player.transform.position, endPosition - player.transform.position));\n\n startAngle = endAngle;\n startForward = endForward;\n startPosition = endPosition;\n\n // Check for occlusions\n\n if (Physics.Linecast(startPosition, player.transform.position, out hit, noCollision)) // CHECK if childs should be on layer Play as well\n {\n if (hit.transform.CompareTag(\"Player\"))\n {\n visibility = true;\n }\n else\n {\n visibility = false;\n Debug.Log(\"OCCLUSION\");\n }\n }\n\n //Debug.Log(\"One node backtracked \" + startAngle + \"/\" + targetAngle); i_backward++;\n }\n Debug.Log(\"Crossed \" + i_forward + \" nodes but then backtracked \" + i_backward + \" nodes from the hit obstacle\");\n return startAngle; // CHECK : Should it be startAngle or endAngle ?\n }\n\n i_forward++;\n //Debug.Log(\"One node crossed : \" + endAngle + \"/\" + targetAngle);\n\n // Debug.DrawLine(startPosition, endPosition, Color.blue, 2f, false);\n\n // Start is now End\n\n startAngle = endAngle;\n startForward = endForward;\n startPosition = player.transform.position + startForward; // height ???? it's a the ground level not at the camera's height !!!\n\n /* If reached the target without a single collision,\n * we still have to check for minDistance */\n\n if (Mathf.Approximately(startAngle, targetAngle))\n {\n Debug.Log(\"Reached the targetAngle without any obstacle, now looking-forward\");\n\n float forwardCheckingAngle = Mathf.Sign(targetAngle) * InverseArcLength(startForward.magnitude, minDistanceToObstacle); // SIGN !!!!!!!!!!!!!!!!!!!!! / Should increment on startAngle ?\n Vector3 forwardCheckingForward = Quaternion.Euler(0, forwardCheckingAngle, 0) * startForward;\n Vector3 forwardCheckingPosition = player.transform.position + forwardCheckingForward;\n\n // Do a forward-checking to guarantee the minDistance\n\n int i_lf_backward = 0;\n float distanceToObstacle = Mathf.Infinity;\n Vector3 obstaclePosition = Vector3.positiveInfinity;\n\n if (Physics.Linecast(startPosition, forwardCheckingPosition, out hit, noCollision))\n {\n Debug.Log(\"Hit obstacle during looking-forward\");\n\n obstaclePosition = hit.point;\n distanceToObstacle = ArcLength(startForward.magnitude, Vector3.Angle(obstaclePosition - player.transform.position, startPosition - player.transform.position));\n }\n\n bool visibility = true;\n\n if (Physics.Linecast(startPosition, player.transform.position, out hit, noCollision)) // CHECK if childs should be on layer Play as well\n {\n if(hit.transform.CompareTag(\"Player\"))\n {\n visibility = true;\n }\n else\n {\n visibility = false;\n Debug.Log(\"OCCLUSION\");\n }\n }\n\n // If position isn't available, start a backtracking\n\n while ((distanceToObstacle < minDistanceToObstacle\n || visibility == false)\n && Mathf.Abs(endAngle) < 180) // SIGN !!! No backtrack under -180 or above 180 // startAngle or endAngle ??????\n {\n // Backtrack to 0, SPECIAL CASE : WHEN EVEN 0 IS NOT ENOUGH TO RESPECT THE MINDISTANCE !!!!!!!!!!!!!! WE CAN'T GO UNDER 0 BECAUSE WE DON'T KNOW IF THERE ARE OBSTACLES THERE\n i_lf_backward++;\n\n endAngle = Mathf.Sign(targetAngle) > 0 ? Mathf.Max(startAngle - maxDegDelta, -180) : Mathf.Min(startAngle + maxDegDelta, 180); // 180 degrees beyond 0\n endForward = Quaternion.Euler(0, endAngle - startAngle, 0) * startForward;\n endPosition = player.transform.position + endForward;\n\n if (distanceToObstacle != Mathf.Infinity)\n distanceToObstacle = ArcLength(endForward.magnitude, Vector3.Angle(obstaclePosition - player.transform.position, startPosition - player.transform.position)); // CHECK : startPosition or endPosition ???\n\n startAngle = endAngle;\n startForward = endForward;\n startPosition = endPosition;\n\n // Check for occlusions\n\n if (Physics.Linecast(startPosition, player.transform.position, out hit, noCollision)) // CHECK if childs should be on layer Play as well\n {\n if (hit.transform.CompareTag(\"Player\"))\n {\n visibility = true;\n }\n else\n {\n visibility = false;\n Debug.Log(\"OCCLUSION\");\n }\n }\n\n // If angle has backtracked to the other side, check for collision on this unknown side\n // No need to check for minDistance as we have already checked every other solution\n // So on the first opposite obstacle, we know we have no solutions left\n\n if ((endAngle < 0 && targetAngle > 0) || (endAngle > 0 && targetAngle < 0))\n {\n if (Physics.Linecast(startPosition, endPosition, out hit, noCollision))\n {\n // no solution, return default angle\n Debug.Log(\"No solution for visibility, reseting angle to 0\");\n return 0;\n }\n }\n }\n\n Debug.Log(\"Crossed \" + i_forward + \" nodes and backtracked \" + i_lf_backward + \" nodes from the obstacle\");\n return startAngle; // should it be startAngle or endAngle ?\n }\n\n // END\n }\n\n return targetAngle;\n }\n\n float Sinerp(float x)\n {\n if (!(0 <= x && x <= 1))\n {\n throw new System.Exception(\"Sinerp argument must be in range [0-1] : \" + x);\n }\n return Mathf.Sin(x * Mathf.PI / 2f);\n }\n\n float InverseSinerp(float x)\n {\n return Mathf.Asin(Mathf.Clamp(x, -1.0f, 1.0f)) * 2f / Mathf.PI; // get the original [0-1] from the smooth [0-1] updated with the angle modification, need clamping because Asin's domain is [-1,1]\n }\n\n float ArcLength(float radius, float angle)\n {\n return 2f * Mathf.PI * radius * (angle / 360f);\n }\n\n float InverseArcLength(float radius, float arcLength)\n {\n return (360f * arcLength) / (2f * Mathf.PI * radius);\n }\n\n void LookAround(Vector2 v)\n {\n float smoothx = 0;\n float smoothy = 0;\n\n //Debug.Log(\"Accumulator : \" + accumulator);\n\n if (!Mathf.Approximately(v.x, 0))\n {\n accumulator.x = Mathf.Clamp(accumulator.x + v.x * Time.deltaTime / horizontalDuration, -1, 1);\n smoothx = Mathf.Sign(accumulator.x) * Mathf.Sin(Mathf.Abs(accumulator.x) * Mathf.PI * 0.5f);\n }\n else\n {\n accumulator.x = (1 - Mathf.Sign(accumulator.x)) / 2f * Mathf.Min(accumulator.x - Mathf.Sign(accumulator.x) * Time.deltaTime / horizontalDuration, 0) + (1 + Mathf.Sign(accumulator.x)) / 2f * Mathf.Max(accumulator.x - Mathf.Sign(accumulator.x) * Time.deltaTime / horizontalDuration, 0);\n smoothx = Mathf.Sign(accumulator.x) * Mathf.Sin(Mathf.Abs(accumulator.x) * Mathf.PI * 0.5f);\n }\n\n if (!Mathf.Approximately(v.y, 0))\n {\n accumulator.y = Mathf.Clamp(accumulator.y + v.y * Time.deltaTime / verticalDuration, -1, 1);\n smoothy = Mathf.Sign(accumulator.y) * Mathf.Sin(Mathf.Abs(accumulator.y) * Mathf.PI * 0.5f);\n }\n else\n {\n accumulator.y = (1 - Mathf.Sign(accumulator.y)) / 2f * Mathf.Min(accumulator.y - Mathf.Sign(accumulator.y) * Time.deltaTime / verticalDuration, 0) + (1 + Mathf.Sign(accumulator.y)) / 2f * Mathf.Max(accumulator.y - Mathf.Sign(accumulator.y) * Time.deltaTime / verticalDuration, 0);\n smoothy = Mathf.Sign(accumulator.y) * Mathf.Sin(Mathf.Abs(accumulator.y) * Mathf.PI * 0.5f);\n }\n\n // Stabilization of the look around\n float y_stabilization = 0;\n if (cameraState == STATE.NORMAL) { y_stabilization = Mathf.Abs(smoothx) * -angleFromNormalToHorizon; }\n\n else if (cameraState == STATE.HURRY) { y_stabilization = Mathf.Abs(smoothx) * -angleFromHurryToHorizon; }\n else if (cameraState == STATE.NORMAL_TO_HURRY) { y_stabilization = Mathf.Abs(smoothx) * (-angleFromNormalToHorizon * zoomTimer / timeNormalToHurry - angleFromHurryToHorizon * (timeNormalToHurry - zoomTimer) / timeNormalToHurry); }\n else if (cameraState == STATE.HURRY_TO_NORMAL) { y_stabilization = Mathf.Abs(smoothx) * (-angleFromHurryToHorizon * zoomTimer / timeHurryToNormal - angleFromNormalToHorizon * (timeHurryToNormal - zoomTimer) / timeHurryToNormal); ; }\n\n else if (cameraState == STATE.PROTECTED) { y_stabilization = Mathf.Abs(smoothx) * -angleFromProtectedToHorizon; }\n else if (cameraState == STATE.NORMAL_TO_PROTECTED) { y_stabilization = Mathf.Abs(smoothx) * (-angleFromNormalToHorizon * zoomTimer / timeNormalToProtected - angleFromProtectedToHorizon * (timeNormalToProtected - zoomTimer) / timeNormalToProtected); }\n else if (cameraState == STATE.PROTECTED_TO_NORMAL) { y_stabilization = Mathf.Abs(smoothx) * (-angleFromProtectedToHorizon * zoomTimer / timeProtectedToNormal - angleFromNormalToHorizon * (timeProtectedToNormal - zoomTimer) / timeProtectedToNormal); }\n\n else if (cameraState == STATE.HURRY_TO_PROTECTED) { y_stabilization = Mathf.Abs(smoothx) * (-angleFromHurryToHorizon * zoomTimer / timeHurryToProtected - angleFromProtectedToHorizon * (timeHurryToProtected - zoomTimer) / timeHurryToProtected); }\n else if (cameraState == STATE.PROTECTED_TO_HURRY) { y_stabilization = Mathf.Abs(smoothx) * (-angleFromProtectedToHorizon * zoomTimer / timeProtectedToHurry - angleFromHurryToHorizon * (timeProtectedToHurry - zoomTimer) / timeProtectedToHurry); }\n\n // Must be separated in two because unity's order for euler is ZYX and we want X-Y-X\n //heldCamera.transform.localRotation = Quaternion.Euler(-smoothy * maxLookAroundAngle, smoothx * maxLookAroundAngle, 0);\n heldCamera.transform.localRotation = Quaternion.Euler(y_stabilization, 0, 0);\n heldCamera.transform.localRotation *= Quaternion.Euler(0, smoothx * maxHorizontalAngle, 0);\n heldCamera.transform.localRotation *= Quaternion.Euler(-smoothy * maxVerticalAngle, 0, 0);\n }\n\n void SmoothLookAround(Vector2 inputVector)\n {\n if (!Mathf.Approximately(inputVector.x, 0))\n {\n if (lastInputVector.x == 0 || inputVector.x < 0 && lastInputVector.x > 0 || inputVector.x > 0 && lastInputVector.x < 0)\n {\n accumulator.x = smoothAccumulator.x;\n startAccumulator.x = accumulator.x;\n }\n else\n {\n // WHY HERE ?\n accumulator.x = Mathf.Clamp(accumulator.x + inputVector.x * Time.deltaTime / horizontalDuration, -1, 1);\n }\n\n if (!Mathf.Approximately(Mathf.Sign(inputVector.x), startAccumulator.x)) // avoid dividing by zero\n {\n smoothAccumulator.x = Mathf.SmoothStep(startAccumulator.x, Mathf.Sign(inputVector.x), Mathf.Abs(accumulator.x - startAccumulator.x) / Mathf.Abs((Mathf.Sign(inputVector.x) - startAccumulator.x)));\n }\n else\n {\n smoothAccumulator.x = 1.0f;\n }\n\n lastInputVector.x = inputVector.x;\n }\n else\n {\n if (accumulator.x == 0)\n {\n startAccumulator.x = 0;\n }\n if (lastInputVector.x != 0)\n {\n accumulator.x = smoothAccumulator.x;\n startAccumulator.x = accumulator.x;\n }\n else\n {\n // WHY HERE ?\n accumulator.x = (1 - Mathf.Sign(accumulator.x)) / 2f * Mathf.Min(accumulator.x - Mathf.Sign(accumulator.x) * Time.deltaTime / horizontalDuration, 0) + (1 + Mathf.Sign(accumulator.x)) / 2f * Mathf.Max(accumulator.x - Mathf.Sign(accumulator.x) * Time.deltaTime / horizontalDuration, 0);\n }\n\n if (startAccumulator.x != 0)\n {\n smoothAccumulator.x = Mathf.SmoothStep(startAccumulator.x, 0, Mathf.Abs(accumulator.x - startAccumulator.x) / Mathf.Abs(startAccumulator.x));\n }\n else\n {\n smoothAccumulator.x = 0.0f;\n }\n\n lastInputVector.x = 0;\n }\n\n if (!Mathf.Approximately(inputVector.y, 0))\n {\n accumulator.y = Mathf.Clamp(accumulator.y + inputVector.y * Time.deltaTime / verticalDuration, -1, 1);\n\n if (lastInputVector.y == 0 || inputVector.y < 0 && lastInputVector.y > 0 || inputVector.y > 0 && lastInputVector.y < 0)\n {\n accumulator.y = smoothAccumulator.y;\n startAccumulator.y = accumulator.y;\n }\n\n if (!Mathf.Approximately(Mathf.Sign(inputVector.y), startAccumulator.y)) // avoid dividing by zero\n {\n smoothAccumulator.y = Mathf.SmoothStep(startAccumulator.y, Mathf.Sign(inputVector.y), Mathf.Abs(accumulator.y - startAccumulator.y) / Mathf.Abs((Mathf.Sign(inputVector.y) - startAccumulator.y)));\n }\n else\n {\n smoothAccumulator.y = 1.0f;\n }\n lastInputVector.y = inputVector.y;\n }\n else\n {\n if (accumulator.y == 0)\n {\n startAccumulator.y = 0;\n }\n\n if (lastInputVector.y != 0)\n {\n accumulator.y = smoothAccumulator.y;\n startAccumulator.y = accumulator.y;\n }\n\n if (startAccumulator.y != 0)\n {\n smoothAccumulator.y = Mathf.SmoothStep(startAccumulator.y, 0, Mathf.Abs(accumulator.y - startAccumulator.y) / Mathf.Abs(startAccumulator.y));\n }\n else\n {\n smoothAccumulator.y = 0.0f;\n }\n\n accumulator.y = (1 - Mathf.Sign(accumulator.y)) / 2f * Mathf.Min(accumulator.y - Mathf.Sign(accumulator.y) * Time.deltaTime / verticalDuration, 0) + (1 + Mathf.Sign(accumulator.y)) / 2f * Mathf.Max(accumulator.y - Mathf.Sign(accumulator.y) * Time.deltaTime / verticalDuration, 0);\n\n lastInputVector.y = 0;\n }\n\n // Stabilization of the look around\n float y_stabilization = 0;\n if (cameraState == STATE.NORMAL) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * -angleFromNormalToHorizon; }\n\n else if (cameraState == STATE.HURRY) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * -(angleFromHurryToHorizon - angleFromNormalToHorizon); }\n else if (cameraState == STATE.NORMAL_TO_HURRY) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * (-angleFromNormalToHorizon * zoomTimer / timeNormalToHurry - (angleFromHurryToHorizon - angleFromNormalToHorizon) * (timeNormalToHurry - zoomTimer) / timeNormalToHurry); }\n else if (cameraState == STATE.HURRY_TO_NORMAL) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * (-(angleFromHurryToHorizon - angleFromNormalToHorizon) * zoomTimer / timeHurryToNormal - angleFromNormalToHorizon * (timeHurryToNormal - zoomTimer) / timeHurryToNormal); }\n\n else if (cameraState == STATE.PROTECTED) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * -(angleFromProtectedToHorizon - angleFromNormalToHorizon); }\n else if (cameraState == STATE.NORMAL_TO_PROTECTED) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * (-angleFromNormalToHorizon * zoomTimer / timeNormalToProtected - (angleFromProtectedToHorizon - angleFromNormalToHorizon) * (timeNormalToProtected - zoomTimer) / timeNormalToProtected); }\n else if (cameraState == STATE.PROTECTED_TO_NORMAL) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * (-(angleFromProtectedToHorizon - angleFromNormalToHorizon) * zoomTimer / timeProtectedToNormal - angleFromNormalToHorizon * (timeProtectedToNormal - zoomTimer) / timeProtectedToNormal); }\n\n else if (cameraState == STATE.HURRY_TO_PROTECTED) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * (-(angleFromHurryToHorizon - angleFromNormalToHorizon) * zoomTimer / timeHurryToProtected - (angleFromProtectedToHorizon - angleFromNormalToHorizon) * (timeHurryToProtected - zoomTimer) / timeHurryToProtected); }\n else if (cameraState == STATE.PROTECTED_TO_HURRY) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * (-(angleFromProtectedToHorizon - angleFromNormalToHorizon) * zoomTimer / timeProtectedToHurry - (angleFromHurryToHorizon - angleFromNormalToHorizon) * (timeProtectedToHurry - zoomTimer) / timeProtectedToHurry); }\n\n // Must be separated in two because unity's order for euler is ZYX and we want X-Y-X\n //heldCamera.transform.localRotation = Quaternion.Euler(-smoothy * maxLookAroundAngle, smoothx * maxLookAroundAngle, 0);\n \n heldCamera.transform.localRotation = Quaternion.Euler(y_stabilization, 0, 0);\n heldCamera.transform.localRotation *= Quaternion.Euler(0, smoothAccumulator.x * maxHorizontalAngle, 0);\n heldCamera.transform.localRotation *= Quaternion.Euler(-smoothAccumulator.y * maxVerticalAngle, 0, 0);\n }\n\n void SmoothProjectiveLookAround(Vector2 inputVector)\n {\n // Projection\n float sinerpForward;\n if (inputVector != Vector2.zero)\n {\n projectiveAccumulator = Mathf.Clamp(projectiveAccumulator + Time.deltaTime / projectiveDuration, 0, 1);\n sinerpForward = Mathf.Sin(projectiveAccumulator * Mathf.PI * 0.5f);\n }\n else\n {\n projectiveAccumulator = Mathf.Clamp(projectiveAccumulator - Time.deltaTime / projectiveDuration, 0, 1);\n sinerpForward = Mathf.Sin(projectiveAccumulator * Mathf.PI * 0.5f);\n }\n\n if (!Mathf.Approximately(inputVector.x, 0))\n {\n if (lastInputVector.x == 0 || inputVector.x < 0 && lastInputVector.x > 0 || inputVector.x > 0 && lastInputVector.x < 0)\n {\n accumulator.x = smoothAccumulator.x;\n startAccumulator.x = accumulator.x;\n }\n else\n {\n // WHY HERE ?\n accumulator.x = Mathf.Clamp(accumulator.x + inputVector.x * Time.deltaTime / horizontalDuration, -1, 1);\n }\n\n if (!Mathf.Approximately(Mathf.Sign(inputVector.x), startAccumulator.x)) // avoid dividing by zero\n {\n smoothAccumulator.x = Mathf.SmoothStep(startAccumulator.x, Mathf.Sign(inputVector.x), Mathf.Abs(accumulator.x - startAccumulator.x) / Mathf.Abs((Mathf.Sign(inputVector.x) - startAccumulator.x)));\n }\n else\n {\n smoothAccumulator.x = 1.0f;\n }\n\n lastInputVector.x = inputVector.x;\n }\n else\n {\n if (accumulator.x == 0)\n {\n startAccumulator.x = 0;\n }\n if (lastInputVector.x != 0)\n {\n accumulator.x = smoothAccumulator.x;\n startAccumulator.x = accumulator.x;\n }\n else\n {\n // WHY HERE ?\n accumulator.x = (1 - Mathf.Sign(accumulator.x)) / 2f * Mathf.Min(accumulator.x - Mathf.Sign(accumulator.x) * Time.deltaTime / horizontalDuration, 0) + (1 + Mathf.Sign(accumulator.x)) / 2f * Mathf.Max(accumulator.x - Mathf.Sign(accumulator.x) * Time.deltaTime / horizontalDuration, 0);\n }\n\n if (startAccumulator.x != 0)\n {\n smoothAccumulator.x = Mathf.SmoothStep(startAccumulator.x, 0, Mathf.Abs(accumulator.x - startAccumulator.x) / Mathf.Abs(startAccumulator.x));\n }\n else\n {\n smoothAccumulator.x = 0.0f;\n }\n\n lastInputVector.x = 0;\n }\n\n if (!Mathf.Approximately(inputVector.y, 0))\n {\n accumulator.y = Mathf.Clamp(accumulator.y + inputVector.y * Time.deltaTime / verticalDuration, -1, 1);\n\n if (lastInputVector.y == 0 || inputVector.y < 0 && lastInputVector.y > 0 || inputVector.y > 0 && lastInputVector.y < 0)\n {\n accumulator.y = smoothAccumulator.y;\n startAccumulator.y = accumulator.y;\n }\n\n if (!Mathf.Approximately(Mathf.Sign(inputVector.y), startAccumulator.y)) // avoid dividing by zero\n {\n smoothAccumulator.y = Mathf.SmoothStep(startAccumulator.y, Mathf.Sign(inputVector.y), Mathf.Abs(accumulator.y - startAccumulator.y) / Mathf.Abs((Mathf.Sign(inputVector.y) - startAccumulator.y)));\n }\n else\n {\n smoothAccumulator.y = 1.0f;\n }\n lastInputVector.y = inputVector.y;\n }\n else\n {\n if (accumulator.y == 0)\n {\n startAccumulator.y = 0;\n }\n\n if (lastInputVector.y != 0)\n {\n accumulator.y = smoothAccumulator.y;\n startAccumulator.y = accumulator.y;\n }\n\n if (startAccumulator.y != 0)\n {\n smoothAccumulator.y = Mathf.SmoothStep(startAccumulator.y, 0, Mathf.Abs(accumulator.y - startAccumulator.y) / Mathf.Abs(startAccumulator.y));\n }\n else\n {\n smoothAccumulator.y = 0.0f;\n }\n\n accumulator.y = (1 - Mathf.Sign(accumulator.y)) / 2f * Mathf.Min(accumulator.y - Mathf.Sign(accumulator.y) * Time.deltaTime / verticalDuration, 0) + (1 + Mathf.Sign(accumulator.y)) / 2f * Mathf.Max(accumulator.y - Mathf.Sign(accumulator.y) * Time.deltaTime / verticalDuration, 0);\n\n lastInputVector.y = 0;\n }\n\n // Stabilization of the look around\n float y_stabilization = 0;\n if (cameraState == STATE.NORMAL) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * -angleFromNormalToHorizon; }\n\n if (cameraState == STATE.HURRY) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * -angleFromHurryToHorizon; }\n else if (cameraState == STATE.NORMAL_TO_HURRY) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * (-angleFromNormalToHorizon * zoomTimer / timeNormalToHurry - angleFromHurryToHorizon * (timeNormalToHurry - zoomTimer) / timeNormalToHurry); }\n else if (cameraState == STATE.HURRY_TO_NORMAL) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * (-angleFromHurryToHorizon * zoomTimer / timeHurryToNormal - angleFromNormalToHorizon * (timeHurryToNormal - zoomTimer) / timeHurryToNormal); }\n\n else if (cameraState == STATE.PROTECTED) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * -angleFromProtectedToHorizon; }\n else if (cameraState == STATE.NORMAL_TO_PROTECTED) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * (-angleFromNormalToHorizon * zoomTimer / timeNormalToProtected - angleFromProtectedToHorizon * (timeNormalToProtected - zoomTimer) / timeNormalToProtected); }\n else if (cameraState == STATE.PROTECTED_TO_NORMAL) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * (-angleFromProtectedToHorizon * zoomTimer / timeProtectedToNormal - angleFromNormalToHorizon * (timeProtectedToNormal - zoomTimer) / timeProtectedToNormal); }\n\n else if (cameraState == STATE.HURRY_TO_PROTECTED) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * (-angleFromHurryToHorizon * zoomTimer / timeHurryToProtected - angleFromProtectedToHorizon * (timeHurryToProtected - zoomTimer) / timeHurryToProtected); }\n else if (cameraState == STATE.PROTECTED_TO_HURRY) { y_stabilization = Mathf.Abs(smoothAccumulator.x) * (-angleFromProtectedToHorizon * zoomTimer / timeProtectedToHurry - angleFromHurryToHorizon * (timeProtectedToHurry - zoomTimer) / timeProtectedToHurry); }\n\n // Must be separated in two because unity's order for euler is ZYX and we want X-Y-X\n //heldCamera.transform.localRotation = Quaternion.Euler(-smoothy * maxLookAroundAngle, smoothx * maxLookAroundAngle, 0);\n heldCamera.transform.localRotation = Quaternion.Euler(y_stabilization, 0, 0);\n heldCamera.transform.localRotation *= Quaternion.Euler(0, smoothAccumulator.x * maxHorizontalAngle, 0);\n heldCamera.transform.localRotation *= Quaternion.Euler(-smoothAccumulator.y * maxVerticalAngle, 0, 0);\n\n // Projection\n heldCamera.transform.position = transform.position + (player.transform.position + Quaternion.Euler(0, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z) * projectiveOffset - transform.position) * sinerpForward;\n }\n\n void ProjectiveLookAround(float v)\n {\n float sinerpForward = 0;\n Debug.Log(\"V = \" + v);\n if(v != 0)\n {\n projectiveAccumulator = Mathf.Clamp (projectiveAccumulator + Time.deltaTime / projectiveDuration, 0, 1);\n sinerpForward = Mathf.Sin(projectiveAccumulator * Mathf.PI * 0.5f);\n }\n else\n {\n projectiveAccumulator = Mathf.Clamp(projectiveAccumulator - Time.deltaTime / projectiveDuration, 0, 1);\n sinerpForward = Mathf.Sin(projectiveAccumulator * Mathf.PI * 0.5f);\n }\n //heldCamera.transform.position = (1-v)*transform.position + v* (player.transform.position) + (player.transform.forward * forwardDistance) * sinerpForward;\n heldCamera.transform.position = transform.position + (player.transform.position + player.transform.forward * projectiveDistance - transform.position) * sinerpForward;\n }\n\n void ExtendedLookAround(Vector2 v)\n {\n maxHorizontalAngle = 90; // needed\n float minHorizontalAngle = 45;\n\n float rotationSmooth = 0;\n float lateralSmooth = 0;\n float forwardSmooth = 0;\n\n float rightProjection = 5;\n float forwardProjection = 12;\n\n if (!Mathf.Approximately(v.x, 0))\n {\n accumulator.x = Mathf.Clamp(accumulator.x + v.x * Time.deltaTime / horizontalDuration, -1, 1);\n rotationSmooth = Mathf.Sign(accumulator.x) * Mathf.Sin(Mathf.Abs(accumulator.x) * Mathf.PI * 0.5f);\n //lateralSmooth = Mathf.Sign(accumulator.x) * (1 - Mathf.Sqrt(1 - Mathf.Pow(accumulator.x,2)));\n lateralSmooth = Mathf.Sign(accumulator.x) * Mathf.Sin(Mathf.Abs(accumulator.x) * Mathf.PI * 0.5f);\n }\n else\n {\n accumulator.x = (1 - Mathf.Sign(accumulator.x)) / 2f * Mathf.Min(accumulator.x - Mathf.Sign(accumulator.x) * Time.deltaTime / horizontalDuration, 0) + (1 + Mathf.Sign(accumulator.x)) / 2f * Mathf.Max(accumulator.x - Mathf.Sign(accumulator.x) * Time.deltaTime / horizontalDuration, 0);\n rotationSmooth = Mathf.Sign(accumulator.x) * Mathf.Sin(Mathf.Abs(accumulator.x) * Mathf.PI * 0.5f);\n //lateralSmooth = Mathf.Sign(accumulator.x) * (1 - Mathf.Sqrt(1 - Mathf.Pow(accumulator.x,2)));\n lateralSmooth = Mathf.Sign(accumulator.x) * Mathf.Sin(Mathf.Abs(accumulator.x) * Mathf.PI * 0.5f);\n }\n\n if (!Mathf.Approximately(v.y, 0))\n {\n //inputs.Player.Walk.Disable();\n accumulator.y = Mathf.Clamp(accumulator.y + v.y * Time.deltaTime / verticalDuration, -1, 1);\n forwardSmooth = Mathf.Sign(accumulator.y) * Mathf.Sin(Mathf.Abs(accumulator.y) * Mathf.PI * 0.5f);\n }\n else\n {\n //inputs.Player.Walk.Enable();\n accumulator.y = (1 - Mathf.Sign(accumulator.y)) / 2f * Mathf.Min(accumulator.y - Mathf.Sign(accumulator.y) * Time.deltaTime / verticalDuration, 0) + (1 + Mathf.Sign(accumulator.y)) / 2f * Mathf.Max(accumulator.y - Mathf.Sign(accumulator.y) * Time.deltaTime / verticalDuration, 0);\n forwardSmooth = Mathf.Sign(accumulator.y) * Mathf.Sin(Mathf.Abs(accumulator.y) * Mathf.PI * 0.5f);\n }\n\n // Stabilization of the look around\n float y_stabilization = 0;\n if (cameraState == STATE.NORMAL) { y_stabilization = Mathf.Abs(rotationSmooth) * -angleFromNormalToHorizon; }\n\n else if (cameraState == STATE.HURRY) { y_stabilization = Mathf.Abs(rotationSmooth) * -angleFromHurryToHorizon; }\n else if (cameraState == STATE.NORMAL_TO_HURRY) { y_stabilization = Mathf.Abs(rotationSmooth) * (-angleFromNormalToHorizon * zoomTimer / timeNormalToHurry - angleFromHurryToHorizon * (timeNormalToHurry - zoomTimer) / timeNormalToHurry); }\n else if (cameraState == STATE.HURRY_TO_NORMAL) { y_stabilization = Mathf.Abs(rotationSmooth) * (-angleFromHurryToHorizon * zoomTimer / timeHurryToNormal - angleFromNormalToHorizon * (timeHurryToNormal - zoomTimer) / timeHurryToNormal); }\n\n else if (cameraState == STATE.PROTECTED) { y_stabilization = Mathf.Abs(rotationSmooth) * -angleFromProtectedToHorizon; }\n else if (cameraState == STATE.NORMAL_TO_PROTECTED) { y_stabilization = Mathf.Abs(rotationSmooth) * (-angleFromNormalToHorizon * zoomTimer / timeNormalToProtected - angleFromProtectedToHorizon * (timeNormalToProtected - zoomTimer) / timeNormalToProtected); }\n else if (cameraState == STATE.PROTECTED_TO_NORMAL) { y_stabilization = Mathf.Abs(rotationSmooth) * (-angleFromProtectedToHorizon * zoomTimer / timeProtectedToNormal - angleFromNormalToHorizon * (timeProtectedToNormal - zoomTimer) / timeProtectedToNormal); }\n\n else if (cameraState == STATE.HURRY_TO_PROTECTED) { y_stabilization = Mathf.Abs(rotationSmooth) * (-angleFromHurryToHorizon * zoomTimer / timeHurryToProtected - angleFromProtectedToHorizon * (timeHurryToProtected - zoomTimer) / timeHurryToProtected); }\n else if (cameraState == STATE.PROTECTED_TO_HURRY) { y_stabilization = Mathf.Abs(rotationSmooth) * (-angleFromProtectedToHorizon * zoomTimer / timeProtectedToHurry - angleFromHurryToHorizon * (timeProtectedToHurry - zoomTimer) / timeProtectedToHurry); }\n\n // Must be separated in two because unity's order for euler is ZYX and we want X-Y-X\n //heldCamera.transform.localRotation = Quaternion.Euler(-smoothy * maxLookAroundAngle, smoothx * maxLookAroundAngle, 0);\n heldCamera.transform.localRotation = Quaternion.Euler(y_stabilization, 0, 0);\n heldCamera.transform.localRotation *= Quaternion.Euler(0, rotationSmooth * (minHorizontalAngle + forwardSmooth * (maxHorizontalAngle - minHorizontalAngle)), 0);\n //heldCamera.transform.localRotation *= Quaternion.Euler(-smoothy * maxVerticalAngle, 0, 0);\n\n heldCamera.transform.position = transform.position + transform.right * rightProjection * lateralSmooth + (player.transform.position + player.transform.forward * forwardProjection - transform.position) * forwardSmooth;\n }\n\n void UpdateRecoilPosition()\n {\n if (cameraState == STATE.NORMAL)\n {\n if (!isTargeting) //isAvailable ?\n {\n if (player.GetComponent<PlayerFirst>().IsProtectingEyes || player.GetComponent<PlayerFirst>().IsProtectingEars)\n {\n Debug.Log(\"CAMERA DETECTED THAT PLAYER IS PROTECTING\");\n zoomTimer = timeNormalToProtected;\n isAvailable = false;\n cameraState = STATE.NORMAL_TO_PROTECTED;\n }\n\n else if (player.GetComponent<PlayerFirst>().IsHurry)\n {\n zoomTimer = timeNormalToHurry;\n isAvailable = false;\n cameraState = STATE.NORMAL_TO_HURRY;\n }\n }\n }\n\n else if (cameraState == STATE.NORMAL_TO_HURRY)\n {\n Vector3 startPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position,Vector3.up).normalized * Z_OffsetHurry + Vector3.up * Y_OffsetHurry) * (timeNormalToHurry - zoomTimer) / timeNormalToHurry; // recreate original position\n Vector3 endPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetHurry + Vector3.up * Y_OffsetHurry) * zoomTimer / timeNormalToHurry; // recreate original position\n //float smoothstep = Mathf.SmoothStep(0.0f, 1.0f, (timeToFocus - recoilTimer) / timeToFocus);\n zoomTimer = Mathf.Max(zoomTimer - Time.deltaTime, 0);\n transform.position = Vector3.Lerp(startPosition, endPosition, (timeNormalToHurry - zoomTimer) / timeNormalToHurry);\n\n // Transition\n if (zoomTimer <= 0)\n {\n transform.position = endPosition; // should wait one frame more\n isAvailable = true;\n cameraState = STATE.HURRY;\n }\n }\n\n else if (cameraState == STATE.HURRY)\n {\n if (!isTargeting) // isAvailable ?\n {\n if (gameManager.GetComponent<GameManager>().IsGameOver)\n {\n zoomTimer = timeHurryToGameover;\n isAvailable = false;\n cameraState = STATE.HURRY_TO_GAMEOVER;\n }\n\n else if (player.GetComponent<PlayerFirst>().IsProtectingEyes || player.GetComponent<PlayerFirst>().IsProtectingEars)\n {\n zoomTimer = timeHurryToProtected;\n isAvailable = false;\n cameraState = STATE.HURRY_TO_PROTECTED;\n }\n else if (!player.GetComponent<PlayerFirst>().IsHurry)\n {\n zoomTimer = timeHurryToNormal;\n isAvailable = false;\n cameraState = STATE.HURRY_TO_NORMAL;\n }\n }\n }\n\n else if (cameraState == STATE.HURRY_TO_NORMAL)\n {\n Vector3 startPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetHurry + Vector3.up * Y_OffsetHurry) * (timeHurryToNormal - zoomTimer) / timeHurryToNormal; // recreate original position\n Vector3 endPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetHurry + Vector3.up * Y_OffsetHurry) * zoomTimer / timeHurryToNormal; // recreate original position\n zoomTimer = Mathf.Max(zoomTimer - Time.deltaTime, 0);\n //float smoothstep = Mathf.SmoothStep(0.0f, 1.0f, (timeToNormal - recoilTimer) / timeToNormal);\n transform.position = Vector3.Lerp(startPosition, endPosition, (timeHurryToNormal - zoomTimer) / timeHurryToNormal);\n \n // Transition\n if (zoomTimer <= 0)\n {\n transform.position = endPosition; // should wait one frame more\n isAvailable = true;\n cameraState = STATE.NORMAL;\n }\n }\n\n else if (cameraState == STATE.NORMAL_TO_PROTECTED)\n {\n Vector3 startPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetProtected + Vector3.up * Y_OffsetProtected) * (timeNormalToProtected - zoomTimer) / timeNormalToProtected; // recreate original position\n Vector3 endPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetProtected + Vector3.up * Y_OffsetProtected) * zoomTimer / timeNormalToProtected; // recreate original position\n //float smoothstep = Mathf.SmoothStep(0.0f, 1.0f, (timeToFocus - recoilTimer) / timeToFocus);\n zoomTimer = Mathf.Max(zoomTimer - Time.deltaTime, 0);\n transform.position = Vector3.Lerp(startPosition, endPosition, (timeNormalToProtected - zoomTimer) / timeNormalToProtected);\n \n // Transition\n if (zoomTimer <= 0)\n {\n transform.position = endPosition; // should wait one frame more\n isAvailable = true;\n cameraState = STATE.PROTECTED;\n }\n }\n\n else if (cameraState == STATE.PROTECTED)\n {\n if (!isTargeting) // isAvailable ?\n {\n if (gameManager.GetComponent<GameManager>().IsGameOver)\n {\n zoomTimer = timeProtectedToGameover;\n isAvailable = false;\n cameraState = STATE.PROTECTED_TO_GAMEOVER;\n }\n\n else if (!player.GetComponent<PlayerFirst>().IsProtectingEyes && !player.GetComponent<PlayerFirst>().IsProtectingEars)\n {\n if (player.GetComponent<PlayerFirst>().IsHurry)\n {\n zoomTimer = timeProtectedToHurry;\n isAvailable = false;\n cameraState = STATE.PROTECTED_TO_HURRY;\n }\n else\n {\n zoomTimer = timeProtectedToNormal;\n isAvailable = false;\n cameraState = STATE.PROTECTED_TO_NORMAL;\n }\n }\n }\n }\n\n else if (cameraState == STATE.PROTECTED_TO_NORMAL)\n {\n Vector3 startPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetProtected + Vector3.up * Y_OffsetProtected) * (timeProtectedToNormal - zoomTimer) / timeProtectedToNormal; // recreate original position\n Vector3 endPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetProtected + Vector3.up * Y_OffsetProtected) * zoomTimer / timeProtectedToNormal; // recreate original position\n zoomTimer = Mathf.Max(zoomTimer - Time.deltaTime, 0);\n //float smoothstep = Mathf.SmoothStep(0.0f, 1.0f, (timeToNormal - recoilTimer) / timeToNormal);\n transform.position = Vector3.Lerp(startPosition, endPosition, (timeProtectedToNormal - zoomTimer) / timeProtectedToNormal);\n\n // Transition\n if (zoomTimer <= 0)\n {\n isAvailable = true;\n transform.position = endPosition; // should wait one frame more\n cameraState = STATE.NORMAL;\n }\n }\n\n else if (cameraState == STATE.HURRY_TO_PROTECTED)\n {\n Vector3 startPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * (Z_OffsetHurry - Z_OffsetProtected) + Vector3.up * (Y_OffsetHurry - Y_OffsetProtected)) * (timeHurryToProtected - zoomTimer) / timeHurryToProtected; // recreate original position\n Vector3 endPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * (Z_OffsetHurry - Z_OffsetProtected) + Vector3.up * (Y_OffsetHurry - Y_OffsetProtected)) * zoomTimer / timeHurryToProtected; // recreate original position\n zoomTimer = Mathf.Max(zoomTimer - Time.deltaTime, 0);\n //float smoothstep = Mathf.SmoothStep(0.0f, 1.0f, (timeToNormal - recoilTimer) / timeToNormal);\n transform.position = Vector3.Lerp(startPosition, endPosition, (timeHurryToProtected - zoomTimer) / timeHurryToProtected);\n\n // Transition\n if (zoomTimer <= 0)\n {\n transform.position = endPosition; // should wait one frame more\n isAvailable = true;\n cameraState = STATE.PROTECTED;\n }\n }\n\n else if (cameraState == STATE.PROTECTED_TO_HURRY)\n {\n Vector3 startPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * (Z_OffsetProtected - Z_OffsetHurry) + Vector3.up * (Y_OffsetProtected - Y_OffsetHurry)) * (timeProtectedToHurry - zoomTimer) / timeProtectedToHurry; // recreate original position\n Vector3 endPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * (Z_OffsetProtected - Z_OffsetHurry) + Vector3.up * (Y_OffsetProtected - Y_OffsetHurry)) * zoomTimer / timeProtectedToHurry; // recreate original position\n zoomTimer = Mathf.Max(zoomTimer - Time.deltaTime, 0);\n //float smoothstep = Mathf.SmoothStep(0.0f, 1.0f, (timeToNormal - recoilTimer) / timeToNormal);\n transform.position = Vector3.Lerp(startPosition, endPosition, (timeProtectedToHurry - zoomTimer) / timeProtectedToHurry);\n\n // Transition\n if (zoomTimer <= 0)\n {\n transform.position = endPosition; // should wait one frame more\n isAvailable = true;\n cameraState = STATE.HURRY;\n }\n }\n\n else if (cameraState == STATE.HURRY_TO_GAMEOVER)\n {\n Vector3 startPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * (Z_OffsetHurry - Z_OffsetGameover) + Vector3.up * (Y_OffsetHurry - Y_OffsetGameover)) * (timeHurryToGameover - zoomTimer) / timeHurryToGameover; // recreate original position\n Vector3 endPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * (Z_OffsetHurry - Z_OffsetGameover) + Vector3.up * (Y_OffsetHurry - Y_OffsetGameover)) * zoomTimer / timeHurryToGameover; // recreate original position\n zoomTimer = Mathf.Max(zoomTimer - Time.deltaTime, 0);\n //float smoothstep = Mathf.SmoothStep(0.0f, 1.0f, (timeToNormal - recoilTimer) / timeToNormal);\n transform.position = Vector3.Lerp(startPosition, endPosition, (timeHurryToGameover - zoomTimer) / timeHurryToGameover);\n\n // Transition\n if (zoomTimer <= 0)\n {\n transform.position = endPosition; // should wait one frame more\n isAvailable = true;\n cameraState = STATE.GAMEOVER; // should be unused\n }\n }\n\n else if (cameraState == STATE.PROTECTED_TO_GAMEOVER)\n {\n Vector3 startPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * (Z_OffsetProtected - Z_OffsetGameover) + Vector3.up * (Y_OffsetProtected - Y_OffsetGameover)) * (timeProtectedToGameover - zoomTimer) / timeProtectedToGameover; // recreate original position\n Vector3 endPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * (Z_OffsetProtected - Z_OffsetGameover) + Vector3.up * (Y_OffsetProtected - Y_OffsetGameover)) * zoomTimer / timeProtectedToGameover; // recreate original position\n zoomTimer = Mathf.Max(zoomTimer - Time.deltaTime, 0);\n //float smoothstep = Mathf.SmoothStep(0.0f, 1.0f, (timeToNormal - recoilTimer) / timeToNormal);\n transform.position = Vector3.Lerp(startPosition, endPosition, (timeProtectedToGameover - zoomTimer) / timeProtectedToGameover);\n\n // Transition\n if (zoomTimer <= 0)\n {\n transform.position = endPosition; // should wait one frame more\n isAvailable = true;\n cameraState = STATE.GAMEOVER;\n }\n }\n\n else if (cameraState == STATE.GAMEOVER)\n {\n transform.position += Vector3.up * flyAwaySpeed;\n }\n }\n\n /* Floating */\n\n void InitializeSway()\n {\n latitude = Random.Range(0, 180);\n longitude = Random.Range(0, 360);\n swayRadiusMin = swayNormalRadiusMin;\n swayRadiusMax = swayNormalRadiusMax;\n swayDurationMin = swayNormalDurationMin;\n swayDurationMax = swayNormalDurationMax;\n swayRadius = Random.Range(swayRadiusMin, swayRadiusMax);\n swayDuration = Random.Range(swayDurationMin, swayDurationMax);\n swayTimer = swayDuration;\n\n originalSwayPosition = heldCamera.transform.localPosition;\n\n targetSwayPosition = heldCamera.transform.localPosition + heldCamera.transform.localRotation * new Vector3\n (\n swayRadius * Mathf.Sin(latitude * Mathf.Deg2Rad) * Mathf.Cos(longitude * Mathf.Deg2Rad),\n swayRadius * Mathf.Sin(latitude * Mathf.Deg2Rad) * Mathf.Sin(longitude * Mathf.Deg2Rad),\n swayRadius * Mathf.Cos(latitude * Mathf.Deg2Rad)\n );\n }\n IEnumerator Sway()\n {\n for (; ;)\n {\n if ((cameraState == STATE.HURRY || cameraState == STATE.NORMAL_TO_HURRY) && lastCameraState != STATE.HURRY && lastCameraState != STATE.NORMAL_TO_HURRY)\n {\n // immediately speed up\n float newSwayDuration = Random.Range(swayHurryDurationMin, swayHurryDurationMax);\n\n swayTimer *= (newSwayDuration / swayDuration); // rescale timer\n swayDuration = newSwayDuration;\n\n // for next iteration\n swayDurationMin = swayHurryDurationMin;\n swayDurationMax = swayHurryDurationMax;\n swayRadiusMin = swayHurryRadiusMin;\n swayRadiusMax = swayHurryRadiusMax;\n backToNormalRadiusSpeed = 2f;\n backToNormalRadiusAcceleration = 2.5f;\n }\n else if (cameraState == STATE.NORMAL && lastCameraState != STATE.NORMAL)\n {\n // for next iteration\n swayDurationMin = swayNormalDurationMin;\n swayDurationMax = swayNormalDurationMax;\n swayRadiusMin = swayNormalRadiusMin;\n swayRadiusMax = swayNormalRadiusMax;\n }\n\n swayTimer = Mathf.Max(swayTimer - Time.deltaTime, 0.0f);\n float smoothstep = Mathf.SmoothStep(0.0f, 1.0f, (swayDuration - swayTimer) / swayDuration);\n cameraSway.transform.localPosition = Vector3.Lerp(originalSwayPosition, targetSwayPosition, smoothstep);\n\n if (smoothstep == 1)\n {\n latitude = Random.Range(0, 90) + 90 * (1 - Mathf.Sign(latitude - 90) / 2f);\n longitude = Random.Range(longitude - 90, longitude + 90) % 360;\n\n // Revenir progressivement à swayNormalRadiusMin, swayNormalRadiusMax\n // WARNING : Here we suppose that radius is greater in hurry than in normal, and conversely for the duration\n // Transition for the radius, but not for the duration\n backToNormalRadiusSpeed = Mathf.Max(backToNormalRadiusSpeed + Time.deltaTime * backToNormalRadiusAcceleration, 0.1f);\n swayRadiusMin = Mathf.Max(swayRadiusMin - Time.deltaTime * backToNormalRadiusSpeed, swayNormalRadiusMin);\n swayRadiusMax = Mathf.Max(swayRadiusMax - Time.deltaTime * backToNormalRadiusSpeed, swayNormalRadiusMax);\n //swayDurationMin = Mathf.Min(swayDurationMin + Time.deltaTime * backToNormalRadiusSpeed, swayNormalDurationMin);\n //swayDurationMax = Mathf.Min(swayDurationMax + Time.deltaTime * backToNormalRadiusSpeed, swayNormalDurationMax);\n\n swayRadius = Random.Range(swayRadiusMin, swayRadiusMax);\n swayDuration = Random.Range(swayDurationMin, swayDurationMax);\n swayTimer = swayDuration;\n\n originalSwayPosition = cameraSway.transform.localPosition;\n targetSwayPosition = heldCamera.transform.localPosition + heldCamera.transform.localRotation * new Vector3\n (\n swayRadius * Mathf.Sin(latitude * Mathf.Deg2Rad) * Mathf.Cos(longitude * Mathf.Deg2Rad),\n swayRadius * Mathf.Sin(latitude * Mathf.Deg2Rad) * Mathf.Sin(longitude * Mathf.Deg2Rad),\n swayRadius * Mathf.Cos(latitude * Mathf.Deg2Rad)\n );\n }\n\n lastCameraState = cameraState;\n\n yield return null;\n }\n }\n\n /* Targeting */\n\n public void TargetingObstacle(GameObject target)\n {\n if (!isTargeting && isAvailable && !player.GetComponent<PlayerFirst>().IsProtectingEyes && !player.GetComponent<PlayerFirst>().IsProtectingEars)\n {\n //isAvailable = false;\n inputs.Player.ProtectEars.Disable();\n inputs.Player.ProtectEyes.Disable();\n isTargeting = true;\n targetingTimer = targetingDuration;\n\n targetPosition = target.transform.position;\n\n storedForward = heldCamera.transform.forward;\n storedRotation = heldCamera.transform.localRotation;\n initialParentRotation = this.transform.rotation;\n\n StartCoroutine(\"SlerpTo\");\n }\n }\n\n IEnumerator SlerpTo()\n {\n startForward = storedForward;\n endForward = Vector3.ProjectOnPlane((targetPosition - heldCamera.transform.position).normalized, Vector3.up);\n\n while (targetingTimer > (targetingDuration - targetingPause) * 0.5f + targetingPause)\n {\n currentParentRotation = this.transform.rotation;\n //startForward = Quaternion.Inverse(currentParentRotation) * storedForward;\n startForward = Vector3.ProjectOnPlane(defaultForward.transform.forward, Vector3.up);\n endForward = Vector3.ProjectOnPlane((targetPosition - heldCamera.transform.position).normalized, Vector3.up); // Check if ok\n targetingTimer = Mathf.Max(targetingTimer - Time.deltaTime, (targetingDuration - targetingPause) * 0.5f + targetingPause);\n Vector3 current = Vector3.Slerp(startForward, endForward, ((targetingDuration - targetingPause) * 0.5f - (targetingTimer - ((targetingDuration - targetingPause) * 0.5f + targetingPause))) / ((targetingDuration - targetingPause) * 0.5f));\n //current = new Vector3(current.x, current.y, 0);\n /* Quaternion rotation = Quaternion.LookRotation(transform.up, -current)\n * Quaternion.AngleAxis(90f, Vector3.right);\n heldCamera.transform.rotation = rotation; */\n //Quaternion look = Quaternion.LookRotation((new Vector3(current.x,current.y,0)).normalized, Vector3.up);\n heldCamera.transform.localRotation = Quaternion.Inverse(heldCamera.transform.parent.rotation) * Quaternion.LookRotation(current, Vector3.up);\n //heldCamera.transform.rotation = Quaternion.LookRotation(current, Vector3.up);\n //float angle = Vector3.Angle(Vector3.ProjectOnPlane(startForward, Vector3.up), Vector3.ProjectOnPlane(endForward, Vector3.up));\n //heldCamera.transform.rotation = Quaternion.Inverse(heldCamera.transform.parent.rotation) * Quaternion.Euler(0, -angle, 0);\n\n //heldCamera.transform.rotation = Quaternion.LookRotation(current);\n\n Debug.Log(\"startForward: \" + startForward + \", endForward: \" + endForward + \", currentForward: \" + current);\n yield return null;\n }\n while (targetingTimer > (targetingDuration - targetingPause) * 0.5f)\n {\n targetingTimer = Mathf.Max(targetingTimer - Time.deltaTime, (targetingDuration - targetingPause) * 0.5f);\n heldCamera.transform.LookAt(targetPosition);\n }\n StartCoroutine(\"SlerpFrom\");\n }\n\n IEnumerator SlerpFrom()\n {\n startForward = heldCamera.transform.forward;\n endForward = storedForward;\n\n while (targetingTimer > 0)\n {\n targetingTimer = Mathf.Max(targetingTimer - Time.deltaTime, 0);\n Vector3 current = Vector3.Slerp(startForward, endForward, ((targetingDuration - targetingPause) * 0.5f - targetingTimer) / ((targetingDuration - targetingPause) * 0.5f));\n heldCamera.transform.localRotation = Quaternion.Inverse(heldCamera.transform.parent.rotation) * Quaternion.LookRotation(current);\n yield return null;\n }\n isTargeting = false;\n inputs.Player.ProtectEars.Enable();\n inputs.Player.ProtectEyes.Enable();\n\n /* Let's try this here */\n /*\n if (!player.GetComponent<PlayerFirst>().IsDamaged)\n {\n StartCoroutine(\"Timer\");\n }\n player.GetComponent<PlayerFirst>().IsDamaged = true;*/\n }\n\n // CHECK IF OK TO REMOVE THIS :\n /*\n IEnumerator Timer()\n {\n yield return new WaitForSeconds(3);\n player.GetComponent<PlayerFirst>().IsDamagedEyes = false;\n }*/\n\n} //FINISH\n" }, { "alpha_fraction": 0.5600000023841858, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 23, "blob_id": "4ccc98f4575c1c5ee605a1bb65202488df1fff68", "content_id": "81b03d0d26845a87e03dd74c5c87fe285604b321", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 25, "license_type": "no_license", "max_line_length": 23, "num_lines": 1, "path": "/LICENSE.md", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "\nCopyright (C) 2021 HeuR\n" }, { "alpha_fraction": 0.6686878800392151, "alphanum_fraction": 0.6754252910614014, "avg_line_length": 33.51744079589844, "blob_id": "9bcb66890e6f1a3b245521f8b42efd7f2e42a0fd", "content_id": "9334241729700dd5d765b36b8f276b3a4dd483af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5939, "license_type": "no_license", "max_line_length": 155, "num_lines": 172, "path": "/SoA-Unity/Assets/Scripts/Menus/StartButton.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.UI;\nusing UnityEngine.EventSystems;\n\npublic class StartButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler, ISelectHandler, IDeselectHandler, ISubmitHandler\n{\n GameObject menuManager;\n\n Navigation navigation;\n \n private ParticleSystem sunSpots;\n ParticleSystem.EmissionModule emission;\n ParticleSystem.VelocityOverLifetimeModule velocity;\n float rateOverTime = 5;\n\n public delegate void ButtonHandler();\n public event ButtonHandler EnterButtonEvent;\n public event ButtonHandler ValidateButtonEvent;\n\n // Start is called before the first frame update\n void Start()\n {\n menuManager = GameObject.FindGameObjectWithTag(\"MenuManager\");\n if (menuManager == null)\n {\n throw new System.NullReferenceException(\"Missing MenuManager object\");\n }\n\n sunSpots = transform.GetChild(1).GetComponent<ParticleSystem>();\n emission = sunSpots.emission;\n emission.enabled = true;\n emission.rateOverTime = 0;\n velocity = sunSpots.velocityOverLifetime;\n velocity.enabled = true;\n\n EnterButtonEvent += menuManager.GetComponent<MenuManager>().PlayHoverSound;\n ValidateButtonEvent += menuManager.GetComponent<MenuManager>().PlayClickSound;\n }\n\n // Update is called once per frame\n void Update()\n {\n // take the particle system to the center of the button\n Vector2 center = transform.GetChild(0).GetComponent<RectTransform>().rect.center;\n transform.GetChild(1).position = transform.GetComponent<RectTransform>().TransformPoint(new Vector3(center.x, center.y, -250));\n }\n\n /* Mouse Selection */\n\n void IPointerEnterHandler.OnPointerEnter(PointerEventData eventData)\n {\n //transform.GetChild(0).GetComponent<Text>().color = hoveringColor;\n //transform.GetChild(0).GetComponent<Animation>().Play(\"MenuItemPop\");\n //transform.GetChild(0).GetComponent<Animation>().Play(\"MenuItemColorIn\");\n //emission.rateOverTime = rateOverTime;\n //GetComponent<Button>().Select();\n EnterButtonAnimation();\n }\n\n void IPointerExitHandler.OnPointerExit(PointerEventData eventData)\n {\n ExitButtonAnimation();\n }\n\n void IPointerClickHandler.OnPointerClick(PointerEventData eventData)\n {\n ValidateButtonAnimation();\n }\n\n /* Keyboard selection */\n\n void ISelectHandler.OnSelect(BaseEventData eventData)\n {\n EnterButtonAnimation();\n }\n\n void IDeselectHandler.OnDeselect(BaseEventData eventData)\n {\n ExitButtonAnimation();\n }\n\n void ISubmitHandler.OnSubmit(BaseEventData eventData)\n {\n ValidateButtonAnimation();\n }\n\n /* Generic */\n\n private void EnterButtonAnimation()\n {\n //transform.GetChild(0).GetComponent<Text>().color = hoveringColor;\n //transform.GetChild(0).GetComponent<Animation>().Play(\"MenuItemPop\");\n transform.GetChild(0).GetComponent<Animation>().Play(\"MenuItemColorIn\");\n emission.rateOverTime = rateOverTime;\n transform.GetChild(1).GetComponent<MenuParticleSystem>().PlayParticleSound();\n\n EnterButtonEvent();\n }\n\n private void ExitButtonAnimation()\n {\n //transform.GetChild(0).GetComponent<Text>().color = defaultColor;\n transform.GetChild(0).GetComponent<Animation>().Play(\"MenuItemColorOut\");\n emission.rateOverTime = 0;\n transform.GetChild(1).GetComponent<MenuParticleSystem>().StopParticleSound();\n }\n\n private void ValidateButtonAnimation()\n {\n /*\n if (creditsPanel.GetComponent<CanvasGroup>().alpha != 0)\n {\n creditsPanel.GetComponent<Animation>().Play(\"CreditsFadeOut\");\n }*/\n transform.GetChild(0).GetComponent<Animation>().Play(\"MenuItemFlash\");\n transform.GetChild(1).GetComponent<MenuParticleSystem>().StopParticleSound();\n\n StartCoroutine(\"BurstSpots\");\n\n // Handle navigation\n\n navigation = GetComponent<Button>().navigation;\n navigation.mode = Navigation.Mode.None;\n\n ValidateButtonEvent();\n\n if (menuManager.GetComponent<MenuManager>().MenuState == MENU_STATE.CREDITS)\n {\n menuManager.GetComponent<MenuManager>().HideCredits();\n transform.parent.GetChild(2).GetChild(0).GetComponent<Animation>().Play(\"MenuItemUngreyed\");\n\n // Restore navigation\n\n //navigation = transform.parent.GetChild(2).GetComponent<Button>().navigation;\n //navigation.mode = Navigation.Mode.Automatic | Navigation.Mode.Vertical | Navigation.Mode.Horizontal;\n\n }\n else if (menuManager.GetComponent<MenuManager>().MenuState == MENU_STATE.CONTROLS)\n {\n menuManager.GetComponent<MenuManager>().HideControls();\n transform.parent.GetChild(1).GetChild(0).GetComponent<Animation>().Play(\"MenuItemUngreyed\");\n\n // Restore navigation\n\n //navigation = transform.parent.GetChild(1).GetComponent<Button>().navigation;\n //navigation.mode = Navigation.Mode.Automatic | Navigation.Mode.Vertical | Navigation.Mode.Horizontal;\n }\n\n menuManager.GetComponent<MenuManager>().StartGame();\n //menuManager.GetComponent<MenuManager>().Fade.GetComponent<Animation>().Play(\"TitleFadeOut\");\n }\n\n IEnumerator BurstSpots()\n {\n emission.rateOverTime = 30;\n yield return null;\n emission.rateOverTime = 0; // ou rateOverTime si encore dessus\n velocity.radial = 15;\n while(velocity.radial.constant > 0)\n {\n velocity.radial = Mathf.Max(0, velocity.radial.constant - Time.deltaTime * 10);\n yield return null;\n }\n }\n\n private void OnDisable()\n {\n transform.GetChild(1).GetComponent<MenuParticleSystem>().StopParticleSound();\n }\n}\n" }, { "alpha_fraction": 0.6597127914428711, "alphanum_fraction": 0.665402352809906, "avg_line_length": 36.292930603027344, "blob_id": "c7137875e14c92371198dca26dba7323e6a4a673", "content_id": "7fe7f048c9449a4fe968d5b4db2acb1ce2cebcad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3693, "license_type": "no_license", "max_line_length": 159, "num_lines": 99, "path": "/SoA-Unity/Assets/Scripts/Sound/PostWwiseEventFootstep.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class PostWwiseEventFootstep : MonoBehaviour\n{\n [SerializeField]\n private AK.Wwise.Event MyEvent;\n\n [SerializeField]\n private GameObject rightFoot;\n\n [SerializeField]\n private GameObject leftFoot;\n\n private LayerMask ground;\n\n private Vector3 verticalOffset;\n private Vector3 forwardOffset;\n\n // Use this for initialization.\n void Start()\n {\n ground = LayerMask.GetMask(\"AsphaltGround\") | LayerMask.GetMask(\"GrassGround\") | LayerMask.GetMask(\"ConcreteGround\") | LayerMask.GetMask(\"SoilGround\");\n\n if (rightFoot == null)\n {\n throw new System.Exception(\"No reference to the right foot position\");\n }\n else if(leftFoot == null)\n {\n throw new System.Exception(\"No reference to the left foot position\");\n }\n\n verticalOffset = new Vector3(0, 0.5f, 0);\n forwardOffset = new Vector3(0.25f, 0, 0);\n\n GameObject rightFootRaycaster = new GameObject(\"R_Raycaster\");\n rightFootRaycaster.transform.SetParent (rightFoot.transform);\n rightFootRaycaster.transform.position = rightFoot.transform.position + rightFoot.transform.TransformDirection(forwardOffset + verticalOffset);\n rightFootRaycaster.transform.rotation = rightFoot.transform.rotation;\n\n GameObject leftFootRaycaster = new GameObject(\"L_Raycaster\");\n leftFootRaycaster.transform.SetParent (leftFoot.transform);\n leftFootRaycaster.transform.position = leftFoot.transform.position + leftFoot.transform.TransformDirection( - (forwardOffset + verticalOffset));\n leftFootRaycaster.transform.rotation = Quaternion.Euler(0, 90, 180) * leftFoot.transform.rotation;\n }\n\n // Update is called once per frame.\n void Update()\n {\n\n }\n\n private static string GetGroundType(GameObject o)\n {\n if (o.layer == LayerMask.NameToLayer(\"AsphaltGround\")) { return \"Asphalt\"; }\n if (o.layer == LayerMask.NameToLayer(\"GrassGround\")) { return \"Herbe\"; }\n if (o.layer == LayerMask.NameToLayer(\"SoilGround\")) { return \"Terre\"; }\n if (o.layer == LayerMask.NameToLayer(\"ConcreteGround\")) { return \"Beton\"; }\n else { return \"None\"; }\n }\n\n public void PlayRightFootstepSound()\n {\n AKRESULT result = AkSoundEngine.SetSwitch(\"Droit_Gauche\", \"Droit\", gameObject); // Right foot step sounds\n if(result == AKRESULT.AK_Fail)\n {\n throw new System.Exception(\"Could set the side of the footstep wwise sound\");\n }\n\n if (Physics.Raycast(rightFoot.transform.position, -Vector3.up, out RaycastHit hit, Mathf.Infinity, ground))\n {\n // Load the correct sound according to the ground\n Debug.Log(\"IM WALKING ON = \" + GetGroundType(hit.transform.gameObject));\n result = AkSoundEngine.SetSwitch(\"Pas_Matiere\", GetGroundType(hit.transform.gameObject), gameObject);\n }\n\n MyEvent.Post(gameObject);\n }\n\n public void PlayLeftFootstepSound()\n {\n AKRESULT result = AkSoundEngine.SetSwitch(\"Droit_Gauche\", \"Gauche\", gameObject); // Left foot step sounds\n\n if (result == AKRESULT.AK_Fail)\n {\n throw new System.Exception(\"Could set the side of the footstep wwise sound\");\n }\n\n if (Physics.Raycast(leftFoot.transform.position, -Vector3.up, out RaycastHit hit, Mathf.Infinity, ground))\n {\n // Load the correct sound according to the ground\n result = AkSoundEngine.SetSwitch(\"Pas_Matiere\", GetGroundType(hit.transform.gameObject), gameObject);\n }\n\n MyEvent.Post(gameObject);\n }\n}" }, { "alpha_fraction": 0.6015123724937439, "alphanum_fraction": 0.6209899187088013, "avg_line_length": 31.08823585510254, "blob_id": "f51a05c4df15ecfd9b23125c6b0704f4e6fbeff7", "content_id": "5adfac4d7ccecb0cbbf0b2d6ddb85e5953861f18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4369, "license_type": "no_license", "max_line_length": 169, "num_lines": 136, "path": "/SoA-Unity/Assets/Resources/Scripts/Render_PostProcess.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\n\npublic class Render_PostProcess : MonoBehaviour\n{\n private GameObject player;\n\n [SerializeField]\n public float coef_blur = 1000.0f;\n [SerializeField]\n private float coef_intensity = 16.0f;\n\n [SerializeField]\n public float radius = 0.6f;\n [SerializeField]\n private Vector3 offSetColor;\n [SerializeField]\n private bool state_blur;\n [SerializeField]\n private bool state_chromatique;\n [SerializeField]\n private bool state_feedBack;\n [SerializeField]\n private bool state_vignette_pleine;\n [SerializeField]\n private float lerp_effet;\n [SerializeField]\n public Vector3 offsetChroma;\n\n //partie pour back up visuel pour son\n [SerializeField]\n private GameObject head;\n [SerializeField]\n private Vector2 position;\n [SerializeField]\n private float radius_head_min;\n [SerializeField]\n private float radius_head_max;\n [SerializeField]\n private bool head_activate;\n [SerializeField]\n private Vector4 color_sense;\n\n\n public bool shader_actif = false;\n private Material mat;\n public string shader_name = \"PostProcessV2\";\n private Camera cam;\n private RenderTexture RT;\n int it = 0;\n\n float time_actual = 0.0f;\n float time_refresh = 1.0f;\n\n public float coef = 0.001f;\n\n public float offsetX = 0.0f;\n public float offsetY = 0.0f;\n\n // Start is called before the first frame update\n //a l'init ici\n void Awake()\n {\n state_blur = true;\n state_chromatique = true;\n //courbe blur a gérer en fonction de l'état de vie\n\n player = GameObject.FindGameObjectWithTag(\"Player\");\n\n if(player == null)\n {\n throw new System.NullReferenceException(\"Missing an object tagged Player in the scene\");\n }\n\n lerp_effet = 1.0f;\n\n color_sense = new Vector4(1.0f,1.0f,1.0f,1.0f);\n\n cam = GetComponent<Camera>();\n changeShader(\"PostProcessV2\");\n }\n\n public void changeShader(string name)\n {\n shader_name = name;\n mat = new Material(Shader.Find(\"Shaders/\" + shader_name));\n }\n\n public void SetBlur(float blur)\n {\n //mat.SetFloat(\"_CoefBlur\", blur);\n }\n\n private void OnRenderImage(RenderTexture source, RenderTexture destination)\n {\n \n //non activé\n if (!shader_actif)\n {\n Graphics.Blit(source, destination);\n }\n else\n {\n mat.SetFloat(\"type\", 0);\n\n changeShader(\"PostProcessV2\");\n //mat.SetFloat(\"width\", coef_blur);\n //mat.SetFloat(\"height\", coef_blur);\n mat.SetFloat(\"width\", source.width);\n mat.SetFloat(\"height\", source.height);\n mat.SetFloat(\"life\", player.GetComponent<EnergyBehaviour>().Energy / 10); // 0-1000 -> 0-100\n mat.SetFloat(\"_CoefBlur\", coef_intensity);\n mat.SetFloat(\"_Radius\", radius);\n mat.SetVector(\"_OffsetColor\",new Vector4(offSetColor.x, offSetColor.y, offSetColor.z,1.0f));\n mat.SetInt(\"_StateBlur\",(state_blur ? 1 : 0));\n mat.SetInt(\"_StateChromatique\", (state_chromatique ? 1 : 0));\n mat.SetInt(\"_StateFeedBack\", (state_feedBack ? 1 : 0));\n mat.SetInt(\"_VignettePleine\", (state_vignette_pleine ? 1 : 0));\n mat.SetFloat(\"_LerpEffect\", lerp_effet);\n mat.SetVector(\"_OffsetColor\", new Vector4(offsetChroma.x, offsetChroma.y, offsetChroma.z, 1.0f));\n //mat.SetVector(\"_Position_Head\",new Vector4(head.transform.position.x, head.transform.position.y, head.transform.position.z,(head_activate ? 1.0f : 0.0f)));\n Vector3 position = Camera.current.WorldToScreenPoint(head.transform.position);\n mat.SetVector(\"_Position_Head\", new Vector4(position.x, position.y, position.z, (head_activate ? 1.0f : 0.0f)));\n //mat.SetVector(\"_Position_Head\", new Vector4(position.x, position.y, 0.0f, (head_activate ? 1.0f : 0.0f)));\n mat.SetFloat(\"_Radius_Head_Min\",radius_head_min);\n mat.SetFloat(\"_Radius_Head_Max\", radius_head_max);\n mat.SetVector(\"_Color_Sense\", color_sense);\n\n Debug.Log(\"Marker head est de \" + head.transform.position);\n\n Graphics.Blit(source, destination,mat);\n }\n }\n}\n" }, { "alpha_fraction": 0.5624118447303772, "alphanum_fraction": 0.5691114068031311, "avg_line_length": 27.93877601623535, "blob_id": "193812702b9908dd0027f534788c5b9333c5017f", "content_id": "4d7c9e0f04f4eb112665c7749daf014b99365b51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5674, "license_type": "no_license", "max_line_length": 145, "num_lines": 196, "path": "/SoA-Unity/Assets/Scripts/PlayerControllerB/AnimIkFoot.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class AnimIkFoot : MonoBehaviour\n{\n [SerializeField]\n private GameObject player;\n\n [SerializeField]\n private GameObject ground;\n\n [SerializeField]\n private Animator anim;\n\n [SerializeField]\n [Range(0, 1)]\n private float distanceToGround; \n\n [SerializeField]\n private LayerMask layerMask;\n\n [SerializeField]\n private float skinWidth = 0.2f;\n\n/*\n\n [SerializeField]\n private float ikWeight = 1;\n\n [SerializeField]\n private Transform leftIKTarget, rightIKTarget;\n\n [SerializeField]\n private Transform hintLeft, hintRight;\n\n Vector3 lFpos, rFpos;\n\n Quaternion lFrot, rFrot;\n\n float lFWeight, rFWeight;\n\n Transform leftFoot, rightFoot;\n\n public float offsetY;\n\n */\n\n // Start is called before the first frame update\n void Start()\n {\n /* anim = GetComponent<Animator>();\n\n leftFoot = anim.GetBoneTransform(HumanBodyBones.LeftFoot);\n rightFoot = anim.GetBoneTransform(HumanBodyBones.RightFoot);\n\n lFrot = leftFoot.rotation;\n rFrot = rightFoot.rotation;\n */\n }\n\n\n // Update is called once per frame\n void Update()\n {\n /* RaycastHit leftHit;\n RaycastHit rightHit;\n\n Vector3 lpos = leftFoot.TransformPoint(Vector3.zero);\n Vector3 rpos = rightFoot.TransformPoint(Vector3.zero);\n\n if(Physics.Raycast(lpos, -Vector3.up, out leftHit, 1, layerMask))\n {\n lFpos = leftHit.point;\n lFrot = Quaternion.FromToRotation(transform.up, leftHit.normal) * transform.rotation;\n }\n\n if (Physics.Raycast(rpos, -Vector3.up, out rightHit, 1, layerMask))\n {\n rFpos = rightHit.point;\n rFrot = Quaternion.FromToRotation(transform.up, rightHit.normal) * transform.rotation;\n } */\n }\n\n\n/*\n private void OnAnimatorIK(int layerIndex)\n {\n lFWeight = anim.GetFloat(\"LeftFoot\");\n rFWeight = anim.GetFloat(\"RightFoot\");\n\n \n anim.SetIKPositionWeight(AvatarIKGoal.LeftFoot, lFWeight);\n anim.SetIKPositionWeight(AvatarIKGoal.RightFoot, rFWeight);\n\n anim.SetIKPosition(AvatarIKGoal.LeftFoot, lFpos + new Vector3(0, offsetY, 0));\n anim.SetIKPosition(AvatarIKGoal.RightFoot, rFpos + new Vector3(0, offsetY, 0));\n\n \n anim.SetIKHintPositionWeight(AvatarIKHint.LeftKnee, ikWeight);\n anim.SetIKHintPositionWeight(AvatarIKHint.RightKnee, ikWeight);\n\n anim.SetIKHintPosition(AvatarIKHint.LeftKnee, hintLeft.position);\n anim.SetIKHintPosition(AvatarIKHint.RightKnee, hintLeft.position);\n \n\n\n anim.SetIKRotationWeight(AvatarIKGoal.LeftFoot, lFWeight);\n anim.SetIKRotationWeight(AvatarIKGoal.RightFoot, rFWeight);\n\n anim.SetIKRotation(AvatarIKGoal.LeftFoot, lFrot);\n anim.SetIKRotation(AvatarIKGoal.RightFoot, rFrot);\n\n }\n\n*/\n\n\n\n\n\n private void OnAnimatorIK(int layerIndex)\n {\n \n RaycastHit hit;\n\n\n //Stand Still\n Ray ray = new Ray(anim.GetIKPosition(AvatarIKGoal.LeftFoot) + Vector3.up, Vector3.down);\n\n if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask))\n {\n if (hit.transform.tag == \"Walkable\")\n {\n Vector3 footPosition = hit.point;\n\n Vector3 prevPos = ground.transform.position;\n prevPos.y = footPosition.y - skinWidth;\n ground.transform.position = prevPos;\n \n }\n }\n if(anim)\n {\n //Left Foot\n anim.SetIKPositionWeight(AvatarIKGoal.LeftFoot, 1f);\n anim.SetIKRotationWeight(AvatarIKGoal.LeftFoot, 1f);\n\n // Left Foot Up\n Ray leftRay = new Ray(anim.GetIKPosition(AvatarIKGoal.LeftFoot) + Vector3.up, Vector3.down);\n\n if (Physics.Raycast(leftRay, out hit, distanceToGround + 1f, layerMask))\n {\n if (hit.transform.tag == \"Walkable\")\n {\n Vector3 footPosition = hit.point;\n footPosition.y += distanceToGround;\n\n anim.SetIKPosition(AvatarIKGoal.LeftFoot, footPosition);\n\n anim.SetIKRotation(AvatarIKGoal.LeftFoot, Quaternion.FromToRotation(Vector3.up, hit.normal) * transform.rotation);\n\n }\n }\n\n\n\n // Right Foot\n anim.SetIKPositionWeight(AvatarIKGoal.RightFoot, 1f);\n anim.SetIKRotationWeight(AvatarIKGoal.RightFoot, 1f);\n\n //Right Foot Up\n Ray rightRay = new Ray(anim.GetIKPosition(AvatarIKGoal.RightFoot) + Vector3.up, Vector3.down);\n\n if (Physics.Raycast(rightRay, out hit, distanceToGround + 1f, layerMask))\n {\n if (hit.transform.tag == \"Walkable\")\n {\n Vector3 footPosition = hit.point;\n footPosition.y += distanceToGround;\n\n anim.SetIKPosition(AvatarIKGoal.RightFoot, footPosition);\n\n anim.SetIKRotation(AvatarIKGoal.RightFoot, Quaternion.FromToRotation(Vector3.up, hit.normal) * transform.rotation);\n\n\n }\n }\n\n\n }\n }\n\n \n\n } //FINISH\n" }, { "alpha_fraction": 0.6583912372589111, "alphanum_fraction": 0.6608738899230957, "avg_line_length": 29.984615325927734, "blob_id": "e7dc14502ec3040a4df108e8c3ecf5dfc5825608", "content_id": "dc98ec4ebb119e5fc6970dad29831071510b9e77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2016, "license_type": "no_license", "max_line_length": 98, "num_lines": 65, "path": "/SoA-Unity/Assets/Scripts/Managers/AmbianceManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing AK.Wwise;\n\npublic class AmbianceManager : MonoBehaviour\n{\n private GameObject player;\n\n // Start is called before the first frame update\n void Start()\n {\n player = GameObject.FindGameObjectWithTag(\"Player\");\n\n if(player == null)\n {\n throw new System.NullReferenceException(\"Missing game object tagged with \\\"Player\\\"\");\n }\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n public void PlayHomeAmbiance()\n {\n AkSoundEngine.PostEvent(\"Play_Music_Safe_Zone_Home\", player);\n AkSoundEngine.PostEvent(\"Stop_Pigeon\", player);\n AkSoundEngine.PostEvent(\"Stop_Parc_Oiseaux1\", player);\n }\n\n public void PlayShedAmbiance()\n {\n AkSoundEngine.PostEvent(\"Play_Music_Safe_Zone_Parc\", player);\n AkSoundEngine.PostEvent(\"Stop_Pigeon\", player);\n AkSoundEngine.PostEvent(\"Stop_Parc_Oiseaux1\", player);\n }\n\n public void PlayBarAmbiance()\n {\n AkSoundEngine.PostEvent(\"Play_Music_Safe_Zone_Ville\", player);\n AkSoundEngine.PostEvent(\"Stop_Pigeon\", player);\n AkSoundEngine.PostEvent(\"Stop_Parc_Oiseaux1\", player);\n }\n\n public void PlayCityAmbiance()\n {\n AkSoundEngine.PostEvent(\"Play_Pigeon\", player);\n AkSoundEngine.PostEvent(\"Stop_Parc_Oiseaux1\", player);\n AkSoundEngine.PostEvent(\"Stop_Music_Safe_Zone_Ville\", player);\n AkSoundEngine.PostEvent(\"Stop_Music_Safe_Zone_Parc\", player);\n AkSoundEngine.PostEvent(\"Stop_Music_Safe_Zone_Home\", player);\n }\n\n public void PlayParkAmbiance()\n {\n AkSoundEngine.PostEvent(\"Play_Parc_Oiseaux1\", player);\n AkSoundEngine.PostEvent(\"Stop_Pigeon\", player);\n AkSoundEngine.PostEvent(\"Stop_Music_Safe_Zone_Ville\", player);\n AkSoundEngine.PostEvent(\"Stop_Music_Safe_Zone_Parc\", player);\n AkSoundEngine.PostEvent(\"Stop_Music_Safe_Zone_Home\", player);\n }\n}\n" }, { "alpha_fraction": 0.5014282464981079, "alphanum_fraction": 0.510657012462616, "avg_line_length": 27.092592239379883, "blob_id": "c6d2f11b94138e02140d52283d809b00cd45bc4e", "content_id": "c665c836b7f810d543e671f7e319bb2310f74c1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4553, "license_type": "no_license", "max_line_length": 178, "num_lines": 162, "path": "/SoA-Unity/Assets/Resources/Scripts/OpenCVFaceDetection.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing UnityEngine;\n\n\n//3 * 4 (size of int)\n//autrement dit taille de la structure\n[StructLayout(LayoutKind.Sequential, Size = 12)]\npublic struct CvCircle\n{\n public int X, Y, Radius;\n}\n\ninternal static class OpenCVInterop\n{\n [DllImport(\"Test_OpenCV\")]\n internal static extern int Init(ref int outCameraWidth, ref int outCameraHeight);\n\n [DllImport(\"Test_OpenCV\")]\n internal static extern int Close();\n\n [DllImport(\"Test_OpenCV\")]\n internal static extern int SetScale(int downscale);\n\n\n [DllImport(\"Test_OpenCV\")]\n internal unsafe static extern void Detect(CvCircle* outFaces, int maxOutFacesCount, ref int outDetectedFacesCount);\n\n}\n\npublic class OpenCVFaceDetection : MonoBehaviour\n{\n public static readonly int DIST_MAX = 100;\n public static readonly int DIST_MIN = 10;\n\n public static List<Vector2> NormalizedFacePositions { get; private set; }\n public static Vector2 CameraResolution;\n public static Vector3 positions;\n public static float taille;\n\n private const int DetectionDownScale = 1;\n\n //ne marche pas avec static\n [SerializeField]\n private bool activate = true;\n\n private bool _ready;\n private int _maxFaceDetectCount = 5;\n private bool reset = true;\n private CvCircle[] _faces;\n private Vector2 oldPosition;\n\n void Start()\n {\n activate = false;\n int camWidth = 0, camHeight = 0;\n int result = OpenCVInterop.Init(ref camWidth, ref camHeight);\n if( result < 0)\n {\n if (result == -1)\n {\n Debug.LogWarningFormat(\"[{0}] Failed to find cascades definition.\", GetType());\n }\n else if (result == -2)\n {\n Debug.LogWarningFormat(\"[{0}] Failed to open camera stream.\", GetType());\n }\n\n return;\n }\n CameraResolution = new Vector2(camWidth, camHeight);\n _faces = new CvCircle[_maxFaceDetectCount];\n NormalizedFacePositions = new List<Vector2>();\n OpenCVInterop.SetScale(DetectionDownScale);\n _ready = true;\n }\n\n private void OnApplicationQuit()\n {\n if(_ready)\n {\n OpenCVInterop.Close();\n }\n }\n\n public void setActivate(bool state)\n {\n this.activate = state;\n }\n\n public bool getActivate()\n {\n return this.activate;\n }\n\n void Update()\n {\n if (activate)\n {\n if (!_ready)\n return;\n\n int detectedFaceCount = 0;\n unsafe\n {\n fixed (CvCircle* outFaces = _faces)\n {\n OpenCVInterop.Detect(outFaces, _maxFaceDetectCount, ref detectedFaceCount);\n }\n }\n NormalizedFacePositions.Clear();\n int max = 0;\n int num = -1;\n\n if (detectedFaceCount == 0 || oldPosition == null)\n {\n reset = true;\n }\n else\n {\n reset = false;\n }\n\n for (int i = 0; i < detectedFaceCount; i++)\n {\n NormalizedFacePositions.Add(new Vector2((_faces[i].X * DetectionDownScale) / CameraResolution.x, 1f - ((_faces[i].Y * DetectionDownScale) / CameraResolution.y)));\n if (max < _faces[i].Radius)\n {\n if (!reset)\n {\n //un premier filtre d'input\n float distance = _faces[i].Radius;\n if (distance < 100.0f && distance >= 0.5f)\n {\n max = _faces[i].Radius;\n positions = NormalizedFacePositions[NormalizedFacePositions.Count - 1];\n positions.z = max;\n num = i;\n }\n }\n else\n {\n max = _faces[i].Radius;\n positions = NormalizedFacePositions[NormalizedFacePositions.Count - 1];\n positions.z = max;\n num = i;\n }\n }\n }\n taille = max;\n if (num < 0)\n {\n detectedFaceCount = 0;\n }\n else\n {\n oldPosition = new Vector2(positions.x, positions.y);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5845031142234802, "alphanum_fraction": 0.5951712727546692, "avg_line_length": 28.316871643066406, "blob_id": "d6c7b1a7473e53730cf3317c37e61bd7a355af6d", "content_id": "5e7ba41eea45312dff0fe3f0e8530934fb8e60bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7126, "license_type": "no_license", "max_line_length": 130, "num_lines": 243, "path": "/SoA-Unity/Assets/Scripts/HearingScript.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing AK.Wwise;\n\npublic class HearingScript : MonoBehaviour\n{\n //const int sampleNumber = 1024; // 32768; // 2^15 number of samples for 0,743 seconds\n //const float sampleSeconds = 0.2f; //0.743f; // 32768 hertz / 48000\n\n //private int sampleTotal;\n //private float[] sampleData;\n\n //[SerializeField]\n //[Range(1, 5)]\n //private int hearingMultiplier = 1;\n\n [Header(\"Loudness Detector\")]\n\n [SerializeField]\n [Tooltip(\"How many times per second the hearing is updated (in Hz)\")]\n private float refreshFrequency = 4;\n\n [SerializeField]\n [Range(0, 1)]\n [Tooltip(\"Loudness level limit before character starts feeling damage in protected mode\")]\n private float normalLoudnessThreshold = 0.7f;\n\n [SerializeField]\n [Range(0, 1)]\n [Tooltip(\"Loudness level limit before character starts feeling damage in protected mode\")]\n private float protectedLoudnessThreshold = 0.8f;\n\n [SerializeField]\n [Range(0, 1)]\n [Tooltip(\"Brightness level limit before character starts feeling discomfort\")]\n private float uncomfortableLoudnessThreshold = 0.6f;\n\n private float loudnessThreshold;\n public float LoudnessThreshold { get { return loudnessThreshold; } set { loudnessThreshold = value; } }\n\n [SerializeField]\n [Range(0, 100)]\n private float loudnessDamage = 25;\n\n [Space]\n [Header(\"References\")]\n\n [SerializeField]\n private GameObject player;\n\n [SerializeField]\n private GameObject esthesia;\n\n [SerializeField]\n private EnergyBehaviour energyBehaviour;\n\n [SerializeField]\n private DebuggerBehaviour debuggerBehaviour;\n\n private delegate void LoudnessHandler(float b);\n private event LoudnessHandler LoudnessThresholdEvent;\n private event LoudnessHandler LoudnessUpdateEvent;\n\n private delegate void DamagingSourceHandler(GameObject o);\n private event DamagingSourceHandler DamagingSourceEvent;\n\n private AudioManager audioManager;\n\n // Awake Function\n void Awake()\n {\n //sampleTotal = hearingMultiplier * sampleNumber;\n //sampleData = new float[sampleTotal];\n \n loudnessThreshold = normalLoudnessThreshold;\n }\n\n // Start is called before the first frame update\n void Start()\n {\n audioManager = AudioManager.Instance;\n if (audioManager == null)\n {\n throw new System.NullReferenceException(\"The audio manager could not be loaded\");\n }\n\n if (esthesia.GetComponent<Animator>() == null)\n {\n throw new System.NullReferenceException(\"No Animator attached to Esthesia game object\");\n }\n if (esthesia.GetComponent<EsthesiaAnimation>() == null)\n {\n throw new System.NullReferenceException(\"No Esthesia animation script attached to Esthesia game object\");\n }\n\n LoudnessThresholdEvent += energyBehaviour.DecreaseEnergy;\n LoudnessUpdateEvent += debuggerBehaviour.DisplayLoudness;\n\n // DamagingSourceEvent += cameraFollow.TargetingObstacle;\n\n //StartCoroutine(\"Hear\");\n StartCoroutine(\"WwiseHear\");\n } \n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n /*\n IEnumerator Hear()\n {\n for (; ;)\n {\n float loudness = 0f; \n\n AudioListener.GetOutputData(sampleData, 0);\n //AudioListener.GetOutputData(sampleData+1024, 1);\n\n for (int i = 0; i < sampleTotal; i++)\n {\n float sample = sampleData[i];\n loudness += Mathf.Abs(sample);\n }\n\n loudness /= sampleTotal; //Average Volume\n \n LoudnessUpdateEvent(loudness);\n\n if (loudness >= loudnessThreshold)\n {\n LoudnessThresholdEvent(loudnessDamage);\n\n DamagingSourceEvent(ClosestAudioSource());\n }\n\n yield return new WaitForSeconds(sampleSeconds * hearingMultiplier);\n }\n }*/\n\n IEnumerator WwiseHear()\n {\n for (; ; )\n {\n float loudness = 0f;\n int type = 1;\n AKRESULT result;\n\n result = AkSoundEngine.GetRTPCValue(\"VolumeEcoutePerso\", null, 0, out loudness, ref type);\n\n if(result == AKRESULT.AK_Fail)\n {\n throw new System.Exception(\"No input from Wwise Meter\");\n }\n\n // remap loundess to [0-1] range\n loudness = 1 + loudness / 48.01278f;\n\n LoudnessUpdateEvent(loudness);\n\n if(loudness >= uncomfortableLoudnessThreshold)\n {\n if (!player.GetComponent<PlayerFirst>().IsInsideShelter)\n {\n player.GetComponent<PlayerFirst>().IsUncomfortableEars = true;\n }\n }\n else\n {\n player.GetComponent<PlayerFirst>().IsUncomfortableEars = false;\n }\n\n if (loudness >= loudnessThreshold)\n {\n if (!player.GetComponent<PlayerFirst>().IsInsideShelter)\n {\n // Handle energy loss\n LoudnessThresholdEvent(loudnessDamage);\n\n // Handle animation\n if (!player.GetComponent<PlayerFirst>().IsDamagedEyes)\n {\n player.GetComponent<PlayerFirst>().IsDamagedEars = true;\n // Set animation layer weight\n //esthesia.GetComponent<EsthesiaAnimation>().SelectEarsDamageLayer();\n }\n\n //DamagingSourceEvent?.Invoke(ClosestAudioSource()); // more explicit test of existence needed\n }\n }\n else\n {\n player.GetComponent<PlayerFirst>().IsDamagedEars = false;\n }\n yield return new WaitForSeconds(1f / refreshFrequency);\n }\n }\n\n public void PlugEars()\n {\n loudnessThreshold = protectedLoudnessThreshold;\n }\n\n public void UnplugEars()\n {\n loudnessThreshold = normalLoudnessThreshold;\n }\n\n /* For user options */\n\n public void SetLoudnessDamage(float loudnessDamage)\n {\n this.loudnessDamage = loudnessDamage;\n }\n\n /*\n public GameObject ClosestAudioSource()\n {\n float minDistance = Mathf.Infinity;\n GameObject closestAudioSource = null;\n\n foreach (GameObject o in audioManager.GameObjectWithAudioSources)\n {\n if (o != null)\n {\n float distanceFromAudio = (o.transform.position - transform.parent.transform.parent.transform.position).magnitude;\n\n if (minDistance > distanceFromAudio)\n {\n minDistance = distanceFromAudio;\n closestAudioSource = o;\n }\n }\n }\n\n Debug.Log(closestAudioSource.transform.name + closestAudioSource.transform.position + \" is the closest AudioSource\");\n return closestAudioSource;\n }\n */\n\n} // FINISH\n" }, { "alpha_fraction": 0.6709359884262085, "alphanum_fraction": 0.6709359884262085, "avg_line_length": 35.25, "blob_id": "0d2f6af89bdbf540bee5029988949dab0842b1e7", "content_id": "8f347d0fbadf638fea07b261c2d3540997011e4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3047, "license_type": "no_license", "max_line_length": 124, "num_lines": 84, "path": "/SoA-Unity/Assets/Scripts/Sound/PostWwiseAmbiance.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing AK.Wwise;\n\npublic class PostWwiseAmbiance : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The play event of the park ambiance\")]\n private AK.Wwise.Event parkAmbianceEventPlay;\n public AK.Wwise.Event ParkAmbianceEventPlay { get { return parkAmbianceEventPlay; } }\n\n [SerializeField]\n [Tooltip(\"The stop event of the park ambiance\")]\n private AK.Wwise.Event parkAmbianceEventStop;\n public AK.Wwise.Event ParkAmbianceEventStop { get { return parkAmbianceEventStop; } }\n\n [SerializeField]\n [Tooltip(\"The play event of the city ambiance\")]\n private AK.Wwise.Event cityAmbianceEventPlay;\n public AK.Wwise.Event CityAmbianceEventPlay { get { return cityAmbianceEventPlay; } }\n\n [SerializeField]\n [Tooltip(\"The stop event of the city ambiance\")]\n private AK.Wwise.Event cityAmbianceEventStop;\n public AK.Wwise.Event CityAmbianceEventStop { get { return cityAmbianceEventStop; } }\n\n [SerializeField]\n [Tooltip(\"The play event of the shelter ambiance\")]\n private AK.Wwise.Event shelterAmbianceEventPlay;\n public AK.Wwise.Event ShelterAmbianceEventPlay { get { return shelterAmbianceEventPlay; } }\n\n [SerializeField]\n [Tooltip(\"The stop event of the city ambiance\")]\n private AK.Wwise.Event shelterAmbianceEventStop;\n public AK.Wwise.Event ShelterAmbianceEventStop { get { return shelterAmbianceEventStop; } }\n\n [SerializeField]\n [Tooltip(\"The ambiance the game starts with\")]\n private AMBIANCE ambiance = AMBIANCE.NONE;\n\n // Start is called before the first frame update\n void Start()\n {\n if(parkAmbianceEventPlay == null)\n {\n throw new System.NullReferenceException(\"No parkAmbiance play sound event set on the script PostWwiseAmbiance\");\n }\n if (cityAmbianceEventPlay == null)\n {\n throw new System.NullReferenceException(\"No cityAmbiance play sound event set on the script PostWwiseAmbiance\");\n }\n if (parkAmbianceEventStop == null)\n {\n throw new System.NullReferenceException(\"No parkAmbiance stop sound event set on the script PostWwiseAmbiance\");\n }\n if (cityAmbianceEventStop == null)\n {\n throw new System.NullReferenceException(\"No cityAmbiance stop sound event set on the script PostWwiseAmbiance\");\n }\n\n switch (ambiance)\n {\n case AMBIANCE.PARK:\n CityAmbianceEventStop.Post(gameObject);\n ParkAmbianceEventPlay.Post(gameObject);\n break;\n case AMBIANCE.CITY:\n ParkAmbianceEventStop.Post(gameObject);\n CityAmbianceEventPlay.Post(gameObject);\n break;\n case AMBIANCE.SHELTER:\n ShelterAmbianceEventPlay.Post(gameObject);\n ParkAmbianceEventPlay.Post(gameObject);\n break;\n }\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n}\n" }, { "alpha_fraction": 0.6674938201904297, "alphanum_fraction": 0.6674938201904297, "avg_line_length": 22.705883026123047, "blob_id": "c9b98917be4c736b455b9a12a3c76ac43b70c4ab", "content_id": "08c61d13512ff8f91127372806b1cffe2d9e52ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 808, "license_type": "no_license", "max_line_length": 97, "num_lines": 34, "path": "/SoA-Unity/Assets/Scripts/Menus/MenuParticleSystem.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class MenuParticleSystem : MonoBehaviour\n{\n // Start is called before the first frame update\n void Start()\n {\n ParticleSystem.MainModule main = GetComponent<ParticleSystem>().main;\n main.stopAction = ParticleSystemStopAction.Callback; // To call OnParticleSystemStopped()\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n public void PlayParticleSound()\n {\n AkSoundEngine.PostEvent(\"Play_Texte_Anim_Particule\", gameObject);\n }\n\n public void StopParticleSound()\n {\n AkSoundEngine.PostEvent(\"Stop_Texte_Anim_Particule\", gameObject);\n }\n\n void OnParticleSystemStopped()\n {\n Debug.Log(\"System has stopped!\");\n }\n}\n" }, { "alpha_fraction": 0.6155038475990295, "alphanum_fraction": 0.6186046600341797, "avg_line_length": 22.88888931274414, "blob_id": "1dccdd4353c4fbfd7f7ff88908154b1b6f81f6e2", "content_id": "69712c8dc29c4627872aec6024c13a4a4b014d20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 647, "license_type": "no_license", "max_line_length": 63, "num_lines": 27, "path": "/SoA-Unity/Assets/Resources/Scripts/Neon.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Neon : MonoBehaviour\n{\n [SerializeField]\n Light l;\n [SerializeField]\n bool activate = true;\n\n Material mat;\n // Start is called before the first frame update\n void Start()\n {\n mat = GetComponent<MeshRenderer>().material;\n //nouvelle instance\n mat = new Material(mat);\n gameObject.GetComponent<MeshRenderer>().material = mat;\n }\n void Update()\n {\n mat.SetInt(\"_On\", (activate ? 1 : 0));\n mat.SetFloat(\"_Intensity\", l.intensity);\n mat.SetColor(\"_Color\",l.color);\n }\n}\n" }, { "alpha_fraction": 0.624715268611908, "alphanum_fraction": 0.6355352997779846, "avg_line_length": 30.92727279663086, "blob_id": "72eba7f9f49652d7dc7b6027884fd06aa645efe0", "content_id": "c6606a87063d483d9223c4fd6a7a4b00092ddd2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1758, "license_type": "no_license", "max_line_length": 125, "num_lines": 55, "path": "/SoA-Unity/Assets/LevelPark/Scripts/Placements/SpawnParkTreesSpline.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing Pixelplacement;\n\npublic class SpawnParkTreesSpline : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The model of the park tree to spawn\")]\n private GameObject parkTreePrefab;\n\n [SerializeField]\n [Tooltip(\"The number of park trees in the spline\")]\n [Range(1,100)]\n private int splineLength = 10;\n\n [SerializeField]\n [Tooltip(\"The spline used to spawn the park trees\")]\n private Spline spline;\n\n [SerializeField]\n private Vector3 rotationFixer;\n private Quaternion qRotationFixer;\n\n // Start is called before the first frame update\n void Start()\n {\n if(parkTreePrefab == null)\n {\n throw new System.NullReferenceException(\"No prefab set for the park tree\");\n }\n if(spline == null)\n {\n throw new System.NullReferenceException(\"No spline set for the park tree\");\n }\n\n for (int i = 0; i < splineLength; i++)\n {\n qRotationFixer = Quaternion.Euler(rotationFixer);\n Vector3 pos = spline.GetPosition((i + 1f) / (splineLength + 1f));\n //Quaternion rot = qRotationFixer * Quaternion.LookRotation(spline.GetDirection((i + 1f) / (splineLength + 1f)));\n Quaternion randomize = Quaternion.Euler(0, Random.Range(0, 360), 0);\n Quaternion rot = qRotationFixer * randomize * Quaternion.LookRotation(transform.forward);\n GameObject parkTree = Object.Instantiate(parkTreePrefab, pos, rot);\n parkTree.transform.SetParent(transform, true);\n parkTree.name = \"ParkTree \" + i.ToString();\n }\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n}\n" }, { "alpha_fraction": 0.6016367673873901, "alphanum_fraction": 0.6111404299736023, "avg_line_length": 34.074073791503906, "blob_id": "f30b41a96be3ea20374b4dac60ca686dc4e22c4b", "content_id": "2c8040e5796dfc64c2abfa372c3052dd5ece683d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3791, "license_type": "no_license", "max_line_length": 147, "num_lines": 108, "path": "/SoA-Unity/Assets/LevelStreets/Scripts/Façade.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.SocialPlatforms;\n\npublic class Façade: MonoBehaviour\n{\n private GameObject[] windows;\n private int index;\n\n [SerializeField]\n [Range(0,100)]\n private float lightIntensity = 1;\n\n [SerializeField]\n private float lightAngle = 20;\n\n [SerializeField]\n private float lightRange = 10;\n\n [SerializeField]\n private Material darkMat;\n\n [SerializeField]\n private Material lightMat;\n\n // Start is called before the first frame update\n void Start()\n {\n windows = new GameObject[transform.childCount];\n for (int i = 0; i < transform.childCount; i++)\n {\n windows[i] = transform.GetChild(i).gameObject;\n if(!windows[i].TryGetComponent<MeshRenderer>(out MeshRenderer meshRenderer))\n {\n throw new System.NullReferenceException(\"No MeshRender for the window \" + windows[i].name + \" of the building \" + transform.name);\n }\n if(windows[i].transform.GetChild(0) == null)\n {\n throw new System.NullReferenceException(\"No light child for the window \" + windows[i].name + \" of the building \" + transform.name);\n }\n if(!windows[i].transform.GetChild(0).TryGetComponent<Light>(out Light light))\n {\n throw new System.NullReferenceException(\"No light for the window \" + windows[i].name + \" of the building \" + transform.name);\n }\n if (windows[i].transform.GetChild(1) == null)\n {\n throw new System.NullReferenceException(\"No halo child for the window \" + windows[i].name + \" of the building \" + transform.name);\n }\n if (!windows[i].transform.GetChild(1).TryGetComponent<MeshRenderer>(out MeshRenderer mesRenderer))\n {\n throw new System.NullReferenceException(\"No halo for the window \" + windows[i].name + \" of the building \" + transform.name);\n }\n }\n index = Random.Range(0, transform.childCount);\n\n LightsOut(); // TO DO : Some lights might be highlighted from the start\n\n StartCoroutine(\"Flash\");\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n private void Highlight()\n {\n int newIndex = Random.Range(0, transform.childCount);\n index = (newIndex != index) ? newIndex : (newIndex + 1) % transform.childCount;\n \n windows[index].GetComponent<MeshRenderer>().material = lightMat;\n windows[index].transform.GetChild(0).GetComponent<Light>().enabled = true;\n windows[index].transform.GetChild(0).GetComponent<Light>().spotAngle = 20;\n windows[index].transform.GetChild(0).GetComponent<Light>().spotAngle = 10;\n windows[index].transform.GetChild(0).GetComponent<Light>().intensity = 0.5f;\n windows[index].transform.GetChild(1).GetComponent<MeshRenderer>().enabled = false; // CILYNDRE A METRE TRUUUUUE CACA\n }\n\n private void LightsOut()\n {\n for (int i = 0; i < transform.childCount; i++)\n {\n windows[i].GetComponent<MeshRenderer>().material = darkMat;\n windows[i].transform.GetChild(0).GetComponent<Light>().enabled = false;\n windows[i].transform.GetChild(1).GetComponent<MeshRenderer>().enabled = false;\n }\n }\n\n IEnumerator Flash()\n {\n float darkDuration, lightDuration;\n for (; ; )\n {\n darkDuration = Random.Range(2, 6);\n lightDuration = Random.Range(8, 16);\n\n yield return new WaitForSeconds(darkDuration);\n\n Highlight();\n\n yield return new WaitForSeconds(lightDuration);\n\n LightsOut();\n }\n }\n}\n" }, { "alpha_fraction": 0.6115583777427673, "alphanum_fraction": 0.6190638542175293, "avg_line_length": 31.787471771240234, "blob_id": "68b6c1258de21054faa7711b93fc79a06e2b579f", "content_id": "9c1072d37017912aee309b5ff5fa6f1ba93169c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 14658, "license_type": "no_license", "max_line_length": 222, "num_lines": 447, "path": "/SoA-Unity/Assets/Scripts/PlayerControllerB/PlayerFirst.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing AK.Wwise;\n\npublic interface IAnimable\n{\n Animator Anim { get; }\n bool IsProtectingEyes { get; set; }\n bool IsProtectingEars { get; set; }\n}\npublic class PlayerFirst : MonoBehaviour, IAnimable\n{\n\n private Inputs inputs;\n\n private GameObject gameManager;\n\n [Space]\n [Header(\"Player Settings\")]\n [Space]\n\n [SerializeField]\n private GameObject player;\n\n [SerializeField]\n private CharacterController characterController;\n\n [Space]\n\n [SerializeField]\n [Range(1.0f, 20.0f)]\n [Tooltip(\"Speed of the character\")]\n private float normalSpeed = 18;\n\n private float speed;\n\n [SerializeField]\n [Tooltip(\"Speed of turning right or left\")]\n [Range(1.0f, 360.0f)]\n private float rotationSpeed = 150;\n\n [SerializeField]\n [Tooltip(\"Duration of the half-turn\")]\n [Range(0.1f,10)]\n private float turnBackTime = 0.35f; // seconds\n\n [SerializeField]\n [Tooltip(\"Sensitivity of the Y-Axis to trigger the half-turn\")]\n [Range(-1,0)]\n private float turnBackThreshold = -0.5f;\n\n [SerializeField]\n [Tooltip(\"Minimum Y-Axis value\")]\n [Range(0, 1)]\n private float walkingForwardThreshold = 0.6f;\n\n [SerializeField]\n [Tooltip(\"Minimum X-Axis value\")]\n [Range(0, 1)]\n private float turningAngleThreshold = 0.6f;\n\n [SerializeField]\n [Tooltip(\"Total angle of the joystick (in degrees) that trigger the turn back\")]\n [Range(0, 180)]\n float turnBackAngle = 30; // degs\n\n [SerializeField]\n [Tooltip(\"Total angle of the joystick (in degrees) that trigger full forward movement\")]\n [Range(0, 180)]\n float fullForwardAngle = 60; // degs\n\n private float steeringAngle;\n public float SteeringAngle { get { return steeringAngle; } set { steeringAngle = value; } }\n private bool isTurningBack;\n\n private bool turningBackPressed;\n\n [Space]\n [Header(\"Hurry State\")]\n\n [SerializeField]\n [Range(1.0f, 100.0f)]\n [Tooltip(\"Speed when the character is losing energy\")]\n private float hurrySpeed = 36;\n\n [SerializeField]\n [Tooltip(\"Delay in seconds to transition to normal state after the danger has passed\")]\n [Range(0,30)]\n private float delayToNormalState = 3; // s\n\n private float backToNormalSpeedTimer = 0; // s\n\n\n private bool isHurry;\n public bool IsHurry { get { return isHurry; } }\n\n private bool isProtectingEyes;\n public bool IsProtectingEyes { get { return isProtectingEyes; } set { isProtectingEyes = value; } }\n\n private bool isProtectingEars;\n public bool IsProtectingEars { get { return isProtectingEars; } set { isProtectingEars = value; } }\n\n private bool isDamagedEyes;\n public bool IsDamagedEyes { get { return isDamagedEyes; } set { isDamagedEyes = value; } }\n\n private bool isDamagedEars;\n public bool IsDamagedEars { get { return isDamagedEars; } set { isDamagedEars = value; } }\n\n private float eyesDamageSources;\n public float EyesDamageSources { get { return eyesDamageSources; } set { eyesDamageSources = value; } }\n\n private bool isRunning;\n public bool IsRunning { get { return isRunning; } set { isRunning = value; } }\n\n private bool isUncomfortableEyes;\n public bool IsUncomfortableEyes { get { return isUncomfortableEyes; } set { isUncomfortableEyes = value; } }\n\n private bool isUncomfortableEars;\n public bool IsUncomfortableEars { get { return isUncomfortableEars; } set { isUncomfortableEars = value; } }\n\n private float eyesUncomfortableSources;\n public float EyesUncomfortableSources { get { return eyesUncomfortableSources; } set { eyesUncomfortableSources = value; } }\n\n private bool isInsideShelter;\n public bool IsInsideShelter { get { return isInsideShelter; } set { isInsideShelter = value; } }\n\n [SerializeField]\n private Animator anim;\n public Animator Anim { get { return anim; } }\n\n [SerializeField]\n private GameObject esthesia;\n\n private Vector3 movement;\n\n [Space]\n [Header(\"Ground Detector\")]\n\n [SerializeField]\n private Transform groundLevelPosition;\n\n [SerializeField]\n private Transform raycastPosition;\n\n [SerializeField]\n private GameObject wwiseGameObjectFootstep;\n\n [SerializeField]\n private GameObject wwiseGameObjectBreath;\n\n [Header(\"Shelter\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"The speed of the character when inside the shelter\")]\n [Range(0, 10)]\n private float shelterSpeed = 6;\n public float ShelterSpeed { get { return shelterSpeed; } }\n\n void Awake()\n {\n steeringAngle = player.transform.rotation.eulerAngles.y;\n\n inputs = InputsManager.Instance.Inputs;\n\n gameManager = GameObject.FindGameObjectWithTag(\"GameManager\");\n\n if(gameManager == null)\n {\n throw new System.NullReferenceException(\"No GameManager found in the scene\");\n }\n\n isTurningBack = false;\n isHurry = false;\n isProtectingEyes = false;\n isProtectingEars = false;\n isRunning = false;\n turningBackPressed = false;\n\n // Make sure we spawn at home\n isInsideShelter = true;\n\n isUncomfortableEyes = false;\n isUncomfortableEars = false;\n \n eyesDamageSources = 0;\n\n movement = Vector3.zero;\n\n if(wwiseGameObjectFootstep == null)\n {\n throw new System.Exception(\"Missing reference to a Wwise GameObject\");\n }\n\n if (esthesia.GetComponent<Animator>() == null)\n {\n throw new System.NullReferenceException(\"No Animator attached to Esthesia game object\");\n }\n if (esthesia.GetComponent<EsthesiaAnimation>() == null)\n {\n throw new System.NullReferenceException(\"No Esthesia animation script attached to Esthesia game object\");\n }\n }\n\n // Start is called before the first frame update\n void Start()\n {\n speed = normalSpeed;\n }\n\n // Update is called once per frame\n void Update()\n {\n if(gameManager.GetComponent<GameManager>().IsGameOver)\n {\n anim.SetBool(\"isGameOver\", true);\n\n // deactivate protections if used\n anim.SetBool(\"isProtectingEyes\", false);\n anim.SetBool(\"isProtectingEars\", false);\n }\n \n if (inputs.Player.enabled) // Compulsory, as Disabling or Enabling an Action also Enable the ActionGroup !!!\n {\n StickToGround();\n\n Walk(inputs.Player.Walk.ReadValue<Vector2>());\n\n Debug.Log(\"Movement : \" + movement);\n characterController.Move(movement);\n movement = Vector3.zero;\n\n // Manage the two kinds of vision\n\n if (eyesDamageSources > 0) { isDamagedEyes = true; }\n else { isDamagedEyes = false; }\n eyesDamageSources = 0;\n\n if (eyesUncomfortableSources > 0) { isUncomfortableEyes = true; }\n else { isUncomfortableEyes = false; }\n eyesUncomfortableSources = 0;\n\n if (isDamagedEyes || isDamagedEars) // TO DO : Remove ???\n {\n //inputs.Player.Walk.Disable();\n //inputs.Player.ProtectEyes.Enable();\n //inputs.Player.ProtectEars.Enable();\n AKRESULT result;\n result = AkSoundEngine.SetSwitch(\"Court_Marche\", \"Court\", wwiseGameObjectFootstep); // Running step sounds\n result = AkSoundEngine.SetSwitch(\"Court_Marche\", \"Court\", wwiseGameObjectBreath); // Running step sounds\n }\n\n if (isProtectingEyes || isProtectingEars)\n {\n //inputs.Player.Walk.Enable();\n isDamagedEyes = false; // To check\n isDamagedEars = false; // To check\n AKRESULT result;\n result = AkSoundEngine.SetSwitch(\"Court_Marche\", \"Court\", wwiseGameObjectFootstep); // Running step sounds\n result = AkSoundEngine.SetSwitch(\"Court_Marche\", \"Court\", wwiseGameObjectBreath); // Running step sounds\n }\n\n if (!isDamagedEyes && !isDamagedEars) // TO DO : Remove ???\n {\n inputs.Player.Walk.Enable();\n }\n\n anim.SetBool(\"isProtectingEyes\", isProtectingEyes);\n anim.SetBool(\"isProtectingEars\", isProtectingEars);\n anim.SetBool(\"isDamagedEyes\", isDamagedEyes);\n anim.SetBool(\"isDamagedEars\", isDamagedEars);\n anim.SetBool(\"isUncomfortableEyes\", isUncomfortableEyes);\n anim.SetBool(\"isUncomfortableEars\", isUncomfortableEars);\n }\n else // World-shelter transition\n {\n anim.SetBool(\"isWalking\", false); // stop animation when warping\n // handle animation layer\n esthesia.GetComponent<EsthesiaAnimation>().SelectIdleLayer();\n\n AKRESULT result;\n result = AkSoundEngine.SetSwitch(\"Court_Marche\", \"Idle\", wwiseGameObjectFootstep); // Idle step sounds\n result = AkSoundEngine.SetSwitch(\"Court_Marche\", \"Idle\", wwiseGameObjectBreath); // Idle step sounds\n }\n }\n\n void OnEnable()\n {\n inputs.Player.Enable();\n }\n\n void OnDisable()\n {\n inputs.Player.Disable();\n }\n\n void Walk(Vector2 v)\n {\n if (!isTurningBack)\n {\n if (IsInTurnBackSector(v) && !turningBackPressed) { turningBackPressed = true; StartCoroutine(\"TurnBack\"); return; }\n if (turningBackPressed && v.y > turnBackThreshold) { turningBackPressed = false; }\n \n if (v.y > 0)\n {\n movement += player.transform.forward * Mathf.Clamp(v.y, walkingForwardThreshold, 1f) * speed * Time.deltaTime;\n }\n if (!IsInFullForwardSector(v) && !IsInTurnBackSector(v))\n {\n steeringAngle += Mathf.Sign(v.x) * Mathf.Clamp(Mathf.Abs(v.x), turningAngleThreshold, 1f) * rotationSpeed * Time.deltaTime; // TO DO : Minimum rotation speed threshold, just like the walkingForwardThreshold\n characterController.transform.rotation = Quaternion.Euler(0, steeringAngle, 0);\n if(v.y <= 0)\n {\n movement += player.transform.forward * walkingForwardThreshold * speed * Time.deltaTime;\n }\n }\n\n if (v.magnitude == 0)\n {\n isRunning = false;\n anim.SetBool(\"isWalking\", false);\n // handle animation layer\n esthesia.GetComponent<EsthesiaAnimation>().SelectIdleLayer();\n\n AKRESULT result;\n result = AkSoundEngine.SetSwitch(\"Court_Marche\", \"Idle\", wwiseGameObjectFootstep); // Idle step sounds\n result = AkSoundEngine.SetSwitch(\"Court_Marche\", \"Idle\", wwiseGameObjectBreath); // Idle step sounds\n } else\n {\n isRunning = true;\n anim.SetBool(\"isWalking\", true);\n // handle animation layer\n esthesia.GetComponent<EsthesiaAnimation>().SelectWalkLayer();\n\n AKRESULT result;\n result = AkSoundEngine.SetSwitch(\"Court_Marche\", \"Marche\", wwiseGameObjectFootstep); // Walking step sounds\n result = AkSoundEngine.SetSwitch(\"Court_Marche\", \"Marche\", wwiseGameObjectBreath); // Walking step sounds\n }\n }\n }\n\n private bool IsInTurnBackSector(Vector2 point)\n {\n return point.y <= turnBackThreshold && Mathf.Abs(Mathf.Atan2(point.x, -point.y)) <= turnBackAngle / 2f * Mathf.Deg2Rad;\n }\n\n private bool IsInFullForwardSector(Vector2 point)\n {\n return Mathf.Abs(Mathf.Atan2(point.x, point.y)) <= fullForwardAngle / 2f * Mathf.Deg2Rad;\n }\n\n public void ResetTransform(Vector3 position, float angle)\n {\n transform.position = position;\n StickToGround();\n transform.position += movement;\n movement = Vector3.zero;\n steeringAngle = angle;\n characterController.transform.rotation = Quaternion.Euler(0, steeringAngle, 0);\n }\n\n void StickToGround()\n {\n if (raycastPosition && groundLevelPosition)\n {\n LayerMask ground = LayerMask.GetMask(\"AsphaltGround\") | LayerMask.GetMask(\"GrassGround\") | LayerMask.GetMask(\"ConcreteGround\") | LayerMask.GetMask(\"SoilGround\");\n\n if (Physics.Raycast(raycastPosition.position, -Vector3.up, out RaycastHit hit, Mathf.Infinity, ground))\n {\n movement = new Vector3(0, (hit.point - groundLevelPosition.position).y, 0);\n }\n else\n {\n movement = Vector3.zero;\n }\n }\n }\n\n IEnumerator TurnBack()\n {\n isTurningBack = true;\n\n // TO DO : verifiy these two\n isRunning = true;\n anim.SetBool(\"isWalking\", true);\n\n // handle animation layer\n esthesia.GetComponent<EsthesiaAnimation>().SelectWalkLayer();\n\n AKRESULT result;\n result = AkSoundEngine.SetSwitch(\"Court_Marche\", \"Marche\", wwiseGameObjectFootstep);\n result = AkSoundEngine.SetSwitch(\"Court_Marche\", \"Marche\", wwiseGameObjectBreath);\n\n Vector3 beginForward = transform.forward;\n Vector3 endForward = -transform.forward;\n Vector3 newForward = beginForward;\n\n float elapsedTime = 0;\n\n while (elapsedTime != turnBackTime)\n {\n elapsedTime = Mathf.Min(elapsedTime + Time.deltaTime, turnBackTime);\n newForward = Vector3.RotateTowards(beginForward, endForward, Mathf.PI * elapsedTime / turnBackTime, 0.0f); // turn back = PI\n transform.rotation = Quaternion.LookRotation(newForward);\n yield return null;\n }\n steeringAngle -= 180; // synchronize with update\n isTurningBack = false;\n\n // BUG : Esthesia keep on walking when playing with the game pad\n }\n\n public void Hurry(float energy)\n {\n isHurry = true;\n backToNormalSpeedTimer = delayToNormalState;\n if (speed != hurrySpeed)\n {\n StartCoroutine(\"TransitionToNormalSpeed\");\n }\n speed = hurrySpeed;\n }\n\n IEnumerator TransitionToNormalSpeed()\n {\n while (backToNormalSpeedTimer > 0)\n {\n backToNormalSpeedTimer -= Time.deltaTime;\n yield return null;\n }\n backToNormalSpeedTimer = 0;\n speed = normalSpeed;\n isHurry = false;\n }\n \n public void SetShelterSpeed()\n {\n this.speed = shelterSpeed;\n }\n\n public void ResetSpeed()\n {\n this.speed = normalSpeed;\n }\n\n} // FINISH\n" }, { "alpha_fraction": 0.5960144996643066, "alphanum_fraction": 0.5978260636329651, "avg_line_length": 21.079999923706055, "blob_id": "e04150391b8f6c175c5b5c1c1f14a2c1cc2812df", "content_id": "8ec1cf1c97947cf053c6ec8eba3efac0c7758559", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1106, "license_type": "no_license", "max_line_length": 90, "num_lines": 50, "path": "/SoA-Unity/Assets/Scripts/Managers/InputsManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.InputSystem;\nusing System.Linq;\n\npublic class InputsManager\n{\n private Inputs inputs;\n public Inputs Inputs { get { return inputs; } }\n\n private static InputsManager instance = null;\n public static InputsManager Instance {\n get\n {\n if (instance == null)\n {\n instance = new InputsManager();\n }\n return instance;\n }\n }\n\n private InputsManager()\n {\n inputs = new Inputs();\n /*\n var array = inputs.Player.LookAround.bindings;\n InputBinding binding = array.First(i => i.GetNameOfComposite() == \"OKLM\");\n inputs.Player.LookAround.ChangeBinding(binding).WithName(\"OKLM(whichSideWins=1)\");\n \n inputs.Player.AddCompositeBinding\n (\"Axis(whichSideWins=1)\");*/\n }\n\n private void SetGameControllerAsDevice()\n {\n\n }\n\n private void SetKeyboardMouseAsDevice()\n {\n\n }\n\n public static void Destroy()\n {\n instance = null;\n }\n}\n" }, { "alpha_fraction": 0.5765957236289978, "alphanum_fraction": 0.5787234306335449, "avg_line_length": 22.5, "blob_id": "9b7b7a3b80ca61c88f39cf94277b8daced119e14", "content_id": "89867c3bd909d4cf77ce82032587010ddee2fe35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 942, "license_type": "no_license", "max_line_length": 86, "num_lines": 40, "path": "/SoA-Unity/Assets/Scripts/LightVFXManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\n\npublic class LightVFXManager : MonoBehaviour\n{\n // Start is called before the first frame update\n void Start()\n {\n StartCoroutine(DeactivateLightVFX());\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n IEnumerator DeactivateLightVFX()\n {\n // Wait 1 second for all prefabs to spawn\n // TO DO : Find a cleaner way\n\n yield return new WaitForSeconds(1f);\n\n // Deactivate all brightness VFX during daylight\n\n if (SceneManager.GetActiveScene().name == \"GameElise\")\n {\n foreach (GameObject o in GameObject.FindObjectsOfType(typeof(GameObject)))\n {\n if (o.name == \"LightVisualEffect\")\n {\n o.SetActive(false);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5872291922569275, "alphanum_fraction": 0.5872291922569275, "avg_line_length": 18.93181800842285, "blob_id": "e68e86ad2eff41434e47cfe8489211ab17842df8", "content_id": "6a839d6e349be8fc983021018a2a09eb032ca2a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 879, "license_type": "no_license", "max_line_length": 90, "num_lines": 44, "path": "/SoA-Unity/Assets/Scripts/UI/MessageTrigger.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class MessageTrigger : MonoBehaviour\n{\n private GameObject messageManager;\n\n [SerializeField]\n [Tooltip(\"Tutorial Message to be displayed\")]\n private string infoMessage;\n\n private bool fired;\n\n private void Awake()\n {\n messageManager = transform.parent.gameObject;\n fired = false;\n }\n\n // Start is called before the first frame update\n void Start()\n {\n \n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n private void OnTriggerEnter(Collider other)\n {\n if (!fired)\n {\n if (other.CompareTag(\"Player\"))\n {\n messageManager.GetComponent<MessageManager>().DisplayMessage(infoMessage);\n fired = true;\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6543909311294556, "alphanum_fraction": 0.6543909311294556, "avg_line_length": 21.0625, "blob_id": "2a03b365e1960132614fd24978ba0cba77adf997", "content_id": "ab541f4c45658b7f1aedbdaea4b43f858c3e0083", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 708, "license_type": "no_license", "max_line_length": 121, "num_lines": 32, "path": "/SoA-Unity/Assets/Scripts/Sound/PostWwiseEventCry.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class PostWwiseEventCry : MonoBehaviour\n{\n [SerializeField]\n private AK.Wwise.Event MyEvent;\n\n [SerializeField]\n private GameObject player;\n\n // Use this for initialization.\n void Start()\n {\n player.GetComponent<EnergyBehaviour>().EnterDamageStateEvent += PlayCrySound;\n }\n\n // Update is called once per frame.\n private void Update()\n {\n \n }\n\n public void PlayCrySound()\n {\n if (!player.GetComponent<PlayerFirst>().IsProtectingEars && !player.GetComponent<PlayerFirst>().IsProtectingEyes)\n {\n MyEvent.Post(gameObject);\n }\n }\n}\n" }, { "alpha_fraction": 0.6101589202880859, "alphanum_fraction": 0.6170146465301514, "avg_line_length": 22.59558868408203, "blob_id": "346cfcffbcc0538d71df92ce0c51f254a77980ab", "content_id": "b05c425b8f4ce1b757dc1ebd1a2b8d5b4485f760", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3211, "license_type": "no_license", "max_line_length": 122, "num_lines": 136, "path": "/SoA-Unity/Assets/Scripts/EnergyBehaviour.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nusing UnityEngine.UI;\n\npublic class EnergyBehaviour : MonoBehaviour\n{\n private Inputs inputs;\n\n [SerializeField]\n [Range(0,1000)]\n private float energy;\n public float Energy { get { return energy; } set { energy = value; } }\n\n public GameObject gameManager;\n\n private MonoBehaviour script;\n\n [SerializeField]\n private DebuggerBehaviour debuggerBehaviour;\n\n public delegate void EnergyChangedHandler(float e);\n public event EnergyChangedHandler EnergyChangedEvent;\n\n public delegate void EnterDamageStateHandler();\n public event EnterDamageStateHandler EnterDamageStateEvent;\n\n public delegate void OutOfEnergyHandler();\n public event OutOfEnergyHandler OutOfEnergyEvent;\n\n private bool isReloading;\n public bool IsReloading { get { return isReloading; } set { isReloading = value; } }\n \n [SerializeField]\n [Tooltip(\"Refilling speed in hp/second\")]\n private int refillRate = 10;\n\n private bool godMode;\n\n private void Awake()\n {\n gameManager = GameObject.FindGameObjectWithTag(\"GameManager\");\n\n if(gameManager == null)\n {\n throw new System.NullReferenceException(\"No game manager attached to energy script\");\n }\n\n isReloading = false;\n\n godMode = false;\n debuggerBehaviour.transform.Find(\"GodMode\").GetComponent<Text>().enabled = false;\n\n inputs = InputsManager.Instance.Inputs;\n\n // TO DO : Comment it out for final release\n //inputs.Player.GodMode.performed += _ctx => GodMode();\n\n script = GetComponent<PlayerFollow>() ? GetComponent<PlayerFollow>() : (MonoBehaviour)GetComponent<PlayerFirst>();\n OutOfEnergyEvent += gameManager.GetComponent<GameManager>().GameOver;\n EnergyChangedEvent += debuggerBehaviour.DisplayEnergy;\n EnergyChangedEvent += GetComponent<PlayerFirst>().Hurry;\n }\n\n // Start is called before the first frame update\n void Start()\n {\n\n }\n\n // Update is called once per frame\n void Update()\n {\n if(isReloading)\n {\n IncreaseEnergy(refillRate);\n }\n }\n\n public void DecreaseEnergy(float e)\n {\n if(godMode)\n {\n return;\n }\n\n if (energy != 0)\n {\n energy -= e;\n\n EnergyChangedEvent(energy);\n\n if (energy <= 0)\n {\n energy = 0;\n OutOfEnergy();\n }\n }\n }\n\n public void IncreaseEnergy(float e)\n {\n energy += e;\n\n EnergyChangedEvent(energy);\n\n if(energy > 1000)\n {\n energy = 1000;\n }\n }\n\n void OutOfEnergy() // pour l'instant\n {\n OutOfEnergyEvent?.Invoke();\n script.enabled = false;\n }\n\n public bool IsFull()\n {\n return energy == 1000;\n }\n\n private void GodMode()\n {\n godMode = !godMode;\n debuggerBehaviour.transform.Find(\"GodMode\").GetComponent<Text>().enabled = godMode;\n }\n\n public void Invincibility(bool invincibility)\n {\n godMode = invincibility;\n }\n\n} // FINISH\n" }, { "alpha_fraction": 0.7022569179534912, "alphanum_fraction": 0.7065972089767456, "avg_line_length": 35, "blob_id": "4ed187d2ba2ba6f7c0797578705fab4dc89850cb", "content_id": "7b18d6b09c83d2b89fbb53a29457a31acb6de6da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1154, "license_type": "no_license", "max_line_length": 123, "num_lines": 32, "path": "/SoA-Unity/Assets/Scripts/UI/Billboard.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Billboard : MonoBehaviour\n{\n private GameObject mainCamera;\n\n //private float zAngle;\n ParticleSystem.ShapeModule shapeModule;\n\n // Start is called before the first frame update\n void Start()\n {\n //Debug.Assert(GetComponent<ParticleSystemRenderer>() != null);\n //GetComponent<ParticleSystemRenderer>().material.renderQueue = 4001;\n //zAngle = transform.rotation.eulerAngles.z;\n //shapeModule = GetComponent<ParticleSystem>().shape;\n mainCamera = GameObject.FindGameObjectWithTag(\"MainCamera\");\n Debug.Assert(mainCamera != null);\n }\n\n // Update is called once per frame\n void Update()\n {\n //transform.LookAt(Vector3.zero);\n transform.LookAt(mainCamera.transform.position);\n //transform.rotation = Quaternion.LookRotation(mainCamera.transform.position - transform.position);\n //shapeModule.rotation = Quaternion.LookRotation(mainCamera.transform.position - shapeModule.position).eulerAngles;\n //transform.LookAt(Camera.main.transform.position);\n }\n}\n" }, { "alpha_fraction": 0.7416413426399231, "alphanum_fraction": 0.7477203607559204, "avg_line_length": 29, "blob_id": "37f58cd0452d019a9d0ed5f35887393d378f5ef4", "content_id": "ad622fbd986e05f7cfe423f7e827c8eaa3d7488a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 331, "license_type": "no_license", "max_line_length": 169, "num_lines": 11, "path": "/SoA-Unity/Assets/Scripts/Cutscene/InvalidResourceException.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class InvalidResourceException : System.IO.IOException\n{\n public InvalidResourceException(string name, string path) : base(string.Format(\"Resources '{0}' could not be loaded from the resources folder at '{1}'\", name, path))\n {\n\n }\n}" }, { "alpha_fraction": 0.6951219439506531, "alphanum_fraction": 0.7682926654815674, "avg_line_length": 40, "blob_id": "819d26f2fca8991c41eb81d921399ffeece4bf4f", "content_id": "b8f863e3c2532a897b86e4a43ee4a2a8fa85f12d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 82, "license_type": "no_license", "max_line_length": 75, "num_lines": 2, "path": "/README.md", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "# SoA\nSenses of Adventure is a student video game project made on Unity 2019.3.6.\n" }, { "alpha_fraction": 0.6165919303894043, "alphanum_fraction": 0.6337817907333374, "avg_line_length": 25.235294342041016, "blob_id": "69d968bb4e13a8bebcd2741d2f61c5971efbd258", "content_id": "769d83bc94bf980b9e2d30c9c893d183398d8cf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1340, "license_type": "no_license", "max_line_length": 88, "num_lines": 51, "path": "/SoA-Unity/Assets/LevelPark/Scripts/WateringSystem.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class WateringSystem : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"Number of divisions of the full rotation\")]\n [Range(5,25)]\n private float divisions = 10;\n\n [SerializeField]\n [Tooltip(\"The delay between two bursts in seconds\")]\n [Range(0.01f, 1f)]\n private float delay = 0.4f;\n\n private float deltaAngle;\n private float xAngle;\n private float yAngle;\n\n private ParticleSystem.EmissionModule emission;\n\n // Start is called before the first frame update\n void Start()\n {\n xAngle = transform.rotation.eulerAngles.x;\n yAngle = transform.rotation.eulerAngles.y;\n deltaAngle = 360f / divisions;\n emission = GetComponent<ParticleSystem>().emission;\n StartCoroutine(\"Rotate\");\n }\n\n // Update is called once per frame\n void Update()\n {\n\n }\n\n IEnumerator Rotate()\n {\n for(;;)\n {\n yAngle = Mathf.Repeat(yAngle + deltaAngle, 360f);\n transform.rotation = Quaternion.Euler(xAngle, yAngle, transform.rotation.y);\n emission.rateOverTime = 100;\n yield return new WaitForSeconds(delay / 2f);\n emission.rateOverTime = 0;\n yield return new WaitForSeconds(delay / 2f);\n }\n }\n}\n" }, { "alpha_fraction": 0.6491525173187256, "alphanum_fraction": 0.6491525173187256, "avg_line_length": 25.22222137451172, "blob_id": "40e79bc6138dc0596ab10e62082f3f08eedc6d84", "content_id": "ae4771aaaa52fbd62ff80f6209e5175e3e2972ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1182, "license_type": "no_license", "max_line_length": 104, "num_lines": 45, "path": "/SoA-Unity/Assets/Scripts/Sound/PostWwiseEventObstacle.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class PostWwiseEventObstacle : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The play event of the obstacle\")]\n private AK.Wwise.Event obstacleEventPlay;\n public AK.Wwise.Event ObstacleEventPlay { get { return obstacleEventPlay; } }\n\n [SerializeField]\n [Tooltip(\"The stop event of the obstacle\")]\n private AK.Wwise.Event obstacleEventStop;\n public AK.Wwise.Event ObstacleEventStop { get { return obstacleEventStop; } }\n\n // Start is called before the first frame update\n void Start()\n {\n if(obstacleEventPlay == null)\n {\n throw new System.NullReferenceException(\"No play event for the obstacle \" + transform.name);\n }\n if(obstacleEventStop == null)\n {\n throw new System.NullReferenceException(\"No stop event for the obstacle \" + transform.name);\n }\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n public void Play()\n {\n obstacleEventPlay.Post(gameObject);\n }\n\n public void Stop()\n {\n obstacleEventStop.Post(gameObject);\n }\n}\n" }, { "alpha_fraction": 0.8035714030265808, "alphanum_fraction": 0.8214285969734192, "avg_line_length": 27, "blob_id": "f2b3bff0ce253af1cbc14fd3914ec9148e8787e9", "content_id": "3586f426f5b9bfafe2752cf82a2001c8ca0f8b27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 56, "license_type": "no_license", "max_line_length": 34, "num_lines": 2, "path": "/SoA-Unity/Assets/Models/Home/desktop.ini", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "[LocalizedFileNames]\nhouse_outdoor.fbx=@house_outdoor,0\n" }, { "alpha_fraction": 0.6577181220054626, "alphanum_fraction": 0.6684563755989075, "avg_line_length": 26.592592239379883, "blob_id": "802a2aa68050122b388277230ed5f629692ff034", "content_id": "cf38c79e0e26e1fe3cf21029b1da15eba9aff507", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 747, "license_type": "no_license", "max_line_length": 147, "num_lines": 27, "path": "/SoA-Unity/Assets/Resources/Scripts/Herbe.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Herbe : MonoBehaviour\n{\n [SerializeField]\n GameObject Player;\n\n Material mat;\n\n // Start is called before the first frame update\n void Start()\n {\n mat = GetComponent<MeshRenderer>().material;\n }\n\n // Update is called once per frame\n void Update()\n {\n float distance = (Player.transform.position - transform.position).magnitude;\n mat.SetVector(\"_PlayerPosition\", new Vector4(Player.transform.position.x, Player.transform.position.y, Player.transform.position.z, 0.0f));\n mat.SetInt(\"_DynamicRender\", 1);\n //ici tess fixer a 50\n //mat.SetFloat(\"_TessellationUniform\", 50);\n }\n}\n" }, { "alpha_fraction": 0.6617953777313232, "alphanum_fraction": 0.6701461672782898, "avg_line_length": 33.71014404296875, "blob_id": "f934aa07deffd79aead724c53166ea6d7c786ee9", "content_id": "27285f662bb613d1a7cdbc9fd90e2968e9544eb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2399, "license_type": "no_license", "max_line_length": 341, "num_lines": 69, "path": "/SoA-Unity/Assets/Scripts/Tutorial/TutorialManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.InputSystem;\nusing TMPro;\nusing UnityEngine.SceneManagement;\nusing UnityEngine.UI;\n\npublic class TutorialManager : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"Message to update\")]\n private GameObject message;\n\n [SerializeField]\n [Tooltip(\"The skip button of the message box\")]\n private Image skipButton;\n\n private Inputs inputs;\n\n private GameObject transitions;\n\n // Start is called before the first frame update\n void Start()\n {\n // Transitions\n transitions = GameObject.FindGameObjectWithTag(\"Transitions\");\n transitions.GetComponent<Transitions>().FadeIn();\n\n inputs = InputsManager.Instance.Inputs;\n inputs.Player.Enable();\n\n inputs.Player.SkipDialog.performed += StartGame;\n\n Debug.Assert(skipButton != null, \"Missing skip button\");\n if (PlayerPrefs.GetString(\"controls\").Equals(\"gamepad\"))\n {\n skipButton.sprite = Resources.Load<Sprite>(\"Cutscene\\\\Images\\\\cutscene 1920\\\\skip-button-white\");\n }\n else\n {\n skipButton.sprite = Resources.Load<Sprite>(\"Cutscene\\\\Images\\\\cutscene 1920\\\\skip-key-white\");\n }\n\n //message.GetComponent<TextMeshProUGUI>().text = \"Quand vous ne pouvez éviter un <color=#adb1d0><b>obstacle</b></color>, utilisez <color=#adb1d0><b>\" + inputs.Player.ProtectEyes.GetBindingDisplayString() + \"</b></color> ou <color=#adb1d0><b>\" + inputs.Player.ProtectEars.GetBindingDisplayString() + \"</b></color> pour vous protéger\";\n message.GetComponent<TextMeshProUGUI>().text = \"When you can't avoid an <color=#adb1d0><b>obstacle</b></color>, use <color=#adb1d0><b>\" + inputs.Player.ProtectEyes.GetBindingDisplayString() + \"</b></color> or <color=#adb1d0><b>\" + inputs.Player.ProtectEars.GetBindingDisplayString() + \"</b></color> to protect yourself\";\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n private void StartGame(InputAction.CallbackContext ctx)\n {\n Debug.Log(\"Loading game elise\");\n\n StartCoroutine(transitions.GetComponent<Transitions>().FadeOut(\"GameElise\"));\n //SceneManager.LoadScene(\"GameElise\");\n }\n\n private void OnDestroy()\n {\n Debug.Log(\"On Destroy\");\n\n inputs.Player.SkipDialog.performed -= StartGame;\n }\n}\n" }, { "alpha_fraction": 0.6374993920326233, "alphanum_fraction": 0.6486778259277344, "avg_line_length": 43.080745697021484, "blob_id": "01e8c6fcd8dc5c09c6f63dc312eed190f70f6f60", "content_id": "55a54befd1cdc481abfec6cc791586002b510bf5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 21293, "license_type": "no_license", "max_line_length": 333, "num_lines": 483, "path": "/SoA-Unity/Assets/Scripts/PlayerControllerA/CameraFirst.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class CameraFirst : MonoBehaviour\n{\n\n private Inputs inputs;\n\n [Space]\n [Header(\"Camera Settings\")]\n [Space]\n\n [SerializeField]\n private GameObject player;\n\n [SerializeField]\n [Tooltip(\"Camera's angular offset from the player's orientation\")]\n private Vector3 cameraAngularOffset;\n\n [Space]\n [Header(\"Position (Spherical Coordinates)\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"Distance to the player\")]\n private float radius = 10f;\n private float storedRadius;\n\n [SerializeField]\n [Tooltip(\"Longitude in degrees\")]\n [Range(-180, 180)]\n private float longitude = 20f;\n private float storedLongitude;\n\n [SerializeField]\n [Tooltip(\"Latitude in degrees\")]\n [Range(-90, 90)]\n private float latitude = -45f;\n private float storedLatitude;\n\n [Space]\n [Header(\"Position (Cartesian Coordinates)\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"Camera's position in cartesians coordinates relative to the player's position\")]\n private Vector3 cameraOffset;\n private Vector3 storedCameraOffset;\n\n private Vector3 lastPlayerPosition;\n\n [Space]\n [Header(\"Look around\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"The held camera (must be a child of the camera holder)\")]\n private GameObject heldCamera;\n\n [SerializeField]\n [Tooltip(\"Max horizontal angle of a look around\")]\n [Range(5, 90)]\n private float maxHorizontalAngle = 45; // degrees\n\n [SerializeField]\n [Tooltip(\"Max vertical angle of a look around\")]\n [Range(5, 90)]\n private float maxVerticalAngle = 45; // degrees\n\n [SerializeField]\n [Tooltip(\"Duration to reach the maxHorizontalLookAroundAngle when the input is pushed at max\")]\n [Range(0.1f, 5)]\n private float horizontalDuration = 0.5f; // seconds\n\n [SerializeField]\n [Tooltip(\"Duration to reach the maxVerticalLookAroundAngle when the input is pushed at max\")]\n [Range(0.1f, 5)]\n private float verticalDuration = 0.5f; // seconds\n\n private Vector2 accumulator = Vector2.zero;\n\n enum STATE\n {\n NORMAL,\n HURRY,\n PROTECTED,\n NORMAL_TO_HURRY,\n HURRY_TO_NORMAL,\n HURRY_TO_PROTECTED,\n NORMAL_TO_PROTECTED,\n PROTECTED_TO_NORMAL,\n PROTECTED_TO_HURRY\n };\n STATE cameraState;\n\n [Space]\n [Header(\"Normal Mode\")]\n\n [SerializeField]\n [Tooltip(\"The delay to switch from hurry to normal view, in seconds\")]\n [Range(0.1f, 5)]\n private float timeHurryToNormal = 1.5f;\n\n [SerializeField]\n [Tooltip(\"The delay to switch from protected to normal view, in seconds\")]\n [Range(0.1f, 5)]\n private float timeProtectedToNormal = 0.7f;\n\n [Space]\n [Header(\"Hurry Mode\")]\n\n [SerializeField]\n [Tooltip(\"Z-Offset when player is in hurry mode (-closer, +farther)\")]\n [Range(-10, 10)]\n private float Z_OffsetHurry = -4f;\n\n [SerializeField]\n [Tooltip(\"Y-Offset when player is in hurry mode (-closer, +farther)\")]\n [Range(-10, 10)]\n private float Y_OffsetHurry = 0;\n\n [SerializeField]\n [Tooltip(\"The delay to switch from normal to hurry view, in seconds\")]\n [Range(0.1f, 5)]\n private float timeNormalToHurry = 0.7f;\n\n [SerializeField]\n [Tooltip(\"The delay to switch from protected to hurry view, in seconds\")]\n [Range(0.1f, 5)]\n private float timeProtectedToHurry = 0.4f;\n\n [Space]\n [Header(\"Protected Mode\")]\n\n [SerializeField]\n [Tooltip(\"Z-Offset when player is in protected mode (-closer, +farther)\")]\n [Range(-10, 10)]\n private float Z_OffsetProtected = -10f;\n\n [SerializeField]\n [Tooltip(\"Y-Offset when player is in hurry mode (-closer, +farther)\")]\n [Range(-10, 10)]\n private float Y_OffsetProtected = 4;\n\n [SerializeField]\n [Tooltip(\"The delay to switch from normal to protected view, in seconds\")]\n [Range(0.1f, 5)]\n private float timeNormalToProtected = 0.7f;\n\n [SerializeField]\n [Tooltip(\"The delay to switch from hurry to protected view, in seconds\")]\n [Range(0.1f, 5)]\n private float timeHurryToProtected = 0.4f;\n\n private float zoomTimer;\n\n private float angleFromNormalToHorizon = 0;\n private float angleFromHurryToHorizon = 0;\n private float angleFromProtectedToHorizon = 0;\n\n private void Awake()\n {\n inputs = InputsManager.Instance.Inputs;\n }\n\n // Start is called before the first frame update\n void Start()\n {\n InitializeConverter();\n\n transform.position = player.transform.position + Quaternion.Euler(90, 0, 0) * new Vector3(radius * Mathf.Cos(Mathf.Deg2Rad * latitude) * Mathf.Cos(Mathf.Deg2Rad * longitude),\n radius * Mathf.Cos(Mathf.Deg2Rad * latitude) * Mathf.Sin(Mathf.Deg2Rad * longitude),\n radius * Mathf.Sin(Mathf.Deg2Rad * latitude));\n\n angleFromNormalToHorizon = Vector3.Angle(Vector3.ProjectOnPlane((player.transform.position - transform.position), Vector3.up).normalized, (player.transform.position - transform.position).normalized);\n\n Vector3 hurryPosition = transform.position - Z_OffsetHurry * Vector3.ProjectOnPlane((player.transform.position - transform.position).normalized, Vector3.up) + Y_OffsetHurry * Vector3.up;\n angleFromHurryToHorizon = Vector3.Angle(Vector3.ProjectOnPlane((player.transform.position - transform.position), Vector3.up).normalized, (player.transform.position - hurryPosition).normalized);\n\n Vector3 protectedPosition = transform.position - Z_OffsetProtected * Vector3.ProjectOnPlane((player.transform.position - transform.position).normalized, Vector3.up) + Y_OffsetProtected * Vector3.up;\n angleFromProtectedToHorizon = Vector3.Angle(Vector3.ProjectOnPlane((player.transform.position - transform.position), Vector3.up).normalized, (player.transform.position - protectedPosition).normalized);\n\n cameraState = STATE.NORMAL;\n zoomTimer = 0;\n\n lastPlayerPosition = player.transform.position;\n }\n\n // Update is called once per frame\n void LateUpdate()\n {\n UpdateCamera();\n\n LookAround(inputs.Player.LookAround.ReadValue<Vector2>());\n }\n\n private void OnEnable()\n {\n inputs.Player.Enable();\n }\n\n private void OnDisable()\n {\n inputs.Player.Disable();\n }\n\n private void UpdateCamera ()\n {\n UpdateRecoilPosition();\n\n transform.position += (player.transform.position - lastPlayerPosition);\n lastPlayerPosition = player.transform.position;\n\n transform.rotation = Quaternion.LookRotation(player.transform.position - transform.position);\n\n transform.rotation *= Quaternion.Euler(cameraAngularOffset.x, cameraAngularOffset.y, cameraAngularOffset.z);\n }\n\n void UpdateRecoilPosition()\n {\n if (cameraState == STATE.NORMAL)\n {\n if (player.GetComponent<PlayerFollow>().IsProtectingEyes || player.GetComponent<PlayerFirst>().IsProtectingEars)\n {\n zoomTimer = timeNormalToProtected;\n cameraState = STATE.NORMAL_TO_PROTECTED;\n }\n\n else if (player.GetComponent<PlayerFollow>().IsHurry)\n {\n zoomTimer = timeNormalToHurry;\n cameraState = STATE.NORMAL_TO_HURRY;\n }\n }\n\n else if (cameraState == STATE.HURRY)\n {\n if (player.GetComponent<PlayerFollow>().IsProtectingEyes || player.GetComponent<PlayerFirst>().IsProtectingEars)\n {\n zoomTimer = timeHurryToProtected;\n cameraState = STATE.HURRY_TO_PROTECTED;\n }\n else if (!player.GetComponent<PlayerFollow>().IsHurry)\n {\n zoomTimer = timeHurryToNormal;\n cameraState = STATE.HURRY_TO_NORMAL;\n }\n }\n\n else if (cameraState == STATE.PROTECTED)\n {\n if (!player.GetComponent<PlayerFollow>().IsProtectingEyes && !player.GetComponent<PlayerFirst>().IsProtectingEars)\n {\n if (player.GetComponent<PlayerFollow>().IsHurry)\n {\n zoomTimer = timeProtectedToHurry;\n cameraState = STATE.PROTECTED_TO_HURRY;\n }\n else\n {\n zoomTimer = timeProtectedToNormal;\n cameraState = STATE.PROTECTED_TO_NORMAL;\n }\n }\n }\n\n else if (cameraState == STATE.NORMAL_TO_HURRY)\n {\n Vector3 startPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetHurry + Vector3.up * Y_OffsetHurry) * (timeNormalToHurry - zoomTimer) / timeNormalToHurry; // recreate original position\n Vector3 endPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetHurry + Vector3.up * Y_OffsetHurry) * zoomTimer / timeNormalToHurry; // recreate original position\n zoomTimer = Mathf.Max(zoomTimer - Time.deltaTime, 0);\n transform.position = Vector3.Lerp(startPosition, endPosition, (timeNormalToHurry - zoomTimer) / timeNormalToHurry);\n\n if (zoomTimer <= 0)\n {\n transform.position = endPosition; // should wait one frame more\n cameraState = STATE.HURRY;\n }\n }\n\n else if (cameraState == STATE.HURRY_TO_NORMAL)\n {\n Vector3 startPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetHurry + Vector3.up * Y_OffsetHurry) * (timeHurryToNormal - zoomTimer) / timeHurryToNormal; // recreate original position\n Vector3 endPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetHurry + Vector3.up * Y_OffsetHurry) * zoomTimer / timeHurryToNormal; // recreate original position\n zoomTimer = Mathf.Max(zoomTimer - Time.deltaTime, 0);\n transform.position = Vector3.Lerp(startPosition, endPosition, (timeHurryToNormal - zoomTimer) / timeHurryToNormal);\n\n if (zoomTimer <= 0)\n {\n transform.position = endPosition; // should wait one frame more\n cameraState = STATE.NORMAL;\n }\n }\n\n else if (cameraState == STATE.NORMAL_TO_PROTECTED)\n {\n Vector3 startPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetProtected + Vector3.up * Y_OffsetProtected) * (timeNormalToProtected - zoomTimer) / timeNormalToProtected; // recreate original position\n Vector3 endPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetProtected + Vector3.up * Y_OffsetProtected) * zoomTimer / timeNormalToProtected; // recreate original position\n zoomTimer = Mathf.Max(zoomTimer - Time.deltaTime, 0);\n transform.position = Vector3.Lerp(startPosition, endPosition, (timeNormalToProtected - zoomTimer) / timeNormalToProtected);\n\n if (zoomTimer <= 0)\n {\n transform.position = endPosition; // should wait one frame more\n cameraState = STATE.PROTECTED;\n }\n }\n\n else if (cameraState == STATE.PROTECTED_TO_NORMAL)\n {\n Vector3 startPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetProtected + Vector3.up * Y_OffsetProtected) * (timeProtectedToNormal - zoomTimer) / timeProtectedToNormal; // recreate original position\n Vector3 endPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * Z_OffsetProtected + Vector3.up * Y_OffsetProtected) * zoomTimer / timeProtectedToNormal; // recreate original position\n zoomTimer = Mathf.Max(zoomTimer - Time.deltaTime, 0);\n transform.position = Vector3.Lerp(startPosition, endPosition, (timeProtectedToNormal - zoomTimer) / timeProtectedToNormal);\n\n if (zoomTimer <= 0)\n {\n transform.position = endPosition; // should wait one frame more\n cameraState = STATE.NORMAL;\n }\n }\n\n else if (cameraState == STATE.HURRY_TO_PROTECTED)\n {\n Vector3 startPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * (Z_OffsetHurry - Z_OffsetProtected) + Vector3.up * (Y_OffsetHurry - Y_OffsetProtected)) * (timeHurryToProtected - zoomTimer) / timeHurryToProtected; // recreate original position\n Vector3 endPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * (Z_OffsetHurry - Z_OffsetProtected) + Vector3.up * (Y_OffsetHurry - Y_OffsetProtected)) * zoomTimer / timeHurryToProtected; // recreate original position\n zoomTimer = Mathf.Max(zoomTimer - Time.deltaTime, 0);\n transform.position = Vector3.Lerp(startPosition, endPosition, (timeHurryToProtected - zoomTimer) / timeHurryToProtected);\n\n if (zoomTimer <= 0)\n {\n transform.position = endPosition; // should wait one frame more\n cameraState = STATE.PROTECTED;\n }\n }\n\n else if (cameraState == STATE.PROTECTED_TO_HURRY)\n {\n Vector3 startPosition = transform.position + (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * (Z_OffsetProtected - Z_OffsetHurry) + Vector3.up * (Y_OffsetProtected - Y_OffsetHurry)) * (timeProtectedToHurry - zoomTimer) / timeProtectedToHurry; // recreate original position\n Vector3 endPosition = transform.position - (-Vector3.ProjectOnPlane(player.transform.position - transform.position, Vector3.up).normalized * (Z_OffsetProtected - Z_OffsetHurry) + Vector3.up * (Y_OffsetProtected - Y_OffsetHurry)) * zoomTimer / timeProtectedToHurry; // recreate original position\n zoomTimer = Mathf.Max(zoomTimer - Time.deltaTime, 0);\n transform.position = Vector3.Lerp(startPosition, endPosition, (timeProtectedToHurry - zoomTimer) / timeProtectedToHurry);\n\n if (zoomTimer <= 0)\n {\n transform.position = endPosition; // should wait one frame more\n cameraState = STATE.HURRY;\n }\n }\n }\n\n void LookAround(Vector2 v)\n {\n float smoothx = 0;\n float smoothy = 0;\n\n bool lookingAround = false;\n\n if(Mathf.Approximately(v.magnitude, 0))\n {\n lookingAround = false;\n }\n else\n {\n lookingAround = true;\n }\n\n if (!Mathf.Approximately(v.x, 0)) // then increase accumulator.x\n {\n accumulator.x = Mathf.Clamp(accumulator.x + v.x * Time.deltaTime / horizontalDuration, -1, 1);\n smoothx = Mathf.Sign(accumulator.x) * Mathf.Sin(Mathf.Abs(accumulator.x) * Mathf.PI * 0.5f);\n }\n else // then decrease accumulator.x\n {\n accumulator.x = (1 - Mathf.Sign(accumulator.x)) / 2f * Mathf.Min(accumulator.x - Mathf.Sign(accumulator.x) * Time.deltaTime / horizontalDuration, 0) + (1 + Mathf.Sign(accumulator.x)) / 2f * Mathf.Max(accumulator.x - Mathf.Sign(accumulator.x) * Time.deltaTime / horizontalDuration, 0);\n smoothx = Mathf.Sign(accumulator.x) * Mathf.Sin(Mathf.Abs(accumulator.x) * Mathf.PI * 0.5f);\n }\n\n if (!Mathf.Approximately(v.y, 0)) // then increase accumulator.y\n {\n accumulator.y = Mathf.Clamp(accumulator.y + v.y * Time.deltaTime / verticalDuration, -1, 1);\n smoothy = Mathf.Sign(accumulator.y) * Mathf.Sin(Mathf.Abs(accumulator.y) * Mathf.PI * 0.5f);\n }\n else // then decrease accumulator.y\n {\n accumulator.y = (1 - Mathf.Sign(accumulator.y)) / 2f * Mathf.Min(accumulator.y - Mathf.Sign(accumulator.y) * Time.deltaTime / verticalDuration, 0) + (1 + Mathf.Sign(accumulator.y)) / 2f * Mathf.Max(accumulator.y - Mathf.Sign(accumulator.y) * Time.deltaTime / verticalDuration, 0);\n smoothy = Mathf.Sign(accumulator.y) * Mathf.Sin(Mathf.Abs(accumulator.y) * Mathf.PI * 0.5f);\n }\n\n // Stabilization of the look around\n float y_stabilization = 0;\n if (cameraState == STATE.NORMAL) { y_stabilization = -angleFromNormalToHorizon; } // this state needed by this camera\n\n else if (cameraState == STATE.HURRY) { y_stabilization = -angleFromHurryToHorizon; }\n else if (cameraState == STATE.NORMAL_TO_HURRY) { y_stabilization = -(angleFromNormalToHorizon * zoomTimer / timeNormalToHurry + angleFromHurryToHorizon * (timeNormalToHurry - zoomTimer) / timeNormalToHurry); }\n else if (cameraState == STATE.HURRY_TO_NORMAL) { y_stabilization = -(angleFromHurryToHorizon * zoomTimer / timeHurryToNormal + angleFromNormalToHorizon * (timeHurryToNormal - zoomTimer) / timeHurryToNormal); }\n\n else if (cameraState == STATE.PROTECTED) { y_stabilization = -angleFromProtectedToHorizon; }\n else if (cameraState == STATE.NORMAL_TO_PROTECTED) { y_stabilization = -(angleFromNormalToHorizon * zoomTimer / timeNormalToProtected + angleFromProtectedToHorizon * (timeNormalToProtected - zoomTimer) / timeNormalToProtected); }\n else if (cameraState == STATE.PROTECTED_TO_NORMAL) { y_stabilization = -(angleFromProtectedToHorizon * zoomTimer / timeProtectedToNormal + angleFromNormalToHorizon * (timeProtectedToNormal - zoomTimer) / timeProtectedToNormal); }\n\n else if (cameraState == STATE.HURRY_TO_PROTECTED) { y_stabilization = -(angleFromHurryToHorizon * zoomTimer / timeHurryToProtected + angleFromProtectedToHorizon * (timeHurryToProtected - zoomTimer) / timeHurryToProtected); }\n else if (cameraState == STATE.PROTECTED_TO_HURRY) { y_stabilization = -(angleFromProtectedToHorizon * zoomTimer / timeProtectedToHurry + angleFromHurryToHorizon * (timeProtectedToHurry - zoomTimer) / timeProtectedToHurry); }\n\n // Must be separated in three because unity's order for euler is ZYX and we want X-Y-X\n heldCamera.transform.localRotation = Quaternion.Euler( Mathf.Abs(smoothx) * y_stabilization, 0, 0);\n heldCamera.transform.localRotation *= Quaternion.Euler(0, smoothx * maxHorizontalAngle, 0);\n heldCamera.transform.localRotation *= Quaternion.Euler(-smoothy * maxVerticalAngle, 0, 0);\n\n //heldCamera.transform.localRotation = Quaternion.Euler(-smoothy * maxLookAroundAngle, smoothx * maxLookAroundAngle, 0);\n }\n\n /* Spherical-Cartesian conversion functions */\n\n private void InitializeConverter()\n {\n storedCameraOffset = cameraOffset;\n storedLatitude = latitude;\n storedLongitude = longitude;\n storedRadius = radius;\n }\n\n private void SphericalToCartesian()\n {\n Debug.Log(\"Spherical -> Cartesian\");\n cameraOffset.x = radius * Mathf.Cos(longitude * Mathf.Deg2Rad) * Mathf.Cos(latitude * Mathf.Deg2Rad);\n cameraOffset.y = radius * Mathf.Sin(longitude * Mathf.Deg2Rad) * Mathf.Cos(latitude * Mathf.Deg2Rad);\n cameraOffset.z = radius * Mathf.Sin(latitude * Mathf.Deg2Rad);\n\n storedCameraOffset = cameraOffset;\n }\n\n public void CartesianToSpherical()\n {\n Debug.Log(\"Cartesian -> Spherical\");\n radius = cameraOffset.magnitude;\n longitude = Mathf.Atan(Mathf.Sqrt(Mathf.Pow(cameraOffset.x,2) + Mathf.Pow(cameraOffset.y,2)) / cameraOffset.z) * Mathf.Rad2Deg;\n latitude = Mathf.Atan(cameraOffset.x / cameraOffset.y) * Mathf.Rad2Deg;\n\n storedLatitude = latitude;\n storedLongitude = longitude;\n storedRadius = radius;\n }\n\n // OnValidate is called before Awake\n private void OnValidate()\n {\n if (isActiveAndEnabled)\n {\n if (storedCameraOffset != cameraOffset)\n {\n transform.position += (cameraOffset - storedCameraOffset); // update the game\n\n storedCameraOffset = cameraOffset;\n CartesianToSpherical();\n }\n\n else if (storedRadius != radius)\n {\n // TO DO : update the game from changed value\n\n storedRadius = radius;\n SphericalToCartesian();\n }\n else if (storedLongitude != longitude)\n {\n // TO DO : update the game from changed value\n\n storedLongitude = longitude;\n SphericalToCartesian();\n }\n else if (storedLatitude != latitude)\n {\n // TO DO : update the game from changed value\n\n storedLatitude = latitude;\n SphericalToCartesian();\n }\n }\n }\n\n} //FINISH\n" }, { "alpha_fraction": 0.6833616495132446, "alphanum_fraction": 0.6918506026268005, "avg_line_length": 22.098039627075195, "blob_id": "c25eb5b33ffa65fa1ff30f846145c8c59eeb5eac", "content_id": "fd3f321e944105ffaa24e19accf4d55af5b28165", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1178, "license_type": "no_license", "max_line_length": 131, "num_lines": 51, "path": "/SoA-Unity/Assets/AnalyticsData/PlotAnimation.py", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "import matplotlib as mpl\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cbook as cbook\nimport matplotlib.animation as animation\nimport csv\nimport os\nimport sys\n\nxdata = []\nydata = []\n\nif len(sys.argv) < 2:\n number = 0;\nelse:\n number = sys.argv[1]\n\nwith open('C:/Users/Administrateur/Documents/GitHub/SoA/SoA-Unity/Assets/AnalyticsData/run' + str(number) + '.csv') as csvDataFile:\n csvReader = csv.reader(csvDataFile)\n for row in csvReader:\n xdata.append(float(row[1]))\n ydata.append(float(row[2]))\n\nxmin = np.min(xdata)\nxmax = np.max(xdata)\nymin = np.min(ydata)\nymax = np.max(ydata)\n\nfig = plt.figure()\n\naxes = fig.add_subplot(111)\naxes.set_title(\"Path of Esthesia\\nEvolution of the player's position on the map\") \naxes.set_xlabel('X Position')\naxes.set_ylabel('Y Position')\naxes.set_xlim([xmin,xmax])\naxes.set_ylim([ymin,ymax])\n\nline, = axes.plot([],[])\n\ndef start():\n line.set_data([],[])\n return line,\n\n\ndef update(frame):\n line.set_data(xdata[:frame], ydata[:frame])\n return line,\n\nani = animation.FuncAnimation(fig, update, init_func=start, frames=len(xdata), blit=True, interval=20, repeat=False)\n\nplt.show()\n" }, { "alpha_fraction": 0.5951265096664429, "alphanum_fraction": 0.6082473993301392, "avg_line_length": 30.382352828979492, "blob_id": "f4a64737f1f441e149d969dd03f1812cd6c175bf", "content_id": "6df509512c7e7a845519bd151e9536a8226b5131", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2136, "license_type": "no_license", "max_line_length": 98, "num_lines": 68, "path": "/SoA-Unity/Assets/Scripts/NPC/NPCMaterialsManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class NPCMaterialsManager : MonoBehaviour\n{\n private List<Material> hairEyebrowsMats;\n private List<Material> hatMats;\n private List<Material> femaleNPCMats;\n private List<Material> maleNPCMats;\n\n // Start is called before the first frame update\n void Awake()\n {\n Random.InitState(Random.Range(0,1000));\n\n hairEyebrowsMats = new List<Material>();\n hatMats = new List<Material>();\n femaleNPCMats = new List<Material>();\n maleNPCMats = new List<Material>();\n\n string materialName;\n for(int i = 1; i <= 14; i++)\n {\n materialName = \"Materials/NPC/material_hair_eyebrows_\" + i.ToString().PadLeft(2, '0');\n hairEyebrowsMats.Add(Resources.Load<Material>(materialName));\n }\n for(int i = 1; i <= 6; i++)\n {\n materialName = \"Materials/NPC/material_hat_\" + i.ToString().PadLeft(2, '0');\n hatMats.Add(Resources.Load(materialName, typeof(Material)) as Material);\n }\n for (int i = 1; i <= 10; i++)\n {\n materialName = \"Materials/NPC/material_NPC_F_\" + i.ToString().PadLeft(2, '0');\n femaleNPCMats.Add(Resources.Load(materialName, typeof(Material)) as Material);\n }\n for (int i = 1; i <= 10; i++)\n {\n materialName = \"Materials/NPC/material_NPC_M_\" + i.ToString().PadLeft(2, '0');\n maleNPCMats.Add(Resources.Load(materialName, typeof(Material)) as Material);\n }\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n public Material GetMaleNPCMaterial()\n {\n return maleNPCMats[Random.Range(0, maleNPCMats.Count)];\n }\n\n public Material GetFemaleNPCMaterial()\n {\n return femaleNPCMats[Random.Range(0, femaleNPCMats.Count)];\n }\n public Material GetHatMaterial()\n {\n return hatMats[Random.Range(0, hatMats.Count)];\n }\n public Material GetHairEyebrowsMaterial()\n {\n return hairEyebrowsMats[Random.Range(0, hairEyebrowsMats.Count)];\n }\n}\n" }, { "alpha_fraction": 0.6915500164031982, "alphanum_fraction": 0.6993260979652405, "avg_line_length": 30.112903594970703, "blob_id": "34be27a588ae564351bdfebf48aacfe8cc2c2d56", "content_id": "8e98a0607632701c5ab99bf96a24c8b34ffe8c7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1931, "license_type": "no_license", "max_line_length": 218, "num_lines": 62, "path": "/SoA-Unity/Assets/Scripts/UI/CompassBehavior.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nusing UnityEngine.UI;\n\npublic class CompassBehavior : MonoBehaviour\n{\n private GameObject compassMagnet;\n\n private GameObject mainCamera;\n\n private GameObject compassBackground;\n\n private float degrees = 0;\n private Vector3 axis;\n private Quaternion orientation;\n\n // Start is called before the first frame update\n void Awake()\n {\n mainCamera = GameObject.FindGameObjectWithTag(\"MainCamera\");\n compassMagnet = GameObject.FindGameObjectWithTag(\"CompassMagnet\");\n compassBackground = transform.parent.gameObject;\n\n Debug.Assert(compassBackground != null, \"No child found in Compass\");\n Debug.Assert(mainCamera != null, \"Missing main camera\");\n Debug.Assert(compassMagnet != null, \"Missing compass magnet\");\n\n //axis = (Quaternion.Euler(-45, 0, 0) * Vector3.up).normalized;\n axis = Vector3.forward;\n orientation = Quaternion.FromToRotation(Vector3.forward, axis);\n\n compassBackground.transform.rotation = orientation;\n }\n\n // Update is called once per frame\n void Update()\n {\n Redraw();\n }\n\n private void OnEnable()\n {\n Redraw();\n }\n\n public void Redraw()\n {\n degrees = Vector3.SignedAngle(Vector3.ProjectOnPlane(compassMagnet.transform.position - mainCamera.transform.position, Vector3.up), Vector3.ProjectOnPlane(mainCamera.transform.forward, Vector3.up), Vector3.up);\n transform.rotation = Quaternion.AngleAxis(degrees, axis) * orientation;\n }\n\n public void ReloadReferences()\n {\n mainCamera = GameObject.FindGameObjectWithTag(\"MainCamera\");\n compassMagnet = GameObject.FindGameObjectWithTag(\"CompassMagnet\");\n\n compassBackground = transform.parent.gameObject;\n compassBackground.transform.rotation = orientation;\n }\n}\n" }, { "alpha_fraction": 0.6219098567962646, "alphanum_fraction": 0.6320891976356506, "avg_line_length": 30.738462448120117, "blob_id": "9a131fa317ae99417b6e458e81433a187a387b61", "content_id": "2ee0413a32766f02b7a508658a7a1fd328e4ff0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2065, "license_type": "no_license", "max_line_length": 150, "num_lines": 65, "path": "/SoA-Unity/Assets/LevelPark/Scripts/Placements/SpawnStreetLampsLine.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing Pixelplacement;\n\npublic class SpawnStreetLampsLine : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The model of the street light to spawn\")]\n private GameObject streetLightPrefab;\n\n [SerializeField]\n [Tooltip(\"The number of street lamps in the line\")]\n [Range(1,100)]\n private int lineLength = 10;\n\n [SerializeField]\n [Tooltip(\"The start position of the line\")]\n private Transform startLine;\n\n [SerializeField]\n [Tooltip(\"The end position of the line\")]\n private Transform endLine;\n\n private Quaternion rotationFixer = Quaternion.Euler(0, 180, 0);\n\n // Start is called before the first frame update\n void Start()\n {\n if(streetLightPrefab == null)\n {\n throw new System.NullReferenceException(\"No prefab set for the street light\");\n }\n if(startLine == null)\n {\n throw new System.NullReferenceException(\"No start position set for the street lights\");\n }\n if(endLine == null)\n {\n throw new System.NullReferenceException(\"No end position set for the street lights\");\n }\n if(endLine == startLine)\n {\n throw new System.NullReferenceException(\"Start and end position are the same for the street lights line\");\n }\n\n Vector3 startPos = startLine.position;\n Vector3 endPos = endLine.position;\n\n for (int i = 0; i < lineLength; i++)\n {\n Vector3 pos = Vector3.Lerp(startPos, endPos, (i + 1f) / (lineLength + 1f));\n Quaternion rot = rotationFixer * Quaternion.LookRotation(Vector3.Slerp(startLine.forward, endLine.forward, (i + 1f) / (lineLength + 1f)));\n GameObject streetLight = Object.Instantiate(streetLightPrefab, pos, rot);\n streetLight.transform.SetParent(transform, true);\n streetLight.name = \"StreetLamp \" + i.ToString();\n }\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n}\n" }, { "alpha_fraction": 0.5911722183227539, "alphanum_fraction": 0.6049203872680664, "avg_line_length": 23.24561309814453, "blob_id": "366fb8c5d8ad8a4e0eb5f5dda44828fb325b9701", "content_id": "a3e9dcf7c6833c43c012db1828c33e4dcb9695d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1384, "license_type": "no_license", "max_line_length": 90, "num_lines": 57, "path": "/SoA-Unity/Assets/LevelStreets/Scripts/Bus.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityEngine.SocialPlatforms;\n\npublic class Bus : MonoBehaviour\n{\n [SerializeField]\n private GameObject axis;\n\n [SerializeField]\n private GameObject stop;\n\n [SerializeField]\n [Range(1,100)]\n private float speed = 5;\n\n [SerializeField]\n private float waitTime = 7;\n\n private Vector3 startPosition;\n private float radius;\n private float angle;\n\n private float accumulator = 0;\n\n // Start is called before the first frame update\n void Start()\n {\n startPosition = transform.position;\n radius = (transform.position - axis.transform.position).magnitude;\n StartCoroutine(\"StopAndGo\");\n }\n\n // Update is called once per frame\n void Update()\n {\n }\n\n private IEnumerator StopAndGo()\n {\n for(; ;)\n {\n //float arc = Mathf.PI * 2f * radius * angle / 360;\n accumulator = 0;\n while(accumulator != 360)\n {\n angle = -Time.deltaTime * speed;\n accumulator = Mathf.Min(accumulator + Mathf.Abs(angle), 360);\n transform.RotateAround(axis.transform.position, axis.transform.up, angle);\n yield return null;\n }\n yield return new WaitForSeconds(waitTime);\n }\n }\n}\n" }, { "alpha_fraction": 0.5536799430847168, "alphanum_fraction": 0.5651586651802063, "avg_line_length": 34.261905670166016, "blob_id": "ae7e6f8a34aab83e8ab822c762a48aa91527bba5", "content_id": "40a09e86224b17d39d633d40b2afdacd9f0d1082", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1483, "license_type": "no_license", "max_line_length": 79, "num_lines": 42, "path": "/SoA-Unity/Assets/Resources/Scripts/Dynamic.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Dynamic : MonoBehaviour\n{\n private static readonly int NB_BUFFER_SHADER = 16;\n MeshRenderer mesh;\n // Start is called before the first frame update\n void Start()\n {\n mesh = GetComponent<MeshRenderer>();\n if(mesh == null)\n {\n SkinnedMeshRenderer skinmesh = GetComponent<SkinnedMeshRenderer>();\n List < Vector4 > vec = new List<Vector4>();\n for (int i = 0; i < NB_BUFFER_SHADER; i++)\n {\n vec.Add(new Vector4());\n }\n skinmesh.materials[0].SetFloat(\"vector_lenght\", 0);\n skinmesh.materials[0].SetVectorArray(\"vector_pos\", vec);\n skinmesh.materials[0].SetVectorArray(\"vector_dir\", vec);\n skinmesh.materials[0].SetVectorArray(\"vector_col\", vec);\n skinmesh.materials[0].SetVectorArray(\"vector_opt\", vec);\n }\n else\n {\n List<Vector4> vec = new List<Vector4>();\n for (int i = 0; i < NB_BUFFER_SHADER; i++)\n {\n vec.Add(new Vector4());\n }\n mesh.material.SetFloat(\"vector_lenght\", 0);\n mesh.material.SetVectorArray(\"vector_pos\", vec);\n mesh.material.SetVectorArray(\"vector_dir\", vec);\n mesh.material.SetVectorArray(\"vector_col\", vec);\n mesh.material.SetVectorArray(\"vector_opt\", vec);\n }\n }\n\n}\n" }, { "alpha_fraction": 0.5885810256004333, "alphanum_fraction": 0.5885810256004333, "avg_line_length": 25.76404571533203, "blob_id": "d725ba7dceffa7d25c3767fce6f4fdbbe2b9c784", "content_id": "a4efe5fec13defbd3cca6601cface1d52a228441", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2384, "license_type": "no_license", "max_line_length": 113, "num_lines": 89, "path": "/SoA-Unity/Assets/Scripts/Protect.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Protect : MonoBehaviour\n{\n [SerializeField]\n private HearingScript hearingScript;\n\n [SerializeField]\n private VisionBehaviour indirectBrightness;\n\n [SerializeField]\n private VisionBehaviour directBrightness;\n\n private Inputs inputs;\n\n private IAnimable player;\n\n private void Awake()\n {\n foreach(IAnimable controller in GetComponents<IAnimable>()) // does getcomponents works with interfaces ?\n {\n if((controller as MonoBehaviour).enabled)\n {\n player = controller;\n }\n }\n if(player == null)\n {\n throw new System.NullReferenceException(\"No player reference passed to Protect script\");\n }\n if(hearingScript == null)\n {\n throw new System.NullReferenceException(\"No hearing script reference passed to Protect script\");\n }\n\n inputs = InputsManager.Instance.Inputs;\n\n inputs.Player.ProtectEyes.performed += _ctx =>\n {\n player.IsProtectingEyes = true; \n indirectBrightness.CoverEyes();\n directBrightness.CoverEyes();\n AkSoundEngine.SetState(\"Protection_Oui_Non\", \"Active\"); // Wwise\n };\n inputs.Player.ProtectEyes.canceled += _ctx =>\n {\n player.IsProtectingEyes = false;\n indirectBrightness.UncoverEyes();\n directBrightness.UncoverEyes();\n AkSoundEngine.SetState(\"Protection_Oui_Non\", \"Pas_Active\"); // Wwise\n };\n\n inputs.Player.ProtectEars.performed += _ctx =>\n {\n player.IsProtectingEars = true;\n hearingScript.PlugEars();\n AkSoundEngine.SetState(\"Protection_Oui_Non\", \"Active\"); // Wwise\n };\n inputs.Player.ProtectEars.canceled += _ctx =>\n {\n player.IsProtectingEars = false;\n hearingScript.UnplugEars();\n AkSoundEngine.SetState(\"Protection_Oui_Non\", \"Pas_Active\"); // Wwise\n };\n }\n\n // Start is called before the first frame update\n void Start()\n {\n \n }\n\n // Update is called once per frame\n void Update()\n {\n\n }\n\n void OnEnable()\n {\n inputs.Player.Enable();\n }\n void OnDisable()\n {\n inputs.Player.Disable();\n }\n}\n" }, { "alpha_fraction": 0.6263473033905029, "alphanum_fraction": 0.6263473033905029, "avg_line_length": 20.973684310913086, "blob_id": "c74cb47d12410c993dc0686efea810f6e60285bf", "content_id": "76b533917b8e6cd82ce0014dd7ca5c645fa3c5ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 837, "license_type": "no_license", "max_line_length": 93, "num_lines": 38, "path": "/SoA-Unity/Assets/Scripts/ExitCity.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class ExitCity : MonoBehaviour\n{\n\n [SerializeField]\n [Tooltip(\"Reference to the game manager\")]\n private GameObject gameManager;\n\n private delegate void ExitHandler();\n private event ExitHandler ExitEvent;\n\n // Start is called before the first frame update\n void Start()\n {\n if (gameManager == null)\n {\n throw new System.NullReferenceException(\"Missing reference to the game manager\");\n }\n ExitEvent += gameManager.GetComponent<GameManager>().WinGame;\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n private void OnTriggerEnter(Collider other)\n {\n if(other.CompareTag(\"Player\"))\n {\n ExitEvent();\n }\n }\n}\n" }, { "alpha_fraction": 0.5927295088768005, "alphanum_fraction": 0.593961775302887, "avg_line_length": 21.859155654907227, "blob_id": "44461316a07730fcb2658b3bb546ee4c7bd308f9", "content_id": "63e4acfaea82cedbe065e2166189d90446de6002", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1625, "license_type": "no_license", "max_line_length": 69, "num_lines": 71, "path": "/SoA-Unity/Assets/Scripts/Transitions/Transitions.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nusing UnityEngine.UI;\n\npublic class Transitions : MonoBehaviour\n{\n private static GameObject singleton;\n\n [SerializeField]\n private GameObject black;\n\n // Start is called before the first frame update\n void Awake()\n {\n if (singleton == null)\n {\n singleton = gameObject;\n DontDestroyOnLoad(gameObject);\n }\n else if (singleton != gameObject)\n {\n Destroy(gameObject);\n return;\n }\n }\n\n public bool IsOn()\n {\n return black.GetComponent<Image>().color.a == 1;\n }\n\n public bool IsOff()\n {\n return black.GetComponent<Image>().color.a == 0;\n }\n\n\n public void FadeIn()\n {\n black.GetComponent<Animation>().Play(\"TransitionsFadeIn\");\n }\n\n public IEnumerator FadeOut(string sceneName)\n {\n black.GetComponent<Animation>().Play(\"TransitionsFadeOut\");\n\n yield return new WaitUntil(() => IsOn());\n\n if (GameObject.FindGameObjectWithTag(\"GameManager\") == null)\n {\n SceneManager.LoadScene(sceneName);\n }\n else\n {\n SceneManager.LoadScene(sceneName); // idem\n\n // DoDestroyOnLoad\n Destroy(GameObject.FindGameObjectWithTag(\"SaveManager\"));\n Destroy(GameObject.FindGameObjectWithTag(\"MainCanvas\"));\n Destroy(GameObject.FindGameObjectWithTag(\"GameManager\"));\n }\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n}\n" }, { "alpha_fraction": 0.485397607088089, "alphanum_fraction": 0.5049260854721069, "avg_line_length": 34.97468185424805, "blob_id": "781555ae11fb19ceefb5f4e598559d5f199a5b70", "content_id": "767c01dccb46b77b0f2378633688c2877989e087", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5686, "license_type": "no_license", "max_line_length": 157, "num_lines": 158, "path": "/SoA-Unity/Assets/Resources/Scripts/ColliderStatic.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class ColliderStatic : MonoBehaviour\n{\n private static readonly int NB_BUFFER_SHADER = 32;\n MeshRenderer mesh;\n HashSet<GameObject> lights;\n int cmpt = 0;\n bool collider = true;\n\n // Start is called before the first frame update\n void Awake()\n {\n lights = new HashSet<GameObject>();\n mesh = GetComponent<MeshRenderer>();\n List <Vector4> vec = new List <Vector4>();\n for(int i = 0; i < NB_BUFFER_SHADER; i++)\n {\n vec.Add(new Vector4());\n }\n mesh.material.SetFloat(\"vector_lenght\", 0);\n mesh.material.SetVectorArray(\"vector_pos\",vec);\n mesh.material.SetVectorArray(\"vector_dir\", vec);\n mesh.material.SetVectorArray(\"vector_col\", vec);\n mesh.material.SetVectorArray(\"vector_opt\", vec);\n }\n\n void Update()\n {\n if(Time.realtimeSinceStartup > 4.0f && collider)\n {\n Debug.Log(\"Debut \" + gameObject.name);\n collider = false;\n CapsuleCollider [] colliders = gameObject.GetComponents<CapsuleCollider>();\n if(colliders != null && colliders.Length > 0)\n {\n for (int i = 0; i < colliders.Length; i++)\n {\n colliders[i].enabled = false;\n }\n }\n else\n {\n Debug.Log(\"Box \" + gameObject.name);\n BoxCollider[] boxes = gameObject.GetComponents<BoxCollider>();\n for (int i = 0; i < boxes.Length; i++)\n {\n boxes[i].enabled = false;\n }\n }\n\n } \n }\n\n void OnTriggerEnter(UnityEngine.Collider other)\n {\n\n if (gameObject.name.Equals(\"Downtown Terrain\") && !other.name.Equals(\"Light_Lampadaire\"))\n {\n return;\n }\n\n Light l = other.gameObject.GetComponent<Light>();\n\n if (l != null && lights.Count < NB_BUFFER_SHADER && !lights.Contains(other.gameObject))\n {\n Debug.Log(\"Static Enter \" + other.name + \" \" + gameObject.name);\n\n lights.Add(l.gameObject);\n Vector4 pos_;\n Vector4 dir_;\n Vector4 opt_;\n Vector4 col_;\n\n col_ = l.color;\n float value = l.range;\n opt_ = new Vector4(0.0f, 0.0f, 0.0f, 0.0f);\n dir_ = new Vector4(0.0f, 0.0f, 0.0f, l.intensity);\n switch (l.type)\n {\n case LightType.Point:\n value *= -1;\n //opt_ = new Vector4(0.0f, 0.0f, 0.0f, 0.0f);\n //dir_ = new Vector4(0.0f, 0.0f, 0.0f, 0.0f);\n break;\n case LightType.Spot:\n Vector3 direction = l.transform.rotation.eulerAngles;\n dir_ = new Vector4((direction.x * Mathf.PI) / 180.0f, (direction.y * Mathf.PI) / 180.0f, (direction.z * Mathf.PI) / 180.0f, l.intensity);\n //angle\n float outerRad = Mathf.Deg2Rad * 0.5f * l.spotAngle;\n float outerCos = Mathf.Cos(outerRad);\n float outerTan = Mathf.Tan(outerRad);\n float innerCos = Mathf.Cos(Mathf.Atan(((64.0f - 18.0f) / 64.0f) * outerTan));\n float angleRange = Mathf.Max(innerCos - outerCos, 0.001f);\n\n float X = 1.0f / Mathf.Max(l.range * l.range, 0.00001f);\n float Z = 1.0f / angleRange;\n float W = -outerCos * Z;\n\n opt_ = new Vector4(X, 0.0f, Z, W);\n break;\n default:\n //\n break;\n }\n pos_ = new Vector4(l.gameObject.transform.position.x, l.gameObject.transform.position.y, l.gameObject.transform.position.z, value);\n\n\n float len = mesh.material.GetFloat(\"vector_lenght\");\n if (cmpt == 0)\n len = 0;\n int size = (int)len;\n Vector4[] pos = mesh.material.GetVectorArray(\"vector_pos\");\n Vector4[] dir = mesh.material.GetVectorArray(\"vector_dir\");\n Vector4[] col = mesh.material.GetVectorArray(\"vector_col\");\n Vector4[] opt = mesh.material.GetVectorArray(\"vector_opt\");\n\n List<Vector4> positions = new List<Vector4>();\n List<Vector4> directions = new List<Vector4>();\n List<Vector4> colors = new List<Vector4>();\n List<Vector4> options = new List<Vector4>();\n //a voir si dans un seule array a la suite\n /*if(pos != null)\n {\n positions.AddRange(pos);\n directions.AddRange(dir);\n colors.AddRange(col);\n options.AddRange(opt);\n }*/\n\n positions.AddRange(pos);\n directions.AddRange(dir);\n colors.AddRange(col);\n options.AddRange(opt);\n\n /*positions.Add(pos_);\n directions.Add(dir_);\n colors.Add(col_);\n options.Add(opt_);*/\n\n positions[size] = pos_;\n directions[size] = dir_;\n colors[size] = col_;\n options[size] = opt_;\n\n mesh.material.SetFloat(\"vector_lenght\",size+1);\n mesh.material.SetVectorArray(\"vector_pos\",positions);\n mesh.material.SetVectorArray(\"vector_dir\", directions);\n mesh.material.SetVectorArray(\"vector_col\", colors);\n mesh.material.SetVectorArray(\"vector_opt\", options);\n\n Debug.Log(\"Toucher couler !!!!!!\");\n cmpt++;\n }\n }\n}\n" }, { "alpha_fraction": 0.6519080996513367, "alphanum_fraction": 0.6583920121192932, "avg_line_length": 27.26177978515625, "blob_id": "41230be7fbd293ae6e59f9dd19cb089fe2e745c4", "content_id": "34d32942b61b3a8da8d6146e7b82102a9285f644", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5400, "license_type": "no_license", "max_line_length": 99, "num_lines": 191, "path": "/SoA-Unity/Assets/Scripts/DebuggerBehaviour.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.UI;\nusing System;\n\npublic class DebuggerBehaviour : MonoBehaviour\n{\n //private static GameObject instance;\n\n [Header(\"Indirect Brightness Display\")]\n\n [SerializeField]\n private RawImage indirectBrightnessGreyDisplay;\n\n [SerializeField]\n private Slider indirectBrightnessGauge;\n\n [SerializeField]\n private Slider indirectBrightnessThresholdGauge;\n\n [SerializeField]\n private VisionBehaviour indirectBrightness;\n\n [SerializeField]\n private Text indirectBrightnessPercentage;\n\n [Space]\n [Header(\"Direct Brightness Display\")]\n \n [SerializeField]\n private RawImage directBrightnessGreyDisplay;\n\n [SerializeField]\n private Slider directBrightnessGauge;\n\n [SerializeField]\n private Slider directBrightnessThresholdGauge;\n\n [SerializeField]\n private VisionBehaviour directBrightness;\n\n [SerializeField]\n private Text directBrightnessPercentage;\n\n [Space]\n [Header(\"Loudness Display\")]\n\n [SerializeField]\n private Slider loudnessGauge;\n\n [SerializeField]\n private Slider loudnessThresholdGauge;\n\n [SerializeField]\n private HearingScript loudnessScript;\n\n [SerializeField]\n private Text loudnessValue;\n\n [Space]\n [Header(\"Energy Display\")]\n\n [SerializeField]\n private Slider energyBar;\n\n void Awake()\n {\n /*\n if (instance == null)\n {\n instance = gameObject;\n DontDestroyOnLoad(gameObject);\n }\n else if (gameObject != instance)\n {\n Destroy(gameObject);\n return;\n }\n */\n }\n\n // Start is called before the first frame update\n void Start()\n {\n energyBar.maxValue = 1000; // TO DO : Place in game manager\n energyBar.value = energyBar.maxValue;\n\n indirectBrightnessGauge.maxValue = 1;\n indirectBrightnessThresholdGauge.maxValue = indirectBrightnessGauge.maxValue;\n\n directBrightnessGauge.maxValue = 1;\n directBrightnessThresholdGauge.maxValue = directBrightnessGauge.maxValue;\n\n loudnessGauge.maxValue = 1;\n loudnessThresholdGauge.maxValue = loudnessGauge.maxValue;\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n \n public void DisplayBrightness(GameObject sender, Texture2D t2D, float percentage)\n {\n //Debug.Log(\"Sender : \" + sender.name);\n if (String.Equals(sender.name, indirectBrightness.name))\n {\n DisplayIndirectBrightness(t2D, percentage);\n //Debug.Log(\"Display from inside vision\");\n }\n else if (String.Equals(sender.name, directBrightness.name))\n {\n DisplayDirectBrightness(t2D, percentage);\n //Debug.Log(\"Display from outside vision\");\n }\n }\n\n public void DisplayIndirectBrightness (Texture2D t2D, float percentage) \n {\n indirectBrightnessGreyDisplay.texture = t2D;\n indirectBrightnessPercentage.text = Mathf.Round(percentage*1000)/10 + \"%\";\n\n indirectBrightnessGauge.value = percentage;\n indirectBrightnessThresholdGauge.value = indirectBrightness.BrightnessThreshold;\n\n if (percentage >= indirectBrightness.BrightnessThreshold)\n {\n indirectBrightnessGauge.fillRect.gameObject.GetComponent<Image>().color = Color.red;\n }\n else if (percentage >= indirectBrightness.BrightnessThreshold * 0.5f)\n {\n indirectBrightnessGauge.fillRect.gameObject.GetComponent<Image>().color = Color.yellow;\n }\n else\n {\n indirectBrightnessGauge.fillRect.gameObject.GetComponent<Image>().color = Color.white;\n }\n }\n\n public void DisplayDirectBrightness(Texture2D t2D, float percentage)\n {\n directBrightnessGreyDisplay.texture = t2D;\n directBrightnessPercentage.text = Mathf.Round(percentage * 1000) / 10 + \"%\";\n\n directBrightnessGauge.value = percentage;\n directBrightnessThresholdGauge.value = directBrightness.BrightnessThreshold;\n\n if (percentage >= directBrightness.BrightnessThreshold)\n {\n directBrightnessGauge.fillRect.gameObject.GetComponent<Image>().color = Color.red;\n }\n else if (percentage >= directBrightness.BrightnessThreshold * 0.5f)\n {\n directBrightnessGauge.fillRect.gameObject.GetComponent<Image>().color = Color.yellow;\n }\n else\n {\n directBrightnessGauge.fillRect.gameObject.GetComponent<Image>().color = Color.white;\n }\n }\n\n\n public void DisplayLoudness (float volume)\n {\n loudnessGauge.value = volume;\n loudnessThresholdGauge.value = loudnessScript.LoudnessThreshold;\n\n if (volume >= loudnessScript.LoudnessThreshold)\n {\n loudnessGauge.fillRect.gameObject.GetComponent<Image>().color = Color.red;\n } \n else if (volume >= loudnessScript.LoudnessThreshold * 0.5f)\n {\n loudnessGauge.fillRect.gameObject.GetComponent<Image>().color = Color.yellow;\n }\n else\n {\n loudnessGauge.fillRect.gameObject.GetComponent<Image>().color = Color.white;\n }\n\n loudnessValue.text = \"\" + volume;\n }\n\n public void DisplayEnergy (float energy)\n {\n energyBar.value = energy;\n }\n\n} // FINISH\n" }, { "alpha_fraction": 0.6352941393852234, "alphanum_fraction": 0.6429411768913269, "avg_line_length": 30.481481552124023, "blob_id": "c5ba35ad0efc9558d2facc5e7032b21f2aaa103c", "content_id": "5da33e7e1ac0cc32cabd7e451a5f912977a605df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1702, "license_type": "no_license", "max_line_length": 125, "num_lines": 54, "path": "/SoA-Unity/Assets/LevelPark/Scripts/Placements/SpawnStreetLampsSpline.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing Pixelplacement;\n\npublic class SpawnStreetLampsSpline : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The model of the street light to spawn\")]\n private GameObject streetLightPrefab;\n\n [SerializeField]\n [Tooltip(\"The number of street lamps in the spline\")]\n [Range(1,100)]\n private int splineLength = 10;\n\n [SerializeField]\n [Tooltip(\"The spline used to spawn the street lights\")]\n private Spline spline;\n\n [SerializeField]\n private Vector3 rotationFixer;\n private Quaternion qRotationFixer;\n\n // Start is called before the first frame update\n void Start()\n {\n if(streetLightPrefab == null)\n {\n throw new System.NullReferenceException(\"No prefab set for the street light\");\n }\n if(spline == null)\n {\n throw new System.NullReferenceException(\"No spline set for the street lights\");\n }\n\n for (int i = 0; i < splineLength; i++)\n {\n qRotationFixer = Quaternion.Euler(rotationFixer);\n Vector3 pos = spline.GetPosition((i + 1f) / (splineLength + 1f));\n //Quaternion rot = qRotationFixer * Quaternion.LookRotation(spline.GetDirection((i + 1f) / (splineLength + 1f)));\n Quaternion rot = qRotationFixer * Quaternion.LookRotation(transform.forward);\n GameObject streetLight = Object.Instantiate(streetLightPrefab, pos, rot);\n streetLight.transform.SetParent(transform, true);\n streetLight.name = \"StreetLamp \" + i.ToString();\n }\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n}\n" }, { "alpha_fraction": 0.6528662443161011, "alphanum_fraction": 0.6528662443161011, "avg_line_length": 21.428571701049805, "blob_id": "e64ff03b769654b179448eadacfae82986520c57", "content_id": "3522b537bc6660608a945fdab42a0b76f0edc5b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 630, "license_type": "no_license", "max_line_length": 107, "num_lines": 28, "path": "/SoA-Unity/Assets/Scripts/Debug/DebugCollision.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class DebugCollision : MonoBehaviour\n{\n // Start is called before the first frame update\n void Start()\n {\n \n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n private void OnCollisionEnter(Collision collision)\n {\n Debug.Log(string.Concat(name, \" entre en collision avec le rigidbody \", collision.rigidbody.name));\n }\n\n private void OnTriggerEnter(Collider other)\n {\n Debug.Log(string.Concat(name, \" entre en collision avec le trigger \", other.name));\n }\n}\n" }, { "alpha_fraction": 0.5735870003700256, "alphanum_fraction": 0.5737735629081726, "avg_line_length": 29.460227966308594, "blob_id": "5571fb8f0e6edc5e3d896721366c0c9c1f3903a8", "content_id": "d8eddba0def1cc6692feb95df9f6dfaf519fb01f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5364, "license_type": "no_license", "max_line_length": 138, "num_lines": 176, "path": "/SoA-Unity/Assets/Scripts/Cutscene/CutsceneManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.UI;\nusing TMPro;\nusing UnityEngine.SceneManagement;\n\nnamespace story\n{\n public class CutsceneManager : MonoBehaviour\n {\n [SerializeField]\n [Tooltip(\"Story in JSON format\")]\n private TextAsset jsonData;\n\n [SerializeField]\n [Tooltip(\"Story deserialized\")]\n private Story story;\n\n private List<Story.Scene>.Enumerator itScenes;\n private List<Story.Scene.Action>.Enumerator itActions;\n\n private GameObject transitions;\n\n [Space]\n\n // TO DO : Use dictionaries or hashmaps instead of list to find them easily\n\n [SerializeField]\n [Tooltip(\"List of the images\")]\n private Image[] images;\n\n [SerializeField]\n [Tooltip(\"List of the sounds\")]\n private AkEvent[] sounds;\n\n [Space]\n\n [SerializeField]\n [Tooltip(\"The message manager\")]\n private GameObject messagesManager;\n\n [SerializeField]\n [Tooltip(\"The images manager\")]\n private GameObject imagesManager;\n\n [SerializeField]\n [Tooltip(\"The sound manager\")]\n private GameObject soundManager;\n\n public delegate void ReadyHandler(string type, string id);\n public event ReadyHandler NewMessageEvent;\n public event ReadyHandler NewImageEvent;\n public event ReadyHandler NewSoundEvent;\n public event ReadyHandler NewSceneEvent;\n\n private Inputs inputs;\n\n // Start is called before the first frame update\n\n private void Awake()\n {\n inputs = InputsManager.Instance.Inputs;\n inputs.Player.Enable();\n }\n\n void Start()\n {\n // Transitions\n transitions = GameObject.FindGameObjectWithTag(\"Transitions\");\n transitions.GetComponent<Transitions>().FadeIn();\n\n // Callback functions\n NewMessageEvent += messagesManager.GetComponent<MessagesManager>().WriteMessage;\n NewImageEvent += imagesManager.GetComponent<ImagesManager>().ChangeImage;\n NewSoundEvent += soundManager.GetComponent<SoundManager>().PlaySound;\n NewSceneEvent += imagesManager.GetComponent<ImagesManager>().ChangeScene;\n\n messagesManager.GetComponent<MessagesManager>().MessageShownEvent += ExecuteNextAction;\n imagesManager.GetComponent<ImagesManager>().ImageShownEvent += ExecuteNextAction;\n soundManager.GetComponent<SoundManager>().SoundPlayedEvent += ExecuteNextAction;\n\n // TO DO : Runtime loading of the json file for multilanguage support (EN/FR)\n //jsonData = Resources.Load<TextAsset>(\"Cutscenes/cutscenes\");\n\n story = new Story(jsonData.text);\n itScenes = story.scenes.GetEnumerator();\n itScenes.MoveNext(); // Initialization ?\n itActions = itScenes.Current.actions.GetEnumerator();\n\n AkSoundEngine.SetState(\"Menu_Oui_Non\", \"Menu_Non\");\n\n // Start music\n AkSoundEngine.PostEvent(\"Play_Music_Cinematique\", gameObject);\n\n // Start with the first action\n ExecuteNextAction();\n }\n\n // Update is called once per frame\n void Update()\n {\n\n }\n\n public Inputs GetInputs()\n {\n return inputs;\n }\n\n public void ExecuteNextAction()\n {\n ExecuteAction(GetNextAction());\n }\n\n public Story.Scene.Action GetNextAction()\n {\n if (!itActions.MoveNext())\n {\n if (!itScenes.MoveNext())\n {\n // TO DO : Close cutscene and start game\n //SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);\n\n messagesManager.GetComponent<MessagesManager>().HideSkipButton();\n inputs.Player.Disable();\n AkSoundEngine.PostEvent(\"Stop_Music_Cinematique\", gameObject);\n\n //SceneManager.LoadScene(\"Tuto\");\n StartCoroutine(transitions.GetComponent<Transitions>().FadeOut(\"Tuto-EN\")); // Replace with Tuto-FR for french version\n\n return null;\n }\n //Debug.Log(\"Scène suivante\");\n // A fade is needed\n\n itActions = itScenes.Current.actions.GetEnumerator();\n itActions.MoveNext(); // Initialization\n }\n return itActions.Current;\n }\n\n void ExecuteAction(Story.Scene.Action action)\n {\n if (action == null) return;\n\n switch (action.type)\n {\n case \"message\":\n\n NewMessageEvent(action.metadata, action.data);\n break;\n\n case \"image\":\n\n NewImageEvent(action.metadata, action.data);\n break;\n\n case \"sound\":\n\n NewSoundEvent(action.metadata, action.data);\n break;\n\n case \"scene\":\n\n NewSceneEvent(action.metadata, action.data);\n break;\n\n default:\n\n ExecuteNextAction(); // Skip unknown actions\n break;\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.8142856955528259, "alphanum_fraction": 0.8285714387893677, "avg_line_length": 34, "blob_id": "68d5ba786ffa60e5f13e36ed4d07371aae9dc969", "content_id": "aa991fa9e43e6ef4e02ffe1c3420ccc72af56fec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 70, "license_type": "no_license", "max_line_length": 48, "num_lines": 2, "path": "/SoA-Unity/Assets/Models/Esthesia/Final/desktop.ini", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "[LocalizedFileNames]\nAvatar_Esthesia_idle.fbx=@Avatar_Esthesia_idle,0\n" }, { "alpha_fraction": 0.7040441036224365, "alphanum_fraction": 0.7084276080131531, "avg_line_length": 44.044586181640625, "blob_id": "7b40438b97ea9f201c887041b490cacadb5ece78", "content_id": "cd69514c6b5db4ba0cbe3572bb23430a22cba23f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7074, "license_type": "no_license", "max_line_length": 355, "num_lines": 157, "path": "/SoA-Unity/Assets/Scripts/InGameMenu/InGameMenuManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing TMPro;\nusing UnityEngine.UI;\nusing UnityEngine.InputSystem;\nusing UnityEngine.Rendering.PostProcessing;\nusing UnityEngine.SceneManagement;\n\npublic class InGameMenuManager : MonoBehaviour\n{\n private static GameObject singleton;\n\n private GameObject gameManager;\n\n private PostProcessVolume postProcessVolume;\n private Vignette vignette;\n\n //[SerializeField]\n //[Tooltip(\"Reference to the difficulty label\")]\n //private GameObject difficultyLabel;\n\n //[SerializeField]\n //[Tooltip(\"Reference to the difficulty slider\")]\n //private GameObject difficultySlider;\n\n [SerializeField]\n [Tooltip(\"Reference to the pause menu\")]\n private GameObject pauseMenu;\n\n [SerializeField]\n [Tooltip(\"Reference to the easy mode button\")]\n private GameObject easyModeButton;\n\n [SerializeField]\n [Tooltip(\"Reference to the medium mode button\")]\n private GameObject mediumModeButton;\n\n [SerializeField]\n [Tooltip(\"Reference to the medium mode button\")]\n private GameObject hardModeButton;\n\n [SerializeField]\n [Tooltip(\"Reference to the resume button\")]\n private GameObject resumeButton;\n\n [SerializeField]\n [Tooltip(\"Reference to the back to menu button\")]\n private GameObject backButton;\n\n // Start is called before the first frame update\n void Start()\n {\n if (singleton == null)\n {\n singleton = gameObject;\n DontDestroyOnLoad(gameObject);\n }\n else if (singleton != gameObject)\n {\n Destroy(gameObject);\n return;\n }\n\n gameManager = GameObject.FindGameObjectWithTag(\"GameManager\");\n postProcessVolume = GameObject.FindGameObjectWithTag(\"MainCamera\").GetComponent<PostProcessVolume>();\n postProcessVolume.profile.TryGetSettings(out vignette);\n\n Debug.Assert(pauseMenu != null, \"Missing pause menu reference\");\n Debug.Assert(gameManager != null, \"Missing Game Manager reference\");\n //Debug.Assert(difficultyLabel != null, \"Missing difficulty label reference\");\n //Debug.Assert(difficultySlider != null, \"Missing difficulty slider reference\");\n Debug.Assert(resumeButton != null, \"Missing resume button reference\");\n Debug.Assert(backButton != null, \"Missing quit button reference\");\n Debug.Assert(easyModeButton != null, \"Missing easy mode button reference\");\n Debug.Assert(mediumModeButton != null, \"Missing medium mode button reference\");\n Debug.Assert(hardModeButton != null, \"Missing hard mode button reference\");\n\n // Link menu visibility to the game manager\n gameManager.GetComponent<GameManager>().GamePausedEvent += DisplayPauseMenu;\n gameManager.GetComponent<GameManager>().GameResumedEvent += HidePauseMenu;\n\n // Link buttons to the game manager\n\n //difficultySlider.GetComponent<Slider>().onValueChanged.AddListener(gameManager.GetComponent<GameManager>().ChangeDifficulty);\n\n easyModeButton.GetComponent<Button>().onClick.AddListener(gameManager.GetComponent<GameManager>().ChangeToEasy);\n mediumModeButton.GetComponent<Button>().onClick.AddListener(gameManager.GetComponent<GameManager>().ChangeToMedium);\n hardModeButton.GetComponent<Button>().onClick.AddListener(gameManager.GetComponent<GameManager>().ChangeToHard);\n\n resumeButton.GetComponent<Button>().onClick.AddListener(gameManager.GetComponent<GameManager>().ResumeGame);\n backButton.GetComponent<Button>().onClick.AddListener(gameManager.GetComponent<GameManager>().GoToTitle);\n\n // when update from the game manager, change the slider without notifying events, or else we would go into an infinite loop\n\n //gameManager.GetComponent<GameManager>().EasyDifficultyEvent += () => { difficultyLabel.GetComponent<TextMeshProUGUI>().SetText(\"Easy\"); difficultyLabel.GetComponent<TextMeshProUGUI>().color = new Color(0, 0, 1); difficultySlider.GetComponent<Slider>().SetValueWithoutNotify(1); };\n //gameManager.GetComponent<GameManager>().MediumDifficultyEvent += () => { difficultyLabel.GetComponent<TextMeshProUGUI>().SetText(\"Medium\"); difficultyLabel.GetComponent<TextMeshProUGUI>().color = new Color(0, 1, 0); difficultySlider.GetComponent<Slider>().SetValueWithoutNotify(2); };\n //gameManager.GetComponent<GameManager>().HardDifficultyEvent += () => { difficultyLabel.GetComponent<TextMeshProUGUI>().SetText(\"Hard\"); difficultyLabel.GetComponent<TextMeshProUGUI>().color = new Color(1, 0, 0); difficultySlider.GetComponent<Slider>().SetValueWithoutNotify(3); };\n //gameManager.GetComponent<GameManager>().OneshotDifficultyEvent += () => { difficultyLabel.GetComponent<TextMeshProUGUI>().SetText(\"One Shot\"); difficultyLabel.GetComponent<TextMeshProUGUI>().color = new Color(128 / 255f, 0 / 255f, 0 / 255f); difficultySlider.GetComponent<Slider>().SetValueWithoutNotify(3); }; // shouldn't happen in normal game\n\n gameManager.GetComponent<GameManager>().EasyDifficultyEvent += UpdateDifficultySprites;\n gameManager.GetComponent<GameManager>().MediumDifficultyEvent += UpdateDifficultySprites;\n gameManager.GetComponent<GameManager>().HardDifficultyEvent += UpdateDifficultySprites;\n gameManager.GetComponent<GameManager>().OneshotDifficultyEvent += UpdateDifficultySprites;\n\n HidePauseMenu();\n }\n\n private void UpdateDifficultySprites()\n {\n easyModeButton.GetComponent<Image>().sprite = Resources.Load<Sprite>(\"Textures\\\\UI\\\\difficulty-1\" + (gameManager.GetComponent<GameManager>().GetDifficulty() == DIFFICULTY.EASY ? \"-selected\" : \"\" ));\n mediumModeButton.GetComponent<Image>().sprite = Resources.Load<Sprite>(\"Textures\\\\UI\\\\difficulty-2\" + (gameManager.GetComponent<GameManager>().GetDifficulty() == DIFFICULTY.MEDIUM ? \"-selected\" : \"\"));\n hardModeButton.GetComponent<Image>().sprite = Resources.Load<Sprite>(\"Textures\\\\UI\\\\difficulty-3\" + (gameManager.GetComponent<GameManager>().GetDifficulty() == DIFFICULTY.HARD ? \"-selected\" : \"\"));\n }\n\n // Update is called once per frame\n void Update()\n {\n\n }\n\n private void DisplayPauseMenu()\n {\n pauseMenu.SetActive(true);\n vignette.active = true;\n }\n\n private void HidePauseMenu()\n {\n pauseMenu.SetActive(false);\n vignette.active = false;\n }\n\n public void DestroySingleton()\n {\n singleton = null;\n }\n\n private void OnEnable()\n {\n SceneManager.sceneLoaded += OnSceneLoaded;\n }\n\n public void OnDestroy()\n {\n SceneManager.sceneLoaded -= OnSceneLoaded;\n }\n\n void OnSceneLoaded(Scene scene, LoadSceneMode mode)\n {\n if (scene.name == \"GameElise\" || scene.name == \"Game\" || scene.name == \"CutZonesScene\" || scene.name == \"GameNight\")\n {\n // Reload references of the compass\n GameObject.FindGameObjectWithTag(\"Compass\").transform.GetChild(0).GetComponent<CompassBehavior>().ReloadReferences();\n }\n }\n}\n" }, { "alpha_fraction": 0.6509078741073608, "alphanum_fraction": 0.6562630534172058, "avg_line_length": 35.547401428222656, "blob_id": "8b3cf37d289ebf016a43fa0bc5e395d575d59ba4", "content_id": "071492e3e3739b4f3f0eac10f96d387353f35d7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 11953, "license_type": "no_license", "max_line_length": 128, "num_lines": 327, "path": "/SoA-Unity/Assets/Scripts/Menus/ControlsManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.InputSystem;\nusing UnityEngine.UI;\nusing System.Linq;\nusing UnityEngine.EventSystems;\nusing System;\n\npublic class ControlsManager : MonoBehaviour\n{\n Inputs inputs;\n\n private GameObject menuManager;\n\n [SerializeField]\n [Tooltip(\"The button to select the mouse-keyboard controls\")]\n private GameObject mouseKeyboardButton;\n\n [SerializeField]\n [Tooltip(\"The button to select the gamepad controls\")]\n private GameObject gamepadButton;\n\n [SerializeField]\n [Tooltip(\"The button to rebind the move up action to another key\")]\n private GameObject moveUpButton;\n\n [SerializeField]\n [Tooltip(\"The button to rebind the move left action to another key\")]\n private GameObject moveLeftButton;\n\n [SerializeField]\n [Tooltip(\"The button to rebind the move down action to another key\")]\n private GameObject moveDownButton;\n\n [SerializeField]\n [Tooltip(\"The button to rebind the move right action to another key\")]\n private GameObject moveRightButton;\n\n [SerializeField]\n [Tooltip(\"The button to rebind the interact action to another key\")]\n private GameObject interactButton;\n\n [SerializeField]\n [Tooltip(\"The button to rebind the eye protect action to another key\")]\n private GameObject eyeProtectButton;\n\n [SerializeField]\n [Tooltip(\"The button to rebind the ear protect action to another key\")]\n private GameObject earProtectButton;\n\n [SerializeField]\n [Tooltip(\"The button to restore the default bindings\")]\n private GameObject restoreBindingsButton;\n\n [SerializeField]\n [Tooltip(\"The button to save the current bindings\")]\n private GameObject saveBindingsButton;\n\n // Rebinding\n\n private InputActionRebindingExtensions.RebindingOperation rebindOperation;\n\n private List<string> reservedPaths;\n\n // US-Layout\n private Dictionary<string, string> defaultPaths = new Dictionary<string, string> {\n { \"forward\", \"<Keyboard>/w\" },\n { \"turnleft\", \"<Keyboard>/a\" },\n { \"turnback\", \"<Keyboard>/s\" },\n { \"turnright\", \"<Keyboard>/d\" },\n { \"interact\", \"<Keyboard>/e\" },\n { \"protecteyes\", \"<Mouse>/leftButton\" },\n { \"protectears\", \"<Mouse>/rightButton\" }\n };\n\n // Navigation\n\n private Navigation navigationOff = new Navigation();\n private Navigation navigationAuto = new Navigation();\n\n private Color reactivatedColor = new Color(1, 1, 1);\n private Color deactivatedColor = new Color(0.1f, 0.1f, 0.1f);\n\n // Start is called before the first frame update\n void Awake()\n {\n inputs = InputsManager.Instance.Inputs;\n\n menuManager = GameObject.FindGameObjectWithTag(\"MenuManager\");\n\n navigationOff.mode = Navigation.Mode.None;\n navigationAuto.mode = Navigation.Mode.Automatic;\n\n if (PlayerPrefs.HasKey(\"controls\") && PlayerPrefs.GetString(\"controls\").Equals(\"gamepad\"))\n {\n UseGamepadControls();\n }\n else\n {\n UseMouseKeyboardControls();\n }\n\n InitBindings();\n\n reservedPaths = new List<string> {\n \"<Keyboard>/AnyKey\",\n \"<Keyboard>/Alt\",\n \"<Keyboard>/LeftAlt\",\n \"<Keyboard>/PrintScreen\",\n \"<Pointer>/Press\",\n inputs.Player.Interact.bindings[0].path,\n inputs.Player.ProtectEyes.bindings[0].path,\n inputs.Player.ProtectEars.bindings[0].path,\n inputs.Player.Walk.bindings[1].path,\n inputs.Player.Walk.bindings[2].path,\n inputs.Player.Walk.bindings[3].path,\n inputs.Player.Walk.bindings[4].path\n };\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n /* Controller type */\n\n public void SelectGamepadControls()\n {\n PlayNewKeySound();\n\n UseGamepadControls();\n }\n\n public void UseGamepadControls()\n {\n inputs.bindingMask = InputBinding.MaskByGroup(inputs.GamepadScheme.bindingGroup);\n\n DeactivateButton(gamepadButton);\n ReactivateButton(mouseKeyboardButton);\n menuManager.GetComponent<MenuManager>().SwitchToGamepadControls();\n\n PlayerPrefs.SetString(\"controls\", \"gamepad\");\n }\n\n public void SelectMouseKeyboardControls()\n {\n PlayNewKeySound();\n\n UseMouseKeyboardControls();\n }\n\n public void UseMouseKeyboardControls()\n {\n inputs.bindingMask = InputBinding.MaskByGroup(inputs.MouseKeyboardScheme.bindingGroup);\n\n DeactivateButton(mouseKeyboardButton);\n ReactivateButton(gamepadButton);\n menuManager.GetComponent<MenuManager>().SwitchToMouseKeyboardControls();\n\n PlayerPrefs.SetString(\"controls\", \"mousekeyboard\");\n }\n\n private void ReactivateButton(GameObject button)\n {\n button.transform.GetChild(0).GetComponent<Text>().color = reactivatedColor;\n button.GetComponent<Button>().interactable = true;\n button.GetComponent<EventTrigger>().enabled = true;\n }\n\n private void DeactivateButton(GameObject button)\n {\n button.transform.GetChild(0).GetComponent<Text>().color = deactivatedColor;\n button.GetComponent<Button>().interactable = false;\n button.GetComponent<EventTrigger>().enabled = false;\n }\n\n /* Key bindings */\n\n public void RebindMoveUp() { RebindAction(inputs.Player.Walk, moveUpButton, 1); }\n\n public void RebindMoveLeft() { RebindAction(inputs.Player.Walk, moveLeftButton, 2); }\n\n public void RebindMoveDown() { RebindAction(inputs.Player.Walk, moveDownButton, 3); }\n\n public void RebindMoveRight() { RebindAction(inputs.Player.Walk, moveRightButton, 4); }\n\n public void RebindInteract() { RebindAction(inputs.Player.Interact, interactButton, 0); }\n\n public void RebindEyeProtect() { RebindAction(inputs.Player.ProtectEyes, eyeProtectButton, 0); }\n\n public void RebindEarsProtect() { RebindAction(inputs.Player.ProtectEars, earProtectButton, 0); }\n\n private void RebindAction(InputAction action, GameObject button, int index)\n {\n PlayRemoveKeySound();\n\n if (rebindOperation != null && !rebindOperation.completed)\n {\n rebindOperation.Cancel(); // in case of two successive clicks without key press\n }\n\n // Disable click and submit on the button\n button.GetComponent<EventTrigger>().enabled = false;\n\n // Disable navigation on the button\n button.GetComponent<Button>().navigation = navigationOff;\n\n button.transform.GetChild(0).GetComponent<Text>().text = \"...\";\n\n action.Disable();\n\n Action<InputActionRebindingExtensions.RebindingOperation> callback = context =>\n {\n action.Enable();\n rebindOperation.Dispose();\n button.transform.GetChild(0).GetComponent<Text>().text = action.GetBindingDisplayString(index);\n reservedPaths.Add(action.bindings[index].overridePath);\n button.GetComponent<EventTrigger>().enabled = true;\n button.GetComponent<Button>().navigation = navigationAuto;\n PlayNewKeySound();\n };\n\n rebindOperation = action.PerformInteractiveRebinding()\n .OnComplete(callback)\n .OnCancel(callback)\n .WithControlsHavingToMatchPath(\"<Keyboard>\")\n .WithControlsHavingToMatchPath(\"<Mouse>\")\n .WithCancelingThrough(\"<Keyboard>/escape\")\n // next two lines compulsory for a composite binding\n .WithTargetBinding(index)\n .WithExpectedControlType(\"Button\")\n //.Start()\n ;\n\n // forbid utilization of a key already in use\n reservedPaths.Remove(action.bindings[index].overridePath);\n foreach (var path in reservedPaths)\n {\n //Debug.Log(path);\n rebindOperation.WithControlsExcluding(path);\n }\n\n rebindOperation.Start();\n }\n\n private void InitBindings()\n {\n if (PlayerPrefs.HasKey(\"forward\"))\n {\n inputs.Player.Walk.ApplyBindingOverride(1, PlayerPrefs.GetString(\"forward\"));\n inputs.Player.Walk.ApplyBindingOverride(2, PlayerPrefs.GetString(\"turnleft\"));\n inputs.Player.Walk.ApplyBindingOverride(3, PlayerPrefs.GetString(\"turnback\"));\n inputs.Player.Walk.ApplyBindingOverride(4, PlayerPrefs.GetString(\"turnright\"));\n inputs.Player.Interact.ApplyBindingOverride(0, PlayerPrefs.GetString(\"interact\"));\n inputs.Player.ProtectEyes.ApplyBindingOverride(0, PlayerPrefs.GetString(\"protecteyes\"));\n inputs.Player.ProtectEars.ApplyBindingOverride(0, PlayerPrefs.GetString(\"protectears\"));\n }\n else\n {\n ResetBindings();\n }\n\n UpdateLabels();\n }\n\n public void ResetBindings()\n {\n PlayRemoveKeySound();\n\n inputs.Player.Walk.ApplyBindingOverride(1, defaultPaths[\"forward\"]);\n inputs.Player.Walk.ApplyBindingOverride(2, defaultPaths[\"turnleft\"]);\n inputs.Player.Walk.ApplyBindingOverride(3, defaultPaths[\"turnback\"]);\n inputs.Player.Walk.ApplyBindingOverride(4, defaultPaths[\"turnright\"]);\n inputs.Player.Interact.ApplyBindingOverride(0, defaultPaths[\"interact\"]);\n inputs.Player.ProtectEyes.ApplyBindingOverride(0, defaultPaths[\"protecteyes\"]);\n inputs.Player.ProtectEars.ApplyBindingOverride(0, defaultPaths[\"protectears\"]);\n\n UpdateLabels();\n }\n\n public void SaveBindings()\n {\n PlayNewKeySound();\n\n PlayerPrefs.SetString(\"forward\", inputs.Player.Walk.bindings[1].overridePath);\n PlayerPrefs.SetString(\"turnleft\", inputs.Player.Walk.bindings[2].overridePath);\n PlayerPrefs.SetString(\"turnback\", inputs.Player.Walk.bindings[3].overridePath);\n PlayerPrefs.SetString(\"turnright\", inputs.Player.Walk.bindings[4].overridePath);\n PlayerPrefs.SetString(\"interact\", inputs.Player.Interact.bindings[0].overridePath);\n PlayerPrefs.SetString(\"protecteyes\", inputs.Player.ProtectEyes.bindings[0].overridePath);\n PlayerPrefs.SetString(\"protectears\", inputs.Player.ProtectEars.bindings[0].overridePath);\n }\n\n private void UpdateLabels()\n {\n moveUpButton.transform.GetChild(0).GetComponent<Text>().text = inputs.Player.Walk.GetBindingDisplayString(1);\n moveLeftButton.transform.GetChild(0).GetComponent<Text>().text = inputs.Player.Walk.GetBindingDisplayString(2);\n moveDownButton.transform.GetChild(0).GetComponent<Text>().text = inputs.Player.Walk.GetBindingDisplayString(3);\n moveRightButton.transform.GetChild(0).GetComponent<Text>().text = inputs.Player.Walk.GetBindingDisplayString(4);\n interactButton.transform.GetChild(0).GetComponent<Text>().text = inputs.Player.Interact.GetBindingDisplayString(0);\n eyeProtectButton.transform.GetChild(0).GetComponent<Text>().text = inputs.Player.ProtectEyes.GetBindingDisplayString(0);\n earProtectButton.transform.GetChild(0).GetComponent<Text>().text = inputs.Player.ProtectEars.GetBindingDisplayString(0);\n\n restoreBindingsButton.transform.GetChild(0).GetComponent<Text>().text = \"Reset Keys\";\n saveBindingsButton.transform.GetChild(0).GetComponent<Text>().text = \"Save Keys\";\n }\n\n /* Wwise functions */\n\n private void PlayRemoveKeySound()\n {\n AkSoundEngine.PostEvent(\"Play_Clavier_Suppression\", gameObject);\n }\n\n private void PlayNewKeySound()\n {\n AkSoundEngine.PostEvent(\"Play_Clavier_Assignation\", gameObject);\n }\n\n private void OnEnable()\n {\n inputs.Player.Enable();\n }\n}\n" }, { "alpha_fraction": 0.6679058074951172, "alphanum_fraction": 0.6679058074951172, "avg_line_length": 22.05714225769043, "blob_id": "3edcce22562152e8d97ccff5119e4722c7a143c8", "content_id": "aee7ac366942686ce0306e92146b4b856cb73588", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 809, "license_type": "no_license", "max_line_length": 81, "num_lines": 35, "path": "/SoA-Unity/Assets/Scripts/Credits/CreditsManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\n\npublic class CreditsManager : MonoBehaviour\n{\n private GameObject transitions;\n\n // Start is called before the first frame update\n void Start()\n {\n // Transitions\n transitions = GameObject.FindGameObjectWithTag(\"Transitions\");\n transitions.GetComponent<Transitions>().FadeIn();\n\n AkSoundEngine.PostEvent(\"Play_Music_Menu\", gameObject);\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n public void GoToTitle()\n {\n StartCoroutine(transitions.GetComponent<Transitions>().FadeOut(\"Title\"));\n }\n\n public void OnDestroy()\n {\n AkSoundEngine.PostEvent(\"Stop_Music_Menu\", gameObject);\n }\n}\n" }, { "alpha_fraction": 0.6089193820953369, "alphanum_fraction": 0.6114922761917114, "avg_line_length": 26.761905670166016, "blob_id": "e2502ec3496bc502827f7c4358cbb6e68e515117", "content_id": "426984b3dcb57dd60172b3fcabaedcbcd09cecea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2334, "license_type": "no_license", "max_line_length": 206, "num_lines": 84, "path": "/SoA-Unity/Assets/Scripts/Analytics/PositionTracker.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing System.Linq;\nusing Pixelplacement.TweenSystem;\nusing System.IO;\nusing System;\nusing System.Text.RegularExpressions;\n\npublic class PositionTracker : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"Reference to the player\")]\n private GameObject player;\n\n [SerializeField]\n [Tooltip(\"The object to track\")]\n private GameObject trackedObject;\n\n [SerializeField]\n [Tooltip(\"The refreshing frequency in Hz\")]\n private float frequency = 2;\n\n struct Data { public float t; public Vector2 position; }\n List<Data> positionData;\n\n // Start is called before the first frame update\n void Start()\n {\n positionData = new List<Data>();\n player.GetComponent<EnergyBehaviour>().OutOfEnergyEvent += SaveRun;\n StartCoroutine(\"TrackPosition\");\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n IEnumerator TrackPosition()\n {\n for (; ; )\n {\n Data data = new Data();\n\n data.t = Time.time;\n data.position = new Vector2(transform.position.x, transform.position.z);\n positionData.Add(data);\n\n yield return new WaitForSeconds(1f / frequency);\n }\n }\n\n string CheckForFilename(string name, int number, string extension)\n {\n if (File.Exists(name + number + extension))\n {\n return CheckForFilename(name, number + 1, extension);\n }\n else\n {\n return name + number.ToString() + extension;\n }\n }\n\n public void SaveRun()\n {\n string name = Application.dataPath + \"/AnalyticsData/run\";\n int number = 0;\n string extension = \".csv\";\n string filename = CheckForFilename(name, number, extension);\n StreamWriter streamWriter = new StreamWriter(filename, false);\n Regex regex = new Regex(\",\");\n foreach ( Data data in positionData)\n {\n streamWriter.WriteLine(regex.Replace(data.t.ToString(), \".\") + \",\" + regex.Replace(data.position.x.ToString(), \".\") + \",\" + regex.Replace(data.position.y.ToString(), \".\"), Environment.NewLine );\n // streamWriter.NewLine(;\n }\n streamWriter.Close();\n Debug.Log(\"File written\");\n }\n\n} // FINISH\n" }, { "alpha_fraction": 0.5481468439102173, "alphanum_fraction": 0.554728090763092, "avg_line_length": 23.88793182373047, "blob_id": "3dc9a3e3c482f2328dcbc81e7fc3ba9d7d65daa8", "content_id": "cbc52685746000ace23332e08f0a3ebd711aa8a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5776, "license_type": "no_license", "max_line_length": 102, "num_lines": 232, "path": "/SoA-Unity/Assets/Scripts/Cutscene/ImagesManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using story;\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.InputSystem;\nusing UnityEngine.UI;\n\npublic class ImagesManager : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The cutscene manager\")]\n private GameObject cutsceneManager;\n\n [Space]\n [Header(\"Positions\")]\n\n [SerializeField]\n private GameObject background;\n\n [SerializeField]\n private GameObject right;\n\n [SerializeField]\n private GameObject left;\n\n public delegate void ImageHandler();\n public event ImageHandler ImageShownEvent;\n\n [Space]\n [Header(\"Image Animation Options\")]\n\n [SerializeField]\n [Tooltip(\"The duration for one image to appear\")]\n [Range(0.1f,4f)]\n private float fadeDuration = 3f;\n\n private Inputs inputs;\n\n bool next = false;\n\n // Start is called before the first frame update\n void Awake()\n {\n inputs = cutsceneManager.GetComponent<CutsceneManager>().GetInputs();\n Debug.Assert(inputs != null, \"Inputs not instantiated\");\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n public void ChangeImage(string position, string id)\n {\n StartCoroutine(ReplaceImage(position, id));\n }\n\n public void ChangeScene(string position, string id)\n {\n StartCoroutine(FadeImage(position, id));\n }\n\n private IEnumerator ReplaceImage(string position, string id)\n {\n next = false;\n\n Image image = null;\n\n switch (position)\n {\n case \"background\":\n case \"background-stop\":\n image = background.GetComponent<Image>();\n break;\n\n case \"left\":\n image = left.GetComponent<Image>();\n break;\n\n case \"right\":\n image = right.GetComponent<Image>();\n break;\n }\n\n Sprite sprite = Resources.Load<Sprite>(string.Concat(\"Cutscene\\\\Images\\\\\", id));\n if (sprite == null)\n {\n throw new InvalidResourceException(id, \"Cutscene\\\\Images\\\\\");\n }\n image.sprite = sprite;\n image.preserveAspect = true;\n\n if (position == \"background-stop\")\n {\n inputs.Player.SkipDialog.performed += NextEvent;\n\n while (!next)\n {\n yield return new WaitForEndOfFrame();\n }\n }\n\n ImageShownEvent();\n }\n\n private IEnumerator FadeImage(string position, string id)\n {\n next = false;\n\n Image image = null;\n\n switch (position)\n {\n case \"background\":\n case \"background-stop\":\n image = background.GetComponent<Image>();\n break;\n\n case \"left\":\n image = left.GetComponent<Image>();\n break;\n\n case \"right\":\n image = right.GetComponent<Image>();\n break;\n }\n\n Color color;\n color = image.color;\n color.a = 1;\n image.color = color;\n\n //float fadeDuration = 5; // in seconds\n float timeStep = 0.1f; // in seconds\n\n float halfwayPauseDuration = 0.1f;\n\n float halfDuration = fadeDuration / 2f - halfwayPauseDuration;\n\n float fadeStep = timeStep / halfDuration;\n\n while (image.color.a != 0)\n {\n color = image.color;\n color.a = Mathf.Clamp(image.color.a - fadeStep, 0, 1);\n image.color = color;\n\n yield return new WaitForSeconds(timeStep);\n }\n\n // For test\n // image.color = new Color(0, 1, 0.5f, 0);\n\n //TO DO : Load the actual sprite\n\n Sprite sprite = Resources.Load<Sprite>(string.Concat(\"Cutscene\\\\Images\\\\\", id));\n if(sprite == null)\n {\n throw new InvalidResourceException(id, \"Cutscene\\\\Images\\\\\");\n }\n image.sprite = sprite;\n image.preserveAspect = true;\n\n yield return new WaitForSeconds(halfwayPauseDuration);\n\n while (image.color.a != 1)\n {\n color = image.color;\n color.a = Mathf.Clamp(image.color.a + fadeStep, 0, 1);\n image.color = color;\n\n yield return new WaitForSeconds(timeStep);\n }\n\n if (position == \"background-stop\")\n {\n inputs.Player.SkipDialog.performed += NextEvent;\n\n while (!next)\n {\n yield return new WaitForEndOfFrame();\n }\n }\n\n ImageShownEvent();\n }\n\n private void NextEvent(InputAction.CallbackContext ctx)\n {\n AkSoundEngine.PostEvent(\"Play_Touche_Next\", gameObject);\n\n inputs.Player.SkipDialog.performed -= NextEvent;\n\n next = true;\n }\n\n /*\n private IEnumerator CrossFade(string id)\n {\n Image fadeIn = (background == background1 ? background2 : background1).GetComponent<Image>(),\n fadeOut = (background == background1 ? background1 : background2).GetComponent<Image>();\n Color color;\n color = fadeIn.color;\n color.a = 0;\n fadeIn.color = color;\n color = fadeOut.color;\n color.a = 1;\n fadeOut.color = color;\n\n //float fadeDuration = 5; // in seconds\n float timeStep = 0.1f; // in seconds\n\n float fadeStep = timeStep / fadeDuration;\n\n while(fadeIn.color.a != 1)\n {\n color = fadeIn.color;\n color.a = Mathf.Clamp(fadeIn.color.a + fadeStep, 0, 1);\n fadeIn.color = color;\n\n color = fadeOut.color;\n color.a = Mathf.Clamp(fadeOut.color.a - fadeStep, 0, 1);\n fadeOut.color = color;\n\n yield return new WaitForSeconds(timeStep);\n }\n\n ImageShownEvent();\n }\n */\n}\n" }, { "alpha_fraction": 0.6258334517478943, "alphanum_fraction": 0.6294940710067749, "avg_line_length": 30.220407485961914, "blob_id": "67b0e06086f73f9396545fa72cefab95e67de8bc", "content_id": "87f713d21a7345e45880e6781dc657353542d910", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 15307, "license_type": "no_license", "max_line_length": 204, "num_lines": 490, "path": "/SoA-Unity/Assets/Scripts/Managers/GameManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.Analytics;\nusing UnityEngine.SceneManagement;\nusing AK.Wwise;\nusing UnityEngine.UI;\nusing UnityEngine.InputSystem;\n\npublic enum DIFFICULTY { EASY, MEDIUM, HARD, ONESHOT };\n\npublic class GameManager : MonoBehaviour\n{\n private static GameObject singleton;\n\n private Inputs inputs;\n\n [Header(\"Transitions\")]\n\n [SerializeField]\n [Tooltip(\"The animator to transition\")]\n private GameObject sceneTransition;\n\n //private Animator nightTransition;\n //private Animator creditsTransition;\n\n private GameObject transitions;\n\n [SerializeField]\n [Tooltip(\"Duration of the transitions to credits in seconds\")]\n [Range(1, 5)]\n private float transitionDuration = 3;\n\n [SerializeField]\n [Tooltip(\"Duration of the fade to restart in seconds\")]\n [Range(2, 10)]\n private float restartFadeDuration = 5;\n\n private Image fade;\n private Image gameOverLogo;\n private Text gameOverMessage;\n\n private GameObject brightness;\n private GameObject loudness;\n private GameObject crowd;\n\n private bool isGameOver;\n public bool IsGameOver { get { return isGameOver; } }\n\n //private Camera mainCamera;\n //private Camera transitionCamera;\n\n bool firstRun;\n\n [Space]\n [Header(\"Options\")]\n\n [SerializeField]\n [Tooltip(\"Default difficulty level\")]\n private DIFFICULTY difficulty = DIFFICULTY.MEDIUM;\n\n //Dictionary<DIFFICULTY, float> brightnessDamages = new Dictionary<DIFFICULTY, float> { { DIFFICULTY.MEDIUM, 10f }, { DIFFICULTY.EASY, 5f }, { DIFFICULTY.HARD, 20f }, { DIFFICULTY.ONESHOT, 1000f } };\n Dictionary<DIFFICULTY, float> brightnessDamages = new Dictionary<DIFFICULTY, float> { { DIFFICULTY.MEDIUM, 50f }, { DIFFICULTY.EASY, 10f }, { DIFFICULTY.HARD, 100f }, { DIFFICULTY.ONESHOT, 1000f } };\n Dictionary<DIFFICULTY, float> loudnessDamages = new Dictionary<DIFFICULTY, float> { { DIFFICULTY.MEDIUM, 50f }, { DIFFICULTY.EASY, 10f }, { DIFFICULTY.HARD, 100f }, { DIFFICULTY.ONESHOT, 1000f } };\n Dictionary<DIFFICULTY, float> crowdDamages = new Dictionary<DIFFICULTY, float> { { DIFFICULTY.MEDIUM, 10f }, { DIFFICULTY.EASY, 5f }, { DIFFICULTY.HARD, 20f }, { DIFFICULTY.ONESHOT, 1000f } };\n \n public delegate void GamePausedHandler();\n public event GamePausedHandler GamePausedEvent;\n public event GamePausedHandler GameResumedEvent;\n\n public delegate void DifficultyChangedHandler();\n public event DifficultyChangedHandler EasyDifficultyEvent;\n public event DifficultyChangedHandler MediumDifficultyEvent;\n public event DifficultyChangedHandler HardDifficultyEvent;\n public event DifficultyChangedHandler OneshotDifficultyEvent;\n\n private void Awake()\n {\n // Transitions\n transitions = GameObject.FindGameObjectWithTag(\"Transitions\");\n transitions.GetComponent<Transitions>().FadeIn();\n\n firstRun = true;\n isGameOver = false;\n\n if (singleton == null)\n {\n singleton = gameObject;\n DontDestroyOnLoad(gameObject);\n }\n else if (singleton != gameObject)\n {\n Destroy(gameObject);\n return;\n }\n\n Debug.Log(\"A NEW GAME MANAGER IS LOADED ! YEAH !\");\n\n inputs = InputsManager.Instance.Inputs;\n\n inputs.Player.Quit.performed += PauseGame;\n\n fade = GameObject.FindGameObjectWithTag(\"Fade\").GetComponent<Image>();\n gameOverLogo = GameObject.FindGameObjectWithTag(\"GameOver\").GetComponent<Image>();\n gameOverMessage = GameObject.FindGameObjectWithTag(\"GameOverMessage\").GetComponent<Text>();\n\n brightness = GameObject.FindGameObjectWithTag(\"Brightness\");\n loudness = GameObject.FindGameObjectWithTag(\"Loudness\");\n crowd = GameObject.FindGameObjectWithTag(\"Crowd\");\n\n Debug.Assert(brightness != null, \"Missing vision reference\");\n Debug.Assert(loudness != null, \"Missing hearing reference\");\n Debug.Assert(crowd != null, \"Missing crowd reference\");\n if(SceneManager.GetActiveScene().name == \"GameNight\")\n Debug.Assert(brightness.GetComponent<VisionBehaviour>() != null, \"Incorrect vision reference\");\n Debug.Assert(loudness.GetComponent<HearingScript>() != null, \"Incorrect hearing reference\");\n Debug.Assert(crowd.GetComponent<FieldOfView>() != null, \"Incorrect crowd reference\");\n\n //mainCamera = GameObject.FindGameObjectWithTag(\"MainCamera\").GetComponent<Camera>();\n //transitionCamera = GameObject.FindGameObjectWithTag(\"TransitionCamera\").GetComponent<Camera>();\n\n if (fade == null)\n {\n throw new System.ArgumentException(\"No fade found in the UI\");\n }\n }\n\n private void OnEnable()\n {\n SceneManager.sceneLoaded += OnSceneLoaded;\n }\n\n // Start is called before the first frame update\n void Start()\n {\n AkSoundEngine.SetState(\"Menu_Oui_Non\", \"Menu_Non\");\n\n\n if (SceneManager.GetActiveScene().name == \"GameElise\")\n {\n sceneTransition.GetComponent<Animator>().runtimeAnimatorController = Resources.Load<RuntimeAnimatorController>(\"Animators\\\\NightTransition\");\n }\n\n if(SceneManager.GetActiveScene().name == \"GameNight\")\n {\n sceneTransition.GetComponent<Animator>().runtimeAnimatorController = Resources.Load<RuntimeAnimatorController>(\"Animators\\\\CreditsTransition\");\n }\n\n sceneTransition.GetComponent<Animator>().SetBool(\"HasWon\", false);\n sceneTransition.GetComponent<Animator>().SetBool(\"CreditsLoaded\", false);\n\n //nightTransition.SetBool(\"HasWon\", false);\n //nightTransition.SetBool(\"CreditsLoaded\", false);\n\n ChangeDifficulty(difficulty);\n\n /*\n if (stopAllEvent == null)\n {\n throw new System.NullReferenceException(\"No reference to the wwise stop all sounds event on the game manager\");\n }*/\n Analytics.enabled = false;\n\n //DontDestroyOnLoad(gameObject);\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n /* Pause functions */\n\n private void PauseGame(InputAction.CallbackContext ctx)\n {\n Time.timeScale = 0;\n AkSoundEngine.Suspend();\n\n // Switch pause key callback\n inputs.Player.Quit.performed -= PauseGame;\n inputs.Player.Quit.performed += ResumeGame;\n\n // To avoid triggering the click action\n inputs.Player.Disable();\n inputs.Player.Quit.Enable();\n\n // Display menu\n GamePausedEvent();\n }\n\n public void ResumeGame()\n {\n Time.timeScale = 1;\n AkSoundEngine.WakeupFromSuspend();\n\n // Switch pause key callback\n inputs.Player.Quit.performed -= ResumeGame;\n inputs.Player.Quit.performed += PauseGame;\n\n inputs.Player.Enable();\n\n // Hide menu\n GameResumedEvent();\n }\n public void ResumeGame(InputAction.CallbackContext ctx)\n {\n ResumeGame();\n }\n\n /* Interface for slider */\n\n public void ChangeDifficulty(float value)\n {\n //Debug.Log(\"Difficulty changed from slider !\");\n\n Debug.Assert(value >= 1 && value <= 3, \"Unknown difficulty level : \" + value);\n difficulty = (DIFFICULTY)((int)value - 1);\n ChangeDifficulty(difficulty);\n }\n\n /* Interface for buttons */\n\n public void ChangeToEasy()\n {\n difficulty = DIFFICULTY.EASY;\n ChangeDifficulty(difficulty);\n }\n\n public void ChangeToMedium()\n {\n difficulty = DIFFICULTY.MEDIUM;\n ChangeDifficulty(difficulty);\n }\n\n public void ChangeToHard()\n {\n difficulty = DIFFICULTY.HARD;\n ChangeDifficulty(difficulty);\n }\n\n public void ChangeDifficulty(DIFFICULTY difficulty)\n {\n brightness.GetComponent<VisionBehaviour>().SetBrightnessDamage(brightnessDamages[difficulty]);\n loudness.GetComponent<HearingScript>().SetLoudnessDamage(loudnessDamages[difficulty]);\n crowd.GetComponent<FieldOfView>().SetCrowdDamage(crowdDamages[difficulty]);\n\n switch (difficulty)\n {\n case DIFFICULTY.EASY:\n EasyDifficultyEvent();\n break;\n case DIFFICULTY.MEDIUM:\n MediumDifficultyEvent();\n break;\n case DIFFICULTY.HARD:\n HardDifficultyEvent();\n break;\n case DIFFICULTY.ONESHOT:\n OneshotDifficultyEvent();\n break;\n default:\n throw new System.IndexOutOfRangeException(\"Unknown difficulty level : \" + difficulty);\n }\n }\n\n public DIFFICULTY GetDifficulty()\n {\n return difficulty;\n }\n\n public void QuitGame() // Unused\n {\n // TO DO : Add warning message\n Application.Quit();\n }\n\n public void GoToTitle()\n {\n GoToScene(\"Title\");\n }\n\n public void GoToCredits()\n {\n GoToScene(\"CreditsScene\");\n }\n\n public void GoToScene(string sceneName)\n {\n // FIX ????\n firstRun = true;\n isGameOver = false;\n\n singleton = null;\n SceneManager.sceneLoaded -= OnSceneLoaded;\n\n // Destroy singletons\n GameObject.FindGameObjectWithTag(\"SaveManager\").GetComponent<SaveManager>().DestroySingleton();\n GameObject.FindGameObjectWithTag(\"MainCanvas\").GetComponent<InGameMenuManager>().DestroySingleton();\n\n // Unpause\n Time.timeScale = 1;\n AkSoundEngine.WakeupFromSuspend();\n inputs.Player.Enable();\n\n // Inputs\n inputs.Player.Quit.performed -= PauseGame;\n inputs.Player.Quit.performed -= ResumeGame;\n\n // Destroy singleton\n InputsManager.Destroy();\n\n //Wwise\n AkSoundEngine.StopAll();\n\n // Load title\n StartCoroutine(transitions.GetComponent<Transitions>().FadeOut(sceneName));\n\n //SceneManager.LoadScene(sceneName);\n \n // DoDestroyOnLoad\n //Destroy(GameObject.FindGameObjectWithTag(\"SaveManager\"));\n //Destroy(GameObject.FindGameObjectWithTag(\"MainCanvas\"));\n //Destroy(GameObject.FindGameObjectWithTag(\"GameManager\"));\n }\n\n /* Defeat functions */\n\n public void GameOver()\n {\n isGameOver = true;\n\n //Disable player inputs\n inputs.Player.Disable();\n\n //Play defeat sound\n AkSoundEngine.PostEvent(\"Play_Mort\", gameObject, (uint)AkCallbackType.AK_EndOfEvent, CallbackFunction, null);\n\n // Fade out\n fade.GetComponent<Animation>().Play(\"BlackScreenFadeIn\");\n\n // Display message\n // gameOverMessage.GetComponent<Animation>().Play(\"GameOverMessageFadeInOut\");\n\n // Display logo\n // gameOverLogo.GetComponent<Animation>().Play(\"LogoFadeIn\");\n\n // Display new message\n gameOverMessage.GetComponent<Animation>().Play(\"GameOverMessageFadeIn\");\n }\n\n void CallbackFunction(object in_cookie, AkCallbackType in_type, object in_info)\n {\n // Stop all sounds\n AkSoundEngine.StopAll();\n\n Debug.Log(\"Loading scene\");\n //gameOverLogo.GetComponent<Image>().color = new Color(gameOverLogo.GetComponent<Image>().color.r, gameOverLogo.GetComponent<Image>().color.g, gameOverLogo.GetComponent<Image>().color.b, 1);\n \n gameOverMessage.GetComponent<Text>().color = new Color(gameOverMessage.GetComponent<Text>().color.r, gameOverMessage.GetComponent<Text>().color.g, gameOverMessage.GetComponent<Text>().color.b, 1);\n fade.GetComponent<Image>().color = new Color(fade.GetComponent<Image>().color.r, fade.GetComponent<Image>().color.g, fade.GetComponent<Image>().color.b, 1);\n\n // Switch camera\n //transitionCamera.enabled = true;\n //mainCamera.enabled = false;\n\n SceneManager.LoadScene(SceneManager.GetActiveScene().name);\n\n isGameOver = false;\n }\n\n void OnSceneLoaded(Scene scene, LoadSceneMode mode)\n {\n if (scene.name == \"GameElise\" || scene.name == \"Game\" || scene.name == \"CutZonesScene\" || scene.name == \"GameNight\")\n {\n // Reload references\n\n transitions = GameObject.FindGameObjectWithTag(\"Transitions\"); // not needed\n\n fade = GameObject.FindGameObjectWithTag(\"Fade\").GetComponent<Image>();\n gameOverLogo = GameObject.FindGameObjectWithTag(\"GameOver\").GetComponent<Image>();\n gameOverMessage = GameObject.FindGameObjectWithTag(\"GameOverMessage\").GetComponent<Text>();\n\n brightness = GameObject.FindGameObjectWithTag(\"Brightness\");\n loudness = GameObject.FindGameObjectWithTag(\"Loudness\");\n crowd = GameObject.FindGameObjectWithTag(\"Crowd\");\n\n if (!firstRun)\n {\n Debug.Log(\"IT'S NOT A FIRST RUN !\");\n\n // Fade out\n //gameOverLogo.GetComponent<Animation>().Play(\"LogoFadeOut\");\n\n gameOverMessage.GetComponent<Animation>().Play(\"GameOverMessageFadeOut\");\n fade.GetComponent<Animation>().Play(\"BlackScreenFadeOut\");\n\n inputs.Player.Enable();\n }\n else\n {\n Debug.Log(\"IT'S A FIRST RUN\");\n firstRun = false;\n }\n }\n }\n\n /* Victory functions */\n\n public void WinGame()\n {\n inputs.Player.Disable();\n\n // TO DO : Esthesia invincibility (and no damage animation)\n\n //sceneTransition.GetComponent<Animator>().SetBool(\"HasWon\", true);\n\n if (SceneManager.GetActiveScene().name == \"GameElise\")\n {\n Debug.Log(\"Transition to GameNight\");\n GoToNight();\n }\n else if (SceneManager.GetActiveScene().name == \"GameNight\")\n {\n Debug.Log(\"Transition to CreditsScene\");\n GoToCredits();\n }\n }\n\n public void DisplayCredits()\n {\n //AkSoundEngine.StopAll();\n //SceneManager.LoadScene(\"CreditsScene\");\n\n GoToCredits();\n\n /*\n if (SceneManager.GetActiveScene().name != \"CreditsScene\")\n {\n Debug.Log(\"Credits loading\");\n StartCoroutine(\"WaitForCreditsLoad\");\n }\n else\n {\n Debug.Log(\"Crédits déjà prêts\");\n }*/\n }\n\n private IEnumerator WaitForCreditsLoad()\n {\n while (SceneManager.GetActiveScene().name != \"CreditsScene\")\n {\n yield return null;\n }\n\n if (SceneManager.GetActiveScene().name == \"CreditsScene\")\n {\n sceneTransition.GetComponent<Animator>().SetBool(\"CreditsLoaded\", true);\n }\n }\n\n public void GoToNight()\n {\n GoToScene(\"GameNight\");\n\n /*\n if (SceneManager.GetActiveScene().name != \"GameNight\")\n {\n Debug.Log(\"Night loading\");\n StartCoroutine(\"WaitForNightLoad\");\n }\n else\n {\n Debug.Log(\"Night déjà prêt\");\n }*/\n }\n\n private IEnumerator WaitForNightLoad()\n {\n while (SceneManager.GetActiveScene().name != \"GameNight\")\n {\n yield return null;\n }\n\n if (SceneManager.GetActiveScene().name == \"GameNight\")\n {\n sceneTransition.GetComponent<Animator>().SetBool(\"CreditsLoaded\", true);\n }\n }\n}\n" }, { "alpha_fraction": 0.6713075041770935, "alphanum_fraction": 0.6773607730865479, "avg_line_length": 28.5, "blob_id": "5ee258b2c78f0ca9f1d7e2055c0fe5bb594c7634", "content_id": "29d442ad1739a7787694d18808b236f0bf0221ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1654, "license_type": "no_license", "max_line_length": 129, "num_lines": 56, "path": "/SoA-Unity/Assets/LevelPark/Scripts/RemoteCar.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing Pixelplacement;\n\npublic class RemoteCar : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The spline used by the object\")]\n private Spline spline;\n\n [SerializeField]\n [Tooltip(\"The speed of the remote car\")]\n private float speed;\n\n private float percentage;\n\n [Header(\"Ground\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"The raycaster\")]\n private Transform raycaster;\n\n [SerializeField]\n [Tooltip(\"The ground level\")]\n private Transform groundLevel;\n private float groundOffset;\n\n // Start is called before the first frame update\n void Start()\n {\n percentage = 0;\n groundOffset = transform.position.y - groundLevel.transform.position.y;\n }\n\n // Update is called once per frame\n void Update()\n {\n percentage = Mathf.Repeat(percentage + Time.deltaTime * speed / 100f, 1);\n Vector3 position = spline.GetPosition(percentage);\n transform.position = StickToTheGround(position);\n //transform.position = StickToTheGround(position);\n transform.rotation = Quaternion.LookRotation(spline.GetDirection(percentage));\n }\n\n private Vector3 StickToTheGround(Vector3 position)\n {\n LayerMask mask = LayerMask.GetMask(\"AsphaltGround\") | LayerMask.GetMask(\"GrassGround\") | LayerMask.GetMask(\"SoilGround\");\n if (Physics.Raycast(raycaster.transform.position, Vector3.down, out RaycastHit hit, Mathf.Infinity, mask))\n {\n return new Vector3(position.x, hit.point.y + groundOffset, position.z);\n }\n return position;\n }\n}\n" }, { "alpha_fraction": 0.5515605211257935, "alphanum_fraction": 0.561048686504364, "avg_line_length": 51.69736862182617, "blob_id": "979302c67a6cc45584cdf56bfa570212db60636c", "content_id": "6ba07330868fdf1ef3970cc2026cec38eaadbcb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 12018, "license_type": "no_license", "max_line_length": 302, "num_lines": 228, "path": "/SoA-Unity/Assets/LevelStreets/Scripts/Vehicles/TrafficManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing Pixelplacement;\n\npublic class TrafficManager : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The street splines to be watched\")]\n private Spline[] streetSplines;\n\n [SerializeField]\n [Range(10,100)]\n [Tooltip(\"The distance below which the object must tailor its speed to the predecessor\")]\n private float minWatchDistance = 20f;\n\n [SerializeField]\n [Range(0, 5f)]\n [Tooltip(\"How much the speed of the object impact its safety distance\")]\n private float minSafetySpeedFactor = 2f/3f;\n\n [SerializeField]\n [Range(1, 100)]\n [Tooltip(\"The distance below which the object must stop\")]\n private float minSafetyDistance = 2f;\n\n // Start is called before the first frame update\n void Start()\n {\n // Compute the length of every splines before using them\n foreach(Spline streetSpline in streetSplines)\n {\n streetSpline.CalculateLength();\n }\n }\n\n // Update is called once per frame\n void Update()\n {\n CheckForward();\n CheckCrossroad();\n\n // compare which one is closer !\n\n }\n\n void CheckForward()\n {\n foreach (Spline spline in streetSplines)\n {\n foreach (GameObject user in spline.GetComponent<StreetMap>().Users)\n {\n // Set default state, except if in FREEZE mode\n if(user.GetComponent<StreetUser>().MovingState != StreetUser.STATE.FREEZE)\n {\n user.GetComponent<StreetUser>().MovingState = StreetUser.STATE.NORMAL;\n }\n\n foreach (GameObject otherUser in spline.GetComponent<StreetMap>().Users)\n {\n if ( ! GameObject.ReferenceEquals(user, otherUser))\n {\n //Debug.Log(\"Comparing \" + user.name + \" at \" + user.GetComponent<SplineStreetUser>().Percentage + \" and \" + otherUser.name + \" at \" + otherUser.GetComponent<SplineStreetUser>().Percentage + \" !!!!!!!!!!!!!\");\n float distance = otherUser.GetComponent<StreetUser>().Percentage - user.GetComponent<StreetUser>().Percentage;\n\n // TO DO : ADD Forward/Backward Distinction\n // minSafetyDistance proportional to speed of the object\n float minWatchPercentage = Mathf.Max(user.GetComponent<StreetUser>().Speed * minSafetySpeedFactor, minWatchDistance) / spline.Length;\n\n // Join the end and the start of the spline\n if ((0 <= distance && distance <= minWatchPercentage) || (-1 <= distance && distance <= -1 + minWatchPercentage))\n {\n //Debug.Log(otherUser.name + \" IS IN FRONT OF \" + user.name + \" !!!!\");\n user.GetComponent<StreetUser>().FrontSpeed = otherUser.GetComponent<StreetUser>().Speed;\n user.GetComponent<StreetUser>().MovingState = StreetUser.STATE.STAYBEHIND;\n float minSafetyPercentage = minSafetyDistance / spline.Length;\n user.GetComponent<StreetUser>().ObstaclePercentage = Mathf.Repeat(otherUser.GetComponent<StreetUser>().Percentage - minSafetyPercentage + 1, 1); // +1 because Repeat does not take negative numbers into argument\n // TO DO : When there are two vehicules in front ! Choose the closer one !!!\n }\n }\n }\n\n foreach (Colinearity colinearity in spline.GetComponent<StreetMap>().Colinearities)\n {\n // TO DO : Take into account the minWatchPercentage to check colinearity before we're in\n float minWatchPercentage = Mathf.Max(user.GetComponent<StreetUser>().Speed * minSafetySpeedFactor, minWatchDistance) / spline.Length;\n float colinearityPercentageForward = Mathf.Repeat(colinearity.percentageStart - minWatchPercentage + 1, 1);\n\n if (IsInRange(user.GetComponent<StreetUser>().Percentage, colinearityPercentageForward, colinearity.percentageEnd)) // used to be : colinearity.percentageStart\n {\n foreach (GameObject otherUser in colinearity.otherSpline.GetComponent<StreetMap>().Users)\n {\n // TO DO : Take into account the minWatchPercentage to check colinearity before we're in\n float otherMinWatchPercentage = Mathf.Max(otherUser.GetComponent<StreetUser>().Speed * minSafetySpeedFactor, minWatchDistance) / spline.Length;\n float colinearityOtherPercentageForward = Mathf.Repeat(colinearity.otherPercentageStart - otherMinWatchPercentage + 1, 1);\n\n if (IsInRange(otherUser.GetComponent<StreetUser>().Percentage, colinearityOtherPercentageForward, colinearity.otherPercentageEnd))\n {\n // Règle de trois\n //float otherUserMappedPercentage = Remap(otherUser.GetComponent<StreetUser>().Percentage, colinearity.otherPercentageStart, colinearity.otherPercentageEnd, colinearity.percentageStart, colinearity.percentageEnd);\n float otherUserMappedPercentage = Remap(otherUser.GetComponent<StreetUser>().Percentage, colinearityOtherPercentageForward, colinearity.otherPercentageEnd, colinearityPercentageForward, colinearity.percentageEnd);\n\n Debug.Log(\"COLINEARITY OF TWO VEHICLES : \" + user.name + \" at \" + user.GetComponent<StreetUser>().Percentage + \" and the other \" + otherUser.name + \" at \" + otherUserMappedPercentage);\n\n float distance = otherUserMappedPercentage - user.GetComponent<StreetUser>().Percentage;\n\n // TO DO : ADD Forward/Backward Distinction -> Remove Backward handling\n minWatchPercentage = Mathf.Max(user.GetComponent<StreetUser>().Speed * minSafetySpeedFactor, minWatchDistance) / spline.Length;\n if ((0 <= distance && distance < minWatchPercentage) || (-1 <= distance && distance <= -1 + minWatchPercentage))\n {\n Debug.Log(otherUser.name + \" IS IN FRONT OF \" + user.name + \" BY COLINEARITY !!!!\");\n user.GetComponent<StreetUser>().MovingState = StreetUser.STATE.STAYBEHIND;\n user.GetComponent<StreetUser>().FrontSpeed = otherUser.GetComponent<StreetUser>().Speed; // TO DO : Remap too ?\n float minSafetyPercentage = minSafetyDistance / spline.Length;\n user.GetComponent<StreetUser>().ObstaclePercentage = Mathf.Repeat(otherUserMappedPercentage - minSafetyPercentage + 1, 1); // +1 because Repeat does not take negative numbers into argument\n Debug.Log(\"COLINEARITY TRIGGER WITH OBSTACLE PERCENTAGE AT \" + user.GetComponent<StreetUser>().ObstaclePercentage);\n // TO DO : When there are two vehicules in front ! Choose the closer !!!\n }\n }\n }\n }\n }\n }\n }\n }\n\n public static bool IsInRange(float value, float start, float end)\n {\n if (!(0 <= value && value <= 1 && 0 <= start && start <= 1 && 0 <= end && end <= 1))\n {\n throw new System.ArgumentOutOfRangeException(\"Values are not in a valid range [0,1] : start = \" + start + \", end = \" + end + \", value = \" + value);\n }\n if(start < end)\n {\n return start <= value && value <= end;\n }\n if(end < start)\n {\n return start <= value || value <= end;\n }\n else // end == start\n {\n return value == end && start == value;\n }\n }\n\n public static float Remap(float value, float start1, float end1, float start2, float end2)\n {\n if (start1 < end1 && start2 < end2)\n {\n return start2 + ((value - start1) / (end1 - start1)) * (end2 - start2);\n }\n\n else if (end1 < start1 && start2 < end2)\n {\n float x = 0;\n if(start1 <= value)\n {\n x = (value - start1) / (1 - start1 + end1);\n }\n else if(value <= end1)\n {\n x = (1 - start1 + value) / (1 - start1 + end1);\n }\n else\n {\n throw new System.ArgumentOutOfRangeException(\"Wrong value for remapping\");\n }\n return start2 + x * (end2 - start2);\n }\n\n else if (start1 < end1 && end2 < start2)\n {\n return Mathf.Repeat(start2 + ((value - start1) / (end1 - start1)) * (1 - start2 + end2), 1);\n }\n\n else if (end1 < start1 && end2 < start2)\n {\n float x = 0;\n if (value >= start1)\n {\n x = (value - start1) / (1 - start1 + end1);\n }\n else if (value <= end1)\n {\n x = (1 - start1 + value) / (1 - start1 + end1);\n }\n return Mathf.Repeat(start2 + x * (1 - start2 + end2), 1);\n }\n return value;\n }\n\n void CheckCrossroad()\n {\n foreach(Spline spline in streetSplines)\n {\n foreach (GameObject user in spline.GetComponent<StreetMap>().Users)\n {\n // No need to set the default mode, as CheckCrossroad is called after CheckForward\n\n foreach (Intersection intersection in spline.GetComponent<StreetMap>().Intersections)\n {\n float distanceToIntersection = intersection.percentage - user.GetComponent<StreetUser>().Percentage;\n float minWatchPercentage = Mathf.Max(user.GetComponent<StreetUser>().Speed * minSafetySpeedFactor, minWatchDistance) / spline.Length;\n\n if ((0 <= distanceToIntersection && distanceToIntersection <= minWatchPercentage) || (-1 <= distanceToIntersection && distanceToIntersection <= -1 + minWatchPercentage))\n {\n foreach (GameObject otherUser in intersection.otherSpline.GetComponent<StreetMap>().Users)\n {\n //Debug.Log(\"Comparing \" + user.name + \" on \" + spline.name + \" at \" + user.GetComponent<SplineStreetUser>().Percentage + \" with \" + otherUser.name + \" on \" + intersection.otherSpline.name + \" at \" + otherUser.GetComponent<SplineStreetUser>().Percentage + \" !!!!!!!!!!!!!\");\n\n float otherDistanceToIntersection = intersection.otherPercentage - otherUser.GetComponent<StreetUser>().Percentage;\n float otherMinWatchPercentage = Mathf.Max(otherUser.GetComponent<StreetUser>().Speed * minSafetySpeedFactor, minWatchDistance) / spline.Length;\n\n // Join the end and the start of the spline\n if ((0 <= otherDistanceToIntersection && otherDistanceToIntersection <= otherMinWatchPercentage) || (-1 <= otherDistanceToIntersection && otherDistanceToIntersection <= -1 + otherMinWatchPercentage))\n {\n user.GetComponent<StreetUser>().MovingState = StreetUser.STATE.STOP;\n float minSafetyPercentage = minSafetyDistance / spline.Length;\n user.GetComponent<StreetUser>().IntersectionPercentage = Mathf.Repeat(intersection.percentage - minSafetyPercentage + 1, 1);\n }\n }\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6502002477645874, "alphanum_fraction": 0.6515353918075562, "avg_line_length": 27.80769157409668, "blob_id": "117969512914b8c8390645d0dc9381752587fd9f", "content_id": "8eb9cf3f8c51033800e54a574bd7ff8cb57564dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 751, "license_type": "no_license", "max_line_length": 82, "num_lines": 26, "path": "/SoA-Unity/Assets/Resources/Scripts/AfficheScript.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class AfficheScript : MonoBehaviour\n{\n [SerializeField]\n Light l;\n Material mat;\n // Start is called before the first frame update\n void Start()\n {\n mat = GetComponent<MeshRenderer>().material;\n //mat = new Material(mat);\n //mat.SetVector(\"_Color\",new Vector4(color.r, color.g, color.b, color.a));\n //gameObject.GetComponent<MeshRenderer>().material = mat;\n }\n\n // Update is called once per frame\n void Update()\n {\n //mat.SetVector(\"_LightPosition\",gameObject.transform.parent.position);\n mat.SetFloat(\"_LightIntensity\",l.intensity);\n mat.SetColor(\"_ContourColor\",l.color);\n }\n}\n" }, { "alpha_fraction": 0.6285046935081482, "alphanum_fraction": 0.6429906487464905, "avg_line_length": 26.792207717895508, "blob_id": "7b137ed4b82f0caf35c87ed7098074f76c31a79b", "content_id": "7d866bb746c070a11e2ec6fb5ac3ffca543a809d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2142, "license_type": "no_license", "max_line_length": 74, "num_lines": 77, "path": "/SoA-Unity/Assets/LevelStreets/Scripts/Headlights.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Headlights : MonoBehaviour\n{\n [SerializeField]\n private Light headlight1;\n\n [SerializeField]\n private Light headlight2;\n\n [SerializeField]\n private GameObject cone1;\n\n [SerializeField]\n private GameObject cone2;\n\n [SerializeField]\n private GameObject lightSquare1;\n\n [SerializeField]\n private GameObject lightSquare2;\n\n [SerializeField]\n private Material darkMat;\n\n [SerializeField]\n private Material lightMat;\n\n // Start is called before the first frame update\n void Start()\n {\n headlight1.enabled = false;\n headlight2.enabled = false;\n cone1.GetComponent<MeshRenderer>().enabled = false;\n cone2.GetComponent<MeshRenderer>().enabled = false;\n lightSquare1.GetComponent<MeshRenderer>().material = darkMat;\n lightSquare2.GetComponent<MeshRenderer>().material = darkMat;\n\n StartCoroutine(\"Flash\");\n }\n\n // Update is called once per frame\n void Update()\n {\n\n }\n\n IEnumerator Flash()\n {\n float darkDuration, lightDuration;\n for (; ; )\n {\n darkDuration = 2; // Random.Range(2f, 6f);\n lightDuration = 3; // Random.Range(0.1f, 4f);\n\n yield return new WaitForSeconds(darkDuration);\n\n headlight1.enabled = true;\n headlight2.enabled = true;\n cone1.GetComponent<MeshRenderer>().enabled = true;\n cone2.GetComponent<MeshRenderer>().enabled = true;\n lightSquare1.GetComponent<MeshRenderer>().material = lightMat;\n lightSquare2.GetComponent<MeshRenderer>().material = lightMat;\n\n yield return new WaitForSeconds(lightDuration);\n\n headlight1.enabled = false;\n headlight2.enabled = false;\n cone1.GetComponent<MeshRenderer>().enabled = false;\n cone2.GetComponent<MeshRenderer>().enabled = false;\n lightSquare1.GetComponent<MeshRenderer>().material = darkMat;\n lightSquare2.GetComponent<MeshRenderer>().material = darkMat;\n }\n }\n}\n" }, { "alpha_fraction": 0.4466542899608612, "alphanum_fraction": 0.4892193377017975, "avg_line_length": 27.465608596801758, "blob_id": "a5dd7c174229d0b5492ab2641b9b6d4a9896b032", "content_id": "9c69f65caec38a690a5cacb6d7a90d9c0bc0b064", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5383, "license_type": "no_license", "max_line_length": 122, "num_lines": 189, "path": "/SoA-Unity/Assets/Resources/Scripts/CameraHead.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class CameraHead : MonoBehaviour\n{\n Camera cam;\n Matrix4x4 cam_base;\n\n Matrix4x4 T, M, P;\n //pour mouvement camera avec axe x \n Vector3 va, vb, vc;\n Vector3 vr, vu, vn;\n Vector3 eye_pos;\n Vector3 pa, pb, pc;\n //right left bottom top distance\n float r, l, b, t, d;\n\n private Vector2 offSet;\n float offsetZ;\n [SerializeField]\n private float factor = 1.0f;\n [SerializeField]\n float marge_erreur = 0.025f;\n [SerializeField]\n private OpenCVFaceDetection opencv;\n float a00, a01, a02;\n float a10, a11, a12;\n float a20, a21, a22;\n\n float clamp(float min,float max, float value)\n {\n if(value < min)\n {\n value = min;\n }else if(value > max)\n {\n value = max;\n }\n return value;\n }\n\n float smoothstep(float min, float max, float value)\n {\n float v = (value - min) / (max - min);\n v = clamp(0.0f, 1.0f, v);\n v = v * v * (3 - 2 * v);\n return v;\n }\n\n float roundDecimal(float value,int pow)\n {\n if(pow <= 0)\n {\n return value;\n }\n else\n {\n float v = (int)(value * Mathf.Pow(10.0f, pow));\n int unit = ((int)(v/10.0f))*10;\n float nb = v - unit;\n\n if (nb >= 5)\n {\n v = (unit + 1) / Mathf.Pow(10.0f, pow);\n }\n else\n {\n v = unit / Mathf.Pow(10.0f, pow);\n }\n return v;\n }\n }\n // Start is called before the first frame update\n void Start()\n {\n a00 = a01 = a02 = a10 = a11 = a12 = a20 = a21 = a22 = 0.0f;\n offSet = new Vector2(0.0f,0.0f);\n offsetZ = 1.0f;\n cam = GetComponent<Camera>();\n cam_base = cam.projectionMatrix;\n\n\n //v3D\n P = new Matrix4x4();\n M = new Matrix4x4();\n T = new Matrix4x4();\n\n\n float x = 1.0f;\n float y = x / cam.aspect;\n\n //point en bas a gauche\n pa = new Vector3(-x, -y, -cam.nearClipPlane);\n //point a droite\n pb = new Vector3(x, -y, -cam.nearClipPlane);\n //point en haut a gauche\n pc = new Vector3(-x, y, -cam.nearClipPlane);\n\n\n //vecteur droite\n vr = (pb - pa).normalized;\n //vecteur up\n vu = (pc - pa).normalized;\n //vecteur normal\n vn = Vector3.Cross(vr, vu).normalized;\n \n eye_pos = transform.position;\n }\n\n // Update is called once per frame\n void Update()\n {\n float x = Input.GetAxis(\"Horizontal\") * 10.0f * Time.deltaTime;\n float z = Input.GetAxis(\"Vertical\") * 10.0f * Time.deltaTime;\n transform.Translate(new Vector3(x, 0, z));\n\n if (OpenCVFaceDetection.NormalizedFacePositions.Count == 0)\n return;\n\n Vector2 old_offset = new Vector2(offSet.x, offSet.y);\n float old_offset_z = offsetZ;\n\n \n\n float radius_median = 85.0f;\n float marge_erreur_radius = 5.0f;\n\n if (opencv.getActivate())\n {\n offSet.x = (OpenCVFaceDetection.positions.x * 2.0f) - 1.0f;\n offSet.y = (OpenCVFaceDetection.positions.y * 2.0f) - 1.0f;\n\n offSet.x = -offSet.x;\n if (Mathf.Abs(offSet.x - old_offset.x) > marge_erreur || Mathf.Abs(offSet.y - old_offset.y) > marge_erreur)\n {\n Matrix4x4 shear = Matrix4x4.identity;\n Mathf.Clamp(offsetZ, 0.995f, 1.005f);\n\n //fov doit etre régler sur vertical pour FOV_AXIS\n float near, far, fov_vertical, fov_horizontal, right, left, top, bottom;\n\n float coef_deplacement = 1.0f;\n\n\n near = cam.nearClipPlane;\n far = cam.farClipPlane;\n fov_vertical = cam.fieldOfView;\n\n top = near * Mathf.Tan((fov_vertical / 2.0f) * Mathf.Deg2Rad);\n bottom = -top;\n right = top * cam.aspect;\n left = -right;\n\n\n float r2, l2, t2, b2;\n r2 = right * (1.0f - offSet.x);\n l2 = left * (1.0f + offSet.x);\n\n t2 = top * (1.0f - offSet.y);\n b2 = bottom * (1.0f + offSet.y);\n\n\n Matrix4x4 camera = new Matrix4x4();\n\n /*methode 2 sur projection + shear Translation*/\n shear.SetRow(0, new Vector4(1.0f, 0.0f, 0.0f, -offSet.x * 4.0f));\n shear.SetRow(1, new Vector4(0.0f, 1.0f, 0.0f, -offSet.y * 4.0f));\n shear.SetRow(2, new Vector4(0.0f, 0.0f, 1.0f, 0.0f));\n\n camera.SetRow(0, new Vector4((2 * near) / (r2 - l2), 0.0f, (r2 + l2) / (r2 - l2), 0.0f));\n camera.SetRow(1, new Vector4(0.0f, (2 * near) / (top - bottom), (t2 + b2) / (t2 - b2), 0.0f));\n camera.SetRow(2, new Vector4(0.0f, 0.0f, -(far + near) / (far - near), -(2 * near * far) / (far - near)));\n camera.SetRow(3, new Vector4(0.0f, 0.0f, -1.0f, 0.0f));\n\n cam.projectionMatrix = camera * shear;\n }\n else\n {\n offSet = old_offset;\n offsetZ = old_offset_z;\n }\n }\n else\n {\n cam.projectionMatrix = cam_base;\n }\n }\n}\n" }, { "alpha_fraction": 0.6348490118980408, "alphanum_fraction": 0.6494272947311401, "avg_line_length": 31.370786666870117, "blob_id": "2ac01000f8e222e97423ea8b6a7f67cd30ee4cfc", "content_id": "1ca907fd35c14bce9c7dd6758cbc3e0ee6b5f407", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2883, "license_type": "no_license", "max_line_length": 144, "num_lines": 89, "path": "/SoA-Unity/Assets/LevelStreets/Scripts/Vehicles/StreetUsersManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing Pixelplacement;\n\npublic class StreetUsersManager : MonoBehaviour\n{\n [SerializeField]\n private GameObject[] streetUsers;\n public GameObject[] StreetUsers { get { return streetUsers; } set { streetUsers = value; } }\n\n private List<GameObject> availableUsers;\n\n [Header(\"Common Values\")]\n [Space]\n\n [SerializeField]\n [Range(1f, 1000f)]\n [Tooltip(\"The acceleration of the object between two speeds\")]\n private float acceleration = 10f;\n\n [SerializeField]\n [Range(1f, 1000f)]\n [Tooltip(\"The deceleration of the object between two speeds\")]\n private float deceleration = 10f;\n\n [SerializeField]\n [Range(1f, 1000f)]\n [Tooltip(\"The deceleration of the object when behind another object\")]\n private float decelerationObstacle = 50f;\n\n [SerializeField]\n [Range(1f, 1000f)]\n [Tooltip(\"The deceleration of the object to full stop\")]\n private float decelerationStop = 50f;\n\n [SerializeField]\n [Range(1f, 5f)]\n [Tooltip(\"The duration of the freeze\")]\n private float freezeDuration = 3f;\n\n private Vector3 storagePoint = new Vector3(-641, 0, -175); \n\n // Start is called before the first frame update\n void Start()\n {\n // Each user register to the event\n foreach(GameObject streetUser in streetUsers)\n {\n if(streetUser.GetComponent<StreetUser>() == null)\n {\n throw new System.Exception(streetUser.name + \" doesn't contain a StreetUser script\");\n }\n // Initialize common values\n streetUser.GetComponent<StreetUser>().CommonSet(acceleration, deceleration, decelerationObstacle, decelerationStop, freezeDuration);\n streetUser.GetComponent<StreetUser>().AvailableEvent += PushCar;\n }\n availableUsers = new List<GameObject>(streetUsers); // copy constructor\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n private void PushCar(GameObject car)\n {\n // TO DO : Make sure it's not already in there before adding it\n car.transform.position = storagePoint;\n availableUsers.Add(car);\n Debug.Log(\"One car added to the pool, \" + availableUsers.Count + \" cars are available\");\n }\n\n public GameObject PopCar()\n {\n if (availableUsers.Count < 1)\n {\n //throw new System.Exception(\"No available car to supply to this request\");\n Debug.Log(\"No car available for this request\");\n return null;\n }\n int randomIndex = Random.Range(0, availableUsers.Count);\n GameObject car = availableUsers[randomIndex];\n availableUsers.RemoveAt(randomIndex);\n Debug.Log(\"One car removed from the pool, \" + availableUsers.Count + \" cars are available\");\n return car;\n }\n}\n" }, { "alpha_fraction": 0.5513126254081726, "alphanum_fraction": 0.5656324625015259, "avg_line_length": 22.716981887817383, "blob_id": "caf47a701268bf5c98de777d6d11531b1683e223", "content_id": "e23b9f07dcbe3488485e2e03007a0b33860906c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1259, "license_type": "no_license", "max_line_length": 97, "num_lines": 53, "path": "/SoA-Unity/Assets/Resources/Scripts/Duck.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing System.Threading;\nusing UnityEngine;\n\npublic class Duck : MonoBehaviour\n{\n [SerializeField]\n GameObject pivot = null;\n\n [SerializeField]\n float speed = 10.0f;\n\n //sert pour le verrou pour inc nb_id\n static Object obj_lock = new Object();\n\n static int nb_id = 0;\n int id;\n Material mat;\n\n public void setId(int id)\n {\n this.id = id;\n }\n \n // Start is called before the first frame update\n void Start()\n {\n //pour id \n lock (obj_lock)\n {\n id = nb_id;\n Interlocked.Increment(ref nb_id);\n }\n //ici on prend le vecteur\n if(pivot != null)\n {\n Vector3 dir = (transform.position - pivot.transform.position).normalized;\n transform.forward = new Vector3(dir.x, transform.forward.y, dir.z);\n transform.Rotate(0.0f, (speed > 0 ? 90.0f : -90.0f), 0.0f,Space.Self);\n }\n mat = GetComponent<MeshRenderer>().material;\n mat.SetFloat(\"_Id\", id);\n }\n\n void Update()\n {\n if(pivot != null)\n {\n transform.RotateAround(pivot.transform.position, Vector3.up, speed * Time.deltaTime);\n }\n }\n}\n" }, { "alpha_fraction": 0.6378539204597473, "alphanum_fraction": 0.6378539204597473, "avg_line_length": 24.80769157409668, "blob_id": "cbd8355f77a980e39e45dc95c372165e1519c860", "content_id": "448392b6de58c0570dee928b5b77fc32a9d8390f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 673, "license_type": "no_license", "max_line_length": 63, "num_lines": 26, "path": "/SoA-Unity/Assets/Resources/Scripts/Afficheur.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Afficheur : MonoBehaviour\n{\n [SerializeField]\n Light l;\n\n Material mat;\n // Start is called before the first frame update\n void Start()\n {\n mat = GetComponent<MeshRenderer>().material;\n //nouvelle instance\n mat = new Material(mat);\n gameObject.GetComponent<MeshRenderer>().material = mat;\n }\n void Update()\n {\n mat.SetFloat(\"_LightRange\", l.range);\n mat.SetFloat(\"_LightIntensity\", l.intensity);\n mat.SetColor(\"_LightColor\", l.color);\n mat.SetVector(\"_LightPos\", l.transform.position);\n }\n}\n" }, { "alpha_fraction": 0.5477481484413147, "alphanum_fraction": 0.5522282719612122, "avg_line_length": 36.20175552368164, "blob_id": "5de547cefec1c9bdfdeb7161cbf3bf40262a13e6", "content_id": "eb1e1eff4be2c2ab39fbfb56b5e1b1394a8de8b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8484, "license_type": "no_license", "max_line_length": 153, "num_lines": 228, "path": "/SoA-Unity/Assets/Scripts/NPC/RandomizeNPC.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class RandomizeNPC : MonoBehaviour\n{\n //[SerializeField]\n //[Tooltip(\"Reference to the NPC material manager\")]\n private GameObject NpcMaterialsManager;\n\n private static readonly int NB_BUFFER_SHADER = 16;\n\n // Start is called before the first frame update\n void Start()\n {\n List<GameObject> props = new List<GameObject>();\n List<GameObject> beards = new List<GameObject>();\n List<GameObject> hairs = new List<GameObject>();\n List<GameObject> eyes = new List<GameObject>();\n\n foreach (Transform category in transform)\n {\n if(category.name.StartsWith(\"eyes\"))\n {\n foreach (Transform eye in category)\n {\n eyes.Add(eye.gameObject);\n eye.gameObject.SetActive(false);\n }\n }\n else if (category.name.StartsWith(\"hair\"))\n {\n foreach (Transform hair in category)\n {\n hairs.Add(hair.gameObject);\n hair.gameObject.SetActive(false);\n }\n }\n else if (category.name.StartsWith(\"beard\"))\n {\n foreach (Transform beard in category)\n {\n beards.Add(beard.gameObject);\n beard.gameObject.SetActive(false);\n }\n }\n else if (category.name.StartsWith(\"props\"))\n {\n foreach (Transform prop in category)\n {\n props.Add(prop.gameObject);\n prop.gameObject.SetActive(false);\n }\n }\n }\n\n NpcMaterialsManager = GameObject.FindGameObjectWithTag(\"NPCMaterialsManager\");\n if (NpcMaterialsManager == null)\n {\n throw new System.NullReferenceException(\"No object tagged with NPCMaterialsManager\");\n }\n\n RandomizeFeatures(eyes, beards, props, hairs);\n\n RandomizeMaterials();\n\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n private void RandomizeMaterials()\n {\n\n }\n\n private void RandomizeFeatures(List<GameObject> eyes, List<GameObject> beards, List<GameObject> props, List<GameObject> hairs)\n {\n int index;\n Material hairEyebrowsEyesMaterial = null;\n\n if (eyes.Count > 0)\n {\n index = Random.Range(0, eyes.Count);\n eyes[index].SetActive(true);\n\n NpcMaterialsManager.GetComponent<NPCMaterialsManager>();\n // material\n hairEyebrowsEyesMaterial = NpcMaterialsManager.GetComponent<NPCMaterialsManager>().GetHairEyebrowsMaterial();\n\n if (eyes[index].transform.GetChild(0).GetComponent<MeshRenderer>())\n {\n eyes[index].transform.GetChild(0).GetComponent<MeshRenderer>().material = hairEyebrowsEyesMaterial; // eyebrows\n //eyes[index].transform.GetChild(1).GetComponent<MeshRenderer>().material = hairEyebrowsEyesMaterial; // eyes\n }\n else if (eyes[index].transform.GetChild(0).GetComponent<SkinnedMeshRenderer>())\n {\n eyes[index].transform.GetChild(0).GetComponent<SkinnedMeshRenderer>().material = hairEyebrowsEyesMaterial; // eyebrows\n //eyes[index].transform.GetChild(1).GetComponent<SkinnedMeshRenderer>().material = hairEyebrowsEyesMaterial; // eyes\n }\n }\n\n if (beards.Count > 0)\n {\n index = Random.Range(0, beards.Count + 1);\n if (index < beards.Count) // can be beardless\n {\n beards[index]?.SetActive(true);\n\n // material\n if (beards[index].GetComponent<MeshRenderer>())\n {\n beards[index].GetComponent<MeshRenderer>().material = hairEyebrowsEyesMaterial;\n }\n else if (beards[index].GetComponent<SkinnedMeshRenderer>())\n {\n beards[index].GetComponent<SkinnedMeshRenderer>().material = hairEyebrowsEyesMaterial;\n }\n }\n }\n\n if (props.Count > 0)\n {\n index = Random.Range(0, props.Count + 1);\n if (index < props.Count) // can wear no hat\n {\n props[index].SetActive(true);\n\n // material\n if (props[index].GetComponent<MeshRenderer>())\n {\n props[index].GetComponent<MeshRenderer>().material = NpcMaterialsManager.GetComponent<NPCMaterialsManager>().GetHatMaterial();\n }\n else if (props[index].GetComponent<SkinnedMeshRenderer>())\n {\n props[index].GetComponent<SkinnedMeshRenderer>().material = NpcMaterialsManager.GetComponent<NPCMaterialsManager>().GetHatMaterial();\n }\n }\n }\n\n if (hairs.Count > 0)\n {\n bool isFemaleOrKid = transform.Find(\"body\").GetChild(0).name.Contains(\"npcMkid\") || transform.Find(\"body\").GetChild(0).name.Contains(\"npcF\");\n index = Random.Range(0, hairs.Count + (isFemaleOrKid ? 0 : 1));\n if (index < hairs.Count) // can be bald\n {\n hairs[index].SetActive(true);\n\n // material\n if (hairs[index].GetComponent<MeshRenderer>())\n {\n hairs[index].GetComponent<MeshRenderer>().material = hairEyebrowsEyesMaterial;\n }\n else if (hairs[index].GetComponent<SkinnedMeshRenderer>())\n {\n hairs[index].GetComponent<SkinnedMeshRenderer>().material = hairEyebrowsEyesMaterial;\n }\n }\n }\n\n GameObject body = transform.Find(\"body\")?.GetChild(0)?.gameObject;\n\n if(body == null)\n {\n throw new System.NullReferenceException(\"No body gameobject for the NPC \" + transform.name);\n }\n\n if (body.name.Contains(\"npcM\"))\n {\n if (body.GetComponent<MeshRenderer>())\n {\n body.GetComponent<MeshRenderer>().material = NpcMaterialsManager.GetComponent<NPCMaterialsManager>().GetMaleNPCMaterial();\n }\n else if (body.GetComponent<SkinnedMeshRenderer>())\n {\n body.GetComponent<SkinnedMeshRenderer>().material = NpcMaterialsManager.GetComponent<NPCMaterialsManager>().GetMaleNPCMaterial();\n }\n }\n else if (body.name.Contains(\"npcF\"))\n {\n if (body.GetComponent<MeshRenderer>())\n {\n body.GetComponent<MeshRenderer>().material = NpcMaterialsManager.GetComponent<NPCMaterialsManager>().GetMaleNPCMaterial();\n }\n else if (body.GetComponent<SkinnedMeshRenderer>())\n {\n body.GetComponent<SkinnedMeshRenderer>().material = NpcMaterialsManager.GetComponent<NPCMaterialsManager>().GetMaleNPCMaterial();\n }\n }\n else\n {\n throw new System.Exception(\"No body mesh for the NPC \" + transform.name);\n }\n\n MeshRenderer mesh = body.GetComponent<MeshRenderer>();\n if (mesh == null)\n {\n SkinnedMeshRenderer skinmesh = body.GetComponent<SkinnedMeshRenderer>();\n List<Vector4> vec = new List<Vector4>();\n for (int i = 0; i < NB_BUFFER_SHADER; i++)\n {\n vec.Add(new Vector4());\n }\n skinmesh.materials[0].SetFloat(\"vector_lenght\", 0);\n skinmesh.materials[0].SetVectorArray(\"vector_pos\", vec);\n skinmesh.materials[0].SetVectorArray(\"vector_dir\", vec);\n skinmesh.materials[0].SetVectorArray(\"vector_col\", vec);\n skinmesh.materials[0].SetVectorArray(\"vector_opt\", vec);\n }\n else\n {\n List<Vector4> vec = new List<Vector4>();\n for (int i = 0; i < NB_BUFFER_SHADER; i++)\n {\n vec.Add(new Vector4());\n }\n mesh.material.SetFloat(\"vector_lenght\", 0);\n mesh.material.SetVectorArray(\"vector_pos\", vec);\n mesh.material.SetVectorArray(\"vector_dir\", vec);\n mesh.material.SetVectorArray(\"vector_col\", vec);\n mesh.material.SetVectorArray(\"vector_opt\", vec);\n }\n\n }\n}\n" }, { "alpha_fraction": 0.7820512652397156, "alphanum_fraction": 0.8205128312110901, "avg_line_length": 38, "blob_id": "725adbf38985b14996bc5783ebda9f268ac623c3", "content_id": "5687fa512fc9216d14a18d422a04ee1bf88d0669", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 78, "license_type": "no_license", "max_line_length": 56, "num_lines": 2, "path": "/SoA-Unity/Assets/Models/Façade/desktop.ini", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "[LocalizedFileNames]\nbuilding_roof_triangle_2.fbx=@building_roof_triangle_2,0\n" }, { "alpha_fraction": 0.59968101978302, "alphanum_fraction": 0.6100478172302246, "avg_line_length": 24.59183692932129, "blob_id": "8740bf333e9becb84a832169bce238e2022abfe7", "content_id": "d2fd2733ac729a960c217d42690fc2c22e9b489f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1256, "license_type": "no_license", "max_line_length": 91, "num_lines": 49, "path": "/SoA-Unity/Assets/LevelStreets/Scripts/Clock.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Clock : MonoBehaviour\n{\n [Header(\"VFX\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"VFX to play when loud sound is emitted\")]\n private GameObject loudVFX;\n\n [SerializeField]\n [Tooltip(\"Initial delay to start the VFX\")]\n [Range(0,1)]\n private float initialDelay = 0;\n\n // Start is called before the first frame update\n void Awake()\n {\n Debug.Assert(loudVFX != null);\n loudVFX.GetComponent<ParticleSystem>().Stop();\n ParticleSystem.MainModule mainModule = loudVFX.GetComponent<ParticleSystem>().main;\n mainModule.startLifetime = 0.25f; // One quarter of the default value\n StartCoroutine(VFX());\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n private IEnumerator VFX()\n {\n if(initialDelay != 0)\n {\n yield return new WaitForSeconds(initialDelay);\n }\n for (; ;)\n {\n loudVFX.GetComponent<ParticleSystem>().Play();\n yield return new WaitForSeconds(0.05f);\n loudVFX.GetComponent<ParticleSystem>().Stop();\n yield return new WaitForSeconds(0.60f);\n }\n }\n}\n" }, { "alpha_fraction": 0.4587387144565582, "alphanum_fraction": 0.4698575437068939, "avg_line_length": 40.11428451538086, "blob_id": "fb809bafcddc6fc47de3f03c787fd30672b7be6c", "content_id": "df7a3c5f59dbe3f974d6a4cc19261d299c6f9c96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 11518, "license_type": "no_license", "max_line_length": 165, "num_lines": 280, "path": "/SoA-Unity/Assets/Resources/Scripts/ColliderLight.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class ColliderLight : MonoBehaviour\n{\n Light l;\n Vector4 pos_;\n Vector4 dir_;\n Vector4 opt_;\n Vector4 col_;\n // Start is called before the first frame update\n void Awake()\n {\n l = gameObject.GetComponent<Light>();\n col_ = l.color;\n float value = l.range;\n switch (l.type)\n {\n case LightType.Point:\n value *= -1;\n opt_ = new Vector4(0.0f,0.0f,0.0f,0.0f);\n dir_ = new Vector4(0.0f,0.0f,0.0f,l.intensity);\n break;\n case LightType.Spot:\n Debug.Log(\"Spot light\");\n Vector4 direction = new Vector4(0.0f,0.0f,0.0f,0.0f);//l.transform.rotation.eulerAngles;\n dir_ = direction;//new Vector4((direction.x * Mathf.PI) / 180.0f, (direction.y * Mathf.PI) / 180.0f, (direction.z * Mathf.PI) / 180.0f, l.intensity);\n //angle\n float outerRad;// = Mathf.Deg2Rad * 0.5f * l.spotAngle;\n //float outerCos = Mathf.Cos(outerRad);\n //float outerTan = Mathf.Tan(outerRad);\n //float innerCos = Mathf.Cos(Mathf.Atan(((64.0f - 18.0f) / 64.0f) * outerTan));\n //float angleRange = Mathf.Max(innerCos - outerCos, 0.001f);\n\n outerRad = 17.5f * Mathf.Deg2Rad;\n float inner = 12.5f * Mathf.Deg2Rad;\n\n float X = inner;//1.0f / Mathf.Max(l.range * l.range, 0.00001f);\n float Y = outerRad;//1.0f / angleRange;\n float Z = 0.0f;\n float W = 0.0f;//-outerCos * Z;\n X = l.spotAngle * Mathf.Deg2Rad;\n opt_ = new Vector4(Mathf.Cos(X), Y, Z, W);\n \n \n break;\n default:\n //\n break;\n }\n pos_ = new Vector4(transform.position.x, transform.position.y, transform.position.z, value);\n }\n\n void OnTriggerEnter(UnityEngine.Collider other)\n {\n\n //if(other.gameObject.GetComponent<Light>() == null && other.gameObject.GetComponent<ColliderStatic>() == null)\n if (other.gameObject.GetComponent<RandomizeNPC>() != null || other.gameObject.name.Equals(\"Player\") || other.gameObject.GetComponent<Dynamic>() != null)\n {\n Debug.Log(\"Collider Light Enter \" + other.name + \" \" + gameObject.name);\n //MeshRenderer mesh = other.gameObject.GetComponent<MeshRenderer>();\n SkinnedMeshRenderer mesh_skin = other.gameObject.GetComponent<SkinnedMeshRenderer>();\n MeshRenderer mesh_ren = null;\n\n\n if (mesh_skin == null)\n {\n mesh_skin = other.transform.Find(\"body\")?.GetChild(0)?.gameObject.GetComponent<SkinnedMeshRenderer>();\n if (other.gameObject.name.Equals(\"Player\"))\n {\n mesh_skin = other.transform.Find(\"Avatar_Esthesia_mergedAnims/CharaEsthesia_geo/charaBody_Esthesia_geo\").GetComponent<SkinnedMeshRenderer>();\n if(mesh_skin == null)\n other.transform.Find(\"Avatar_Esthesia_mergedAnims/CharaEsthesia_geo/charaHair_Esthesia_geo\").GetComponent<SkinnedMeshRenderer>();\n }\n if(mesh_skin == null)\n {\n mesh_ren = other.transform.Find(\"body\")?.GetChild(0)?.gameObject.GetComponent<MeshRenderer>();\n }\n }\n\n if(mesh_skin != null || mesh_ren != null)\n {\n Vector4[] pos;\n Vector4[] dir;\n Vector4[] col;\n Vector4[] opt;\n float len = 0.0f;\n\n Material mat;\n if (mesh_skin != null)\n {\n //normalement je pense que c'est déjà géré mais bon on sait jamais\n mat = mesh_skin.material;\n if (mat == null)\n mat = mesh_skin.materials[0];\n pos = mat.GetVectorArray(\"vector_pos\");\n dir = mat.GetVectorArray(\"vector_dir\");\n col = mat.GetVectorArray(\"vector_col\");\n opt = mat.GetVectorArray(\"vector_opt\");\n len = mat.GetFloat(\"vector_lenght\");\n }\n else\n {\n mat = mesh_ren.material;\n if (mat == null)\n mat = mesh_ren.materials[0];\n pos = mat.GetVectorArray(\"vector_pos\");\n dir = mat.GetVectorArray(\"vector_dir\");\n col = mat.GetVectorArray(\"vector_col\");\n opt = mat.GetVectorArray(\"vector_opt\");\n len = mat.GetFloat(\"vector_lenght\");\n }\n\n List<Vector4> positions = new List<Vector4>();\n List<Vector4> directions = new List<Vector4>();\n List<Vector4> colors = new List<Vector4>();\n List<Vector4> options = new List<Vector4>();\n //a voir si dans un seule array a la suite\n\n int size = (int)len;\n if (pos != null && len > 0)\n {\n positions.AddRange(pos);\n directions.AddRange(dir);\n colors.AddRange(col);\n options.AddRange(opt);\n\n positions[size] = pos_;\n directions[size] = dir_;\n colors[size] = col_;\n options[size] = opt_;\n }\n else\n {\n positions.Add(pos_);\n directions.Add(dir_);\n colors.Add(col_);\n options.Add(opt_);\n }\n\n bool trouver = false;\n int i = 0;\n\n if (mesh_skin != null)\n {\n mat.SetFloat(\"vector_lenght\", size + 1);\n mat.SetVectorArray(\"vector_pos\", positions);\n mat.SetVectorArray(\"vector_dir\", directions);\n mat.SetVectorArray(\"vector_col\", colors);\n mat.SetVectorArray(\"vector_opt\", options);\n }\n else\n {\n mat.SetFloat(\"vector_lenght\", size + 1);\n mat.SetVectorArray(\"vector_pos\", positions);\n mat.SetVectorArray(\"vector_dir\", directions);\n mat.SetVectorArray(\"vector_col\", colors);\n mat.SetVectorArray(\"vector_opt\", options);\n }\n\n }\n }\n }\n\n void OnTriggerExit(UnityEngine.Collider other)\n {\n //if (other.gameObject.GetComponent<Light>() == null && other.gameObject.GetComponent<ColliderStatic>() == null)\n if(other.gameObject.GetComponent<RandomizeNPC>() != null || other.gameObject.name.Equals(\"Player\") || other.gameObject.GetComponent<Dynamic>() != null)\n {\n Debug.Log(\"Collider Light Exit \" + other.name + \" \" + gameObject.name);\n SkinnedMeshRenderer mesh_skin = other.gameObject.GetComponent<SkinnedMeshRenderer>();\n MeshRenderer mesh_ren = null;\n\n if (mesh_skin == null)\n {\n if (other.gameObject.name.Equals(\"Player\"))\n {\n mesh_skin = other.transform.Find(\"Avatar_Esthesia_mergedAnims/CharaEsthesia_geo/charaBody_Esthesia_geo\").GetComponent<SkinnedMeshRenderer>();\n if (mesh_skin == null)\n other.transform.Find(\"Avatar_Esthesia_mergedAnims/CharaEsthesia_geo/charaHair_Esthesia_geo\").GetComponent<SkinnedMeshRenderer>();\n }\n else\n mesh_skin = other.transform.Find(\"body\")?.GetChild(0)?.gameObject.GetComponent<SkinnedMeshRenderer>();\n if (mesh_skin == null)\n {\n mesh_ren = other.transform.Find(\"body\")?.GetChild(0)?.gameObject.GetComponent<MeshRenderer>();\n }\n }\n\n\n if(mesh_skin != null || mesh_ren != null)\n {\n Vector4[] pos;\n Vector4[] dir;\n Vector4[] col;\n Vector4[] opt;\n float len = 0.0f;\n\n Material mat;\n\n if (mesh_skin != null)\n {\n mat = mesh_skin.material;\n if (mat == null)\n mat = mesh_skin.materials[0];\n pos = mat.GetVectorArray(\"vector_pos\");\n dir = mat.GetVectorArray(\"vector_dir\");\n col = mat.GetVectorArray(\"vector_col\");\n opt = mat.GetVectorArray(\"vector_opt\");\n len = mat.GetFloat(\"vector_lenght\");\n }\n else\n {\n mat = mesh_ren.material;\n if (mat == null)\n mat = mesh_ren.materials[0];\n pos = mat.GetVectorArray(\"vector_pos\");\n dir = mat.GetVectorArray(\"vector_dir\");\n col = mat.GetVectorArray(\"vector_col\");\n opt = mat.GetVectorArray(\"vector_opt\");\n len = mat.GetFloat(\"vector_lenght\");\n }\n\n List<Vector4> positions = new List<Vector4>();\n List<Vector4> directions = new List<Vector4>();\n List<Vector4> colors = new List<Vector4>();\n List<Vector4> options = new List<Vector4>();\n //a voir si dans un seule array a la suite\n\n /*if(pos != null)\n {\n positions.AddRange(pos);\n directions.AddRange(dir);\n colors.AddRange(col);\n options.AddRange(opt);\n }*/\n\n positions.AddRange(pos);\n directions.AddRange(dir);\n colors.AddRange(col);\n options.AddRange(opt);\n\n bool trouver = false;\n int i = 0;\n while (i < pos.Length && !trouver)\n {\n if (pos[i].x == other.transform.position.x && pos[i].y == other.transform.position.y && pos[i].z == other.transform.position.z)\n {\n trouver = true;\n positions.RemoveAt(i);\n directions.RemoveAt(i);\n colors.RemoveAt(i);\n options.RemoveAt(i);\n }\n i++;\n }\n\n if (mesh_skin != null)\n {\n mat.SetFloat(\"vector_lenght\", len - 1);\n mat.SetVectorArray(\"vector_pos\", positions);\n mat.SetVectorArray(\"vector_dir\", directions);\n mat.SetVectorArray(\"vector_col\", colors);\n mat.SetVectorArray(\"vector_opt\", options);\n }\n else\n {\n mat.SetFloat(\"vector_lenght\", len - 1);\n mat.SetVectorArray(\"vector_pos\", positions);\n mat.SetVectorArray(\"vector_dir\", directions);\n mat.SetVectorArray(\"vector_col\", colors);\n mat.SetVectorArray(\"vector_opt\", options);\n }\n }\n\n \n }\n }\n}\n" }, { "alpha_fraction": 0.6179212927818298, "alphanum_fraction": 0.6194751262664795, "avg_line_length": 30.139785766601562, "blob_id": "be10fed11f145706ed2786fab420f9167616b69a", "content_id": "a6bdb30b2d8bdf73c7293b1a29d718deb7f05f96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5794, "license_type": "no_license", "max_line_length": 171, "num_lines": 186, "path": "/SoA-Unity/Assets/Scripts/ExitShelter.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.UI;\nusing UnityEngine.InputSystem;\n\npublic class ExitShelter : MonoBehaviour\n{\n private Inputs inputs;\n \n [SerializeField]\n private EnergyBehaviour energyBehaviour;\n\n private Image shade;\n\n private GameObject shelter;\n private Camera shelterCamera;\n\n [SerializeField]\n private ShelterManager shelterManager;\n\n [SerializeField]\n private Camera mainCamera;\n\n [SerializeField]\n private GameObject cameraHolder;\n\n private GameObject ambianceManager;\n\n private GameObject compass;\n\n private string shelterTag;\n\n private void Awake()\n {\n inputs = InputsManager.Instance.Inputs;\n inputs.Player.Interact.Disable();\n\n ambianceManager = GameObject.FindGameObjectWithTag(\"AmbianceManager\");\n shade = GameObject.FindGameObjectWithTag(\"Fade\").GetComponent<Image>();\n compass = GameObject.FindGameObjectWithTag(\"Compass\");\n Debug.Assert(compass != null, \"Missing gameobject with compass tag\");\n\n if (ambianceManager == null)\n {\n throw new System.NullReferenceException(\"Missing game object tagged with \\\"AmbianceManager\\\"\");\n }\n }\n\n // Start is called before the first frame update\n void Start()\n {\n \n }\n\n // Update is called once per frame\n void Update()\n {\n GetComponent<PlayerFirst>().SetShelterSpeed();\n\n if (shelterManager && inputs.Player.enabled)\n {\n inputs.Player.Interact.performed -= ShelterToWorld;\n inputs.Player.Interact.Disable();\n\n RaycastHit hit;\n LayerMask mask = LayerMask.GetMask(\"Shelter Exit\");\n\n if (Physics.Raycast(transform.position, transform.forward, out hit, shelterManager.MaxDistanceToDoor, mask))\n {\n shelterCamera = hit.transform.parent.transform.Find(\"Shelter Camera\").GetComponent<Camera>();\n shelter = shelterManager.GoOutside(hit.collider.transform.parent.gameObject);\n shelterTag = hit.transform.parent.transform.tag;\n inputs.Player.Interact.performed += ShelterToWorld;\n\n if (inputs.Player.enabled)\n {\n inputs.Player.Interact.Enable();\n }\n }\n }\n }\n\n void ShelterToWorld(InputAction.CallbackContext ctx)\n {\n StartCoroutine(\"Exit\");\n }\n\n IEnumerator Exit()\n {\n inputs.Player.Disable();\n\n energyBehaviour.IsReloading = false;\n while (!Mathf.Approximately(shade.color.a, 1))\n {\n shade.color = new Color(shade.color.r, shade.color.g, shade.color.b, Mathf.Min(shade.color.a + Time.deltaTime / (shelterManager.TransitionDuration * 0.5f),1));\n yield return null;\n }\n\n // Play sound\n switch (shelterTag)\n {\n case \"Home\":\n AkSoundEngine.PostEvent(\"Play_Shelter_House_Door_Close\", gameObject);\n break;\n case \"Shed\":\n AkSoundEngine.PostEvent(\"Play_Shelter_Parc_Door_Close\", gameObject);\n break;\n case \"Bar\":\n AkSoundEngine.PostEvent(\"Play_Shelter_Bar_Door_Close\", gameObject);\n break;\n default:\n Debug.LogError(\"Shelter not recognized: \" + shelterTag);\n break;\n }\n\n // Reset character position and speed\n\n if (transform.GetComponent<PlayerFirst>().isActiveAndEnabled)\n {\n Transform warp = shelter.transform.Find(\"Warp Position\");\n GetComponent<PlayerFirst>().ResetTransform(warp.position, warp.rotation.eulerAngles.y);\n GetComponent<PlayerFirst>().ResetSpeed();\n }\n\n // Reset camera\n\n GetComponent<PlayerFirst>().IsInsideShelter = false;\n mainCamera.enabled = true;\n\n if (cameraHolder.GetComponent<CameraFollow>().isActiveAndEnabled)\n {\n cameraHolder.GetComponent<CameraFollow>().ResetCameraToFrontView();\n }\n shelterCamera.enabled = false;\n\n // Wait for one frame to have a correct camera angle\n yield return new WaitForEndOfFrame();\n\n // Reset sound\n mainCamera.gameObject.GetComponent<AkAudioListener>().enabled = true;\n shelterCamera.gameObject.GetComponent<AkAudioListener>().enabled = false;\n\n AkSoundEngine.SetState(\"Dans_Lieu_Repos\", \"Non\");\n\n // Ambiance sound\n if (shelterTag == \"Home\" || shelterTag == \"Bar\")\n {\n ambianceManager.GetComponent<AmbianceManager>().PlayCityAmbiance();\n }\n else if (shelterTag == \"Shed\")\n {\n ambianceManager.GetComponent<AmbianceManager>().PlayParkAmbiance();\n }\n\n // UI\n compass.GetComponent<Image>().enabled = true;\n compass.SetActive(true);\n\n //GetComponent<PostWwiseAmbiance>().ShelterAmbianceEventStop.Post(gameObject);\n //GetComponent<PostWwiseAmbiance>().ParkAmbianceEventPlay.Post(gameObject);\n\n while (shade.color.a > 0)\n {\n shade.color = new Color(shade.color.r, shade.color.g, shade.color.b, Mathf.Max(shade.color.a - Time.deltaTime / (shelterManager.TransitionDuration * 0.5f),0));\n yield return null;\n }\n shade.color = new Color(shade.color.r, shade.color.g, shade.color.b, 0);\n\n inputs.Player.Interact.performed -= ShelterToWorld;\n inputs.Player.Enable();\n\n GetComponent<EnterShelter>().enabled = true;\n GetComponent<ExitShelter>().enabled = false;\n }\n\n void OnDisable()\n {\n //inputs.Player.Disable();\n }\n\n private void OnDestroy()\n {\n inputs.Player.Interact.performed -= ShelterToWorld;\n }\n}\n" }, { "alpha_fraction": 0.6223404407501221, "alphanum_fraction": 0.6238297820091248, "avg_line_length": 32.21554946899414, "blob_id": "d2e15e868a99f13e74fcc738b04ebb9cc682e613", "content_id": "b8211b0966789ae95963795c72d32d7ad4d4850a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9402, "license_type": "no_license", "max_line_length": 172, "num_lines": 283, "path": "/SoA-Unity/Assets/Scripts/EnterShelter.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.UI;\nusing UnityEngine.InputSystem;\nusing System.Linq;\n\npublic class EnterShelter : MonoBehaviour\n{\n private Inputs inputs;\n\n [SerializeField]\n private EnergyBehaviour energyBehaviour;\n\n private Image shade;\n\n private GameObject shelter;\n\n [SerializeField]\n private ShelterManager shelterManager;\n\n [SerializeField]\n private Camera mainCamera;\n\n private GameObject ambianceManager;\n\n private string shelterTag;\n\n private GameObject saveManager;\n\n private GameObject compass;\n\n private void Awake()\n {\n inputs = InputsManager.Instance.Inputs;\n inputs.Player.Interact.Disable();\n }\n\n // Start is called before the first frame update\n void Start()\n {\n GetComponent<ExitShelter>().enabled = false;\n\n ambianceManager = GameObject.FindGameObjectWithTag(\"AmbianceManager\");\n saveManager = GameObject.FindGameObjectWithTag(\"SaveManager\");\n shade = GameObject.FindGameObjectWithTag(\"Fade\").GetComponent<Image>();\n compass = GameObject.FindGameObjectWithTag(\"Compass\");\n Debug.Assert(compass != null, \"Missing gameobject with compass tag\");\n\n if (ambianceManager == null)\n {\n throw new System.NullReferenceException(\"Missing game object tagged with tag \\\"AmbianceManager\\\"\");\n }\n if (saveManager == null)\n {\n throw new System.NullReferenceException(\"Missing game object tagged with tag \\\"SaveManager\\\"\");\n }\n\n // Load shelter from save\n shelter = null;\n switch(saveManager.GetComponent<SaveManager>().SaveShelterIndex)\n {\n case SHELTER.HOME:\n shelter = shelterManager.GetComponent<ShelterManager>().ShelterInsides.Where(s => s.tag == \"Home\").First();\n break;\n case SHELTER.SHED:\n shelter = shelterManager.GetComponent<ShelterManager>().ShelterInsides.Where(s => s.tag == \"Shed\").First();\n break;\n case SHELTER.BAR:\n shelter = shelterManager.GetComponent<ShelterManager>().ShelterInsides.Where(s => s.tag == \"Bar\").First();\n break;\n }\n StartCoroutine(\"Respawn\");\n }\n\n // Update is called once per frame\n void Update()\n {\n if (shelterManager && inputs.Player.enabled)\n {\n inputs.Player.Interact.performed -= WorldToShelter;\n inputs.Player.Interact.Disable();\n\n RaycastHit hit;\n LayerMask mask = LayerMask.GetMask(\"Shelter Entrance\");\n\n if (Physics.Raycast(transform.position, transform.forward, out hit, shelterManager.MaxDistanceToDoor, mask))\n {\n shelter = shelterManager.GoInside(hit.collider.transform.parent.gameObject);\n inputs.Player.Interact.performed += WorldToShelter;\n inputs.Player.Interact.Enable();\n }\n }\n }\n\n IEnumerator Respawn()\n {\n // suspend interaction both with player and world\n inputs.Player.Disable();\n\n GetComponent<EnergyBehaviour>().Invincibility(true);\n\n GetComponent<PlayerFirst>().IsInsideShelter = true;\n\n shelterTag = shelter.tag;\n\n // Reset Character Position and Speed\n\n if (transform.GetComponent<PlayerFirst>().isActiveAndEnabled)\n {\n Transform warp = shelter.transform.Find(\"Warp Position\");\n transform.GetComponent<PlayerFirst>().ResetTransform(warp.position, warp.rotation.eulerAngles.y);\n transform.GetComponent<PlayerFirst>().SetShelterSpeed();\n }\n\n // Reset Camera\n\n mainCamera.enabled = false;\n\n // TO DO : Do not follow inside\n\n shelter.transform.Find(\"Shelter Camera\").GetComponent<Camera>().enabled = true;\n\n // Reset sound\n\n shelter.transform.Find(\"Shelter Camera\").GetComponent<AkAudioListener>().enabled = true;\n mainCamera.gameObject.GetComponent<AkAudioListener>().enabled = false;\n\n AkSoundEngine.SetState(\"Dans_Lieu_Repos\", \"Oui\");\n\n // Ambiance sound\n if (shelterTag == \"Home\")\n {\n ambianceManager.GetComponent<AmbianceManager>().PlayHomeAmbiance();\n }\n else if (shelterTag == \"Shed\")\n {\n ambianceManager.GetComponent<AmbianceManager>().PlayShedAmbiance();\n }\n else if (shelterTag == \"Bar\")\n {\n ambianceManager.GetComponent<AmbianceManager>().PlayBarAmbiance();\n }\n\n //UI\n compass.GetComponent<Image>().enabled = false;\n //compass.GetComponent<CompassBehavior>().enabled = false;\n compass.SetActive(false);\n\n //GetComponent<PostWwiseAmbiance>().ParkAmbianceEventStop.Post(gameObject);\n //GetComponent<PostWwiseAmbiance>().ShelterAmbianceEventPlay.Post(gameObject);\n\n while (shade.color.a > 0)\n {\n shade.color = new Color(shade.color.r, shade.color.g, shade.color.b, Mathf.Max(shade.color.a - Time.deltaTime / (shelterManager.TransitionDuration * 0.5f), 0));\n yield return null;\n }\n shade.color = new Color(shade.color.r, shade.color.g, shade.color.b, 0);\n energyBehaviour.IsReloading = true;\n\n inputs.Player.Interact.performed -= WorldToShelter;\n inputs.Player.Enable();\n\n GetComponent<EnergyBehaviour>().Invincibility(false);\n\n GetComponent<ExitShelter>().enabled = true;\n GetComponent<EnterShelter>().enabled = false;\n\n // do the save\n saveManager.GetComponent<SaveManager>().Save(shelter);\n }\n\n void WorldToShelter(InputAction.CallbackContext ctx)\n {\n StartCoroutine(\"Enter\");\n }\n\n IEnumerator Enter()\n {\n // suspend interactions with both the player and the world\n inputs.Player.Disable();\n GetComponent<EnergyBehaviour>().Invincibility(true);\n\n shelterTag = shelter.tag;\n\n // Play sound\n switch (shelterTag)\n {\n case \"Home\":\n AkSoundEngine.PostEvent(\"Play_Shelter_House_Door_Open\", gameObject);\n break;\n case \"Shed\":\n AkSoundEngine.PostEvent(\"Play_Shelter_Parc_Door_Open\", gameObject);\n break;\n case \"Bar\":\n AkSoundEngine.PostEvent(\"Play_Shelter_Bar_Door_Open\", gameObject);\n break;\n default:\n Debug.LogError(\"Shelter not recognized: \" + shelterTag);\n break;\n }\n\n while (!Mathf.Approximately(shade.color.a, 1))\n {\n shade.color = new Color(shade.color.r, shade.color.g, shade.color.b, Mathf.Min(shade.color.a + Time.deltaTime / (shelterManager.TransitionDuration * 0.5f), 1));\n yield return null;\n }\n\n // Reset Character Position and Speed\n\n if (transform.GetComponent<PlayerFirst>().isActiveAndEnabled)\n {\n Transform warp = shelter.transform.Find(\"Warp Position\");\n transform.GetComponent<PlayerFirst>().ResetTransform(warp.position, warp.rotation.eulerAngles.y);\n transform.GetComponent<PlayerFirst>().SetShelterSpeed();\n }\n\n // Reset Camera\n\n mainCamera.enabled = false;\n GetComponent<PlayerFirst>().IsInsideShelter = true;\n shelter.transform.Find(\"Shelter Camera\").GetComponent<Camera>().enabled = true;\n\n // Reset sound\n\n AkSoundEngine.SetState(\"Dans_Lieu_Repos\", \"Oui\");\n\n shelter.transform.Find(\"Shelter Camera\").GetComponent<AkAudioListener>().enabled = true;\n mainCamera.gameObject.GetComponent<AkAudioListener>().enabled = false;\n\n // Ambiance sound\n if (shelterTag == \"Home\")\n {\n ambianceManager.GetComponent<AmbianceManager>().PlayHomeAmbiance();\n }\n else if (shelterTag == \"Shed\")\n {\n ambianceManager.GetComponent<AmbianceManager>().PlayShedAmbiance();\n }\n else if (shelterTag == \"Bar\")\n {\n ambianceManager.GetComponent<AmbianceManager>().PlayBarAmbiance();\n }\n\n //UI\n compass.GetComponent<Image>().enabled = false;\n //compass.GetComponent<CompassBehavior>().enabled = false;\n compass.SetActive(false);\n\n //GetComponent<PostWwiseAmbiance>().ParkAmbianceEventStop.Post(gameObject);\n //GetComponent<PostWwiseAmbiance>().ShelterAmbianceEventPlay.Post(gameObject);\n\n while (shade.color.a > 0)\n {\n shade.color = new Color(shade.color.r, shade.color.g, shade.color.b, Mathf.Max(shade.color.a - Time.deltaTime / (shelterManager.TransitionDuration * 0.5f), 0));\n yield return null;\n }\n shade.color = new Color(shade.color.r, shade.color.g, shade.color.b, 0);\n energyBehaviour.IsReloading = true;\n\n inputs.Player.Interact.performed -= WorldToShelter;\n inputs.Player.Enable();\n\n GetComponent<ExitShelter>().enabled = true;\n GetComponent<EnterShelter>().enabled = false;\n\n GetComponent<EnergyBehaviour>().Invincibility(false);\n\n // do the save\n saveManager.GetComponent<SaveManager>().Save(shelter);\n }\n\n void OnDisable()\n {\n //inputs.Player.Disable();\n }\n\n private void OnDestroy()\n {\n inputs.Player.Interact.performed -= WorldToShelter;\n }\n\n} //FINISH\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6122375726699829, "avg_line_length": 30.571969985961914, "blob_id": "088193dc98f4b1041f8982ad68c58da6929adcff", "content_id": "dbf96236f2a78129c5c78be0c7ad26f65631c6bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8337, "license_type": "no_license", "max_line_length": 117, "num_lines": 264, "path": "/SoA-Unity/Assets/Scripts/VisionBehaviour.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class VisionBehaviour : MonoBehaviour\n{\n static int instanceCount = 0;\n\n [Space]\n [Header(\"Character Camera\")]\n\n [SerializeField]\n [Tooltip(\"The offset to the head\")]\n private Vector3 cameraOffset = Vector3.zero;\n // = new Vector(0, 0.3f, 0.2f); // Inside Offset\n // = new Vector(0, 0.4f, 0.45f); // Outside Offset\n\n [SerializeField]\n [Tooltip(\"The angle to the head\")]\n private Vector3 cameraAngle = Vector3.zero;\n // = new Vector(0, 0, 0); // Inside Angle\n // = new Vector(30, 180, 0); // Outside Angle\n\n [SerializeField]\n [Tooltip(\"The texture to render the view\")]\n private RenderTexture targetTexture;\n\n private Camera visionCamera;\n private Transform headMesh;\n private GameObject head;\n //[SerializeField]\n //private GameObject characterMesh;\n\n [SerializeField]\n private LayerMask ignoreMask;\n\n [Space]\n [Header(\"Brightness Detector\")]\n\n [SerializeField]\n [Tooltip(\"How many times per second the vision is updated (in Hz)\")]\n private float refreshFrequency = 4;\n\n private enum FILTERMODE { BlackAndWhite, GreyLevels }\n [SerializeField]\n [Tooltip(\"Apply a black and white or a grey levels filter\")]\n private FILTERMODE filterMode = FILTERMODE.BlackAndWhite;\n\n [SerializeField]\n [Range(0, 255)]\n [Tooltip(\"When using black and white filter, specify the brightness limit between black and white\")]\n private float blackAndWhiteThreshold = 220f;\n\n [SerializeField]\n [Range(0,1)]\n [Tooltip(\"Brightness level limit before character starts feeling damage in normal mode\")]\n private float normalBrightnessThreshold = 0.7f;\n\n [SerializeField]\n [Range(0, 1)]\n [Tooltip(\"Brightness level limit before character starts feeling damage in protected mode\")]\n private float protectedBrightnessThreshold = 0.8f;\n\n private float brightnessThreshold;\n public float BrightnessThreshold { get { return brightnessThreshold; } }\n\n [SerializeField]\n [Range(0, 1)]\n [Tooltip(\"Brightness level limit before character start feeling disconfort\")]\n private float uncomfortableBrightnessThreshold = 0.6f;\n\n [SerializeField]\n [Range(0, 100)]\n [Tooltip(\"Damages applied to the character when threshold is reached\")]\n private float brightnessDamage = 10f;\n\n [SerializeField]\n [Tooltip(\"Are we in the nighttime ?\")]\n private bool nighttime = false;\n\n [Space]\n [Header(\"References\")]\n\n [SerializeField]\n private GameObject player;\n\n [SerializeField]\n private GameObject esthesia;\n\n [SerializeField]\n private EnergyBehaviour energyBehaviour;\n\n [SerializeField]\n private DebuggerBehaviour debuggerBehaviour;\n\n private delegate void BrightnessThresholdHandler(float b);\n private event BrightnessThresholdHandler brightnessThresholdEvent;\n\n private event BrightnessThresholdHandler uncomfortableThresholdEvent;\n\n public delegate void GrayscaleChangedHandler(GameObject sender, Texture2D t, float p);\n public event GrayscaleChangedHandler grayScaleChangedEvent;\n\n void Awake()\n {\n\n }\n\n // Start is called before the first frame update\n void Start()\n {\n if(esthesia.GetComponent<Animator>() == null)\n {\n throw new System.NullReferenceException(\"No Animator attached to Esthesia game object\");\n }\n if (esthesia.GetComponent<EsthesiaAnimation>() == null)\n {\n throw new System.NullReferenceException(\"No Esthesia animation script attached to Esthesia game object\");\n }\n brightnessThreshold = normalBrightnessThreshold;\n brightnessThresholdEvent += energyBehaviour.DecreaseEnergy;\n grayScaleChangedEvent += debuggerBehaviour.DisplayBrightness;\n\n InjectCameraToFBX(); // create the camera inside the script\n\n if (visionCamera.targetTexture != null)\n {\n StartCoroutine(\"UpdateVision\");\n }\n }\n\n // Update is called once per frame\n void Update()\n {\n //head.transform.position = headMesh.transform.position + cameraOffset;\n //head.transform.rotation = Quaternion.Euler(cameraAngle) * headMesh.transform.rotation;\n }\n\n private IEnumerator UpdateVision()\n {\n for (; ; )\n {\n Texture2D t2D = RenderTexturetoTexture2D(visionCamera.targetTexture);\n ComputeBrightnessAverage(t2D);\n\n yield return new WaitForSeconds(1f / refreshFrequency);\n }\n }\n\n private Texture2D RenderTexturetoTexture2D (RenderTexture rt)\n {\n RenderTexture.active = rt;\n Texture2D t2D = new Texture2D(rt.width, rt.height, TextureFormat.RGB24, false);\n t2D.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);\n t2D.Apply();\n\n return t2D;\n }\n\n /* Many methods to compute brightness level of a frame */\n\n private void ComputeBrightnessAverage (Texture2D t2D)\n {\n float sum = 0;\n\n for (int i=0; i < t2D.width; i++)\n {\n for (int j=0; j< t2D.height; j++)\n {\n if (filterMode == FILTERMODE.BlackAndWhite)\n {\n if (t2D.GetPixel(i, j).grayscale * 255 >= blackAndWhiteThreshold)\n {\n t2D.SetPixel(i, j, new Color(1, 1, 1));\n sum++;\n }\n else\n {\n t2D.SetPixel(i, j, new Color(0, 0, 0));\n }\n }\n else if (filterMode == FILTERMODE.GreyLevels)\n {\n float grey = t2D.GetPixel(i, j).grayscale;\n t2D.SetPixel(i, j, new Color(grey,grey,grey));\n sum += grey;\n }\n }\n }\n\n if (nighttime)\n {\n if (sum >= uncomfortableBrightnessThreshold * t2D.width * t2D.height)\n {\n if (!player.GetComponent<PlayerFirst>().IsInsideShelter)\n {\n player.GetComponent<PlayerFirst>().EyesUncomfortableSources++;\n }\n }\n else\n {\n player.GetComponent<PlayerFirst>().IsUncomfortableEyes = false;\n }\n\n if (sum >= brightnessThreshold * t2D.width * t2D.height)\n {\n if (!player.GetComponent<PlayerFirst>().IsInsideShelter)\n {\n brightnessThresholdEvent(brightnessDamage);\n\n // Handle animations\n if (!player.GetComponent<PlayerFirst>().IsDamagedEars)\n {\n player.GetComponent<PlayerFirst>().EyesDamageSources++;\n //player.GetComponent<PlayerFirst>().IsDamagedEyes = true;\n // Set animation layer weight\n //esthesia.GetComponent<EsthesiaAnimation>().SelectEyesDamageLayer();\n }\n }\n }\n }\n\n t2D.Apply();\n grayScaleChangedEvent(this.gameObject, t2D, sum / (t2D.width * t2D.height));\n }\n\n public void CoverEyes()\n {\n brightnessThreshold = protectedBrightnessThreshold;\n }\n\n public void UncoverEyes()\n {\n brightnessThreshold = normalBrightnessThreshold;\n }\n\n private void InjectCameraToFBX()\n {\n headMesh = GameObject.FindWithTag(\"Head\").transform;\n if(headMesh == null)\n {\n throw new System.Exception(\"Camera Character Error : No head element found\");\n }\n head = new GameObject();\n head.name = \"Camera\";\n head.transform.position = headMesh.transform.position + transform.rotation * cameraOffset;\n head.transform.rotation = transform.rotation * Quaternion.Euler(cameraAngle);\n\n visionCamera = head.AddComponent<Camera>();\n visionCamera.nearClipPlane = 0.1f;\n visionCamera.targetTexture = targetTexture;\n visionCamera.cullingMask = ~ignoreMask;\n //visionCamera.targetDisplay = ++instanceCount;\n head.transform.SetParent(headMesh);\n }\n\n /* For user options */\n\n public void SetBrightnessDamage(float brightnessDamage)\n {\n this.brightnessDamage = brightnessDamage;\n }\n\n} // FINISH\n" }, { "alpha_fraction": 0.6504854559898376, "alphanum_fraction": 0.6699029207229614, "avg_line_length": 26.32653045654297, "blob_id": "e60a6c1a88c7ba120339eb6f59fd4ec268571b14", "content_id": "1567f322ced693f740e9577b2b175fb8495e50b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1341, "license_type": "no_license", "max_line_length": 116, "num_lines": 49, "path": "/SoA-Unity/Assets/LevelStreets/Scripts/Vehicles/SplineDebugger.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing Pixelplacement;\n\npublic class SplineDebugger : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The first spline to debug\")]\n private Spline spline1;\n\n [SerializeField]\n [Tooltip(\"Percentage on the first spline\")]\n [Range(0,1)]\n private float percentage1 = 0f;\n\n [SerializeField]\n [Tooltip(\"The second spline to debug\")]\n private Spline spline2;\n\n [SerializeField]\n [Tooltip(\"Percentage on the second spline\")]\n [Range(0, 1)]\n private float percentage2 = 0f;\n\n // Start is called before the first frame update\n void Start()\n {\n\n }\n\n // Update is called once per frame\n void Update()\n {\n\n }\n\n private void OnValidate()\n {\n transform.GetChild(0).position = spline1.GetPosition(percentage1, true);\n transform.GetChild(0).transform.rotation = Quaternion.LookRotation(spline1.GetDirection(percentage1, true));\n\n transform.GetChild(1).transform.position = spline2.GetPosition(percentage2, true);\n transform.GetChild(1).transform.rotation = Quaternion.LookRotation(spline2.GetDirection(percentage2, true));\n \n Debug.Log(\"On spline \" + spline1.name + \" : \" + percentage1);\n Debug.Log(\"On spline \" + spline2.name + \" : \" + percentage2);\n }\n}\n" }, { "alpha_fraction": 0.6652904748916626, "alphanum_fraction": 0.6673547625541687, "avg_line_length": 30.398147583007812, "blob_id": "7cea12a1d5a57626124fcbec70eca1c347740e6e", "content_id": "ff8f9e9dacdeea265d8fc8d7154db301a4e5b8f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3393, "license_type": "no_license", "max_line_length": 157, "num_lines": 108, "path": "/SoA-Unity/Assets/Scripts/NightRespawn.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.UI;\n\npublic class NightRespawn : MonoBehaviour\n{\n private Inputs inputs;\n\n private Camera mainCamera;\n\n [SerializeField]\n private GameObject cameraHolder;\n\n [SerializeField]\n private GameObject respawnPoint;\n\n private GameObject ambianceManager;\n\n private GameObject compass;\n\n private Image shade;\n\n private float transitionDuration = 2.0f;\n\n // Start is called before the first frame update\n void Start()\n {\n inputs = InputsManager.Instance.Inputs;\n mainCamera = GameObject.FindGameObjectWithTag(\"MainCamera\").GetComponent<Camera>();\n ambianceManager = GameObject.FindGameObjectWithTag(\"AmbianceManager\");\n compass = GameObject.FindGameObjectWithTag(\"Compass\");\n shade = GameObject.FindGameObjectWithTag(\"Fade\").GetComponent<Image>();\n\n StartCoroutine(Respawn());\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n IEnumerator Respawn()\n {\n // suspend interaction both with player and world\n inputs.Player.Disable();\n\n GetComponent<EnergyBehaviour>().Invincibility(true);\n\n GetComponent<PlayerFirst>().IsInsideShelter = false;\n\n // Reset Character Position and Speed\n\n if (transform.GetComponent<PlayerFirst>().isActiveAndEnabled)\n {\n Transform warp = respawnPoint.transform; // change to supermarket position\n transform.GetComponent<PlayerFirst>().ResetTransform(warp.position, warp.rotation.eulerAngles.y);\n transform.GetComponent<PlayerFirst>().ResetSpeed();\n }\n\n // Reset Camera\n\n GetComponent<PlayerFirst>().IsInsideShelter = false;\n mainCamera.enabled = true;\n\n if (cameraHolder.GetComponent<CameraFollow>().isActiveAndEnabled)\n {\n cameraHolder.GetComponent<CameraFollow>().ResetCameraToFrontView();\n }\n //shelterCamera.enabled = false;\n\n // Wait for one frame to have a correct camera angle\n yield return new WaitForEndOfFrame();\n\n // Reset sound\n mainCamera.gameObject.GetComponent<AkAudioListener>().enabled = true;\n //shelterCamera.gameObject.GetComponent<AkAudioListener>().enabled = false;\n\n AkSoundEngine.SetState(\"Dans_Lieu_Repos\", \"Non\");\n\n // Ambiance sound\n ambianceManager.GetComponent<AmbianceManager>().PlayCityAmbiance();\n\n // UI\n compass.GetComponent<Image>().enabled = true;\n compass.SetActive(true);\n\n //GetComponent<PostWwiseAmbiance>().ParkAmbianceEventStop.Post(gameObject);\n //GetComponent<PostWwiseAmbiance>().ShelterAmbianceEventPlay.Post(gameObject);\n\n while (shade.color.a > 0)\n {\n shade.color = new Color(shade.color.r, shade.color.g, shade.color.b, Mathf.Max(shade.color.a - Time.deltaTime / (transitionDuration * 0.5f), 0));\n yield return null;\n }\n shade.color = new Color(shade.color.r, shade.color.g, shade.color.b, 0);\n //energyBehaviour.IsReloading = false;\n\n //inputs.Player.Interact.performed -= WorldToShelter;\n inputs.Player.Enable();\n\n GetComponent<EnergyBehaviour>().Invincibility(false);\n\n GetComponent<ExitShelter>().enabled = false;\n GetComponent<EnterShelter>().enabled = false;\n }\n}\n" }, { "alpha_fraction": 0.6361904740333557, "alphanum_fraction": 0.6380952596664429, "avg_line_length": 17.75, "blob_id": "f6b2e019e6c2c888c7ba6fa55702e16054e9b388", "content_id": "6157a1a0d3d6533fc41874e6b22339d15a31349f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 527, "license_type": "no_license", "max_line_length": 60, "num_lines": 28, "path": "/SoA-Unity/Assets/LevelStreets/Scripts/Shopping/Shop.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing Pixelplacement;\n\npublic class Shop : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"List of spline coming from this shop\")]\n private Spline[] exitPaths;\n\n // Start is called before the first frame update\n void Start()\n {\n \n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n public Spline GetExitPath()\n {\n return exitPaths[Random.Range(0, exitPaths.Length)];\n }\n}\n" }, { "alpha_fraction": 0.619131326675415, "alphanum_fraction": 0.6213909387588501, "avg_line_length": 28.28676414489746, "blob_id": "c7c66074431dc2b8e999825abc9077101b3ddbd8", "content_id": "cbfcb861a51bf86ec6c5192ffd5c7e4ab78255c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3986, "license_type": "no_license", "max_line_length": 129, "num_lines": 136, "path": "/SoA-Unity/Assets/LevelStreets/Scripts/Shopping/Client.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using UnityEngine;\nusing System.Collections;\nusing System.Collections.Generic;\nusing Pixelplacement;\n\npublic enum CLIENTSTATE { WALKING, FREEZE, SHOPPING }\n\npublic class Client : MonoBehaviour\n{\n private Spline spline;\n private float percentage;\n\n private float speed;\n private float walkingSpeed;\n private float minShoppingDuration;\n private float maxShoppingDuration;\n\n [Header(\"Ground\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"The raycaster\")]\n private Transform raycaster;\n\n [SerializeField]\n [Tooltip(\"The ground level\")]\n private Transform groundLevel;\n private float groundOffset;\n\n private CLIENTSTATE clientState;\n public CLIENTSTATE ClientState { get { return clientState; } set { clientState = value; } }\n\n private void Awake()\n {\n groundOffset = transform.position.y - groundLevel.transform.position.y;\n }\n private void Start()\n {\n\n }\n\n private void Update()\n {\n if (clientState == CLIENTSTATE.WALKING)\n {\n /* UPDATE PERCENTAGE */\n\n percentage = Mathf.Min(percentage + (speed * Time.deltaTime) / spline.Length, 1);\n\n /* UPDATE TRANSFORM */\n\n Vector3 position = spline.GetPosition(percentage);\n transform.position = StickToTheGround(position);\n transform.rotation = Quaternion.LookRotation(spline.GetDirection(percentage));\n\n /* SHOPPING CONDITION */\n\n if (percentage == 1)\n {\n GetComponent<Animator>().SetBool(\"IsWalking\", false);\n ClientState = CLIENTSTATE.SHOPPING;\n StartCoroutine(\"GoShopping\");\n }\n }\n }\n\n private IEnumerator GoShopping()\n {\n yield return new WaitForSeconds(Random.Range(minShoppingDuration, maxShoppingDuration));\n\n // Reset walking\n percentage = 0;\n ClientState = CLIENTSTATE.WALKING;\n GetComponent<Animator>().SetBool(\"IsWalking\", true);\n }\n\n public void SetConstants(float speed, float minShoppingDuration, float maxShoppingDuration)\n {\n this.walkingSpeed = speed;\n this.minShoppingDuration = minShoppingDuration;\n this.maxShoppingDuration = maxShoppingDuration;\n\n this.speed = this.walkingSpeed;\n }\n\n public void Initialize(Spline startSpline, float startPercentage, CLIENTSTATE startState)\n {\n spline = startSpline;\n clientState = startState;\n percentage = startPercentage;\n GetComponent<Animator>().SetBool(\"IsWalking\", clientState == CLIENTSTATE.WALKING);\n }\n\n /* PHYSICS RELATED FUNCTIONS */\n\n private Vector3 StickToTheGround(Vector3 position)\n {\n LayerMask mask = LayerMask.GetMask(\"AsphaltGround\") | LayerMask.GetMask(\"GrassGround\") | LayerMask.GetMask(\"SoilGround\");\n if (Physics.Raycast(raycaster.transform.position, Vector3.down, out RaycastHit hit, Mathf.Infinity, mask))\n {\n return new Vector3(position.x, hit.point.y + groundOffset, position.z);\n }\n return position;\n }\n\n private void OnTriggerEnter(Collider other)\n {\n if(other.transform.CompareTag(\"Shop\"))\n {\n // Get the next shop to go to\n spline = other.GetComponent<Shop>().GetExitPath();\n }\n\n if (other.transform.CompareTag(\"Player\"))\n {\n if (clientState != CLIENTSTATE.FREEZE)\n {\n Debug.Log(\"Player me bloque, je m'arrête\");\n clientState = CLIENTSTATE.FREEZE;\n GetComponent<Animator>().SetBool(\"IsWalking\", false);\n speed = 0;\n }\n }\n }\n\n private void OnTriggerExit(Collider other)\n {\n if (other.transform.CompareTag(\"Player\"))\n {\n Debug.Log(\"Player est parti, je remarche\");\n GetComponent<Animator>().SetBool(\"IsWalking\", true);\n clientState = CLIENTSTATE.WALKING;\n speed = walkingSpeed;\n }\n }\n}\n" }, { "alpha_fraction": 0.6499999761581421, "alphanum_fraction": 0.6553571224212646, "avg_line_length": 25.66666603088379, "blob_id": "75cea3e9963005276e48cffa35acc49a53e75c36", "content_id": "b69772f8ec8e5d3bf6f210bb709b4e162dead912", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 562, "license_type": "no_license", "max_line_length": 127, "num_lines": 21, "path": "/SoA-Unity/Assets/Resources/Scripts/VerreOpaque.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class VerreOpaque : MonoBehaviour\n{\n [SerializeField]\n Light l;\n Material mat;\n // Start is called before the first frame update\n void Start()\n {\n mat = GetComponent<MeshRenderer>().material;\n }\n void Update()\n {\n mat.SetVector(\"_Light_Pos\", new Vector4(l.transform.position.x, l.transform.position.y, l.transform.position.z, 1.0f));\n mat.SetFloat(\"_Intensity\", l.intensity);\n mat.SetColor(\"_Color\",l.color);\n }\n}\n" }, { "alpha_fraction": 0.6569037437438965, "alphanum_fraction": 0.6658697128295898, "avg_line_length": 33.14285659790039, "blob_id": "bacb949763e192caf3d3fb653be902576fa125ae", "content_id": "36a2a7780645acd09c1367cc104dfc71cae6a6ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1675, "license_type": "no_license", "max_line_length": 126, "num_lines": 49, "path": "/SoA-Unity/Assets/Scripts/Menus/FitBackground.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.UI;\n\npublic class FitBackground : MonoBehaviour\n{\n void Awake()\n {\n\n }\n\n // Start is called before the first frame update\n void Start()\n {\n\n }\n\n // Update is called once per frame\n void Update()\n {\n Image background = GetComponent<Image>();\n if (background == null) return;\n\n background.SetNativeSize();\n transform.localScale = new Vector3(1, 1, 1);\n float width = background.rectTransform.rect.size.x;\n float height = background.rectTransform.rect.size.y;\n\n // Set the anchor at the center of the screen and center the image on it\n background.rectTransform.anchorMin = new Vector2(0.5f, 0.5f);\n background.rectTransform.anchorMax = new Vector2(0.5f, 0.5f);\n background.rectTransform.anchoredPosition = Vector2.zero;\n\n // Check if the screen's ratio is higher or wider than the image's one\n if ((float)Screen.width / Screen.height > width / height)\n {\n // then match screen's width\n background.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, Screen.width);\n background.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height * Screen.width / width);\n }\n else\n {\n // then match screen's height\n background.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, Screen.height);\n background.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, width * Screen.height / height);\n }\n }\n}\n" }, { "alpha_fraction": 0.5767869353294373, "alphanum_fraction": 0.5850719213485718, "avg_line_length": 29.174999237060547, "blob_id": "ec8f32ec2e4b08080220891c242e16b0670f3eb2", "content_id": "83430240665ba5229fd2aa4b6e8b6ae8da3b9145", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 13279, "license_type": "no_license", "max_line_length": 128, "num_lines": 440, "path": "/SoA-Unity/Assets/Scripts/FieldOfView.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing System.Linq;\n\npublic class FieldOfView : MonoBehaviour\n{\n [Space]\n [Header(\"General Crowd Detector Settings\")]\n [Space]\n\n [SerializeField]\n private float meshResolution;\n\n [SerializeField]\n public LayerMask targetMask;\n\n [SerializeField]\n public LayerMask obstacleMask;\n\n private List<Transform> frontVisibleTargets = new List<Transform>();\n private List<Transform> sideVisibleTargets = new List<Transform>();\n private List<Transform> backVisibleTargets = new List<Transform>();\n\n\n [SerializeField]\n private EnergyBehaviour energyBehaviour;\n\n private delegate void CrowdThresholdHandler(float b);\n private event CrowdThresholdHandler crowdThresholdEvent;\n\n [Space]\n [Header(\"Animation Damage Settings\")]\n [Space]\n\n [SerializeField]\n private float idleAnimDanger;\n [SerializeField]\n private float moveAnimDanger, danceAnimDanger; \n\n [Space]\n [Header(\"Front Crowd Detector Settings\")]\n [Space]\n\n [SerializeField]\n [Range(0, 360)]\n public float frontViewAngle;\n\n [SerializeField]\n private float frontViewRadius, totalFrontTargets, frontPow, frontCrowdInfo, frontDangerThreshold, crowdFrontDanger;\n\n [SerializeField]\n [Range(0, 100)]\n private float crowdFrontDamage;\n\n\n\n [Space]\n [Header(\"Side Crowd Detector Settings\")]\n [Space]\n\n [SerializeField]\n [Range(0, 360)]\n public float sideViewAngle;\n\n [SerializeField]\n private float sideViewRadius, totalSideTargets, sidePow, sideCrowdInfo, sideDangerThreshold, crowdSideDanger;\n\n [SerializeField]\n [Range(0, 100)]\n private float crowdSideDamage;\n\n\n\n [Space]\n [Header(\"BackCrowdDetector Settings\")]\n [Space]\n\n [SerializeField]\n [Range(0, 360)]\n public float backViewAngle;\n\n [SerializeField]\n private float backViewRadius, totalBackTargets, backPow, backCrowdInfo, backDangerThreshold, crowdBackDanger;\n\n [SerializeField]\n [Range(0, 100)]\n private float crowdBackDamage;\n\n\n\n\n\n\n // Start is called before the first frame update\n void Start()\n {\n StartCoroutine(\"FindFrontTargetsWithDelay\", .2f);\n\n StartCoroutine(\"FindSideTargetsWithDelay\", .2f);\n\n StartCoroutine(\"FindBackTargetsWithDelay\", .2f);\n\n\n //obstacleMask = ~targetMask;\n obstacleMask = 0;\n\n crowdThresholdEvent += energyBehaviour.DecreaseEnergy;\n }\n\n\n // Update is called once per frame\n void Update()\n {\n //Back View\n //\tDrawTotalFieldOfBackView();\n DrawFieldOfBackView();\n\n //Side View\n //\tDrawTotalFieldOfSideView();\n DrawFieldOfSideView();\n\n //Front View\n //DrawTotalFieldOfFrontView();\n DrawFieldOfFrontView();\n }\n\n IEnumerator FindFrontTargetsWithDelay(float delay)\n {\n while (true)\n {\n yield return new WaitForSeconds(delay);\n FindFrontVisibleTargets();\n }\n }\n\n //Adapt to every Views !!!!\n void FindFrontVisibleTargets()\n {\n frontVisibleTargets.Clear();\n frontCrowdInfo = 0;\n crowdFrontDanger = 0;\n\n\n Collider[] targetsInViewRadius = Physics.OverlapSphere(transform.position, frontViewRadius, targetMask);\n\n for (int i = 0; i < targetsInViewRadius.Length; i++)\n {\n //Debug.Log(\"J'ai \" + targetsInViewRadius.Length + \" cibles dans mon rayon\");\n Transform target = targetsInViewRadius[i].transform;\n Vector3 dirToTarget = (target.position - transform.position).normalized;\n if (Vector3.Angle(transform.forward, dirToTarget) < frontViewAngle / 2)\n {\n float dstToTarget = Vector3.Distance(transform.position, target.position);\n\n if (!Physics.Raycast(transform.position, dirToTarget, dstToTarget, obstacleMask))\n {\n frontVisibleTargets.Add(target);\n Debug.DrawLine(transform.position, target.position, Color.red);\n\n\n frontCrowdInfo += Mathf.Pow((1 - dstToTarget / frontViewRadius), frontPow);\n\n\n //Get NPC's Animation\n /*\n Animator anim = target.GetComponent<Animator>();\n if (anim.GetBool(\"isMoving\") == true)\n {\n crowdFrontDanger += moveAnimDanger * Mathf.Pow((1 - dstToTarget / frontViewRadius), frontPow);\n } else if (anim.GetBool(\"isDancing\") == true)\n {\n crowdFrontDanger += danceAnimDanger * Mathf.Pow((1 - dstToTarget / frontViewRadius), frontPow);\n } else\n {\n crowdFrontDanger += idleAnimDanger * Mathf.Pow((1 - dstToTarget / frontViewRadius), frontPow);\n }*/\n }\n\n // Apply Damage\n /*\n if (crowdFrontDanger > frontDangerThreshold)\n {\n crowdThresholdEvent(crowdFrontDamage);\n }*/\n\n totalFrontTargets = frontVisibleTargets.Count();\n if (totalFrontTargets > frontDangerThreshold) // max 5 persons before it's considered a crowd\n {\n crowdThresholdEvent(crowdFrontDamage);\n }\n }\n }\n }\n\n\n\n IEnumerator FindSideTargetsWithDelay(float delay)\n {\n while (true)\n {\n yield return new WaitForSeconds(delay);\n FindSideVisibleTargets();\n }\n }\n\n //Adapt to every Views !!!!\n void FindSideVisibleTargets()\n {\n sideVisibleTargets.Clear();\n sideCrowdInfo = 0;\n crowdSideDanger = 0;\n\n\n Collider[] targetsInViewRadius = Physics.OverlapSphere(transform.position, sideViewRadius, targetMask);\n\n for (int i = 0; i < targetsInViewRadius.Length; i++)\n {\n Transform target = targetsInViewRadius[i].transform;\n Vector3 dirToTarget = (target.position - transform.position).normalized;\n\n if (Vector3.Angle(transform.forward, dirToTarget) < sideViewAngle / 2\n && Vector3.Angle(transform.forward, dirToTarget) > frontViewAngle / 2)\n {\n float dstToTarget = Vector3.Distance(transform.position, target.position);\n\n if (!Physics.Raycast(transform.position, dirToTarget, dstToTarget, obstacleMask))\n {\n sideVisibleTargets.Add(target);\n Debug.DrawLine(transform.position, target.position, Color.blue);\n\n sideCrowdInfo += Mathf.Pow((1 - dstToTarget / sideViewRadius), sidePow);\n\n\n //Get NPC's Animation \n Animator anim = target.GetComponent<Animator>();\n if (anim.GetBool(\"isMoving\") == true)\n {\n crowdSideDanger += moveAnimDanger * Mathf.Pow((1 - dstToTarget / sideViewRadius), sidePow);\n }\n else if (anim.GetBool(\"isDancing\") == true)\n {\n crowdSideDanger += danceAnimDanger * Mathf.Pow((1 - dstToTarget / sideViewRadius), sidePow);\n }\n else\n {\n crowdSideDanger += idleAnimDanger * Mathf.Pow((1 - dstToTarget / sideViewRadius), sidePow);\n }\n }\n\n\n // Apply Damage\n if (crowdSideDanger > sideDangerThreshold)\n {\n crowdThresholdEvent(crowdSideDamage);\n }\n\n totalSideTargets = sideVisibleTargets.Count();\n }\n }\n }\n\n\n\n\n IEnumerator FindBackTargetsWithDelay(float delay)\n {\n while (true)\n {\n yield return new WaitForSeconds(delay);\n FindBackVisibleTargets();\n }\n }\n\n //Adapt to every Views !!!!\n void FindBackVisibleTargets()\n {\n backVisibleTargets.Clear();\n backCrowdInfo = 0;\n crowdBackDanger = 0;\n\n\n Collider[] targetsInViewRadius = Physics.OverlapSphere(transform.position, backViewRadius, targetMask);\n\n for (int i = 0; i < targetsInViewRadius.Length; i++)\n {\n Transform target = targetsInViewRadius[i].transform;\n Vector3 dirToTarget = (target.position - transform.position).normalized;\n\n if (Vector3.Angle(transform.forward, dirToTarget) < backViewAngle / 2\n && Vector3.Angle(transform.forward, dirToTarget) > sideViewAngle / 2)\n {\n float dstToTarget = Vector3.Distance(transform.position, target.position);\n\n if (!Physics.Raycast(transform.position, dirToTarget, dstToTarget, obstacleMask))\n {\n backVisibleTargets.Add(target);\n Debug.DrawLine(transform.position, target.position, Color.green);\n\n backCrowdInfo += Mathf.Pow((1 - dstToTarget / backViewRadius), backPow);\n\n\n //Get NPC's Animation \n Animator anim = target.GetComponent<Animator>();\n if (anim.GetBool(\"isMoving\") == true)\n {\n crowdBackDanger += moveAnimDanger * Mathf.Pow((1 - dstToTarget / backViewRadius), frontPow);\n }\n else if (anim.GetBool(\"isDancing\") == true)\n {\n crowdBackDanger += danceAnimDanger * Mathf.Pow((1 - dstToTarget / backViewRadius), frontPow);\n }\n else\n {\n crowdBackDanger += idleAnimDanger * Mathf.Pow((1 - dstToTarget / backViewRadius), frontPow);\n }\n }\n\n\n // Apply Damage\n if (crowdBackDanger > backDangerThreshold)\n {\n crowdThresholdEvent(crowdBackDamage);\n }\n\n\n\n totalBackTargets = backVisibleTargets.Count();\n }\n }\n }\n\n\n //FrontView\n /* void DrawTotalFieldOfFrontView()\n\t{\n\n\n\t\tint stepCount = Mathf.RoundToInt(360 * meshResolution);\n\t\tfloat stepAngleSize = 360 / stepCount;\n\n\t\tfor (int i = 0; i <= stepCount; i++)\n\t\t{\n\t\t\tfloat angle = transform.eulerAngles.y - 360 / 2 + stepAngleSize * i;\n\t\t\tDebug.DrawLine(transform.position, transform.position + DirFromAngle(angle, true) * frontViewRadius, Color.white);\n\t\t}\n\t} */\n void DrawFieldOfFrontView()\n {\n\n\n int stepCount = Mathf.RoundToInt(frontViewAngle * meshResolution);\n float stepAngleSize = frontViewAngle / stepCount;\n\n for (int i = 0; i <= stepCount; i++)\n {\n float angle = transform.eulerAngles.y - frontViewAngle / 2 + stepAngleSize * i;\n Debug.DrawLine(transform.position, transform.position + DirFromAngle(angle, true) * frontViewRadius, Color.yellow);\n }\n }\n\n\n //SideView\n /*\tvoid DrawTotalFieldOfSideView()\n {\n\n\n int stepCount = Mathf.RoundToInt(360 * meshResolution);\n float stepAngleSize = 360 / stepCount;\n\n for (int i = 0; i <= stepCount; i++)\n {\n float angle = transform.eulerAngles.y - 360 / 2 + stepAngleSize * i;\n Debug.DrawLine(transform.position, transform.position + DirFromAngle(angle, true) * sideViewRadius, Color.white);\n }\n } */\n void DrawFieldOfSideView()\n {\n\n\n int stepCount = Mathf.RoundToInt(sideViewAngle * meshResolution);\n float stepAngleSize = sideViewAngle / stepCount;\n\n for (int i = 0; i <= stepCount; i++)\n {\n float angle = transform.eulerAngles.y - sideViewAngle / 2 + stepAngleSize * i;\n Debug.DrawLine(transform.position, transform.position + DirFromAngle(angle, true) * sideViewRadius, Color.white);\n }\n }\n\n\n //BackView\n /* void DrawTotalFieldOfBackView()\n\t{\n\n\n\t\tint stepCount = Mathf.RoundToInt(360 * meshResolution);\n\t\tfloat stepAngleSize = 360 / stepCount;\n\n\t\tfor (int i = 0; i <= stepCount; i++)\n\t\t{\n\t\t\tfloat angle = transform.eulerAngles.y - 360 / 2 + stepAngleSize * i;\n\t\t\tDebug.DrawLine(transform.position, transform.position + DirFromAngle(angle, true) * backViewRadius, Color.white);\n\t\t}\n\t} */\n void DrawFieldOfBackView()\n {\n\n\n int stepCount = Mathf.RoundToInt(backViewAngle * meshResolution);\n float stepAngleSize = backViewAngle / stepCount;\n\n for (int i = 0; i <= stepCount; i++)\n {\n float angle = transform.eulerAngles.y - backViewAngle / 2 + stepAngleSize * i;\n Debug.DrawLine(transform.position, transform.position + DirFromAngle(angle, true) * backViewRadius, Color.gray);\n }\n }\n\n\n\n\n public Vector3 DirFromAngle(float angleInDegrees, bool angleIsGlobal)\n {\n if (!angleIsGlobal)\n {\n angleInDegrees += transform.eulerAngles.y;\n }\n return new Vector3(Mathf.Sin(angleInDegrees * Mathf.Deg2Rad), 0, Mathf.Cos(angleInDegrees * Mathf.Deg2Rad));\n }\n\n /* For user options */\n\n public void SetCrowdDamage(float crowdDamage)\n {\n this.crowdFrontDamage = crowdDamage;\n }\n\n\n} // FINISH\n" }, { "alpha_fraction": 0.6421663165092468, "alphanum_fraction": 0.6421663165092468, "avg_line_length": 20.54166603088379, "blob_id": "b83c97ee4121288be904d545f998376b09c01dba", "content_id": "270bfbe14a4047eb5153ac48427e469035bd76b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 519, "license_type": "no_license", "max_line_length": 61, "num_lines": 24, "path": "/SoA-Unity/Assets/Resources/Scripts/Lampadaire.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Lampadaire : MonoBehaviour\n{\n [SerializeField]\n GameObject light;\n Material mat;\n Light l;\n\n // Start is called before the first frame update\n void Start()\n {\n l = light.GetComponent<Light>();\n mat = GetComponent<MeshRenderer>().material;\n }\n public void Update()\n {\n mat.SetFloat(\"height_scale\", transform.localScale.y);\n mat.SetColor(\"_color\", l.color);\n }\n\n}\n" }, { "alpha_fraction": 0.633577287197113, "alphanum_fraction": 0.6463860869407654, "avg_line_length": 25.975309371948242, "blob_id": "1cdb152f67e6cb9172ecaec76147a1f5d83bbc46", "content_id": "df71f82ee66ae5188c9be70ec34bbc535ab3c319", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2188, "license_type": "no_license", "max_line_length": 166, "num_lines": 81, "path": "/SoA-Unity/Assets/LevelStreets/Scripts/Shopping/ClientFactory.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing System.Linq;\nusing Pixelplacement;\n\npublic class ClientFactory : MonoBehaviour\n{\n [Header(\"Shops\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"List of the shops\")]\n private GameObject[] shops;\n\n\n [Header(\"Clients\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"List of the prefabs of the clients\")]\n private GameObject[] clientPrefabs;\n\n [SerializeField]\n [Tooltip(\"Number of clients to spawn\")]\n [Range(0,50)]\n private float clientsNumber = 20;\n\n [SerializeField]\n [Tooltip(\"Speed of the clients\")]\n [Range(1, 50)]\n private float speed = 20;\n\n [SerializeField]\n [Tooltip(\"Minimum shopping duration\")]\n [Range(5, 20)]\n private float minShoppingDuration = 5;\n\n [SerializeField]\n [Tooltip(\"Maximum shopping duration\")]\n [Range(5, 20)]\n private float maxShoppingDuration = 20;\n\n [SerializeField]\n [Tooltip(\"The duration of the freeze\")]\n private float freezeDuration = 1;\n\n // Start is called before the first frame update\n void Start()\n {\n SpawnClients();\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n private void SpawnClients()\n {\n for (int i = 0; i < clientsNumber; i++)\n {\n GameObject clientPrefab = clientPrefabs[Random.Range(0, clientPrefabs.Length)];\n GameObject myShop = shops[Random.Range(0, shops.Length)];\n //CLIENTSTATE myState = (CLIENTSTATE)Random.Range(0, 2);\n CLIENTSTATE myState = CLIENTSTATE.WALKING;\n\n float myStartPercentage = 1f;\n Spline mySpline = null;\n\n mySpline = myShop.GetComponent<Shop>().GetExitPath();\n myStartPercentage = Random.Range(0f, 1f);\n\n GameObject client = Instantiate(clientPrefab, mySpline.GetPosition(myStartPercentage), Quaternion.LookRotation(mySpline.GetDirection(myStartPercentage)));\n\n client.GetComponent<Client>().SetConstants(speed, minShoppingDuration, maxShoppingDuration);\n client.GetComponent<Client>().Initialize(mySpline, myStartPercentage, myState);\n }\n }\n}\n\n" }, { "alpha_fraction": 0.5683605074882507, "alphanum_fraction": 0.569894552230835, "avg_line_length": 34.965518951416016, "blob_id": "0810263e4a99ef86e83bedce238a1ac53b04dd96", "content_id": "c6dc08020ad3585062be78d56bb418d43be682f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5217, "license_type": "no_license", "max_line_length": 143, "num_lines": 145, "path": "/SoA-Unity/Assets/LevelStreets/Scripts/Vehicles/FlowsManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing Pixelplacement;\nusing System.Linq;\n\n[System.Serializable]\nstruct Flow\n{\n public Spline spline;\n public float timeSpan; // in seconds\n public float count;\n public float averageFastSpeed;\n public float averageNormalSpeed;\n public float averageSlowSpeed;\n public float averageCautiousSpeed;\n public float variability;\n}\n\nstruct Schedule\n{\n public float startTime;\n public float endTime;\n public List<float> spawnTimes;\n}\n\npublic class FlowsManager : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The list of the flows\")]\n private Flow[] flows;\n\n [SerializeField]\n [Tooltip(\"The street users manager\")]\n private GameObject streetUsersManager;\n\n private Schedule[] schedules;\n\n private List<float> spawnTimesWatcher;\n private int vehicleCount; //s\n\n // Start is called before the first frame update\n void Start()\n {\n Random.InitState((int)System.DateTime.UtcNow.Ticks);\n\n vehicleCount = streetUsersManager.GetComponent<StreetUsersManager>().StreetUsers.Length;\n\n spawnTimesWatcher = new List<float>();\n\n if(streetUsersManager == null)\n {\n throw new System.ArgumentNullException(\"The FlowsManager is not linked to the StreetUsersManager\");\n }\n if (streetUsersManager.GetComponent<StreetUsersManager>() == null)\n {\n throw new System.ArgumentNullException(\"The StreetUsersManager doesn't have the correct script attached to it\");\n }\n\n schedules = new Schedule[flows.Length];\n for (int i = 0; i < flows.Length; i++)\n {\n if(flows[i].timeSpan == 0)\n {\n throw new System.ArgumentOutOfRangeException(\"Time span of the flow cannot be zero\");\n }\n schedules[i] = new Schedule();\n schedules[i].spawnTimes = new List<float>();\n Reschedule(ref schedules[i], flows[i]);\n }\n }\n\n // Update is called once per frame\n void Update()\n {\n for(int i = 0; i < schedules.Length; i++)\n {\n // if one schedule reach its limit, reschedule immediately\n if (Time.time >= schedules[i].endTime)\n {\n Debug.Log(\"RESCHEDULE NOW FOR \" + flows[i].spline.name + \" !!!!!!!!!!!!! PREVIOUS END TIME : \" + schedules[i].endTime);\n Reschedule(ref schedules[i], flows[i]);\n Debug.Log(\"RESCHEDULED FOR \" + flows[i].spline.name + \" !!!!!!!!!!!!! NEXT END TIME : \" + schedules[i].endTime);\n\n }\n // spawn cars\n foreach(float spawnTime in schedules[i].spawnTimes.ToList()) // work on a copy not to remove item on an foreach enumeration\n {\n if(Time.time >= spawnTime)\n {\n Debug.Log(\"SPAWN CAR ON \" + flows[i].spline.name + \" AT \" + spawnTime);\n schedules[i].spawnTimes.Remove(spawnTime);\n\n float fastSpeed = flows[i].averageFastSpeed + Random.Range(-flows[i].variability, flows[i].variability);\n float normalSpeed = flows[i].averageNormalSpeed + Random.Range(-flows[i].variability, flows[i].variability);\n float slowSpeed = flows[i].averageSlowSpeed + Random.Range(-flows[i].variability, flows[i].variability);\n float cautiousSpeed = flows[i].averageCautiousSpeed + Random.Range(-flows[i].variability, flows[i].variability);\n GameObject car = streetUsersManager.GetComponent<StreetUsersManager>().PopCar();\n if (car != null)\n {\n car.GetComponent<StreetUser>().SpecificSet(flows[i].spline, fastSpeed, normalSpeed, slowSpeed, cautiousSpeed);\n }\n }\n }\n }\n }\n private void Reschedule(ref Schedule schedule, Flow flow)\n {\n // general spawn times\n foreach (float spawnTime in schedule.spawnTimes)\n {\n spawnTimesWatcher.Remove(spawnTime);\n }\n\n schedule.startTime = Time.time;\n schedule.endTime = Time.time + flow.timeSpan;\n schedule.spawnTimes.Clear();\n for (int j = 0; j < flow.count; j++)\n {\n // choose a time that is not too close to a reserved one\n bool accepted = false;\n float time = 0;\n while (!accepted)\n {\n time = Random.Range(Time.time, Time.time + flow.timeSpan); // TO DO : Check if correct\n accepted = true;\n Debug.Log(\"2\");\n \n foreach (float reservedTime in spawnTimesWatcher)\n {\n if (time >= reservedTime - flow.timeSpan / (vehicleCount + 2) && time <= reservedTime + flow.timeSpan / (vehicleCount + 2))\n {\n //accepted = false;\n //break;\n }\n }\n }\n Debug.Log(\"Time reserved : \" + time);\n schedule.spawnTimes.Add(time);\n\n // general spawn times\n spawnTimesWatcher.Add(time);\n }\n }\n}\n" }, { "alpha_fraction": 0.6563786268234253, "alphanum_fraction": 0.6563786268234253, "avg_line_length": 25.2702693939209, "blob_id": "54ec721c219fac93e5f39aa6f55db1b2e0ca51b0", "content_id": "d86d73f55c7b5ab92ff29c8dbe2b37209774ede5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 975, "license_type": "no_license", "max_line_length": 111, "num_lines": 37, "path": "/SoA-Unity/Assets/Scripts/Cutscene/SoundManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class SoundManager : MonoBehaviour\n{\n public delegate void SoundHandler();\n public event SoundHandler SoundPlayedEvent;\n\n // Start is called before the first frame update\n void Start()\n {\n // TO DO : Play cutscene music\n //AkSoundEngine.PostEvent(\"Play_Music_Cutscene\", gameObject);\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n public void PlaySound(string type, string id)\n {\n // TO DO : Set the data in the JSON file to match the Wwise name convention\n // AkSoundEngine.PostEvent(id, gameObject, (uint)AkCallbackType.AK_EndOfEvent, CallbackFunction, null);\n\n // Test only with global sound !\n SoundPlayedEvent();\n }\n\n void CallbackFunction(object in_cookie, AkCallbackType in_type, object in_info)\n {\n Debug.Log(\"Son joué\");\n SoundPlayedEvent();\n }\n}\n" }, { "alpha_fraction": 0.5860491991043091, "alphanum_fraction": 0.5860491991043091, "avg_line_length": 22.958904266357422, "blob_id": "980491065fb575ca39c6393fa2c40a9646b87d65", "content_id": "a642972d1b67489917cbb74f70a1748a7275f3f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1752, "license_type": "no_license", "max_line_length": 93, "num_lines": 73, "path": "/SoA-Unity/Assets/Scripts/UI/TransitionScript.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class TransitionScript : MonoBehaviour\n{\n private static GameObject singleton;\n\n private GameObject gameManager;\n\n private bool nightDone;\n private bool creditsDone;\n\n private void Awake()\n {\n // Must exist between scenes to achieve transitions\n if (singleton == null)\n {\n singleton = transform.parent.gameObject;\n DontDestroyOnLoad(transform.parent.gameObject); // save all canvas\n }\n else if (singleton != transform.parent.gameObject)\n {\n Destroy(transform.parent.gameObject); // destroy all canvas\n return;\n }\n\n gameManager = GameObject.FindGameObjectWithTag(\"GameManager\");\n\n if (gameManager == null)\n {\n throw new System.NullReferenceException(\"Missing reference to the game manager\");\n }\n }\n\n // Start is called before the first frame update\n void Start()\n {\n nightDone = false;\n creditsDone = false;\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n public void TriggerNight()\n {\n if (!nightDone)\n {\n Debug.Log(\"Fin de l'anim de fade out avant la night\");\n gameManager.GetComponent<GameManager>().GoToNight();\n nightDone = true;\n }\n }\n\n public void TriggerCredits()\n {\n if (!creditsDone)\n {\n Debug.Log(\"Fin de l'anim de fade out avant les crédits\");\n gameManager.GetComponent<GameManager>().DisplayCredits();\n creditsDone = true;\n }\n }\n\n public void DestroySingleton()\n {\n singleton = null; \n }\n}\n" }, { "alpha_fraction": 0.611716628074646, "alphanum_fraction": 0.6185286045074463, "avg_line_length": 24.310344696044922, "blob_id": "c6a313df5891448dea58b6d00bf1c00fbacb54ad", "content_id": "13aa3a6acc0d4a23daf620c538003ad98a1989d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 736, "license_type": "no_license", "max_line_length": 78, "num_lines": 29, "path": "/SoA-Unity/Assets/LevelStreets/Scripts/MovingWalls.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class MovingWalls : MonoBehaviour\n{\n private float amplitude = 5;\n private float speed = 1;\n private float accumulator = 0;\n private int direction = 1;\n // Start is called before the first frame update\n void Start()\n {\n \n }\n\n // Update is called once per frame\n void Update()\n {\n accumulator += direction * Time.deltaTime;\n if(Mathf.Abs(accumulator) >= amplitude)\n {\n accumulator = direction * amplitude;\n direction = -direction;\n }\n Vector3 move = transform.forward * Time.deltaTime * speed * direction;\n transform.position += move;\n }\n}\n" }, { "alpha_fraction": 0.6094890236854553, "alphanum_fraction": 0.6222627758979797, "avg_line_length": 30.01886749267578, "blob_id": "96d34333661c9c60a82c859e92502a7eeb53beac", "content_id": "3e88f7e8faf19941d75690a9a51bcabb96922213", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1646, "license_type": "no_license", "max_line_length": 170, "num_lines": 53, "path": "/SoA-Unity/Assets/Scripts/UI/DoorMessage.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.InputSystem;\nusing UnityEngine.UI;\nusing UnityEngine.SceneManagement;\n\npublic class DoorMessage : MonoBehaviour\n{\n Inputs inputs;\n\n // Start is called before the first frame update\n void Start()\n {\n inputs = InputsManager.Instance.Inputs;\n if (SceneManager.GetActiveScene().name == \"GameElise\")\n {\n transform.GetChild(0).GetComponent<Text>().text = \"Press \" + inputs.Player.Interact.GetBindingDisplayString() + \" To Enter\";\n }\n if (SceneManager.GetActiveScene().name == \"GameNight\")\n {\n transform.GetChild(0).GetComponent<Text>().text = \"Closed at night\";\n }\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n private void OnTriggerEnter(Collider other)\n {\n if(other.CompareTag(\"Player\"))\n {\n // Display message\n // transform.GetChild(0).GetComponent<Text>().color = new Color(1, 1, 1, 1);\n transform.GetChild(0).GetComponent<Animation>().Play(\"DoorTextFadeIn\");\n\n //transform.rotation = Quaternion.Euler(0,180,0) * Quaternion.LookRotation(Vector3.ProjectOnPlane(other.transform.position - transform.position, Vector3.up));\n }\n }\n\n private void OnTriggerExit(Collider other)\n {\n if(other.CompareTag(\"Player\"))\n {\n // Hide message\n // transform.GetChild(0).GetComponent<Text>().color = new Color(1, 1, 1, 1);\n transform.GetChild(0).GetComponent<Animation>().Play(\"DoorTextFadeOut\");\n }\n }\n}\n" }, { "alpha_fraction": 0.6063348650932312, "alphanum_fraction": 0.6102941036224365, "avg_line_length": 29.482759475708008, "blob_id": "a64d98a8108ee72bdce2531ddab5b98a88f3bb5e", "content_id": "8928e251acee5abd85718d1c045b729f9d12fd6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1770, "license_type": "no_license", "max_line_length": 136, "num_lines": 58, "path": "/SoA-Unity/Assets/LevelStreets/Scripts/JamCar.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class JamCar : MonoBehaviour\n{\n private readonly float minDelay = 2; // seconds\n private readonly float maxDelay = 4; // seconds\n\n [SerializeField]\n [Tooltip(\"Reference to the zone manager\")]\n private GameObject zoneManager;\n\n [Header(\"VFX\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"VFX to play when loud sound is emitted\")]\n private GameObject loudVFX;\n\n // Start is called before the first frame update\n void Start()\n {\n Debug.Assert(loudVFX != null);\n loudVFX.GetComponent<ParticleSystem>().Stop();\n\n if (zoneManager == null)\n {\n throw new System.NullReferenceException(\"No reference to the zone manager on \" + transform.name);\n }\n // Define which car horn type to use\n AkSoundEngine.SetSwitch(\"Klaxons\", new string[5]{ \"A\", \"B\", \"C\", \"D\", \"E\" }[Random.Range(0, 5)], gameObject);\n StartCoroutine(\"CarHornCountdown\");\n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n private IEnumerator CarHornCountdown()\n {\n float delay;\n for (; ; )\n {\n delay = Random.Range(minDelay, maxDelay);\n yield return new WaitForSeconds(delay);\n if (zoneManager.GetComponent<ZoneManager>().PlayerZone != ZoneManager.ZONE.PARK) // TO DO : Update when there are more zones\n {\n AkSoundEngine.PostEvent(\"Play_Klaxons\", gameObject);\n }\n loudVFX.GetComponent<ParticleSystem>().Play();\n yield return new WaitForSeconds(0.5f); // How long last a car horn ? make a guess\n loudVFX.GetComponent<ParticleSystem>().Stop();\n }\n }\n}\n" }, { "alpha_fraction": 0.6742313504219055, "alphanum_fraction": 0.6764275431632996, "avg_line_length": 27.45833396911621, "blob_id": "7fd7da264c726f66d742c48b9b907970c060f766", "content_id": "ae27e3b063074c1c8e8aab5d0098fabac7786051", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1368, "license_type": "no_license", "max_line_length": 103, "num_lines": 48, "path": "/SoA-Unity/Assets/Scripts/UI/MessageManager.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.UI;\nusing UnityEngine.InputSystem;\n\npublic class MessageManager : MonoBehaviour\n{\n Inputs inputs;\n\n private GameObject tutorialCanvas;\n public GameObject TutorialCanvas { get { return tutorialCanvas; } }\n\n private void Awake()\n {\n inputs = InputsManager.Instance.Inputs;\n\n tutorialCanvas = GameObject.FindGameObjectWithTag(\"TutorialCanvas\");\n if (tutorialCanvas == null)\n {\n throw new System.NullReferenceException(\"Missing a TutorialCanvas in the scene\");\n }\n }\n\n // Start is called before the first frame update\n void Start()\n {\n \n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n\n public void DisplayMessage(string message)\n {\n // TO DO : Ensure no message are overlapping when triggered close to each other\n\n message = message\n .Replace(\"(eyeprotectkey)\", inputs.Player.ProtectEyes.GetBindingDisplayString())\n .Replace(\"(earprotectkey)\", inputs.Player.ProtectEars.GetBindingDisplayString());\n\n tutorialCanvas.transform.GetChild(0).transform.GetChild(1).GetComponent<Text>().text = message;\n tutorialCanvas.transform.GetChild(0).GetComponent<Animation>().Play(\"CanvasGroupFadeInOut\");\n }\n}\n" }, { "alpha_fraction": 0.6349607110023499, "alphanum_fraction": 0.6422559022903442, "avg_line_length": 33.61165237426758, "blob_id": "d8d021c24d6ad47362f844f06e3fa617fb7faf49", "content_id": "92d7fa856936ff7ca3544d839e431edf5bf91218", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3566, "license_type": "no_license", "max_line_length": 172, "num_lines": 103, "path": "/SoA-Unity/Assets/Scripts/Sound/PostWwiseEventBreath.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class PostWwiseEventBreath : MonoBehaviour\n{\n [SerializeField]\n private AK.Wwise.Event MyEvent;\n\n [SerializeField]\n private GameObject player;\n\n private float breathPerMinute;\n private float breathPerMinuteNext;\n\n private const float transitionSpeedUp = 100f; //= 6f;\n private const float transitionSpeedDown = 100f; //= 2f;\n\n private const float breathPerMinuteIdle = 15;\n private const float breathPerMinuteRunning = 15;\n private const float breathPerMinuteHurry = 45;\n private const float breathPerMinuteProtected = 45;\n\n // Use this for initialization.\n void Start()\n {\n if (player == null)\n {\n throw new System.Exception(\"No reference to the player in the PostWwiseEventBreath script\");\n }\n //player.GetComponent<EnergyBehaviour>().EnterDamageStateEvent += HoldBreath; // no breathing over the cry\n\n breathPerMinute = breathPerMinuteIdle;\n breathPerMinuteNext = breathPerMinute;\n StartCoroutine(\"Breath\");\n }\n\n // Update is called once per frame.\n void LateUpdate()\n {\n // TO DO : Use events instead\n\n if (player.GetComponent<PlayerFirst>().IsHurry)\n {\n breathPerMinuteNext = breathPerMinuteHurry;\n }\n else if (player.GetComponent<PlayerFirst>().IsProtectingEars || player.GetComponent<PlayerFirst>().IsProtectingEyes)\n {\n breathPerMinuteNext = breathPerMinuteProtected;\n }\n else if (player.GetComponent<PlayerFirst>().IsRunning)\n {\n breathPerMinuteNext = breathPerMinuteRunning;\n }\n else\n {\n breathPerMinuteNext = breathPerMinuteIdle;\n }\n\n if (breathPerMinute < breathPerMinuteNext)\n {\n breathPerMinute = Mathf.Min(breathPerMinute + Time.deltaTime * transitionSpeedUp, breathPerMinuteNext);\n }\n else if (breathPerMinute > breathPerMinuteNext)\n {\n breathPerMinute = Mathf.Max(breathPerMinute - Time.deltaTime * transitionSpeedDown, breathPerMinuteNext);\n }\n }\n\n IEnumerator Breath()\n {\n for (; ; )\n {\n PlayBreathInSound();\n for (float timer = 0; timer < 0.5f * 60f / breathPerMinute; timer += Time.deltaTime) { yield return null; }\n while (player.GetComponent<PlayerFirst>().IsDamagedEyes || player.GetComponent<PlayerFirst>().IsDamagedEars) { yield return null; } // no breathing during a cry\n\n PlayBreathOutSound();\n for (float timer = 0; timer < 0.5f * 60f / breathPerMinute; timer += Time.deltaTime) { yield return null; }\n while (player.GetComponent<PlayerFirst>().IsDamagedEyes || player.GetComponent<PlayerFirst>().IsDamagedEars) { yield return null; } // no breathing during a cry\n }\n }\n\n public void PlayBreathInSound()\n {\n AKRESULT result = AkSoundEngine.SetSwitch(\"Respiration_Ex_or_In\", \"Inspire\", gameObject);\n if (result == AKRESULT.AK_Fail)\n {\n throw new System.Exception(\"Could set the phase of the breath wwise sound\");\n }\n MyEvent.Post(gameObject);\n }\n\n public void PlayBreathOutSound()\n {\n AKRESULT result = AkSoundEngine.SetSwitch(\"Respiration_Ex_or_In\", \"Expire\", gameObject);\n if (result == AKRESULT.AK_Fail)\n {\n throw new System.Exception(\"Could set the phase of the breath wwise sound\");\n }\n MyEvent.Post(gameObject);\n }\n}" }, { "alpha_fraction": 0.5015180706977844, "alphanum_fraction": 0.5227711796760559, "avg_line_length": 27.3046875, "blob_id": "69485550faee230fee91099bb150fd29c1747bcf", "content_id": "dfd24008a8d996e0932cf2bb4d05333513b35c7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7252, "license_type": "no_license", "max_line_length": 104, "num_lines": 256, "path": "/SoA-Unity/Assets/Resources/Scripts/Render.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\n\npublic struct StructTexture\n{\n public Texture2D tex;\n}\n\npublic class Render : MonoBehaviour\n{\n\n [SerializeField]\n private float coef_blur = 300.0f;\n [SerializeField]\n private float coef_intensity = 16.0f;\n\n [SerializeField]\n private float radius = 0.6f;\n [SerializeField]\n private Vector3 offSetColor;\n [SerializeField]\n private bool state_blur;\n [SerializeField]\n private bool state_chromatique;\n [SerializeField]\n private bool state_vignette_pleine;\n [SerializeField]\n private float lerp_effet;\n\n private float vie;\n public bool shader_actif = false;\n private Material mat;\n public string shader_name = \"NoVision\";\n private Camera cam;\n private RenderTexture RT;\n int it = 0;\n\n float time_actual = 0.0f;\n float time_refresh = 1.0f;\n\n public float coef = 0.001f;\n\n public float offsetX = 0.0f;\n public float offsetY = 0.0f;\n\n Matrix4x4 projection_base;\n\n // Start is called before the first frame update\n //a l'init ici\n void Awake()\n {\n state_blur = false;\n state_chromatique = false;\n //courbe blur a gérer en fonction de l'état de vie\n\n lerp_effet = 1.0f;\n\n cam = GetComponent<Camera>();\n projection_base = new Matrix4x4();\n for(int i= 0; i < 4; i++)\n {\n projection_base.SetRow(i, cam.projectionMatrix.GetRow(i));\n }\n\n \n RT = new RenderTexture(1024, 1024, 24, RenderTextureFormat.ARGB32, 4);\n RT.volumeDepth = 3;\n\n RT.useMipMap = true;\n RT.autoGenerateMips = true;\n RT.enableRandomWrite = true;\n RT.Create();\n\n if (RT.useMipMap)\n {\n Debug.Log(\"MipMap activate !\"+RT.width+ \" \"+RT.height);\n }\n\n changeShader(\"PostProcessV2\");\n mat.SetFloat(\"height\", Screen.currentResolution.height);\n mat.SetFloat(\"width\", Screen.currentResolution.width);\n }\n\n public void changeShader(string name)\n {\n shader_name = name;\n mat = new Material(Shader.Find(\"Shaders/\" + shader_name));\n }\n\n private void OnPreRender()\n {\n //cam.targetTexture = RT;\n }\n\n\n private void OnRenderImage(RenderTexture source, RenderTexture destination)\n {\n if (!shader_actif)\n {\n Graphics.Blit(source, destination);\n }\n else\n {\n\n mat.SetFloat(\"type\", 0);\n\n if (Time.realtimeSinceStartup - time_actual > time_refresh)\n {\n ComputeShader shader = Resources.Load<ComputeShader>(\"Shaders/Test\");\n \n RenderTexture RT_0 = new RenderTexture(32, 32, source.depth, source.format, 0);\n RT_0.volumeDepth = 3;\n\n RT_0.enableRandomWrite = true;\n RT_0.Create();\n\n Graphics.Blit(source, RT_0);\n\n RT = RT_0;\n\n int w = source.width;\n int h = source.height;\n\n float ratio = 16.0f / 9.0f;\n float n_w = 128.0f;\n float n_h = n_w / ratio;\n\n n_w = RT.width;\n n_h = RT.height;\n\n shader.SetFloat(\"width\", w);\n shader.SetFloat(\"height\", h);\n\n int nb_element = 2;\n\n float mipLevel = 1;\n\n uint[] values = new uint[nb_element];\n values[0] = 0;\n\n values[1] = 0;\n\n //taille d'un element pareil a cuda ou ogl\n ComputeBuffer cb = new ComputeBuffer(nb_element, sizeof(uint));\n cb.SetData(values);\n\n\n n_w /= mipLevel;\n n_h /= mipLevel;\n\n //pour RT\n shader.SetFloat(\"width\", n_w);\n shader.SetFloat(\"height\", n_h);\n\n //qd pas trouvé erreur compilation\n int indexKernel = shader.FindKernel(\"CSMain\");\n\n shader.SetBuffer(indexKernel, \"res\", cb);\n\n shader.SetTexture(indexKernel, \"Result\", RT, (int)(mipLevel - 1));\n \n //comme en cuda\n int x, y, z;\n \n float reducer = 32.0f;\n\n float tmp = n_w / reducer;\n //pour tronquer à l'entier le plus haut chiffre quand reste non null\n x = (int)( ((int)(tmp)) != tmp ? tmp+1 : tmp );\n tmp = n_h / reducer;\n y = (int)(((int)(tmp)) != tmp ? tmp+1 : tmp);\n z = 1;\n \n shader.Dispatch(indexKernel, x, y, z);\n\n cb.GetData(values);\n cb.Release();\n\n double total = values[0];\n total /= 100.0f;\n total /= (n_w * n_h);\n\n if (total > 0.5f)\n {\n mat.SetFloat(\"type\", 1);\n }\n\n //Debug.Log(\"Values est de \" + total);\n //Debug.Log(\"Cmpt est de \" + values[1]);\n time_actual = Time.realtimeSinceStartup;\n }\n\n\n\n\n\n \n\n changeShader(\"PostProcessV2\");\n mat.SetFloat(\"width\", coef_blur);\n mat.SetFloat(\"height\", coef_blur);\n mat.SetFloat(\"life\", vie);\n mat.SetFloat(\"_CoefBlur\", coef_intensity);\n mat.SetFloat(\"_Radius\", radius);\n mat.SetVector(\"_OffsetColor\",new Vector4(offSetColor.x, offSetColor.y, offSetColor.z,1.0f));\n mat.SetInt(\"_StateBlur\",(state_blur ? 1 : 0));\n mat.SetInt(\"_StateChromatique\", (state_chromatique ? 1 : 0));\n mat.SetInt(\"_VignettePleine\", (state_vignette_pleine ? 1 : 0));\n mat.SetFloat(\"_LerpEffect\", lerp_effet);\n\n\n Graphics.Blit(source, destination,mat);\n }\n }\n private void OnPostRender()\n {\n //Camera.main.targetTexture = null;\n //Graphics.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), RT);\n }\n\n public void Update()\n {\n Matrix4x4 shear = Matrix4x4.identity;\n shear.SetRow(2, new Vector4(offsetX, offsetY, 1, 0));\n cam.projectionMatrix = projection_base * shear;\n\n\n \n float angle_horizontal = cam.fieldOfView;\n\n float near, far, left, right, bottom, top;\n near = cam.nearClipPlane;\n far = cam.farClipPlane;\n right = -Mathf.Cos(angle_horizontal / 2.0f) * near;\n left = Mathf.Cos(angle_horizontal / 2.0f) * near;\n \n float angle_vertical = angle_horizontal / cam.aspect;\n bottom = Mathf.Sin(-angle_vertical) * near;\n top = Mathf.Sin(angle_vertical) * near;\n\n Matrix4x4 mat = new Matrix4x4();\n //2n/r-l 0 r+l/r-l 0\n mat.SetRow(0,new Vector4((2*near)/(right-left),0,(right+left)/(right- left),0));\n //0 2n/t-b t+b/t-b 0\n mat.SetRow(1, new Vector4(0,(2*near)/(top-bottom),(top+bottom)/(top - bottom),0));\n //0 0 -f+n/f-n -2fn/f-n\n mat.SetRow(2, new Vector4(0,0,-(far+near)/(far-near),-(2*far*near)/(far-near)));\n //0 0 -1 0\n mat.SetRow(3, new Vector4(0,0,-1.0f,0));\n\n\n cam.projectionMatrix = projection_base;// * shear; \n }\n}\n" }, { "alpha_fraction": 0.6661891341209412, "alphanum_fraction": 0.6665472984313965, "avg_line_length": 28.70212745666504, "blob_id": "3d32a9b34168c1ae00cf2525c1577a17b2586634", "content_id": "7842ac8b82565b8c52edfe05beccd8ae0ba8b119", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2794, "license_type": "no_license", "max_line_length": 142, "num_lines": 94, "path": "/SoA-Unity/Assets/LevelStreets/Scripts/Vehicles/StreetMap.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing Pixelplacement;\nusing System.Linq;\n\npublic enum SPEEDLIMIT { FAST, NORMAL, SLOW, CAUTIOUS }\n\n[System.Serializable]\npublic struct Colinearity\n{\n public float percentageStart;\n public float percentageEnd;\n public Spline otherSpline;\n public float otherPercentageStart;\n public float otherPercentageEnd;\n}\n\n[System.Serializable]\npublic struct Intersection\n{\n public float percentage;\n public Spline otherSpline;\n public float otherPercentage;\n //public bool priority;\n}\n\n\npublic class StreetMap : MonoBehaviour\n{\n [Header(\"Spline zones\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"The speed zones along the spline, anchor by anchor\")]\n private SPEEDLIMIT[] speedLimits;\n public SPEEDLIMIT[] SpeedLimits { get { return speedLimits; } set { speedLimits = value; } }\n\n [Header(\"Interactions with other splines\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"The intersections along the spline\")]\n private Intersection[] intersections;\n public Intersection[] Intersections { get { return intersections; } set { intersections = value; } }\n\n [SerializeField]\n [Tooltip(\"The colinearities with others splines\")]\n private Colinearity[] colinearities;\n public Colinearity[] Colinearities { get { return colinearities; } set { colinearities = value; } }\n\n private List<GameObject> users;\n public List<GameObject> Users { get { return users; } set { users = value; } }\n\n private Dictionary<float, SPEEDLIMIT> speedZones;\n public Dictionary<float, SPEEDLIMIT> SpeedZones { get { return speedZones; } set { speedZones = value; } }\n\n private void Awake()\n {\n users = new List<GameObject>();\n\n float[] percentages = new float[transform.childCount];\n int anchorChildCount = 0;\n foreach(Transform child in transform)\n {\n if(child.name.Contains(\"Anchor\"))\n {\n percentages[anchorChildCount] = GetComponent<Spline>().ClosestPoint(child.position);\n anchorChildCount++;\n }\n }\n if (speedLimits.Length != anchorChildCount)\n {\n throw new System.Exception(transform.name + \" : Anchor percentages and speed zones arrays not of the same length\");\n }\n\n speedZones = percentages.Zip(speedLimits, (first, second) => new { first, second }).ToDictionary(val => val.first, val => val.second);\n }\n\n public void RegisterUser(GameObject user)\n {\n users.Add(user);\n }\n\n public void UnregisterUser(GameObject user)\n {\n users.Remove(user);\n }\n\n public override string ToString()\n {\n return gameObject.name + \" has currently \" + users.Count + \" vehicles taking it\";\n }\n}\n" }, { "alpha_fraction": 0.6245959997177124, "alphanum_fraction": 0.6296057105064392, "avg_line_length": 28.607654571533203, "blob_id": "c20e8fe99eee1a8903fbac1a7a5e853e746a8d21", "content_id": "2d3d3514cd9b8c54efe9584af37ec7aa16b60910", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6190, "license_type": "no_license", "max_line_length": 137, "num_lines": 209, "path": "/SoA-Unity/Assets/LevelStreets/Scripts/AutomaticDoors.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class AutomaticDoors : MonoBehaviour\n{\n [SerializeField]\n [Tooltip(\"The left automatic door\")]\n private GameObject leftDoor;\n\n [SerializeField]\n [Tooltip(\"The right automatic door\")]\n private GameObject rightDoor;\n\n [SerializeField]\n [Tooltip(\"The speed of the doors\")]\n [Range(1,10)]\n private float speed = 3;\n\n [SerializeField]\n [Tooltip(\"The openness of the doors\")]\n [Range(1, 10)]\n private float openness = 4;\n\n [SerializeField]\n [Tooltip(\"Minimal time for the doors to stay open\")]\n [Range(1, 5)]\n private float minimalDuration = 3.5f;\n\n [Header(\"Sounds\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"Event to be played when doors are opened\")]\n private AK.Wwise.Event doorsOpenPlay;\n\n [SerializeField]\n [Tooltip(\"Event to stop the sound\")]\n private AK.Wwise.Event doorsOpenStop;\n\n [SerializeField]\n [Tooltip(\"Sound to be played when doors are closed\")]\n private AK.Wwise.Event doorsClosedPlay;\n\n [SerializeField]\n [Tooltip(\"Event to stop the sound\")]\n private AK.Wwise.Event doorsClosedStop;\n\n [Header(\"VFX\")]\n [Space]\n\n [SerializeField]\n [Tooltip(\"VFX to play when loud sound is emitted\")]\n private GameObject loudVFX;\n\n /*\n [SerializeField]\n [Tooltip(\"Event to play supermarket annoucement\")]\n private AK.Wwise.Event jinglePlay;\n \n [SerializeField]\n [Tooltip(\"Event to stop supermarket annoucement\")]\n private AK.Wwise.Event jingleStop;\n\n [SerializeField]\n [Tooltip(\"Interval between two announcements\")]\n [Range(5,10)]\n private float jingleInterval = 5;\n */\n\n private float timer;\n private Vector3 leftDoorClosedPos, rightDoorClosedPos;\n private Vector3 leftDoorOpenPos, rightDoorOpenPos;\n private enum STATE { OPEN, CLOSED, INBETWEEN};\n private STATE state;\n // Start is called before the first frame update\n\n private bool isOpeningDoor = false;\n private bool isClosingDoor = false;\n\n void Start()\n {\n if(leftDoor == null || rightDoor == null)\n {\n throw new System.NullReferenceException(\"No automatic doors for the building \" + transform.parent.transform.name);\n }\n if(doorsClosedPlay == null || doorsOpenPlay == null || doorsClosedStop == null || doorsOpenStop == null)\n {\n throw new System.NullReferenceException(\"No doors sounds for the building \" + transform.parent.transform.name);\n }\n leftDoorClosedPos = leftDoor.transform.position;\n rightDoorClosedPos = rightDoor.transform.position;\n leftDoorOpenPos = leftDoor.transform.position + leftDoor.transform.right * openness;\n rightDoorOpenPos = rightDoor.transform.position - rightDoor.transform.right * openness;\n state = STATE.CLOSED;\n timer = 0;\n\n loudVFX.GetComponent<ParticleSystem>().Stop();\n ParticleSystem.MainModule mainModule = loudVFX.GetComponent<ParticleSystem>().main;\n mainModule.startLifetime = 0.25f; // One quarter of the default value\n\n /*\n if (jinglePlay != null)\n {\n StartCoroutine(\"PlayJingle\");\n }*/\n }\n\n // Update is called once per frame\n void Update()\n {\n\n }\n\n private void OnTriggerEnter(Collider other)\n {\n if (state != STATE.OPEN && isOpeningDoor == false) // only one instance at a time\n {\n state = STATE.INBETWEEN;\n isOpeningDoor = true;\n StartCoroutine(\"OpenDoors\");\n }\n }\n private IEnumerator OpenDoors()\n {\n doorsClosedStop.Post(gameObject);\n doorsOpenPlay.Post(gameObject);\n //jinglePlay?.Post(gameObject);\n StopCoroutine(\"CloseDoors\");\n\n // TO DO : Play ambiance sound\n\n while (leftDoor.transform.position != leftDoorOpenPos)\n {\n leftDoor.transform.position = Vector3.MoveTowards(leftDoor.transform.position, leftDoorOpenPos, Time.deltaTime * speed);\n rightDoor.transform.position = Vector3.MoveTowards(rightDoor.transform.position, rightDoorOpenPos, Time.deltaTime * speed);\n yield return null;\n }\n Debug.Log(\"Doors opened !\");\n state = STATE.OPEN;\n\n isOpeningDoor = false;\n isClosingDoor = false;\n }\n\n private void OnTriggerExit(Collider other)\n {\n if (isClosingDoor == false)\n {\n isClosingDoor = true;\n StartCoroutine(\"CloseDoors\");\n }\n }\n\n private IEnumerator CloseDoors()\n {\n /* must wait till it's fully open before starting the timer */\n while (state != STATE.OPEN)\n {\n yield return null;\n }\n\n yield return new WaitForSeconds(minimalDuration);\n \n state = STATE.INBETWEEN;\n\n doorsClosedPlay.Post(gameObject);\n StartCoroutine(PlayVFX());\n\n while (leftDoor.transform.position != leftDoorClosedPos)\n {\n if (isOpeningDoor || state == STATE.OPEN) // if going the other way or reopen\n {\n doorsClosedStop.Post(gameObject);\n }\n\n leftDoor.transform.position = Vector3.MoveTowards(leftDoor.transform.position, leftDoorClosedPos, Time.deltaTime * speed);\n rightDoor.transform.position = Vector3.MoveTowards(rightDoor.transform.position, rightDoorClosedPos, Time.deltaTime * speed);\n yield return null;\n }\n\n //jingleStop?.Post(gameObject);\n state = STATE.CLOSED;\n\n isClosingDoor = false;\n isOpeningDoor = false;\n }\n\n /*\n private IEnumerator PlayJingle()\n {\n for(; ;)\n {\n jinglePlay.Post(gameObject);\n yield return new WaitForSeconds(jingleInterval);\n }\n }*/\n\n private IEnumerator PlayVFX()\n {\n yield return new WaitForSeconds(1.1f);\n if (!isOpeningDoor && state != STATE.OPEN) // if not going the other way and not reopen\n {\n loudVFX.GetComponent<ParticleSystem>().Play();\n yield return new WaitForSeconds(0.05f);\n loudVFX.GetComponent<ParticleSystem>().Stop();\n }\n }\n}\n" }, { "alpha_fraction": 0.607988178730011, "alphanum_fraction": 0.6094674468040466, "avg_line_length": 19.484848022460938, "blob_id": "8c57cfdbb84ca104d0c6c63c0365af43459dc105", "content_id": "e47a56f9cb15437786405f671a726f1a1dccfcde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 678, "license_type": "no_license", "max_line_length": 61, "num_lines": 33, "path": "/SoA-Unity/Assets/LevelPark/Scripts/PassengerDissapear.cs", "repo_name": "heurteph/PathOfEsthesia", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class PassengerDissapear : MonoBehaviour\n{\n [SerializeField]\n private GameObject[] passengers;\n\n // Start is called before the first frame update\n void Start()\n {\n \n }\n\n // Update is called once per frame\n void Update()\n {\n if (gameObject.GetComponent<StreetUser>().HasStopped)\n {\n StartCoroutine(\"Dissappear\");\n }\n }\n\n IEnumerator Dissappear()\n {\n yield return new WaitForSeconds(2);\n foreach (GameObject passenger in passengers)\n {\n passenger.SetActive(false);\n }\n }\n}\n" } ]
106
valeriat/mozilla_ci_tools
https://github.com/valeriat/mozilla_ci_tools
6d7f5f2b89bdfb8e88808f956ac9db5e3a6c054d
c18a5952162ff7937a3b07a11bbe96fc16679ee5
17e74e0302ad525d8e654fc622adbe226bc77afa
refs/heads/master
2021-01-18T23:35:25.160519
2015-03-03T21:02:29
2015-03-03T21:02:29
31,135,596
0
0
null
2015-02-21T18:24:44
2015-02-20T20:52:49
2015-02-20T20:52:48
null
[ { "alpha_fraction": 0.7454545497894287, "alphanum_fraction": 0.7454545497894287, "avg_line_length": 35.66666793823242, "blob_id": "eb5a9de87e38b35c899bb0747631ad42d7aadc6f", "content_id": "7c3e55b296beca7d7eab4af40bdb8d67f504e329", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 110, "license_type": "no_license", "max_line_length": 69, "num_lines": 3, "path": "/mozci/__init__.py", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": "''' In mozci you can find modules to deal with the various components\nthat Mozilla's CI are comprised of.\n'''\n" }, { "alpha_fraction": 0.5860214829444885, "alphanum_fraction": 0.5860214829444885, "avg_line_length": 19.66666603088379, "blob_id": "b875d9103806903182598269abe8fc1bdf796fc8", "content_id": "0b70fb116837a182a8ca2aebaae8feed655431a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 186, "license_type": "no_license", "max_line_length": 42, "num_lines": 9, "path": "/docs/allthethings.rst", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": ":mod:`allthethings`\n###################\n\nallthethings.py module\n----------------------\nModule: :mod:`mozci.sources.allthethings`\n\n.. automodule:: mozci.sources.allthethings\n :members:\n" }, { "alpha_fraction": 0.7721518874168396, "alphanum_fraction": 0.7721518874168396, "avg_line_length": 38.5, "blob_id": "e5c90987cbe835141a4322f2db906db9aef4dbb7", "content_id": "dc8302b06140e5c6097577c6838a6f73a646c9a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 158, "license_type": "no_license", "max_line_length": 73, "num_lines": 4, "path": "/mozci/utils/__init__.py", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": "''' Modules that are not necessarily related to the various components\nthat compose Mozilla's CI. In here you will find helper code for the main\nmodules.\n'''\n" }, { "alpha_fraction": 0.5858041048049927, "alphanum_fraction": 0.5916442275047302, "avg_line_length": 38.75, "blob_id": "2f2f8eb50bf3cf0681c7c3b9bff3174e904fe5c5", "content_id": "83427f14a497bd3d40d23f9c8b4af52acbd37120", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2226, "license_type": "no_license", "max_line_length": 94, "num_lines": 56, "path": "/scripts/trigger.py", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# This script is designed to trigger an arbitrary job\n# http://johnzeller.com/blog/2014/03/12/triggering-of-arbitrary-buildstests-is-now-possible\nimport argparse\nimport logging\n\nfrom mozci.mozci import trigger_job, query_jobs_schedule_url, query_repo_name_from_buildername\n\nlogging.basicConfig(format='%(asctime)s %(levelname)s:\\t %(message)s',\n datefmt='%m/%d/%Y %I:%M:%S')\nLOG = logging.getLogger()\nLOG.setLevel(logging.INFO)\n\n\ndef main():\n parser = argparse.ArgumentParser(\n usage='%(prog)s -b buildername --rev revision [OPTION]...')\n parser.add_argument('-b', '--buildername', dest='buildername',\n required=True,\n help='The buildername used in Treeherder')\n parser.add_argument('--rev', dest='revision', required=True,\n help='The 12 character revision.')\n parser.add_argument('--file', dest='files', action=\"append\", default=[],\n help='Append files needed to run the job (e.g.'\n 'installer, test.zip)')\n parser.add_argument('--debug', action='store_const', const=True,\n help='Print debugging information')\n parser.add_argument('--dry-run', action='store_const', const=True,\n help='Do not make post requests.')\n args = parser.parse_args()\n repo_name = query_repo_name_from_buildername(args.buildername)\n\n if args.debug:\n LOG.setLevel(logging.DEBUG)\n LOG.info(\"Setting DEBUG level\")\n\n list_of_requests = trigger_job(\n repo_name=repo_name,\n revision=args.revision,\n buildername=args.buildername,\n files=args.files,\n dry_run=args.dry_run\n )\n\n for req in list_of_requests:\n if req is not None:\n if req.status_code == 202:\n LOG.info(\"You return code is: %s\" % req.status_code)\n LOG.info(\"See your running jobs in here:\")\n LOG.info(query_jobs_schedule_url(repo_name, args.revision))\n else:\n LOG.error(\"Something has gone wrong. We received \"\n \"status code: %s\" % req.status_code)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6018236875534058, "alphanum_fraction": 0.6210206151008606, "avg_line_length": 35.77058792114258, "blob_id": "2a2efcd25f9e86fda6719dcefc5ddfe8360d49e2", "content_id": "1003e197b2c96c24ec57b1bb071e6927e64eccc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6251, "license_type": "no_license", "max_line_length": 95, "num_lines": 170, "path": "/mozci/sources/buildjson.py", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\"\"\"\nThis module helps with the buildjson data generated by the Release Engineering\nsystems: http://builddata.pub.build.mozilla.org/builddata/buildjson\n\"\"\"\nimport json\nimport logging\nimport os\nimport requests\n\nfrom mozci.utils.tzone import utc_dt, utc_time, utc_day\n\nLOG = logging.getLogger()\n\nBUILDJSON_DATA = \"http://builddata.pub.build.mozilla.org/builddata/buildjson\"\nBUILDS_4HR_FILE = \"builds-4hr.js.gz\"\nBUILDS_DAY_FILE = \"builds-%s.js\"\n\n\ndef _fetch_file(data_file, url):\n LOG.debug(\"We will now fetch %s\" % url)\n # Fetch tar ball\n req = requests.get(url)\n # NOTE: requests deals with decrompressing the gzip file\n with open(data_file, 'wb') as fd:\n for chunk in req.iter_content(chunk_size=1024):\n fd.write(chunk)\n\n\ndef _fetch_buildjson_day_file(date):\n '''\n In BUILDJSON_DATA we have the information about all jobs stored\n as a gzip file per day.\n\n This function caches the uncompressed gzip files requested in the past.\n\n This function returns a json object containing all jobs for a given day.\n '''\n data_file = BUILDS_DAY_FILE % date\n\n if not os.path.exists(data_file):\n url = \"%s/%s.gz\" % (BUILDJSON_DATA, data_file)\n LOG.debug(\"We have not been able to find on disk %s.\" % data_file)\n _fetch_file(data_file, url)\n\n return json.load(open(data_file))[\"builds\"]\n\n\ndef _fetch_buildjson_4hour_file():\n '''\n This file is generate every minute.\n It has the same data as today's buildjson day file but only for the\n last 4 hours.\n '''\n LOG.debug(\"Fetching %s...\" % BUILDS_4HR_FILE)\n url = \"%s/%s\" % (BUILDJSON_DATA, BUILDS_4HR_FILE)\n _fetch_file(BUILDS_4HR_FILE, url)\n return json.load(open(BUILDS_4HR_FILE))[\"builds\"]\n\n\ndef _find_job(request_id, builds, filename):\n '''\n Look for request_id in builds extracted from filename.\n\n raises Exception when we can't find the job.\n '''\n LOG.debug(\"We are going to look for %s in %s.\" % (request_id, filename))\n\n for job in builds:\n if request_id in job[\"request_ids\"]:\n LOG.debug(\"Found %s\" % str(job))\n return job\n\n raise Exception(\n \"We have not found the job. If you see this problem please grep \"\n \"in %s for %d and run again with --debug and --dry-run.\" % (filename, request_id)\n )\n\n\ndef query_job_data(complete_at, request_id):\n \"\"\"\n This function looks for a job identified by `request_id` inside of a\n buildjson file under the \"builds\" entry.\n\n Through `complete_at`, we can determine on which day we can find the\n metadata about this job.\n\n If found, the returning entry will look like this (only important values\n are referenced):\n\n .. code-block:: python\n\n {\n \"builder_id\": int, # It is a unique identifier of a builder\n \"starttime\": int,\n \"endtime\": int,\n \"properties\": {\n \"buildername\": string,\n \"buildid\": string,\n \"revision\": string,\n \"repo_path\": string, # e.g. projects/cedar\n \"log_url\", string,\n \"slavename\": string, # e.g. t-w864-ix-120\n \"packageUrl\": string, # It only applies for build jobs\n \"testsUrl\": string, # It only applies for build jobs\n \"blobber_files\": json, # Mainly applicable to test jobs\n \"symbolsUrl\": string, # It only applies for build jobs\n },\n \"request_ids\": list of ints, # Scheduling ID\n \"requestime\": int,\n \"result\": int, # Job's exit code\n \"slave_id\": int, # Unique identifier for the machine that run it\n }\n\n NOTE: Remove this block once https://bugzilla.mozilla.org/show_bug.cgi?id=1135991\n is fixed.\n\n There is so funkiness in here. A buildjson file for a day is produced\n every 15 minutes all the way until midnight pacific time. After that, a new\n _UTC_ day comences. However, we will only contain all jobs ending within the\n UTC day and not the PT day. If you run any of this code in the last 4 hours of\n the pacific day, you will have a gap of 4 hours for which you won't have buildjson\n data (between 4-8pm PT). The gap starts appearing after 8pm PT when builds-4hr\n cannot cover it.\n\n If we look all endtime values on a day and we print the minimum and maximues values,\n this is what we get:\n\n .. code-block:: python\n\n 1424649600 Mon, 23 Feb 2015 00:00:00 () Sun, 22 Feb 2015 16:00:00 -0800 (PST)\n 1424736000 Tue, 24 Feb 2015 00:00:00 () Mon, 23 Feb 2015 16:00:00 -0800 (PST)\n\n This means that since 4pm to midnight we generate the same file again and again\n without adding any new data.\n \"\"\"\n assert type(request_id) is int\n assert type(complete_at) is int\n\n date = utc_day(complete_at)\n LOG.debug(\"Job identified with complete_at value: %d run on %s UTC.\" % (complete_at, date))\n\n then = utc_dt(complete_at)\n hours_ago = (utc_dt() - then).total_seconds() / (60 * 60)\n LOG.debug(\"The job completed at %s (%d hours ago).\" % (utc_time(complete_at), hours_ago))\n\n # If it has finished in the last 4 hours\n if hours_ago < 4:\n filename = BUILDS_4HR_FILE\n job = _find_job(request_id, _fetch_buildjson_4hour_file(), filename)\n else:\n filename = BUILDS_DAY_FILE % date\n builds = _fetch_buildjson_day_file(date)\n # If it is today's date we might need to clobber the file since we could\n # have cached today's file for a job earlier in the day\n if utc_day() == date and os.path.exists(filename):\n try:\n job = _find_job(request_id, builds, filename)\n except:\n last_modified = int(os.path.getmtime(filename)) / 60\n LOG.info(\"We removed today's buildjson file since the job was not found.\")\n LOG.info(\"We will fetch again since it is %s minutes out of date.\" %\n last_modified)\n os.remove(filename)\n builds = _fetch_buildjson_day_file(date)\n job = _find_job(request_id, builds, filename)\n else:\n job = _find_job(request_id, builds, filename)\n\n return job\n" }, { "alpha_fraction": 0.694200336933136, "alphanum_fraction": 0.7073813676834106, "avg_line_length": 26.095237731933594, "blob_id": "050e9ed34b2eb90d2eb36b72b91e7afaaca9b5a4", "content_id": "c196d803d023a9735653245c85305b5412c56b72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1138, "license_type": "no_license", "max_line_length": 91, "num_lines": 42, "path": "/docs/index.rst", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": ".. Mozilla CI Tools documentation master file, created by\n sphinx-quickstart on Wed Jan 21 14:26:02 2015.\n You can adapt this file completely to your liking, but it should at least\n contain the root `toctree` directive.\n\nIntroduction\n============\n\nMozilla CI Tools (mozci) is designed to allow interacting with the various components\nwhich compose Mozilla's Continous Integration. Specifically, we're talking about the builds\nand test jobs produced in treeherder_.\n\nmozci tools has several modules and command line scripts to help you use them.\n\nTable of contents\n-----------------\n.. toctree::\n :maxdepth: 2\n\n project_definition\n using_mozci\n scripts\n\nResources\n---------\n* Source_\n* Docs_\n* Issues_ and Tasks_\n* Pypi_\n\nIndices and tables\n------------------\n\n* :ref:`genindex`\n* :ref:`modindex`\n\n.. _Source: https://github.com/armenzg/mozilla_ci_tools\n.. _Docs: https://mozilla-ci-tools.readthedocs.org\n.. _Tasks: https://trello.com/b/BplNxd94/mozilla-ci-tools-public\n.. _Pypi: https://pypi.python.org/pypi/mozci\n.. _Issues: https://github.com/armenzg/mozilla_ci_tools/issues\n.. _treeherder: https://treeherder.mozilla.org\n" }, { "alpha_fraction": 0.6702811121940613, "alphanum_fraction": 0.6867470145225525, "avg_line_length": 36.727272033691406, "blob_id": "e3128b01d3b01086592e6f4748ca73fe3da496e0", "content_id": "5693e6ae4c09cb5f0f14e169ac6c04b626364872", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2492, "license_type": "no_license", "max_line_length": 95, "num_lines": 66, "path": "/docs/roadmap.rst", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": "Roadmap\n=======\n\n**NOTE** This roadmap needs to be reviewed.\n\nMilestones\n----------\nCreate prototype to trigger N jobs for a range of revisions\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nThis allows backfilling jobs.\n\nThis has been accomplished on the 0.2.1 release (13/02/2015).\n\nAdd pushlog support\n^^^^^^^^^^^^^^^^^^^\nThis helps interacting with ranges of revisions.\n\nThis has been accomplished on the 0.2.1 release (13/02/2015).\n\nDetermine accurately the current state of jobs\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nWe can determine any information on jobs run on the Buildbot CI by retrieving\nscheduling information through Self-Serve's BuildAPI.\nThe information retrieved can then be matched to the buildjson status dumps that\nare produced every minute (for the last 4 hours) and every 15 minutes (for the day's worth of\ndata).\n\nThis feature is close to completion. Only issue 46 is left (25/02/2015).\n\nCreate prototype to backfill\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nGiven a bad job, we can simply to scan the previous revisions for the last\nknown good job for it. Known that, we can trigger all jobs require to coverage\nthe missing jobs.\n\nIntegrate backfilling feature into treeherder\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nThis will be similar to the re-trigger button that is part of the treeherder UI.\nWe select a job that is failing and request that we backfill.\nmozci will determine when was the last time there was a successful job and trigger\nall missing jobs up to the last known good job.\n\nProduce data structure for monitoring\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nThis would be useful to help us monitor jobs that:\n\n* get triggered\n* could be triggered\n* expect to be triggered after an upstream job finishes\n\nAllow a user to monitor jobs triggered\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nWe currently trigger jobs and don’t have an standardized method to monitor such triggered jobs.\nWe have buildapi, buildjson, builds-running, builds-pending and treeherder APIs as our source\ncandidates.\n\nTest framework to test CI data sources\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nWe need to have a way to prevent regressions on Mozilla CI tools.\nAdding coverage reports would help us fix this issue.\n\nWe also need a way to test the data sources structures for changes that could regress us\n(e.g. new builder naming for Buildbot).\nWe might be able to simply mock it but we might need to set up the various data sources.\n\nThis is to be tackled in Q2/Q3 2015.\n" }, { "alpha_fraction": 0.8870967626571655, "alphanum_fraction": 0.8870967626571655, "avg_line_length": 19.66666603088379, "blob_id": "ca92b2b4b49336aac6145c9d8a774692d5f0b159", "content_id": "25b054ece5cc18dc2a5775af592a45f660ed9a3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 62, "license_type": "no_license", "max_line_length": 27, "num_lines": 3, "path": "/docs/requirements.txt", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": "sphinx_rtd_theme\nsphinx-autobuild\nsphinxcontrib-programoutput\n" }, { "alpha_fraction": 0.6338028311729431, "alphanum_fraction": 0.6338028311729431, "avg_line_length": 14.777777671813965, "blob_id": "7fd33b06280ef38c4ecf367a58cc1b24cfa7ae8d", "content_id": "2e27a165135d23b794ff6e220f26ba82b7007e12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 142, "license_type": "no_license", "max_line_length": 38, "num_lines": 9, "path": "/docs/buildapi.rst", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": ":mod:`buildapi`\n###############\n\nTODO: Better document this.\n\nThe module :mod:`buildapi`\n\n.. automodule:: mozci.sources.buildapi\n :members:\n" }, { "alpha_fraction": 0.5652173757553101, "alphanum_fraction": 0.5652173757553101, "avg_line_length": 11.777777671813965, "blob_id": "4ac21c0afc3a89baf86ad82c7141c44b7adbe560", "content_id": "4ef605fdd3c1b8997d73d8779dee7062bc999c01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 115, "license_type": "no_license", "max_line_length": 27, "num_lines": 9, "path": "/docs/mozci.rst", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": ":mod:`mozci`\n###############\n\nTODO: Curate doc.\n\nThe module :mod:`mozci`\n\n.. automodule:: mozci.mozci\n :members:\n" }, { "alpha_fraction": 0.7431906461715698, "alphanum_fraction": 0.7431906461715698, "avg_line_length": 33.72972869873047, "blob_id": "24eec32d36848e290048dcf45b32ff3f07cf098a", "content_id": "b6f6cbf76c7b19cbd8ea3f9cea61edc706e228ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1285, "license_type": "no_license", "max_line_length": 94, "num_lines": 37, "path": "/docs/scripts.rst", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": "Scripts\n#######\n\nThe scripts directory contains various scripts that have various specific\nuses and help drive the development of Mozilla CI tools.\n\nTo be able to use these scripts all you have to do is this: ::\n\n git clone https://github.com/armenzg/mozilla_ci_tools.git\n python setup.py develop (or install)\n\ntrigger.py\n^^^^^^^^^^\nIt simply helps trigger a job. It deals with missing jobs and determining\nassociated build jobs for test and talos jobs.\n\n.. program-output:: python ../scripts/trigger.py --help\n\ntrigger_range.py\n^^^^^^^^^^^^^^^^\nThis script allows you to trigger a buildername many times across a range of pushes.\nYou can either:\n\na) give a start and end revision\nb) go back N revisions from a given revision\nc) use a range based on a delta from a given revision\n\n.. program-output:: python ../scripts/trigger_range.py --help\n\ngenerate_triggercli.py\n^^^^^^^^^^^^^^^^^^^^^^\nThis script allows you to generate a bunch of cli commands that would allow you to investigate\nthe revision to blame for an intermittent orange.\nYou have to specify the bug number for the intermittent orange you're investigating and this\nscript will you give you the scripts you need to run to backfill the jobs you need.\n\n.. program-output:: python ../scripts/generate_triggercli.py --help\n" }, { "alpha_fraction": 0.533808708190918, "alphanum_fraction": 0.5357757806777954, "avg_line_length": 33.760684967041016, "blob_id": "487c5eef231fa6fedca44083f0989bc8993a6b5d", "content_id": "f24021564069ae9e233239656d0e7990635d23c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4067, "license_type": "no_license", "max_line_length": 96, "num_lines": 117, "path": "/scripts/trigger_range.py", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": "import logging\nimport urllib\n\nfrom argparse import ArgumentParser\nfrom mozci.mozci import trigger_range, query_repo_url, query_repo_name_from_buildername\nfrom mozci.sources.pushlog import query_revisions_range_from_revision_and_delta\nfrom mozci.sources.pushlog import query_revisions_range, query_revision_info, query_pushid_range\n\nlogging.basicConfig(format='%(asctime)s %(levelname)s:\\t %(message)s',\n datefmt='%m/%d/%Y %I:%M:%S')\nLOG = logging.getLogger()\n\n\ndef parse_args(argv=None):\n '''\n Parse command line options.\n '''\n parser = ArgumentParser()\n\n parser.add_argument('-b', \"--buildername\",\n dest=\"buildername\",\n required=True,\n type=str,\n help=\"The buildername used in Treeherder.\")\n\n parser.add_argument(\"--times\",\n dest=\"times\",\n type=int,\n default=1,\n help=\"Number of times to retrigger the push.\")\n\n parser.add_argument(\"--delta\",\n dest=\"delta\",\n type=int,\n help=\"Number of jobs to add/subtract from push revision.\")\n\n parser.add_argument(\"--rev\",\n dest=\"push_revision\",\n help=\"revision of the push.\")\n\n parser.add_argument('--start-rev',\n dest='start',\n help='The 12 character revision to start from (oldest).')\n\n parser.add_argument('--end-rev',\n dest='end',\n help='The 12 character revision to end with (newest).')\n\n parser.add_argument(\"--back-revisions\",\n dest=\"back_revisions\",\n type=int,\n help=\"Number of revisions to go back from current revision (--rev).\")\n\n parser.add_argument(\"--dry-run\",\n action=\"store_true\",\n dest=\"dry_run\",\n help=\"flag to test without actual push.\")\n\n parser.add_argument(\"--debug\",\n action=\"store_true\",\n dest=\"debug\",\n help=\"set debug for logging.\")\n\n options = parser.parse_args(argv)\n return options\n\n\nif __name__ == \"__main__\":\n options = parse_args()\n repo_name = query_repo_name_from_buildername(options.buildername)\n repo_url = query_repo_url(repo_name)\n\n if (options.start or options.end) and (options.delta or options.push_revision):\n raise Exception(\"Use either --start-rev and --end-rev together OR\"\n \" use --rev and --delta together.\")\n\n if options.back_revisions and options.push_revision:\n push_info = query_revision_info(repo_url, options.push_revision)\n end_id = int(push_info[\"pushid\"])\n start_id = end_id - options.back_revisions\n revlist = query_pushid_range(repo_url, start_id, end_id)\n\n if options.delta and options.push_revision:\n revlist = query_revisions_range_from_revision_and_delta(\n repo_url,\n options.push_revision,\n options.delta)\n\n if options.start and options.end:\n revlist = query_revisions_range(\n repo_url,\n options.start,\n options.end)\n\n if options.debug:\n LOG.setLevel(logging.DEBUG)\n LOG.info(\"Setting DEBUG level\")\n else:\n LOG.setLevel(logging.INFO)\n\n try:\n trigger_range(\n buildername=options.buildername,\n repo_name=repo_name,\n revisions=revlist,\n times=options.times,\n dry_run=options.dry_run\n )\n except Exception, e:\n LOG.exception(e)\n exit(1)\n\n LOG.info('https://treeherder.mozilla.org/#/jobs?%s' %\n urllib.urlencode({'repo': repo_name,\n 'fromchange': revlist[0],\n 'tochange': revlist[-1],\n 'filter-searchStr': options.buildername}))\n" }, { "alpha_fraction": 0.6304348111152649, "alphanum_fraction": 0.6304348111152649, "avg_line_length": 14.333333015441895, "blob_id": "c0e5cd5d97b31952e48862ed7439104a95b3817d", "content_id": "20881ce4c15e372df355d8ef2a104047200c8bdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 138, "license_type": "no_license", "max_line_length": 37, "num_lines": 9, "path": "/docs/pushlog.rst", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": ":mod:`pushlog`\n##############\n\nTODO: Better document this.\n\nThe module :mod:`pushlog`\n\n.. automodule:: mozci.sources.pushlog\n :members:\n" }, { "alpha_fraction": 0.6532273292541504, "alphanum_fraction": 0.6590952277183533, "avg_line_length": 30.446428298950195, "blob_id": "1e037158e4d8960aea34e2b612a06847bfc5cad5", "content_id": "e7a7f5cd22a8a481af412d153d4ba44631895b8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5283, "license_type": "no_license", "max_line_length": 94, "num_lines": 168, "path": "/mozci/sources/buildapi.py", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\"\"\"\nThis script is designed to trigger jobs through Release Engineering's\nbuildapi self-serve service.\n\nThe API documentation is in here (behind LDAP):\nhttps://secure.pub.build.mozilla.org/buildapi/self-serve\n\nThe docs can be found in here:\nhttp://moz-releng-buildapi.readthedocs.org\n\"\"\"\nfrom __future__ import absolute_import\nimport json\nimport logging\nimport os\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom mozci.utils.authentication import get_credentials\nfrom mozci.sources.pushlog import query_revision_info\n\nLOG = logging.getLogger()\nHOST_ROOT = 'https://secure.pub.build.mozilla.org/buildapi/self-serve'\nREPOSITORIES_FILE = os.path.abspath(\"repositories.txt\")\n\n# Self-serve cannot give us the whole granularity of states; Use buildjson where necessary.\n# http://hg.mozilla.org/build/buildbot/file/0e02f6f310b4/master/buildbot/status/builder.py#l25\nPENDING, RUNNING, UNKNOWN = range(-3, 0)\nSUCCESS, WARNING, FAILURE, SKIPPED, EXCEPTION, RETRY, CANCELLED = range(7)\nRESULTS = [\"success\", \"warnings\", \"failure\", \"skipped\", \"exception\", \"retry\", \"cancelled\"]\n\n\nclass BuildapiException(Exception):\n pass\n\n\ndef make_request(url, payload):\n ''' We request from buildapi to trigger a job for us.\n\n We return the request.\n '''\n # NOTE: A good response returns json with request_id as one of the keys\n req = requests.post(url, data=payload, auth=get_credentials())\n assert req.status_code != 401, req.reason\n LOG.debug(\"We have received this request:\")\n LOG.debug(\" - status code: %s\" % req.status_code)\n LOG.debug(\" - text: %s\" % BeautifulSoup(req.text).get_text())\n return req\n\n\ndef _valid_builder():\n ''' Not implemented function '''\n raise Exception(\"Not implemented because of bug 1087336. Use \"\n \"mozci.allthethings.\")\n\n\ndef valid_revision(repo_name, revision):\n '''\n There are revisions that won't exist in buildapi\n For instance, commits with DONTBUILD will not exist\n '''\n LOG.debug(\"Determine if the revision is valid for buildapi.\")\n revision_info = query_revision_info(query_repo_url(repo_name), revision, full=True)\n if \"DONTBUILD\" in revision_info[\"changesets\"][0][\"desc\"]:\n LOG.info(\"We will _NOT_ trigger anything for revision %s for %s since \"\n \"it does not exist in self-serve.\" % (revision, repo_name))\n return False\n else:\n return True\n\n\n#\n# Functions to query\n#\ndef query_job_status(job):\n '''\n Helper to determine the scheduling status of a job from self-serve.\n '''\n if not (\"status\" in job):\n return PENDING\n else:\n status = job[\"status\"]\n if status is None:\n if \"endtime\" in job:\n return RUNNING\n else:\n return UNKNOWN\n elif status in (SUCCESS, WARNING, FAILURE, EXCEPTION, RETRY, CANCELLED):\n return status\n else:\n LOG.debug(job)\n raise Exception(\"Unexpected status\")\n\n\ndef query_jobs_schedule(repo_name, revision):\n ''' It returns a list with all jobs for that revision.\n\n If we can't query about this revision in buildapi we return an empty list.\n\n raises BuildapiException\n '''\n if not valid_revision(repo_name, revision):\n raise BuildapiException\n\n url = \"%s/%s/rev/%s?format=json\" % (HOST_ROOT, repo_name, revision)\n LOG.debug(\"About to fetch %s\" % url)\n req = requests.get(url, auth=get_credentials())\n assert req.status_code in [200], req.content\n\n return req.json()\n\n\ndef query_jobs_url(repo_name, revision):\n ''' Returns url of where a developer can login to see the\n scheduled jobs for a revision.\n '''\n return \"%s/%s/rev/%s\" % (HOST_ROOT, repo_name, revision)\n\n\ndef query_repository(repo_name):\n ''' Return dictionary with information about a specific repository.\n '''\n repositories = query_repositories()\n if repo_name not in repositories:\n repositories = query_repositories(clobber=True)\n if repo_name not in repositories:\n raise Exception(\"That repository does not exist.\")\n\n return repositories[repo_name]\n\n\ndef query_repo_url(repo_name):\n LOG.debug(\"Determine repository associated to %s\" % repo_name)\n return query_repository(repo_name)[\"repo\"]\n\n\ndef query_repositories(clobber=False):\n '''\n Return dictionary with information about the various repositories.\n The data about a repository looks like this:\n\n .. code-block:: python\n\n \"ash\": {\n \"repo\": \"https://hg.mozilla.org/projects/ash\",\n \"graph_branches\": [\"Ash\"],\n \"repo_type\": \"hg\"\n }\n '''\n repositories = None\n if clobber and os.path.exists(REPOSITORIES_FILE):\n os.remove(REPOSITORIES_FILE)\n\n if os.path.exists(REPOSITORIES_FILE):\n LOG.debug(\"Loading %s\" % REPOSITORIES_FILE)\n fd = open(REPOSITORIES_FILE)\n repositories = json.load(fd)\n else:\n url = \"%s/branches?format=json\" % HOST_ROOT\n LOG.debug(\"About to fetch %s\" % url)\n req = requests.get(url, auth=get_credentials())\n assert req.status_code != 401, req.reason\n repositories = req.json()\n with open(REPOSITORIES_FILE, \"wb\") as fd:\n json.dump(repositories, fd)\n\n return repositories\n" }, { "alpha_fraction": 0.6535714268684387, "alphanum_fraction": 0.6785714030265808, "avg_line_length": 15.470588684082031, "blob_id": "1480a8b908ff7c097761f8104184341accdcc364", "content_id": "b9e465492e3150aaa4dcb54656fbdf84bd37749b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 280, "license_type": "no_license", "max_line_length": 55, "num_lines": 17, "path": "/tox.ini", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": "[tox]\nenvlist = py27\n\n[testenv]\nbasepython = python2.7\n\ndeps =\n coverage\n # coveralls\n pep8\n pyflakes\n pytest\n\ncommands =\n pep8 --config=.pep8rc docs mozci scripts test\n pyflakes docs mozci scripts test\n coverage run --source=mozci,scripts -m py.test test\n" }, { "alpha_fraction": 0.6710993051528931, "alphanum_fraction": 0.6715425252914429, "avg_line_length": 29.904109954833984, "blob_id": "21a0d176e6fa68ab552de515a35ab456931ef556", "content_id": "02845be4445cdde0c035091b77ae1370230807cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2256, "license_type": "no_license", "max_line_length": 86, "num_lines": 73, "path": "/test/test_platforms.py", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": "\"\"\"\nWe use a mapping generated by a version with triggers\nallthethings.json and compare this with the results we get\nfrom platforms.py\n\"\"\"\nimport json\nimport os\nimport pytest\n\nimport mozci.sources.allthethings\nimport mozci.platforms\n\n\ndef _update_json():\n filepath = os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n \"test_platforms.json\"\n )\n with open(filepath, 'r') as f:\n reference_builders_info = json.load(f)\n\n builders_data = mozci.sources.allthethings.fetch_allthethings_data()['builders']\n\n for builder in reference_builders_info.keys():\n if builder not in builders_data:\n del reference_builders_info[builder]\n\n return reference_builders_info\n\n\ndef complex_data():\n reference_builders_info = _update_json()\n\n # The values of all the builds can be obtained by using .values()\n # on the data from test_platforms.json. When asking\n # determine_upstream_builder() for a builder we return itself. We add known\n # build jobs to reference_builders_info\n build_jobs = set(reference_builders_info.values())\n for build_job in build_jobs:\n reference_builders_info[build_job] = build_job\n\n latest_builders = mozci.sources.allthethings.fetch_allthethings_data()['builders']\n\n tests = []\n for builder in reference_builders_info.keys():\n properties = latest_builders[builder]['properties']\n # If we can't guess a repo_name we can't test determine_upstream_builder\n try:\n repo_name = properties['repo_path'].split('/')[-1]\n except:\n continue\n\n expected = reference_builders_info[builder]\n tests.append((builder, repo_name, expected))\n\n return tests\n\n\ndef list_untested():\n t = set(_update_json())\n s = set(mozci.sources.allthethings.list_builders())\n with open('untested_builders.txt', 'w') as f:\n for x in sorted(s.difference(t)):\n f.write(x + '\\n')\n\nlist_untested()\n\n\n@pytest.mark.parametrize(\"builder,repo_name,expected\", complex_data())\ndef test_builders(builder, repo_name, expected):\n obtained = mozci.platforms.determine_upstream_builder(builder, repo_name)\n assert obtained == expected, \\\n 'obtained: \"%s\", expected \"%s\"' % (obtained, expected)\n" }, { "alpha_fraction": 0.6815537214279175, "alphanum_fraction": 0.6928473711013794, "avg_line_length": 43.9538459777832, "blob_id": "e8bb4d9986207745326ddf24a7f37c3e07b396f8", "content_id": "d859770d9bad3c90f8c00cc4f4334202d95b18fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5844, "license_type": "no_license", "max_line_length": 78, "num_lines": 130, "path": "/mozci/platforms.py", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\"\"\"\nThis module helps us connect builds to tests since we don't have an API\nto help us with this task.\n\"\"\"\nfrom sources.allthethings import fetch_allthethings_data\n\n# We will start by pre-computing some structures that will be used for\n# determine_upstream_builder. They are globals so we don't compute them over\n# and over again when calling determine_upstream_builder multiple times\n\nall_builders_information = fetch_allthethings_data()\nbuildernames = all_builders_information['builders'].keys()\n\n# In buildbot, once a build job finishes, it triggers a scheduler,\n# which causes several tests to run. In allthethings.json we have the\n# name of the trigger that activates a scheduler, but what each build\n# job triggers is not directly available from the json file. Since\n# trigger names for a given build are similar to their shortnames,\n# which are available in allthethings.json, we'll use shortnames to\n# find the which builder triggered a given scheduler given only the\n# trigger name. In order to do that we'll need a mapping from\n# shortnames to build jobs. For example:\n# \"Android armv7 API 11+ larch build\":\n# { ... \"shortname\": \"larch-android-api-11\", ...},\n# Will give us the entry:\n# \"larch-android-api-11\" : \"Android armv7 API 11+ larch build\"\nshortname_to_name = {}\n\n# For every test job we can find the scheduler that runs it and the\n# corresponding trigger in allthethings.json. For example:\n# \"schedulers\": {...\n# \"tests-larch-panda_android-opt-unittest\": {\n# \"downstream\": [ \"Android 4.0 armv7 API 11+ larch opt test cppunit\", ...],\n# \"triggered_by\": [\"larch-android-api-11-opt-unittest\"]},\n# means that \"Android 4.0 armv7 API 11+ larch opt test cppunit\" is ran\n# by the \"tests-larch-panda_android-opt-unittest\" scheduler, and this\n# scheduler is triggered by \"larch-android-api-11-opt-unittest\". In\n# buildername_to_trigger we'll store the corresponding trigger to\n# every test job. In this case, \"Android 4.0 armv7 API 11+ larch opt\n# test cppunit\" : larch-android-api-11-opt-unittest\nbuildername_to_trigger = {}\n\n# We'll look at every builder and if it's a build job we will add it\n# to shortname_to_name\nfor buildername in buildernames:\n # Skipping nightly for now\n if 'nightly' in buildername:\n continue\n\n builder_info = all_builders_information['builders'][buildername]\n props = builder_info['properties']\n # We heuristically figure out what jobs are build jobs by checking\n # the \"slavebuilddir\" property\n if 'slavebuilddir' not in props or props['slavebuilddir'] != 'test':\n shortname_to_name[builder_info['shortname']] = buildername\n\n# data['schedulers'] is a dictionary that maps a scheduler name to a\n# dictionary of it's properties:\n# \"schedulers\": {...\n# \"tests-larch-panda_android-opt-unittest\": {\n# \"downstream\": [ \"Android 4.0 armv7 API 11+ larch opt test cppunit\",\n# \"Android 4.0 armv7 API 11+ larch opt test crashtest\",\n# \"Android 4.0 armv7 API 11+ larch opt test jsreftest-1\",\n# \"Android 4.0 armv7 API 11+ larch opt test jsreftest-2\",\n# ... ],\n# \"triggered_by\": [\"larch-android-api-11-opt-unittest\"]},\n# A test scheduler has a list of tests in \"downstream\" and a trigger\n# name in \"triggered_by\". We will map every test in downstream to the\n# trigger name in triggered_by\nfor sched, values in all_builders_information['schedulers'].iteritems():\n # We are only interested in test schedulers\n if not sched.startswith('tests-'):\n continue\n\n for buildername in values['downstream']:\n assert buildername not in buildername_to_trigger\n buildername_to_trigger[buildername] = values['triggered_by'][0]\n\n\ndef determine_upstream_builder(buildername, repo_name):\n '''Given a builder name, find the build job that triggered it. When\n buildername corresponds to a test job, it does so by looking at\n allthethings.json. When buildername corresponds to a build job, it\n returns it unchanged.\n '''\n assert repo_name in buildername, \\\n \"You have requested '%s' buildername, \" % buildername + \\\n \"however, the key '%s' \" % repo_name + \\\n \"is not found in it.\"\n\n # If a buildername is not in buildername_to_trigger, that means\n # it's a build job and it should be returned unchanged\n if buildername not in buildername_to_trigger:\n return buildername\n\n # For some (but not all) platforms and repos, -pgo is explicit in\n # the trigger but not in the shortname, e.g. \"Linux\n # mozilla-release build\" shortname is \"mozilla-release-linux\" but\n # the associated trigger name is\n # \"mozilla-release-linux-pgo-unittest\"\n SUFFIXES = ['-opt-unittest', '-unittest', '-talos', '-pgo']\n\n # Guess the build job's shortname from the test job's trigger\n # e.g. from \"larch-android-api-11-opt-unittest\"\n # look for \"larch-android-api-11\" in shortname_to_name and find\n # \"Android armv7 API 11+ larch build\"\n shortname = buildername_to_trigger[buildername]\n for suffix in SUFFIXES:\n if shortname.endswith(suffix):\n shortname = shortname[:-len(suffix)]\n if shortname in shortname_to_name:\n return shortname_to_name[shortname]\n\n # B2G jobs are weird\n shortname = \"b2g_\" + shortname.replace('-emulator', '_emulator') + \"_dep\"\n if shortname in shortname_to_name:\n return shortname_to_name[shortname]\n\n\ndef is_downstream(buildername):\n ''' Determine if a job requires files to be triggered.\n '''\n # XXX: This is closely tied to the buildbot naming\n # We could determine this by looking if the builder belongs to\n # the right schedulers in allthethings.json\n for match in (\"opt\", \"pgo\", \"debug\", \"talos\"):\n if buildername.find(match) != -1:\n return True\n return False\n" }, { "alpha_fraction": 0.6015625, "alphanum_fraction": 0.6015625, "avg_line_length": 13.222222328186035, "blob_id": "fa0f7acd02b3711de1a7a7489e2470ba3a95e100", "content_id": "d24c5d9da7ec4181419ed14a61e7821ee16556ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 128, "license_type": "no_license", "max_line_length": 31, "num_lines": 9, "path": "/docs/platforms.rst", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": ":mod:`platforms`\n################\n\nTODO: Curate doc.\n\nThe module :mod:`platforms`\n\n.. automodule:: mozci.platforms\n :members:\n" }, { "alpha_fraction": 0.6752862930297852, "alphanum_fraction": 0.6811968684196472, "avg_line_length": 35.09333419799805, "blob_id": "4cdbefc015c6eb104878a860d07e56343457e90d", "content_id": "4853d9cf54fdd86d98c8b49b3fb71b701dd873d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2707, "license_type": "no_license", "max_line_length": 99, "num_lines": 75, "path": "/docs/use_cases.rst", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": "Use cases\n=========\n\nCase scenario 1: Bisecting permanent issue\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n* We have a job failing\n* There are jobs that were coalesced between the last good and the first bad job\n* We need to backfill between good revision and the bad revision\n\nThis has been completed by the trigger_range.py.\n\nCase scenario 2: Bisecting intermittent issue\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n* We have an intermittent job\n* We want to determine when it started happening\n* It is not only a matter of coalescing but also a matter of frequency\n* We want to give a range of changesets and bisect until spotting culprit\n\nNOTE: We trigger more than one job compared to case scenario 1\n\nThe script trigger_range.py helps with triggering multiple times the same jobs.\nThe script generate_cli.py helps with tracking filed intermittent oranges in bugzilla.\n\nCase scenario 3: Retrigger an intermittent job on a changeset until hit\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nhttps://bugzilla.mozilla.org/show_bug.cgi?id=844746\n\n* This is more of an optimization.\n* The intent is to hit the orange with extra debugging information.\n* We're not bisecting in here.\n* We can trigger batches (e.g. 5 at a time)\n\nNot in scope at the moment.\n\nThis could be done with a modification of trigger.py where we monitor the jobs\nrunning until one of them fails.\n\nThe monitoring module would help with this.\n\nCase scenario 4: Bisecting Talos\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n* We have a performance regression\n* We want to determine when it started showing up\n* Given a revision that _failed_\n* Re-trigger that revision N times and all revisions prior to it until the last data point + 1 more\n\nNOTE: Ask jmaher if he already has implemented this.\n\nCase scenario 5: After uplift we need a new baseline for release branches\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n* We need several data points to establish a baseline\n* After an uplift we need to generate a new baseline\n* Once there is a baseline we can determine regression\n\nNOTE: Ask jmaher if he already has implemented this.\n\nThe scripts trigger.py and trigger_range.py would be suitable for this.\n\nCase scenario 6: New test validation\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n* New test validation\n* Re-triggering to determine indeterminacy\n* Single revision\n* All platforms running test\n\nNOTE: I don't know how to determine on which job and which platforms we run a specific test.\n\nNot in scope at the moment.\n\nCase scenario 7: Fill in a changeset\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n* We know that a changeset is missing jobs\n* We want to add all missing jobs\n\nNot in scope at the moment.\n" }, { "alpha_fraction": 0.6031610369682312, "alphanum_fraction": 0.6046403050422668, "avg_line_length": 33.90217208862305, "blob_id": "fea76059647e72155723d91741363e300931454b", "content_id": "3bdba92142c24a9222c58b6ae6ba3ff5613bafa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12844, "license_type": "no_license", "max_line_length": 95, "num_lines": 368, "path": "/mozci/mozci.py", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": "\"\"\" This module is generally your first starting point.\nInstead of going directly to the module that represent different data sources\n(e.g. buildapi.py), we highly encourage you to interface to them through here.\nAs the continuous integration changes, you will be better off letting mozci.py\ndetermine which source to reach to take the actions you need.\n\nIn here, you will also find high level functions that will do various low level\ninteractions with distinct modules to meet your needs.\"\"\"\nfrom __future__ import absolute_import\n\nimport json\nimport logging\n\nfrom mozci.platforms import determine_upstream_builder\nfrom mozci.sources import allthethings, buildapi, buildjson, pushlog\nfrom mozci.utils.misc import _all_urls_reachable\n\nLOG = logging.getLogger()\n\n\ndef _matching_jobs(buildername, all_jobs):\n '''\n It returns all jobs that matched the criteria.\n '''\n LOG.debug(\"Find jobs matching '%s'\" % buildername)\n matching_jobs = []\n for j in all_jobs:\n if j[\"buildername\"] == buildername:\n matching_jobs.append(j)\n\n LOG.info(\"We have found %d job(s) of '%s'.\" %\n (len(matching_jobs), buildername))\n return matching_jobs\n\n\ndef _determine_trigger_objective(repo_name, revision, buildername):\n '''\n Determine if we need to trigger any jobs and which job.\n\n trigger: The name of the builder we need to trigger\n files: Files needed for such builder\n '''\n trigger = None\n files = None\n\n # Let's figure out the associated build job\n # XXX: We have to handle the case when we query a build job\n build_buildername = determine_upstream_builder(buildername, repo_name)\n assert valid_builder(build_buildername), \\\n \"Our platforms mapping system has failed.\"\n # Let's figure out which jobs are associated to such revision\n all_jobs = query_jobs(repo_name, revision)\n # Let's only look at jobs that match such build_buildername\n matching_jobs = _matching_jobs(build_buildername, all_jobs)\n\n if len(matching_jobs) == 0:\n # We need to simply trigger a build job\n LOG.debug(\"We might trigger %s instead of %s\" %\n (build_buildername, buildername))\n trigger = build_buildername\n else:\n # We know there is at least one build job in some state\n # We need to determine if we need to trigger a build job\n # or the test job\n successful_job = None\n running_job = None\n\n LOG.debug(\"List of matching jobs:\")\n for job in matching_jobs:\n LOG.debug(job)\n status = job.get(\"status\")\n if status is None:\n LOG.debug(\"We found a running job. We don't search anymore.\")\n running_job = job\n # XXX: If we break, we mean that we wait for this job and ignore\n # what status other jobs might be in\n break\n elif status == 0:\n LOG.debug(\"We found a successful job. We don't search anymore.\")\n successful_job = job\n break\n else:\n LOG.debug(\"We found a job that finished but its status \"\n \"is not successful.\")\n\n if successful_job:\n # A build job has completed successfully\n # If the files are still around on FTP we can then trigger\n # the test job, otherwise, we need to trigger the build.\n LOG.info(\"There is a job that has completed successfully.\")\n LOG.debug(str(successful_job))\n files = _find_files(successful_job)\n if not _all_urls_reachable(files):\n LOG.debug(\"The files are not around on Ftp anymore:\")\n LOG.debug(files)\n trigger = build_buildername\n files = []\n else:\n # We have the files needed to trigger the test job\n trigger = buildername\n elif running_job:\n # NOTE: Note that a build might have not finished yet\n # the installer and test.zip might already have been uploaded\n # For now, we will ignore this situation but need to take note of it\n LOG.info(\"We are waiting for a build to finish.\")\n LOG.debug(str(running_job))\n trigger = None\n else:\n LOG.info(\"We are going to trigger %s instead of %s\" %\n (build_buildername, buildername))\n trigger = build_buildername\n\n return trigger, files\n\n\ndef _find_files(scheduled_job_info):\n '''\n This function helps us find the files needed to trigger a job.\n '''\n files = []\n\n # Let's grab the last job\n complete_at = scheduled_job_info[\"requests\"][0][\"complete_at\"]\n request_id = scheduled_job_info[\"requests\"][0][\"request_id\"]\n\n # NOTE: This call can take a bit of time\n job_status = buildjson.query_job_data(complete_at, request_id)\n assert job_status is not None, \\\n \"We should not have received an empty status\"\n\n properties = job_status.get(\"properties\")\n\n if not properties:\n LOG.error(str(job_status))\n raise Exception(\"The status of the job is expected to have a \"\n \"properties key, hwoever, it is missing.\")\n\n LOG.debug(\"We want to find the files needed to trigger %s\" %\n properties[\"buildername\"])\n\n if properties:\n if \"packageUrl\" in properties:\n files.append(properties[\"packageUrl\"])\n if \"testsUrl\" in properties:\n files.append(properties[\"testsUrl\"])\n\n return files\n\n\n#\n# Query functionality\n#\ndef query_jobs(repo_name, revision):\n '''\n Return list of jobs scheduling information for a revision.\n '''\n return buildapi.query_jobs_schedule(repo_name, revision)\n\n\ndef query_jobs_schedule_url(repo_name, revision):\n ''' Returns url of where a developer can login to see the\n scheduled jobs for a revision.\n '''\n return buildapi.query_jobs_url(repo_name, revision)\n\n\ndef query_repo_name_from_buildername(buildername, clobber=False):\n ''' Returns the repository name from a given buildername.\n '''\n repositories = buildapi.query_repositories(clobber)\n ret_val = None\n for repo_name in repositories:\n if repo_name in buildername:\n ret_val = repo_name\n break\n\n if ret_val is None and not clobber:\n # Since repositories file is cached, it can be that something has changed.\n # Adding clobber=True will make it overwrite the cached version with latest one.\n query_repo_name_from_buildername(buildername, clobber=True)\n\n if ret_val is None:\n raise Exception(\"Repository name not found in buildername. \"\n \"Please provide a correct buildername.\")\n\n return ret_val\n\n\ndef query_builders():\n ''' Returns list of all builders.\n '''\n return allthethings.list_builders()\n\n\ndef query_repositories():\n ''' Returns all information about the repositories we have.\n '''\n return buildapi.query_repositories()\n\n\ndef query_repository(repo_name):\n ''' Returns all information about a specific repository.\n '''\n return buildapi.query_repository(repo_name)\n\n\ndef query_repo_url(repo_name):\n ''' Returns the full repository URL for a given known repo_name.\n '''\n return buildapi.query_repo_url(repo_name)\n\n\ndef query_revisions_range(repo_name, start_revision, end_revision, version=2):\n ''' Return a list of revisions for that range.\n '''\n return pushlog.query_revisions_range(\n query_repo_url(repo_name),\n start_revision,\n end_revision,\n version\n )\n\n\n#\n# Validation code\n#\ndef valid_builder(buildername):\n ''' This function determines if the builder you're trying to trigger is\n valid.\n '''\n builders = query_builders()\n if buildername in builders:\n LOG.debug(\"Buildername %s is valid.\" % buildername)\n return True\n else:\n LOG.warning(\"Buildername %s is *NOT* valid.\" % buildername)\n LOG.info(\"Check the file we just created builders.txt for \"\n \"a list of valid builders.\")\n with open(\"builders.txt\", \"wb\") as fd:\n for b in sorted(builders):\n fd.write(b + \"\\n\")\n\n return False\n\n\n#\n# Trigger functionality\n#\ndef trigger_job(repo_name, revision, buildername, times=1, files=None, dry_run=False):\n ''' This function triggers a job through self-serve.\n We return a list of all requests made.'''\n trigger = None\n list_of_requests = []\n LOG.info(\"We want to trigger '%s' on revision '%s' a total of %d time(s).\" %\n (buildername, revision, times))\n\n if not buildapi.valid_revision(repo_name, revision):\n return []\n\n if not valid_builder(buildername):\n LOG.error(\"The builder %s requested is invalid\" % buildername)\n # XXX How should we exit cleanly?\n exit(-1)\n\n if files:\n trigger = buildername\n _all_urls_reachable(files)\n else:\n # For test and talos jobs we need to determine\n # what installer and test urls to use.\n # If there are no available files we might need to trigger\n # a build job instead\n trigger, files = _determine_trigger_objective(\n repo_name,\n revision,\n buildername,\n )\n\n if trigger:\n payload = {}\n # These propertie are needed for Treeherder to display running jobs\n payload['properties'] = json.dumps({\n \"branch\": repo_name,\n \"revision\": revision\n })\n\n if files:\n payload['files'] = json.dumps(files)\n\n url = r'''%s/%s/builders/%s/%s''' % (\n buildapi.HOST_ROOT,\n repo_name,\n trigger,\n revision\n )\n\n if not dry_run:\n for _ in range(times):\n list_of_requests.append(buildapi.make_request(url, payload))\n else:\n # We could use HTTPPretty to mock an HTTP response\n # https://github.com/gabrielfalcao/HTTPretty\n LOG.info(\"We were going to post to this url: %s\" % url)\n LOG.info(\"With this payload: %s\" % str(payload))\n if files:\n LOG.info(\"With these files: %s\" % str(files))\n else:\n LOG.debug(\"Nothing needs to be triggered\")\n\n return list_of_requests\n\n\ndef trigger_range(buildername, repo_name, revisions, times, dry_run=False):\n '''\n Schedule the job named \"buildername\" (\"times\" times) from \"start_revision\" to\n \"end_revision\".\n '''\n LOG.info(\"We want to have %s job(s) of %s on revisions %s\" %\n (times, buildername, str(revisions)))\n for rev in revisions:\n LOG.info(\"\")\n LOG.info(\"=== %s ===\" % rev)\n LOG.info(\"We want to have %s job(s) of %s on revision %s\" %\n (times, buildername, rev))\n\n # 1) How many potentially completed jobs can we get for this buildername?\n jobs = query_jobs(repo_name, rev)\n matching_jobs = _matching_jobs(buildername, jobs)\n successful_jobs = 0\n pending_jobs = 0\n running_jobs = 0\n\n for job in matching_jobs:\n status = buildapi.query_job_status(job)\n if status == buildapi.PENDING:\n pending_jobs += 1\n if status == buildapi.RUNNING:\n running_jobs += 1\n if status == buildapi.SUCCESS:\n successful_jobs += 1\n\n potential_jobs = pending_jobs + running_jobs + successful_jobs\n LOG.debug(\"We found %d pending jobs, %d running jobs and %d successful_jobs.\" %\n (pending_jobs, running_jobs, successful_jobs))\n\n if potential_jobs >= times:\n LOG.info(\"We have %d job(s) for '%s' which is enough for the %d job(s) we want.\" %\n (potential_jobs, buildername, times))\n else:\n # 2) If we have less potential jobs than 'times' instances then\n # we need to fill it in.\n LOG.debug(\"We have found %d job(s) matching '%s' on %s. We need to trigger more.\" %\n (potential_jobs, buildername, rev))\n list_of_requests = \\\n trigger_job(\n repo_name,\n rev,\n buildername,\n times=times-potential_jobs,\n dry_run=dry_run)\n if list_of_requests and any(req.status_code != 202 for req in list_of_requests):\n LOG.warning(\"Not all requests succeeded.\")\n\n # TODO:\n # 3) Once we trigger a build job, we have to monitor it to make sure that it finishes;\n # at that point we have to trigger as many test jobs as we originally intended\n # If a build job does not finish, we have to notify the user... what should it then\n # happen?\n" }, { "alpha_fraction": 0.6369863152503967, "alphanum_fraction": 0.6369863152503967, "avg_line_length": 15.222222328186035, "blob_id": "303381b1c4b949196e07dcb84058dc9f321103ac", "content_id": "cba094d28121a69444043f1652eb9f0b24da5285", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 146, "license_type": "no_license", "max_line_length": 39, "num_lines": 9, "path": "/docs/buildjson.rst", "repo_name": "valeriat/mozilla_ci_tools", "src_encoding": "UTF-8", "text": ":mod:`buildjson`\n################\n\nTODO: Better document this.\n\nThe module :mod:`buildjson`\n\n.. automodule:: mozci.sources.buildjson\n :members:\n" } ]
21
rpasta42/7z-fs
https://github.com/rpasta42/7z-fs
ce5dd7b799e4fd8cc7e5af186762844528aea6c7
65ce44174d4de0000ffa27cf6de60ac2637750a0
c8ff60250208b7625622ee876700d2f8781fae59
refs/heads/master
2020-03-20T18:40:29.803225
2018-06-17T14:48:36
2018-06-17T14:48:36
137,599,478
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6285714507102966, "alphanum_fraction": 0.6571428775787354, "avg_line_length": 12.600000381469727, "blob_id": "49cb7be8b0f9ceee0d9b728995ea143a2cde11c1", "content_id": "f8dc094f7787be82c0efeb272b60a4151ce60197", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 140, "license_type": "no_license", "max_line_length": 38, "num_lines": 10, "path": "/README.md", "repo_name": "rpasta42/7z-fs", "src_encoding": "UTF-8", "text": "\n##Installation\n\n```bash\nsudo pip3 install fusepy\nsudo ln -s /usr/bin/7z /usr/bin/sevenz\n\n```\n\n##Usage\n`./7z-fs.py archive.7z mount_pnt`\n\n\n\n" }, { "alpha_fraction": 0.4948776364326477, "alphanum_fraction": 0.5116676092147827, "avg_line_length": 19.430233001708984, "blob_id": "27efe062b147d773a14475f18f44c2efcbd2b05f", "content_id": "0f7b5002f93644e5eca1f858104e27ba994f0a99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3514, "license_type": "no_license", "max_line_length": 70, "num_lines": 172, "path": "/7z-fs.py", "repo_name": "rpasta42/7z-fs", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\nimport os, sys, errno\n\nimport sh\nfrom sh import sevenz\n\nfrom fuse import FUSE, FuseOSError, Operations\n\nfrom utiltools import shellutils as shu\n\n#sh.sudo('ln -s /usr/bin/7z /usr/bin/sevenz')\n\ndef parse_7z_list_names(out):\n lines = out.split('\\n')\n\n names_started = False\n\n fnames = []\n\n for line in lines:\n if '----' in line:\n if not names_started:\n names_started = True\n continue\n else:\n break\n if names_started:\n words = line.split(' ')\n if len(words) > 0:\n fnames.append(words[-1])\n pass\n\n return fnames\n\n\ndef parse_7z_list(out):\n lines = out.split('\\n')\n\n names_started = False\n\n files = []\n\n for line in lines:\n\n if '----' in line:\n if not names_started:\n names_started = True\n continue\n else:\n break\n pass\n\n if names_started:\n\n words = list(filter(lambda x: x!='', line.split(' ')))\n #print(words)\n\n if len(words) > 0:\n fdata = {}\n\n fdata['date'] = words[0]\n fdata['time'] = words[1]\n fdata['attr'] = words[2]\n fdata['size'] = int(words[3])\n fdata['compressed'] = int(words[4])\n fdata['name'] = words[-1]\n\n files.append(fdata)\n pass\n\n pass\n\n pass\n\n return files\n\n\ndef mk_tmp():\n rand_str = shu.rand_str(10)\n tmp_path = '/tmp/7z_fs/tmp_' + rand_str\n shu.mkdir(tmp_path)\n return tmp_path\n\n\nclass SevenZipFs(Operations):\n\n def __init__(self, root):\n root = root.replace('.7z', '') + '.7z'\n\n self.root = root\n self.tmp_path = mk_tmp()\n print('tmp path:', self.tmp_path)\n\n if shu.file_exists(root):\n sh.sevenz('a', root, '.empty_file')\n\n\n pass\n\n def access(self, path, mode):\n print('access')\n pass\n def chmod(self, path, mode):\n print('chmod')\n pass\n def chown(self, path, uid, gid):\n print('chown')\n pass\n\n\n def getattr(self, path, fh=None):\n print('getattr', path, fh)\n out = sh.sevenz('l', self.root)\n flist = parse_7z_list(out)\n\n if path == '/':\n return {\n 'st_mode' : 16877,\n 'st_nlink' : 2\n }\n\n ret = {\n #'st_mtime' : flist[0]['time'],\n 'st_atime' : 0,\n 'st_ctime' : 0,\n 'st_gid' : 1000,\n 'st_mode' : (33204 & 40000), #33204,\n 'st_mtime' : 0,\n 'st_nlink' : 1,\n 'st_size' : flist[0]['size'],\n 'st_uid' : 1000\n }\n\n return ret\n\n\n def readdir(self, path, fh):\n print('readdir', path, fh)\n #print(self.getattr('/'))\n\n out = sh.sevenz('l', self.root)\n dirents = parse_7z_list_names(out)\n\n #for r in dirents:\n # yield r\n return dirents\n\n def unlink(self, path):\n print('unlink', path)\n #sh.sevenz('d',\n\n #File methods\n def read(self, path, length, offset, fh):\n print('read', path, length, offset, fh)\n\n fname = path.split('/')[-1]\n\n out = sh.sevenz('l', self.root)\n if not (fname in parse_7z_list_names(out)):\n return None\n\n sevenz('e', self.root, fname, '-o' + self.tmp_path)\n fval = shu.read_file(self.tmp_path + '/' + fname, binary=True)\n return fval[offset:offset+length]\n pass\n\ndef main(mountpoint, root):\n FUSE(SevenZipFs(root), mountpoint, nothreads=True, foreground=True)\n\nif __name__ == '__main__':\n main(sys.argv[2], sys.argv[1])\n" } ]
2
ficusrobusta/HackerRank_coding_problems
https://github.com/ficusrobusta/HackerRank_coding_problems
fee54000a96df3f35865b06b11778092564c502d
6c903f2b661d8c784e6308c7dea1a9ffa0df62be
11de512b9334b833ca2e3c46b8c7a504f61e10da
refs/heads/main
2023-07-15T20:05:56.211931
2021-02-08T18:06:51
2021-02-08T18:06:51
333,085,358
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6871795058250427, "alphanum_fraction": 0.7025641202926636, "avg_line_length": 22.214284896850586, "blob_id": "a8cbf71f8e06f8b984a49eee1e3fb82b28feb69d", "content_id": "a72cd716e8e7120341c5578924c5e69a8c187e6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 975, "license_type": "no_license", "max_line_length": 132, "num_lines": 42, "path": "/Arrays.py", "repo_name": "ficusrobusta/HackerRank_coding_problems", "src_encoding": "UTF-8", "text": "# Problem\n# Objective \n# Today, we will learn about the Array data structure. Check out the Tutorial tab for learning materials and an instructional video.\n# Task \n# Given an array, , of integers, print 's elements in reverse order as a single line of space-separated numbers.\n# Example\n\n# Print 4 3 2 1. Each integer is separated by one space.\n# Input Format\n# The first line contains an integer, (the size of our array). \n# The second line contains space-separated integers that describe array 's elements.\n# Constraints\n# Constraints\n\n# , where is the integer in the array.\n# Output Format\n# Print the elements of array in reverse order as a single line of space-separated numbers.\n# Sample Input\n# 4\n# 1 4 3 2\n# Sample Output\n# 2 3 4 1\n\n# Solution\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n\nif __name__ == '__main__':\n n = int(input())\n\n arr = list(map(int, input().rstrip().split()))\n\n \nprint(\" \".join(map(str, arr[::-1])))\n" }, { "alpha_fraction": 0.7089337110519409, "alphanum_fraction": 0.7146974205970764, "avg_line_length": 27.91666603088379, "blob_id": "66a0ed4a2429f862323329f095ca1820f0f09f0c", "content_id": "d5e2cd58ade3564333f9ad8dba20e9fa28c90ca5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1041, "license_type": "no_license", "max_line_length": 192, "num_lines": 36, "path": "/Let's_Review.py", "repo_name": "ficusrobusta/HackerRank_coding_problems", "src_encoding": "UTF-8", "text": "# Problem\n# Objective \n# Today we will expand our knowledge of strings, combining it with what we have already learned about loops. Check out the Tutorial tab for learning materials and an instructional video.\n# Task \n# Given a string, , of length that is indexed from to , print its even-indexed and odd-indexed characters as space-separated strings on a single line (see the Sample below for more detail).\n# Note: is considered to be an even index.\n# Example\n\n# Print abc def\n# Input Format\n# The first line contains an integer, (the number of test cases). \n# Each line of the subsequent lines contain a string, .\n# Constraints\n\n\n# Output Format\n# For each String (where ), print 's even-indexed characters, followed by a space, followed by 's odd-indexed characters.\n# Sample Input\n# 2\n# Hacker\n# Rank\n# Sample Output\n# Hce akr\n# Rn ak\n\n# Solution\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nT = int(input())\ns = [] \n\nfor i in range(1,T+1):\n s.append(input())\n\nfor i in s:\n print(i[::2], i[1::2])\n" }, { "alpha_fraction": 0.49948185682296753, "alphanum_fraction": 0.582383394241333, "avg_line_length": 16.23214340209961, "blob_id": "70464b5c3de82e52b035cedf07e0e1fe80fed6d8", "content_id": "fb102047c7ec99c2509dc5638c9486c6cefbd7e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 965, "license_type": "no_license", "max_line_length": 134, "num_lines": 56, "path": "/Loops.py", "repo_name": "ficusrobusta/HackerRank_coding_problems", "src_encoding": "UTF-8", "text": "# Poblem\n# Objective \n# In this challenge, we will use loops to do some math. Check out the Tutorial tab to learn more.\n# Task \n# Given an integer, , print its first multiples. Each multiple (where ) should be printed on a new line in the form: n x i = result.\n# Example \n\n# The printout should look like this:\n# 3 x 1 = 3\n# 3 x 2 = 6\n# 3 x 3 = 9\n# 3 x 4 = 12\n# 3 x 5 = 15\n# 3 x 6 = 18\n# 3 x 7 = 21\n# 3 x 8 = 24\n# 3 x 9 = 27\n# 3 x 10 = 30\n# Input Format\n# A single integer, .\n# Constraints\n\n# Output Format\n# Print lines of output; each line (where ) contains the of in the form: \n# n x i = result.\n# Sample Input\n# 2\n# Sample Output\n# 2 x 1 = 2\n# 2 x 2 = 4\n# 2 x 3 = 6\n# 2 x 4 = 8\n# 2 x 5 = 10\n# 2 x 6 = 12\n# 2 x 7 = 14\n# 2 x 8 = 16\n# 2 x 9 = 18\n# 2 x 10 = 20\n\n# Solution\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n\nif __name__ == '__main__':\n n = int(input())\n\n for i in range(1,11):\n print(n,\"x\", i, \"=\", n*i)\n" }, { "alpha_fraction": 0.6561886072158813, "alphanum_fraction": 0.6954813599586487, "avg_line_length": 34.71929931640625, "blob_id": "4c72ce5cf9c8ee0fb386adf7e376e03fb1ddfede", "content_id": "dffb04051bb69340afa1084ae0c403819d9f36af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2036, "license_type": "no_license", "max_line_length": 197, "num_lines": 57, "path": "/Mean_Median_Mode.py", "repo_name": "ficusrobusta/HackerRank_coding_problems", "src_encoding": "UTF-8", "text": "# Problem\n# Objective \n# In this challenge, we practice calculating the mean, median, and mode. Check out the Tutorial tab for learning materials and an instructional video!\n# Task \n# Given an array, , of integers, calculate and print the respective mean, median, and mode on separate lines. If your array contains more than one modal value, choose the numerically smallest one.\n# Note: Other than the modal value (which will always be an integer), your answers should be in decimal form, rounded to a scale of decimal place (i.e., , format).\n# The mean is . \n# The median is . \n# The mode is because occurs most frequently.\n# Input Format\n# The first line contains an integer, , the number of elements in the array. \n# The second line contains space-separated integers that describe the array's elements\n# , where is the element of the array.\n# Output Format\n# Print lines of output in the following order:\n# Print the mean on the first line to a scale of decimal place (i.e., , ).\n# Print the median on a new line, to a scale of decimal place (i.e., , ).\n# Print the mode on a new line. If more than one such value exists, print the numerically smallest one.\n# Sample Input\n# 10\n# 64630 11735 14216 99233 14470 4978 73429 38120 51135 67060\n# Sample Output\n# 43900.6\n# 44627.5\n# 4978\n\n# Solution \nEnter your code here. Read input from STDIN. Print output to STDOUT\nimport statistics\n\nN = int(input())\nX = list(map(int, input().split()))\n\nx_sort = sorted(X)\nmean = sum(X) / N\nnums = list(set(X))\nnum_count = {} \nfor num in nums:\n num_count[num] = X.count(num)\n# num_count = sorted(num_count.items(), key=lambda x: x[1]) \nif N % 2 != 0:\n median = x_sort[int(N/2)+1]\nelse:\n median = (x_sort[int(N/2)-1] + x_sort[int(N/2)]) / 2\n# median = statistics.median(X)\nall_values = num_count.values()\nmax_value = max(all_values)\nif max_value != 1:\n mode = statistics.mode(x_sort)\n \n # mode = max(num_count, key = num_count.get)\nelse:\n mode = x_sort[0]\n \nprint(round(mean,1))\nprint(round(median,1))\nprint(mode)\n" }, { "alpha_fraction": 0.6864808201789856, "alphanum_fraction": 0.7022619843482971, "avg_line_length": 36.27450942993164, "blob_id": "124974191fb1afd450670a18a5934da712134326", "content_id": "1f81c2742ce33fd6dce6b91429059d6825c3c165", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1901, "license_type": "no_license", "max_line_length": 265, "num_lines": 51, "path": "/Interquartile_Range.py", "repo_name": "ficusrobusta/HackerRank_coding_problems", "src_encoding": "UTF-8", "text": "# Solution\n# Objective \n# In this challenge, we practice calculating the interquartile range. We recommend you complete the Quartiles challenge before attempting this problem.\n# Task \n# The interquartile range of an array is the difference between its first () and third () quartiles (i.e., ).\n# Given an array, , of integers and an array, , representing the respective frequencies of 's elements, construct a data set, , where each occurs at frequency . Then calculate and print 's interquartile range, rounded to a scale of decimal place (i.e., format).\n# Tip: Be careful to not use integer division when averaging the middle two elements for a data set with an even number of elements, and be sure to not include the median in your upper and lower data sets.\n# Input Format\n# The first line contains an integer, , denoting the number of elements in arrays and . \n# The second line contains space-separated integers describing the respective elements of array . \n# The third line contains space-separated integers describing the respective elements of array .\n# Constraints\n\n# , where is the element of array .\n# , where is the element of array .\n# The number of elements in is equal to .\n# Output Format\n# Print the interquartile range for the expanded data set on a new line. Round your answer to a scale of decimal place (i.e., format).\n# Sample Input\n# 6\n# 6 12 8 10 20 16\n# 5 4 3 2 1 5\n# Sample Output\n# 9.0\n\n# Problem\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nfrom statistics import median\nN = int(input())\nX = list(map(int, input().split()))\nF = list(map(int, input().split()))\nS = []\n\nfor i in range(N):\n S += [X[i]] * F[i]\n\nS = sorted(S)\nnums = len(S)\n\nif nums % 2 != 0:\n L = S[:int(nums/2)]\n U = S[int((nums/2)+1):]\n \nelse:\n L = S[:int(nums/2)]\n U = S[int(nums/2):]\n\nQ1 = median(L)\nQ3 = median(U)\nIQR = float(Q3 - Q1)\nprint(IQR)\n" }, { "alpha_fraction": 0.6633573770523071, "alphanum_fraction": 0.6787003874778748, "avg_line_length": 21.612245559692383, "blob_id": "04b3a3a343085a4287084a57a95c08a2a0fa8093", "content_id": "2ff7c4b96819195e83ed246a4e81eb21c6b672dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1108, "license_type": "no_license", "max_line_length": 137, "num_lines": 49, "path": "/Intro_To_Conditional_Statements.py", "repo_name": "ficusrobusta/HackerRank_coding_problems", "src_encoding": "UTF-8", "text": "# Problem\n# Objective \n# In this challenge, we learn about conditional statements. Check out the Tutorial tab for learning materials and an instructional video.\n# Task \n# Given an integer, , perform the following conditional actions:\n# If is odd, print Weird\n# If is even and in the inclusive range of to , print Not Weird\n# If is even and in the inclusive range of to , print Weird\n# If is even and greater than , print Not Weird\n# Complete the stub code provided in your editor to print whether or not is weird.\n# Input Format\n# A single line containing a positive integer, .\n# Constraints\n\n# Output Format\n# Print Weird if the number is weird; otherwise, print Not Weird.\n# Sample Input 0\n# 3\n# Sample Output 0\n# Weird\n# Sample Input 1\n# 24\n# Sample Output 1\n# Not Weird\n\n# Solution\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\nif __name__ == '__main__':\n N = int(input())\n\n \nif N % 2 != 0:\n print(\"Weird\")\nelse:\n if N in range(2,6):\n print(\"Not Weird\")\n elif N in range(6,21):\n print(\"Weird\")\n elif N > 20:\n print(\"Not Weird\")\n" }, { "alpha_fraction": 0.6972147226333618, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 31.735294342041016, "blob_id": "347278e329f97cfb0a06e5fe1397c6674bc60a68", "content_id": "2596d04f54c672647063c22ebfcc6b782a1ae39d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1113, "license_type": "no_license", "max_line_length": 236, "num_lines": 34, "path": "/Standard_Deviation.py", "repo_name": "ficusrobusta/HackerRank_coding_problems", "src_encoding": "UTF-8", "text": "# Problem\n# Objective \n# In this challenge, we practice calculating standard deviation. Check out the Tutorial tab for learning materials and an instructional video!\n# Task \n# Given an array, , of integers, calculate and print the standard deviation. Your answer should be in decimal form, rounded to a scale of decimal place (i.e., format). An error margin of will be tolerated for the standard deviation.\n# Input Format\n# The first line contains an integer, , denoting the number of elements in the array. \n# The second line contains space-separated integers describing the respective elements of the array.\n# Constraints\n\n# , where is the element of array .\n# Output Format\n# Print the standard deviation on a new line, rounded to a scale of decimal place (i.e., format).\n# Sample Input\n# 5\n# 10 40 30 50 20\n# Sample Output\n# 14.1\n\n# Solution\n# Enter your code here. Read input from STDIN. Print output to STDOUT\n\nN = int(input())\nX = list(map(int, input().split()))\n\nmean = sum(X) / N\n\nstdev = 0\nfor i in range(N):\n stdev += (X[i] - mean)**2\n\nstdev = (stdev / N)**(1/2)\n \nprint(round(stdev,1))\n" }, { "alpha_fraction": 0.5952522158622742, "alphanum_fraction": 0.6219584345817566, "avg_line_length": 28.05172348022461, "blob_id": "39d35d578512fc73e7b11cf90b1ccbc217ce8799", "content_id": "4cdd35b06dd64dcc6826e331b98cc702a86b6dee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1685, "license_type": "no_license", "max_line_length": 192, "num_lines": 58, "path": "/Sales_By_Match.py", "repo_name": "ficusrobusta/HackerRank_coding_problems", "src_encoding": "UTF-8", "text": "# Problem\n# There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.\n# There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is .\n# Function Description\n# Complete the sockMerchant function in the editor below.\n# sockMerchant has the following parameter(s):\n# int n: the number of socks in the pile\n# int ar[n]: the colors of each sock\n# Returns\n# int: the number of pairs\n# Input Format\n# The first line contains an integer , the number of socks represented in . \n# The second line contains space-separated integers, , the colors of the socks in the pile.\n# Sample Input\n# STDIN Function\n# ----- --------\n# 9 n = 9\n# 10 20 20 10 10 30 50 10 20 ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]\n# Sample Output\n# 3\n\n# Solution\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the sockMerchant function below.\ndef sockMerchant(n, ar):\n total_pairs = 0\n i = 0\n colours = list(set(ar))\n if n <= 1:\n print(total_pairs)\n else:\n while i< len(colours):\n colour = colours[i]\n total_pairs = total_pairs + int(ar.count(colour) / 2) \n i = i + 1\n print(total_pairs)\n return total_pairs\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n ar = list(map(int, input().rstrip().split()))\n\n result = sockMerchant(n, ar)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n" }, { "alpha_fraction": 0.6566068530082703, "alphanum_fraction": 0.6835236549377441, "avg_line_length": 25.085105895996094, "blob_id": "8a22ca9e5872e458f08f51d3b165ecc5a7f66f7a", "content_id": "98da82280685b0f0d79394daa140b0ed6816876e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1226, "license_type": "no_license", "max_line_length": 165, "num_lines": 47, "path": "/Quartiles.py", "repo_name": "ficusrobusta/HackerRank_coding_problems", "src_encoding": "UTF-8", "text": "#Problem\n# Objective \n# In this challenge, we practice calculating quartiles. Check out the Tutorial tab for learning materials and an instructional video!\n# Task \n# Given an array, , of integers, calculate the respective first quartile (), second quartile (), and third quartile (). It is guaranteed that , , and are integers.\n# Input Format\n# The first line contains an integer, , denoting the number of elements in the array. \n# The second line contains space-separated integers describing the array's elements.\n# Constraints\n\n# , where is the element of the array.\n# Output Format\n# Print lines of output in the following order:\n# The first line should be the value of .\n# The second line should be the value of .\n# The third line should be the value of .\n# Sample Input\n# 9\n# 3 7 8 5 12 14 21 13 18\n# Sample Output\n# 6\n# 12\n# 16\n\n#Solution\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nfrom statistics import median\n\nN = int(input())\nX = list(map(int, input().split()))\nX = sorted(X)\n\nif N % 2 != 0:\n L = X[:int(N/2)]\n U = X[int((N/2)+1):]\n \nelse:\n L = X[:int(N/2)]\n U = X[int(N/2):]\n\nQ2 = int(median(X))\nQ1 = int(median(L))\nQ3 = int(median(U))\n\nprint(Q1)\nprint(Q2)\nprint(Q3)\n" }, { "alpha_fraction": 0.7023105621337891, "alphanum_fraction": 0.717356264591217, "avg_line_length": 35.490196228027344, "blob_id": "a9c7473f23180ead729728cdcad5684d2532f176", "content_id": "bf18ba14e460a8a86aa86352873787c73629e559", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1861, "license_type": "no_license", "max_line_length": 273, "num_lines": 51, "path": "/Operators.py", "repo_name": "ficusrobusta/HackerRank_coding_problems", "src_encoding": "UTF-8", "text": "# Problem\n# Objective \n# In this challenge, you will work with arithmetic operators. Check out the Tutorial tab for learning materials and an instructional video.\n# Task \n# Given the meal price (base cost of a meal), tip percent (the percentage of the meal price being added as tip), and tax percent (the percentage of the meal price being added as tax) for a meal, find and print the meal's total cost. Round the result to the nearest integer.\n# Example \n# A tip of 15% * 100 = 15, and the taxes are 8% * 100 = 8. Print the value and return from the function.\n# Function Description \n# Complete the solve function in the editor below.\n# solve has the following parameters:\n# int meal_cost: the cost of food before tip and tax\n# int tip_percent: the tip percentage\n# int tax_percent: the tax percentage\n# Returns The function returns nothing. Print the calculated value, rounded to the nearest integer.\n# Note: Be sure to use precise values for your calculations, or you may end up with an incorrectly rounded result.\n# Input Format\n# There are lines of numeric input: \n# The first line has a double, (the cost of the meal before tax and tip). \n# The second line has an integer, (the percentage of being added as tip). \n# The third line has an integer, (the percentage of being added as tax).\n# Sample Input\n# 12.00\n# 20\n# 8\n# Sample Output\n# 15\n\n# Solution\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the solve function below.\ndef solve(meal_cost, tip_percent, tax_percent):\n tip = float(meal_cost / 100 * tip_percent)\n tax = float(meal_cost / 100 * tax_percent)\n total_cost = round(meal_cost + tip + tax)\n print(total_cost)\n \nif __name__ == '__main__':\n meal_cost = float(input())\n\n tip_percent = int(input())\n\n tax_percent = int(input())\n\n solve(meal_cost, tip_percent, tax_percent)\n" }, { "alpha_fraction": 0.7045636773109436, "alphanum_fraction": 0.7213770747184753, "avg_line_length": 38.03125, "blob_id": "d3b4774cbe4d79fc20dcd647fee6f7cce2ae02a1", "content_id": "680ea94992092f0a5418196e4fcb3497de1f5bfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1249, "license_type": "no_license", "max_line_length": 229, "num_lines": 32, "path": "/Weighted_Mean.py", "repo_name": "ficusrobusta/HackerRank_coding_problems", "src_encoding": "UTF-8", "text": "# Problem\n# Objective \n# In the previous challenge, we calculated a mean. In this challenge, we practice calculating a weighted mean. Check out the Tutorial tab for learning materials and an instructional video!\n# Task \n# Given an array, , of integers and an array, , representing the respective weights of 's elements, calculate and print the weighted mean of 's elements. Your answer should be rounded to a scale of decimal place (i.e., format).\n# Input Format\n# The first line contains an integer, , denoting the number of elements in arrays and . \n# The second line contains space-separated integers describing the respective elements of array . \n# The third line contains space-separated integers describing the respective elements of array .\n# Output Format\n# Print the weighted mean on a new line. Your answer should be rounded to a scale of decimal place (i.e., format).\n# Sample Input\n# 5\n# 10 40 30 50 20\n# 1 2 3 4 5\n# Sample Output\n# 32.0\n\n\n# Solution\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nN = int(input())\nX = list(map(int, input().split()))\nW = list(map(int, input().split()))\nZ = 0\n\nfor i in range(N):\n Z = Z + (X[i]*W[i])\nW_sum = sum(W)\nWeight_mean = round((Z / W_sum),1)\n\nprint(Weight_mean)\n" } ]
11
Eugenec139/torpy
https://github.com/Eugenec139/torpy
96474aa8db4f23244a160234d42795798f80eccd
c0b2b6dedf4d1456e373a2d0ed44cf4286391b9a
03ea844e709c068227746de90a052d59ad4914c5
refs/heads/master
2022-12-04T17:12:45.546083
2020-08-28T22:10:05
2020-08-28T22:10:05
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5612000226974487, "alphanum_fraction": 0.6240800023078918, "avg_line_length": 41.955326080322266, "blob_id": "02f4878d0f891b20ff25739d2503facad7e6464b", "content_id": "a912b6833ab92fa9b18005c1467783a04ffd7a9e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12500, "license_type": "permissive", "max_line_length": 120, "num_lines": 291, "path": "/torpy/consesus.py", "repo_name": "Eugenec139/torpy", "src_encoding": "UTF-8", "text": "# Copyright 2019 James Brown\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport socket\nimport random\nimport logging\nimport functools\nfrom base64 import b32decode\nfrom threading import Lock\n\nfrom torpy.utils import retry, log_retry\nfrom torpy.http.client import HttpStreamClient\nfrom torpy.documents import TorDocumentsFactory\nfrom torpy.guard import TorGuard\nfrom torpy.cache_storage import TorCacheDirStorage\nfrom torpy.crypto_common import rsa_verify, rsa_load_der\nfrom torpy.documents.network_status import RouterFlags, NetworkStatusDocument, FetchDescriptorError, Router\nfrom torpy.documents.dir_key_certificate import DirKeyCertificate\nfrom torpy.documents.network_status_diff import NetworkStatusDiffDocument\n\nlogger = logging.getLogger(__name__)\n\n\nclass DirectoryAuthority(Router):\n \"\"\"This class represents a directory authority.\"\"\"\n\n def __init__(self, nickname, address, or_port, v3ident, fingerprint, ipv6=None, bridge=False):\n ip, dir_port = address.split(':')\n super().__init__(nickname, bytes.fromhex(fingerprint), ip, or_port, dir_port, RouterFlags.Authority)\n self._v3ident = v3ident\n self._ipv6 = ipv6\n self._bridge = bridge\n\n @property\n def v3ident(self):\n return self._v3ident\n\n\nclass DirectoryAuthoritiesList:\n \"\"\"Hardcoded into each Tor client is the information about 10 beefy Tor nodes run by trusted volunteers.\"\"\"\n\n def __init__(self):\n # tor ref src\\app\\config\\auth_dirs.inc\n # fmt: off\n self._directory_authorities = [\n DirectoryAuthority('moria1', '128.31.0.39:9131', 9101, 'D586D18309DED4CD6D57C18FDB97EFA96D330566',\n '9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31'),\n DirectoryAuthority('tor26', '86.59.21.38:80', 443, '14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4',\n '847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D',\n ipv6='[2001:858:2:2:aabb:0:563b:1526]:443'),\n DirectoryAuthority('dizum', '45.66.33.45:80', 443, 'E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58',\n '7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755'),\n DirectoryAuthority('Serge', '66.111.2.131:9030', 9001, None,\n 'BA44 A889 E64B 93FA A2B1 14E0 2C2A 279A 8555 C533',\n bridge=True),\n DirectoryAuthority('gabelmoo', '131.188.40.189:80', 443, 'ED03BB616EB2F60BEC80151114BB25CEF515B226',\n 'F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281',\n ipv6='[2001:638:a000:4140::ffff:189]:443'),\n DirectoryAuthority('dannenberg', '193.23.244.244:80', 443, '0232AF901C31A04EE9848595AF9BB7620D4C5B2E',\n '7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123',\n ipv6='[2001:678:558:1000::244]:443'),\n DirectoryAuthority('maatuska', '171.25.193.9:443', 80, '49015F787433103580E3B66A1707A00E60F2D15B',\n 'BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810',\n ipv6='[2001:67c:289c::9]:80'),\n DirectoryAuthority('Faravahar', '154.35.175.225:80', 443, 'EFCBE720AB3A82B99F9E953CD5BF50F7EEFC7B97',\n 'CF6D 0AAF B385 BE71 B8E1 11FC 5CFF 4B47 9237 33BC'),\n DirectoryAuthority('longclaw', '199.58.81.140:80', 443, '23D15D965BC35114467363C165C4F724B64B4F66',\n '74A9 1064 6BCE EFBC D2E8 74FC 1DC9 9743 0F96 8145'),\n DirectoryAuthority('bastet', '204.13.164.118:80', 443, '27102BC123E7AF1D4741AE047E160C91ADC76B21',\n '24E2 F139 121D 4394 C54B 5BCC 368B 3B41 1857 C413',\n ipv6='[2620:13:4000:6000::1000:118]:443'),\n ]\n # fmt: on\n\n def find(self, identity):\n return next((authority for authority in self._directory_authorities if authority.v3ident == identity), None)\n\n @property\n def authority_fpr_list(self):\n return '+'.join([authority.v3ident[:6] for authority in self._directory_authorities if authority.v3ident])\n\n @property\n def consensus_url(self):\n # tor ref: directory_get_consensus_url\n return f'/tor/status-vote/current/consensus/{self.authority_fpr_list}.z'\n\n def download_consensus(self, prev_hash=None):\n authority = self.get_random()\n logger.info('Downloading new consensus from %s authority', authority.nickname)\n\n # tor ref: directory_get_from_dirserver DIR_PURPOSE_FETCH_CONSENSUS\n # tor ref: directory_send_command\n with TorGuard(authority) as guard:\n with guard.create_circuit(0) as circ:\n with circ.create_stream() as stream:\n stream.connect_dir()\n http_client = HttpStreamClient(stream)\n headers = {'X-Or-Diff-From-Consensus': prev_hash} if prev_hash else None\n _, response = http_client.get(authority.ip, self.consensus_url, headers=headers)\n return response.decode()\n\n def download_fp_sk(self, identity, keyid):\n # TODO: multiple key download\n authority = self.get_random()\n logger.info('Downloading fp-sk from %s', authority.nickname)\n\n # tor ref: directory_get_from_dirserver DIR_PURPOSE_FETCH_CONSENSUS\n # tor ref: directory_send_command\n with TorGuard(authority) as guard:\n with guard.create_circuit(0) as circ:\n with circ.create_stream() as stream:\n stream.connect_dir()\n http_client = HttpStreamClient(stream)\n url = f'{authority.fp_sk_url}/{identity}-{keyid}'\n _, response = http_client.get(authority.ip, url)\n return response.decode()\n\n @property\n def count(self):\n return len(self._directory_authorities)\n\n def get_random(self):\n return random.choice(self._directory_authorities)\n\n\nclass TorConsensus:\n def __init__(self, authorities=None, cache_storage=None):\n self._lock = Lock()\n self._authorities = authorities or DirectoryAuthoritiesList()\n self._cache_storage = cache_storage or TorCacheDirStorage()\n self._document = self._cache_storage.load_document(NetworkStatusDocument)\n if self._document:\n self._document.link_consensus(self)\n self.renew()\n\n @property\n def document(self):\n self.renew()\n return self._document\n\n @retry(3, BaseException,\n log_func=functools.partial(log_retry, msg='Retry with another authority...', no_traceback=(socket.timeout,)))\n def renew(self, force=False):\n with self._lock:\n if not force and self._document and self._document.is_fresh:\n return\n\n # tor ref: networkstatus_set_current_consensus\n\n prev_hash = self._document.digest_sha3_256.hex() if self._document else None\n raw_string = self._authorities.download_consensus(prev_hash)\n\n # Make sure it's parseable\n new_doc = TorDocumentsFactory.parse(raw_string, possible=(NetworkStatusDocument, NetworkStatusDiffDocument))\n if new_doc is None:\n raise Exception('Unknown document has been received')\n\n if type(new_doc) is NetworkStatusDiffDocument:\n new_doc = self._document.apply_diff(new_doc)\n\n new_doc.link_consensus(self)\n\n if not self.verify(new_doc):\n raise Exception('Invalid consensus')\n\n # Use new consensus document\n self._document = new_doc\n self._cache_storage.save_document(new_doc)\n\n def verify(self, new_doc):\n # tor ref: networkstatus_check_consensus_signature\n signed = 0\n required = self._authorities.count / 2\n\n for voter in new_doc.voters:\n sign = new_doc.find_signature(voter.fingerprint)\n if not sign:\n logger.debug('Not sign by %s (%s)', voter.nickname, voter.fingerprint)\n continue\n\n trusted = self._authorities.find(sign['identity'])\n if not trusted:\n logger.warning('Unknown voter present')\n continue\n\n doc_digest = new_doc.get_digest(sign['algorithm'])\n # TODO: download through circuit\n pubkey = self._get_pubkey(sign['identity'], sign['signing_key_digest'])\n if rsa_verify(pubkey, sign['signature'], doc_digest):\n signed += 1\n return signed > required # more 50% percents of authorities sign\n\n def _get_pubkey(self, identity, signing_key_digest):\n key_certificate = self._authorities.download_fp_sk(identity, signing_key_digest)\n certs = DirKeyCertificate(key_certificate)\n return rsa_load_der(certs.dir_signing_key)\n\n def get_router(self, fingerprint) -> Router:\n # TODO: make mapping with fingerprint as key?\n fingerprint_b = b32decode(fingerprint.upper())\n return next(onion_router for onion_router in self.document.routers if onion_router.fingerprint == fingerprint_b)\n\n def get_routers(self, flags=None, has_dir_port=True):\n \"\"\"\n Select consensus routers that satisfy certain parameters.\n\n :param flags: Router flags\n :param has_dir_port: Has dir port\n :return: return list of routers\n \"\"\"\n results = []\n\n for onion_router in self.document.routers:\n if flags and not all(f in onion_router.flags for f in flags):\n continue\n if has_dir_port and not onion_router.dir_port:\n continue\n results.append(onion_router)\n\n return results\n\n def get_random_router(self, flags=None, has_dir_port=None):\n \"\"\"\n Select a random consensus router that satisfy certain parameters.\n\n :param flags: Router flags\n :param has_dir_port: Has dir port\n :return: router\n \"\"\"\n routers = self.get_routers(flags, has_dir_port)\n return random.choice(routers)\n\n def get_random_guard_node(self, different_flags=None):\n flags = different_flags or [RouterFlags.Guard]\n return self.get_random_router(flags)\n\n def get_random_exit_node(self):\n flags = [RouterFlags.Fast, RouterFlags.Running, RouterFlags.Valid, RouterFlags.Exit]\n return self.get_random_router(flags)\n\n def get_random_middle_node(self):\n flags = [RouterFlags.Fast, RouterFlags.Running, RouterFlags.Valid]\n return self.get_random_router(flags)\n\n def get_hsdirs(self):\n flags = [RouterFlags.HSDir]\n return self.get_routers(flags, has_dir_port=True)\n\n @retry(5, BaseException,\n log_func=functools.partial(log_retry, msg='Retry with another router...',\n no_traceback=(FetchDescriptorError, )))\n def get_descriptor(self, fingerprint):\n \"\"\"\n Get router descriptor by its fingerprint through randomly selected router.\n\n :param fingerprint:\n :return:\n \"\"\"\n descriptor_provider = self.get_random_router(has_dir_port=True)\n return descriptor_provider.get_descriptor_for(fingerprint)\n\n def get_responsibles(self, hidden_service):\n \"\"\"\n Get responsible dir for hidden service specified.\n\n :param hidden_service:\n :return:\n \"\"\"\n hsdir_router_list = self.get_hsdirs()\n\n # Search for the 2 sets of 3 hidden service directories.\n for replica in range(2):\n descriptor_id = hidden_service.get_descriptor_id(replica)\n for i, dir in enumerate(hsdir_router_list):\n if dir.fingerprint > descriptor_id:\n for j in range(3):\n idx = (i + 1 + j) % len(hsdir_router_list)\n yield hsdir_router_list[idx]\n break\n" } ]
1
iras/GAs_examples
https://github.com/iras/GAs_examples
75cbd96a808e8792b6b66a097c8c32a9f3227831
d7d4ec562908791b929d45884811ece7c6ef8401
84344f8c61f02982c6625a372104f6bb686c01cc
refs/heads/master
2020-06-05T04:12:28.334556
2019-07-05T08:32:49
2019-07-05T08:32:49
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7375389337539673, "alphanum_fraction": 0.7429906725883484, "avg_line_length": 24.19607925415039, "blob_id": "cd25e345714c8d748e5ac1137b0a5dc41327359d", "content_id": "ed57d196061aa25381f97d36bca061b1723b3aff", "detected_licenses": [ "MIT", "Python-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1284, "license_type": "permissive", "max_line_length": 114, "num_lines": 51, "path": "/README.md", "repo_name": "iras/GAs_examples", "src_encoding": "UTF-8", "text": "# Genetic algorithms examples\n\nFor informal tutoring purposes.\n\n\n### MIT License\n\n\nPython 3 (Anaconda)\n\n### generic GAs guideline.\n\n1. Initialisation.\n Generate population of N items, each with randomly-generated chromosomes.\n\n2. Selection.\n\t- a. Evaluate the fitness of each element of the population.\n\t- b. build a mating pool.\n\n3. Reproduction.\n\t- Repeat N times:\n\t\t- a. pick two parents with probability according to relative fitness.\n\t\t- b. Crossover - create a child by combining the DNA of these two parents.\n\t\t- c. Mutation - mutate the child's chromosomes.\n\t\t- d. Add the new child to the new population.\n\n4. Replacement of the old population with new population and return to Step 2.\n\n5. Elitism. Keep the best solution and keep spawning from it.\n\n\n#### GA Word Search example.\n\n```python main_word_search_example```\n\ntests:\n\n```python tests_word_search_ga.py```\n\n![word_search_ga screenshot](https://github.com/iras/GA_examples/blob/master/images/GA_word_search_screenshot.png)\n\n\n#### GA Symmetric Travelling Salesman Problem example.\n\n```python main_symmetric_travelling_salesman_example.py```\n\ntests:\n\n```python tests_symmetric_travelling_salesman_ga.py```\n\n![word_search_ga screenshot](https://github.com/iras/GA_examples/blob/master/images/symmetric_TSP_example.png)" }, { "alpha_fraction": 0.5852294564247131, "alphanum_fraction": 0.6075973510742188, "avg_line_length": 29.327486038208008, "blob_id": "9bc81469be3a03c05c06fa6f54476ba9b4e5151b", "content_id": "9849a00863170a00590723790d2afd4884c93d44", "detected_licenses": [ "MIT", "Python-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5186, "license_type": "permissive", "max_line_length": 81, "num_lines": 171, "path": "/word_search/word_search_ga.py", "repo_name": "iras/GAs_examples", "src_encoding": "UTF-8", "text": "# Genetic algorithms examples - GA algorithm.\n# MIT License.\n\n\nfrom datetime import datetime\nimport numpy as np\nimport random\nimport time\n\n\nrandom.seed( time.time() )\n\n\ndef get_initial_population( population_size, word_length ):\n\n population = []\n for n in range( population_size ):\n population.append(\n ''.join(\n [ chr( random.randint( 97, 122 ) ) for m in range(word_length) ]\n )\n )\n return population\n\n\ndef get_fitness_score( word, ref ):\n\n assert( len( word ) == len( ref ) )\n\n charwise_comparisons = [ float(word[n]==ref[n]) for n in range(len(word)) ]\n return sum( charwise_comparisons ) / float( len( ref ) )\n\n\ndef crossover( two_fittest_individuals ):\n\n word_1, word_2 = two_fittest_individuals\n assert( len( word_1 ) == len( word_2 ) )\n\n # random-points crossover. This seems to be comparatively the fastest.\n # choose half random cells from word_1 and replace them with word_2's cells.\n number_letter_substitutions = int( len(word_1) / 2.0 )\n random_positions = random.sample( # e.g.: [ 1, 4, 6, 7 ]\n range( len( word_1 ) ), # e.g.: [ 0, 1, 2, 3, 4, 5, 6, 7 ]\n number_letter_substitutions # e.g.: 4\n )\n tuples = zip( word_1, word_2 )\n\n return ''.join(\n [ t[0] if i in random_positions else t[1] for i, t in enumerate(tuples) ]\n )\n\n \"\"\"\n # mixed crossover.\n crossing_mode = random.random()\n if crossing_mode > 0.666:\n\n # single-point crossover.\n half = int( len( word_1 ) / 2.0 )\n return word_1[:half] + word_2[half:]\n\n elif crossing_mode > 0.5:\n # uniform crossover (even numbers).\n return ''.join(\n [ t[0] if i%2 else t[1] for i, t in enumerate(zip(word_1, word_2)) ]\n )\n\n else:\n # uniform crossover (odd numbers).\n return ''.join(\n [ t[1] if i%2 else t[0] for i, t in enumerate(zip(word_1, word_2)) ]\n )\n \"\"\"\n\n\ndef get_mutated_word( word, number_of_mutations ):\n\n non_overlapping_random_places_in_the_word = \\\n random.sample( range(0, len(word)), number_of_mutations )\n\n # inject mutations in those places.\n word_as_list = list( word )\n for n in non_overlapping_random_places_in_the_word:\n word_as_list[n] = chr( random.randint(97, 122) )\n\n return ''.join( word_as_list )\n\n\ndef selection( population, ref ):\n\n # build mating pool with fitness scores as keys.\n mating_pool = {}\n for word in population:\n score = get_fitness_score( word, ref )\n if score not in mating_pool.keys():\n mating_pool[ score ] = []\n mating_pool[ score ].append( word )\n\n return mating_pool\n\n\ndef get_normalised_fitness_score_mating_pool( mating_pool ):\n # normalise mating_pool's fitness score values.\n # i.e. from: fitness-score key. e.g.: [ 0.428571, 0.142857, 1e-05 ]\n # to: normalised fs key. e.g.: [0.749986, 0.249995, 1.75e-05]\n #\n mating_pool_copy = dict( mating_pool ) # copy dict.\n # replace fitness score 0.0 with a very low non-zero value.\n if 0.0 in mating_pool_copy.keys():\n mating_pool_copy[ 0.00001 ] = mating_pool_copy.pop( 0.0 )\n # calculate scaling_factor.\n denominator_of_scaling_factor = 0\n for k in mating_pool_copy.keys():\n denominator_of_scaling_factor += k\n scaling_factor = 1.0 / denominator_of_scaling_factor\n # generate pool with normalised fitness score values.\n nfs_mating_pool = {}\n for k in mating_pool_copy.keys():\n nfs_mating_pool[ scaling_factor * k ] = mating_pool_copy[ k ]\n\n return nfs_mating_pool\n\n\ndef get_two_fittest_individuals( nfs_mating_pool ):\n # get the two fittest individuals.\n # Two individuals were chosen here to maximise genetic diversity although\n # more than 2 individuals could be used.\n #\n two_fittest_individuals = []\n list_associated_to_the_max_key = \\\n nfs_mating_pool.pop( max( nfs_mating_pool.keys() ) )\n if len( list_associated_to_the_max_key ) > 1:\n # get two fittest individuals.\n two_fittest_individuals = random.sample(\n list_associated_to_the_max_key,\n 2\n )\n else:\n # keep the single fittest individual.\n two_fittest_individuals.append(\n ''.join( list_associated_to_the_max_key[ 0 ] )\n )\n # get the second fittest individual.\n list_associated_to_the_new_max_key = \\\n nfs_mating_pool.pop( max( nfs_mating_pool.keys() ) )\n two_fittest_individuals.append(\n ''.join( random.sample( list_associated_to_the_new_max_key, 1 ) )\n )\n\n return two_fittest_individuals\n\n\ndef reproduction( mating_pool, length_new_population ):\n\n two_fittest_individuals = get_two_fittest_individuals(\n get_normalised_fitness_score_mating_pool( mating_pool )\n )\n\n print( two_fittest_individuals )\n\n # mating.\n #\n new_population = []\n for i in range( length_new_population ):\n\n child_word = crossover( two_fittest_individuals )\n child_word = get_mutated_word( child_word, 1 )\n new_population.append( child_word )\n\n print( new_population )\n\n return new_population\n" }, { "alpha_fraction": 0.5739827156066895, "alphanum_fraction": 0.5875462293624878, "avg_line_length": 20.91891860961914, "blob_id": "a9b651c599a8dc4cf46f74b982050794dcbd9a17", "content_id": "84e7ec6b5121040551e1b56f1ccca95297495469", "detected_licenses": [ "MIT", "Python-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1622, "license_type": "permissive", "max_line_length": 79, "num_lines": 74, "path": "/word_search/main_word_search_example.py", "repo_name": "iras/GAs_examples", "src_encoding": "UTF-8", "text": "# Genetic algorithms examples - main.\n# MIT License.\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as anim\nimport word_search_ga as ga\n\n\nREF_WORD = 'supercalifragilisticexpialidocious'\n\n\npopulation = ga.get_initial_population( 10, len( REF_WORD ) )\nmating_pool = ga.selection( population, REF_WORD )\n\n\ndef data_gen( t = 0 ):\n global mating_pool\n while max( mating_pool.keys() ) < 1.0:\n population = ga.reproduction( mating_pool, 10 );\n mating_pool = ga.selection( population, REF_WORD );\n #print max(mating_pool.keys())\n\n t += 1\n yield t, max( mating_pool.keys() )\n\n\ndef init():\n ax.set_ylim( 0, 1.0 )\n ax.set_xlim( 0, 100 )\n del xdata[:]\n del ydata[:]\n line.set_data( xdata, ydata )\n return line,\n\n\ndef run( data ):\n # update the data\n t, y = data\n xdata.append( t )\n ydata.append( y )\n xmin, xmax = ax.get_xlim()\n\n if y == 1.0:\n animation.event_source.stop()\n plt.axvline(x=t, color='red', lw=.5, ls='-.') # visible if blit=False\n \n print(\n \"\\n - search word converged at step %s. \\\n Please close matplotlib's window to end.\" % t\n )\n\n if t >= xmax:\n ax.set_xlim( xmin, 1.5*xmax )\n ax.figure.canvas.draw()\n line.set_data( xdata, ydata )\n\n return line,\n\n\nfig, ax = plt.subplots()\nline, = ax.plot( [], [], lw=.5 )\nax.grid()\nxdata, ydata = [], []\n\nanimation = anim.FuncAnimation(\n fig, run, data_gen,\n blit=True, interval=1, repeat=False, init_func=init\n)\n#plt.tight_layout()\nplt.ylabel(\"max fitness score\")\nplt.xlabel(\"time (steps)\")\nplt.show()\n" }, { "alpha_fraction": 0.6248565912246704, "alphanum_fraction": 0.6386232972145081, "avg_line_length": 33.63576126098633, "blob_id": "3e1be02f8325c3ded7978b65a9ce6a16b194d22c", "content_id": "5e3811b4731bfd0b58bd54490e4c9c9f2b74ab04", "detected_licenses": [ "MIT", "Python-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5230, "license_type": "permissive", "max_line_length": 80, "num_lines": 151, "path": "/symmetric_travelling_salesman/symmetric_travelling_salesman_ga.py", "repo_name": "iras/GAs_examples", "src_encoding": "UTF-8", "text": "# Genetic algorithms examples - GA algorithm.\n# MIT License.\n\n\nfrom datetime import datetime\nimport numpy as np\nimport random\nimport time\nfrom pprint import pprint as pp\n\n\nrandom.seed( time.time() )\n\n\ndef get_initial_population( population_size, city_ids ):\n # get population of possible routes.\n # A route is defined as a list of cities explored in increasing order.\n # NB: City(0) to city(1) to city(2) to... city(n) to city(0).\n population = []\n for n in range( population_size ):\n route = list( city_ids ) # copy list. The copy will be shuffled below.\n np.random.shuffle( route )\n population.append( route )\n return population\n\n\ndef get_fitness_score( route, dist_memo, city_dict ):\n\n # NB: the fitness score here is the length of the path through all cities\n # including the last city and the first city to complete the round trip.\n\n # append the first city to complete the route's round trip.\n route_copy = list( route ) # copy list since it'll be changed.\n route_copy.append( route_copy[0] )\n\n length = 0\n prev_city_id = route_copy[0]\n for city_id in route_copy[1:]:\n index = ( min(prev_city_id, city_id), max(prev_city_id, city_id), )\n # add distance between those two cities if not already memoised.\n if index not in dist_memo:\n dist_memo[ index ] = np.linalg.norm(\n city_dict[ city_id ] - city_dict[ prev_city_id ]\n )\n length += dist_memo[ index ]\n prev_city_id = city_id\n\n return round(length, 6), dist_memo\n\n\ndef crossover( two_fittest_individuals ):\n\n route_1, route_2 = two_fittest_individuals\n route_1 = list( route_1 ) # copy it since the copy might be altered below.\n\n # This TSP breeding step uses the \"ordered crossover\" method explained by\n # Lee Jacobson (2012) in: www.theprojectspot.com/tutorial-post/applying-a\n # -genetic-algorithm-to-the-travelling-salesman-problem/5\n\n len_route_1 = len( route_1 )\n\n ### route_1's gene is a contiguous sublist of route_1.\n route_1_gene_length = int( len_route_1 / 2 )\n route_1_gene_start = np.random.randint( len_route_1 )\n route_1_gene_end = route_1_gene_start + route_1_gene_length\n # double up route_1 to avoid the gene being at the two extremes of the list.\n if route_1_gene_end > len_route_1:\n route_1.extend( route_1 )\n # extract route_1's gene.\n route_1_gene = route_1[ route_1_gene_start : route_1_gene_end ]\n\n ### route_2's gene is a contiguous sublist of route_2.\n route_2_gene = list( route_2 ) # initially set it as a copy of route_2 and\n # then remove cities in route_2_gene that are already in route_1_gene.\n # The deletion of specific ids will preserve the route_2's items order.\n for city_id in route_1_gene:\n del route_2_gene[ route_2_gene.index( city_id ) ]\n\n ### child_route.\n child_route = route_1_gene + route_2_gene\n assert( len( child_route ) == len( route_2 ) )\n\n return np.array( child_route )\n\n\ndef get_mutated_route( route, number_of_mutations ):\n\n for _ in range( number_of_mutations ):\n # swap two random cities in the given route.\n list_id_0, list_id_1 = np.random.choice( range( len(route) ), 2 )\n city_0 = route[ list_id_0 ]\n city_1 = route[ list_id_1 ]\n route[ list_id_0 ] = city_1\n route[ list_id_1 ] = city_0\n return route\n\n\ndef selection( population, dist_memo, city_dict ):\n\n # build mating pool with fitness scores as keys.\n mating_pool = {}\n for route in population:\n length, dist_memo = get_fitness_score( route, dist_memo, city_dict )\n if length not in mating_pool.keys():\n mating_pool[ length ] = []\n mating_pool[ length ].append( route )\n\n return length, dist_memo, mating_pool\n\n\ndef get_two_fittest_individuals( mating_pool ):\n\n # get the two fittest individuals.\n # Two individuals were chosen here to maximise genetic diversity although\n # more than 2 individuals could be used.\n #\n two_fittest_individuals = []\n list_associated_to_the_min_key = \\\n mating_pool.pop( min( mating_pool.keys() ) )\n if len( list_associated_to_the_min_key ) > 1:\n # get the two fittest individuals.\n two_fittest_individuals = random.sample(\n list_associated_to_the_min_key,\n 2\n )\n else:\n # keep the single fittest individual.\n two_fittest_individuals.append( list_associated_to_the_min_key[ 0 ] )\n # and get the second fittest individual.\n list_associated_to_the_second_min_key = \\\n mating_pool.pop( min( mating_pool.keys() ) )\n two_fittest_individuals.append(\n random.sample( list_associated_to_the_second_min_key, 1 )[0]\n )\n return two_fittest_individuals\n\n\ndef reproduction( mating_pool, length_new_population ):\n\n two_fittest_individuals = get_two_fittest_individuals( mating_pool )\n\n # mating.\n #\n new_population = []\n for i in range( length_new_population ):\n\n child_route = crossover( two_fittest_individuals )\n child_route = get_mutated_route( child_route, 1 )\n new_population.append( child_route )\n\n return new_population\n" }, { "alpha_fraction": 0.4852694571018219, "alphanum_fraction": 0.5118562579154968, "avg_line_length": 28.609928131103516, "blob_id": "25846c94c61f8f7fc68f0e4eabd8869f3a8a5838", "content_id": "251fab86a75a56507eb486aa24e5a0dc3bf73579", "detected_licenses": [ "MIT", "Python-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4175, "license_type": "permissive", "max_line_length": 80, "num_lines": 141, "path": "/word_search/tests_word_search_ga.py", "repo_name": "iras/GAs_examples", "src_encoding": "UTF-8", "text": "# Genetic algorithms examples - tests.\n# MIT License.\n\n\nimport unittest\nimport os, sys\nfrom io import StringIO\nfrom word_search_ga import get_fitness_score, crossover, get_mutated_word, \\\n get_normalised_fitness_score_mating_pool, get_two_fittest_individuals\n\n\n\nclass TestWordSearchGA( unittest.TestCase ):\n\n\n def test_get_fitness_score_1( self ):\n self.assertEqual( get_fitness_score( 'qwerty', 'queens'), 1/3.0 )\n\n\n def test_get_fitness_score_2( self ):\n with self.assertRaises( AssertionError ) as ctx:\n get_fitness_score( 'evolution', 'queens')\n # expected error thrown because of different lenghts of the input words.\n\n\n def test_crossover( self ):\n # random-points crossover test.\n # NB: This is just a probabilistic test and would need a better test or\n # a new crossover function.\n # A crossover word will be generated ten thousands times and the\n # test will always need to be True.\n word_1 = 'abcdefgzy'\n word_2 = 'rstuvwxyz'\n number_letter_substitutions = int( len( word_1 ) / 2.0 )\n\n battery_test_list = []\n while len( battery_test_list ) < 10000:\n\n crossover_word = crossover( (word_1, word_2,) )\n\n crossover_word_1_count = sum([\n 1 if crossover_word[i] in word_1 else 0\n for i in range( len( word_1 ) )\n ])\n\n crossover_word_2_count = sum([\n 1 if crossover_word[i] in word_2 else 0\n for i in range( len( word_2 ) )\n ])\n\n battery_test_list.append(\n ( crossover_word_1_count >= number_letter_substitutions ) and \\\n ( crossover_word_2_count >= number_letter_substitutions )\n )\n\n self.assertTrue( all( battery_test_list ) )\n\n\n def test_get_mutated_word( self ):\n # NB: This is just a probabilistic test and would need a better test or\n # a new get_mutated_word function.\n # This will be tested ten thousands times and the outcome will\n # always need to be True.\n word = 'abcdefgzy'\n number_of_mutations = 1\n\n battery_test_list = []\n while len( battery_test_list ) < 10000:\n\n mutated_word = get_mutated_word( word, number_of_mutations )\n\n mutated_word_count = sum([\n 1 if mutated_word[i] in word else 0\n for i in range( len( word ) )\n ])\n\n battery_test_list.append(\n ( mutated_word_count >= number_of_mutations )\n )\n\n self.assertTrue( all( battery_test_list ) )\n\n\n def test_get_normalised_fitness_score_mating_pool( self ):\n mating_pool = {\n 0.0: [\n 'vfwpcyze',\n 'cqehqacd',\n 'ikgqnnlz',\n 'cpfplhcj',\n 'qwzjpbtk',\n 'ivluyiew',\n 'gsnbcici',\n 'mqdkpvgn',\n ],\n 0.125: ['svvdlsof', 'ebjvywaz']\n }\n nfs_mating_pool = {\n 7.999360051195904e-05: [\n 'vfwpcyze',\n 'cqehqacd',\n 'ikgqnnlz',\n 'cpfplhcj',\n 'qwzjpbtk',\n 'ivluyiew',\n 'gsnbcici',\n 'mqdkpvgn',\n ],\n 0.999920006399488: ['svvdlsof', 'ebjvywaz']\n }\n\n self.assertEqual(\n get_normalised_fitness_score_mating_pool( mating_pool ),\n nfs_mating_pool\n )\n\n\n def test_get_two_fittest_individuals( self ):\n nfs_mating_pool = {\n 7.999360051195904e-05: [\n 'vfwpcyze',\n 'cqehqacd',\n 'ikgqnnlz',\n 'cpfplhcj',\n 'qwzjpbtk',\n 'ivluyiew',\n 'gsnbcici',\n 'mqdkpvgn',\n ],\n 0.999920006399488: ['svvdlsof', 'ebjvywaz']\n }\n\n self.assertEqual(\n sorted( get_two_fittest_individuals( nfs_mating_pool ) ),\n sorted( ['svvdlsof', 'ebjvywaz'] )\n )\n\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.5286392569541931, "alphanum_fraction": 0.5582278370857239, "avg_line_length": 26.723684310913086, "blob_id": "c2e5ab3e19d08c547714c7ad89fb12d611fae9cc", "content_id": "219c300523a595f8439d6e44584115a9809d1507", "detected_licenses": [ "MIT", "Python-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6328, "license_type": "permissive", "max_line_length": 80, "num_lines": 228, "path": "/symmetric_travelling_salesman/main_symmetric_travelling_salesman_example.py", "repo_name": "iras/GAs_examples", "src_encoding": "UTF-8", "text": "# Genetic algorithms examples - main.\n# MIT License.\n\nimport os, shutil\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as anim\nimport symmetric_travelling_salesman_ga as ga\n\n\n# Symmetric TSP.\n#\n# \"Given a list of cities and the distances between each pair of cities, what\n# is the shortest possible route that visits each city and returns to the\n# origin city?\".\n\n# NB: This example does not have an exit condition.\n\n\n################################################################################\n\nNUMBER_OF_CITIES = 30\nTWOPI = 2 * np.pi\n\ntest_cities_x_pos = \\\n [10+10*np.cos(i/NUMBER_OF_CITIES*TWOPI) for i in range( NUMBER_OF_CITIES )]\ntest_cities_y_pos = \\\n [10+10*np.sin(i/NUMBER_OF_CITIES*TWOPI) for i in range( NUMBER_OF_CITIES )]\ncities_x_pos = list( 20 * np.random.random( NUMBER_OF_CITIES) )\ncities_y_pos = list( 20 * np.random.random( NUMBER_OF_CITIES) )\n\n\n# init CITY_DICT.\n# e.g.: CITY_DICT = {\n#  0: array([17.22729579, 7.81743567]),\n# 1: array([ 2.18160281, 14.34073598]),\n# 2: array([19.18576723, 3.90946777]),\n# ...\n# }\nCITY_DICT = dict(\n zip(\n list( np.arange( NUMBER_OF_CITIES ) ), # city ids.\n np.array( list( zip( cities_x_pos, cities_y_pos ) ) ) # city positions.\n #np.array( list( zip( test_cities_x_pos, test_cities_y_pos ) ) ) # test\n )\n)\n\ndist_memo = {} # use memoization to avoid square roots' repeats.\n\n# init symmetric TSP GA.\ncurr_shortest_distance = 1000\npopulation = ga.get_initial_population( 10, list(CITY_DICT.keys()) )\nlength, dist_memo, mating_pool = ga.selection(\n population,\n dist_memo,\n CITY_DICT\n)\n\n\n####### init UI ##############################################################\n\n\ndef get_annotation():\n return plt.annotate( '', xy = ( 5, -5 ), color='green' )\n\nxdata, ydata = [], []\nfig, (ax0, ax1) = plt.subplots( 2, figsize=( 6, 15 ) )\nline_0, = ax0.plot( [], [], lw=.5 )\nline_1, = ax1.plot( [], [], lw=.5, color='r')\nline = [ line_0, line_1 ]\n\n# top plot.\nax0.set_ylabel( 'fitness score' )\nax0.set_xlabel( 'time (steps)' )\n#ax0.grid()\n\n# bottom plot.\nax1.set_yticklabels( [] )\nax1.set_xticklabels( [] )\nax1.xaxis.set_ticks_position( 'none' )\nax1.yaxis.set_ticks_position( 'none' )\nannotation = get_annotation()\n\n# add images folder.\nPATH = os.path.expanduser( '~/Desktop/TSP_screenshots' )\nif os.path.exists( PATH ):\n shutil.rmtree( PATH )\nos.makedirs( PATH )\n\n\n################################################################################\n\n\ndef init():\n global annotation\n global background\n # init top plot.\n ax0.set_ylim( 0, 500 )\n ax0.set_xlim( 0, 100 )\n del xdata[:]\n del ydata[:]\n line[0].set_data( xdata, ydata )\n # init bottom plot.\n ax1.clear()\n ax1.set_ylim( -10, 30 )\n ax1.set_xlim( -10, 30 )\n # add annotation and capture blank background.\n annotation = get_annotation()\n background = ax1.figure.canvas.copy_from_bbox( ax1.bbox )\n return line\n\n\ndef data_gen( t = 0 ):\n global mating_pool\n global population\n global curr_shortest_distance\n global dist_memo\n\n while True:\n\n # save fittest items. \n fittest_items_key = min( mating_pool.keys() )\n fittest_items_copy = list( mating_pool[ fittest_items_key ] )\n\n ### GAs step.\n population = ga.reproduction( mating_pool, 10 );\n length, dist_memo, mating_pool = ga.selection(\n population,\n dist_memo,\n CITY_DICT\n )\n\n ### GA Elitarism step.\n if fittest_items_key not in mating_pool:\n mating_pool[ fittest_items_key ] = []\n mating_pool[ fittest_items_key ].extend( fittest_items_copy )\n\n # update curr_shortest_distance.\n if length < curr_shortest_distance:\n print( '••• %s' % length )\n curr_shortest_distance = length\n t += 1\n\n # generate data for the bottom graph.\n min_dist_path_id = min( mating_pool.keys() )\n min_dist_path = list( mating_pool[ min_dist_path_id ][0] )\n min_dist_path.append( min_dist_path[0] ) # close the path.\n xpairs = []\n ypairs = []\n for i in range( len( min_dist_path ) - 1 ):\n x0, y0 = CITY_DICT[ min_dist_path[ i ] ]\n x1, y1 = CITY_DICT[ min_dist_path[ i + 1 ] ]\n xpairs.append( [ x0, x1 ] )\n ypairs.append( [ y0, y1 ] )\n # add last one connected with the first one.\n x0, y0 = CITY_DICT[ min_dist_path[ len( min_dist_path ) - 1 ] ]\n x1, y1 = CITY_DICT[ min_dist_path[ 0 ] ]\n xpairs.append( [ x0, x1 ] )\n ypairs.append( [ y0, y1 ] )\n # plot speed optimisation.\n xlist = []\n ylist = []\n for xends, yends in zip( xpairs, ypairs ):\n xlist.extend( xends )\n xlist.append( None )\n ylist.extend( yends )\n ylist.append( None )\n\n yield t, length, [xlist, ylist]\n\n\ndef run( data ):\n global fig\n global annotation\n global curr_shortest_distance\n t, y, list_lines = data\n\n # update data top plot.\n xdata.append( t )\n ydata.append( y )\n xmin, xmax = ax0.get_xlim()\n\n # extend horizontal axis.\n if t >= xmax:\n ax0.set_xlim( xmin, 2 * xmax )\n\n # remove old ax1's lines and add new lines.\n try:\n ax1.lines.remove(ax1.lines[0])\n except:\n pass\n line[0].set_data( xdata, ydata )\n\n # update bottom plot - use blitter to make it fast.\n ax1.figure.canvas.restore_region( background )\n ax1.set_ylim( -10, 30 )\n ax1.set_xlim( -10, 30 )\n pict, = ax1.plot(\n list_lines[0],\n list_lines[1],\n 'b-',\n linewidth = .5,\n color = 'olive',\n marker = 'o',\n markersize = 3\n )\n ax1.draw_artist( pict )\n annotation.set_text( y )\n ax1.figure.canvas.blit( ax1.bbox )\n\n # add red dot on the minimum length and save picture to disk.\n if y == curr_shortest_distance:\n ax0.plot( t, y, 'ro', markersize=1 )\n fig.savefig(\n os.path.expanduser( '%s/%s.png' % ( PATH, y ) ),\n dpi=150\n )\n\n return line\n\n\nanimation = anim.FuncAnimation(\n fig, run, data_gen,\n blit=True, interval=0, repeat=False, init_func=init\n)\n\n#plt.tight_layout()\nplt.show()" } ]
6
jacboi/hostSetup
https://github.com/jacboi/hostSetup
5b11cbf2574e171e3f1ca7855d696a5d99a8af9f
ce391411ebefab1e48fca1e850c4a8ed061111d4
b1d2bd3b3e13dea05bff9c0fc46dad3823632c8b
refs/heads/master
2020-12-12T00:21:43.068734
2020-03-15T19:52:07
2020-03-15T19:52:07
233,994,076
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.5199506282806396, "alphanum_fraction": 0.5248869061470032, "avg_line_length": 24.589473724365234, "blob_id": "f51482545898bed11ac2e3afb206f272ef8c4258", "content_id": "3aee36b030d17607c24b4f1e80ba673889e9b68e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2431, "license_type": "no_license", "max_line_length": 67, "num_lines": 95, "path": "/src/host_setup/process.py", "repo_name": "jacboi/hostSetup", "src_encoding": "UTF-8", "text": "from host_setup.video_dir import VideoDir\nfrom host_setup.decorators import state_manager, logger\nimport subprocess\nimport os\nfrom typing import Dict\n\n\nclass Process:\n def __init__(self, path: str, api: object):\n self.video = VideoDir(path)\n self.api = api\n self.run_process()\n\n @property\n def status(self):\n \"\"\"get the status of a given entry\n \"\"\"\n return self.api.get_task_status(self.video.name)\n\n def run_process(self):\n self.actions[self.status](self.video, self.api)\n\n @property\n def actions(self):\n return {\n -1: self.video_busy,\n 0: self.create_entry,\n 1: self.convert_media,\n 2: self.rclone,\n 3: self.delete,\n }\n\n @staticmethod\n def video_busy(video, api):\n # TODO place a timeout here\n return None\n\n @staticmethod\n @state_manager\n @logger\n def create_entry(video, api):\n \"\"\"if there is no video in sqlite\"\"\"\n if video.valid_video:\n api.create_new_task(video.name, video.r_path)\n return True\n\n @staticmethod\n @state_manager\n @logger\n def convert_media(video, api):\n # TODO Try to run fmpgg at several settings to convert data\n for vid in video.video_files:\n old_file = os.path.join(video.path, vid)\n new_file = os.path.join(video.path, video.name)\n Process._convert_vid_ffmpeg(old_file, new_file)\n return True\n\n @staticmethod\n @logger\n def _convert_vid_ffmpeg(old_vid, new_vid):\n return subprocess.call(\n [\n \"ffmpeg\",\n f\"-i {old_vid}\",\n \"-c:v\",\n \"libx264\",\n \"-crf 19\",\n \"-hide_banner\",\n \"-loglevel panic\",\n \"-preset fast\",\n new_vid,\n ]\n )\n\n @staticmethod\n @state_manager\n @logger\n def rclone(video, api):\n # move this to async\n print(\"starting as sync to s3\")\n subprocess.call(\n [\n os.environ[\"RCLONE\"],\n \"move\",\n \"--include mp4,srt\",\n \"--delete-empty-src-dirs\" \"FILES wasab:wasab\",\n ]\n )\n\n @staticmethod\n @state_manager\n @logger\n def delete(video, api):\n print(\"starting a deletion of the file\")\n os.remove(video.path)\n" }, { "alpha_fraction": 0.6484283804893494, "alphanum_fraction": 0.6495925784111023, "avg_line_length": 22.88888931274414, "blob_id": "cb9df3dc74aee31190ebee9e62abd984f18d9763", "content_id": "faf8b6411558c0337db414fcd98a9822257b8185", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 859, "license_type": "no_license", "max_line_length": 65, "num_lines": 36, "path": "/tests/unit/test_state_manager.py", "repo_name": "jacboi/hostSetup", "src_encoding": "UTF-8", "text": "import os\nfrom host_setup.datab import DataB\nfrom host_setup.process import state_manager, logger\nfrom host_setup.video_dir import VideoDir\nimport pytest\n\n\ndef test_state_manager(test_data_dir):\n path = os.path.join(test_data_dir, \"downloads/movie2\")\n db_path = os.path.join(test_data_dir, \"output/decorators.db\")\n db = DataB(db_path)\n db.create_new_table()\n db.create_new_task(\"hello\", \"sss\")\n\n @state_manager\n def dumb_def(video, api):\n print(\"hello\")\n print()\n\n j = VideoDir(path)\n dumb_def(j, db)\n\n \ndef test_logging(test_data_dir):\n @logger\n def dumb_def(hello):\n print(hello)\n print()\n\n dumb_def(\"sdfsdf\")\n\ndef test_delete_db(test_data_dir):\n path = os.path.join(test_data_dir, \"output/decorators.db\")\n db = DataB(path)\n db.delete_database()\n assert not os.path.exists(path)" }, { "alpha_fraction": 0.6134831309318542, "alphanum_fraction": 0.6134831309318542, "avg_line_length": 25.235294342041016, "blob_id": "d4ea1e9daeb30eeab8bf347de64bbbab62bd31ce", "content_id": "bc03a668c8b1b3f5d15e03701b9280730fa950ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 445, "license_type": "no_license", "max_line_length": 45, "num_lines": 17, "path": "/tests/unit/test_env.py", "repo_name": "jacboi/hostSetup", "src_encoding": "UTF-8", "text": "import os\nfrom host_setup.env import Env\n\ndef test_env_auto(test_data_dir):\n os.chdir(test_data_dir)\n auto = Env()\n assert os.getenv(\"TEST\") == \"./TEST\"\n\ndef test_env_file(test_data_dir):\n env = os.path.join(test_data_dir, \".env\")\n env_file = Env(env=env)\n assert os.getenv(\"TEST\") == \"./TEST\"\n\ndef test_env_param():\n params = {\"HELLO\":\"./hello\"}\n env_param = Env(params=params)\n assert os.getenv(\"HELLO\") == \"./hello\"" }, { "alpha_fraction": 0.7043269276618958, "alphanum_fraction": 0.7043269276618958, "avg_line_length": 26.733333587646484, "blob_id": "65255af5788b023fbb4bb961ee34ee1e04db3305", "content_id": "c0005415a64142e8e8a044f3cc8b0ad0a1d56e93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 416, "license_type": "no_license", "max_line_length": 68, "num_lines": 15, "path": "/tests/functional/test_sdf.py", "repo_name": "jacboi/hostSetup", "src_encoding": "UTF-8", "text": "import os\nfrom host_setup.scan_dir import ScanDir\nfrom host_setup.datab import DataB\nfrom host_setup.env import Env\nimport pytest\n\ndef test_find_downloads(test_data_dir):\n path = os.path.join(test_data_dir, \"downloads/\")\n db_path = os.path.join(test_data_dir, \"output/functional_db.db\")\n\n #create a new table\n Env()\n print(os.environ[\"PLEXDB\"])\n scan = ScanDir(path)\n scan.api.delete_database()\n" }, { "alpha_fraction": 0.571319580078125, "alphanum_fraction": 0.5743706822395325, "avg_line_length": 27.5, "blob_id": "a0de6a6e59c5fe61614eba8bb06e5e97ca356043", "content_id": "7f124c121f902caba8b8162a112f792cf9e37264", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1311, "license_type": "no_license", "max_line_length": 85, "num_lines": 46, "path": "/src/host_setup/decorators.py", "repo_name": "jacboi/hostSetup", "src_encoding": "UTF-8", "text": "import time\nimport logging\nimport time\n\nfrom functools import wraps\n\n\n# logging.basicConfig(level=logging.INFO, file='sample.log')\nlogging.basicConfig(level=logging.INFO)\n\n\ndef state_manager(f):\n @wraps(f)\n def action_f(video, api):\n # get the current status of the task at hand\n status = api.get_task_param(\"status\", video.name)\n # set the current task to busy\n proc_state = api.get_task_param(\"processing\", video.name)\n\n try:\n api.update_task_by_name(\"processing\", 1, video.name)\n f(video, api)\n api.update_task_by_name(\"processing\", 0, video.name)\n api.update_task_by_name(\"status\", status + 1, video.name)\n except:\n print(\"somethings wrong\")\n api.update_task_by_name(\"processing\", proc_state-1, video.name)\n print(proc_state)\n\n return action_f\n\n\ndef logger(f):\n @wraps(f)\n def wrap(*args):\n try:\n start_time = time.time()\n logging.info(f\"RUNNING : {f.__name__} - args : {args}\")\n outcome = f(*args)\n logging.info(f\"COMPLETED : {f.__name__} in : {time.time() - start_time}\")\n return outcome\n except:\n logging.error(f\"FAILED {f.__name__} has failed : {args}\")\n raise\n\n return wrap\n" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.625, "avg_line_length": 22.68000030517578, "blob_id": "75a8a338f2e7b6ac4e888decd30668a773c3d146", "content_id": "0fbaea75f13a922d77d76b6fefff6bbccf5851e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 592, "license_type": "no_license", "max_line_length": 56, "num_lines": 25, "path": "/src/host_setup/scan_dir.py", "repo_name": "jacboi/hostSetup", "src_encoding": "UTF-8", "text": "import os\nfrom pathlib import Path\nfrom host_setup.datab import DataB\nfrom host_setup.decorators import logger\nfrom host_setup.process import Process\n\n\nclass ScanDir:\n def __init__(\n self, video_dir: str,\n ):\n self.video_dir = video_dir\n self.api = DataB()\n self.scan_dir()\n\n # @logger\n def scan_dir(self):\n # perform these in a lazy or non-blocking manner\n for dir in os.scandir(self.video_dir):\n self.gen_process(dir, self.api)\n\n @staticmethod\n # @logger\n def gen_process(dir, api):\n return Process(dir, api)\n" }, { "alpha_fraction": 0.6534653306007385, "alphanum_fraction": 0.6600660085678101, "avg_line_length": 26.545454025268555, "blob_id": "6dfc5f20c340ea769fa649864d32ad3e8c0cd877", "content_id": "ddfcf2372708ed96c4fcdb0d677559d2472e633e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 606, "license_type": "no_license", "max_line_length": 71, "num_lines": 22, "path": "/setup.py", "repo_name": "jacboi/hostSetup", "src_encoding": "UTF-8", "text": "import io\nimport re\nfrom setuptools import setup, find_packages\n\n# Read in requirements.txt\nwith open(\"requirements.txt\", \"r\") as f_requirements:\n requirements = f_requirements.readlines()\nrequirements = [r.strip() for r in requirements]\n\nwith io.open(\"src/host_setup/__init__.py\", \"rt\", encoding=\"utf8\") as f:\n version = re.search(r\"__version__ = \\\"(.*?)\\\"\", f.read()).group(1)\n print(version)\n\nsetup(\n name=\"host_setup\",\n version=version,\n author=\"shaddy52\",\n packages=find_packages(where=\"src\"),\n package_dir={\"\": \"src\"},\n install_requires=requirements,\n zip_safe=False,\n)\n" }, { "alpha_fraction": 0.30434781312942505, "alphanum_fraction": 0.47826087474823, "avg_line_length": 22, "blob_id": "50cfec36941455131a17ab1e427cdd9d972c196a", "content_id": "c4db9a292cd07df60dc423ac50bcde5cd3b18784", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23, "license_type": "no_license", "max_line_length": 22, "num_lines": 1, "path": "/src/host_setup/__init__.py", "repo_name": "jacboi/hostSetup", "src_encoding": "UTF-8", "text": "__version__ = \"0.0.02\"\n" }, { "alpha_fraction": 0.621502697467804, "alphanum_fraction": 0.6337629556655884, "avg_line_length": 29.00943374633789, "blob_id": "5608fc86abf1e49dc0985771b258babd44c3ea08", "content_id": "585fe9e5b71d5d2089129838985680f5503cea57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3181, "license_type": "no_license", "max_line_length": 70, "num_lines": 106, "path": "/tests/unit/test_unit_db.py", "repo_name": "jacboi/hostSetup", "src_encoding": "UTF-8", "text": "import os\nfrom host_setup.datab import DataB\nimport pytest\n\n\ndef test_create_connection(test_data_dir):\n path = os.path.join(test_data_dir, \"output/db.db\")\n db = DataB(db_path=path)\n assert os.path.exists(path)\n\n\ndef test_create_new_table(test_data_dir):\n path = os.path.join(test_data_dir, \"output/db.db\")\n db = DataB(db_path=path)\n db.create_new_table()\n\ndef test_create_new_task(test_data_dir):\n path = os.path.join(test_data_dir, \"output/db.db\")\n db = DataB(db_path=path)\n db.create_new_task(\"test\" , \"./sdg\")\n db.create_new_task(\"test2\", \"./sdg\")\n db.create_new_task(\"test3\", \"./sdg\")\n db.create_new_task(\"test4\", \"./sdg\")\n\n tasks = db.select_all_tasks()\n print(len(tasks))\n assert len(tasks) == 4\n\n\ndef test_select_all_tasks(test_data_dir):\n path = os.path.join(test_data_dir, \"output/db.db\")\n db = DataB(db_path=path)\n tasks = db.select_all_tasks()\n assert len(tasks) == 4\n\n\ndef test_select_task_by_param(test_data_dir):\n path = os.path.join(test_data_dir, \"output/db.db\")\n db = DataB(db_path=path)\n tasks = db.select_task_by_param(\"priority\", 0)\n assert len(tasks) == 4\n\n\ndef test_select_task_by_name(test_data_dir):\n path = os.path.join(test_data_dir, \"output/db.db\")\n db = DataB(db_path=path)\n tasks = db.select_task_by_param(\"priority\", 0)\n assert len(tasks) == 4\n\n\ndef test_update_task(test_data_dir):\n path = os.path.join(test_data_dir, \"output/db.db\")\n db = DataB(db_path=path)\n task_data = (\"bbb\", \"sdf\", 0, 2, 0, \"2015-01-01\", \"2015-01-02\", 0)\n db.update_task(task_data)\n\n\ndef test_update_param(test_data_dir):\n path = os.path.join(test_data_dir, \"output/db.db\")\n db = DataB(db_path=path)\n db.update_task_param(\"status\", 2, 0)\n\n\ndef test_update_task_by_name(test_data_dir):\n\n path = os.path.join(test_data_dir, \"output/db.db\")\n db = DataB(db_path=path)\n db.update_task_by_name(\"status\", 2, \"test\")\n\n# def test_get_task_status(test_data_dir):\n# path = os.path.join(test_data_dir, \"output/db.db\")\n# db = DataB(db_path=path)\n# db.create_new_task(\"status test\", \"sdff\")\n# db.update_task_by_name(\"status\", 2, \"status test\")\n# status = db.get_task_status(\"status test\")\n# assert status == 2\n\ndef test_get_task_param(test_data_dir):\n path = os.path.join(test_data_dir, \"output/db.db\")\n db = DataB(db_path=path)\n db.create_new_task(\"status test\", \"sdff\")\n db.update_task_by_name(\"status\", 2, \"status test\")\n status = db.get_task_param(\"status\", \"status test\")\n assert status == 2\n\ndef test_delete_task(test_data_dir):\n path = os.path.join(test_data_dir, \"output/db.db\")\n db = DataB(db_path=path)\n cur_len = len(db.select_all_tasks())\n db.delete_task(1)\n new_len = len(db.select_all_tasks())\n assert (cur_len - new_len) == 1\n\n\ndef test_delete_all_task(test_data_dir):\n path = os.path.join(test_data_dir, \"output/db.db\")\n db = DataB(db_path=path)\n db.delete_all_tasks()\n assert len(db.select_all_tasks()) == 0\n\n\ndef test_delete_db(test_data_dir):\n path = os.path.join(test_data_dir, \"output/db.db\")\n db = DataB(db_path=path)\n db.delete_database()\n assert not os.path.exists(path)\n" }, { "alpha_fraction": 0.5898922681808472, "alphanum_fraction": 0.591549277305603, "avg_line_length": 24.680850982666016, "blob_id": "b7bf51e29763d006447ac36736d23623190ee272", "content_id": "c42a786a51146e31a431a32d21a56ebe6de6094d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1207, "license_type": "no_license", "max_line_length": 87, "num_lines": 47, "path": "/src/host_setup/video_dir.py", "repo_name": "jacboi/hostSetup", "src_encoding": "UTF-8", "text": "from pathlib import Path\nfrom glob import glob\nfrom typing import List\nimport os\n\nEXCLUDE = [\"vpn\"]\nVALID_VIDEO = [\".mp4\", \".avi\"]\nVALID_OTHER = [\".srt\"]\n\n\nclass VideoDir:\n def __init__(self, path: str):\n self.path = path\n self.name = os.path.basename(path)\n\n def __repr__(self):\n return f\"\\n{self.__class__.__name__} \\n path: {self.path} \\n name: {self.name}\"\n\n @staticmethod\n def _get_files(path: str, file_types: List[str]) -> List[str]:\n return [p for p in Path(path).rglob(\"*\") if p.suffix in file_types]\n\n @property\n def r_path(self):\n return str(self.path)\n\n @property\n def valid_video(self):\n \"\"\"checks for a valid video file in a given directory\n Returns:\n valid -- a true or false representing if a video file is present\n \"\"\"\n potentials = self.video_files\n print(potentials)\n\n if len(potentials) > 0:\n return True\n else:\n return False # build helpers into class\n\n @property\n def video_files(self):\n return self._get_files(self.path, VALID_VIDEO)\n\n @property\n def subtitles(self):\n return self._get_files(self.path, VALID_OTHER)\n" }, { "alpha_fraction": 0.5544244050979614, "alphanum_fraction": 0.5544244050979614, "avg_line_length": 26.7608699798584, "blob_id": "d746fe18bc2419cd088134d32e1da23ef69e9296", "content_id": "098692bad92b931f0d5ee0d1d3b0f337d604182b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1277, "license_type": "no_license", "max_line_length": 81, "num_lines": 46, "path": "/src/host_setup/env.py", "repo_name": "jacboi/hostSetup", "src_encoding": "UTF-8", "text": "import os\nfrom typing import Dict, Optional\nfrom dotenv import load_dotenv, find_dotenv\n\n\nclass Env:\n def __init__(self, env: Optional[str] = None, params: Optional[Dict] = None):\n # build in overrides for testing\n self.env = env\n self.params = params\n self.load_global_env()\n\n def load_global_env(self):\n switcher = {\n (True, True): self.auto_load,\n (True, False): self.load_env_file,\n (False, True): self.load_params,\n (False, False): self.load_params,\n }\n\n f = switcher.get(self.check_vals)\n try:\n f()\n except:\n raise ValueError(\"the env couldn't be set\")\n\n @property\n def check_vals(self):\n return self.params is None, self.env is None\n\n def auto_load(self):\n print(\"auto loading -------\")\n load_dotenv(find_dotenv(raise_error_if_not_found=True, usecwd=True))\n\n def load_env_file(self):\n\n if os.path.isfile(self.env):\n load_dotenv(self.env)\n else:\n raise ValueError(\n f\"couldn't load the file, maybe it's here: {find_dotenv()}\"\n )\n\n def load_params(self):\n for key, val in self.params.items():\n os.environ[key] = str(val)\n" }, { "alpha_fraction": 0.6882129311561584, "alphanum_fraction": 0.6920152306556702, "avg_line_length": 20.91666603088379, "blob_id": "9121f32241209a80c7f68e4304c69505d6178e80", "content_id": "b34c41c9c0509cea9dcbefcf20b204df4037f697", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 263, "license_type": "no_license", "max_line_length": 74, "num_lines": 12, "path": "/src/host_setup/main.py", "repo_name": "jacboi/hostSetup", "src_encoding": "UTF-8", "text": "# look for dirs\n# if one found - add the file to sqlite\n# look at the contents and if the file is not an mp4 attempt to convert it\n# move the file with rclone\n\n\nimport os\n\n\ndef find_downloads(path):\n for root, dirs, files in os.walk(path):\n print(dirs)\n" }, { "alpha_fraction": 0.6522842645645142, "alphanum_fraction": 0.6548223495483398, "avg_line_length": 28.185184478759766, "blob_id": "0940eef761d9514e5d867ce38e4cc0a2df0cce08", "content_id": "32a540a7891c83640aaccccee97f84fe4914ff36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 788, "license_type": "no_license", "max_line_length": 60, "num_lines": 27, "path": "/tests/unit/test_init_file.py", "repo_name": "jacboi/hostSetup", "src_encoding": "UTF-8", "text": "import os\nfrom host_setup.actions import find_downloads, AttemptInsert\nimport pytest\nfrom host_setup.datab import DataB\n\n\n# def test_find_downloads(test_data_dir):\n# path = os.path.join(test_data_dir, \"downloads/\")\n# db_path = os.path.join(test_data_dir, \"test.db\")\n# db = DataB(db_path)\n# db.create_new_table()\n# find_downloads(path, db)\n# # assert tables.valid is True\n# # db.commit()\n# db.delete_database()\n\n\ndef test_attempt_insert(test_data_dir):\n path = os.path.join(test_data_dir, \"downloads/movie2\")\n db_path = os.path.join(test_data_dir, \"test.db\")\n db = DataB(db_path)\n db.create_new_table()\n ai = AttemptInsert(path, db)\n assert ai.video.valid_video is True\n assert ai.status == 0\n db.commit()\n # db.delete_database()\n" }, { "alpha_fraction": 0.8529411554336548, "alphanum_fraction": 0.8529411554336548, "avg_line_length": 7.75, "blob_id": "2c575343915e084749cfae38b7fd3575c8606395", "content_id": "e6ca0258cca47d0300a90290631dbf18283e9010", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 34, "license_type": "no_license", "max_line_length": 10, "num_lines": 4, "path": "/requirements-dev.txt", "repo_name": "jacboi/hostSetup", "src_encoding": "UTF-8", "text": "pre-commit\npytest\npytest-cov\nblack" }, { "alpha_fraction": 0.48148149251937866, "alphanum_fraction": 0.48417219519615173, "avg_line_length": 27.331838607788086, "blob_id": "740c24fe31801903d529a4f3afafecd6d3508dcc", "content_id": "7a98367dc2f698e7ca4f98bb21c94899b728e0e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6318, "license_type": "no_license", "max_line_length": 123, "num_lines": 223, "path": "/src/host_setup/datab.py", "repo_name": "jacboi/hostSetup", "src_encoding": "UTF-8", "text": "import sqlite3\nfrom sqlite3 import Error\nimport os\nfrom datetime import datetime\nfrom host_setup.env import Env\n\nDATAB_DEF = \"\"\"CREATE TABLE IF NOT EXISTS tasks (\n id integer PRIMARY KEY,\n name text NOT NULL,\n path text NOT NULL,\n priority integer,\n status integer NOT NULL,\n processing int NOT NULL,\n begin_date text NOT NULL,\n end_date text NOT NULL\n );\"\"\"\n\n\ndef check_db(var):\n if var is not None:\n return var\n else:\n try:\n return os.environ[\"PLEXDB\"]\n except:\n raise EnvironmentError(\"the db var isn't set\")\n\n\nclass DataB:\n def __init__(self, db_path=None):\n self.path = check_db(db_path)\n self.conn = self.create_connection(self.path)\n self.create_new_table()\n\n def __repr__(self):\n return f\"\\n{self.__class__.__name__} \\n path: {self.path} \\n conn: {self.conn} \\n tasks: {self.select_all_tasks()}\"\n\n def __str__(self):\n return f\"path: {self.path} \\n conn: {self.conn} \\n tasks: {self.select_all_tasks()}\"\n\n @staticmethod\n def create_connection(db_file):\n \"\"\" create a database connection to the SQLite database\n specified by the db_file\n :param db_file: database file\n :return: Connection object or None\n \"\"\"\n conn = None\n try:\n conn = sqlite3.connect(db_file)\n except Error as e:\n print(e)\n\n return conn\n\n @property\n def get_start_time(self):\n # datetime object containing current date and time\n return datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")\n\n @property\n def cur(self):\n return self.conn.cursor()\n\n def close(self):\n self.conn.close()\n\n def commit(self):\n self.conn.commit()\n\n def create_new_table(self):\n \"\"\" create a table from the create_table_sql statement\n :return:\n \"\"\"\n try:\n self.cur.execute(DATAB_DEF)\n except Error as e:\n print(e)\n\n def create_new_task(self, name, path, priority=0, status=0, processing=0):\n \"\"\"\n Create a new task for tracking. this is a helper around _create_task\n :param name : str\n :param priority : int\n :param status : int\n :return: id : int\n \"\"\"\n task = (name, path, priority, status, processing, self.get_start_time, \"-\")\n self.create_task(task)\n\n def create_task(self, task):\n \"\"\"\n Create a new task\n :param task:\n :return:\n \"\"\"\n\n sql = \"\"\" INSERT INTO tasks(name,path,priority,status,processing,begin_date,end_date)\n VALUES(?,?,?,?,?,?,?) \"\"\"\n self.cur.execute(sql, task)\n self.commit()\n return self.cur.lastrowid\n\n def update_task(self, task):\n \"\"\"\n update priority, begin_date, and end date of a task\n :param task:\n \"\"\"\n sql = \"\"\" UPDATE tasks\n SET name = ? ,\n path = ? ,\n priority = ? ,\n status = ? ,\n processing = ? ,\n begin_date = ? ,\n end_date = ?\n WHERE id = ?\"\"\"\n self.cur.execute(sql, task)\n self.conn.commit()\n\n def update_task_by_name(self, param, val, name):\n \"\"\"\n update priority, begin_date, and end date of a task\n :param task:\n \"\"\"\n sql = f\"\"\" UPDATE tasks\n SET {param} = ?\n WHERE name = ?\"\"\"\n self.cur.execute(sql, (val, name))\n self.conn.commit()\n\n def update_task_param(self, param, val, task_id):\n \"\"\"\n update priority, begin_date, and end date of a task\n :param task:\n \"\"\"\n sql = f\"\"\" UPDATE tasks\n SET {param} = ?\n WHERE id = ?\"\"\"\n self.cur.execute(sql, (val, task_id))\n self.conn.commit()\n\n def select_all_tasks(self):\n \"\"\"\n Query all rows in the tasks table\n :return:\n \"\"\"\n\n return self.cur.execute(\"SELECT * FROM tasks\").fetchall()\n\n def select_task_by_param(self, param, term):\n \"\"\"\n Query tasks by priority\n :param priority:\n :return:\n \"\"\"\n return self.cur.execute(\n f\"SELECT * FROM tasks WHERE {param}=?\", (term,)\n ).fetchall()\n\n def get_task_param(self, param, name):\n try:\n result = self.cur.execute(\n f\"SELECT {param} FROM tasks WHERE name=?\", (name,)\n ).fetchall()\n if len(result) == 0:\n if param == \"status\" or param == \"processing\":\n return 0\n else:\n return None\n else:\n return result[0][0]\n except:\n return None\n\n def get_task_status(self, name):\n task = self.select_task_by_param(\"name\", name)\n if len(task) == 0:\n return 0\n elif len(task) == 1:\n return task[0][4]\n else:\n # TODO find something smart to do\n print(task)\n print(\"there's a problem we should kill one\")\n return task[0][4]\n\n def select_task_status(self, param, term):\n \"\"\"\n Query tasks \n :param priority:\n :return:\n \"\"\"\n return self.cur.execute(\n f\"SELECT * FROM tasks WHERE {param}=?\", (term,)\n ).fetchall()\n\n def delete_task(self, id):\n \"\"\"\n Delete a task by task id\n :param id: id of the task\n :return:\n \"\"\"\n sql = \"DELETE FROM tasks WHERE id=?\"\n self.cur.execute(sql, (id,))\n self.conn.commit()\n\n def delete_all_tasks(self):\n \"\"\"\n Delete all rows in the tasks table\n :return:\n \"\"\"\n sql = \"DELETE FROM tasks\"\n self.cur.execute(sql)\n self.conn.commit()\n\n def delete_database(self):\n \"\"\"\n Delete the base .db file\n :return:\n \"\"\"\n self.close()\n os.remove(self.path)\n" } ]
15
fm1ck3y/DevOpsProject
https://github.com/fm1ck3y/DevOpsProject
ce0483b650a99644a7ccb3ea75eba05b2ecc70b8
f2c8e26e0dcb875ebf6b98c894ec9ddf7857c9ca
ce02973890e87c742d620dd1563522b2a10f8e32
refs/heads/master
2023-06-18T17:12:47.460888
2021-07-18T17:46:18
2021-07-18T17:46:18
375,085,993
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5066505670547485, "alphanum_fraction": 0.5513905882835388, "avg_line_length": 15.215685844421387, "blob_id": "96dd1c8712d6c269157235c4e3d4ada320871904", "content_id": "79a22a1c73970bc320b03903733f058cc3451b65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "YAML", "length_bytes": 827, "license_type": "no_license", "max_line_length": 47, "num_lines": 51, "path": "/ApiWithNginx/docker-compose.yml", "repo_name": "fm1ck3y/DevOpsProject", "src_encoding": "UTF-8", "text": "version: '3'\n\nservices:\n api_with_json:\n restart: always\n build: ./api_with_json\n ports:\n - \"5002:5000\"\n env_file:\n - db.env\n environment:\n - POSTGRES_HOST=db\n\n api_without_json:\n restart: always\n build: ./api_without_json\n ports:\n - \"5001:5000\"\n env_file:\n - db.env\n environment:\n - POSTGRES_HOST=db\n\n statistics:\n restart: always\n build: ./statistics\n ports:\n - \"5003:5000\"\n env_file:\n - db.env\n environment:\n - POSTGRES_HOST=db\n\n nginx:\n restart: always\n build: ./nginx\n ports:\n - \"80:80\"\n - \"443:443\"\n volumes:\n - ./nginx/conf.d:/etc/nginx/conf.d/\n\n db:\n image: postgres:13-alpine\n volumes:\n - postgres_data:/var/lib/postgresql/data/\n env_file:\n - db.env\n\nvolumes:\n postgres_data:\n" }, { "alpha_fraction": 0.5883244872093201, "alphanum_fraction": 0.5996967554092407, "avg_line_length": 30.404762268066406, "blob_id": "0010be6f31fe906b8fc913f0446d4b31834f6e9a", "content_id": "d3154b1470991dea3f6a42468e4b473a77504fab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1319, "license_type": "no_license", "max_line_length": 129, "num_lines": 42, "path": "/ApiWithNginx/api_without_json/app/views.py", "repo_name": "fm1ck3y/DevOpsProject", "src_encoding": "UTF-8", "text": "from flask import jsonify, request\nfrom app import app\nimport app.database as database\nfrom functools import wraps\nimport json\n\ndef logging_request(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n response_args = {\n 'ip': request.remote_addr,\n 'args': dict((key, request.args.get(key)) for key in request.args)\n }\n app.logger.info(response_args)\n return f(*args, **kwargs)\n\n return wrapper\n\n@app.errorhandler(404)\ndef not_found(error=None):\n return jsonify({\n 'code': 0,\n 'response': 'Not Found'\n })\n\n\n@app.route('/api/v1.0/add_user', methods=['GET'])\n@logging_request\ndef add_user():\n user = json.loads(request.args.get('user'))\n app.logger.info(user)\n if 'email' not in user or \\\n 'username' not in user or \\\n 'full_name' not in user or \\\n 'information_bio' not in user or \\\n 'password' not in user:\n response = {'code': 409, 'response': 'Conflict'}\n elif database.Database().add_user(user['email'],user['username'],user['full_name'],user['information_bio'],user['password']):\n response = { 'code': 201, 'response': 'Created','type_api' : 'not_json'}\n else:\n response = {'code': 409,'response': 'Conflict','type_api' : 'not_json'}\n return jsonify(response)\n" }, { "alpha_fraction": 0.7822580933570862, "alphanum_fraction": 0.7822580933570862, "avg_line_length": 16.85714340209961, "blob_id": "23cccf6ce836dab1a07ffcfff7bf2863fb7fd498", "content_id": "ab65ba967d1a9be2c00057dc2e96c5c17785a0ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 124, "license_type": "no_license", "max_line_length": 39, "num_lines": 7, "path": "/ApiWithNginx/api_with_json/app/__init__.py", "repo_name": "fm1ck3y/DevOpsProject", "src_encoding": "UTF-8", "text": "from flask import Flask\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\napp = Flask(__name__)\n\nfrom app import views" }, { "alpha_fraction": 0.5712066292762756, "alphanum_fraction": 0.5737959742546082, "avg_line_length": 31.74576187133789, "blob_id": "d91f7edbe4668539021950740d173542ebe006de", "content_id": "8257f1a136c45d304cd91acd7f8e648186e66b92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1931, "license_type": "no_license", "max_line_length": 86, "num_lines": 59, "path": "/ApiWithNginx/api_with_json/app/database.py", "repo_name": "fm1ck3y/DevOpsProject", "src_encoding": "UTF-8", "text": "import psycopg2\nimport os\nimport logging\n\nlog = logging.getLogger(__name__)\n\nDBNAME = os.getenv('POSTGRES_DB')\nUSER_DB = os.getenv('POSTGRES_USER')\nPASSWORD_DB = os.getenv('POSTGRES_PASSWORD')\nHOST_DB = os.getenv('POSTGRES_HOST')\nPORT_DB = os.getenv('POSTGRES_PORT')\n\nTABLE_NAME_WITH_JSON = os.getenv('TABLE_NAME_WITH_JSON')\n\nclass Database:\n def connect(self):\n try:\n self.conn = psycopg2.connect(dbname=DBNAME, user=USER_DB,\n password=PASSWORD_DB, host=HOST_DB,port = PORT_DB)\n if self.conn is not None:\n logging.debug(f\"Good connection to {DBNAME} with host= {HOST_DB}\")\n self.create_table()\n return self.conn.cursor()\n raise psycopg2.DatabaseError\n except psycopg2.DatabaseError as e:\n log.info(f\"Bad connection to {DBNAME} with host = {HOST_DB}. Error - {e}\")\n log.info(self.conn)\n return None\n\n def close_connection(self):\n try:\n self.cursor.close()\n self.conn.close()\n except Exception as e:\n log.debug(f\"Bad close connection to {DBNAME}\")\n\n def create_table(self):\n sql = f\"\"\"CREATE TABLE IF NOT EXISTS {TABLE_NAME_WITH_JSON} (\nid serial PRIMARY KEY NOT NULL ,\ndata json NOT NULL);\"\"\"\n self.execute_sql(sql)\n\n def execute_sql(self,sql):\n result = False\n try:\n self.cursor = self.connect()\n if self.cursor is not None:\n self.cursor.execute(sql)\n self.conn.commit()\n result = True\n except psycopg2.DatabaseError as e:\n log.error(f\"Bad execute to {DBNAME}\\nError = {e}\\nSQL execute = {sql}\")\n finally:\n return result\n\n def add_user(self,user):\n sql = f\"INSERT INTO {TABLE_NAME_WITH_JSON} (data) \" \\\n f\"VALUES ('{user}');\"\n return self.execute_sql(sql)" }, { "alpha_fraction": 0.5594771504402161, "alphanum_fraction": 0.5816993713378906, "avg_line_length": 28.600000381469727, "blob_id": "0c3eb57efb1e817922bfd9d85ea7f5e87d15211c", "content_id": "afcb908b5183d5f4f18d8d82bcf2bc6207d25525", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 765, "license_type": "no_license", "max_line_length": 133, "num_lines": 25, "path": "/FilesForJobs/generate_data.py", "repo_name": "fm1ck3y/DevOpsProject", "src_encoding": "UTF-8", "text": "import requests\r\nimport sys\r\nimport random\r\n\r\nif len(sys.argv) < 3:\r\n exit()\r\n\r\nN = int(sys.argv[1])\r\nHOST = sys.argv[2]\r\n\r\nif 'http://' not in HOST or 'https://' not in HOST:\r\n HOST = 'http://' + HOST\r\n\r\nNAMES = [\"Artem Vdovin\", \"Igor Lepeyko\"]\r\nEMAILS = [\"123@mail.ru\",\"456@mail.ru\"]\r\nUSERNAMES = [\"llll123\", \"mmmm3333\"]\r\nINFORMATIONS = [\"PRIVET\",\"POKA\"]\r\nPASSWORDS = [\"123\",\"hi\"]\r\n\r\n\r\nfor i in range(N):\r\n user = f'{{\"email\" : \"{random.choice(EMAILS)}\",\"username\":\"{random.choice(USERNAMES)}\",\"full_name\" : \"{random.choice(NAMES)}\",' \\\r\n f'\"information_bio\" : \"{random.choice(INFORMATIONS)}\",\"password\" : \"{random.choice(PASSWORDS)}\"}}'\r\n print(f\"{HOST}/api/v1.0/add_user?user={user}\")\r\n response = requests.get(url = f\"{HOST}/api/v1.0/add_user?user={user}\")\r\n" }, { "alpha_fraction": 0.6491228342056274, "alphanum_fraction": 0.655701756477356, "avg_line_length": 28.45161247253418, "blob_id": "f548f8301f44cc3f5d75597a4449455168164c5e", "content_id": "e908d0f5e0a14e1d669a7778f3248d9dc32c87b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 912, "license_type": "no_license", "max_line_length": 113, "num_lines": 31, "path": "/ApiWithNginx/statistics/app/views.py", "repo_name": "fm1ck3y/DevOpsProject", "src_encoding": "UTF-8", "text": "from flask import jsonify, request, render_template\nfrom app import app\nimport app.database as database\nfrom functools import wraps\n\ndef logging_request(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n response_args = {\n 'ip': request.remote_addr,\n 'args': dict((key, request.args.get(key)) for key in request.args)\n }\n app.logger.info(response_args)\n return f(*args, **kwargs)\n\n return wrapper\n\n@app.errorhandler(404)\ndef not_found(error=None):\n return jsonify({\n 'code': 0,\n 'response': 'Not Found'\n })\n\n\n@app.route('/api/v1.0/statistics', methods=['GET'])\n@logging_request\ndef get_statistics():\n count_with_json = database.Database().count_users_json()\n count_without_json = database.Database().count_users_sql()\n return render_template('index.html', count_with_json=count_with_json, count_without_json= count_without_json)" }, { "alpha_fraction": 0.6685606241226196, "alphanum_fraction": 0.6761363744735718, "avg_line_length": 24.14285659790039, "blob_id": "172c265a4e61d3b84f11135d70fa92e0c0e25029", "content_id": "96ca2656ea0128511f5868fdf2aeebe5a6dd594c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 528, "license_type": "no_license", "max_line_length": 82, "num_lines": 21, "path": "/ApiWithNginx/nginx/conf.d/change_configuration.py", "repo_name": "fm1ck3y/DevOpsProject", "src_encoding": "UTF-8", "text": "import sys\nimport os\n\nif len(sys.argv) < 3:\n print(\"Invalid count arguments.\")\n exit(0)\n\nPATH_TO_TEMPLATE_NGINX_CONF = \"/opt/ApiWithNginx/nginx/conf.d/nginx.conf.template\"\nPATH_TO_NGINX_CONF_LOCAL = \"/opt/ApiWithNginx/nginx/conf.d/nginx.conf\"\n\nwith open(PATH_TO_TEMPLATE_NGINX_CONF,'r') as f:\n text_file = f.read()\n\ntext_file = text_file.replace(\n '${WEIGHT_API_WITHOUT_JSON}', sys.argv[1]\n).replace(\n '${WEIGHT_API_WITH_JSON}', sys.argv[2]\n)\n\nwith open(PATH_TO_NGINX_CONF_LOCAL,'w') as f:\n f.write(text_file)\n" }, { "alpha_fraction": 0.6991150379180908, "alphanum_fraction": 0.7256637215614319, "avg_line_length": 21.600000381469727, "blob_id": "1eedbe27d2f99a3ed44f19f99499aedcb760a3fd", "content_id": "2512f0a2318e776802a588049cbd6783cdab5c57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 113, "license_type": "no_license", "max_line_length": 35, "num_lines": 5, "path": "/ApiWithNginx/api_without_json/Dockerfile", "repo_name": "fm1ck3y/DevOpsProject", "src_encoding": "UTF-8", "text": "FROM python:3.8-slim-buster\nWORKDIR /app\nADD . /app\nRUN pip install -r requirements.txt\nCMD [\"python3\",\"run.py\"]\n" }, { "alpha_fraction": 0.7326732873916626, "alphanum_fraction": 0.7524752616882324, "avg_line_length": 27.85714340209961, "blob_id": "517ef3efabc085c3409627af473ef804ad5141ce", "content_id": "9adda844827310d3ca642553c9d4ac58a60d6095", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 202, "license_type": "no_license", "max_line_length": 67, "num_lines": 7, "path": "/start.sh", "repo_name": "fm1ck3y/DevOpsProject", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nexport AWS_ACCESS_KEY_ID=\nexport AWS_SECRET_ACCESS_KEY=\nterraform init\nterraform apply -auto-approve -lock=False\necho \"Jenkins = http://$(terraform output -raw jenkins_vm_ip):8080\"\n" }, { "alpha_fraction": 0.5703666806221008, "alphanum_fraction": 0.5743310451507568, "avg_line_length": 32.650001525878906, "blob_id": "077d6a9d1918191c752b5d9a9513496e040f1d65", "content_id": "6d04d7c9d2602b3673267cee48afe153e629bfd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2018, "license_type": "no_license", "max_line_length": 93, "num_lines": 60, "path": "/ApiWithNginx/statistics/app/database.py", "repo_name": "fm1ck3y/DevOpsProject", "src_encoding": "UTF-8", "text": "import psycopg2\nimport os\nimport logging\n\nlog = logging.getLogger(__name__)\n\nDBNAME = os.getenv('POSTGRES_DB')\nUSER_DB = os.getenv('POSTGRES_USER')\nPASSWORD_DB = os.getenv('POSTGRES_PASSWORD')\nHOST_DB = os.getenv('POSTGRES_HOST')\nPORT_DB = os.getenv('POSTGRES_PORT')\n\nTABLE_NAME_WITHOUT_JSON = os.getenv('TABLE_NAME_WITHOUT_JSON')\nTABLE_NAME_WITH_JSON = os.getenv('TABLE_NAME_WITH_JSON')\n\nclass Database:\n def connect(self):\n try:\n self.conn = psycopg2.connect(dbname=DBNAME, user=USER_DB,\n password=PASSWORD_DB, host=HOST_DB, port=PORT_DB)\n if self.conn is not None:\n logging.debug(f\"Good connection to {DBNAME} with host= {HOST_DB}\")\n return self.conn.cursor()\n raise psycopg2.DatabaseError\n except psycopg2.DatabaseError as e:\n log.info(f\"Bad connection to {DBNAME} with host = {HOST_DB}. Error - {e}\")\n log.info(self.conn)\n return None\n\n def close_connection(self):\n try:\n self.cursor.close()\n self.conn.close()\n except Exception as e:\n log.debug(f\"Bad close connection to {DBNAME}\")\n\n def execute_sql(self, sql):\n try:\n self.cursor = self.connect()\n if self.cursor is not None:\n self.cursor.execute(sql)\n response = self.cursor.fetchone()\n return response\n except psycopg2.DatabaseError as e:\n log.error(f\"Bad execute to {DBNAME}\\nError = {e}\\nSQL execute = {sql}\")\n return 0\n\n def count_users_sql(self):\n try:\n count,*_ = self.execute_sql(f\"SELECT COUNT(id) FROM {TABLE_NAME_WITHOUT_JSON};\")\n return int(count)\n except Exception:\n return 0\n\n def count_users_json(self):\n try:\n count,*_ = self.execute_sql(f\"SELECT COUNT(id) FROM {TABLE_NAME_WITH_JSON};\")\n return int(count)\n except Exception:\n return 0" } ]
10
danmandel/WebScraper
https://github.com/danmandel/WebScraper
96956838bfc8c8a3f8e23ec051163c00aa2950a0
f6951d9ffad789c7c3d09229f357b9a8a6cf1d83
e5ac1a236f256e21be1d1859280baeaa2f92de38
refs/heads/master
2021-01-23T07:10:23.689021
2015-03-21T03:19:22
2015-03-21T03:19:22
32,434,012
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.46020975708961487, "alphanum_fraction": 0.466378778219223, "avg_line_length": 27.438596725463867, "blob_id": "f4c9030f7d9d57ea63921b1f20b73e2f8cc92fe5", "content_id": "9150e4042c4f30b1e444e1978ecfcafe310f9de0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1621, "license_type": "no_license", "max_line_length": 79, "num_lines": 57, "path": "/Main.py", "repo_name": "danmandel/WebScraper", "src_encoding": "UTF-8", "text": "import time\nimport urllib2\nfrom urllib2 import urlopen\nimport re\nimport cookielib, urllib2\nfrom cookielib import CookieJar\nimport datetime\nimport nltk\n \n \ncj = CookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))\nopener.addheaders = [('User-agent', 'Mozilla/5.0')]\n \n \n \n \ndef main():\n try:\n page = 'http://www.huffingtonpost.com/feeds/index.xml'\n sourceCode = opener.open(page).read()\n #print sourceCode\n \n try:\n titles = re.findall(r'<title>(.*?)</title>',sourceCode)\n links = re.findall(r'<link>(.*?)</link>',sourceCode)\n #for title in titles:\n #print title\n for link in links[1:]:\n if link == 'www.huffingtonpost.com':\n pass\n else:\n print 'let\\'s visit:',link\n print ' _____________________________________'\n linkSource = opener.open(link).read()\n #content = re.findall(r'<p>(.*?)</p>',linkSource)\n #content = re.findall(r'<p>((.|\\n)*)<p>___</p>',linkSource)\n content = re.findall(r'<p>((.|\\n)*)<p>___</p>',linkSource)\n linesOfInterest = re.findall(r'<p>(.*?)</p>',str(content))\n \n for eachLine in linesOfInterest:\n print eachLine\n \n #time.sleep(55)\n \n \n \n except Exception, e:\n print str(e)\n \n \n \n except Exception,e:\n print str(e)\n pass\n \nmain()\n" } ]
1
12389285/meps
https://github.com/12389285/meps
15a3aac302395714af4a633c9059985740cf6eff
200159d6bbb504cc95f6d3fc3a2203af5dc9486e
0fdcb0780d693ef0b2b0b5089b231b829e41a5fd
refs/heads/master
2020-04-05T00:09:56.659262
2018-12-19T14:18:04
2018-12-19T14:18:04
156,385,913
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5621890425682068, "alphanum_fraction": 0.5820895433425903, "avg_line_length": 23.1200008392334, "blob_id": "7b1530174c4ab492ba72f6adfba63000c9201bd5", "content_id": "96975492afe43a6b0228cf3150407fbcba986b82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 603, "license_type": "no_license", "max_line_length": 76, "num_lines": 25, "path": "/code/algorithms/plot.py", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\n\ndef plot_scores(points, iterations, title):\n \"\"\"\n This function takes the list of scores and iterations and retrun a plot.\n \"\"\"\n\n # plot figure\n if min(points) > 0:\n print(\"ja\")\n ymin = 0\n if min(points) < 0:\n print(\"nee\")\n ymin = -400\n ymax = max(points) + 100\n xmin = 0\n xmax = len(points)\n plt.plot(range(0, xmax), points)\n plt.axis([xmin, xmax, ymin, ymax])\n plt.text(xmax + 1, min(points), min(points))\n plt.title(title)\n plt.xlabel('Iterations')\n plt.ylabel('Points')\n\n return plt.show()\n" }, { "alpha_fraction": 0.5488611459732056, "alphanum_fraction": 0.5584129095077515, "avg_line_length": 39.02941131591797, "blob_id": "5cfb0f7be40e1df3a8918df963cced71c65ad710", "content_id": "ca89abc2c3723d8d0c2563a2e617bfe7a39497ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1361, "license_type": "no_license", "max_line_length": 92, "num_lines": 34, "path": "/code/algorithms/scorefunction_show.py", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "from code.constraints.capacity import capacity\nfrom code.constraints.overlap_simulated import overlapping\nfrom code.constraints.order import order\nimport time\nfrom code.constraints.distribution import distribution\n\ndef scorefunction_show(schedule, courses, rooms, overlap_dict):\n\n malus = 0;\n\n for i in range(len(schedule)):\n for j in range(len(schedule[i])):\n for k in range(len(schedule[i][j])):\n if schedule[i][j][k] != None:\n if j == 4:\n malus = malus + 20\n print('malus 20 points')\n capacity_show = capacity(schedule[i][j][k], rooms[k], courses)\n if capacity_show!= 0:\n print(f'capacity: ', schedule[i][j][k], capacity_show)\n\n malus = malus + capacity(schedule[i][j][k], rooms[k], courses)\n if overlapping(schedule[i][j][k], schedule[i][j], overlap_dict, k) == False:\n print(f'overlapping', schedule[i][j][k])\n malus = malus + 800\n if order(schedule, schedule[i][j][k], i, j) == False:\n print(f'order', schedule[i][j][k])\n malus = malus + 600\n\n\n print(f'points ditribution: ',distribution(schedule, courses))\n malus = malus + distribution(schedule, courses)\n\n return malus\n" }, { "alpha_fraction": 0.5813397169113159, "alphanum_fraction": 0.5944976210594177, "avg_line_length": 41.871795654296875, "blob_id": "f8b7b5d37d220c0ad07b508a02ccba33a11b6dca", "content_id": "74ee4de380e723459d58eb9befacd4bdb11201bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1672, "license_type": "no_license", "max_line_length": 92, "num_lines": 39, "path": "/code/algorithms/scorefunction_deterministic.py", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "from code.constraints.capacity import capacity\nfrom code.constraints.overlap_simulated import overlapping\nfrom code.constraints.order import order\nimport time\nfrom code.constraints.distribution import distribution\n\ndef scorefunction_deterministic(schedule, courses, rooms, overlap_dict):\n \"\"\"\n this scorefunction calculates the malus points for a schedule,\n where the hard constraints are not necessarily satisfied\n \"\"\"\n\n malus = 0;\n\n # loop over days\n for i in range(len(schedule)):\n # loop over timelocksin day\n for j in range(len(schedule[i])):\n # loop over roomlock in timelock\n for k in range(len(schedule[i][j])):\n # only malus points can be calculated if roomlock is not zero\n if schedule[i][j][k] != None:\n # 20 malus points are calculated if roomlock is the last (17-19h)\n if j == 4:\n malus = malus + 20\n # add maluspoints for not enough capacity in the rooms\n malus = malus + capacity(schedule[i][j][k], rooms[k], courses)\n # check if there is a overlapping part subject in same timelock\n if overlapping(schedule[i][j][k], schedule[i][j], overlap_dict, k) == False:\n # if so, add 800 maluspoints\n malus = malus + 800\n # check if order of the activities of subject is ok\n if order(schedule, schedule[i][j][k], i, j) == False:\n # if not, add 600 maluspoints\n malus = malus + 600\n\n malus = malus + distribution(schedule, courses)\n\n return malus\n" }, { "alpha_fraction": 0.5645280480384827, "alphanum_fraction": 0.5645280480384827, "avg_line_length": 28.80219841003418, "blob_id": "a68b24426cb18846f11a1426ba8fb4e8820f8ebb", "content_id": "28718eb7a7eb9b0debd621ceab92f9e80a1d57d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2712, "license_type": "no_license", "max_line_length": 82, "num_lines": 91, "path": "/code/algorithms/start_schedule_algorithm.py", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "from code.constraints.overlap import overlapping\nfrom code.constraints.order import order\nfrom .scorefunction import scorefunction\nimport operator\nfrom operator import attrgetter\nfrom random import shuffle\n\ndef create_start_schedule(courses, schedule, rooms, overlap_dict):\n \"\"\"\n This function returns a schedule that satisfies the hard constraints.\n\n This function takes as input arguments:\n - list of Courses\n - empty schedule\n - list of rooms\n - overlap matrix\n\n This function works as follows:\n - puts activity of queue one by one in first possible room day_lock\n \"\"\"\n\n queue = lecfirst_random_queue(courses)\n\n # check if queue is not empy\n while queue != []:\n # select day i\n for i in range(len(schedule)):\n # select timelock j\n for j in range(len(schedule[i])):\n # select room lock k\n for k in range(len(schedule[i][j])):\n if schedule[i][j][k] is None:\n for l in range(len(queue)):\n if overlapping(queue[l],schedule[i][j], overlap_dict):\n if order(schedule, queue[l], i, j):\n schedule[i][j][k] = queue[l]\n queue.remove(queue[l])\n break\n else:\n continue\n else:\n continue\n\n return(schedule)\n\ndef lecfirst_random_queue(courses):\n \"\"\"\n This function returns a queue:\n - first all lectures of the courses in random order\n - after that all tutorials and practica in random order\n \"\"\"\n\n # create first queue which still is alphabetic\n alphab_queue = alphabetic_queue(courses)\n\n lectures = []\n others = []\n queue = []\n\n # seperate the lectures from other activities in lists\n for i in range(len(alphab_queue)):\n if '_lec' in alphab_queue[i]:\n lectures.append(alphab_queue[i])\n else:\n others.append(alphab_queue[i])\n\n # randomize the order\n shuffle(lectures)\n shuffle(others)\n\n # create queue woth lectures first\n for i in range(len(lectures)):\n queue.append(lectures[i])\n\n for i in range(len(others)):\n queue.append(others[i])\n\n return queue\n\ndef alphabetic_queue(courses):\n \"\"\"\n This function returns a queue of all activities in alphabetic order.\n \"\"\"\n\n alphab_queue = []\n\n for course in courses:\n for i in range(len(course.activities)):\n alphab_queue.append(course.activities[i])\n\n return(alphab_queue)\n" }, { "alpha_fraction": 0.5505882501602173, "alphanum_fraction": 0.5529412031173706, "avg_line_length": 33.4594612121582, "blob_id": "e8ccaa13937f18d9f09a3484df5915e0506f1cc2", "content_id": "0a4e523805e2abec106bf983b0af515423b1ee38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1275, "license_type": "no_license", "max_line_length": 77, "num_lines": 37, "path": "/code/constraints/overlap_simulated.py", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "def overlapping(activity, timelock, overlap_dict, roomlock):\n \"\"\"\n This function returns True if the is no overlap with courses given in the\n overlap matrix. Otherwise, it returns False.\n\n This function takes as input arguments:\n - activity\n - time lock and room lock\n - overlap matrix\n \"\"\"\n\n # if it is None it is always true\n if activity == None:\n return True\n\n else:\n # check if two lectures are given in timelock\n if '_lec' in activity:\n for i in range(len(timelock)):\n if i == roomlock:\n continue\n elif activity == timelock[i]:\n return False\n\n # check if no other overlap-course is given in the same time lock\n activity = activity.split('_')\n for i in range(len(timelock)):\n activity_timelock = timelock[i]\n if activity_timelock != None:\n if i == roomlock:\n continue\n activity_timelock = timelock[i].split('_')\n activity_timelock = activity_timelock[0]\n if activity_timelock in overlap_dict[activity[0]]:\n if activity_timelock != activity[0]:\n return False\n return True\n" }, { "alpha_fraction": 0.5443786978721619, "alphanum_fraction": 0.5443786978721619, "avg_line_length": 23.14285659790039, "blob_id": "eb74b50acf91c27ed74064d33c78610294d1981e", "content_id": "79c609068b39fa47fe5ba4f2ff795e9c77821768", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "no_license", "max_line_length": 66, "num_lines": 14, "path": "/code/classes/room.py", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "class Room(object):\n \"\"\"\n This class classifies all the rooms.\n \"\"\"\n\n def __init__(self, name, capacity):\n \"\"\"\n The rooms have a name and a maximum capicity for students.\n \"\"\"\n self.name = name\n self.capacity = capacity\n\n def __str__(self):\n return f\"{self.name}, {self.capacity}\"\n" }, { "alpha_fraction": 0.5197057127952576, "alphanum_fraction": 0.5281134843826294, "avg_line_length": 30.19672203063965, "blob_id": "6912b30660407e2d2b085e579cb6f1a60c2c02fb", "content_id": "1da406766a5618a6361e839fe2736ddeb73a1aa3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1903, "license_type": "no_license", "max_line_length": 77, "num_lines": 61, "path": "/code/constraints/order.py", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "def order(schedule, activity, daylock, timelock):\n \"\"\"\n This function returns True if the lectures are given before the tutorials\n and/or practica when activity is switched to day en timelock.\n Otherwise, it returns False.\n\n This function takes as input arguments:\n - the schedule\n - the activity\n - the exact day lock and time lock\n\n This function works as follows:\n - if activity is a practica or tutorial: it checks if a lecture is\n given in a timelock after it\n - if activity is lecture: it checks if tutorial or practicum is given\n in an earlier time lock\n \"\"\"\n\n # if None, it can always be switched\n if activity == None:\n return True\n\n else:\n # split to see what kind of activity it is\n course, sort = activity.split(\"_\")\n\n if 'tut' in sort or 'prac' in sort:\n # search for lecture after new tut/prac porition\n\n str = course + '_lec'\n\n for i in range(timelock + 1, 5):\n if str in schedule[daylock][i]:\n return False\n\n for j in range(daylock + 1, 5):\n for k in range(0, 5):\n if str in schedule[j][k]:\n return False\n\n elif 'lec' in sort:\n # search for tut or prac before new lecture position\n\n str1 = course + '_prac'\n str2 = course + '_tut'\n\n\n for i in range(0, timelock):\n if str1 in schedule[daylock][i]:\n return False\n elif str2 in schedule[daylock][i]:\n return False\n\n for j in range(0, daylock):\n for k in range(0, 5):\n if str1 in schedule[j][k]:\n return False\n elif str2 in schedule[j][k]:\n return False\n\n return True\n" }, { "alpha_fraction": 0.582514762878418, "alphanum_fraction": 0.582514762878418, "avg_line_length": 31.838708877563477, "blob_id": "1420ec05141a85056ed8b37c45dd9a9fe0a923bf", "content_id": "2e9b95989113c63e82537327fe8a8aaa7652521f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1018, "license_type": "no_license", "max_line_length": 114, "num_lines": 31, "path": "/code/classes/courses.py", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "class Courses(object):\n\n def __init__(self, name, lec, tut, prac, tut_tot, prac_tot, max_tut, max_prac, exp_stud, act_tot, dif_total):\n\n \"\"\"\n In this class the courses are classified. The courses are divided in Lectures,\n Tutorials and Practials. Also the numbers of different courses are listed and\n the number of expected students.\n \"\"\"\n\n self.name = name\n self.lec = lec\n self.tut = tut\n self.prac = prac\n self.tut_tot = tut_tot\n self.prac_tot = prac_tot\n self.act_tot = act_tot\n self.max_tut = max_tut\n self.max_prac = max_prac\n self.exp_stud = exp_stud\n self.dif_total = dif_total\n self.activities = []\n\n def add(self, activity):\n \"\"\"\n Add function to add the activities to a list.\n \"\"\"\n self.activities.append(activity)\n\n def __str__(self):\n return f\"{self.course_name}, {self.course_lec}, {self.course_tut}, {self.course_prac}, {self.activities} \"\n" }, { "alpha_fraction": 0.7664233446121216, "alphanum_fraction": 0.7688564658164978, "avg_line_length": 50.375, "blob_id": "1ac704ee82d08a3e386bb23d3780b4608f260991", "content_id": "e1c237a482b1242187ea04c4eb793ebc7d544f78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 411, "license_type": "no_license", "max_line_length": 133, "num_lines": 8, "path": "/data/README.md", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "# Data\n\nTo make the schedule we have used 3 data files. These data files can be found in this folder. The data files are CSV formatted files.\n\nThe data files:\n* overlapping.csv: In this file you can find the courses with overlap.\n* rooms.csv: In this file you can find the rooms that are available and the maximum capacity.\n* course.csv: In this file you can find all information of the courses that are given.\n" }, { "alpha_fraction": 0.6359342932701111, "alphanum_fraction": 0.6378850340843201, "avg_line_length": 37.650794982910156, "blob_id": "65d7ca398e760e04eeb7a512725348f80b7cca7d", "content_id": "b7b169146503e7d4efb9204a4e4fe24fcf7b8025", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9740, "license_type": "no_license", "max_line_length": 141, "num_lines": 252, "path": "/code/algorithms/algorithm_deterministic.py", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "import random\nimport copy\nimport time\nimport math\nfrom code.algorithms.start_schedule_algorithm import alphabetic_queue\nfrom code.algorithms.scorefunction_deterministic import scorefunction_deterministic\nfrom .plot import plot_scores\n\ndef make_random_schedule(courses, schedule, rooms, overlap_dict):\n \"\"\"\n This function makes a random schedule (no hard constraints satisfied)\n\n This function takes as input arguments:\n - the courselist (classes)\n - the empty schedule\n - the roomlist\n - the overlapping dictionary\n\n This function works as follows:\n - It makes a alphabetical courselist (by calling the alphabetic_queue function)\n - It iterates over every roomlock in the empty schedule, at each empty roomlock it places a random course acitivty.\n - Then it removes the chosen acitivy from the courselist.\n This proces is repeated untill the courselist is empty.\n \"\"\"\n\n course_list_alphabetic = alphabetic_queue(courses)\n\n for i in range(len(schedule)):\n for j in range(len(schedule[i])):\n for k in range(len(schedule[i][j])):\n if course_list_alphabetic != []:\n length = len(course_list_alphabetic)\n list_place = random.randint(0, (length - 1))\n schedule[i][j][k] = course_list_alphabetic[list_place]\n course_list_alphabetic.remove(course_list_alphabetic[list_place])\n return schedule\n\n\ndef algorithm(courses, schedule_empty, iterations, rooms, overlap_dict, simulated_annealing_true):\n \"\"\"\n This algorithm runs the deterministic algorithms\n\n This algorithm takes as input arguments:\n - the courselist (classes)\n - the empty schedule\n - number of iterations\n - the roomlist,\n - the overlapping dictionary\n - boolean for Simulated Annealing or Hillclimber (boolean)\n\n This function works as follows:\n - First a random schedule is made by calling the function make_random_schedule.\n - The score of the random schedule is saved, a copy of the schedule is made and the temperature is set.\n\n - The algorithm is run as many times as instructed by the user.\n - Every loop the temperature drops with a certain amount (only needed in the simulated annealing).\n - The algorithm iterates through every roomlock in the schedule (first),\n - Then the function swap_with_every is called, which swaps this roomlock with every roomlock\n in the schedule. This swap function returns a score_list, an array_day,\n an array_timelock and an array_roomlock such that in a later stadium the activity of the swap can be found.\n\n - If the user instructed simulated annealing: the simulated annealing function determines the index of swap.\n - The swap function swaps with the chosen swap index.\n - If the swap has a better score then the saved score (at simulated annealing not always the case),\n this score and this schedule are saved\n\n - When the user instructed hillclimber: the hillclimber function determines the index of swap.\n - The swap function swaps with the chosen swap index.\n - Then the score is printed.\n \"\"\"\n schedule = make_random_schedule(courses, schedule_empty, rooms, overlap_dict)\n score_save = scorefunction_deterministic(schedule, courses, rooms, overlap_dict)\n schedule_save = copy.deepcopy(schedule)\n temp = 5\n score_plot_list = []\n\n\n for bigloop in range(iterations):\n temp = temp * 0.75\n for i in range(len(schedule)):\n for j in range(len(schedule[i])):\n for k in range(len(schedule[i][j])):\n\n list_scores = []\n array_day = []\n array_timelock = []\n array_roomlock = []\n\n list_scores, array_day, array_timelock, array_roomlock = swap_with_every(schedule, i, j, k, courses, rooms, overlap_dict)\n\n if simulated_annealing_true == True:\n title_plot = 'Simulated Annealing Deterministic'\n chosen_swap = simulated_annealing(list_scores, temp)\n schedule = swap(schedule, chosen_swap, array_day, array_timelock, array_roomlock, i, j, k)\n\n malus = score = scorefunction_deterministic(schedule, courses, rooms, overlap_dict)\n\n if malus < score_save:\n score_save = malus\n schedule_save = schedule\n\n score_plot_list.append(score_save)\n\n else:\n title_plot = 'Hillclimber Deterministic'\n score_current = scorefunction_deterministic(schedule, courses, rooms, overlap_dict)\n chosen_swap = hillclimber(list_scores, score_current)\n if chosen_swap != False:\n schedule = swap(schedule, chosen_swap, array_day, array_timelock, array_roomlock, i, j, k)\n schedule_save = schedule\n malus = scorefunction_deterministic(schedule, courses, rooms, overlap_dict)\n print(f'score: ', malus)\n score_plot_list.append(malus)\n\n plot_scores(score_plot_list, iterations, title_plot)\n\n return schedule\n\ndef hillclimber(list_scores, score):\n \"\"\"\"\"\n Hillclimber determines the swap index\n Hillclimber determines the swap\n\n This function takes as input arguments:\n - list_scores\n - current score of unswapped schedule\n\n This function works as follows:\n - The minimum of scorelist is determined\n - If the minimum score is lower than the current score:\n The minimum score is looked up in the score list and the corresponding index number is returned\n - If the minimum score is not lower than the current score false is returned\n \"\"\"\"\"\n min_score = min(list_scores)\n\n if min_score < score:\n for m in range(len(list_scores)):\n if list_scores[m] == min_score:\n return m\n else:\n return False\n\n\n\ndef simulated_annealing(list_scores, temp):\n \"\"\"\"\n Simulated annealing determines the swap index\n\n This function takes as input arguments:\n - list_scores\n - temperature\n\n This function works as follows:\n - Of all scores in list_scores the e_scores are calculated and added to e-score list.\n - All e-scores are added to e_score sum.\n - A float between 0 and 1 is extracted from the uniform distribution (probability)\n - Loop over every e-score in list e-score:\n The e-score probability in comparison to the other e-scores is calculated and added to p-sum.\n - The iteration where p-sum becomes bigger than probability, the index of that e-score is returned.\n \"\"\"\n\n e_scores = []\n e_score_sum = 0\n min_score = min(list_scores)\n for z in range(len(list_scores)):\n list_scores[z] = list_scores[z] - min_score\n tmp = -list_scores[z]/temp\n if tmp > 100:\n tmp=100\n e_score = math.exp(tmp)\n e_scores.append(e_score)\n e_score_sum = e_score_sum + e_score\n\n probability = random.uniform(0,1)\n p_sum = 0\n\n for n in range(len(e_scores)):\n e_scores[n] = e_scores[n]/ e_score_sum\n p_sum = p_sum + e_scores[n]\n if p_sum > probability:\n return n\n\ndef swap_with_every(schedule, i, j, k, courses, rooms, overlap_dict):\n \"\"\"\n This function swaps every roomlock in the schedule with the given roomlock\n and calculates the score\n\n This function takes as input arguments:\n - the schedule\n - the daylock i, timelock j and roomlock k (where the algorithm iteration is)\n - the courses (classes)\n - the roomlist\n - the overlapping dictionary\n\n This function works as follows:\n - It loops over every roomlock in the schedule and swaps it with the givgen roomlock\n - It calculates the score of each swap and adds it to the score_list\n - Of each swap the daylock, timelock and roomlock are added to their assigned array\n (this is done such that in the swap function the activity beloning to the swap can be found)\n \"\"\"\n\n list_scores = []\n array_day = []\n array_timelock = []\n array_roomlock = []\n\n for a in range(len(schedule)):\n for b in range(len(schedule[a])):\n for c in range(len(schedule[a][b])):\n schedule_copy = copy.deepcopy(schedule)\n schedule_copy[i][j][k] = schedule[a][b][c]\n schedule_copy[a][b][c] = schedule[i][j][k]\n score = scorefunction_deterministic(schedule_copy, courses, rooms, overlap_dict)\n list_scores.append(score)\n\n array_day.append(a)\n array_timelock.append(b)\n array_roomlock.append(c)\n\n return [list_scores, array_day, array_timelock, array_roomlock]\n\n\n\ndef swap(schedule, chosen_swap, array_day, array_timelock, array_roomlock, i, j, k):\n \"\"\"\n This function swaps 2 activities\n\n This function takes as input arguments:\n - schedule\n - chosen swap index (from hillclimber of simulated annealing)\n - array_day\n - array_timelock\n - array_roomlock\n - i (day of roomlock)\n - j (timelock of roomlock)\n - k (roomlock)\n\n This function works as follows:\n - The day, timelock and roomlock of chosen swap are determined with the arrays\n - The activity is saved in temporary\n - The activities are swapped\n \"\"\"\n a = array_day[chosen_swap]\n b = array_timelock[chosen_swap]\n c = array_roomlock[chosen_swap]\n\n temporary = schedule[i][j][k]\n schedule[i][j][k] = schedule[a][b][c]\n schedule[a][b][c] = temporary\n\n\n return schedule\n" }, { "alpha_fraction": 0.7747349739074707, "alphanum_fraction": 0.7765017747879028, "avg_line_length": 29.594594955444336, "blob_id": "a93d9f90dc7f7c0e35f8850ab302640dfeabab27", "content_id": "2fb9c44371e9b2889ecbf65ec477f747e66ae273", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1132, "license_type": "no_license", "max_line_length": 221, "num_lines": 37, "path": "/code/README.md", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "# Code\n\n## Algorithms\n\nIn the folder algorithms you can find all the algorithms we have used to solve the case. Also the score functions to calculate the amount of points and to plot maker are stored in the folder.\n\n* algorithm_deterministic.py\n* algorithm.py\n* plot.py\n* scorefunction_deterministic.py\n* scorefunction_show.py\n* scorefunction.py\n* start_schedule_algorithm.py\n\n## Classes\n\nIn this folder you can find the classes to load all the data.\n\n* courses.py\n* room.py\n* schedule.py\n\n## Constraints\n\nTo check if the schedule is valid we have to take into account with the constraints.\n\n* capacity.py: the maximum of every room\n* distribution.py: for the distribution of the schedule\n* order.py: to order the courses in lectures, tutorials and practicals\n* overlap_simulated: overlapping of courses\n* overlap.py: overlapping of courses\n\n## Schedule\n\nThe algorithms return a 3D list. To get a better and a more clear view we have written a schedule maker. The schedule maker convert the 3D list into a CSV file which can be opened with Microsoft excel to use the schedule.\n\nThe schedule can be find in meps/results/schedule.csv\n" }, { "alpha_fraction": 0.7542406320571899, "alphanum_fraction": 0.7712031602859497, "avg_line_length": 33.72602844238281, "blob_id": "1f95269bc3ed130bcd7872fd2076621c8f6ab863", "content_id": "e31955a26c64270a1d864310d48d4f36ffe04f28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2535, "license_type": "no_license", "max_line_length": 291, "num_lines": 73, "path": "/README.md", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "# Lectures & Lesroosters\n\n## Description\n\nLecture schedules for students are very difficult to fill in because of the many constraints and variables they contain. In this problem we'll look into a small example of a schedule maker using 29 courses, 7 rooms and 600 students of the University of Amsterdam, location Science Park.\n\nWithin this problem we will look into and calculate the state space of our problem. When we calculated the state space we will implement algorithms to make the best schedule for the students. To decide which schedule is better, we use a score function calculating the malus and bonus points.\n\nFor more information about the case please visit the following page:\n\n```\nhttp://heuristieken.nl/wiki/index.php?title=Lectures_%26_Lesroosters\n```\n\n## Getting started\n\n### Prerequisites\n\nThis code is written in Python version 3.7.0. The libraries/packages the user will need to run our code are written in requirements.txt, these packages are easily to install using pip. Execute the following instruction in your terminal\n\n```\npip install -r requirements.txt\n```\n\n### Structure\n\n#### Code\nIn the code folder you'll find al our codes including the algorithms and the constraints we used. Also all the classes and the converter to get the schedule are stored in the folder code.\n\n#### Data\nIn the data folder you'll find all the CSV files we imported for the data including the rooms, courses and overlapping of the courses.\n\n#### Results\nIn the result folder you'll find the results of some testing, the state space and score function in the readme. The final schedule is also stored in this folder.\n\n### Testing\n\nTo run our code with the settings of your choice, execute the following instruction in your terminal. We have set a range for iterations and number of swaps. The run time for the deterministic algorithms takes a lot longer than the hillclimber and simulated annealing.\n\nHillclimber:\n```\npython main.py hillclimber [1, inf]\n```\n\nHillclimber deterministic:\n```\npython main.py hillclimber_deterministic [1, 20]\n```\n\nSimulated annealing:\n```\npython main.py simulated_annealing [1, inf]\n```\n\nSimulated annealing deterministic:\n```\npython main.py simulated_annealing_deterministic [1, 20]\n```\n\n### Results\n\nThe schedule is stored in the results folder with the name schedule.csv. Matplotlib is making a plot of the number of iterations and the amount of points given for the schedule.\n\n## Authors\n\n* Eefje Roelsema (10993673)\n* Pascalle Veltman (11025646)\n* Max Simons (12389285)\n\n## Acknowledgments\n\n* Bram van de Heuvel\n* StackOverflow\n" }, { "alpha_fraction": 0.6844444274902344, "alphanum_fraction": 0.7337373495101929, "avg_line_length": 29.9375, "blob_id": "9fc8855a83f14ac3c951b5bcbdb9d2bf5489bfe9", "content_id": "84ebf038aa60c0a37d183876d98bf53b7c6a2bd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2475, "license_type": "no_license", "max_line_length": 291, "num_lines": 80, "path": "/results/README.md", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "# State space:\n\nTo get an idea of the valid solutions our problem can solve, we calculated the state space for each section.\n\n### Section A:\n\n* The calculations are weekly based.\n* 25 time locks (5 per day, where for the last lock only one room is available).\n* per time lock 7 rooms.\n\nTotal: 145 rooms available per week.\n\nthere are 29 courses per week\nEvery course has different kind of activities:\n * Lecture\n * Tutorial\n * Practicum\n\nTotal of 72 activities per week.\n\nThe courses will be put in one for one in a room lock. A room lock can only used for one course.\n\nIf we go threw the room locks we start with 145 options and will decrease every time one by one: 145 * 144 * 143 ...\n\nSo our upperbound is:\n\n145 - 72 = 73\n\n145!/73! = 1.800e+146\n\n### section B\n\nTo calculate the state space in section B it is important to use the amount of students the UvA is expecting per course. Some lectures, tutorials or practicals there applied more students than there is place in a room. In this case we have to schedule another room for the leftover students.\n\nTo take into account with the students we have a lot more activities compare to section A. We now have a total of 126 activities we have to schedule.\n\nSo our upperbound for section B is:\n\n145 - 126 = 19\n\n145!/19! = 6.615e+234\n\n## Score function\n\nTo determine which schedule the best schedule is we have a score function.\n\n* For every student who doesn't fit in the room --> 1 malus point\n* For every time we use the 17:00 - 19:00 time lock --> 20 malus malus points\n* If a course have 2-4 activities and the courses are distribute over a week --> 20 bonus points\n* Distribution of x activities in a week --> 10-30 malus points\n\n### section A\n\nIn the worst case:\n* All students didn't got a place --> 1410 malus points\n* Use of last time lock every day --> 100 malus points\n\nTotal of 1510 malus points\n\nbest case:\n* All students got a place --> 0 malus points\n* No use of last time lock --> 0 malus points\n\n### section B\n\nIn the worst case:\n* All students didn't got a place --> 1410 malus points\n* Use of last time lock every day --> 100 malus points\n* No bonus points\n* Distribute x activities on the same day --> 410 malus points\n\nTotal of 1920 points\n\nBest case:\n* All students got a place --> 0 malus points\n* No use of last time lock --> 0 malus points\n* All courses with 2-4 activities distribute over a week --> 400 bonus points\n* Distribution of x activities in a week --> 0 malus points\n\nTotal of -400 points\n" }, { "alpha_fraction": 0.5327635407447815, "alphanum_fraction": 0.5441595315933228, "avg_line_length": 28.25, "blob_id": "7e0c5a3d0ac362a62f345e605f9256bd02807a40", "content_id": "2bdf92d92d2e9186a8e0619af572e14fd933445e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 702, "license_type": "no_license", "max_line_length": 85, "num_lines": 24, "path": "/code/classes/schedule.py", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "class Schedule(object):\n\n def __init__(self):\n self.empty_schedule = self.create()\n\n def create(self):\n\n \"\"\"\n This function creates an empty schedule. First it creates an empty list\n and fills the list with Nones. For every day it creates 5 time locks within\n the first 4, 7 roomslocks. In the last time lock there is only one room lock.\n \"\"\"\n list = []\n for i in range(5):\n time_locks = [None] * 5\n for i in range(4):\n time_locks[i] = [None] * 7\n time_locks[4] = [None]\n list.append(time_locks)\n\n return list\n\n def __str__(self):\n return f\"{self.empty_schedule}\"\n" }, { "alpha_fraction": 0.5741444826126099, "alphanum_fraction": 0.5754119157791138, "avg_line_length": 31.875, "blob_id": "ed308cb3e3e3456a3ad6fe51d0c9c0ca8d9774ba", "content_id": "a339b85ba17859d0a9f10264c0de8eefc1fb4f35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1578, "license_type": "no_license", "max_line_length": 71, "num_lines": 48, "path": "/code/constraints/capacity.py", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "from code.classes.room import Room\nfrom code.classes.courses import Courses\n\ndef capacity(course, room, courses):\n \"\"\"\n This function returns the malus points of students not fitting\n into a room.\n\n This function takes as input arguments:\n - the course activity\n - the room in which the course is given\n - the list of all courses\n\n This function works as follows:\n - it determines how many students are at the activity\n - it calculates how many students do not fit in the rooms\n \"\"\"\n\n # split input into course and activity kind\n if course != None:\n course_kind, activity_kind = course.split(\"_\")\n\n # find the amount of students at activity\n if course != None:\n for i in range(len(courses)):\n if course_kind == courses[i].name:\n if 'lec' in activity_kind:\n students_activity = courses[i].exp_stud\n\n elif 'tut' in activity_kind:\n students_activity = courses[i].max_tut\n\n elif 'prac' in activity_kind:\n students_activity = courses[i].max_prac\n\n else:\n print('not found')\n\n # calculate difference between capacity and amount of students\n room_capacity = room.capacity\n malus = 0\n if int(room_capacity) < int(students_activity):\n malus = malus + int(students_activity) - int(room_capacity)\n return malus\n else:\n return malus\n else:\n return 0\n" }, { "alpha_fraction": 0.6592186093330383, "alphanum_fraction": 0.6723307371139526, "avg_line_length": 37.132652282714844, "blob_id": "bb00d4db191232c8853037f8bac34561110ba5ce", "content_id": "f9cc9c649df9213c670c738ae0ea6f1b4f4e0b64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7475, "license_type": "no_license", "max_line_length": 151, "num_lines": 196, "path": "/code/algorithms/algorithm.py", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "import math\nimport copy\nfrom code.constraints.overlap import overlapping\nfrom code.constraints.order import order\nfrom code.constraints.distribution import distribution\nfrom .scorefunction import scorefunction\nfrom .plot import plot_scores\nimport random\n\ndef algorithm(schedule, number_iterations, rooms, courses, overlap_dict, simulated_annealing_true):\n \"\"\"\"\"\n This algorithm runs the non-deterministic algorithms\n\n This function takes as input arguments:\n - the filled in schedule (hard constraints are satisfied, but furthermore not an optimal schedule)\n - the number of iterations requested by the user\n - the roomlist\n - the courselist (classes)\n - the overlapping dictionary\n - boolean for Simulated Annealing or Hillclimber (boolean)\n\n\n This function works as follows:\n - Saves the current score and current schedule\n - It sets the temperature and number of swaps and makes a scoreplotlist\n - It then iterates as many times as the user requests\n\n - The current score of the scorefunction is calculated\n - It picks 2 random activities (by picking a day, a timelock and a roomlock)\n - It makes a copy of the current schedule to store the swap schedule and makes both chosen roomlocks None\n - It checks if swapping the 2 activities satisfies the hard constraints\n\n - If the user instructed simulated annealing:\n - If 1000 times simulated function is called, the temperature drops\n - The simulated annealing function is called to determine if the schedule is swapped\n - The new score is calculated, new_score and schedule are saved if new score is lower than the best old score\n -\n\n - If the user instructed the hillclimber:\n - The hillclimber function determines if the schedule is swapped and the schedule is saved in schedule_save\n \"\"\"\"\"\n\n score_save = scorefunction(schedule, rooms, courses)\n schedule_save = copy.deepcopy(schedule)\n temp_number = 0\n swaps_number = 0\n temp = 20\n score_plot_list = []\n\n for i in range(number_iterations):\n score_current = scorefunction(schedule, rooms, courses)\n daylock1, timelock1, roomlock1 = random_numbers()\n daylock2, timelock2, roomlock2 = random_numbers()\n activity1 = schedule[daylock1][timelock1][roomlock1]\n activity2 = schedule[daylock2][timelock2][roomlock2]\n\n schedule_swap = copy.deepcopy(schedule)\n\n schedule_swap[daylock1][timelock1][roomlock1] = None\n schedule_swap[daylock2][timelock2][roomlock2] = None\n\n if hard_constraints(schedule_swap, overlap_dict, activity1, activity2, daylock1, daylock2, timelock1, timelock2, roomlock1, roomlock2) == True:\n schedule_swap[daylock1][timelock1][roomlock1] = activity2\n schedule_swap[daylock2][timelock2][roomlock2] = activity1\n score_swap = scorefunction(schedule_swap, rooms, courses)\n\n if simulated_annealing_true == True:\n title_plot = 'Simulated Annealing'\n swaps_number += 1\n if swaps_number == 1000:\n temp = temp * 0.75\n swaps_number = 0\n if temp < 1:\n return schedule\n\n schedule = simulated_annealing(schedule, schedule_swap, temp, score_current, score_swap)\n score_now = scorefunction(schedule, rooms, courses)\n\n if score_now < score_save:\n score_save = score_now\n schedule_save = schedule\n\n temp_number =+ 1\n\n score_plot_list.append(scorefunction(schedule, rooms, courses))\n\n\n else:\n title_plot = 'Hillclimber'\n schedule = hillclimber(schedule, schedule_swap, score_current, score_swap)\n schedule_save = schedule\n\n score_plot_list.append(scorefunction(schedule_save, rooms, courses))\n\n plot_scores(score_plot_list, number_iterations, title_plot)\n\n return schedule_save\n\ndef random_numbers():\n \"\"\"\"\n This function returns a random daylock, timelock and roomlock\n\n This function has no input arguments\n\n This function works as follows:\n - A daylock and timelock are randomly chosen\n - Given the timelock the roomlock is 0 or also randomly chosen\n \"\"\"\n\n daylock = random.randint(0, 4)\n timelock = random.randint(0, 4)\n\n if timelock == 4:\n roomlock = 0\n else:\n roomlock = random.randint(0, 6)\n\n return [daylock, timelock, roomlock]\n\ndef hard_constraints(schedule_swap, overlap_dict, activity1, activity2, daylock1, daylock2, timelock1, timelock2, roomlock1, roomlock2):\n \"\"\"\n This function checks if the hard constraint when swapping are satisfied\n\n - First is of the first acitity in the second roomlock checked if there is no overlapping\n - Then the order is checked of the first acitivity\n - Both actions are then also done for the second activity\n - If all the hard constraints are satisfied return True, otherwise return False\n \"\"\"\n\n if overlapping(activity1, schedule_swap[daylock2][timelock2], overlap_dict):\n if order(schedule_swap, activity1, daylock2, timelock2):\n schedule_swap[daylock2][timelock2][roomlock2] = activity1\n if overlapping(activity2, schedule_swap[daylock1][timelock1], overlap_dict):\n if order(schedule_swap, activity2, daylock1, timelock1):\n schedule_swap[daylock1][timelock1][roomlock1] = activity2\n return True\n else:\n return False\n else:\n return False\n else:\n return False\n\ndef simulated_annealing(schedule, schedule_swap, temp, score_current, score_swap):\n\n \"\"\"\"\n Simulated annealing determines if swapped and returns correct schedule\n\n This function takes as input arguments:\n - schedule\n - schedule_swap\n - temperature\n - score_current\n - score_swap\n\n This function works as follows:\n - Of all both scores the e-score is calculated and added to e_score_sum.\n - A float between 0 and 1 is extracted from the uniform distribution (probability)\n - Calculate the probaility of choosing the current schedule (probability current)\n - If probability current is bigger than the probability from the unifrom distribution,\n the activities won't be swapped and current schedule is returned\n - Else, the activities are swapped by returning the swap schedule\n \"\"\"\n e_score_current = math.exp(-score_current / temp)\n e_score_swap = math.exp(-score_swap / temp)\n e_score_sum = e_score_current + e_score_swap\n\n probability = random.uniform(0,1)\n prob_current = e_score_current / e_score_sum\n prob_swap = e_score_swap / e_score_sum\n\n\n if prob_current > probability:\n return schedule\n\n else:\n return schedule_swap\n\ndef hillclimber(schedule, schedule_swap, score_current, score_swap):\n \"\"\"\n This algorithm determines if swapped and returns the correct schedule\n\n This function takes as input arguments:\n - schedule\n - schedule_swap\n - score_current\n - score_swap§\n\n This function works as follows:\n - If the current score is lower, no swap takes place and current schedule is returned\n - Else, the activities are swapped by returning the swap schedule\n \"\"\"\n if score_current < score_swap:\n return schedule\n else:\n return schedule_swap\n" }, { "alpha_fraction": 0.5322003364562988, "alphanum_fraction": 0.5608229041099548, "avg_line_length": 24.409090042114258, "blob_id": "b6d3895982c8301b73b965293217057c62e8b4c3", "content_id": "e42a768d4518b966ba34962b2cf9fd32e9a4b10d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1118, "license_type": "no_license", "max_line_length": 80, "num_lines": 44, "path": "/code/schedule/schedulemaker.py", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "import csv\n\ndef csvconverter(schedule):\n\n \"\"\"\n This function can convert the 3D list into a clear schedule in excel. The\n input is a 3D list based on one week. The schedule shows the courses per day\n and within the days there are 5 timelocks.\n \"\"\"\n\n # add rooms\n headers = [\"C0.110\", \"A1.04\", \"A1.06\", \"A1.08\", \"A1.10\", \"B0.201\", \"C1.112\"]\n\n with open('results/schedule.csv', 'w', newline='') as fp:\n\n a = csv.writer(fp)\n\n # seperate by comma in excel sheet\n a.writerow([\"sep=,\"])\n\n # get data per day\n a.writerow([\"Maandag\"])\n a.writerow(headers)\n a.writerows(schedule[0])\n a.writerow(\"\")\n\n a.writerow([\"Dinsdag\"])\n a.writerow(headers)\n a.writerows(schedule[1])\n a.writerow(\"\")\n\n a.writerow([\"Woensdag\"])\n a.writerow(headers)\n a.writerows(schedule[2])\n a.writerow(\"\")\n\n a.writerow([\"Donderdag\"])\n a.writerow(headers)\n a.writerows(schedule[3])\n a.writerow(\"\")\n\n a.writerow([\"Vrijdag\"])\n a.writerow(headers)\n a.writerows(schedule[4])\n" }, { "alpha_fraction": 0.5725734829902649, "alphanum_fraction": 0.5814781785011292, "avg_line_length": 35.225807189941406, "blob_id": "32a48d7df00ee140ee9b60bff8d53fa39ec8840f", "content_id": "d1e504d2f18819cfe953a6b8f87fcc913fe7239c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1123, "license_type": "no_license", "max_line_length": 85, "num_lines": 31, "path": "/code/algorithms/scorefunction.py", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "from code.constraints.capacity import capacity\nfrom code.constraints.distribution import distribution\n\ndef scorefunction(schedule, rooms, courses):\n \"\"\"\n this scorefunction calculates the malus points for a schedule,\n where the hard constraints are satisfied\n \"\"\"\n\n # check if queue is not empy\n malus = 0\n\n # loop over days\n for i in range(len(schedule)):\n # loop over timlocks in day\n for j in range(len(schedule[i])):\n # loop over roomlocks in timelock\n for k in range(len(schedule[i][j])):\n # only malus points can be calculated if roomlock is not zero\n if schedule[i][j][k] is not None:\n # add maluspoints for not enough capacity in the rooms\n malus = malus + capacity(schedule[i][j][k], rooms[k], courses)\n # 20 malus points are calculated if roomlock is the last (17-19h)\n if j == 4:\n malus = malus + 20;\n else:\n continue\n\n malus = malus + distribution(schedule, courses)\n\n return malus\n" }, { "alpha_fraction": 0.5366984605789185, "alphanum_fraction": 0.5462374091148376, "avg_line_length": 32.69643020629883, "blob_id": "73db8a09cd5009c1c9cdca7ffdc92a3f7fc34fab", "content_id": "9a630adf33f93ac4b7a671e75ab3d5488e8c7b8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7548, "license_type": "no_license", "max_line_length": 100, "num_lines": 224, "path": "/code/constraints/distribution.py", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "from itertools import permutations, repeat\nimport numpy\n\ndef distribution(schedule, courses):\n \"\"\"\n This function calculates the malus points regarding the spread of course\n activities over the week.\n\n This function takes as input arguments:\n - the schedule\n - list of courses\n\n This function works as follows:\n - makes lists with days on which lectures, tutorials and practica\n are given\n - calculates bonus and malus points regarding the best spread\n combinations of tutorials, lectures and practica\n \"\"\"\n malus = 0\n\n # make lists to see on what day the different activities are scheduled\n for i in range(len(courses)):\n name = courses[i].name\n number_activities = courses[i].dif_total\n day_lec_1 = None\n day_lec_2 = None\n day_tut = []\n day_pr = []\n total_days = []\n total_lecs = []\n double_lec = 0\n for i in range(len(schedule)):\n for j in range(len(schedule[i])):\n for k in range(len(schedule[i][j])):\n if schedule[i][j][k] != None:\n course, sort = str(schedule[i][j][k]).split(\"_\")\n if course == name:\n if 'lec' in sort:\n if day_lec_1 == None:\n day_lec_1 = i\n # add to lecture and total list\n total_lecs.append(i)\n total_days.append(i)\n else:\n day_lec_2 = i\n if day_lec_2 != day_lec_1:\n total_lecs.append(i)\n total_days.append(i)\n else:\n double_lec = 1\n elif 'tut' in sort:\n # add to tutorial days list\n day_tut.append(i)\n elif 'pr' in sort:\n # add to practica days list\n day_pr.append(i)\n\n # in case there are both practica and tutorials\n if day_pr and day_tut:\n malus = malus + tut_and_prac(day_tut, day_pr, total_days, number_activities)\n\n # in case there are only tutorials and no practica\n elif day_tut and not day_pr:\n malus = malus + only_tut(day_tut, total_days, total_lecs, double_lec, number_activities)\n\n # in case there are only practica and no tutorials\n elif day_pr and not day_tut:\n malus = malus + only_prac(day_pr, total_days, total_lecs, double_lec, number_activities)\n\n else:\n if double_lec == 1:\n malus = malus + 10\n\n return malus\n\ndef tut_and_prac(tut, prac, total_days, number_activities):\n \"\"\"\n This function calculates bonus and malus points regarding the best spread\n combinations of tutorials, lectures and practica.\n \"\"\"\n\n # set variables and lists\n malus = 0\n comb_doubles = []\n best_comb = []\n combinations = list(list(zip(r, p)) for (r, p) in zip(repeat(tut), permutations(prac)))\n\n # calculate combination list without prac and tut on the same day\n for i in range(len(combinations)):\n double = 0\n for j in range(len(combinations[i])):\n num = str(combinations[i][j])\n num1, num2 = num.split(',')\n num1 = num1.replace('(', '')\n if num1 in num2:\n double = double + 1\n comb_doubles.append(double)\n best = numpy.min(comb_doubles)\n best_index = [i for i,x in enumerate(comb_doubles) if x == best]\n for i in range(len(best_index)):\n ind = best_index[i]\n best_comb.append(combinations[ind])\n\n # for these combinations, calculate the malus points\n tot = []\n points_list = []\n for i in range(len(best_comb)):\n points_tot = 0\n for j in range(len(best_comb[i])):\n tot = []\n tot.extend(total_days)\n tot.extend(best_comb[i][j])\n tot = list(set(tot))\n points_m = spread_malus(number_activities, tot)\n points_b = spread_bonus(number_activities, tot)\n points_tot = points_tot + (points_m + points_b) / len(best_comb[i])\n points_list.append(points_tot)\n\n # choose the option with the smallest amount malus points, and calculate points\n best_points = numpy.min(points_list)\n best_points_index = numpy.argmin(points_list)\n couples = best_comb[best_points_index]\n malus = best_points\n\n return malus\n\ndef only_tut(day_tut, total_days, total_lecs, double_lec, number_activities):\n \"\"\"\n This function calculates bonus and malus points regarding the best spread\n combinations of tutorials and lectures.\n \"\"\"\n\n malus = 0\n double = 0\n\n # if the lectures are on te same day it costs points\n if double_lec == 1:\n malus = malus + 10\n # count malus points\n for i in range(len(day_tut)):\n total_days.append(day_tut[i])\n if day_tut[i] in total_lecs:\n double = double + 1\n double_frac = double / len(day_tut)\n malus = malus + double_frac * 10\n\n # count bonus points for perfectly spread activities\n bonus = 0\n for i in range(len(day_tut)):\n all_days = []\n all_days.extend(total_lecs)\n all_days.append(day_tut[i])\n bonus = bonus + (spread_bonus(number_activities, all_days) / len(day_tut))\n malus = malus + bonus\n\n return malus\n\ndef only_prac(day_pr, total_days, total_lecs, double_lec, number_activities):\n \"\"\"\n This function calculates bonus and malus points regarding the best spread\n combinations of lectures and practica.\n \"\"\"\n\n malus = 0\n double = 0\n\n # if the lectures are on te same day it costs points\n if double_lec == 1:\n malus = malus + 10\n day_pr = list(set(day_pr))\n for i in range(len(day_pr)):\n total_days.append(day_pr[i])\n if day_pr[i] in total_lecs:\n double = double + 1\n double_frac = double / len(day_pr)\n malus = malus + double_frac * 10\n\n # count bonus points for perfectly spread activities\n bonus = 0\n for i in range(len(day_pr)):\n all_days = []\n all_days.extend(total_lecs)\n all_days.append(day_pr[i])\n bonus_this = (spread_bonus(number_activities, all_days) / len(day_pr))\n bonus = bonus + bonus_this\n malus = malus + bonus\n\n return malus\n\ndef spread_malus(number_activities, diff_days):\n \"\"\"\n This function returns malus points if activities are not spread well\n enough.\n \"\"\"\n\n malus = 0\n\n if len(diff_days) == number_activities - 1:\n malus = malus + 10\n elif len(diff_days) == number_activities - 2:\n malus = malus + 20\n elif len(diff_days) == number_activities - 3:\n malus = malus + 30\n\n return malus\n\ndef spread_bonus(number_activities, diff_days):\n \"\"\"\n This function returns bonus points if activities are perfectly spread.\n \"\"\"\n\n malus = 0\n\n if number_activities == 2:\n if diff_days == [0, 3] or diff_days == [1, 4]:\n malus = malus - 20\n if number_activities == 3:\n if diff_days == [0, 2, 4]:\n malus = malus - 20\n if number_activities == 4:\n if diff_days == [0, 1, 3, 4]:\n malus = malus - 20\n\n return malus\n" }, { "alpha_fraction": 0.5709476470947266, "alphanum_fraction": 0.5724625587463379, "avg_line_length": 38.606666564941406, "blob_id": "cbdce8e8b0b4fa5a9d1358a29cba7030584e49b5", "content_id": "506516b239e06376ea4d091dae98fecb44a83952", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5941, "license_type": "no_license", "max_line_length": 123, "num_lines": 150, "path": "/main.py", "repo_name": "12389285/meps", "src_encoding": "UTF-8", "text": "import csv\nimport sys\nimport time\n\nfrom code.classes.room import Room\nfrom code.classes.courses import Courses\nfrom code.algorithms.start_schedule_algorithm import create_start_schedule as sa\nfrom code.classes.schedule import Schedule\nfrom code.schedule.schedulemaker import csvconverter\nfrom code.algorithms.scorefunction_deterministic import scorefunction_deterministic\nfrom code.algorithms.algorithm_deterministic import algorithm as algorithm_deterministic\nfrom code.algorithms.algorithm import algorithm\nfrom code.algorithms.scorefunction_show import scorefunction_show\n\n\nclass Main():\n\n def __init__(self):\n self.rooms = self.open_room(\"data/rooms.csv\")\n self.courses = self.open_courses(\"data/courses.csv\")\n self.overlap = self.open_overlapping(\"data/overlapping.csv\")\n self.sched = Schedule()\n self.schedule = self.sched.create()\n\n def open_room(self, filename):\n \"\"\"\n This function opens all the room from a csv file and returns a list.\n \"\"\"\n with open(filename) as rooms:\n room_reader = csv.DictReader(rooms)\n rooms = []\n for row in room_reader:\n number = row['Roomnumber']\n capacity = row['Max. capacity']\n room = Room(number, capacity)\n rooms.append(room)\n\n return rooms\n\n def open_courses(self, filename):\n \"\"\"\n This function opens all the courses from a csv file and returns a cours\n list. The function also puts the courses order of amount of activities\n in the activity list.\n \"\"\"\n\n with open(filename) as courses:\n course_reader = csv.DictReader(courses)\n course_list = []\n for row in course_reader:\n name = row['\\ufeffCourses Period 4']\n lec = row['#lec']\n tut = row['#tut']\n prac = row['#pr']\n tut_tot = row['#tuttot']\n prac_tot = row['#prtot']\n max_tut = row['#max stud tut']\n max_prac = row['#max stud pr']\n exp_stud = row['E(students)']\n dif_total = int(row['#lec']) + int(row['#tut']) + int(row['#pr'])\n act_tot = int(row['#lec']) + int(row['#tuttot']) + int(row['#prtot'])\n course = Courses(name, lec, tut, prac, tut_tot, prac_tot, max_tut, max_prac, exp_stud, act_tot, dif_total)\n course_list.append(course)\n\n course_list_simulated = []\n\n for i in range(len(course_list)):\n lecs = int(course_list[i].lec)\n course_list_simulated.append(course_list[i].name + '_lec')\n if lecs > 0:\n for j in range(lecs):\n activity = course_list[i].name\n activity = activity + '_lec'\n course_list[i].add(activity)\n tuts = int(course_list[i].tut_tot)\n if tuts > 0:\n course_list_simulated.append(course_list[i].name + '_tut')\n for k in range(tuts):\n activity = course_list[i].name\n activity = activity + '_tut'\n course_list[i].add(activity)\n pracs = int(course_list[i].prac_tot)\n if pracs > 0:\n course_list_simulated.append(course_list[i].name + '_prac')\n for l in range(pracs):\n activity = course_list[i].name\n activity = activity + '_prac'\n course_list[i].add(activity)\n\n\n return course_list\n\n\n def open_overlapping(self, filename):\n\n \"\"\"\n This function opens a csv file with the overlapping of courses and retruns\n a list.\n \"\"\"\n\n with open(filename) as overlap:\n overlap_reader = csv.DictReader(overlap)\n\n\n overlap_dict = {}\n dubbels = []\n\n for row in overlap_reader:\n course = row['0']\n for i in row:\n dubbels.append(row[i])\n overlap_dict[course] = dubbels\n dubbels = []\n\n return overlap_dict\n\n\n\nif __name__ == \"__main__\":\n\n main = Main()\n overlap_dict = main.overlap\n if len(sys.argv) != 3:\n print('Not enough input arguments')\n exit(1)\n algorithm_input = sys.argv[1]\n number_swaps = sys.argv[2]\n start_time = time.time()\n if algorithm_input == 'hillclimber' or algorithm_input == 'simulated_annealing':\n schedule_begin = sa(main.courses, main.schedule, main.rooms, overlap_dict)\n if algorithm_input == 'hillclimber':\n schedule = algorithm(schedule_begin, int(number_swaps), main.rooms, main.courses, overlap_dict, False)\n scorefunction_show(schedule, main.courses, main.rooms, overlap_dict)\n csvconverter(schedule)\n elif algorithm_input == 'simulated_annealing':\n schedule = algorithm(schedule_begin, int(number_swaps), main.rooms, main.courses, overlap_dict, True)\n scorefunction_show(schedule, main.courses, main.rooms, overlap_dict)\n csvconverter(schedule)\n elif algorithm_input == 'simulated_annealing_deterministic':\n schedule = algorithm_deterministic(main.courses, main.schedule, int(number_swaps), main.rooms, overlap_dict, True)\n scorefunction_show(schedule, main.courses, main.rooms, overlap_dict)\n csvconverter(schedule)\n elif algorithm_input == 'hillclimber_deterministic':\n schedule = algorithm_deterministic(main.courses, main.schedule, int(number_swaps), main.rooms, overlap_dict, False)\n csvconverter(schedule)\n scorefunction_show(schedule, main.courses, main.rooms, overlap_dict)\n\n else:\n print('Algorithm does not exist.')\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n" } ]
20
colligant/BOREALIS-BALLOON-PREDICTION
https://github.com/colligant/BOREALIS-BALLOON-PREDICTION
25e22857a86da3255bc52decc8b5679efd2231aa
e27405cd04f28ebf381f75081ba59ba3566934e0
6a2a09e62584dbdedb41b8982900d80b0cb2f453
refs/heads/master
2022-01-08T02:48:08.606405
2019-06-17T19:39:14
2019-06-17T19:39:14
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6267030239105225, "alphanum_fraction": 0.7452316284179688, "avg_line_length": 35.70000076293945, "blob_id": "82377e128719f190788ae5bc31434b9c4e9a87c1", "content_id": "0489125fa3c7d46bbc3d18286e7d14f2a13f2f7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 734, "license_type": "no_license", "max_line_length": 150, "num_lines": 20, "path": "/WRFDriver.py", "repo_name": "colligant/BOREALIS-BALLOON-PREDICTION", "src_encoding": "UTF-8", "text": "import WRFPrediction\nimport Calculations\nimport numpy as np\n\nstart_lat = -30.240776 #decimal degrees (46.8601 for UM Oval)\nstart_lon = -71.085250 #decimal degrees (-113.9852 for UM Oval)\nstart_alt = 1020.0 #m\nmax_alt = 32000.0 #m\n#WRF FILE AND DIRECTORY\nwrf_file = 'wrfout_d02_2017-07-02_17:00:00' # UTC hour required\nmain_directory = '/home/wrf_user/WRF/WRFV3/eclipse_wrf/WRFV3/run/July_2_2017/'\n\n#Predictions\npoints = WRFPrediction.Prediction(wrf_file, main_directory, start_lat, start_lon, start_alt, max_alt)\n\n#Plotting\nCalculations.Plotting(points, 400000, 400000)\n\n#Write file\nnp.savetxt('WRF_test_July_02_2017_2000_Andacollo.txt', points, fmt='%9.8f', delimiter='\\t', header='Latitude\\tLongitude\\tAltitude(m)\\tRise Rate(m/s)')\n" } ]
1
welinro/Hotel-Flask
https://github.com/welinro/Hotel-Flask
5d1a28bb9b55372e2c2f5f92e5978fc02571616f
e30a349f41e936dff779ef806cd3926d0d6de449
6fd98ffb339514c44511b442b09e6c304f878d84
refs/heads/main
2023-08-10T18:27:02.436137
2021-09-13T18:17:03
2021-09-13T18:17:03
403,387,976
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5562615394592285, "alphanum_fraction": 0.5656896829605103, "avg_line_length": 35.66165542602539, "blob_id": "1f38586ee708503b89f7b5b356eeee7b3d201297", "content_id": "f720eac0aa10b26fe1c436c13d7af9b47cffe7f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4880, "license_type": "no_license", "max_line_length": 119, "num_lines": 133, "path": "/resources/hotel.py", "repo_name": "welinro/Hotel-Flask", "src_encoding": "UTF-8", "text": "\n\nfrom flask_restful import Resource, reqparse\nfrom models.hotel import HotelModel\nfrom models.usuario import UserModel\nfrom flask_jwt_extended import jwt_required\nimport sqlite3\n\ndef normalize_path_parms(cidade=None,\n estrelas_min = 0,\n estrelas_max = 5,\n diaria_min = 0,\n diaria_max = 10000,\n limit = 50,\n offset = 0, **dados):\n if cidade:\n return {\n 'cidade':cidade,\n 'estrelas_min':estrelas_min,\n 'estrelas_max':estrelas_max,\n 'diaria_min':diaria_min,\n 'diaria__max':diaria_max,\n 'limit':limit,\n 'offset':offset}\n \n return {\n 'estrelas_min':estrelas_min,\n 'estrelas_max':estrelas_max,\n 'diaria_min':diaria_min,\n 'estrelas_max':diaria_max,\n 'limit':limit,\n 'offset':offset\n }\n\n#path/hoteis?cidade= Rio de Janeiro&estrelas_min=4&diaria_max=400\npath_params = reqparse.RequestParser()\npath_params.add_argument('cidade', type=str)\npath_params.add_argument('estrelas_min', type=float)\npath_params.add_argument('estelas_max', type=float)\npath_params.add_argument('diaria_min', type=float)\npath_params.add_argument('diaria_max', type=float)\npath_params.add_argument('limit', type=float)\npath_params.add_argument('offset', type=float)\n \nclass Hoteis(Resource):\n def get(self):\n connection = sqlite3.connect('banco.db')\n cursor = connection.cursor()\n\n\n\n dados = path_params.parse_args()\n dados_validos = {chave:dados[chave] for chave in dados if [chave] is not None}\n parametros = normalize_path_parms(**dados_validos)\n \n if not parametros.get('cidade'):\n consulta = \"SELECT * FROM hoteis \\\n WHERE (estrelas > ? and estrelas < ?)\\\n and (diaria > ? and diaria < ?) \\\n LIMIT ? OFFSET ?\"\n tupla = tuple([parametros[chave] for chave in parametros])\n resultado = cursor.execute(consulta,tupla)\n else:\n consulta = \"SELECT * FROM hoteis \\\n WHERE (estrelas > ? and estrelas < ?)\\\n and (diaria > ? and diaria < ?) \\\n and cidade = ? LIMIT ? OFFSET ?\"\n tupla = tuple([parametros[chave] for chave in parametros])\n resultado = cursor.execute(consulta,tupla)\n hoteis = []\n for linha in resultado:\n hoteis.append({\n 'hotel_id': linha[0],\n 'nome': linha[1],\n 'estrelas':linha[2],\n 'diaria': linha[3],\n 'cidade': linha[4]\n })\n\n return{'hoteis': hoteis} #SELECT\nclass Hotel (Resource):\n argumentos = reqparse.RequestParser()\n argumentos.add_argument('nome', type= str, required= True, help=\" The field 'nom' cannot be left blank\" )\n argumentos.add_argument('estrelas', type=float, required= True, help =\" The field 'estrelas' cannot be left blank\")\n argumentos.add_argument('diaria', type= float),\n argumentos.add_argument('cidade', type= str)\n \n\n def get (self, hotel_id):\n hotel = HotelModel.find_hotel(hotel_id)\n if hotel:\n return hotel.json()\n \n return {'message':' Hotel not found não encontrado'}, 404 # not found\n \n @jwt_required()\n def post (self, hotel_id):\n if HotelModel.find_hotel(hotel_id):\n return {\"message\": \"Hotel id '{}' already exists.\".format(hotel_id)}, 400# Bad request\n\n dados = Hotel.argumentos.parse_args()\n hotel= HotelModel(hotel_id, **dados)\n try:\n hotel.save_hotel() \n except:\n return {'message', 'An internal error ocurred tryng to save hotel.'}, 500 # internal server error\n return hotel.json()\n\n \n @jwt_required()\n def put (self, hotel_id):\n dados = Hotel.argumentos.parse_args() \n hotel_encontrado = HotelModel.find_hotel(hotel_id)\n if hotel_encontrado:\n hotel_encontrado.update_hotel(**dados)\n hotel_encontrado.save_hotel()\n return hotel_encontrado.json(), 200 \n hotel= HotelModel(hotel_id, **dados)\n try:\n hotel.save_hotel()\n except:\n return {'message', 'An internal error ocurred tryng to save hotel.'}, 500 # internal server error\n return hotel.json(), 201 # created ttt\n \n\n @jwt_required()\n def delete (self, hotel_id):\n hotel = HotelModel.find_hotel(hotel_id)\n if hotel:\n try:\n hotel.delete_hotel()\n except:\n return {'message', 'An error ocurred tryng to delete hotel.'}, 500 # internal server error\n return {'message': ' Hotel deleted'}\n return {\"message\": 'Hotel not found'}, 400\n\n" }, { "alpha_fraction": 0.7269866466522217, "alphanum_fraction": 0.7372148036956787, "avg_line_length": 26.630434036254883, "blob_id": "52268d6f7899bd051950a0498f2aedbe85e2de02", "content_id": "911221bc8bb05bab9c738b89851aedb0d404a7f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1271, "license_type": "no_license", "max_line_length": 78, "num_lines": 46, "path": "/app.py", "repo_name": "welinro/Hotel-Flask", "src_encoding": "UTF-8", "text": "from flask import Flask\nfrom flask_jwt_extended import JWTManager\nfrom flask_restful import Api\n\nfrom blacklist import BLACKLIST\nfrom resources.hotel import Hoteis, Hotel\nfrom resources.usuario import User, UserLogin, UserLogout, UserRegister\nfrom flask import jsonify\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///banco.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS']= False\napp.config['JWT_SECRET_KEY'] = 'Dont TellAnyone'\napp.config['JWT_BLACKLIST_ENABLED'] = True\napi=Api(app)\n\njwt=JWTManager(app)\n\n@app.before_first_request\ndef cria_banco():\n banco.create_all()\n \n@jwt.token_in_blocklist_loader\n\ndef verifica_blacklist(self,token):\n return token['jti'] in BLACKLIST\n\n@jwt.revoked_token_loader\ndef token_de_acesso_invalido(jwt_header, jwt_payload):\n return jsonify({'message':'You have benn logged out'}), 401 # unauthorizad\n\n\n\napi.add_resource(Hoteis,'/hoteis')\napi.add_resource(Hotel,'/hoteis/<string:hotel_id>')\napi.add_resource(User,'/usuarios/<int:user_id>')\napi.add_resource(UserRegister,'/cadastro')\napi.add_resource(UserLogin, '/login')\napi.add_resource(UserLogout, '/logout')\nif __name__ == '__main__':\n from sql_alchemy import banco\n banco.init_app(app)\n app.run(debug=True)\n\n\n\n#http://127.0.0.1:5000/hoteis\n" }, { "alpha_fraction": 0.6312195062637329, "alphanum_fraction": 0.6399999856948853, "avg_line_length": 33.16666793823242, "blob_id": "34c797f9c4acd8eca8de5d30b93e39fab01e3cba", "content_id": "0daad635c97016a8dc7c95ceeb5aff99bd86b8fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2051, "license_type": "no_license", "max_line_length": 95, "num_lines": 60, "path": "/resources/usuario.py", "repo_name": "welinro/Hotel-Flask", "src_encoding": "UTF-8", "text": "from flask_jwt_extended.utils import get_jwt\nfrom flask_restful import Resource, reqparse\nfrom models.usuario import UserModel\nfrom flask_jwt_extended import create_access_token, jwt_required, get_jwt\nfrom werkzeug.security import safe_str_cmp\nfrom blacklist import BLACKLIST\n\natributos = reqparse.RequestParser()\natributos.add_argument('login', type=str, required= True, help=\"The field login be left blank\")\natributos.add_argument('senha', type=str, required= True, help=\"The field senha be left blank\")\n\n\nclass User (Resource):\n\n # /usuarios/{user_id} \n def get (self, user_id):\n user= UserModel.find_user(user_id)\n if user:\n return user.json()\n \n return {'message':' User not found não encontrado'}, 404 # not found\n @jwt_required()\n def delete (self, user_id):\n user = UserModel.find_user(user_id)\n if user:\n user.delete_user()\n return {\"message\": 'Usuario deleted.'}\n return {\"message\": 'User not found.'},400\n\nclass UserRegister(Resource):\n # /cadastro\n def post(self):\n dados= atributos.parse_args()\n\n if UserModel.find_by_login(dados['login']):\n return {\"message\", \" the login '{}' already exists\".format(dados['login'])}\n\n user = UserModel(**dados)\n user.save_user()\n return{\"message\": \"User created sucessfully\"}, 201 # Created\n\nclass UserLogin(Resource):\n\n @classmethod\n def post (cls):\n dados = atributos.parse_args()\n\n user = UserModel.find_by_login(dados['login'])\n\n if user and safe_str_cmp(user.senha, dados['senha']):\n token_de_acesso = create_access_token(identity= user.user_id)\n return{'acess_token': token_de_acesso}, 200\n return {'message': 'The user name or password is incorrect.'}, 401 # Unauthorized\n\nclass UserLogout(Resource):\n @jwt_required()\n def post(self):\n jwt_id = get_jwt()['jti']# JWT Token Identifier\n BLACKLIST.add(jwt_id)\n return {\"message\": 'Logged out sucessfully'}, 200 " }, { "alpha_fraction": 0.6916666626930237, "alphanum_fraction": 0.7250000238418579, "avg_line_length": 38.66666793823242, "blob_id": "f09772421b91bc5fdba298ce71a5bfa2798cfde9", "content_id": "4bd4057e3bd7ec8f34f0e08bd2f742cf9df2ffe4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 120, "license_type": "no_license", "max_line_length": 74, "num_lines": 3, "path": "/readme.md", "repo_name": "welinro/Hotel-Flask", "src_encoding": "UTF-8", "text": "<h1> MY FIRST API </h1>\n<h3> Resource </h3>\nPasta resource virou um modulo o qual para autiliza-lo importo para app.py\n\n" } ]
4
reckfullol/lung-section-classification
https://github.com/reckfullol/lung-section-classification
b9ef08563fb5f3180ea0a07d15fab66219ad7b34
0d450c4c51e87d3ddd148d76f7501be41f27274c
97ea628f85d5507f3a73a6b5fb3ddf216d362001
refs/heads/master
2021-10-01T14:53:52.546523
2018-11-27T03:04:26
2018-11-27T03:04:26
103,720,911
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6659038662910461, "alphanum_fraction": 0.691990852355957, "avg_line_length": 27.763158798217773, "blob_id": "baea53dafd3d1b75bf5eb77386c3225cbdc0d762", "content_id": "68ee712e06d00affdc06e7c0a16d765afd4e266c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2185, "license_type": "no_license", "max_line_length": 138, "num_lines": 76, "path": "/GUI.py", "repo_name": "reckfullol/lung-section-classification", "src_encoding": "UTF-8", "text": "import sys\nfrom PyQt5.QtWidgets import QApplication, QWidget, QPushButton\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtCore import pyqtSlot\nfrom PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog\nfrom PyQt5.QtGui import QIcon\nfrom keras.preprocessing import image\nfrom keras.models import load_model\nimport numpy as np\nimport os\nfrom PIL import Image\nfrom PIL import ImageFont\nfrom PIL import ImageDraw\n\nmodel = load_model('full_model.h5')\n\n\ndef predict(image_path):\n\ttest_image = image.load_img(image_path, target_size=(299, 299))\n\ttest_image = image.img_to_array(test_image)\n\ttest_image = np.expand_dims(test_image, axis=0)\n\ttest_image *= 1. / 255\n\n\tpredict = model.predict(test_image)[0]\n\tpred_class = np.argmax(predict)\n\tlabel = [\"high\", \"low\", \"medium\", \"normal\"]\n\n\tprint('----------------------')\n\tprint(image_path)\n\tprint(\"Class : {0}\".format(label[pred_class]))\n\tprint(\"Confidence rate : {0}%\".format(predict[pred_class] * 100))\n\tprint('\\n\\n\\n')\n\n\timg = Image.open(image_path)\n\tdraw = ImageDraw.Draw(img)\n\t# font = ImageFont.truetype(<font-file>, <font-size>)\n\tfont = ImageFont.truetype(\"arial.ttf\", 16)\n\t# draw.text((x, y),\"Sample Text\",(r,g,b))\n\tdraw.text((0, 0), \"Class : {0}\\nConfidence rate : {1}%\".format(label[pred_class], predict[pred_class] * 100), (255, 255, 255), font=font)\n\timg.show()\n\nclass App(QWidget):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.title = 'PyQt5'\n\t\tself.left = 10\n\t\tself.top = 10\n\t\tself.width = 320\n\t\tself.height = 200\n\t\tself.initUI()\n\n\tdef initUI(self):\n\t\tself.setWindowTitle(self.title)\n\t\tself.setGeometry(self.left, self.top, self.width, self.height)\n\n\t\tbutton = QPushButton('select', self)\n\t\tbutton.setToolTip('This is an example button')\n\t\tbutton.move(100, 70)\n\t\tbutton.clicked.connect(self.on_click)\n\n\t\tself.show()\n\n\t@pyqtSlot()\n\tdef on_click(self):\n\t\toptions = QFileDialog.Options()\n\t\toptions |= QFileDialog.DontUseNativeDialog\n\t\tfileName, _ = QFileDialog.getOpenFileName(self, \"QFileDialog.getOpenFileName()\", \"\",\n\t\t\t\t\"All Files (*);;Python Files (*.py)\", options=options)\n\t\tif fileName:\n\t\t\tpredict(fileName)\n\n\nif __name__ == '__main__':\n\tapp = QApplication(sys.argv)\n\tex = App()\n\tsys.exit(app.exec_())" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.6728838086128235, "avg_line_length": 31.418603897094727, "blob_id": "212bd2abececdbf28f7866f397e13ece627903b2", "content_id": "0b797ff8578ddf3c57ea2e26dc45e11feb6afc1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1394, "license_type": "no_license", "max_line_length": 138, "num_lines": 43, "path": "/predict.py", "repo_name": "reckfullol/lung-section-classification", "src_encoding": "UTF-8", "text": "from keras.preprocessing import image\nfrom keras.models import load_model\nimport numpy as np\nimport os\nfrom PIL import Image\nfrom PIL import ImageFont\nfrom PIL import ImageDraw\n\ndef predict(model, image_path):\n\ttest_image = image.load_img(image_path, target_size=(299, 299))\n\ttest_image = image.img_to_array(test_image)\n\ttest_image = np.expand_dims(test_image, axis=0)\n\ttest_image *= 1. / 255\n\n\tpredict = model.predict(test_image)[0]\n\tpred_class = np.argmax(predict)\n\tlabel = [\"high\", \"low\", \"medium\", \"normal\"]\n\n\tprint('----------------------')\n\tprint(image_path)\n\tprint(\"Class : {0}\".format(label[pred_class]))\n\tprint(\"Confidence rate : {0}%\".format(predict[pred_class] * 100))\n\tprint('\\n\\n\\n')\n\n\timg = Image.open(image_path)\n\tdraw = ImageDraw.Draw(img)\n\t# font = ImageFont.truetype(<font-file>, <font-size>)\n\tfont = ImageFont.truetype(\"arial.ttf\", 16)\n\t# draw.text((x, y),\"Sample Text\",(r,g,b))\n\tdraw.text((0, 0), \"Class : {0}\\nConfidence rate : {1}%\".format(label[pred_class], predict[pred_class] * 100), (255, 255, 255), font=font)\n\timg.show()\n\nif __name__ == '__main__':\n\tmodel = load_model('full_model.h5')\n\tprint(\"Model load\")\n\n\trootdir = \"D:\\\\PycharmProjects\\\\Image_Classifictaion\\\\test\"\n\n\tfor parent, dirnames, filenames in os.walk(rootdir):\n\t\tfor filename in filenames:\n\t\t\tif '.jpg' in filename.lower():\n\t\t\t\timage_path = os.path.join(parent, filename)\n\t\t\t\tpredict(model, image_path)\n" }, { "alpha_fraction": 0.7170271277427673, "alphanum_fraction": 0.7340846657752991, "avg_line_length": 30.266666412353516, "blob_id": "d750586212baebda034276df185a5fc1529cc839", "content_id": "ccdfd19ef46cffaa2cc1df183782daf96ecac150", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3283, "license_type": "no_license", "max_line_length": 103, "num_lines": 105, "path": "/finetune_inceptionv3.py", "repo_name": "reckfullol/lung-section-classification", "src_encoding": "UTF-8", "text": "from keras import applications\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras import optimizers\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dropout, Flatten, Dense, Input\nfrom keras.utils import to_categorical\nfrom keras.models import load_model\nimport numpy as np\n\n\n# path to the model weights files.\nfull_model_weights_path = 'full_model_weight.h5'\nfull_model_path = 'full_model.h5'\n# dimensions of our images.\nimg_width, img_height = 299, 299\n\ntrain_data_dir = './train'\nvalidation_data_dir = './validation'\nnb_train_samples = 512\nnb_validation_samples = 192\nepochs = 200\nbatch_size = 16\n\n\n# build the InceptionV3 network\ninput_tensor = Input(shape=(img_height, img_width, 3))\nbase_model = applications.InceptionV3(weights='imagenet', include_top=False, input_tensor=input_tensor)\nprint('Model loaded.')\n\n# build a classifier model to put on top of the convolutional model\ntop_model = Sequential()\ntop_model.add(Flatten(input_shape=base_model.output_shape[1:]))\ntop_model.add(Dense(256, activation='relu'))\ntop_model.add(Dropout(0.5))\ntop_model.add(Dense(4, activation='softmax'))\n# print top_model.summary()\n# note that it is necessary to start with a fully-trained\n# classifier, including the top classifier,\n# in order to successfully do fine-tuning\n#top_model.load_weights(full_model_weights_path)\n\n# add the model on top of the convolutional base\n#model = Model(inputs=base_model.input, outputs=top_model(base_model.output))\n\n\n#load the full_model.h5 file\n#model.load_weights(full_model_weights_path)\nmodel = load_model(full_model_path)\n\n# set the first 25 layers (up to the last conv block)\n# to non-trainable (weights will not be updated)\n\n#for layer in model.layers[:len(base_model.layers)-5]:\n# layer.trainable = False\n\n# compile the model with a SGD/momentum optimizer\n# and a very slow learning rate.\nmodel.compile(loss='categorical_crossentropy',\n optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),\n metrics=['accuracy'])\n\n# prepare data augmentation configuration\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n fill_mode='nearest')\n\ntest_datagen = ImageDataGenerator(rescale=1. / 255)\n\ntrain_generator = train_datagen.flow_from_directory(\n train_data_dir,\n target_size=(img_height, img_width),\n batch_size=batch_size,\n class_mode='categorical')\n\nvalidation_generator = test_datagen.flow_from_directory(\n validation_data_dir,\n target_size=(img_height, img_width),\n batch_size=batch_size,\n class_mode='categorical')\n\n# fine-tune the model\nmodel.fit_generator(\n train_generator,\n steps_per_epoch=nb_train_samples,\n epochs=epochs,\n validation_data=validation_generator,\n validation_steps=nb_validation_samples)\n# print model.predict_generator(validation_generator, steps=1)\n\nmodel.save_weights(full_model_weights_path)\n\nmodel.save(full_model_path)\n\n#from keras.utils import plot_model\n#plot_model(model, to_file='model.png')\n# from IPython.display import SVG\n# from keras.utils.vis_utils import model_to_dot\n#\n# SVG(model_to_dot(model).create(prog='dot', format='svg'))\n" } ]
3
Arkenan/glpk-graph
https://github.com/Arkenan/glpk-graph
f3ef9c5fdd103e7aab72ccd40721ec04f979aacd
f42bdaf14f375b3ce32e4381a44a01cfa621ca57
c9a3ac367a65949e3e970a3733301ebb6e547ebf
refs/heads/master
2020-12-30T15:08:56.197522
2017-05-12T17:12:18
2017-05-12T17:12:18
91,113,222
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.759036123752594, "alphanum_fraction": 0.7659208178520203, "avg_line_length": 37.733333587646484, "blob_id": "2086ef88260b8ce5b2d1ba1070142762ea74247c", "content_id": "7dd2f5c8b52db2d40a49c6d0a4b210d284a1caa0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 592, "license_type": "no_license", "max_line_length": 196, "num_lines": 15, "path": "/README.md", "repo_name": "Arkenan/glpk-graph", "src_encoding": "UTF-8", "text": "# Graficador de GLPK\n\nRecibe arhcivos con extensión `.mod`, de modelos en 2D, y grafica el poliedro de soluciones factibles, así como las rectas de restricciones. Si el modelo es en 3 dimensiones o más, lanza un error.\n\n## Actualmente en desarrollo\n\n- Parseo de una ecuación con \"X1\" o \"X2\" nombres de variables. Si hay otros nombres debería dar error.\n\n## Features buscadas\n\n- Selección de archivo de input por línea de comandos.\n- Parseo de archivos de modelos. Una restricción por línea.\n- Detección de variables. Regex?\n- Generación de un modelo de restricciones.\n- Graficado.\n" }, { "alpha_fraction": 0.5380645394325256, "alphanum_fraction": 0.5458064675331116, "avg_line_length": 25.724138259887695, "blob_id": "752d33e522a00a3924be9bf5b9cf7cf0fdcaaad3", "content_id": "e0379fc88e53461abb14f7ed7f33b36840d11538", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 784, "license_type": "no_license", "max_line_length": 68, "num_lines": 29, "path": "/main.py", "repo_name": "Arkenan/glpk-graph", "src_encoding": "UTF-8", "text": "import sys\n\ninputfile = open(\"ej.mod\")\n\nfor linea in inputfile:\n # print (\"linea: \"+ linea)\n # Separo a ambos lados de la restricción.\n # Busco si es <=, >=, =.\n punto = linea.find(\"=\")\n # Chequeo que sea uno solo.\n punto2 = linea.find(\"=\", punto+1)\n\n if punto2 != -1:\n print (\"Error, más de una restricción en la línea \" + linea)\n continue\n # sys.exit()\n\n if punto == -1:\n print (\"Error, no hay restricción en la línea \" + linea)\n continue\n # sys.exit()\n\n c = linea[punto -1]\n if c == \"<\":\n print (\"La restricción es de menor o igual \" + linea)\n elif c == \">\":\n print (\"La restricción es de mayor o igual \" + linea)\n else:\n print (\"La restricción es una igualdad. \" + linea)\n" } ]
2
Kion-Smith/CS3377
https://github.com/Kion-Smith/CS3377
47b5ba0b70a644bb4b831e76695756d95b0933df
aa150a225c896db6a03f25cc04b2a2128c8a5297
686f884a6b1be24ac8f89ef1ad29d1a379cbb645
refs/heads/master
2021-05-13T19:50:12.217265
2018-04-30T02:53:09
2018-04-30T02:53:09
116,901,388
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5944700241088867, "alphanum_fraction": 0.5944700241088867, "avg_line_length": 13.466666221618652, "blob_id": "f2062872099326524f0478397f144b7349f09ae3", "content_id": "8c693fa4566abb404c51fb1c32215d0d2b33d37d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 217, "license_type": "no_license", "max_line_length": 28, "num_lines": 15, "path": "/Bash Scripts/HW 7/switch.sh", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\necho \"Do you like art?\" \necho \"Enter yes or no ::\" \nread userInput\ncase \"$userInput\" in\n\ty|Y|yes|Yes|YES)\n\t\techo \"Agreed\"\n\t\t;;\n\tn|N|no|No|NO)\n\t\techo \"Disagreed\"\n\t\t;;\n\t*)\n\t\techo \"Invalid input\"\n\t\t;;\nesac\n" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.6650000214576721, "avg_line_length": 17.18181800842285, "blob_id": "71c69861eede7c39f5713fbb1b9786fd636b37c0", "content_id": "e46285759d37bde17213271ecf8bba0350fffa81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 200, "license_type": "no_license", "max_line_length": 35, "num_lines": 11, "path": "/Bash Scripts/anotherRandom", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\nfirstNum=$(shuf -i 0-10 -n 1)\nsecondNum=$(shuf -i 0-10 -n 1)\necho $firstNum\necho $secondNum\nif [ \"$firstNum\" -eq \"$secondNum\" ]\nthen\necho \"Match found\"\nelse\necho \"Diff Nums\"\nfi #end of if\n" }, { "alpha_fraction": 0.5435356497764587, "alphanum_fraction": 0.6187335252761841, "avg_line_length": 17.487804412841797, "blob_id": "f7debf9ce1ed664f1c1bdb14a851502cf67d4831", "content_id": "fe272ba79a7a878fc9d20d79ff031bf9d0f9b014", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 758, "license_type": "no_license", "max_line_length": 51, "num_lines": 41, "path": "/Bash Scripts/TestReview", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nfunction first1()\n{\n\tnum1=-10\n\tnum2=10\n\trand1=$[RANDOM%(num2-num1+1)+num1]\n\trand2=$[RANDOM%(num2-num1+1)+num1]\n\tavg=$[($rand1+$rand2)/2]\n\techo \"The first number is $rand1\"\n\techo The second number is \"$rand2\"\n\techo \"The avg is\" $avg\n}\nfirst2()\n{\n\tnum1=-10\n\tnum2=10\n\trand1=$[RANDOM%(num2-num1+1)+num1]\n\techo Enter a number between -10 and 10\n\tread rand2\t\n\tif [ \"$rand2\" -ge 11 ] || [ \"$rand2\" -le -11 ] \n\tthen\n\techo \"Not in the bound\"\n\telif [ \"$rand1\" -le -1 ] && [ \"$rand2\" -le -1 ] \n\tthen\n\techo \"Your numbers are the same sign\"\n\telif [ \"$rand1\" -ge 0 ] && [ \"$rand2\" -ge 0 ] \n\tthen\n\techo \"Your numbers are the same sign\"\n\telse\n\t\techo \"Numbers are not the same sign\"\n\tfi\n\n\techo \"Random $rand1\"\t\n\techo \"Your number $rand2\"\n\t\n}\n\n\nfirst1\nfirst2\n" }, { "alpha_fraction": 0.6490066051483154, "alphanum_fraction": 0.6762325167655945, "avg_line_length": 19.238805770874023, "blob_id": "02fd87d4adb00304380305d3d26fa87a51c0670d", "content_id": "21a0e50fe116112e467a96d5b8cbc99fb310fabb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1359, "license_type": "no_license", "max_line_length": 71, "num_lines": 67, "path": "/Bash Scripts/HW8.sh", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#Kion Smith\n#kls160430\t\n#CS 3377.0W3\n\n#Global variables\nrandom=$[RANDOM%129+0] #the random number\nnumOfGuess=0 #number of guesses\n\n#The main loop used for checking guess\nuserInput() \n{\n\t#Get user input\n\techo \"Enter a number from 0 - 128\"\n\tread userInput\n\n\t#Makes sure user input is between 0 and 128\n\tif [ \"$userInput\" -gt 128 ] || [ \"$userInput\" -le -1 ];then\n\t{\n\t\techo This is num is not within the range\n\t\tuserInput\n\t}\n\tfi\n\t\n\t#check to see if user input is higher,lower or equal to the random num\n\tif [ \"$userInput\" -eq \"$random\" ];then\n\t{\n\t\t#increment by 1\n\t\tnumofGuess=$[numofGuess+1]\n\t\techo \"You guessed correctly in $numofGuess number of guesses\"\n\t\thighScore #go to end of script\n\t\t\n\t}\n\telif [ \"$userInput\" -gt \"$random\" ];then\n\t{\n\t\t#increment by 1\n\t\tnumofGuess=$[numofGuess+1]\n\t\techo High guess\n\t\tuserInput #loop\n\t}\n\telif [ \"$userInput\" -le \"$random\" ];then\n\t{\n\t\t#increment by 1\n\t\tnumofGuess=$[numofGuess+1]\n\t\techo Low guess\n\t\tuserInput #loop back \n\t\t\n\t}\n\tfi\n}\n#end of script function to get highscores\nhighScore()\n{\n\t#get user name to place in file\n\techo What is your name?\n\tread userName\n\n\t#store name and number of guess\n\techo \"$userName $numofGuess\" >> highscores.txt\n\techo\n\techo HighScores\n\techo ----------------------\n\t#sort file by the second col and by numbers\n\tsort -k 2 -n highscores.txt | head -3\n}\n#start the program\nuserInput\n\n\n\n" }, { "alpha_fraction": 0.6311110854148865, "alphanum_fraction": 0.6822222471237183, "avg_line_length": 17, "blob_id": "2582952caa29d84d00832400895a9e057bff8f17", "content_id": "ed2bcb78e49de917e13cef0fd1c7b6b4ef92c412", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 450, "license_type": "no_license", "max_line_length": 44, "num_lines": 25, "path": "/Bash Scripts/HW 7/compare.sh", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\necho \"Enter the 1st word\"\nread word1\necho \"now the 2nd word\"\nread word2\necho \"finally the 3rd word\"\nread word3\n\nif [ $word1 == $word2 ] \nthen\nif [ $word1 == $word3 ] \nthen\necho \"1st, 2nd, and 3rd words all are equal\"\nelse\necho \"1st word is equal to the 2nd\"\nfi\nelif [ $word1 == $word3 ]\nthen\necho \"1st word is equal to the 3rd\"\nelif [ $word2 == $word3 ]\nthen\necho \"2nd word is equal to the 3rd\"\nelse\necho \"None of the words are equal\"\nfi\n" }, { "alpha_fraction": 0.5906432867050171, "alphanum_fraction": 0.6140350699424744, "avg_line_length": 19.520000457763672, "blob_id": "eaddefff99bd72be73227e7645d46d3365eb393c", "content_id": "97336d69d50c078b9006bd278b77b199d60e2bb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 513, "license_type": "no_license", "max_line_length": 43, "num_lines": 25, "path": "/Bash Scripts/HW6Part1", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#Kion Smith\n#kls160430\n#CS3377.0W3\n\necho \"Part A\"\necho \"------------\"\n#Look for john in file\ngrep John testFile\necho \"------------\"\necho \"Part B\"\n#Look for words starting with capital J\ngrep '^\\J' testFile\necho \"------------\"\necho \"Part C\"\n#Look for words ending in stopped\ngrep \"stopped$\" testFile\necho \"------------\"\necho \"Part D\"\n#look for any other line than ones with was\ngrep -v \"was\" testFile\necho \"------------\"\necho \"Part E\"\n#look for capital k or lower case k (regex)\ngrep -E '^(K|k)' testFile\n" }, { "alpha_fraction": 0.664893627166748, "alphanum_fraction": 0.6968085169792175, "avg_line_length": 16.090909957885742, "blob_id": "90204eae80eafff6372655801aa8fc74bf2f33ea", "content_id": "29ed46f30cc45cb523680b3bbd5b9a51cf094351", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 188, "license_type": "no_license", "max_line_length": 35, "num_lines": 11, "path": "/Bash Scripts/Random", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\nfirstNum=$[RANDOM%10+1]\nsecondNum=$[RANDOM%10+1]\necho $firstNum\necho $secondNum\nif [ \"$firstNum\" -eq \"$secondNum\" ]\nthen\necho \"Match found\"\nelse\necho \"Diff Nums\"\nfi #end of if\n" }, { "alpha_fraction": 0.6016260385513306, "alphanum_fraction": 0.6260162591934204, "avg_line_length": 18.5, "blob_id": "1b71473ef1461ea07d12b29513b8d9823ecf606d", "content_id": "e2fc8973ed5307b1941eaff49cdd10eaf82eef2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 123, "license_type": "no_license", "max_line_length": 35, "num_lines": 6, "path": "/Python/FirstPythonScript.py", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "print(3+4)\r\nprint(3)\r\nprint(\"First Python program!\")\r\nname = \"Kion Smith\"\r\nprint('name')\r\nprint(\"Welcome to python\",name,\"!\")\r\n" }, { "alpha_fraction": 0.6476190686225891, "alphanum_fraction": 0.6704761981964111, "avg_line_length": 17.64285659790039, "blob_id": "f0c048bfbf4869923a4c33fbfbb604efe93c07dc", "content_id": "4c1835625c289fdaa164c900d2e5e868ddff9d24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 525, "license_type": "no_license", "max_line_length": 61, "num_lines": 28, "path": "/Bash Scripts/HW 7/CheckRandom.sh", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#check it input is same as cpu's random\nfunction checkInput()\n{\nif [ \"$userNum\" -ge 11 ] || [ \"$userNum\" -le 0 ]\nthen\necho \"enter a nnumber form 1-10\"\nelif [ \"$userNum\" -eq \"$cpuNum\" ]\nthen\necho \"You and the computer generated the same number\" $cpuNum\nelse\necho \"Computer generated\" $cpuNum\", and you guessed\" $userNum\nfi\n}\n\n#get user input\nif [ \"$#\" -eq 0 ]\nthen\necho \"No args\"\nelif [ \"$#\" -gt 1 ]\nthen\necho \"Too many args\"\nelse\n#store inputs for the function\nuserNum=\"$1\"\ncpuNum=$[RANDOM%10+1]\ncheckInput\nfi\n\n\n\n" }, { "alpha_fraction": 0.5403422713279724, "alphanum_fraction": 0.616136908531189, "avg_line_length": 14.148148536682129, "blob_id": "f7e50184c764679090889295041b2e3743eaa29c", "content_id": "e3c04ba1b4b6fe17fd5c786b1fe95a316685cf21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 409, "license_type": "no_license", "max_line_length": 60, "num_lines": 27, "path": "/Homework in C/HW1Part1.c", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "/* Kion Smith\n* kls160430\n* CS 3377.0W3\n*/\n\n#include <stdio.h>\n\n//using defines to set the limits of the bounds\n#define UPPER 400\n#define LOWER 100\n\nint main(void)\n{\n\t//Initilize a\n\tint i;\n\t\n\t//Print F and space for C\n\tprintf(\"F\\t C\\n\");\n\n\t//Loop from 100 to 400 \n\tfor(int i=LOWER;i<=UPPER;i++)\n\t{\n\t\t//Print out the current number in F and converting it to C\n\t\tprintf(\"%d \\t %.2f \\n\",i,(5.0/9.0)*(i-32));\n\t}\n\n}\n" }, { "alpha_fraction": 0.375, "alphanum_fraction": 0.4000000059604645, "avg_line_length": 19, "blob_id": "fbd081ba2d892a8ca2cd393ab404880360c1b83a", "content_id": "7d7e039b218f8e31c013ee49b0052b8f42e9d76c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 40, "license_type": "no_license", "max_line_length": 27, "num_lines": 2, "path": "/Bash Scripts/Example2.sh", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\nls -d */ | cut -d '/' -f -1\n" }, { "alpha_fraction": 0.6919831037521362, "alphanum_fraction": 0.7426160573959351, "avg_line_length": 20.454545974731445, "blob_id": "693515ab299642df17a31d679a7201ff8b10c87f", "content_id": "0c16147bed337ef7f1e83846c766cdd814466625", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 237, "license_type": "no_license", "max_line_length": 43, "num_lines": 11, "path": "/Bash Scripts/HW6Part2", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#Kion Smith\n#kls160430\n#CS3377.0W3\n#copy current directory to coppied\necho \"Creating sub directory called Copied\"\nrsync -Rr ./ ./Copied\n#remove the copy\necho \"Now deleting the sub directory\"\nrm -rf ./Copied\necho \"Task Complete\"\n\n" }, { "alpha_fraction": 0.604651153087616, "alphanum_fraction": 0.6348837018013, "avg_line_length": 20.5, "blob_id": "890b9ca13527ce57c34a3dd7e4ace6c65f81dcfb", "content_id": "9718ffdf08bb9a80f75c5713d8f9e0ac3dd41578", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 430, "license_type": "no_license", "max_line_length": 60, "num_lines": 20, "path": "/Bash Scripts/HW6Part3", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#! /bin/bash\n#Kion Smith\n#kls160430\n#CS3377.0W3\n#get user input\necho \"Enter 2 numbers and I will out put basic calculations\"\necho \"Enter the first number\"\nread x\necho \"Enter the next number\"\nread y\n#Do the calculations\naddTotal=$(($x + $y))\nsubTotal=$(($x - $y))\nmultTotal=$(($x * $y))\ndivTotal=$(($x / $y))\n#outprint totals\necho \"$x + $y = $addTotal\"\necho \"$x - $y = $subTotal\"\necho \"$x * $y = $multTotal\"\necho \"$x / $y = $divTotal\"\n" }, { "alpha_fraction": 0.7283464670181274, "alphanum_fraction": 0.751968502998352, "avg_line_length": 24.100000381469727, "blob_id": "444d81bd5187f76d0ae8a3f40d77da98c02b1a06", "content_id": "3a837961383a58d92b5f89efb2dcf234c3b84a65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 254, "license_type": "no_license", "max_line_length": 76, "num_lines": 10, "path": "/Bash Scripts/randomUserInput2.sh", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\necho Enter 2 numbers and I will generate a random number within those bounds\necho Enter the lower bound\nread num1\necho Enter the upper bound\nread num2\n\nrandom=$(shuf -i $num1-$num2 -n 1)\n\necho \"Random number generated $random using shuf\"\n\n\n\n" }, { "alpha_fraction": 0.6563706398010254, "alphanum_fraction": 0.6718146800994873, "avg_line_length": 11.949999809265137, "blob_id": "6bda25ca22cd895899c5ea79db7b5fb5e34b2a6c", "content_id": "6ea23756d6cdceef4f9c6d9bf028c42a9992843d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 259, "license_type": "no_license", "max_line_length": 39, "num_lines": 20, "path": "/Bash Scripts/HW 7/isNormal.sh", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nfunction checkForFile()\n{\nif [ -f \"$filepath\" ]\nthen\necho $filename\" is a ordinary file\"\nelse\necho $filename\" is not a ordinary file\"\nfi\n}\n\nif [ \"$#\" -le 0 ]\nthen\necho \"Need at least 1 argument\"\nelse\nfilename=\"$1\"\nfilepath=\"./$1\"\ncheckForFile\nfi\n" }, { "alpha_fraction": 0.7335907220840454, "alphanum_fraction": 0.760617733001709, "avg_line_length": 24.600000381469727, "blob_id": "06ef8ea73d72de99fff9f7958f23c55ab5c4bac8", "content_id": "828a165757281c38cbe41a64532fa3c1235e3675", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 259, "license_type": "no_license", "max_line_length": 76, "num_lines": 10, "path": "/Bash Scripts/randomUserInput1.sh", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\necho Enter 2 numbers and I will generate a random number within those bounds\necho Enter the lower bound\nread num1\necho Enter the upper bound\nread num2\n\nrandom=$[ RANDOM % (num2-num1+1)+num1]\n\necho \"Random number generated $random using RANDOM\"\n\n\n\n" }, { "alpha_fraction": 0.7472527623176575, "alphanum_fraction": 0.7472527623176575, "avg_line_length": 17.200000762939453, "blob_id": "682334bed473bac3e80297b2cb17e6dd5fc6175d", "content_id": "7c844917bdc2d9dc19dfda0ff14a1b2fbd292a96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 91, "license_type": "no_license", "max_line_length": 42, "num_lines": 5, "path": "/Bash Scripts/whoson", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\necho \"This is a Bourne Again Shell Script\"\ndate\necho \"Currently Logged In\"\nwho\n" }, { "alpha_fraction": 0.587420642375946, "alphanum_fraction": 0.609347939491272, "avg_line_length": 12.7380952835083, "blob_id": "afb894fcf7c76474703a90552770a8c3c3229455", "content_id": "da3c7265b18c21897d1567f5d803b8a4960f7edb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1733, "license_type": "no_license", "max_line_length": 57, "num_lines": 126, "path": "/Bash Scripts/BashReview2", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\nmin=-23\nmax=31\ndeclare -a randArray \nmaxNum=-24\nmaxCount=0\ncurNum=0\ncurCount=0\nposNum=0\nnegNum=0\nmaxNum=0\nminNum=0\navg=0\nsumNum=0\nsumOfSq=0\nfunction getAvg()\n{\n\tavg=$[sumNum/50]\n}\n\nfunction getMode()\n{\n\tcount=-23\t\n\twhile [ \"$count\" -le 31 ]\n\tdo\n\t\tmaxCount=0\n\t\tcurNum=$count\n\t\tcurCount=0\n\t\tfor i in ${randArray[@]} \n\t\tdo \n\t\t\tif [ \"$i\" -eq \"$maxNum\" ]\n\t\t\tthen\n\t\t\tmaxCount=$[maxCount+1]\n\t\t\tfi\n\n\t\t\tif [ \"$i\" -eq \"$curNum\" ]\n\t\t\tthen\n\t\t\tcurCount=$[curCount+1]\n\t\t\tfi\n\n\n\t\tdone\n\n\t\tif [ \"$curCount\" -ge \"$maxCount\" ]\n\t\tthen\n\t\tmaxNum=$curNum\n\t\tmaxCount=$curCount\n\t\tfi\n\t\tcount=$[count+1]\n\tdone\n\n\techo \"---Occured the most $maxNum\"\n}\n\nfunction sumOfSquares()\n{\n\t#Outprints the array\n\tfor i in ${randArray[@]} \n\tdo \n\t\ttemp=$[i*i]\n\t\tsumOfSq=$[sumOfSq+temp]\n\tdone\n\techo \"Sum of sqaures$sumOfSq\"\n}\n\ncount=1\n\n\nwhile [ \"$count\" -le 50 ]\ndo\n\trand=$[RANDOM%(max-min+1)+min]\n\trandArray[$count]=$rand\n\tif [ \"$rand\" -le -1 ]\n\tthen\n\t\tposNum=$[posNum+1]\n\telse\n\t\tnegNum=$[negNum+1]\n\tfi\n\t\n\tif [ \"$rand\" -ge \"$maxNum\" ]\n\tthen\n\t\tmaxNum=$rand\n\tfi\n\n\tif [ \"$rand\" -le \"$minNum\" ]\n\tthen\n\t\tminNum=$rand\n\tfi\n\n\techo \"$rand\" \n\tsumNum=$[sumNum+rand]\n\tcount=$[count+1]\ndone\n \nfunction print()\n{\n\tgetAvg\n\tgetMode\n\tsumOfSquares\n\techo \"Avg = $avg Mode $maxNum Sum = $sumOfSq\"\n}\n\n\n\n#Outprints the array\n#for i in ${randArray[@]} \n#do \n\t#echo $i; \n#done\n\necho \"Number of P $posNum and N: $negNum\"\necho \"max num is $maxNum min num is $minNum\"\necho $sumNum\n#avg=$[sumNum/100]\n\necho $avg\n\n\necho \"Max = $maxNum\" >> \"repotsbash.txt\"\necho \"Min = $minNum\" >> \"repotsbash.txt\"\necho \"Postive = $posNum\" >> \"repotsbash.txt\"\necho \"Negative = $negNum\" >> \"repotsbash.txt\"\necho \"avg = $avg\" >> \"repotsbash.txt\"\necho \"------------------------------\" >> \"repotsbash.txt\"\n\nprint\n\n\n" }, { "alpha_fraction": 0.4588235318660736, "alphanum_fraction": 0.47058823704719543, "avg_line_length": 9.625, "blob_id": "a9e9898f5684480485a5fedb0b7946c76f4b49f0", "content_id": "32adb41c11a3eaf44be2d09947745ff8c3e47398", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 85, "license_type": "no_license", "max_line_length": 28, "num_lines": 8, "path": "/Bash Scripts/HW 7/isDir.sh", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\nfor f in */\ndo\nif [[ -d $f ]] \nthen\necho \"$f\" | cut -d '/' -f -1\nfi\ndone\n" }, { "alpha_fraction": 0.560606062412262, "alphanum_fraction": 0.6060606241226196, "avg_line_length": 14.29411792755127, "blob_id": "b937c7bd54159e06aaa415cd2a04266997290584", "content_id": "15ff941b520d2a4f097bfaa35641d0df80d6f771", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 264, "license_type": "no_license", "max_line_length": 87, "num_lines": 17, "path": "/Homework in C/HW1Part2.c", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "/* Kion Smith\n* kls160430\n* CS 3377.0W3\n*/\n\n#include <stdio.h>\n\nint main(void)\n{\n\n\tint c;//current char\n\twhile ((c = getchar()) != EOF)// while char is not end of file\n\tputchar(c);// place char to conolse or file(specified as ./a.out < file > other file)\n\t\n\n\n}\n\n\n\n\n" }, { "alpha_fraction": 0.6796537041664124, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 20, "blob_id": "30e46eef58c45b6ae6364fa5d351d3262cc84cb5", "content_id": "5eadb7e85c176a49ab1a5117642d987fa9842ead", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 231, "license_type": "no_license", "max_line_length": 51, "num_lines": 11, "path": "/Bash Scripts/HW 7/untilLoop.sh", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\necho \"Enter a file name to out put the random nums\"\nread filename\ncount=1\nuntil [ \"$count\" -ge 100 ]\ndo\nrandomNum=$[RANDOM%100]\necho \"$randomNum\" >> $filename\ncount=$[count+1]\ndone\necho \"Finished printing to\" $filename\n" }, { "alpha_fraction": 0.5840517282485962, "alphanum_fraction": 0.607758641242981, "avg_line_length": 15.245614051818848, "blob_id": "545d70e7c19b77d745927211272fe3c7f7c52d07", "content_id": "dc879af52a4ab35256a6493ed94fd4c0762dd822", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 928, "license_type": "no_license", "max_line_length": 57, "num_lines": 57, "path": "/Bash Scripts/bashReview", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\nmin=-25\nmax=25\ndeclare -a randArray \n\nposNum=0\nnegNum=0\nmaxNum=0\nminNum=0\navg=0\nsumNum=0\n\ncount=1\nwhile [ \"$count\" -le 100 ]\ndo\n\trand=$[RANDOM%(max-min+1)+min]\n\trandArray[$count]=$rand\n\tif [ \"$rand\" -le -1 ]\n\tthen\n\t\tposNum=$[posNum+1]\n\telse\n\t\tnegNum=$[negNum+1]\n\tfi\n\t\n\tif [ \"$rand\" -ge \"$maxNum\" ]\n\tthen\n\t\tmaxNum=$rand\n\tfi\n\n\tif [ \"$rand\" -le \"$minNum\" ]\n\tthen\n\t\tminNum=$rand\n\tfi\n\n\techo \"$rand\" \n\tsumNum=$[sumNum+rand]\n\tcount=$[count+1]\ndone\n \n#Outprints the array\n#for i in ${randArray[@]} \n#do \n\t#echo $i; \n#done\n\necho \"Number of P $posNum and N: $negNum\"\necho \"max num is $maxNum min num is $minNum\"\necho $sumNum\navg=$[sumNum/100]\necho $avg\n\necho \"Max = $maxNum\" >> \"repotsbash.txt\"\necho \"Min = $minNum\" >> \"repotsbash.txt\"\necho \"Postive = $posNum\" >> \"repotsbash.txt\"\necho \"Negative = $negNum\" >> \"repotsbash.txt\"\necho \"avg = $avg\" >> \"repotsbash.txt\"\necho \"------------------------------\" >> \"repotsbash.txt\"\n\n\n" }, { "alpha_fraction": 0.5617391467094421, "alphanum_fraction": 0.573913037776947, "avg_line_length": 21, "blob_id": "be418800b29206d50e4f416c4eaef8bc7e365c79", "content_id": "8c628eed49353033d165cba76dbac90b116e135b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1725, "license_type": "no_license", "max_line_length": 91, "num_lines": 75, "path": "/Python/pythonReview.py", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#Kion Smith\r\n#REVIEW FOR FINAL\r\nimport random\r\n#Global Variables\r\nrandArray = []\r\nposNum = int(0)\r\nnegNum = int(0)\r\nminNum = int()\r\nmaxNum = int()\r\nsumOfNums = int()\r\n\r\n#function to create random num\r\ndef createNumber(min,max):\r\n return( (random.randint(min,max)) )\r\n\r\n#get the sign of a number\r\ndef countSigns(num):\r\n if num>-1:\r\n global posNum\r\n posNum += 1\r\n else:\r\n global negNum\r\n negNum += 1\r\n#looking for min an max \r\n#could also just search array for min and max, would be better to just check during running\r\ndef getMin(cur):\r\n global minNum\r\n if cur<minNum:\r\n minNum = cur\r\ndef getMax(cur):\r\n global maxNum\r\n if cur>maxNum:\r\n maxNum = cur\r\n \r\n#opening reports and writing everything to a file \r\ndef fileWrite(aoo):\r\n f = open(\"Reports.txt\",\"a\")\r\n f.write(\"Postives = \")\r\n f.write(str(posNum)) #converts to a string (need to do this)\r\n f.write(\"\\n\")\r\n f.write(\"Negatives = \")\r\n f.write(str(negNum))\r\n f.write(\"\\n\")\r\n f.write(\"Min = \")\r\n f.write(str(minNum))\r\n f.write(\"\\n\")\r\n f.write(\"Max = \")\r\n f.write(str(maxNum))\r\n f.write(\"\\n\")\r\n f.write(\"Avg = \")\r\n f.write(str(avg))\r\n f.write(\"\\n\")\r\n f.write(\"------------------------ \\n\")\r\n f.close()\r\n \r\n#main loop \r\ncount = 1;\r\n#loop for 1-100\r\nwhile count<=100:\r\n curNum = createNumber(-25,25)\r\n countSigns(curNum)\r\n randArray.append(curNum)\r\n getMin(curNum)\r\n getMax(curNum)\r\n sumOfNums += curNum\r\n print (\"out prints::\",curNum)\r\n count +=1;\r\n\r\navg = int(sumOfNums/100)\r\n\r\nprint(\"Postive\",posNum,\"Negatives\",negNum)\r\nprint(\"Min\",minNum,\"Max\",maxNum)\r\nprint(\"Sum\",sumOfNums)\r\nprint(\"Avg\",avg)\r\nfileWrite(avg)\r\n" }, { "alpha_fraction": 0.6796537041664124, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 20, "blob_id": "7cf6a456c9bd7527f1b7b5fd54cfc700f27dbda0", "content_id": "ed38543c3802cf9675837111089a2d87005db890", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 231, "license_type": "no_license", "max_line_length": 51, "num_lines": 11, "path": "/Bash Scripts/HW 7/whileLoop.sh", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\necho \"Enter a file name to out put the random nums\"\nread filename\ncount=1\nwhile [ \"$count\" -le 100 ]\ndo\nrandomNum=$[RANDOM%100]\necho \"$randomNum\" >> $filename\ncount=$[count+1]\ndone\necho \"Finished printing to\" $filename\n" }, { "alpha_fraction": 0.6631016135215759, "alphanum_fraction": 0.6844919919967651, "avg_line_length": 12.285714149475098, "blob_id": "c926be52a08ee1b0b4110b5420aead432baa357e", "content_id": "89ee6f7cb7f6833579f3c283ec0dec52bd732da5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 187, "license_type": "no_license", "max_line_length": 39, "num_lines": 14, "path": "/Bash Scripts/example.sh", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#Start of shell script\necho \"Enter a number and I will add 10\"\nread num\n\n#This is a shell function\nfunction addNum()\n{\n\tnum=$(($num +10))\n\techo $num\n}\n\n#Function call\naddNum\n\n" }, { "alpha_fraction": 0.6225789785385132, "alphanum_fraction": 0.6490825414657593, "avg_line_length": 16.171052932739258, "blob_id": "b513ac31a2f921467d14f64d6d9d50703b032566", "content_id": "13909fb8b9a46305dd56644d12ea67534419069f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3924, "license_type": "no_license", "max_line_length": 63, "num_lines": 228, "path": "/Bash Scripts/HW 7/HW7Combined.sh", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n#Kion Smith\n#kls160430\n#CS 3377.0W3\n\n#First Script to generate a random number\nrandom()\n{\t#save and genertate 2 random nums\n\tfirstNum=$[RANDOM%10+1]\n\tsecondNum=$[RANDOM%10+1]\n\t#out print then numbers\n\techo $firstNum\n\techo $secondNum\n\t#Check to see if they are equal or not\n\tif [ \"$firstNum\" -eq \"$secondNum\" ]\n\tthen\n\techo \"Match found\"\n\telse\n\techo \"Different Numbers\"\n\tfi \n}\n\n#User use an arg to check agaisnt the computers random num\nuserRandom()\n{\n\tfunction checkInput()\n\t{\n\t\t#check to see if user num is in between range 1-10\n\t\tif [ \"$userNum\" -ge 11 ] || [ \"$userNum\" -le 0 ]\n\t\tthen\n\t\techo \"enter a number from 1-10\"\n\t\t#check to see if they are equal\n\t\telif [ \"$userNum\" -eq \"$cpuNum\" ]\n\t\tthen\n\t\techo \"You and the computer generated the same number\" $cpuNum\n\t\telse\n\t\techo \"Computer generated\" $cpuNum\", and you guessed\" $userNum\n\t\tfi\n\t}\n\n\t#get user input\n\tif [ \"$argAmount\" -eq 0 ]\n\tthen\n\techo \"No arguments\"\n\telif [ \"$argAmount\" -gt 1 ]\n\tthen\n\techo \"Too many arguments\"\n\telse\n\t#store inputs for the function\n\tuserNum=\"$args\"\n\tcpuNum=$[RANDOM%10+1]\n\t#go to the function\n\tcheckInput\n\tfi\n}\n\n#Check to see if arg is an ordinary file\nordinaryFile()\n{\n\tfunction checkForFile()\n\t{\n\t\t#check the filepath if is a file\n\t\tif [ -f \"./$filepath\" ]\n\t\tthen\n\t\techo $filename\" is a ordinary file\"\n\t\telse\n\t\techo $filename\" is not a ordinary file\"\n\t\tfi\n\t}\n\n\t#check user input\n\tif [ \"$argAmount\" -le 0 ]\n\tthen\n\techo \"Need at least 1 argument\"\n\telse\n\tfilename=\"$args\"\n\tfilepath=\"./$args\"\n\t#do the work in function\n\tcheckForFile\n\tfi\n}\n\n#use switch stament to check input\ncaseStatement()\n{\t\n\t#get user input\n\techo \"Do you like art?\" \n\techo \"Enter yes or no ::\" \n\tread userInput\n\n\t#check input to cases\n\tcase \"$userInput\" in\n\ty|Y|yes|Yes|YES)\n\t\techo \"Agreed\"\n\t\t;;\n\t\tn|N|no|No|NO)\n\t\techo \"Disagreed\"\n\t\t;;\n\t\t*)\n\t\techo \"Invalid input\"\n\t\t;;\n\tesac\n}\n\n#check all the words to find all the matches using elif and if\ncheckWord()\n{\n\t#read the words\n\techo \"Enter the 1st word\"\n\tread word1\n\techo \"now the 2nd word\"\n\tread word2\n\techo \"finally the 3rd word\"\n\tread word3\n\n\t#go through the else if statement\n\tif [ $word1 == $word2 ] \n\tthen\n\tif [ $word1 == $word3 ] \n\tthen\n\techo \"1st, 2nd, and 3rd words all are equal\"\n\telse\n\techo \"1st word is equal to the 2nd\"\n\tfi\n\telif [ $word1 == $word3 ]\n\tthen\n\techo \"1st word is equal to the 3rd\"\n\telif [ $word2 == $word3 ]\n\tthen\n\techo \"2nd word is equal to the 3rd\"\n\telse\n\techo \"None of the words are equal\"\n\tfi\n}\n\n#check for directory through looping\ncheckDir()\n{\n\t#get current directory to loop from (using pwd)\n\tloc=pwd\n\tfor loc in *\n\tdo\n\tif [[ -d $loc ]] \n\tthen\n\t#get rid of / from the name\n\techo \"$loc\" | cut -d '/' -f -1\n\tfi\n\tdone\n}\n\n#while-loop print 100 random nums from 1-100\nrandomNumsWhile()\n{\n\techo \"Enter a file name to out put the random nums\"\n\tread filename\n\tcount=1\n\t#while count<100\n\twhile [ \"$count\" -le 100 ]\n\tdo\n\trandomNum=$[RANDOM%100]\n\t#appened to file\n\techo \"$randomNum\" >> $filename\n\tcount=$[count+1]\n\tdone\n\techo \"Finished printing to\" $filename\n}\n\n#until-loop print 100 random nums from 1-100\nrandomNumsUntil()\n{\n\techo \"Enter a file name to out put the random nums\"\n\tread filename\n\tcount=1\n\t#while count<100\n\tuntil [ \"$count\" -ge 100 ]\n\tdo\n\trandomNum=$[RANDOM%100]\n\t#appened to file\n\techo \"$randomNum\" >> $filename\n\tcount=$[count+1]\n\tdone\n\techo \"Finished printing to\" $filename\n}\n\n#Need to hold args and arg amount to use for the functions\nargAmount=$#\nargs=$1\n\n#OUTPUTS\necho \"-----------------\"\necho \"1st script\"\nrandom\necho \"\"\n\necho \"-----------------\"\necho \"2nd Script\"\nuserRandom\necho \"\"\n\necho \"-----------------\"\necho \"3rd Script\"\nordinaryFile\necho \"\"\n\necho \"-----------------\"\necho \"4th Script\"\ncaseStatement\necho \"\"\n\necho \"-----------------\"\necho \"5th Script\"\ncheckWord\necho \"\"\n\necho \"-----------------\"\necho \"6th Script\"\ncheckDir\necho \"\"\n\necho \"-----------------\"\necho \"7th Script\"\nrandomNumsWhile\necho \"\"\n\necho \"-----------------\"\necho \"8th Script\"\nrandomNumsUntil\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5103793740272522, "alphanum_fraction": 0.520400881767273, "avg_line_length": 19.176469802856445, "blob_id": "c545fecfa74a39e6510168860fd71b89f35b2ec7", "content_id": "88d9e093568c597c449bbe07292699ce98aa18ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1397, "license_type": "no_license", "max_line_length": 76, "num_lines": 68, "path": "/Homework in C/HW2.c", "repo_name": "Kion-Smith/CS3377", "src_encoding": "UTF-8", "text": "/* Kion Smith\n* kls160430\n* CS 3377.0W3\n*/\n//create a program that counts characters in comments(single line and block)\n#include <stdio.h>\n#include <stdlib.h>\nint main(int argc, char*argv[])\n{\n\t//the file pointer and \n\t//char to loop through the file with\n\t//counter to hold how many characters where counted\n\tFILE *fp;\n\tchar c;\n\tint count=0;\n\n\t//open the file(uses the console to run the file)\n\t// ex ./a.out file.c\n\tfp = fopen( argv[1], \"r\" );\n\t\n\t//if the file is null, print that the fly could not be found\n\tif(fp == NULL)\n\t{\n\t\tprintf(\"The file could not be found\\n\");\n\t}\n\telse\n\t{\t//while next is not end of file\n\t\twhile ( (c = fgetc( fp )) != EOF )\n\t\t{\t//if c is a single slash\n\t\t\tif(c =='/')\n\t\t\t{\t//and if the next item is also a slash(//)\n\t\t\t\tif( (c = fgetc(fp)) == '/')\n\t\t\t\t{\t//loop until the end of line character\n\t\t\t\t\twhile((c = fgetc(fp)) != '\\n')\n\t\t\t\t\t{\t\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//if the next item is a * (/*)\n\t\t\t\telse if(c == '*')\n\t\t\t\t{\t//if the end could / is found loop until end\n\t\t\t\t\tif((c = fgetc(fp)) == '/')\n\t\t\t\t\t{\n\t\t\t\t\t\twhile((c = fgetc(fp)) != '\\n')\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// else the count the current characters until /\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\twhile((c = fgetc(fp)) != '/')\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\n\t\t\t\t\t\n\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\t//out put the results\n\t\tprintf(\"Character spaces counted = %d \\n\", count);\n\t}\n\n\t\n}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n" } ]
27
Sylphias/FokusAzureHackathon
https://github.com/Sylphias/FokusAzureHackathon
7cf84590a7dc46adb36068579de0e5c2e22438ac
326972450419185b204ead3c33de5eb2cc476997
5846213ae4c9dd64243e0edcd862d1409f92c883
refs/heads/master
2021-01-11T22:03:07.950946
2017-01-14T06:32:00
2017-01-14T06:32:00
78,906,785
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6701886653900146, "alphanum_fraction": 0.6789937019348145, "avg_line_length": 41.68817138671875, "blob_id": "6c9a2b4a68a87da1c3792079fbab972f343fc1c0", "content_id": "6f57469d97daf3ed294804310b66e3908c7e55c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3975, "license_type": "no_license", "max_line_length": 109, "num_lines": 93, "path": "/screenshotter.py", "repo_name": "Sylphias/FokusAzureHackathon", "src_encoding": "UTF-8", "text": "import pyscreenshot as ImageGrab\nimport datetime\nimport time\nimport json\nimport keys\nimport getpass\nfrom azure.storage.blob import ContentSettings\nfrom azure.storage.blob import BlockBlobService\nfrom azure.storage.blob import PublicAccess\nimport computer_vision as cv\nimport ddist\n\nqueueTimestamps =[]\ndef uploadToBlob(container,filename,object_type=\"image\", blobname=\"\", username=\"\", timestamp=\"\" ):\n block_blob_service = BlockBlobService(account_name=keys.blob_acct_name, account_key=keys.blob_key)\n block_blob_service.create_container(container, public_access=PublicAccess.Container)\n if object_type == \"image\":\n block_blob_service.create_blob_from_path(\n container,\n blobname,\n filename,\n content_settings=ContentSettings(content_type= 'image/png')\n )\n elif object_type == \"text\":\n block_blob_service.create_blob_from_text(\n container,\n blobname,\n filename\n )\n\ndef getJustText(jsonText):\n dictified = json.loads(jsonText)\n reformedString = \"\"\n for key,value in dictified.iteritems():\n reformedString += ' '.join(x+\" \" for x in value)\n return reformedString\n\ndef retrieveFromBlob(container,blobname):\n block_blob_service = BlockBlobService(account_name=keys.blob_acct_name, account_key=keys.blob_key)\n block_blob_service.create_container(container, public_access=PublicAccess.Container)\n block_blob_service.get_blob_to_path(container, blobname, blobname)\n\ndef getListOfBlobs(container):\n block_blob_service = BlockBlobService(account_name=keys.blob_acct_name, account_key=keys.blob_key)\n block_blob_service.create_container(container, public_access=PublicAccess.Container)\n return block_blob_service.list_blobs(container)\n\nclass Screenshotter:\n def __init__(self):\n queueTimestamps = []\n def start(self):\n self.run = True\n p = Process(target=self.sansfin, args=(1000,))\n p.start()\n p.join()\n\n def stop(self):\n self.run = False\n def run_script(self):\n im = ImageGrab.grab(bbox=(0, 0, 1440, 500)) # X1,Y1,X2,Y2\n im.save(\"curr_screen.png\")\n username = getpass.getuser()\n uploadToBlob('sscontainer', 'curr_screen.png', blobname=username)\n response = cv.analyzeImages(keys.blob_endpoint + \"/\" + username)\n timestamp = str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y%m%d%H%M%S'))\n self.queueTimestamps.append(timestamp)\n textJson = json.dumps(response)\n uploadToBlob('ocrcontainer', textJson, object_type='text', blobname=username + timestamp + '.txt')\n blobs = getListOfBlobs('ocrcontainer')\n retrieveFromBlob('ocrcontainer', username + self.queueTimestamps[0] + '.txt')\n model = open(username + self.queueTimestamps[0] + '.txt', \"r\")\n current_data = getJustText(textJson)\n model_data = getJustText(model.read())\n ddist.similarity_score(model_data, current_data)\n\n# if __name__ == '__main__':\nwhile(True):\n time.sleep(5)\n im = ImageGrab.grab(bbox=(0, 0, 1440, 900),childprocess= True,backend='mac_screencapture') # X1,Y1,X2,Y2\n im.save(\"curr_screen.png\")\n username = getpass.getuser()\n uploadToBlob('sscontainer', 'curr_screen.png', blobname=username)\n response = cv.analyzeImages(keys.blob_endpoint + \"/\" + username)\n timestamp = str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y%m%d%H%M%S'))\n queueTimestamps.append(timestamp)\n textJson = json.dumps(response)\n uploadToBlob('ocrcontainer', textJson, object_type='text', blobname=username + timestamp + '.txt')\n blobs = getListOfBlobs('ocrcontainer')\n retrieveFromBlob('ocrcontainer', username + queueTimestamps[0] + '.txt')\n model = open(username + queueTimestamps[0] + '.txt', \"r\")\n current_data = getJustText(textJson)\n model_data = getJustText(model.read())\n ddist.similarity_score(model_data, current_data)\n\n\n\n\n\n" } ]
1
msingh9001/Singh_Projects
https://github.com/msingh9001/Singh_Projects
c8d4feb9b15a915a593fdb59508bb295cc4a42d4
c89e26368068d27366f19f0f8acf6a5d35fcd50c
e69b0ffc47d4a38bfb57895066e21a174fc880ec
refs/heads/master
2021-06-13T21:10:56.432921
2021-03-18T07:03:41
2021-03-18T07:03:41
172,577,990
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.4511070251464844, "alphanum_fraction": 0.48846864700317383, "avg_line_length": 25.439023971557617, "blob_id": "15e89e3e8362aea5dbf3665e995b1920e84837b1", "content_id": "d5c8dbce0153b457c4b6e6ea058bbcbd613392e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2169, "license_type": "no_license", "max_line_length": 157, "num_lines": 82, "path": "/C++ Data Structures/Lab_2/statistician.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// statistician.cpp\n// Lab_2\n//\n// Created by Mandeep Singh on 4/11/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include <stdio.h>\n#include \"statistician.h\"\n\nusing namespace std;\nusing namespace coen79_lab2;\n\nnamespace coen79_lab2{\n \n statistician::statistician(){\n count = 0;\n total = 0;\n tiniest = 0;\n largest = 0;\n }\n \n void statistician::next(double x){\n count += 1;\n total += x;\n if(x < tiniest) { tiniest = x; }\n if(x > largest) { largest = x; }\n }\n \n void statistician::reset(){\n count = 0;\n total = 0;\n largest = 0;\n tiniest = 0;\n }\n \n statistician operator +(const statistician& s1, const statistician& s2){\n statistician s3;\n \n if(s1.length() == 0 && s2.length() == 0)\n return s3;\n else if(s1.length() == 0)\n return s2;\n else if(s2.length() == 0)\n return s1;\n else{\n double smallest = (s1.minimum() < s2.minimum()) ? s1.minimum() : s2.minimum();\n double largest = (s1.maximum() > s2.maximum()) ? s1.maximum() : s2.maximum();\n s3.total = s1.sum() + s2.sum();\n s3.count = s1.length() + s2.length();\n s3.largest = largest;\n s3.tiniest = smallest;\n }\n return s3;\n }\n \n statistician operator *(double scale, const statistician& s){\n statistician s3;\n \n s3.count = s.count;\n s3.total = s.total * scale;\n if(scale >= 0){\n s3.tiniest = s.tiniest * scale;\n s3.largest = s.largest * scale;\n }else{\n s3.tiniest = s.largest * scale;\n s3.largest = s.tiniest * scale;\n }\n \n return s3;\n }\n \n bool operator ==(const statistician& s1, const statistician& s2){\n if(s1.length() == 0 && s2.length() == 0)\n return true;\n else if(s1.length() == s2.length() && s1.sum() == s2.sum() && s1.maximum() == s2.maximum() && s1.mean() == s2.mean() && s1.minimum() == s2.minimum())\n return true;\n else\n return false;\n }\n}\n" }, { "alpha_fraction": 0.6827371716499329, "alphanum_fraction": 0.7099533677101135, "avg_line_length": 39.21875, "blob_id": "6143944005691d4ddb3c1d622aa3279ffce8ae0c", "content_id": "0d5fddc3a7309c32db73c53963ae632beea32e82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1286, "license_type": "no_license", "max_line_length": 125, "num_lines": 32, "path": "/COEN_178_Final_Project_mSingh/Functions/computeTotal.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh*/\n/*COEN 178 Final Project*/\n/*computeTotal Function*/\ncreate or replace function computeTotal (l_order in varchar)\nreturn number is\n\t/*Defining*/\n\ttotal number(10,2);\n ctype customers.custtype%type;\n copies itemorder.noofitems%type;\n l_price storeItems.price%type;\nbegin\n\ttotal := 0;\n\t/*Finding out customer type, number of items they ordered, and the price of the items*/\n select custtype into ctype from customers where custid = (select custid from itemorder where orderid = l_order);\n select noofitems into copies from itemorder where orderid = l_order;\n select price into l_price from storeItems where itemid = (select itemid from itemorder where orderid = l_order);\n /*If the customer type is regular, then total is order total + $10 shipping fee + 5% tax*/\n\tif ctype = 'regular' then\n \ttotal := total + 10 + l_price*copies*1.05; \n\telse\n\t/*If the customer type is gold and the order is less than 100 copies, then total is order total + 5% tax*/\n\t\tif l_price*copies < 100 then\n\t\t\ttotal := total + l_price*copies*1.05;\n\t\telse\n\t\t/*If the customer type is gold and the order is more than 99 copies, then total is order total with 10% discount + 5% tax*/\n\t\t\ttotal := total + l_price*copies*0.9*1.05;\n\t\tend if;\n\tend if;\n\treturn total;\nend;\n/\nshow error;" }, { "alpha_fraction": 0.5342601537704468, "alphanum_fraction": 0.5541211366653442, "avg_line_length": 29.515151977539062, "blob_id": "61482aa4778bf4565897c98519fb979cc63352d7", "content_id": "a5f91d6be6ad85d24641bed45fd2fa8e5fbe6cb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1007, "license_type": "no_license", "max_line_length": 111, "num_lines": 33, "path": "/Operating Systems/Lab_2/part1.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "# Name: Mandeep Singh\n# Date: 01/16/20\n# Title: Lab2 - System Calls\n# Description: This program creates exactly a process and forks to create a child and we see both get completed\n#include <stdio.h>\n#include <sys/types.h> /* pid_t */\n#include <unistd.h> /* fork */\n#include <stdlib.h> /* atoi */\n#include <errno.h> /* errno */\n\nint main(int argc, char *argv[]){\n pid_t pid;\n int i, n = atoi(argv[1]);\n printf(\"\\n Before forking. \\n\");\n pid = fork();\n#If pid is out of bouds, error catcher\n if(pid == -1)\n fprintf(stderr, \"cant print, error %d \\n\", i);\n#If the pid is not 0, then it is parent process and we print parent process\n if(pid){\n for(i = 0; i < 100; i++){\n printf(\"\\t \\t \\t Parent Process %d \\n\",i);\n usleep(n);\n }\n#If the pid is 0, then it is child process and we print child process\n }else{\n for (i = 0; i < 100; i++){\n printf(\"Child process %d\\n\",i);\n usleep(n);\n }\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.6186186075210571, "alphanum_fraction": 0.684684693813324, "avg_line_length": 65.80000305175781, "blob_id": "b7aedef3e2bd17f24b02fcd173ec99133c021f75", "content_id": "1a13f0d1b66af595b7c477582a4c1e3e56247b80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 333, "license_type": "no_license", "max_line_length": 71, "num_lines": 5, "path": "/SQL Databases/lab6/sql1.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "insert into BANKCUST_6 values('c1','Smith','32 Lincoln st','SJ');\ninsert into BANKCUST_6 values('c2','Jones','44 Benton st','SJ');\ninsert into BANKCUST_6 values('c3','Peters','12 palm st','SFO');\ninsert into BANKCUST_6 values('c20','Chen','20 san felipo','LA');\ninsert into BANKCUST_6 values('c33','Williams',' 11 cherry Ave','SFO');" }, { "alpha_fraction": 0.5922666788101196, "alphanum_fraction": 0.6055999994277954, "avg_line_length": 37.26530456542969, "blob_id": "af311a375f8311170dc4dfae0bc6a88a8dff76c5", "content_id": "1a23ce4d8d8303b262ad8c81dd05d63d294fce86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3751, "license_type": "no_license", "max_line_length": 130, "num_lines": 98, "path": "/C Data Structures/Term_Project/application_1_hash+array/dataset.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// dataset.c\n//\n// Created by Mandeep Singh on 02/21/19.\n// Copyright © 2018 Mandeep Singh. All rights .\n//\n//Utilizing a hash table where every index has a pointer to an array that holds IDs of all students that age\n#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"dataset.h\" //Import libraries for usage\n\n//O(n)\nSET *createDataSet(){ //Creates out set using variables initialized in struct set\n SET *sp;\n sp = malloc(sizeof(SET));\n assert(sp != NULL);\n sp -> length = 13;//only have 13 possibilites from [18,30]\n sp -> arrayLength = malloc(sizeof(int*)* (sp -> length)); //Allocate memory for an array to store legnths of hash arrays\n assert(sp -> arrayLength != NULL);\n for(int i = 0; i < sp -> length; i++) //Set all counts to 0\n sp -> arrayLength[i] = 0;\n sp -> arrayCount = malloc(sizeof(int*)* (sp -> length)); //Allocate memory for an array to store counts of hash arrays\n assert(sp -> arrayCount != NULL);\n sp -> data = malloc(sizeof(int*)* (sp -> length)); //Allocate memory for hash table\n assert(sp -> data != NULL);\n for(int j = 0; j < sp -> length; j++)\n sp -> data[j] = NULL; //Set all hash table elts to NULL so we don't need to waste space preallocating each hash array\n return sp;\n}\n\n//O(n)\nvoid destroyDataSet(SET *sp){\n assert(sp != NULL);\n for(int i = 0; i < sp -> length; i++)\n free(sp -> data[i]); //Free each array within hash table\n free(sp -> data); //Free hash table\n free(sp -> arrayCount); //Free array of count elts\n free(sp -> arrayLength); //Free array of length elts\n free(sp); //Free set\n printf(\"All records successfully destroyed\\n\");\n}\n\n//O(1) for worst case\nvoid addElement(SET *sp, int ID, int age){\n assert(sp != NULL);\n int index = age - 18; //Hash func for proper index\n if(sp -> data[index] == NULL){\n sp -> data[index] = malloc(sizeof(int*) * 300); //If the hash table elt is NULL, then we can allocate memory for just\n sp -> count++; //Increment count\n sp -> arrayCount[index] = 0; //Set the hash array count to 0 since it has just been created\n sp -> arrayLength[index] = 300; //Set the original array length of hash array to 300 but can extend it in future w/realloc\n }else if(sp -> arrayCount[index] >= sp -> arrayLength[index]){\n sp -> arrayLength[index] += 100; //Increment length\n sp -> data[index] = realloc(sp -> data[index], sizeof(int*)* (sp -> arrayLength[index])); //Reallocate memory\n }\n sp -> data[index][sp -> arrayCount[index]] = ID; //Set ID as value of the next index in sp -> data[index]\n sp -> arrayCount[index]++; //Increment count\n}\n\n//O(1) for worst case\nvoid removeElement(SET *sp, int age){\n assert(sp != NULL);\n int index = age - 18; //Hash func for proper index\n if(sp -> data[index] == NULL){\n printf(\"Deletion could not be done\\n\");\n }else{\n free(sp -> data[index]);\n sp -> data[index] = NULL;\n sp -> count--;\n printf(\"All IDs associared with age %d were deleted\\n\", age);\n }\n}\n\n//O(1)\nint** searchAge(SET *sp, int age){\n assert(sp != NULL);\n int index = age - 18; //Hash func for proper index\n if((sp -> data[index]) == NULL)\n printf(\"No student IDs associated with this age: %d\\n\", age);\n else{\n printf(\"Student IDs exist here\\n\");\n }\n return 0;\n}\n\n//O(n)\nvoid maxAgeGap(SET *sp){\n int i = 0, j = 12;\n while((sp -> data[i]) == NULL && i < j) //Lower wall for the smallest age\n i++;\n while((sp -> data[j]) == NULL && j > i) //Upper wall for the largest age\n j--;\n int ageGap = j - i; //ageGap is largest minus smallest\n printf(\"The max age gap is %d\\n\", ageGap);\n}\n" }, { "alpha_fraction": 0.6779271960258484, "alphanum_fraction": 0.6917021870613098, "avg_line_length": 36.17073059082031, "blob_id": "958b592af267a1d39fbf7f718ff71c320390febd", "content_id": "34c5c67ce32815502fad16555342e0d7099268d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 3049, "license_type": "no_license", "max_line_length": 188, "num_lines": 82, "path": "/COEN_178_Final_Project_mSingh/Functions/showItemOrders.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh*/\n/*COEN 178 Final Project*/\n/*showItemOrders Function*/\nCREATE OR REPLACE procedure showItemOrders(l_cust in varchar, l_date in date)\nis\n\t/*Defining*/\n\tl_name customers.name%type;\n\tl_phone customers.phone%type;\n\tl_address customers.address%type;\n\tcursor c_order is \n/*Select all the information needed to be displayed from all tables where the orderid is of the customer provided*/\nselect a.orderid, a.itemid, b.title, c.price, a.dateoforder, a.shippeddate, a.noofitems \nfrom itemorder a, storeItems c, comicbook b \nwhere a.custid = l_cust and a.itemid = b.itemid and a.itemid = c.itemid and a.dateoforder > l_date; \n\t/*Defining types*/\n\tl_order itemorder.orderid%type;\n\tl_item itemorder.itemid%type;\n\tl_title comicbook.title%type;\n\tl_price storeItems.price%type;\n\tl_orderdate itemorder.dateoforder%type;\n\tl_shipdate itemorder.shippeddate%type;\n\tl_totalitem storeItems.price%type;\n\tl_tax storeItems.price%type;\n\tl_fee storeItems.price%type;\n\tl_discount storeItems.price%type;\n\tl_total storeItems.price%type;\n\tl_no int;\n\tl_type customers.custtype%type;\n\nbegin \n\t/*Get customer type, name, phone, and address where custid is the customer provided*/\n\tselect custtype into l_type from customers where custid = l_cust;\n\tselect name into l_name from customers where custid = l_cust;\n\tselect phone into l_phone from customers where custid = l_cust;\n\tselect address into l_address from customers where custid = l_cust;\n\t/*Formatting*/\n\tdbms_output.put_line('Customer Information:');\n\tdbms_output.put_line('id: ' || l_cust);\n\tdbms_output.put_line('name: ' || l_name);\n\tdbms_output.put_line('phone: ' || l_phone);\n\tdbms_output.put_line('address: ' || l_address);\n\n\topen c_order;\n\t/*Looping to get information for all orders for a customer*/\n\tloop\n\t/*Retrieve information*/\n\tfetch c_order into l_order, l_item, l_title, l_price, l_orderdate, l_shipdate, l_no;\n\tEXIT WHEN c_order%notfound;\n\t/*Formatting*/ \n\tdbms_output.put_line('Order Information:');\n\tdbms_output.put_line('Order id: ' || l_order || ', item id: ' ||l_item || ', title: '||l_title||', price: ' || l_price || ', Order date: '||l_orderdate||', shipping date: ' ||l_shipdate);\n /*Calculating some outputs*/\n\t/*If regular then calculate the regular customer price level*/\n\tif l_type = 'regular' then\n\t\tl_totalitem := l_price*l_no;\n\t\tl_tax := l_totalitem*0.05;\n\t\tl_fee := 10;\n\t\tl_discount:= 0;\n \tl_total := 10 + l_price*l_no*1.05; \n\telse\n\t/*If gold, then calculate the gold customer price level*/\n\t\tl_fee := 0;\n\t\tl_totalitem := l_price*l_no;\n\t\tif l_price*l_no < 100 then\n\t\t\tl_tax := l_totalitem*0.05;\n\t\t\tl_discount := 0;\n\t\t\tl_total := l_totalitem*1.05;\n\t\telse\n\t\t/*If gold and > 100 copies 10% discount*/\n\t\t\tl_tax := l_totalitem*0.9*0.05;\n\t\t\tl_discount := l_totalitem*0.1;\n\t\t\tl_total := l_totalitem*0.9*1.05;\n\t\tend if;\n\tend if;\n\t/*Formatting*/\n\tdbms_output.put_line('Payment Details:');\n\tdbms_output.put_line('Item(s) Total: '||l_totalitem||', Tax: '||l_tax||', Discount: '||l_discount||', Shipping Fee: '||l_fee||', Total: '||l_total);\n\tend loop;\n\tclose c_order;\nend;\n/\nshow error; " }, { "alpha_fraction": 0.7612500190734863, "alphanum_fraction": 0.7737500071525574, "avg_line_length": 28.07272720336914, "blob_id": "d213280715ec16ae2eab7f89d89c5c46c9d584fe", "content_id": "1aeb3bd5ccd2663067e53c557e9b761014d127e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1600, "license_type": "no_license", "max_line_length": 326, "num_lines": 55, "path": "/SQL Databases/lab7/CreateExpenseReport.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "\n-- the size of one page\nSET PAGESIZE 50\n-- the size of a line\nSET LINESIZE 120\n\nBREAK ON TODAY\n\n/*\nTo use the system date in the header or elsewhere in the report is to execute a query that returns the current date and use the NEW_VALUE clause of the COLUMN command to get that date into a substitution variable. That substitution variable sticks around for the duration of the session and can be used in subsequent reports.\t\n*/\n\n/* The NEW_VALUE option of the COLUMN command is used to update the user variable report_date with the current value of SYSDATE as returned from the database. \n*/\nCOLUMN TODAY NEW_VALUE report_date\nSELECT TO_CHAR(SYSDATE, 'fmMonth DD, YYYY') TODAY\nFROM DUAL;\n\n-- Sets terminal output off\n\nset termout off\n-- Show the title of your report at the top of the page\n\nttitle center \"Expense Report \" report_date skip 2\n\n /* Places and formats a specified title at the bottom of each report page */\n\nbtitle center \"Mandeep Singh\"\n\n--After the SPOOL command, anything entered or displayed on\n-- standard output is written to the spool file, report.html.\n\nspool MyExpenseReport.txt\n\n-- change column headings and format number columns\ncolumn Groceries format $99.99 heading \"Groceries\"\ncolumn Entertainment format $99.99 heading \"Entertainment\"\ncolumn Gas format $99.99 heading \"Gas\"\n\nBREAK ON ROW SKIP 1\nBREAK ON Category SKIP 1 ON REPORT\nCOMPUTE AVG SUM MAXIMUM OF price on category\nselect Category, price\nfrom MyExpenses;\nspool off;\n\n--clear all formatting commands ...\n\nCLEAR COLUMNS\nCLEAR BREAK\nTTITLE OFF \nBTITLE OFF\nSET VERIFY OFF \nSET FEEDBACK OFF\nSET RECSEP OFF\nSET ECHO OFF\n" }, { "alpha_fraction": 0.5905680656433105, "alphanum_fraction": 0.5978027582168579, "avg_line_length": 31.736841201782227, "blob_id": "6e93173d22242971df0ea3aa5a980983f8f7c6e8", "content_id": "3029a74869f9b64e07450b6c45d3f75bcb1e8cd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3733, "license_type": "no_license", "max_line_length": 128, "num_lines": 114, "path": "/C Data Structures/sorted.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// sorted.c\n//\n// Created by Mandeep Singh on 01/23/19.\n// Copyright © 2019 Mandeep Singh. All rights .\n//\n#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"set.h\" //Import libraries for usage\n\nstatic int mybsearch(SET *sp, char *elt, bool *found);//Initialize our private search function\n\ntypedef struct set{ //Define our struct set\n char **data;//Pointer to an array of character strings\n int length; //Length of array\n int count; //Number of elements in array\n}SET;\n\n//O(1)\nSET *createSet(int maxElts){ //Creates out set using variables initialized in struct set\n SET *sp;\n sp = malloc(sizeof(SET));\n assert(sp != NULL);\n sp -> count = 0;\n sp -> length = maxElts;\n sp -> data = malloc(sizeof(char*)*maxElts);\n assert(sp -> data != NULL);\n return sp;\n}\n\n//O(n)\nvoid destroySet(SET *sp){\n assert(sp != NULL);//Checking to see if array elts are NULL\n for(int i = 0; i < sp -> count; i++)\n free(sp -> data[i]);//Freeing up memory\n}\n\n//O(1)\nint numElements(SET *sp){\n assert(sp != NULL);\n return sp -> count;//Return the number of elements in array\n}\n\n//O(nlogn) for worst case\nvoid addElement(SET *sp, char *elt){\n assert(sp != NULL && elt != NULL);\n bool found = false;//Found is false\n int index = mybsearch(sp, elt, &found);//Run search function\n if(found == true){\n // printf(\"This element already exists\");\n }else{\n for(int i = sp -> count; i > index; i--)\n sp -> data[i] = sp -> data[i-1];//Shift up elts in array\n sp -> data[index] = strdup(elt);//Insert elt to respective index\n sp -> count++;//Increase count by 1 to account for new elt\n }\n}\n\n//O(nlogn) for worst case\nvoid removeElement(SET *sp, char *elt){\n assert(sp != NULL && elt != NULL);\n bool found = false;\n int index = mybsearch(sp, elt, &found);//Run search function\n if(found == true){\n for(int i = index + 1; i < sp -> count; i++)\n sp -> data[i-1] = sp -> data[i];//Shift elements down\n sp -> count--;//Decrease count by 1 to account for deleting an elt\n }else{\n // printf(\"That element doesn't exist\");\n }\n}\n\n//O(logn)\nchar *findElement(SET *sp, char *elt){\n assert(sp != NULL && elt != NULL);\n bool found = false;\n int find = mybsearch(sp, elt, &found);//Run search function\n \n if(found)\n return sp -> data[find];//Return the elt found\n else\n return NULL;\n}\n\n//O(1)\nchar **getElements(SET *sp){\n assert(sp != NULL);\n char** ret = malloc(sizeof(char*)* sp -> count);//Allocate memory the size of count for array ret\n memcpy(ret, sp -> data, sizeof(char*)* (sp -> count));//Copy the chunk of memory from original array to array ret\n return ret;//Return ret\n}\n\n//O(logn)\nstatic int mybsearch(SET *sp, char *elt, bool *found){\n assert(sp != NULL && elt != NULL);\n int lo, hi, mid;//initialize variables\n lo = 0, hi = sp -> count - 1;//Give two variables values\n while(lo <= hi){\n mid = (hi + lo)/2;\n if(strcmp(elt, sp -> data[mid]) == 0){ //Compare the strings elt and all the elts in data[] to see if there is any match\n *found = true;//If there is found is true and mid is returned since that is the index where it was found\n return mid;\n }\n if(strcmp(elt, sp -> data[mid]) > 0) //elt is larger than the elt at data[]\n lo = mid + 1;//The elt we are searching for is larger than mid so lo is increased\n else\n hi = mid - 1;// The elt we are searching for is smaller than mid so hi is decreased\n }\n *found = false;//If elt is never found in data[] found is false\n return lo;//lo is returned\n}\n" }, { "alpha_fraction": 0.5391061305999756, "alphanum_fraction": 0.5921787619590759, "avg_line_length": 21.375, "blob_id": "a9b7864768b313387e1dace7e0e2dac821aca70f", "content_id": "e5cd3a3a9af37c4c811eb7afd6f5ec89ebf2fb4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 358, "license_type": "no_license", "max_line_length": 49, "num_lines": 16, "path": "/Artificial Intelligence/Lab_1/class2.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "class FirstClass:\n def setdata(self, value1, value2):\n self.data1 = value1\n self.data2 = value2\n def display(self):\n print(self.data1, '\\n', self.data2, '\\n')\n\nclass SecondClass(FirstClass):\n def adder(self, val1, val2):\n a = val1 + val2\n print(a)\n\nz = SecondClass()\nz.setdata(10, 20)\nz.display()\nz.adder(-5, -10)\n" }, { "alpha_fraction": 0.522982656955719, "alphanum_fraction": 0.5485188961029053, "avg_line_length": 21.25, "blob_id": "c3532bcd0c9b4ffa8de1c6773dbc905660a3d37b", "content_id": "949a1a919e46f6f1c303fb699ede9b84b8a9cdf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 980, "license_type": "no_license", "max_line_length": 65, "num_lines": 44, "path": "/C Data Structures/selection-sort.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// selection-sort.c\n//\n// Created by Mandeep Singh on 03/19/19.\n// Copyright © 2018 Mandeep Singh. All rights .\n//\n//Utilizing the selection sort algorithm to sort an integer array\n#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h> //Import libraries for usage\n#define NUM_OF_ELEMENTS 7\n\nvoid selectionSort(int arr[]);\nvoid swap(int *x, int *y);\n\nint main(){\n int myarray[NUM_OF_ELEMENTS] = {6, 4, 7, 9, 2, 0, 19};\n selectionSort(myarray);\n for(int i = 0; i < NUM_OF_ELEMENTS; i++)\n printf(\"%d\\n\", myarray[i]);\n}\n\n//O(n^2) & not stable\nvoid selectionSort(int arr[]){\n for(int i = 0; i < NUM_OF_ELEMENTS - 1; i++){\n int smallest = i;\n \n for(int j = i + 1; j < NUM_OF_ELEMENTS; j++){\n if(arr[j] < arr[smallest])\n smallest = j;\n }\n swap(&arr[smallest], &arr[i]);\n }\n \n}\n\n//O(1)\nvoid swap(int *x, int *y){\n int temp = *x;\n *x = *y;\n *y = temp;\n}\n" }, { "alpha_fraction": 0.5724770426750183, "alphanum_fraction": 0.6321101188659668, "avg_line_length": 25.9135799407959, "blob_id": "557f91bb9c5da89cbb90616555ba8f018983b9d9", "content_id": "c84041ed5f7a1f4c2976fd2313b9f710fed56216", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2180, "license_type": "no_license", "max_line_length": 73, "num_lines": 81, "path": "/Computer Graphics Systems/HW_2/wireframe.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "# object representation \n\nfrom PIL import Image, ImageDraw\nimport math\nimport csv\nimport array as arr\n\n\n\nimg = Image.new('RGB', (1000, 1000))\npixels = img.load()\n# this list hold all vertices\n# you can use append() to add all x, y, z\n# into it. the format could be like this:\n# [[x1, y1, z1], [x2, y2, z2],......]\nvertices = []\npoints = []\n\n#read in face vertices\nwith open('face-vertices.data.txt', 'r') as f:\n reader = csv.reader(f, delimiter=',')\n vertices = list(reader)\n\n#read index\nwith open('face-index.txt') as csv_file:\n reader = csv.reader(csv_file, delimiter=',')\n points = list(reader)\n\ndef projectX(x, z):\n locz = 1 - z\n return (1500 * x /locz) + 500\n\ndef projectY(y, z):\n locz = 1 - z\n return (1500 * y/locz) + 350\n\ndef draw_pixel(x,y, color):\n pixels[x,y] = (color,0,0)\n\ndraw = ImageDraw.Draw(img)\n\nprint(points)\nfor index in points:\n index0 = int(index[0])\n index1 = int(index[1])\n index2 = int(index[2])\n\n x0 = projectX(float(vertices[index0][0]), float(vertices[index0][2]))\n y0 = projectY(float(vertices[index0][1]), float(vertices[index0][2]))\n x1 = projectX(float(vertices[index1][0]), float(vertices[index1][2]))\n y1 = projectY(float(vertices[index1][1]), float(vertices[index1][2]))\n x2 = projectX(float(vertices[index2][0]), float(vertices[index2][2]))\n y2 = projectY(float(vertices[index2][1]), float(vertices[index2][2]))\n\n draw_pixel(x0, y0, 255)\n\nimg.show()\n\nfor index in points:\n index0 = int(index[0])\n index1 = int(index[1])\n index2 = int(index[2])\n \n x0 = projectX(float(vertices[index0][0]), float(vertices[index0][2]))\n y0 = projectY(float(vertices[index0][1]), float(vertices[index0][2]))\n x1 = projectX(float(vertices[index1][0]), float(vertices[index1][2]))\n y1 = projectY(float(vertices[index1][1]), float(vertices[index1][2]))\n x2 = projectX(float(vertices[index2][0]), float(vertices[index2][2]))\n y2 = projectY(float(vertices[index2][1]), float(vertices[index2][2]))\n \n draw.line((x0,y0,x1,y1), fill=255)\n draw.line((x1,y1,x2,y2), fill=255)\n draw.line((x0,y0,x2,y2), fill=255)\n\n\nimg.show()\n\n## for index in csv_reader:\n##\n##\n## #\n" }, { "alpha_fraction": 0.5099630951881409, "alphanum_fraction": 0.5579335689544678, "avg_line_length": 38.85293960571289, "blob_id": "47a5641cb803107e4ed30fd7ca02c99011578d68", "content_id": "653b653fc3f33e5aa323ef61141585c658b319c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1356, "license_type": "no_license", "max_line_length": 247, "num_lines": 34, "path": "/C++ Data Structures/Homework_1/HW_3/main.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// HW_2\n//\n// Created by Mandeep Singh on 4/10/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include <iostream>\n#include \"statistician.hpp\"\n\nusing namespace std;\n\nint main(int argc, const char * argv[]) {\n statistician s1;\n statistician s2;\n s1.next_number(-10);\n s1.next_number(5);\n s1.next_number(-5);\n s1.next_number(10);\n s1.next_number(5);\n s1.next_number(-5);\n s2.next_number(10);\n s2.next_number(10);\n s2.next_number(-10);\n s2.next_number(-10);\n s2.next_number(10);\n s2.next_number(14);\n statistician s3 = s1 + s2;\n cout << \"Length is: \" << s1.get_length() << \"\\nSum is: \" << s1.get_sum() << \"\\nAverage is: \" << s1.get_avg() << \"\\nSmallest is: \" << s1.get_smallest() << \"\\nLargest is: \" << s1.get_largest() << \"\\nLast Number is: \" << s1.get_lastNum() << endl;\n cout << \"Length is: \" << s2.get_length() << \"\\nSum is: \" << s2.get_sum() << \"\\nAverage is: \" << s2.get_avg() << \"\\nSmallest is: \" << s2.get_smallest() << \"\\nLargest is: \" << s2.get_largest() << \"\\nLast Number is: \" << s2.get_lastNum() << endl;\n cout << \"Length is: \" << s3.get_length() << \"\\nSum is: \" << s3.get_sum() << \"\\nAverage is: \" << s3.get_avg() << \"\\nSmallest is: \" << s3.get_smallest() << \"\\nLargest is: \" << s3.get_largest() << \"\\nLast Number is: \" << s3.get_lastNum() << endl;\n EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.8190630078315735, "alphanum_fraction": 0.8206785321235657, "avg_line_length": 309, "blob_id": "bfd73e8fff05b83e455537ad258a6d1b37c6e49d", "content_id": "55de4524ad9c7a9cc69de7d0d8d876eb57f4a5c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 619, "license_type": "no_license", "max_line_length": 604, "num_lines": 2, "path": "/C Data Structures/Term_Project/application_1_sorted/README.txt", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "Application 1:\rAssume that the college takes very few transfer students and has most of its students stay for at least one year. (Hints: no frequent insertion and deletion operations). And the maximum student number is given. But it does require a lot of search operations based on student ages. Please note that your search functions may return multiple records when only a student age is given. In addition, the college often requires calculating the largest age gap among its students. The major interfaces provided by your code should include createDataSet, destroyDataSet, searchAge, insertion, deletion, maxAgeGap" }, { "alpha_fraction": 0.64812171459198, "alphanum_fraction": 0.656205415725708, "avg_line_length": 33.47541046142578, "blob_id": "791c5dc927f41259762ef653896746060893387c", "content_id": "f9b6cbd2589efe4ce03dc38928c982705128ab60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2103, "license_type": "no_license", "max_line_length": 238, "num_lines": 61, "path": "/SQL Databases/lab8/showMovieStats.php", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n\t<meta charset=\"utf-8\"/>\n <title>Show Movie Stats</title>\n </head>\n <body>\n\n <!-- Edit the link -->\n <a href='http://linux.students.engr.scu.edu/~msingh/showMovieStats.php?show=true'>Show Movie Stats</a>\n <br><br>\n<?php\n\nif (isset($_GET['show'])) {\n showStats();\n}\n\nfunction showStats(){\n\t//connect to your database. Type in your username, password and the DB path\n\t\n\t$conn = oci_connect('msingh', 'Divgeet12', '//dbserver.engr.scu.edu/db11g');\n\tif (!$conn) {\n\t\t$e = oci_error();\n\t\ttrigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);\n\t} \n\tif(!$conn) {\n\t print \"<br> connection failed:\";\n exit;\n\t}\n\t// Query to find the name of movie and the no. of reviews per movie\n\t$query1 = oci_parse($conn, \"SELECT movieName, Count(*) NoOfReviews FROM MovieReviews Group by movieName\");\n\n\t// Execute the query\n\toci_execute($query1);\n\t\n\t// Now access each row fetched in the loop\n\twhile (($row = oci_fetch_array($query1, OCI_BOTH)) != false) {\n\t\t// We can use either numeric indexed starting at 0\n\t\t// or the column name as an associative array index to access the colum value\n\t\t// Use the uppercase column names for the associative array indices\n\t\techo \"<font color='black'>Movie: </font>\";\n\t\techo \"<font color='green'> $row[0] </font>\";\n\t\techo \"<font color='black'>No. of Reviews: </font> <font color='red'> $row[1]</font></br>\";\t\t\n\t}\n\t\n\t/* Write your query 2 here to find the name of the movie(s) \n\twith maximum no. of reviews.\n\t\n\t*/\n\t$query2 = oci_parse($conn, \"SELECT movieName, Count(movieName) FROM MovieReviews Group By movieName Having Count(movieName) = (SELECT MAX(NoOfReviews) From (SELECT movieName, Count(*) NoOfReviews FROM MovieReviews Group by movieName))\");\n\toci_execute($query2);\n\twhile (($row = oci_fetch_array($query2, OCI_BOTH)) != false){\n\t\techo \"<font color='black'>Movie with most Reviews: </font> <font color='green'>$row[0]</font> <font color='black'>-</font> <font color='red'>$row[1]</font> <font color='black'>Reviews</font>\";\n\t}\n\n\tOCILogoff($conn);\n}\n?>\n<!-- end PHP script -->\n </body>\n</html>\n" }, { "alpha_fraction": 0.4751908481121063, "alphanum_fraction": 0.5419847369194031, "avg_line_length": 17.068965911865234, "blob_id": "4fb1285a8e3fa324f63e6d40690ea2a5f6d877e9", "content_id": "3dc187c970d6cd04e4da4013d45d06021d8d0b3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 525, "license_type": "no_license", "max_line_length": 49, "num_lines": 29, "path": "/C++ Data Structures/Homework_2/HW_2/main.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// HW_2\n//\n// Created by Mandeep Singh on 4/17/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include <iostream>\n#include \"bag.hpp\"\n\nusing namespace std;\nint main(int argc, const char * argv[]) {\n set b1;\n set b2;\n b1.insert(3);\n b1.insert(8);\n b1.insert(7);\n b1.insert(10);\n std::cout << b1.size() << endl;\n b1.insert(10);\n std::cout << b1.size() << endl;\n b2.insert(10);\n b2.insert(12);\n b2.insert(3);\n std::cout << b2.size() << endl;\n \n EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.6708385348320007, "alphanum_fraction": 0.6833541989326477, "avg_line_length": 23.212121963500977, "blob_id": "5cf2e42087c218a4428c7733534f55227330ff12", "content_id": "d0664db962d3778e8d74bac1a0c4c368cff357ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 800, "license_type": "no_license", "max_line_length": 121, "num_lines": 33, "path": "/C Data Structures/Term_Project/application_1_hash+array/dataset.h", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// dataset.h\n//\n// Created by Mandeep Singh on 03/14/19.\n// Copyright © 2019 Mandeep Singh. All rights .\n//\n//\n\n# ifndef DATASET_H\n# define DATASET_H\n\ntypedef struct set{ //Define our struct set\n int **data;//Pointer to an array of integers\n int *arrayLength; //Array of integers where each index holds the length for the array at that index in the hash table\n int *arrayCount; //Array of integers where each index holds the length for the array at that index in the hash table\n int count; //Number of elements in array\n int length; //Length of hash table\n \n}SET;\n\nSET *createDataSet();\n\nvoid destroyDataSet(SET *sp);\n\nvoid addElement(SET *sp, int ID, int age);\n\nvoid removeElement(SET *sp, int age);\n\nvoid maxAgeGap(SET *sp);\n\nint** searchAge(SET *sp, int age);\n\n# endif /* DATASET_H */\n" }, { "alpha_fraction": 0.5420560836791992, "alphanum_fraction": 0.5654205679893494, "avg_line_length": 23.69230842590332, "blob_id": "f650f304d7b122b31d0ce206bb9aa33edb1e2216", "content_id": "6591f240ed4c372df8b0d828fc8a77e453ebd076", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 643, "license_type": "no_license", "max_line_length": 110, "num_lines": 26, "path": "/C++ Data Structures/Lab_1/part1.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// part1.cpp\n// Lab_1\n//\n// Created by Mandeep Singh on 4/4/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include \"part1.hpp\"\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nvoid part1(){\n string input;\n cout << \"Please enter a string: \" << endl;\n getline(cin, input);\n int x = 0, y = 0; //x is alphanumeric counter and y is nonalphanumeric and nonspace counter\n for(int i = 0; i < input.length(); i++){\n if(isalnum(input[i])) x++;\n else if (input[i] != ' ') y++;\n }\n \n cout << \"\\nThere are \" << x << \" alpanumeric chars and \" << y << \" nonalphanumeric chars\" << \"\\n\" << endl;\n}\n" }, { "alpha_fraction": 0.5428571701049805, "alphanum_fraction": 0.6095238327980042, "avg_line_length": 14, "blob_id": "e9c1c053966323e5f8667334e61a58aa8f135621", "content_id": "e38411e14a2014d96e200171d64e148718611c02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 211, "license_type": "no_license", "max_line_length": 49, "num_lines": 14, "path": "/C++ Data Structures/Lab_1/part1.hpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// part1.hpp\n// Lab_1\n//\n// Created by Mandeep Singh on 4/4/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#ifndef part1_hpp\n#define part1_hpp\n\n#include <stdio.h>\nvoid part1();\n#endif /* part1_hpp */\n" }, { "alpha_fraction": 0.7316455841064453, "alphanum_fraction": 0.7670885920524597, "avg_line_length": 55.57143020629883, "blob_id": "8f8e527f338a0c0ebeda177f90d3522a8290554c", "content_id": "b59ccbbcd98578fcd05b551a5c1e931feccdcbe8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 395, "license_type": "no_license", "max_line_length": 115, "num_lines": 7, "path": "/SQL Databases/lab7/sql2.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "CREATE TABLE Course(courseNo INTEGER PRIMARY KEY, courseName VARCHAR(20));\nCREATE TABLE Course_Prereq(courseNo INTEGER, prereqNo Integer, Foreign Key(prereqNo) references Course (courseNo));\ninsert into Course values (10,'C++');\ninsert into Course values (11,'Java');\ninsert into Course values (12,'Python');\ninsert into Course values (121,'Web');\ninsert into Course values (133,'Software Eng');" }, { "alpha_fraction": 0.7511835694313049, "alphanum_fraction": 0.7895844578742981, "avg_line_length": 37.81632614135742, "blob_id": "85acd3ecbacdc469df8a6a988ba1ab289eb7b045", "content_id": "e7ad1b910a789f4f9613741441c899c7e72bed87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1901, "license_type": "no_license", "max_line_length": 371, "num_lines": 49, "path": "/COEN_178_Final_Project_mSingh/Functions/report.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh*/\n/*COEN 178 Final Project*/\n/*Report*/\n/*Setting restrictions for pagesize and linesize*/\nSET PAGESIZE 20\nSET LINESIZE 200\n/*Initializing report similar to lab*/\nBREAK ON TODAY\nCOLUMN TODAY NEW_VALUE report_date\nSELECT TO_CHAR(SYSDATE, 'fmMonth DD, YYYY') TODAY\nFROM DUAL;\n\nff\n\nset termout off\n/*Setting title*/\nttitle center \"Customer Report\" report_date skip 2\nbtitle center \"Mandeep Singh COEN 178 Project\"\nspool report.txt\n/*Formatting Column Headers*/\ncolumn custid format a5 heading \"ID\"\ncolumn name format a12 heading \"Name\"\ncolumn phone format a10 heading \"Phone\"\ncolumn address format a17 heading \"Address\"\ncolumn orderid format a6 heading \"OrderID\"\ncolumn itemid format a6 heading \"itemid\"\ncolumn title format a13 heading \"title\"\ncolumn dateoforder format a10 heading \"OrderDate\"\ncolumn shippeddate format a10 heading \"shippeddate\"\ncolumn itemtotal format $99999.00 heading \"ItemTotal\"\ncolumn grandtotal format $99999.00 heading \"GrandTotal\"\ncolumn tax format $99999.00 heading \"Tax\"\ncolumn shippingfee format $99999.00 heading \"ShippingFee\"\n/*Select customer id, name, phone, address, orderid, itemid, \ntitle of comic book, price, date of order, shipping date, \nsubtotal, tax, shipping fee, and order total from the \nnatural join of customers, itemorder, comicbook, storeItems \nfor customer with id c001 and order date after 10 august 2007*/\nselect custid, name, phone, address,orderid, itemid, title, price, dateoforder, shippeddate, noofitems*price as itemtotal, computeTotal(orderid)-noofitems*price-shippingfee as tax, shippingfee, computeTotal(orderid) as grandtotal from customers natural join itemorder natural join comicbook natural join storeItems where custid = 'c001' and dateoforder >= '10-aug-2007';\nspool off;\n/*End of report necessities similar to lab*/\nCLEAR COLUMNS\nCLEAR BREAK\nTTITLE OFF \nBTITLE OFF\nSET VERIFY OFF \nSET FEEDBACK OFF\nSET RECSEP OFF\nSET ECHO OFF" }, { "alpha_fraction": 0.738916277885437, "alphanum_fraction": 0.7487684488296509, "avg_line_length": 28.14285659790039, "blob_id": "0b2f72ae9ce4485f678afc717f2a628452d8ac3c", "content_id": "9fba3f4fa340e29235bf47ad8d51b2dfa09ec566", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 203, "license_type": "no_license", "max_line_length": 51, "num_lines": 7, "path": "/SQL Databases/midterm2_mSingh/Number_8_mSingh/query_mSingh.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh Number 8*/\nSelect * From Emp_Office;\nSelect * From Emp_Phone;\nSelect EO.OfficeNo From Emp_Office EO, Emp_Phone EP\nWHERE EO.EmpNo = EP.EmpNo\nGROUP BY OfficeNo\nHAVING count(DISTINCT EP.PhoneNo)>1;" }, { "alpha_fraction": 0.42003515362739563, "alphanum_fraction": 0.5079085826873779, "avg_line_length": 22.70833396911621, "blob_id": "d1706cbcd57a2f1204ececa3c989257d70835c7a", "content_id": "cef3d9670ca7228eee50613742160f509906b064", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 570, "license_type": "no_license", "max_line_length": 228, "num_lines": 24, "path": "/C++ Data Structures/Lab_1/part2.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// part2.cpp\n// Lab_1\n//\n// Created by Mandeep Singh on 4/4/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include \"part2.hpp\"\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <stdio.h>\n#include <ctype.h>\n\nusing namespace std;\n\nvoid part2(){\n string a = \"0123456789\";\n string b = \"9876543210\";\n \n cout << a << \"\\n\" << setw(11) << b << setw(20) << a << \"\\n\" << setw(13) << b << setw(22) << a << \"\\n\" << setw(15) << b << setw(24) << a << \"\\n\" << setw(17) << b << setw(26) << a << \"\\n\" << setw(19) << b << \"\\n\" << std::endl;\n \n}\n" }, { "alpha_fraction": 0.7404580116271973, "alphanum_fraction": 0.7659032940864563, "avg_line_length": 19.736841201782227, "blob_id": "4431f5d1fb8407b710e54cdf46eac09d879b5e1d", "content_id": "211f280b11f10a506ce5a7a7f5205c3363300cd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 393, "license_type": "no_license", "max_line_length": 46, "num_lines": 19, "path": "/SQL Databases/midterm2_mSingh/extra_credit_mSingh/tables_mSingh.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh Extra Credit*/\ncreate table Book(\nbookid char(2),\ntitle varchar(20),\nauthor varchar(20),\nPRIMARY KEY(bookid)\n);\ncreate table Applicant(\napplicantid char(2),\naname varchar(10),\nPRIMARY KEY(applicantid)\n);\ncreate table BooksRead(\napplicantid char(2),\nbookid char(2),\nFOREIGN KEY(applicantid) REFERENCES Applicant,\nFOREIGN KEY(bookid) REFERENCES Book,\nPRIMARY Key(applicantid, bookid)\n);" }, { "alpha_fraction": 0.7217742204666138, "alphanum_fraction": 0.725806474685669, "avg_line_length": 30.125, "blob_id": "31b650fa637ba8c4f291f7fe0316a38286035b07", "content_id": "501af8bad1bee00ad4677b4970f0aae0ce59837c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 248, "license_type": "no_license", "max_line_length": 133, "num_lines": 8, "path": "/SQL Databases/lab6/psql2.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "CREATE or REPLACE TRIGGER display_customer_trig\nAFTER INSERT ON BankCust_6\nFOR EACH ROW\nBEGIN\nDBMS_OUTPUT.PUT_LINE('From Trigger '||'Customer NO: '||:new.custno||' Customer Name: '||:new.custname||'Customer City: '||:new.city);\nEND;\n/\nshow errors;" }, { "alpha_fraction": 0.7923784255981445, "alphanum_fraction": 0.802890956401825, "avg_line_length": 62.41666793823242, "blob_id": "d4c269e126cdd8ab08ae9f269efde37856957dbb", "content_id": "16c726c47406234d0bb75cfe443d8a836d81ee45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 761, "license_type": "no_license", "max_line_length": 84, "num_lines": 12, "path": "/SQL Databases/lab2/lab2_queries1.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "select custid, city, firstname||lastname AS fullname from cust;\nselect * from cust ORDER BY lastname;\nselect * from schedule ORDER BY serviceid, custid desc;\nselect serviceid from deliveryservice MINUS select serviceid from schedule;\nselect firstname||lastname AS fullname from cust, schedule where day = 'm';\nselect lastname from cust, schedule where cust.custid = schedule.custid;\nselect MAX(servicefee) as highestServiceFee from deliveryservice;\nselect count(day) from schedule GROUP BY day;\nselect A.custid,B.custid,A.city from Cust A, Cust B where A.city = B.city;\nselect custid from cust, deliveryservice where cust.city = deliveryservice.location;\nselect MIN(salary) as MinimumSalary from staff_2010;\nselect MAX(salary) as MaximumSalary from staff_2010;\n" }, { "alpha_fraction": 0.7546296119689941, "alphanum_fraction": 0.7592592835426331, "avg_line_length": 20.700000762939453, "blob_id": "ae734c6a4f99188cfc7e29d4223ae5e91d5eeb13", "content_id": "60fb309e52c74e101b9b6f3fe0bee2101c719c8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 216, "license_type": "no_license", "max_line_length": 52, "num_lines": 10, "path": "/SQL Databases/lab5/part2/psql5.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "CREATE Or Replace TRIGGER titlecountchange_trig \nAFTER INSERT ON AlphaCoEmp \nFOR EACH ROW \nBEGIN \nUpdate EmpStats \nset Empcount = Empcount + 1, lastmodified = SYSDATE \nwhere title = :new.title; \nEND; \n/ \nShow errors;" }, { "alpha_fraction": 0.7418181896209717, "alphanum_fraction": 0.7418181896209717, "avg_line_length": 18.714284896850586, "blob_id": "67d4cb236a36cb9ddc4f28c4f75b3a60c95dd546", "content_id": "86d2e2a8b95b5589d4d7e1b85e370a50912cddc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 275, "license_type": "no_license", "max_line_length": 74, "num_lines": 14, "path": "/SQL Databases/lab5/part1/psql3.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "Create or Replace Function countByTitle(p_title in AlphaCoEmp.title%type) \nRETURN NUMBER \nIS \nl_cnt Integer; \nBEGIN\n\t/* Complete the query below */ \nSelect count(p_title) into l_cnt from AlphaCoEmp \nGroup by title\nHaving \ntitle = p_title;\nreturn l_cnt; \nEND; \n/ \nShow Errors;" }, { "alpha_fraction": 0.5685483813285828, "alphanum_fraction": 0.625, "avg_line_length": 15.533333778381348, "blob_id": "c77dd9e81e9c267ef7fd8c93a9155a0f1eccedec", "content_id": "ec924510359e53830905bb57b4451f9873d07755", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 249, "license_type": "no_license", "max_line_length": 49, "num_lines": 15, "path": "/C++ Data Structures/Lab_1/part4b.hpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// part4b.hpp\n// Lab_1\n//\n// Created by Mandeep Singh on 4/4/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#ifndef part4b_hpp\n#define part4b_hpp\n\n#include <stdio.h>\nvoid part4b();\nint str_len(char s[],int start);\n#endif /* part4b_hpp */\n" }, { "alpha_fraction": 0.5865384340286255, "alphanum_fraction": 0.6132478713989258, "avg_line_length": 29.19354820251465, "blob_id": "a83bb2cd8f1239c0af55c8ef4765c5557982fc66", "content_id": "249601f98cb6488e5e56830613cff247eb7bca57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 936, "license_type": "no_license", "max_line_length": 95, "num_lines": 31, "path": "/Operating Systems/Lab_2/part6.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "# Name: Mandeep Singh\n# Date: 01/16/20\n# Title: Lab2 - System Calls\n# Description: This program creates exactly 2 threads\n#include <stdio.h>\n#include <sys/types.h> /* pid_t */\n#include <unistd.h> /* fork */\n#include <stdlib.h> /* atoi */\n#include <errno.h> /* errno */\n#include <pthread.h> /* pthread_t */\n\nvoid *parentProcess(){\n for(int i = 0; i < 100; i++)\n printf(\"Parent Process %d \\n\",i);\n}\n\nvoid *childProcess(){\n for (int i = 0; i < 100; i++)\n printf(\"Child process %d\\n\",i);\n}\n \nint main(int argc, char *argv[]){\n pthread_t tid[2];\n#Creating 2 threads each that executes a function\n pthread_create(&tid[0], NULL, parentProcess, (void *)&tid[0]);\n pthread_create(&tid[1], NULL, childProcess, (void *)&tid[1]);\n#By using join, we add thread to main process so it completes the thread process before exiting\n pthread_join(tid[0], NULL);\n pthread_join(tid[1], NULL);\n return 0;\n}\n" }, { "alpha_fraction": 0.4801587164402008, "alphanum_fraction": 0.5357142686843872, "avg_line_length": 13.823529243469238, "blob_id": "bdb9c47329ff6eddba910fc1f87e33f374e4a0b0", "content_id": "323807a55c094b1b6bf84b16249c1850492be316", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 252, "license_type": "no_license", "max_line_length": 23, "num_lines": 17, "path": "/Artificial Intelligence/Lab_1/test_if.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "x = 1\nif x:\n y=2\n if y:\n print(\"block2\")\n print(\"block1\")\nprint(\"block0\")\n\nchoice = 'ham'\nif choice == 'spam':\n print(1.25)\nelif choice == 'eggs':\n print(0.99)\nelif choice == 'bacon':\n print(1.10)\nelse:\n print('Bad choice')\n" }, { "alpha_fraction": 0.42458099126815796, "alphanum_fraction": 0.4453312158584595, "avg_line_length": 22.203702926635742, "blob_id": "86aa96315c5422206c0249138ad57f2e020cfc5a", "content_id": "8d574c736d30bbfb6ff79c712bbb467a01909bb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1254, "license_type": "no_license", "max_line_length": 57, "num_lines": 54, "path": "/C++ Data Structures/Homework_1/HW_5/sequence.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// sequence.cpp\n// HW_5\n//\n// Created by Mandeep Singh on 4/10/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include \"sequence.hpp\"\n#include <assert.h>\n\nnamespace std {\n \n sequence::sequence(){\n used = 0;\n current_index = 0;\n for(int i = 0; i < CAPACITY; i++)\n data[i] = -1;\n }\n \n void sequence::insert(const value_type& entry){\n assert(size() < CAPACITY);\n if(used == 0){\n data[0] = entry;\n current_index = 0;\n }else{\n for(int i = current_index; i < used; i++)\n data[i] = data[i+1];\n data[current_index] = entry;\n }\n used++;\n }\n \n void sequence::attach(const value_type& entry){\n assert(size() < CAPACITY);\n if(used == 0){\n data[0] = entry;\n current_index = 0;\n }else{\n for(int i = current_index; i < used; i++)\n data[i+1] = data[i+2];\n data[current_index+1] = entry;\n current_index += 1;\n }\n used++;\n }\n \n void sequence::remove_current(){\n if(is_item()){\n for(int i = CAPACITY; i > current_index; i--)\n data[i] = data[i-1];\n }\n }\n}\n" }, { "alpha_fraction": 0.510722815990448, "alphanum_fraction": 0.5250198841094971, "avg_line_length": 23.230770111083984, "blob_id": "cb58277178974c82e1270991db7a3793d31215f4", "content_id": "d809a357a46faa5634152ba7cf804bffe6d013e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1259, "license_type": "no_license", "max_line_length": 112, "num_lines": 52, "path": "/Java/Test_Rectangle/src/test_rectangle/Rectangle.java", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "package test_rectangle;\npublic class Rectangle {\n private double length ;\n private double width ;\n\n public void setLength( double length)\n {\n if (length < 0 || length > 20)\n {\n throw new IllegalArgumentException(\"For input length:0.0\");\n }\n this.length = length;\n }\n public void setWidth(double width)\n {\n if ( width <0 || width > 20)\n {\n throw new IllegalArgumentException(\"For input width:0.0\");\n }\n this.width = width;\n }\n \n public double getLength()\n {\n return length;\n } \n \n \n public double getWidth()\n {\n return width;\n } \n \n public double getPerimeter()\n {\n return (length + width)*2 ;\n }\n \n public double getArea()\n {\n return length * width ;\n }\n \n public String Calculations1() {\n \t return String.format(\"%n%.2f is the perimeter %n%.2f is the area\",\n getPerimeter(), getArea());\n }\n public String Calculations() {\n \t return String.format(\"%.2f is the length %n%.2f is the width %n%.2f is the perimeter %n%.2f is the area%n\",\n getLength(), getWidth(),getPerimeter(), getArea());\n }\n}" }, { "alpha_fraction": 0.5949535369873047, "alphanum_fraction": 0.6122177839279175, "avg_line_length": 27.961538314819336, "blob_id": "36a253da9d9d723dea19ab6c1a5e6969a6502551", "content_id": "46c4de595252331cdbde9609e4f504126a706676", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 755, "license_type": "no_license", "max_line_length": 90, "num_lines": 26, "path": "/Operating Systems/Lab_3/lab3_part_6.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//Name: Mandeep Singh\n//Date: 01/27/20\n//Title: Lab3 - Pthreads and inter-process Communication – Pipes\n//Description: Runs two for loops that creates threads based on values of i\n#include <stdio.h>\n#include <stdlib.h>\n#include <pthread.h>\nvoid *go(void *);\n#define NTHREADS 10\npthread_t threads[NTHREADS];\n//notes in observation file\nint main() {\n int i;\n for (i = 0; i < NTHREADS; i++) pthread_create(&threads[i], NULL, go, &i);\n for (i = 0; i < NTHREADS; i++) {\n printf(\"Thread %d returned\\n\", i); pthread_join(threads[i],NULL);\n \n }\n printf(\"Main thread done.\\n\");\n return 0;\n}\n\nvoid *go(void *arg) {\n printf(\"Hello from thread %d with iteration %d\\n\", (int)pthread_self(), *(int *)arg);\n return 0;\n}\n" }, { "alpha_fraction": 0.4990689158439636, "alphanum_fraction": 0.5139665007591248, "avg_line_length": 25.850000381469727, "blob_id": "62f9da21d715b03da4642d8a98c46abc264ba390", "content_id": "12668f644b4f2d7e0015383e134cc71a06d6a45f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1074, "license_type": "no_license", "max_line_length": 86, "num_lines": 40, "path": "/Operating Systems/Lab 8/fifo.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n\ntypedef struct{\n int pageno;\n}ref_page;\n\nint main(int argc, char *argv[]){\n\tint C_SIZE = atoi(argv[1]);\n ref_page cache[C_SIZE];\n char pageCache[100];\n int i, j;\n int totalFaults = 0, totalRequests = 0, currentPos = 0;\n \n for (i = 0; i < C_SIZE; i++)\n cache[i].pageno = -1;\n\n while (fgets(pageCache, 100, stdin)){\n \tint page_num = atoi(pageCache);\n totalRequests++;\n for (j = 0; j < C_SIZE; j++){\n if (page_num == cache[j].pageno)\n break;\n if (j == C_SIZE - 1){\n printf(\"Page %d caused a page fault.\\n\", page_num);\n totalFaults++;\n cache[currentPos].pageno = page_num;\n currentPos++;\n if (currentPos == C_SIZE)\n currentPos = 0;\n }\n }\n }\n\n printf(\"\\n%d Total Page Faults\\n\", totalFaults);\n printf(\"FIFO Hit rate = %f\\n\", (totalRequests-totalFaults)/(double)totalRequests);\n return 0;\n}\n" }, { "alpha_fraction": 0.5735042691230774, "alphanum_fraction": 0.5846154093742371, "avg_line_length": 25.590909957885742, "blob_id": "0d82e79e5bd5beaaf130b222b760bf000878bd0d", "content_id": "64840623895edbab2bd16fb82bad195115196374", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1171, "license_type": "no_license", "max_line_length": 92, "num_lines": 44, "path": "/C++ Data Structures/Homework_2/HW_5/kbag.hpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// kbag.hpp\n// HW_4\n//\n// Created by Mandeep Singh on 4/10/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#ifndef kbag_hpp\n#define kbag_hpp\n\n#include <stdio.h>\n#include<cstdlib>\n#include <iostream>\n\nnamespace std {\n class kbag {\n public:\n // TYPEDEFS and MEMBER CONSTANTS\n typedef int value_type;\n typedef std::size_t size_type;\n static const size_type DEFAULT_CAPACITY = 20;\n kbag(size_type initial_capacity = DEFAULT_CAPACITY);\n ~kbag(){ delete [] data; };\n \n // MODIFICATION MEMBER FUNCTIONS\n void remove(int key);\n void insert(const value_type& entry, int key);\n void reserve(size_type new_capacity);\n \n // CONSTANT MEMBER FUNCTIONS\n void print() const { for(int i = 0; i < capacity; i++){ cout << data[i] << endl; } }\n size_type size() const { return used; }\n size_type cap() const{ return capacity; }\n size_type count(const value_type& target) const;\n \n private:\n value_type *data;\n size_type used;\n size_type capacity;\n };\n // NONMEMBER FUNCTIONS for the kkbag class\n}\n#endif /* kbag_hpp */\n" }, { "alpha_fraction": 0.5197916626930237, "alphanum_fraction": 0.5385416746139526, "avg_line_length": 22.414634704589844, "blob_id": "162e7a6e6f54598bf4a4002e5d11efc13771d536", "content_id": "1f8f7a303ade0968c6d571512b4d79628e07181c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 961, "license_type": "no_license", "max_line_length": 135, "num_lines": 41, "path": "/C++ Data Structures/Lab_2/random.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// random.cpp\n// Lab_2\n//\n// Created by Mandeep Singh on 4/11/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include <stdio.h>\n#include \"random.h\"\n\nusing namespace std;\nusing namespace coen79_lab2;\n\nnamespace coen79_lab2{\n rand_gen::rand_gen(int seed, int multiplier, int increment, int modulus){\n this->seed = seed;\n this->multiplier = multiplier;\n this->increment = increment;\n this->modulus = modulus;\n }\n \n void rand_gen::set_seed(int new_seed){\n seed = new_seed;\n }\n \n int rand_gen::next(){\n if(modulus!=0)\n {\n int next_seed = ((multiplier * seed) + increment) % modulus;\n set_seed(next_seed);\n return seed;\n }\n else\n return 0;\n }\n \n void rand_gen::print_info(){\n cout << \"Seed: \" << seed << \"\\nMultiplier: \" << multiplier << \"\\nIncrement: \" << increment << \"\\nModulus: \" << modulus << endl;\n }\n}\n" }, { "alpha_fraction": 0.5423728823661804, "alphanum_fraction": 0.5617433190345764, "avg_line_length": 21.94444465637207, "blob_id": "8def086987b7b7a0fa560c6fd9b7ad0496efb0b2", "content_id": "0fd57c5429b40994671813d87afe9486e500a34e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 413, "license_type": "no_license", "max_line_length": 53, "num_lines": 18, "path": "/Operating Systems/Lab_9/part3.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[]){\n int MAX = atoi(argv[2]);\n char buff[MAX];\n char dest[MAX];\n FILE *fp = fopen(argv[1], \"rb\");\n char filename[20];\n sprintf(filename, \"%soutput%d.rtf\", argv[1],MAX);\n FILE *wp = fopen(filename,\"wb\");\n while(fread(buff,MAX,1,fp)){\n fwrite(buff, MAX,1,wp);\n }\n fclose(fp);\n fclose(wp);\n return 0;\n}\n" }, { "alpha_fraction": 0.5277044773101807, "alphanum_fraction": 0.7176781296730042, "avg_line_length": 62.33333206176758, "blob_id": "fca80faa1c1e7ec401dd762c2c22b631b411c142", "content_id": "e302667f68dc59deb8b829b93680651d37d32ded", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 379, "license_type": "no_license", "max_line_length": 63, "num_lines": 6, "path": "/SQL Databases/lab6/sql3.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "insert into ACCOUNTS_6 values('a1523','checking',2000.00,'c1');\ninsert into ACCOUNTS_6 values('a2134','saving',5000.00,'c1');\ninsert into ACCOUNTS_6 values('a4378','checking',1000.00,'c2');\ninsert into ACCOUNTS_6 values('a5363','saving',8000.00,'c2');\ninsert into ACCOUNTS_6 values('a7236','checking',500.00,'c33');\ninsert into ACCOUNTS_6 values('a8577','checking',150.00,'c20');" }, { "alpha_fraction": 0.5924921035766602, "alphanum_fraction": 0.6037991642951965, "avg_line_length": 31.02898597717285, "blob_id": "578bb6b08a7d0ef9ddd6d9552557613e2d53a519", "content_id": "3b1c0921e2666def772a029fbff11b00a122ae58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2211, "license_type": "no_license", "max_line_length": 118, "num_lines": 69, "path": "/Computer Networks/Lab_2/server/server.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// Behnam Dezfouli\n// CSEN, Santa Clara University\n//\n\n// This program implements a server that accepts connection from a client and copies the received bytes to a file\n//\n// The input arguments are as follows:\n// argv[1]: Sever's port number\n\n\n\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <errno.h>\n#include <string.h>\n#include <sys/types.h>\n\n\nint main (int argc, char *argv[])\n{\n char message[10] = \"received!\"; // message to be sent to the client when the destination file name is received\n int net_bytes_read; // numer of bytes received over socket\n int socket_fd = 0; // socket descriptor\n int connection_fd = 0; // new connection descriptor\n struct sockaddr_in serv_addr; // Address format structure\n char net_buff[1024]; // buffer to hold characters read from socket\n FILE *dest_file; // pointer to the file that will include the received bytes over socket\n \n \n if (argc < 2) // Note: the name of the program is counted as an argument\n {\n printf (\"Port number not specified!\\n\");\n return 1;\n }\n \n serv_addr.sin_family = AF_INET;\n serv_addr.sin_addr.s_addr = htonl (INADDR_ANY);\n serv_addr.sin_port = htons (atoi (argv[1]));\n \n socket_fd = socket(AF_INET, SOCK_STREAM, 0);\n bind(socket_fd, (const struct sockaddr*)&serv_addr, sizeof (serv_addr));\n listen(socket_fd, 10);\n connection_fd = accept(socket_fd, (struct sockaddr *)NULL, NULL);\n read(connection_fd, net_buff, 10);\n \n dest_file = fopen(net_buff, \"wb\");\n printf(\"Here is the message: %s\\n\", net_buff);\n memset (net_buff, '\\0', sizeof(net_buff));\n \n while((net_bytes_read = read(connection_fd, net_buff, sizeof(net_buff)) > 0)){\n if (net_bytes_read < sizeof (net_buff)){\n fwrite(net_buff, 20, net_bytes_read, dest_file);\n break;\n }\n \n fwrite(net_buff, 20, sizeof (net_buff), dest_file);\n memset(net_buff, '\\0', sizeof(net_buff));\n }\n \n close(connection_fd);\n fclose(dest_file);\n \n return 0;\n}\n\n" }, { "alpha_fraction": 0.5253012180328369, "alphanum_fraction": 0.5469879508018494, "avg_line_length": 18.761905670166016, "blob_id": "861614800462503d1ba9b46b2abe925ce844cbe1", "content_id": "a8191bd9122d3d867579608c7698882849fdbc98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 416, "license_type": "no_license", "max_line_length": 51, "num_lines": 21, "path": "/C++ Data Structures/Homework_1/HW_2/statistician.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// statistician.cpp\n// HW_2\n//\n// Created by Mandeep Singh on 4/9/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include \"statistician.hpp\"\n\nnamespace std {\n \n void statistician::next_number(const double x){\n update_length();\n update_sum(x);\n update_avg(x);\n update_lastNum(x);\n if(x < smallest) { smallest = x; }\n if(x > largest) { largest = x; }\n }\n}\n" }, { "alpha_fraction": 0.5412918925285339, "alphanum_fraction": 0.5535567998886108, "avg_line_length": 27.44186019897461, "blob_id": "e41374088f985dd8d04d6d6cf817338d8ca4251d", "content_id": "5a17d23a1a53e7045f29518a130819bb7e9dc4f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1223, "license_type": "no_license", "max_line_length": 126, "num_lines": 43, "path": "/Java/InvoiceTest/src/InvoiceTest.java", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "import java.util.Scanner;\n\npublic class InvoiceTest {\n\n public static void main(String[] args) {\n \n Invoice invoice1 = new Invoice(\"\", \"\", 0, 0.0);\n \n Scanner input = new Scanner(System.in);\n \n String partNumber;\n String partDescription;\n int quantity;\n double price;\n \n System.out.printf(\"Enter part number: \");\n partNumber = input.nextLine();\n invoice1.setPartNumber(partNumber);\n \n System.out.printf(\"%nEnter part description: \");\n partDescription = input.nextLine();\n invoice1.setPartDescription(partDescription);\n \n System.out.printf(\"%nEnter quantity: \");\n quantity = input.nextInt();\n\n if (quantity > 0)\n {\n invoice1.setQuantity(quantity);\n }\n \n System.out.printf(\"%nEnter price per part: \");\n price = input.nextDouble();\n\n if (price > 0)\n {\n invoice1.setPrice(price);\n }\n \n System.out.printf(\"%n The total price of %d %s %s is $%.2f\\n\",\n invoice1.getQuantity(), invoice1.getPartNumber(), invoice1.getPartDescription() ,invoice1.getInvoiceAmount());\n } \n}\n" }, { "alpha_fraction": 0.5707070827484131, "alphanum_fraction": 0.5808081030845642, "avg_line_length": 25.052631378173828, "blob_id": "19214ebca78283b7c9a7014c1dc0d6e6fa3db091", "content_id": "08b7f1dbe4b81a783a0b08e1611ae9767bb324df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 991, "license_type": "no_license", "max_line_length": 63, "num_lines": 38, "path": "/C++ Data Structures/Homework_1/HW_2/statistician.hpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// statistician.hpp\n// HW_2\n//\n// Created by Mandeep Singh on 4/9/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#ifndef statistician_hpp\n#define statistician_hpp\n\n#include <stdio.h>\n\nnamespace std{\n class statistician{\n private:\n double x;\n double length;\n double lastNum;\n double sum;\n double avg;\n double largest;\n double smallest;\n public:\n void next_number(const double x);\n void update_length(){ length += 1; };\n void update_lastNum(const double x){ lastNum = x; };\n void update_sum(const double x){ sum += x; };\n void update_avg(const double x){ avg = (sum/length); };\n double get_length(){ return length; }\n double get_lastNum(){ return lastNum; }\n double get_sum(){ return sum; }\n double get_avg(){ return avg; }\n double get_smallest(){ return smallest; }\n double get_largest(){ return largest; }\n };\n}\n#endif /* statistician_hpp */\n" }, { "alpha_fraction": 0.5852017998695374, "alphanum_fraction": 0.628923773765564, "avg_line_length": 20.7560977935791, "blob_id": "8c100f8b54d3411e70121d472240267d475a1a13", "content_id": "3297a9f08cb48b8ea7e11375717cd1304461e410", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 892, "license_type": "no_license", "max_line_length": 107, "num_lines": 41, "path": "/Computer Graphics Systems/HW_2/points.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "# object representation \n\nfrom PIL import Image, ImageDraw\nimport math\nimport csv\nimport array as arr\n\n\n\nimg = Image.new('RGB', (1000, 1000))\npixels = img.load()\n# this list hold all vertices\n# you can use append() to add all x, y, z\n# into it. the format could be like this:\n# [[x1, y1, z1], [x2, y2, z2],......]\nvertices = []\n\n#read in face vertices\nwith open('face-vertices.data.txt', 'r') as f:\n reader = csv.reader(f, delimiter=',')\n vertices = list(reader)\n#print(vertices)\n\ndef projectX(x, z):\n locz = 1 - z\n return (1500 * x /locz) + 500\n\ndef projectY(y, z):\n locz = 1 - z\n return (1500 * y/locz)\n\ndef draw_pixel(x,y, color):\n pixels[x,y] = (color,0,0)\n \n\nfor index in vertices:\n print(float(index[0]), float(index[1]),float(index[2]))\n\n draw_pixel(projectX(float(index[0]), float(index[2])), projectY(float(index[1]), float(index[2])), 255)\n\nimg.show()\n" }, { "alpha_fraction": 0.5559701323509216, "alphanum_fraction": 0.6604477763175964, "avg_line_length": 88.33333587646484, "blob_id": "a42eb8abd1ad70c6f09098b549db2558329fe986", "content_id": "80c56cd1de1b75580ef41980413ba4b81ca1ed28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1876, "license_type": "no_license", "max_line_length": 128, "num_lines": 21, "path": "/SQL Databases/HW1/a1_values_mSingh.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "insert into Student values('s10', 'Robert', 'Sunnyvale');\ninsert into Student values('s11', 'John', 'Saratoga');\ninsert into Student values('s12', 'Frank', 'Sunnyvale');\ninsert into Student values('s13', 'Jody', 'Saratoga');\ninsert into Student values('s14', 'Alex', 'Cupertino');\ninsert into Student values('s15', 'Jonathan', 'Sunnyvale');\ninsert into Student values('s16', 'Ali', 'Cupertino');\ninsert into SummerJob values('jbID0', 'Cashier', 'McDonalds', 'Cupertino', '15.00');\ninsert into SummerJob values('jbID1', 'Waiter', 'ChikFilA', 'Sunnyvale', '16.50');\ninsert into SummerJob values('jbID2', 'Waitress', 'ChikFilA', 'Sunnyvale', '16.50');\ninsert into SummerJob values('jbID3', 'Technician', 'AMD', 'Cupertino', '75.00');\ninsert into SummerJob values('jbID4', 'Operator', 'Chevrolet', 'Saratoga', '25.00');\ninsert into SummerJob values('jbID5', 'Clerk', 'CVS', 'Cupertino', '12.00');\ninsert into SummerJob values('jbID6', 'Nurse', 'Kaiser', 'Sunnyvale', '45.00');\ninsert into Student_Work values('s10', 'jbID0', '45', to_date('2019-05-18', 'yyyy-mm-dd'), to_date('2020-01-15', 'yyyy-mm-dd'));\ninsert into Student_Work values('s11', 'jbID1', '25', to_date('2018-08-25', 'yyyy-mm-dd'), to_date('2020-04-13', 'yyyy-mm-dd'));\ninsert into Student_Work values('s12', 'jbID2', '15', to_date('2017-02-12', 'yyyy-mm-dd'), to_date('2019-12-04', 'yyyy-mm-dd'));\ninsert into Student_Work values('s13', 'jbID3', '40', to_date('2019-12-09', 'yyyy-mm-dd'), to_date('2020-03-04', 'yyyy-mm-dd'));\ninsert into Student_Work values('s14', 'jbID4', '30', to_date('2016-05-02', 'yyyy-mm-dd'), to_date('2019-07-25', 'yyyy-mm-dd'));\ninsert into Student_Work values('s15', 'jbID5', '69', to_date('2019-07-17', 'yyyy-mm-dd'), to_date('2020-01-15', 'yyyy-mm-dd'));\ninsert into Student_Work values('s16', 'jbID6', '37', to_date('2019-03-13', 'yyyy-mm-dd'), to_date('2020-03-17', 'yyyy-mm-dd'));\n" }, { "alpha_fraction": 0.5471105575561523, "alphanum_fraction": 0.554648220539093, "avg_line_length": 36.904762268066406, "blob_id": "0309cec3d990a56f5800eec3bd118b97b8beffc5", "content_id": "899b1437a04a7dcaec9a9f258b7daaf7942d721d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1592, "license_type": "no_license", "max_line_length": 96, "num_lines": 42, "path": "/Java/courseSelector/src/courseselector/GUISelection.java", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "package courseselector;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport javax.swing.event.*;\n\npublic class GUISelection extends JFrame{\n \n private JList selectCourses;\n private JList displayCourses;\n private JButton moveCourses;\n private static String[] courses = {\"course1\", \"course2\", \"course3\", \"course4\", \"course5\"};\n \n public GUISelection()\n {\n super(\"title\");\n setLayout(new FlowLayout());\n \n selectCourses = new JList(courses);\n selectCourses.setVisibleRowCount(5);\n selectCourses.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);\n add(new JScrollPane(selectCourses));\n \n moveCourses = new JButton(\"Select\");\n moveCourses.addActionListener(\n new ActionListener(){\n public void actionPerformed(ActionEvent event){\n displayCourses.setListData(selectCourses.getSelectedValues());\n }\n }\n );\n \n add(moveCourses);\n displayCourses = new JList();\n displayCourses.setVisibleRowCount(5);\n displayCourses.setFixedCellWidth(100);\n displayCourses.setFixedCellHeight(15);\n displayCourses.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);\n add(new JScrollPane(displayCourses));\n }\n}\n" }, { "alpha_fraction": 0.7821229100227356, "alphanum_fraction": 0.7821229100227356, "avg_line_length": 29, "blob_id": "39e01ecdca466a2f85235baeaaa1ac6123356fb9", "content_id": "43024e77d966a20899bb3e3db02ab86f8b1b87d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 179, "license_type": "no_license", "max_line_length": 93, "num_lines": 6, "path": "/SQL Databases/lab8/psql1.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "Create or Replace procedure addMovieReview (v_movieName IN varchar, v_comment IN varchar) AS \nBEGIN \n\tinsert into MovieReviews values (v_movieName,v_comment);\nEND;\n/ \nshow errors;" }, { "alpha_fraction": 0.5960665941238403, "alphanum_fraction": 0.632375180721283, "avg_line_length": 27.7391300201416, "blob_id": "7e4f1ef272ef017b43e81a54b2331fdc045d3313", "content_id": "a51ec6117d67ed02559e0f4745b890360e517f7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 662, "license_type": "no_license", "max_line_length": 124, "num_lines": 23, "path": "/C++ Data Structures/Lab_1/part4b.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// part4b.cpp\n// Lab_1\n//\n// Created by Mandeep Singh on 4/4/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n//There was no + 1 to start in line 22 which would cause a bad access error since the recursive functionality would not work\n#include<iostream>\n#include \"part4b.hpp\"\n\nvoid part4b(){\n char sentence[50];\n std::cout << \"Enter a string: \\n\";//Enter: I attend Santa Clara University\n std::cin.getline(sentence, 50);\n std::cout <<\"The string you entered contains \" << str_len(sentence,0) << \" characters.\" << std::endl;\n}\n\nint str_len(char s[],int start){\n if(s[start] =='\\0')\n return 0;\n return 1 + str_len(s, start + 1);\n}\n" }, { "alpha_fraction": 0.5534883737564087, "alphanum_fraction": 0.6186046600341797, "avg_line_length": 14.357142448425293, "blob_id": "89346e38aa791f2878e75dd09ccfac608270d0a0", "content_id": "f7d1ddfbb005b11787088196227dea44f0bee925", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 216, "license_type": "no_license", "max_line_length": 49, "num_lines": 14, "path": "/C++ Data Structures/Lab_1/part4a.hpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// part4a.hpp\n// Lab_1\n//\n// Created by Mandeep Singh on 4/4/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#ifndef part4a_hpp\n#define part4a_hpp\n\n#include <stdio.h>\nvoid part4a();\n#endif /* part4a_hpp */\n" }, { "alpha_fraction": 0.7179693579673767, "alphanum_fraction": 0.723609983921051, "avg_line_length": 34.400001525878906, "blob_id": "1fbb2579e0c47fb70a2b01245659c8ab64143d32", "content_id": "eb54379df07d07803ecdacd571a744d6437f6128", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1241, "license_type": "no_license", "max_line_length": 140, "num_lines": 35, "path": "/Computer Networks/Lab_5/SMTPClient-secure-gmail.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "\n# Behnam Dezfouli\n# CSEN, Santa Clara University\n\n# This program implements a simple smtp mail client to send an email to a local smtp server\n# the program runs the ping command, and emails the result using smtp.gmail.com\n\n# NOTE: Do not forget to allow login from less secure apps in your gmail account. Otherwise gmail will complain about username and password.\n\n\nimport smtplib, ssl\nimport subprocess\n\nport = 465 # For SSL\nemail_address = str(input(\"Please enter your email address: \"))\npassword = str(input(\"Please enter your password: \"))\nreceiver_email = str(input(\"Please enter receiver's email address: \"))\n\n# ping google.com and save the result\n# STUDENT WORK\nping_response = subprocess.Popen([\"ping\", \"-c\", \"3\",\n \"google.com\"], stdout=subprocess.PIPE).stdout.read()\nprint(ping_response)\n\nprint( '\\nNow contacting the mail server...')\n# STUDENT WORK\nserver = smtplib.SMTP_SSL('smtp.gmail.com', 465)\nserver.ehlo()\nserver.login(email_address, password)\n\nprint( '\\nSending email...')\n# STUDENT WORK\nmessage = 'Subject: Server ping result!\\n\\nI have pinged google.com and the result is attached to this email:\\n\\n' + str(ping_response)\nprint(message)\n\nserver.sendmail(email_address, receiver_email, message)\n\n" }, { "alpha_fraction": 0.2934472858905792, "alphanum_fraction": 0.3504273593425751, "avg_line_length": 24.071428298950195, "blob_id": "b8da08018368d9515c22b5c49d31e7c554d9fc45", "content_id": "73f8b16877fd88e88d24f9f5f6f5bbd18cdb4f40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 351, "license_type": "no_license", "max_line_length": 87, "num_lines": 14, "path": "/Java/example/src/Example.java", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "public class Example {\n public static void main(String[] args) {\n \n int n = 0;\n \n System.out.printf(\"N 10*N 100*N 1000*N\\n\");\n \n while(n < 5)\n {\n n++; \n System.out.printf(\"%d %d %d %d\\n\", n, 10*n, 100*n, 1000*n); \n }\n } \n}\n" }, { "alpha_fraction": 0.7529880404472351, "alphanum_fraction": 0.7529880404472351, "avg_line_length": 27, "blob_id": "2595e2990ae73d05bb8edf6e9aa9b049de9f54b3", "content_id": "c0388631e5b214ceb53c39c647e41907204fc200", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 251, "license_type": "no_license", "max_line_length": 61, "num_lines": 9, "path": "/SQL Databases/midterm2_mSingh/extra_credit_mSingh/query_mSingh.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh Extra Credit*/\nSelect * From Book;\nSelect * From Applicant;\nSelect * From BooksRead;\nSelect A.ANAME\nFrom Applicant A, BooksRead R\nWhere A.applicantid = R.applicantid\nGroup By ANAME\nHaving count(R.BookID)= (select count(B.BookID) From Book B);" }, { "alpha_fraction": 0.7380496859550476, "alphanum_fraction": 0.7514340281486511, "avg_line_length": 39.30769348144531, "blob_id": "cbfc9fcd23ad29b9828c7726c3a037bf484e2bd9", "content_id": "0ae55b33fb6c04140392068386b65c26780f2c51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 523, "license_type": "no_license", "max_line_length": 125, "num_lines": 13, "path": "/SQL Databases/lab6/psql3.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "Create Or Replace Trigger Acct_Cust_Trig\nAFTER INSERT ON Accounts_6\nFOR EACH ROW\nBEGIN\n/*If the custno is already in the Totals_6 table, the update will succeed */\nupdate totals_6\nset totalAmount = totalAmount + :new.amount\nwhere custno = :new.custno;\n/*If the custno is not in the Totals_6 table, we insert a row intoTotals_6 table. Complete the missing part in te subquery */\ninsert into totals_6 (select :new.custno, :new.amount from dual\n where not exists (select * from TOTALS_6 where custno = :new.custno));\nEND;\n/" }, { "alpha_fraction": 0.6474359035491943, "alphanum_fraction": 0.6559829115867615, "avg_line_length": 15.571428298950195, "blob_id": "9a44b9ae425fc8e0a33466901b0c4363cfc66b60", "content_id": "266151f7e48b560bba38b330eb74b2f523b51042", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 468, "license_type": "no_license", "max_line_length": 42, "num_lines": 28, "path": "/Computer Networks/Lab_6/tfv1.h", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "\n\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/select.h>\n#include <sys/time.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <string.h>\n\n#define SIZE 100\n\n// Header format\ntypedef struct\n{\n int\tseq_ack;\n int len; // for ACK packets len = 0\n int checksum;\n} HEADER;\n\n\n// Packet format\ntypedef struct\n{\n HEADER\theader;\n char\tdata[SIZE]; // data in the packet\n} PACKET;\n\n\n" }, { "alpha_fraction": 0.39788293838500977, "alphanum_fraction": 0.4178082048892975, "avg_line_length": 26.689655303955078, "blob_id": "025ca60475f9d9a5e77a3bada4a18080a8cfb76b", "content_id": "4a53ee2afc1c4f11bf6a872d086b57bf8be04034", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1606, "license_type": "no_license", "max_line_length": 68, "num_lines": 58, "path": "/Java/Line Application/src/LineApplication.java", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "import java.util.Scanner;\npublic class LineApplication {\n public static void main(String[] args) {\n Scanner input = new Scanner(System.in);\n \n int num1= 0;\n int num2= 0;\n int num3= 0;\n int num4= 0;\n int num5 =0;\n int number;\n \n for (int counter = 1; counter <= 5; counter++) {\n System.out.println(\"Enter an Integer:\");\n number = input.nextInt();\n switch (counter) {\n case 1:\n num1 = number;\n break;\n \n case 2:\n num2 = number;\n break;\n case 3:\n num3 = number;\n break;\n case 4:\n num4 = number;\n break;\n case 5:\n num5 = number;\n break;\n }\n \n } \n \n for (int asterisk = 1 ; asterisk <= num1; asterisk++) {\n System.out.print(\"*\");\n }\n System.out.println();\n for (int asterisk = 1 ; asterisk <= num2; asterisk++) {\n System.out.print(\"*\");\n }\n System.out.println();\n for (int asterisk = 1 ; asterisk <= num3; asterisk++) {\n System.out.print(\"*\");\n }\n System.out.println();\n for (int asterisk = 1 ; asterisk <= num4; asterisk++) {\n System.out.print(\"*\");\n }\n System.out.println();\n for (int asterisk = 1 ; asterisk <= num5; asterisk++) {\n System.out.print(\"*\");\n }\n System.out.println();\n }\n}\n" }, { "alpha_fraction": 0.5005170702934265, "alphanum_fraction": 0.5160289406776428, "avg_line_length": 23.174999237060547, "blob_id": "29a0062be3eae2fa6b93b2d76ae608e06f5a92e3", "content_id": "82db45465d9653b0b6e34662302a430b2995ea17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 968, "license_type": "no_license", "max_line_length": 62, "num_lines": 40, "path": "/C++ Data Structures/Homework_2/HW_3/bag.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// bag.cpp\n// HW_4\n//\n// Created by Mandeep Singh on 4/10/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include \"bag.hpp\"\n#include <iostream>\n#include <algorithm> // Provides copy function\n#include <cassert> // Provides assert function\nnamespace std {\n const bag::size_type bag::CAPACITY;\n \n void bag::remove(int key){\n if(data[key] != -1)\n data[key] = -1;\n else\n cout << \"No key exists here\" << endl;\n }\n \n void bag::insert(const value_type& entry, int key){\n assert(size() < CAPACITY);\n if(data[key] == -1){\n data[key] = entry;\n used++;\n }else\n cout << \"This key already has an item\" << endl;\n }\n \n bag::size_type bag::count(const value_type& target) const{\n size_type answer;\n size_type i;\n answer = 0;\n for (i = 0; i < used; ++i)\n if (target == data[i]) ++answer;\n return answer;\n }\n}\n" }, { "alpha_fraction": 0.7302504777908325, "alphanum_fraction": 0.7360308170318604, "avg_line_length": 38.92307662963867, "blob_id": "37abf6ca8732c290f5689bec1ee6201d2befbc59", "content_id": "a671c46a00e82e587e2a7b4d2b928d72032e6d81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1042, "license_type": "no_license", "max_line_length": 70, "num_lines": 26, "path": "/SQL Databases/lab5/part1/psql4.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "CREATE or REPLACE procedure saveCountByTitle \nAS \nl_advisor_cnt integer := 0;\nl_director_cnt integer := 0;\nl_assistant_cnt integer := 0;\nl_manager_cnt integer := 0;\nl_supervisor_cnt integer := 0;\nl_intern_cnt integer := 0;\nBEGIN \nl_advisor_cnt := countByTitle('advisor'); \nl_director_cnt := countByTitle('director');\nl_assistant_cnt := countByTitle('assistant');\nl_manager_cnt := countByTitle('manager');\nl_supervisor_cnt := countByTitle('supervisor');\nl_intern_cnt := countByTitle('intern');\ndelete from EmpStats; -- Any previously loaded data is deleted \n/* inserting count of employees with title, ‘advisor’.*/ \ninsert into EmpStats values ('advisor', l_advisor_cnt, SYSDATE); \ninsert into EmpStats values ('director', l_director_cnt, SYSDATE);\ninsert into EmpStats values ('assistant', l_assistant_cnt, SYSDATE);\ninsert into EmpStats values ('manager', l_manager_cnt, SYSDATE);\ninsert into EmpStats values ('supervisor', l_supervisor_cnt, SYSDATE);\ninsert into EmpStats values ('intern', l_intern_cnt, SYSDATE);\nEND; \n/ \nShow errors; " }, { "alpha_fraction": 0.48316407203674316, "alphanum_fraction": 0.5120256543159485, "avg_line_length": 31.824562072753906, "blob_id": "6dd14c905b91635d8c322156eeab5c67da6925c0", "content_id": "f487a73bc801f387b9acd907826d14d8d9553aa0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1871, "license_type": "no_license", "max_line_length": 72, "num_lines": 57, "path": "/Artificial Intelligence/Lab_2/vaccum.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "def vaccum(test_input):\n output_moves = []\n current_position = test_input[2]\n cost = 0\n while(test_input[0] == \"Dirty\" or test_input[1] == \"Dirty\"):\n if(test_input[0] == \"Clean\" and test_input[1] == \"Clean\"):\n break\n if(current_position == 0):\n if(test_input[0] == \"Dirty\"):\n output_moves.append(\"Sucking Dirt\")\n test_input[0] = \"Clean\"\n cost += 1\n elif(test_input[0] == \"Clean\" and test_input[1] == \"Dirty\"):\n output_moves.append(\"Moving right\")\n current_position = 1\n cost += 1\n elif(current_position == 1):\n if(test_input[1] == \"Dirty\"):\n output_moves.append(\"Sucking dirt\")\n test_input[1] = \"Clean\"\n cost += 1\n elif(test_input[1] == \"Clean\" and test_input[0] == \"Dirty\"):\n output_moves.append(\"Moving left\")\n current_position = 0\n cost += 1\n print(output_moves)\n print(\"Cost:\", cost)\n\n\ndef testCase():\n test1 = [\"Clean\", \"Clean\", 0]\n test2 = [\"Clean\", \"Clean\", 1]\n test3 = [\"Clean\", \"Dirty\", 0]\n test4 = [\"Clean\", \"Dirty\", 1]\n test5 = [\"Dirty\", \"Clean\", 0]\n test6 = [\"Dirty\", \"Clean\", 1]\n test7 = [\"Dirty\", \"Dirty\", 0]\n test8 = [\"Dirty\", \"Dirty\", 1]\n\n print(\"Clean, Clean, Left:\")\n result1 = vaccum(test1)\n print(\"\\nClean, Clean, Right:\")\n result2 = vaccum(test2)\n print(\"\\nClean, Dirty, Left:\")\n result3 = vaccum(test3)\n print(\"\\nClean, Dirty, Right:\")\n result4 = vaccum(test4)\n print(\"\\nDirty, Clean, Left:\")\n result5 = vaccum(test5)\n print(\"\\nDirty, Clean, Right:\")\n result6 = vaccum(test6)\n print(\"\\nDirty, Dirty, Left:\")\n result7 = vaccum(test7)\n print(\"\\nDirty, Dirty, Right:\")\n result8 = vaccum(test8)\n\ntestCase()\n" }, { "alpha_fraction": 0.4921875, "alphanum_fraction": 0.5044642686843872, "avg_line_length": 21.9743595123291, "blob_id": "424342f739d9024d8ebae877c8173caa5fe12c44", "content_id": "59bf1b0f84354ac523a21dfd71f8cdaa5c85bc4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 897, "license_type": "no_license", "max_line_length": 64, "num_lines": 39, "path": "/C++ Data Structures/Homework_1/HW_1/3d_point.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// 3d_point.cpp\n// HW_1\n//\n// Created by Mandeep Singh on 4/7/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include \"3d_point.hpp\"\n#include <cmath>\n\nnamespace std{\n point::point(double init_x, double init_y, double init_z){\n x = init_x;\n y = init_y;\n z = init_z;\n }\n \n void point::shift(double x_amt, double y_amt, double z_amt){\n x += x_amt;\n y += y_amt;\n z += z_amt;\n }\n \n void point::rotate_x(double degrees){\n y = (y)*cos(degrees) - (z)*sin(degrees);\n z = (y)*sin(degrees) + (z)*cos(degrees);\n }\n \n void point::rotate_y(double degrees){\n x = (x)*cos(degrees) + (z)*sin(degrees);\n z = (-x)*sin(degrees) + (z)*cos(degrees);\n }\n \n void point::rotate_z(double degrees){\n x = (x)*cos(degrees) - (y)*sin(degrees);\n y = (x)*sin(degrees)+ (y)*cos(degrees);\n }\n}\n" }, { "alpha_fraction": 0.7454545497894287, "alphanum_fraction": 0.7545454502105713, "avg_line_length": 26.58333396911621, "blob_id": "1343ac99588d6e591b11e889dfc6be9a4274cd30", "content_id": "edb67341b558de5eb9c903809b4d2a69a4422df9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 330, "license_type": "no_license", "max_line_length": 83, "num_lines": 12, "path": "/COEN_178_Final_Project_mSingh/Functions/setShippingDate.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh*/\n/*COEN 178 Final Project*/\n/*setShippingDate Function*/\nCREATE OR REPLACE procedure setShippingDate (l_order in varchar, l_date in date)\nis\n/*Update the shipping date where the orderid is the one provided in function call*/\nbegin\n\tupdate itemorder\n\t\tset shippeddate = l_date where orderid = l_order;\nend;\n/\nshow errors;" }, { "alpha_fraction": 0.46195653080940247, "alphanum_fraction": 0.4748023748397827, "avg_line_length": 31.645160675048828, "blob_id": "998bd80ba9daadc5e7ce64b2acff206d9b870843", "content_id": "7fa69ca01a24800b1777fe01e3b7eedbbbe6dac3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2025, "license_type": "no_license", "max_line_length": 245, "num_lines": 62, "path": "/C++ Data Structures/Homework_1/HW_1/main.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// HW_1\n//\n// Created by Mandeep Singh on 4/7/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include <iostream>\n#include \"3d_point.hpp\"\n\nusing namespace std;\n\nint main(int argc, const char * argv[]) {\n point mypoint;\n \n int in = 0;\n \n cout << \"Please enter a number 1 - 5 to perform an operation:\\n1 - Shift your point\\n2 - Rotate about the x-axis\\n3 - Rotate about the y-axis\\n4 - Rotate aboute the z-axis\\n5 - Get the coordinates of your point\\nOr enter -1 to exit\" << endl;\n \n while(in != -1){\n cout << \"\\nPlease enter a value: \" << endl;\n cin >> in;\n \n if(in == -1){\n cout << \"Exiting...\" << endl;\n }else if(in == 1){\n int x, y, z;\n cout << \"\\nEnter a x value: \" << endl;\n cin >> x;\n cout << \"\\nEnter a y value: \" << endl;\n cin >> y;\n cout << \"\\nEnter a z value: \" << endl;\n cin >> z;\n mypoint.shift(x, y, z);\n cout << \"\\nYour point has been shifted\" << endl;\n }else if(in == 2){\n int degree;\n cout << \"\\nEnter the degree value: \" << endl;\n cin >> degree;\n mypoint.rotate_x(degree);\n cout << \"\\nYour point has been rotated\" << endl;\n }else if(in == 3){\n int degree;\n cout << \"\\nEnter the degree value: \" << endl;\n cin >> degree;\n mypoint.rotate_y(degree);\n cout << \"\\nYour point has been rotated\" << endl;\n }else if(in == 4){\n int degree;\n cout << \"\\nEnter the degree value: \" << endl;\n cin >> degree;\n mypoint.rotate_z(degree);\n cout << \"\\nYour point has been rotated\" << endl;\n }else if(in == 5){\n cout << \"\\nThe coordinates are x: \" << mypoint.get_x() << \" y: \" << mypoint.get_y() << \" z: \" << mypoint.get_z() << endl;\n }else{\n cout << \"\\nPlease enter a valid input\\n\";\n }\n }\n EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.7336065769195557, "alphanum_fraction": 0.7663934230804443, "avg_line_length": 19.33333396911621, "blob_id": "099f3ee107117bc073952fce1fef8345aa84e239", "content_id": "d440841fbdf0446342ff2c7a0d206533de496874", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 488, "license_type": "no_license", "max_line_length": 53, "num_lines": 24, "path": "/SQL Databases/HW1/a1_tables_mSingh.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "create table Student(\nstudentId char(3),\nname varchar(20),\ncity varchar(15),\nPRIMARY KEY(studentID)\n);\ncreate table SummerJob(\njobId char(5),\njobTitle varchar(25),\ncompany varchar(20),\ncity varchar(20),\nhrlyPay decimal(4,2),\nPRIMARY KEY(jobId)\n);\ncreate table Student_Work(\nstudentId char(3),\njobId char(5),\nhrsWorked INT,\nStartDate DATE,\nEndDate DATE,\nPRIMARY KEY(studentId, jobId),\nFOREIGN KEY(studentId) REFERENCES Student(studentId),\nFOREIGN KEY(jobId) REFERENCES SummerJob(jobId)\n);\n" }, { "alpha_fraction": 0.7428571581840515, "alphanum_fraction": 0.800000011920929, "avg_line_length": 70, "blob_id": "8910d57b83448140445c0eb5b58d50c9b41bbaa8", "content_id": "103d2df0ed749293d258bfb6c4ff16e1fd8c1a1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 70, "license_type": "no_license", "max_line_length": 70, "num_lines": 1, "path": "/SQL Databases/Extra_Credit_1/sql1.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "CREATE TABLE Supplier(SNO integer,sname varchar(20),city varchar(20));" }, { "alpha_fraction": 0.5364860892295837, "alphanum_fraction": 0.5508925914764404, "avg_line_length": 37, "blob_id": "ca4a5f89b1756260133086c70b8c8822892dbf4f", "content_id": "2700a5d56e5228b21a73465a30586cd15edc271c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3193, "license_type": "no_license", "max_line_length": 195, "num_lines": 84, "path": "/Computer Networks/Lab_4/webserver.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "\n# Behnam Dezfouli\n# CSEN, Santa Clara University\n\n# This program implements a simple web server that serves html and jpg files\n\n# Input arguments:\n# argv[1]: Sever's port number\n\n\nfrom socket import * # Import socket module\nimport datetime # Import datetime module\nimport sys # To terminate the program\n\n\nif __name__ == \"__main__\":\n\n # check if port number is provided\n# if len(sys.argv) != 2:\n# print 'Usage: python %s <PortNumber>' % (sys.argv[0])\n# sys.exit()\n\n \n # STUDENT WORK\n serverSocket = socket(AF_INET, SOCK_STREAM)\n serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\n serverPort = int(sys.argv[1])\n serverSocket.bind((\"\", serverPort))\n serverSocket.listen(1)\n\n # Server should be up and running and listening to the incoming connections\n while True:\n print('The server is ready to respond to incoming requests...')\n\n\n # STUDENT WORK\n connectionSocket, addr = serverSocket.accept()\n message = connectionSocket.recv(1024)\n print(message)\n \n try:\n # STUDENT WORK\n file_name = message.split('/')\n print(file_name)\n temp = file_name[1].split(' ')\n print(temp)\n file = str(temp[0])\n file_extension = temp[0].split('.')\n print(file_extension)\n if (file_extension[1] == 'html'):\n temp = 0\n response_headers = 'Content-Type: text/html; encoding=utf8'\n elif (file_extension[1] == 'jpg'):\n temp = 1\n response_headers = 'Content-Type: image/jpeg; encoding=utf8'\n else:\n print('Invalid file type, we only support html and jpg!')\n break\n\n\n # STUDENT WORK\n t = str(datetime.datetime.now())\n if(temp == 0):\n f = open(file, 'rb')\n outputdata = f.read()\n header = 'HTTP/1.1 200 OK \\nDate: ' + t + '\\nServer: Shreks Dank Swamp\\n' + response_headers + '\\nContent Length: ' + str(len(outputdata)-1) +'\\n\\n'\n header += outputdata\n elif(temp == 1):\n f = open(file, 'rb')\n outputdata = f.read()\n header = 'HTTP/1.1 200 OK \\nDate: ' + t + '\\nServer: Shreks Dank Swamp\\n' + response_headers + '\\nContent Length: ' + str(len(outputdata)-1) +'\\n\\n'\n header += outputdata\n \n print(header)\n connectionSocket.send(header)\n connectionSocket.close()\n #Raised when an I/O operation (such as a print statement, the built-in open() function or a method of a file object) fails for an I/O-related reason, e.g., \"file not found\" or \"disk full\"\n except IOError:\n # STUDENT WORK\n print('404 NOT FOUND')\n header = 'HTTP/1.1 200 OK \\nDate: ' + t + '\\nServer: Shreks Dank Swamp\\n' + 'Content-Type: text/plain; encoding=utf8' + '\\nContent Length: ' + str(len(outputdata)-1) +'\\n\\n'\n errorMessage = '404 NOT FOUND'\n header += errorMessage\n connectionSocket.send(header)\n connectionSocket.close()\n" }, { "alpha_fraction": 0.7470511198043823, "alphanum_fraction": 0.7627785205841064, "avg_line_length": 26.727272033691406, "blob_id": "47df5f9618a125beb2e48e14dd3abc820f93a5ce", "content_id": "2fa0b6579a0710f458ae9eab2354a80bfd4aef0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1526, "license_type": "no_license", "max_line_length": 326, "num_lines": 55, "path": "/SQL Databases/lab7/CreateEmpReport.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "\n-- the size of one page\nSET PAGESIZE 20\n-- the size of a line\nSET LINESIZE 120\n\nBREAK ON TODAY\n\n/*\nTo use the system date in the header or elsewhere in the report is to execute a query that returns the current date and use the NEW_VALUE clause of the COLUMN command to get that date into a substitution variable. That substitution variable sticks around for the duration of the session and can be used in subsequent reports.\t\n*/\n\n/* The NEW_VALUE option of the COLUMN command is used to update the user variable report_date with the current value of SYSDATE as returned from the database. \n*/\nCOLUMN TODAY NEW_VALUE report_date\nSELECT TO_CHAR(SYSDATE, 'fmMonth DD, YYYY') TODAY\nFROM DUAL;\n\n-- Sets terminal output off\n\nset termout off\n-- Show the title of your report at the top of the page\n\nttitle center \"Employee Listing \" report_date skip 2\n\n /* Places and formats a specified title at the bottom of each report page */\n\nbtitle center \"COEN 178 Lab-7\"\n\n--After the SPOOL command, anything entered or displayed on\n-- standard output is written to the spool file, report.html.\n\nspool EmpReport.txt\n\n-- change column headings and format number columns\ncolumn empname format a20 heading \"Name\"\ncolumn deptId format a5 heading \"Department\"\ncolumn salary format $9999999,999 heading \"Salary\"\n\n-- Run the query\nselect empname,\n deptid,\n salary\nfrom EMP7;\nspool off;\n\n--clear all formatting commands ...\n\nCLEAR COLUMNS\nCLEAR BREAK\nTTITLE OFF \nBTITLE OFF\nSET VERIFY OFF \nSET FEEDBACK OFF\nSET RECSEP OFF\nSET ECHO OFF\n" }, { "alpha_fraction": 0.6556776762008667, "alphanum_fraction": 0.6593406796455383, "avg_line_length": 25, "blob_id": "16e327f8aae03997ea058a387c728073bdbfb22d", "content_id": "691b6b7545a8c473f3ba959fa137c83df9217703", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 546, "license_type": "no_license", "max_line_length": 81, "num_lines": 21, "path": "/Java/JavaApplication1/src/javaapplication1/JavaApplication1.java", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "package javaapplication1;\nimport java.util.Scanner;\n\npublic class JavaApplication1 {\n public static void main(String[] args)\n {\n \n Scanner input = new Scanner(System.in);\n \n Account myAccount = new Account();\n \n System.out.printf(\"Initial name is: %s%n%n\", myAccount.getName());\n \n System.out.println(\"Please enter the name: \");\n String theName = input.nextLine();\n myAccount.setName(theName);\n System.out.println();\n \n System.out.printf(\"Name in object myAccount is:%s%n%n\", myAccount.getName());\n}\n}\n" }, { "alpha_fraction": 0.6968325972557068, "alphanum_fraction": 0.7239819169044495, "avg_line_length": 21.200000762939453, "blob_id": "86a368147b2b88a9e7993edb6ef822bd36510268", "content_id": "d276a742414e14f04459ecac7c6dc30e725d858f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 221, "license_type": "no_license", "max_line_length": 67, "num_lines": 10, "path": "/SQL Databases/lab6/psql5.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "Create Or Replace Trigger NoUpdatePK_trig\nAfter UPDATE ON BANKCUST_6\nFor each row\nBEGIN \n if updating ('custno') then\n raise_application_error (-20999,'Cannot update a Primary Key');\n End if;\nEND;\n/\nshow errors;" }, { "alpha_fraction": 0.49152541160583496, "alphanum_fraction": 0.5461393594741821, "avg_line_length": 20.239999771118164, "blob_id": "27fbb3ef2d041f6219d6edc8a167f8fca5e248b6", "content_id": "552a86a69dbd0686cfc7089782f19fbd69ba8f2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 532, "license_type": "no_license", "max_line_length": 51, "num_lines": 25, "path": "/C++ Data Structures/Homework_2/HW_5/main.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// HW_5\n//\n// Created by Mandeep Singh on 4/18/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include <iostream>\n#include \"kbag.hpp\"\n#include \"sequence1.hpp\"\n#include \"set.hpp\"\nusing namespace std;\nint main(int argc, const char * argv[]) {\n kbag k1;\n kbag k2(32);\n cout<< k1.cap() << \" \" << k2.cap() << endl;\n sequence s1;\n sequence s2(17);\n cout<< s1.cap() << \" \" << s2.cap() << endl;\n set set1;\n set set2(15);\n cout<< set1.cap() << \" \" << set2.cap() << endl;\n EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.5808544158935547, "alphanum_fraction": 0.5859986543655396, "avg_line_length": 35.05644989013672, "blob_id": "b99fe82fab5baccc2b5a2e5cff0ef0983da1e171", "content_id": "db49154c0a5514f25fb027a5129d2b19a13d660d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4471, "license_type": "no_license", "max_line_length": 119, "num_lines": 124, "path": "/C Data Structures/Term_Project/application_1_sorted/dataset.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"dataset.h\" //Import libraries for usage\n\ntypedef struct set{ //Define our struct set\n int *data;//Pointer to an array of integers\n int length; //Length of array\n int count; //Number of elements in array\n}SET;\n\nstatic int mybsearch(SET *sp, int elt, bool *found);//Initialize our private search function\n\n//O(n)\nSET *createDataSet(int maxElts){ //Creates out set using variables initialized in struct set\n SET *sp;\n sp = malloc(sizeof(SET)); //Allocate memory for set\n assert(sp != NULL);\n sp -> count = 0; //Set count to 0\n sp -> length = maxElts; //Set length to maxElts\n sp -> data = malloc(sizeof(int*)* maxElts); //Allocate memory for array data\n assert(sp -> data != NULL);\n for(int i = 0; i < sp -> length; i++){\n sp -> data[i] = 0; //Set all values in data to 0\n }\n return sp;\n}\n\n//O(1)\nvoid destroyDataSet(SET *sp){\n assert(sp != NULL);//Checking to see if array elts are NULL\n free(sp -> data); //Free array data\n free(sp); //Free set\n printf(\"All records successfully destroyed\\n\");\n}\n\n//O(n) for worst case\nvoid addElement(SET *sp, int age, int ID){\n assert(sp != NULL);\n bool found = false;\n int index = mybsearch(sp, age, &found); //O(logn) search func\n \n for(int i = sp -> count; i > index; i--)\n sp -> data[i] = sp -> data[i-1];//Shift up elts in array\n sp -> data[index] = age;//Insert elt to respective index\n sp -> count++;//Increase count by 1 to account for new elt\n}\n\n//O(n) for worst case\nvoid removeElements(SET *sp, int age){\n assert(sp != NULL);\n \n bool found = false;\n int exist = mybsearch(sp, age, &found);//Use to check if age even exists so if it doesn't worse case is O(logn)\n if(true){\n int firstIndex, lastIndex;\n int j = 0;//Used to count how many repetitions of age there are\n for(int i = 0; i < sp -> count; i++){\n if(sp -> data[i] == age){\n j++; //increment j\n }\n if(sp -> data[i] != age && j != 0){\n lastIndex = i - 1; //Last index with age\n firstIndex = i - j; //First index with age\n break;\n }\n }\n for(int k = lastIndex + 1; k < sp -> count; k++){\n sp -> data[k] = sp -> data[firstIndex]; //Shifting down\n printf(\"Record was found and deleted\\n\");\n firstIndex++; //Increment so every index with age is shifted over\n sp -> count--; //Decrement to account for deleted elt\n }\n }else\n printf(\"No records with that age found\\n\");\n}\n\n//O(logn)\nvoid searchAge(SET *sp, int age){\n assert(sp != NULL);\n \n bool found = false; //Initialize boolean\n int index = mybsearch(sp, age, &found);//Utilizing binary search\n if(false){\n printf(\"No student associated with this age: %d\\n\", age); //No IDs associated with age\n }else{\n printf(\"Student ID: %d\\nStudent Age: %d\\n\", index, age); //There is ID(s) associated with age\n }\n}\n\n//O(1)\n//Since this is a sorted array, largest age is at the end and smallest is at the beginning\nvoid maxAgeGap(SET *sp){\n if(sp -> count <= 0) //If count <= 0, there are no records\n printf(\"There are no student records\\n\");\n else{\n int j = sp -> data[sp -> count - 1];//j is largest age\n int i = sp -> data[0]; //i is smallest age\n int ageGap = j - i; //ageGap is largest - smallest\n printf(\"The max age gap is %d\\n\", ageGap);\n }\n}\n\n//O(logn)\nstatic int mybsearch(SET *sp, int elt, bool *found){\n assert(sp != NULL);\n int lo, hi, mid;//initialize variables\n lo = 0, hi = sp -> count - 1;//Give two variables values\n while(lo <= hi){\n mid = (hi + lo)/2;\n if(elt == (sp -> data[mid])){ //Compare the strings elt and all the elts in data[] to see if there is any match\n *found = true;//If there is found is true and mid is returned since that is the index where it was found\n return mid;\n }\n if(elt > sp -> data[mid]) //elt is larger than the elt at data[]\n lo = mid + 1;//The elt we are searching for is larger than mid so lo is increased\n else\n hi = mid - 1;// The elt we are searching for is smaller than mid so hi is decreased\n }\n *found = false;//If elt is never found in data[] found is false\n return lo;//lo is returned\n}\n" }, { "alpha_fraction": 0.4196169376373291, "alphanum_fraction": 0.43412652611732483, "avg_line_length": 28.20339012145996, "blob_id": "c9826ddbcb7aa115ae7584c401d3174f1e8df25d", "content_id": "58fb94d988ad6e521bd05e633a6b7771a2cf8921", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1723, "license_type": "no_license", "max_line_length": 85, "num_lines": 59, "path": "/Operating Systems/Lab 8/lru.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n\ntypedef struct {\n int pageno;\n int count;\n} ref_page;\n\nint main(int argc, char *argv[]){\n\tint C_SIZE = atoi(argv[1]);\n ref_page cache[C_SIZE];\n char pageCache[100];\n int i, j, k, l, m;\n int totalFaults = 0, totalRequests = 0, currentPos = 0;\n \n for (i = 0; i < C_SIZE; i++){\n cache[i].pageno = -1;\n cache[i].count = 100;\n }\n\n while (fgets(pageCache, 100, stdin)){\n \tint page_num = atoi(pageCache);\n totalRequests++;\n int least_rec = cache[j].count;\n for (j = 0; j < C_SIZE; j++){\n if (page_num == cache[j].pageno){\n for (k = 0; k < C_SIZE; k++)\n if (cache[k].count < cache[j].count)\n cache[k].count++;\n cache[j].count = 0;\n break;\n }\n\n if (j == C_SIZE - 1){\n for (l = 0; l < C_SIZE; l++)\n cache[l].count = cache[l].count++;\n for (m = 0; m < C_SIZE; m++){\n if (least_rec < cache[m].count){\n least_rec = cache[m].count;\n currentPos = m;\n }\n }\n printf(\"Page %d caused a page fault.\\n\", page_num);\n totalFaults++;\n cache[currentPos].pageno = page_num;\n cache[currentPos].count = 0;\n j++;\n if (j == C_SIZE - 1)\n j = 0;\n }\n }\n }\n\n printf(\"%d Total Page Faults\\n\", totalFaults);\n printf(\"LRU Hit rate = %f\\n\", (totalRequests-totalFaults)/(double)totalRequests);\n return 0;\n}\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.7222222089767456, "avg_line_length": 15.454545021057129, "blob_id": "d5ce19ad19ebfef8c486d0581c8ec75139cc2b94", "content_id": "09fc13635307bd3c27593222e0aaa04b31b2c4aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 180, "license_type": "no_license", "max_line_length": 24, "num_lines": 11, "path": "/SQL Databases/midterm2_mSingh/Number_8_mSingh/tables_mSingh.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh Number 8*/\ncreate table Emp_Office(\nEmpNo char(2),\nOfficeNo Integer,\nPRIMARY KEY(EmpNo)\n);\ncreate table Emp_Phone(\nEmpNo char(2),\nPhoneNo varchar(2),\nPRIMARY KEY(EmpNo)\n);" }, { "alpha_fraction": 0.5385401844978333, "alphanum_fraction": 0.5735023617744446, "avg_line_length": 34.963233947753906, "blob_id": "e247ca569d6a38585259c691694558f9bcc84f37", "content_id": "41c024d793b42369d2222d3fd8513cb4cda1e8ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4891, "license_type": "no_license", "max_line_length": 123, "num_lines": 136, "path": "/Computer Graphics Systems/HW_3/ray_trace.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "from math import *\nfrom PIL import Image\n\nclass Vector( object ):\n def __init__(self,x,y,z):\n self.x = x\n self.y = y\n self.z = z\n\n def dot(self, b): # vector dot product\n return self.x*b.x + self.y*b.y + self.z*b.z\n\n def cross(self, b): # vector cross product\n return (self.y*b.z-self.z*b.y, self.z*b.x-self.x*b.z, self.x*b.y-self.y*b.x)\n\n def magnitude(self): # vector magnitude\n return sqrt(self.x**2+self.y**2+self.z**2)\n\n def normal(self): # compute a normalized (unit length) vector\n mag = self.magnitude()\n return Vector(self.x/mag,self.y/mag,self.z/mag)\n\n # Provide \"overridden methods via the \"__operation__\" notation; allows you to do, for example, a+b, a-b, a*b\n def __add__(self, b): # add another vector (b) to a given vector (self)\n return Vector(self.x + b.x, self.y+b.y, self.z+b.z)\n\n def __sub__(self, b): # subtract another vector (b) from a given vector (self)\n return Vector(self.x-b.x, self.y-b.y, self.z-b.z)\n\n def __mul__(self, b): # scalar multiplication of a given vector\n assert type(b) == float or type(b) == int\n return Vector(self.x*b, self.y*b, self.z*b)\n\nclass Sphere( object ):\n def __init__(self, center, radius, color):\n self.c = center\n self.r = radius\n self.col = color\n\n def intersection(self, l):\n q = l.d.dot(l.o - self.c)**2 - (l.o - self.c).dot(l.o - self.c) + self.r**2\n if q < 0:\n return Intersection( Vector(0,0,0), -1, Vector(0,0,0), self)\n else:\n d = -l.d.dot(l.o - self.c)\n d1 = d - sqrt(q)\n d2 = d + sqrt(q)\n if 0 < d1 and ( d1 < d2 or d2 < 0):\n return Intersection(l.o+l.d*d1, d1, self.normal(l.o+l.d*d1), self)\n elif 0 < d2 and ( d2 < d1 or d1 < 0):\n return Intersection(l.o+l.d*d2, d2, self.normal(l.o+l.d*d2), self)\n else:\n return Intersection( Vector(0,0,0), -1, Vector(0,0,0), self)\n\n def normal(self, b):\n return (b - self.c).normal()\n\nclass Plane( object ):\n def __init__(self, point, normal, color):\n self.n = normal\n self.p = point\n self.col = color\n\n def intersection(self, l):\n d = l.d.dot(self.n)\n if d == 0:\n return Intersection( vector(0,0,0), -1, vector(0,0,0), self)\n else:\n d = (self.p - l.o).dot(self.n) / d\n return Intersection(l.o+l.d*d, d, self.n, self)\n\nclass Ray( object ):\n def __init__(self, origin, direction):\n self.o = origin\n self.d = direction\n\nclass Intersection( object ):\n def __init__(self, point, distance, normal, obj):\n self.p = point\n self.d = distance\n self.n = normal\n self.obj = obj\n\ndef testRay(ray, objects, ignore=None):\n intersect = Intersection( Vector(0,0,0), -1, Vector(0,0,0), None)\n\n for obj in objects:\n if obj is not ignore:\n currentIntersect = obj.intersection(ray)\n if currentIntersect.d > 0 and intersect.d < 0:\n intersect = currentIntersect\n elif 0 < currentIntersect.d < intersect.d:\n intersect = currentIntersect\n return intersect\n\ndef trace(ray, objects, light, maxRecur):\n if maxRecur < 0:\n return (0,0,0)\n intersect = testRay(ray, objects)\n if intersect.d == -1:\n col = vector(AMBIENT,AMBIENT,AMBIENT)\n elif intersect.n.dot(light - intersect.p) < 0:\n col = intersect.obj.col * AMBIENT\n else:\n lightRay = Ray(intersect.p, (light-intersect.p).normal())\n if testRay(lightRay, objects, intersect.obj).d == -1:\n lightIntensity = 1000.0/(4*pi*(light-intersect.p).magnitude()**2)\n col = intersect.obj.col * max(intersect.n.normal().dot((light - intersect.p).normal()*lightIntensity), AMBIENT)\n else:\n col = intersect.obj.col * AMBIENT\n return col\n\ndef gammaCorrection(color,factor):\n return (int(pow(color.x/255.0,factor)*255),\n int(pow(color.y/255.0,factor)*255),\n int(pow(color.z/255.0,factor)*255))\n\nAMBIENT = 0.1\nGAMMA_CORRECTION = 1/2.2\n\nobjs = [] # create an empty Python \"list\"\n\nobjs.append(Sphere( Vector(3.5,0,-10), 2.0, Vector(0,255,0))) # center, radius, color(=RGB)\nobjs.append(Sphere( Vector(-2,0,-10), 3.0, Vector(255,0,0)))\n\nobjs.append(Plane( Vector(0,0,-12), Vector(0,0,1), Vector(255,255,255)))\nlightSource = Vector(-10,0,0) #light position\n\nimg = Image.new(\"RGB\",(500,500))\ncameraPos = Vector(0,0,20)\nfor x in range(500): # loop over all x values for our image\n for y in range(500): # loop over all y values\n ray = Ray( cameraPos, (Vector(x/50.0-5,y/50.0-5,0)-cameraPos).normal())\n col = trace(ray, objs, lightSource, 10)\n img.putpixel((x,499-y),gammaCorrection(col,GAMMA_CORRECTION))\nimg.save(\"trace.png\",\"PNG\")\n" }, { "alpha_fraction": 0.511958122253418, "alphanum_fraction": 0.5224215388298035, "avg_line_length": 25.254901885986328, "blob_id": "8a501e674a0e54059a14a8106be27c4ebbe50b4c", "content_id": "2974e578aa4b7503a8cc3d8351284ae31d2afc30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1338, "license_type": "no_license", "max_line_length": 64, "num_lines": 51, "path": "/Java/Test_Rectangle/src/test_rectangle/Test_Rectangle.java", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "package test_rectangle;\nimport java.util.Scanner;\npublic class Test_Rectangle {\n public static void main(String[] args) {\n Scanner input = new Scanner(System.in);\n \n \t Rectangle test_rectangle = new Rectangle();\n \t \n \t System.out.printf(\"%s\",test_rectangle.Calculations());\n \t \n \t int count = 1;\n \t \n \t while(count !=3) {\n \t\t System.out.println(\"1) Enter 1 to Input Length\");\n \t\t System.out.println(\"2) Enter 2 to Input Width\");\n \t\t System.out.println(\"3) Enter 3 to Exit\");\n \t\t \n \t\t count = input.nextInt();\n \t\t \n \t\t if(count != 3) {\n \t\t\t switch(count)\n {\n case 1:\n \t\t\t\t System.out.println(\"Enter a value for the length:\");\n \t\t\t\t int length = input.nextInt();\n \t\t\t\t test_rectangle.setLength(length);\n \t\t\t\t break;\n \t\t\t\t \n case 2:\n \t\t\t\t System.out.println(\"Enter a value for the width\");\n \t\t\t\t int width = input.nextInt();\n \t\t\t\t test_rectangle.setWidth(width);\n \t\t\t\t break;\n \t\t\t\t \n case 3:\n \t\t\t\t break;\t \n \t\t\t }\n \t\t\t \n \t\t\t System.out.printf(\"%s%n\",test_rectangle.Calculations1());\n \t\t }\n }\n } \n}\n\n\n\n/*public void setInterestRates(int interestRates)\n {\n \t if(interestRates > 0)\n \t\t Savings_Account.interestRates = interestRates;\n }*/" }, { "alpha_fraction": 0.7412399053573608, "alphanum_fraction": 0.7466307282447815, "avg_line_length": 20.823530197143555, "blob_id": "984d57be9f672a1621697838c52d28c5857021c3", "content_id": "843f6e327d351550bd7b0cab03143767e6010510", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 371, "license_type": "no_license", "max_line_length": 51, "num_lines": 17, "path": "/SQL Databases/lab5/part2/psql6.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "CREATE Or Replace TRIGGER countchange_trig \nAFTER INSERT or DELETE ON AlphaCoEmp \nFOR EACH ROW \nBEGIN \nIF DELETING THEN \nUpdate EmpStats \nset Empcount = Empcount -1, lastmodified = SYSDATE \nwhere title = :old.title; \nEND IF; \nIF Inserting THEN \nUpdate EmpStats \nset Empcount = Empcount + 1, lastmodified = SYSDATE\nwhere title = :new.title; \nEnd IF; \nEND;\n/ \nShow errors; " }, { "alpha_fraction": 0.6236559152603149, "alphanum_fraction": 0.6505376100540161, "avg_line_length": 14.5, "blob_id": "d81f1a1942cec0e1e3f5adc5e092b3558368ec12", "content_id": "c6ffd59f0b67ad17a2eda945f4c5a7c7b3f1c63f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 373, "license_type": "no_license", "max_line_length": 42, "num_lines": 24, "path": "/C Data Structures/Term_Project/application_2/dataset.h", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// dataset.c\n//\n// Created by Mandeep Singh on 03/10/19.\n// Copyright © 2019 Mandeep Singh. All rights .\n//\n//\n\n# ifndef DATASET_H\n# define DATASET_H\n\ntypedef struct set SET;\n\nSET *createDataSet(int maxElts);\n\nvoid destroyDataSet(SET *sp);\n\nvoid addElement(SET *sp, int elt, int ID);\n\nvoid removeElement(SET *sp, int ID);\n\nint searchID(SET *sp, int ID);\n\n# endif /* DATASET_H */\n" }, { "alpha_fraction": 0.5234636664390564, "alphanum_fraction": 0.5435754060745239, "avg_line_length": 27.41269874572754, "blob_id": "5bac1b790938e762bcdc93e43a6a9e741f4e21e1", "content_id": "c2e6115061cc4f711498e89ac85909f31d070c4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1790, "license_type": "no_license", "max_line_length": 120, "num_lines": 63, "path": "/Operating Systems/Lab_4/matrix.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//Name: Mandeep Singh\n//Date: 02/03/20\n//Title: Lab 4 - Developing multi-thread applications\n//Description: This program uses threads to multiply matrices\n#include <stdio.h>\n#include <sys/types.h> /* pid_t */\n#include <unistd.h> /* fork */\n#include <stdlib.h> /* atoi */\n#include <errno.h> /* errno */\n#include <pthread.h> /* pthread_t */\n#include <time.h>\n#define N 1024\n#define M 1024\n#define L 1024\n//Initialize matrices and multiplication function\nvoid *multiplication(int x);\nint temp[N];\nint matrixA[N][M];\nint matrixB[M][L];\nint matrixC[N][L];\n\nvoid *multiplication(int x){\n//Each thread processes a row of the output matrix\n for(int v = 0; v < L; v++){\n int temp = 0;\n for (int b = 0; b < M; b++)\n temp += matrixA[x][b] * matrixB[b][v];\n matrixC[x][v] = temp;\n }\n}\n\nint main(int argc, char *argv[]){\n for(int p = 0; p < N; p++)\n temp[p] = p;\n//Assigns random values to matrices\n int i, j, k;\n srand(time(NULL));\n for (i = 0; i < N; i++)\n for (j = 0; j < M; j++)\n matrixA[i][j] = rand()%10;\n for (i = 0; i < M; i++)\n for (j = 0; j < L; j++)\n matrixB[i][j] = rand()%10;\n// Creates Processes and assigns them to multiplication function and passes which row they will calculate to function\n pthread_t tid[N];\n \n for (i = 0; i < N; i++)\n pthread_create(&tid[i], NULL, multiplication, (void *)temp[i]);\n// Joins function to main thread\n for (i = 0; i < N; i++) {\n pthread_join(tid[i], NULL);\n printf(\"Thread %d returned \\n\", i);\n }\n// Outputs final matrix\n for(i = 0; i < M; i++){\n for(j = 0; j < L; j++)\n printf(\"%d \", matrixC[i][j]);\n printf(\"\\n\");\n }\n \n printf(\"Main thread done.\\n\");\n return 0;\n}\n" }, { "alpha_fraction": 0.5902438759803772, "alphanum_fraction": 0.6536585092544556, "avg_line_length": 16.08333396911621, "blob_id": "5721d339b4be8e15bfbaaba5d298dd6ec22aa2f8", "content_id": "a7f844a3d75a59c3d64ece126b7d29bfa1ac973b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 205, "license_type": "no_license", "max_line_length": 48, "num_lines": 12, "path": "/Artificial Intelligence/Lab_1/class_as_module.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "import class3\n\nrec3 = class3.Person('Jane', ['dev', 'mgr'], 30)\n\nprint(rec3.age)\nprint(rec3.info())\n\nfrom class3 import Person\n\nrec4 = Person('Mike', ['dev', 'mgr'], 35)\nprint(rec4.age)\nprint(rec4.info())\n" }, { "alpha_fraction": 0.5935030579566956, "alphanum_fraction": 0.6251097321510315, "avg_line_length": 31.542856216430664, "blob_id": "cbca07bc4ba4684971b545711537bdb7d03f365a", "content_id": "858af7f334cd9ea5e645ae8171c8fcf5b0adbda0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1140, "license_type": "no_license", "max_line_length": 115, "num_lines": 35, "path": "/C Data Structures/lab1.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// main.c\n// Example 1\n//\n// Created by Mandeep Singh on 01/09/19.\n// Copyright © 2019 Mandeep Singh. All rights .\n//\n\n#include<stdio.h>\n#define MAX_WORD_LEGNTH 30 //Setting the max words variable as 30\n\nint main(int argc, char *argv[]) //Initializing main function with two parameters\n\n{\n FILE *file1; //Setting pointer to file1\n int count = 0; //Initializing and setting the word count to 0\n\n char a1[MAX_WORD_LEGNTH+1]; //Creating character array to store strings in\n\n if(argc == 1){ //If no filepath given\n printf(\"No arguments were passed\\n\"); //Print statement\n \n }else{ //otherwise\n \n file1 = fopen(argv[1], \"r\"); //setting file1 as reading argv[1]\n if(file1 == NULL) //If file not found\n printf(\"file not found\\n\"); //Return statement\n\n while(fscanf(file1, \"%s\", a1) == 1) { //While fscanf returns 1 for reading file 1 and placing the string in a1\n count++; //Add 1 to count variable\n }\n printf(\"%d total words\\n\", count); //Print statement with # of words in file\n }\n return 0; //Return 0 to verify program ran all the way through properly\n}\n" }, { "alpha_fraction": 0.6355748176574707, "alphanum_fraction": 0.6746203899383545, "avg_line_length": 40.90909194946289, "blob_id": "f9fd1522b73fa30788796975de5d09fa296da6ef", "content_id": "757909102161971e66f4c99175143de511df114c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 461, "license_type": "no_license", "max_line_length": 43, "num_lines": 11, "path": "/SQL Databases/lab3/script.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "insert into L_EMP values(1,'smith','d1');\ninsert into L_EMP values(2,'jones','d2');\ninsert into L_EMP values(3,'wayne','d1');\ninsert into L_EMP values(4,'moor','d3');\ninsert into L_EMP values(5,'king','d1');\ninsert into L_EMP values(6,'chen','d1');\ninsert into L_EMP values(7,'winger','d3');\ninsert into L_DEPT values('d1','Research');\ninsert into L_DEPT values('d2','Devt');\ninsert into L_DEPT values('d3','Testing');\ninsert into L_DEPT values('d4','Advert');\n" }, { "alpha_fraction": 0.4485294222831726, "alphanum_fraction": 0.5343137383460999, "avg_line_length": 16, "blob_id": "cbc7ba0aa08b8a3835fcb6459aa573ebf23c9148", "content_id": "263712a922040ce2876e72192f2e9627136d8c75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 409, "license_type": "no_license", "max_line_length": 49, "num_lines": 24, "path": "/C++ Data Structures/Homework_2/HW_3/main.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// HW_3\n//\n// Created by Mandeep Singh on 4/18/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include <iostream>\n#include \"bag.hpp\"\n\nint main(int argc, const char * argv[]) {\n std::bag b1;\n b1.insert(1, 5);\n b1.insert(2, 10);\n b1.print();\n b1.insert(3, 7);\n b1.insert(8, 2);\n b1.insert(3, 10);\n b1.print();\n b1.remove(1);\n b1.remove(9);\n b1.print();\n}\n" }, { "alpha_fraction": 0.4752790927886963, "alphanum_fraction": 0.5111642479896545, "avg_line_length": 28.162790298461914, "blob_id": "5654ebc5649446be648d37917bce5fac09e18faa", "content_id": "c5e92ae00118937490c25f8489c5e92cb3a02a52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1255, "license_type": "no_license", "max_line_length": 110, "num_lines": 43, "path": "/C++ Data Structures/Homework_1/HW_3/statistician.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// statistician.cpp\n// HW_2\n//\n// Created by Mandeep Singh on 4/9/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include \"statistician.hpp\"\n\nnamespace std {\n \n void statistician::next_number(const double x){\n update_length();\n update_sum(x);\n update_avg(x);\n update_lastNum(x);\n if(x < smallest) { smallest = x; }\n if(x > largest) { largest = x; }\n }\n \n statistician operator +(statistician& s1, statistician& s2){\n statistician s3;\n \n if(s1.get_length() == 0 && s2.get_length() == 0)\n return s3;\n else if(s1.get_length() == 0)\n return s2;\n else if(s2.get_length() == 0)\n return s1;\n else{\n double smallest = (s1.get_smallest() < s2.get_smallest()) ? s1.get_smallest() : s2.get_smallest();\n double largest = (s1.get_largest() > s2.get_largest()) ? s1.get_largest() : s2.get_largest();\n s3.sum = s1.get_sum() + s2.get_sum();\n s3.length = s1.get_length() + s2.get_length();\n s3.avg = s3.get_sum()/s3.get_length();\n s3.largest = largest;\n s3.smallest = smallest;\n s3.lastNum = s2.lastNum;\n }\n return s3;\n }\n}\n" }, { "alpha_fraction": 0.5308279395103455, "alphanum_fraction": 0.5419847369194031, "avg_line_length": 27.86440658569336, "blob_id": "6307e7bb4fc8615c470f0d60ce8eec8c8ee1bdb4", "content_id": "744dadf74719fa31523ec2880a084d42176749fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1706, "license_type": "no_license", "max_line_length": 108, "num_lines": 59, "path": "/C++ Data Structures/Homework_2/HW_5/kbag.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// kbag.cpp\n// HW_4\n//\n// Created by Mandeep Singh on 4/10/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include \"kbag.hpp\"\n#include <iostream>\n#include <algorithm> // Provides copy function\n#include <cassert> // Provides assert function\nnamespace std {\n const kbag::size_type kbag::DEFAULT_CAPACITY;\n \n kbag::kbag(size_type initial_capacity){\n used = 0;\n data = new value_type[initial_capacity];\n capacity = initial_capacity;\n for(int i = 0; i < capacity; i++)\n data[i] = -1;\n }\n \n void kbag::reserve(size_type new_capacity){\n value_type *larger_array;\n if (new_capacity == capacity)\n return; // The allocated memory is already the right size. if (new_capacity < used)\n new_capacity = used; // Can’t allocate less than we are using.\n larger_array = new value_type[new_capacity]; copy(data, data + used, larger_array); delete [ ] data;\n data = larger_array;\n capacity = new_capacity;\n }\n \n void kbag::remove(int key){\n if(data[key] != -1)\n data[key] = -1;\n else\n cout << \"No key exists here\" << endl;\n }\n \n void kbag::insert(const value_type& entry, int key){\n if (used == capacity)\n reserve(used+1);\n if(data[key] == -1){\n data[key] = entry;\n used++;\n }else\n cout << \"This key already has an item\" << endl;\n }\n \n kbag::size_type kbag::count(const value_type& target) const{\n size_type answer;\n size_type i;\n answer = 0;\n for (i = 0; i < used; ++i)\n if (target == data[i]) ++answer;\n return answer;\n }\n}\n" }, { "alpha_fraction": 0.6453333497047424, "alphanum_fraction": 0.7253333330154419, "avg_line_length": 61.66666793823242, "blob_id": "cb2190639403ab516b8aafa262f16c4acbe16f83", "content_id": "a5827d006935da786f745503363d1b3698addbaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 375, "license_type": "no_license", "max_line_length": 63, "num_lines": 6, "path": "/SQL Databases/Extra_Credit_1/sql2.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "insert into Supplier values('00001', 'Williams', 'San Jose');\ninsert into Supplier values('00002', 'Johnson', 'Sunnyvale');\ninsert into Supplier values('00003', 'Hendelson', 'Sunnyvale');\ninsert into Supplier values('00004', 'Waltgreen', 'Chicago');\ninsert into Supplier values('00005', 'Fredrick', 'Sunnyvale');\ninsert into Supplier values('00006', 'Robertson', 'San Jose');" }, { "alpha_fraction": 0.5722714066505432, "alphanum_fraction": 0.6076695919036865, "avg_line_length": 16.842105865478516, "blob_id": "7349d459d3ea0f863d1ffe5c5cbdd60b952492fc", "content_id": "2cdc1bd8b51325e920b489380f4f2a37a89696a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 339, "license_type": "no_license", "max_line_length": 49, "num_lines": 19, "path": "/Artificial Intelligence/Lab_1/class1.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "class FirstClass:\n def setdata(self, value1, value2):\n self.data1 = value1\n self.data2 = value2\n def display(self):\n print(self.data1, '\\n', self.data2, '\\n')\n\nx = FirstClass()\n\nx.setdata(\"King Arthur\", -5)\nx.display()\n\nx.data1 = \"QQ\"\nx.data2 = -3\nx.display()\n\nx.anothername = \"spam\"\nx.display()\nprint(x.anothername)\n" }, { "alpha_fraction": 0.49422287940979004, "alphanum_fraction": 0.5173313617706299, "avg_line_length": 25.554454803466797, "blob_id": "fc436fe419b333c0efb21ed202c2e4d09c417c39", "content_id": "e13ad625f8746df7d160ff4d5b8dfb5912397964", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2684, "license_type": "no_license", "max_line_length": 100, "num_lines": 101, "path": "/C Data Structures/pqueue.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// pqueue.c\n//\n// Created by Mandeep Singh on 02/28/19.\n// Copyright © 2019 Mandeep Singh. All rights .\n//\n//Priority queue by utilizing binary heap implemented through an array\n#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h> //Import libraries for usage\n#include \"pqueue.h\"\n#define LEFT ((2 * i) + 1)\n#define RIGHT ((2 * i) + 2)\n\ntypedef struct pqueue {\n int length;\n int count;\n void **data;\n int (*compare)();\n} PQ;\n\n//O(1)\nPQ *createQueue(int (*compare)()){\n PQ *queue;\n queue = malloc(sizeof(PQ));\n assert(queue != NULL);\n queue -> count = 0;\n queue -> length = 10;\n queue -> data = malloc(sizeof(void*) * queue -> length);\n assert(queue -> data != NULL);\n queue -> compare = compare;\n return queue;\n}\n\n//O(1)\nvoid destroyQueue(PQ *pq){ //Destroy entire queue\n free(pq -> data);\n free(pq);\n}\n\n//O(1)\nint numEntries(PQ *pq){\n return pq -> count; //Return number of elts in queue\n}\n\n//O(logn)\nvoid addEntry(PQ *pq, void *entry) {\n if(pq -> count >= pq -> length){\n pq -> length *= 2;\n pq -> data = realloc(pq -> data, sizeof(void*) * pq -> length); //Reallocate memory\n }\n\n int i1 = pq -> count;//Set i1 to index value of soon-to-be newly inserted data\n int i2 = (i1 - 1) / 2;\n pq -> data[pq -> count] = entry; //Insert new data at count and then increment count\n \n while(1){\n if((*pq -> compare)(entry, pq -> data[i2]) < 0){ //If data at entry is less than data parent\n\\\n void* temp = pq -> data[i2]; //swap entry & pq -> data[i2]\n pq -> data[i2] = entry;\n pq -> data[i1] = temp;\n i1 = i2; //update i1\n i2 = (i1 - 1) / 2; //update i2\n }else\n break; //Break to end while loop once reheaping is done\n }\n pq -> count++; //Increment to account for new elt\n}\n\n// O(logn)\nvoid *removeEntry(PQ *pq){\n if(pq -> count <= 0)\n return NULL;\n else if(pq -> count == 1){\n void* x = pq -> data[0];\n pq -> data[0] = NULL;\n pq -> count--; //Decrement to account for deleted elt\n return x;\n }\n \n void *x = pq -> data[0];\n pq -> data[0] = pq -> data[pq -> count - 1];\n pq -> data[pq -> count - 1] = NULL;\n int i = pq -> count - 2;\n \n while(1){\n if(i <= 0)\n break;\n if((*pq -> compare)(pq -> data[i], pq -> data[(i-1)/2]) < 0){\n void *temp = pq->data[i]; //swap pq -> data[i] & pq -> data[(i-1)/2]\n pq -> data[i] = pq -> data[(i-1)/2];\n pq -> data[(i-1)/2] = temp;\n }\n i--; //Decrement i\n }\n pq -> count--; //Decrement count\n return x;\n}\n\n" }, { "alpha_fraction": 0.7706422209739685, "alphanum_fraction": 0.7895305156707764, "avg_line_length": 153.4583282470703, "blob_id": "283af5b984e57899ab39ae849b9a3791a4f209f2", "content_id": "0a6b451ac6124b4243e6d77a90542c8de5c180af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 3744, "license_type": "no_license", "max_line_length": 717, "num_lines": 24, "path": "/C Data Structures/Term_Project/README.txt", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "1.Scenario\nConsider a college holding records about its students, where each record contains two integer fields: ID and Age. Given different application scenarios below, for each application, please (1) identify the most appropriate data structures so that the Big-O run time for frequent operations is optimized, (2) provide the implementation code, and (3) analyze the worst-case Big-O run time for each operation. Your possible data structure choices mainly include struct, array, linked list, and hash table. Please note that the college assigns a global unique ID to a student when he/she first enrolls and the ID will never be recycled for other students (Hints: No need to check the uniqueness of a record for insertion).\n\n2. Implementation\rFor each application, you need to implement two separate files as college.c (i.e. the “outsider” program containing a main function), and dataset.c (i.e. your dataset ADT with specific data structures).\r(1) Implementing a main function (college.c)\rFor completeness of the project and testing purpose, you need to write your own code with a main function. Please generate a separate code file for your main function (college.c), where the following tasks are performed.\r• Create your data set. For application 1 and 2, you can assume the maximum number of students is 3000 and pass this value as a parameter when creating your data set.\r• Generate 1000 student records with random ages ranging from 18 to 30. Follow the steps below to generate random unique student IDs.\ra. Implement a random integer generator, which randomly generates an integer number as either 1 or 2.\rb. The first student ID can be determined as the return value of the random integer generator (i.e. either 1 or 2).\rc. For each of the remaining student records, the ID field is determined by the previous student’s ID plus the return value of the random integer generator. For example, assuming that the 3rd student ID is 5, and that 2 is returned as a result of the random integer generator, the 4th student ID can be then determined as 5 + 2 = 7.\r• Each time when a new student record is generated, insert it into your data set.\r• Randomly generate a student record with ID (ranging from 00001 ~ 2000) and age (ranging from 18~30). Search for the student in your data set. Depending on the specific application, you may do search based on either ID or age.\r• For application 2 and 3, randomly generate a student ID (ranging from 0001 ~ 2000). Delete the record from your data set if it is found. For application 1, randomly generate a student age. Delete all the records with the given age in your data set.\r• For application 1 and 3, call the maxAgeGap interface and print out the return value.\r• Destroy your data set.\r(2) Printf statement\r• Add printf in searchAge, searchID, deletion functions, which prints (1) the Age and ID for the student record that needs to be searched or deleted; and (2) whether the delete has been done successfully or whether the item has been found.\r• Add printf within maxAge function, which prints the maximum age gap for the current elements.\r(3) Implementing your dataset ADT (dataset.c)\rFor each of the two applications that you choose, identify the most appropriate data structures so that the Big-O run time for frequent operations is optimized. Implement the interfaces required by the specific application in dataset.c.\r(4) Some extra notes for hash table\rIf you use hash table for your implementation, please use a prime number for the table length. For example, 1009 is the smallest prime number greater than 1000. For simplicity reason, you can just use linear probing to resolve collisions, and an example hash function can be ℎ(𝑘)=(𝑘+𝑖)%𝑚" }, { "alpha_fraction": 0.46803978085517883, "alphanum_fraction": 0.4779829680919647, "avg_line_length": 22.46666717529297, "blob_id": "7b03fbc5866b9e0c06fad68ce107ccaa73cbb288", "content_id": "569357032afd7f5b26055139b7579ab1711fa58d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1409, "license_type": "no_license", "max_line_length": 57, "num_lines": 60, "path": "/C++ Data Structures/Homework_2/HW_2/bag.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// set.cpp\n// HW_2\n//\n// Created by Mandeep Singh on 4/17/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include \"bag.hpp\"\n#include <algorithm> // Provides copy function\n#include <cassert> // Provides assert function\nnamespace std {\n \n const set::size_type set::CAPACITY;\n \n //O(n)\n set::size_type set::erase(const value_type& target)\n {\n size_type index = 0;\n size_type many_removed = 0;\n while (index < used) {\n if (data[index] == target) {\n --used;\n data[index] = data[used];\n ++many_removed;\n }\n else\n ++index;\n }\n return many_removed;\n }\n \n //O(n)\n bool set::erase_one(const value_type& target) {\n size_type index;\n index = 0;\n while ((index < used) && (data[index] != target))\n ++index;\n if (index == used)\n return false;\n --used;\n data[index] = data[used]; return true;\n }\n \n //O(n)\n void set::insert(const value_type& entry){\n assert(size( ) < CAPACITY);\n if(!contains(entry)){\n data[used] = entry;\n used++;\n }\n }\n \n //O(n)\n bool set::contains(const value_type& target) const{\n for (size_type i = 0; i < used; ++i)\n if (target == data[i]) return true;\n return false;\n }\n}\n" }, { "alpha_fraction": 0.5415691137313843, "alphanum_fraction": 0.5497658252716064, "avg_line_length": 23.399999618530273, "blob_id": "03591f897e287265a3901e879f901bd50186359f", "content_id": "4bf188b35f9ebd60e7b9b33761d11ec72cc5350b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1708, "license_type": "no_license", "max_line_length": 91, "num_lines": 70, "path": "/COEN_178_Final_Project_mSingh/Extra_Credit/updateGold.php", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh*/\n/*COEN 178 Final Project*/\n/*PHP updateGold*/\n<?php\n\nif ($_SERVER[\"REQUEST_METHOD\"] == \"POST\") {\n\n // collect input data from the form\n $custid = $_POST['custid'];\n \n if (!empty($custid)){\n $custid = prepareInput($custid);\n }\n\n updateGold($custid);\n \n}\n\nfunction prepareInput($inputData){\n $inputData = trim($inputData);\n $inputData = htmlspecialchars($inputData);\n return $inputData;\n}\n\nfunction updateGold($custid){\n $conn = oci_connect('username', 'password', '//dbserver.engr.scu.edu/db11g');\n \n if (!$conn) {\n $e = oci_error();\n trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);\n }\n if(!$conn) {\n print \"<br> connection failed:\";\n exit;\n }\n // Updating in Customers\n $sql = oci_parse($conn, \"Update Customers SET custtype = 'gold' where custid = :cust\");\n \n oci_bind_by_name($sql, ':cust', $custid);\n \n //Inserting into GoldCustomer\n $sql = oci_parse($conn, \"Insert into GoldCustomer values(:id, sysdate)\");\n \n oci_bind_by_name($sql2, ':id', $custid);\n \n // Execute the query\n $res = oci_execute($sql);\n $res2 = oci_execute($sql2);\n \n if ($res){\n echo '<br><br> <p style=\"color:green;font-size:20px\">';\n echo \"Updated in Customer </p>\";\n }\n else{\n $e = oci_error($query);\n echo $e['message'];\n }\n if ($res2){\n echo '<br><br> <p style=\"color:green;font-size:20px\">';\n echo \"Inserted into GoldCustomers</p>\";\n }\n else{\n $e = oci_error($query);\n echo $e['message'];\n }\n oci_free_statement($sql);\n oci_free_statement($sql2);\n OCILogoff($conn);\n}\n?>\n" }, { "alpha_fraction": 0.5871501564979553, "alphanum_fraction": 0.5916030406951904, "avg_line_length": 24.354839324951172, "blob_id": "7ea5a45d33fa305414685a99b3f49a4c5402b1fc", "content_id": "45ba18576db7cc02a8577c32ceee8b813d8683cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1572, "license_type": "no_license", "max_line_length": 97, "num_lines": 62, "path": "/COEN_178_Final_Project_mSingh/Extra_Credit/computeTotal.php", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh*/\n/*COEN 178 Final Project*/\n/*PHP computeTotal*/\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\"/>\n <title>Compute Total</title>\n </head>\n <body>\n<form method=\"post\" action=\"<?php echo htmlspecialchars($_SERVER[\"PHP_SELF\"]);?>\">\n Order ID: <input type=\"text\" name=\"orderid\" id=\"orderid\">\n <input type=\"submit\">\n </form>\n<?php\nif ($_SERVER[\"REQUEST_METHOD\"] == \"POST\") {\n # collect input data\n $orderid = $_POST['orderid'];\n\n if (!empty($orderid)){\n $orderid = prepareInput($orderid);\n $total = getTotalFromDB($orderid);\n echo \"Order ID: $orderid <br>\";\n echo \"Total: $total <br>\";\n }\n}\n\nfunction getTotalFromDB($orderid){\n $conn=oci_connect('username','password', '//dbserver.engr.scu.edu/db11g');\n if(!$conn) {\n print \"<br> connection failed:\";\n exit;\n }\n $query = oci_parse($conn, \"select computeTotal(orderid) from itemorder where orderid = :bv\");\n oci_bind_by_name($query,':bv',$orderid);\n oci_execute($query);\n\n if (($row = oci_fetch_array($query, OCI_BOTH)) != false) {\n $itemid = $row[0];\n }\n else {\n echo \"Error <br>\\n\";\n }\n oci_free_statement($query);\n oci_close($conn);\n\n return $itemid;\n }\n\nfunction prepareInput($inputData){\n // Removes any leading or trailing white space\n $inputData = trim($inputData);\n // Removes any special characters that are not allowed in the input\n $inputData = htmlspecialchars($inputData);\n return $inputData;\n}\n\n?>\n<!-- end PHP script -->\n </body>\n</html>\n" }, { "alpha_fraction": 0.5607476830482483, "alphanum_fraction": 0.6028037667274475, "avg_line_length": 12.375, "blob_id": "0b7f5e04636354a708f0f7e285bee15b8ad14f6b", "content_id": "be539f6d58c292f8d80c55457b4bb588b791fff3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 215, "license_type": "no_license", "max_line_length": 49, "num_lines": 16, "path": "/C++ Data Structures/Lab_1/test.hpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// test.hpp\n// Lab_1\n//\n// Created by Mandeep Singh on 4/4/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#ifndef test_hpp\n#define test_hpp\n\n#include <stdio.h>\n\nvoid print_hello();\n\n#endif /* test_hpp */\n" }, { "alpha_fraction": 0.45571520924568176, "alphanum_fraction": 0.4679391086101532, "avg_line_length": 27.090360641479492, "blob_id": "12c570bd78b4f7f5f91e0f72f1d2f7436988c574", "content_id": "19f1309a3b1b5dcb84fdf105c42acd3d099b66e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4666, "license_type": "no_license", "max_line_length": 108, "num_lines": 166, "path": "/C++ Data Structures/Homework_2/HW_5/sequence1.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// sequence1.cpp\n// Lab_3\n//\n// Created by Mandeep Singh on 4/18/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include <stdio.h>\n#include <cmath>\n#include \"sequence1.hpp\"\n\nnamespace std{\n \n sequence::sequence(size_type initial_capacity){\n used = 0; current_index = 0;\n data = new value_type[initial_capacity];\n capacity = initial_capacity;\n }\n \n void sequence::reserve(size_type new_capacity){\n value_type *larger_array;\n if (new_capacity == capacity)\n return; // The allocated memory is already the right size. if (new_capacity < used)\n new_capacity = used; // Can’t allocate less than we are using.\n larger_array = new value_type[new_capacity]; copy(data, data + used, larger_array); delete [ ] data;\n data = larger_array;\n capacity = new_capacity;\n }\n \n void sequence::advance(){\n if(is_item()){\n if(current_index < used)\n current_index++;\n }\n }\n \n void sequence::insert(const value_type& entry){\n if (used == capacity)\n reserve(used+1);\n if(used == 0){\n data[0] = entry;\n current_index = 0;\n }else{\n // for(size_type i = current_index + 1; i < used; i++)\n // data[i-1] = data[i];\n for(size_type i = used + 1; i > current_index; i--)\n data[i] = data[i-1];\n \n data[current_index] = entry;\n }\n used++;\n }\n \n void sequence::attach(const value_type& entry){\n if (used == capacity)\n reserve(used+1);\n if(used == 0){\n current_index = 0;\n data[current_index] = entry;\n }else{\n for(size_type i = current_index; i < used; i++)\n data[i+1] = data[i+2];\n data[current_index+1] = entry;\n current_index += 1;\n }\n used++;\n }\n \n void sequence::remove_current(){\n if(is_item()){\n for(int i = capacity; i > current_index; i--)\n data[i- 1] = data[i];\n }\n used--;\n std::cout << \"**********Length: \" << this->size() << std::endl;\n \n }\n \n void sequence::insert_front(const value_type& entry){\n if (used == capacity)\n reserve(used+1);\n if(used == 0){\n data[0] = entry;\n current_index = 0;\n }else{\n for(size_type i = 0; i < used; i++)\n data[i] = data[i+1];\n data[0] = entry;\n current_index = 0;\n }\n used++;\n }\n \n void sequence::attach_back(const value_type& entry){\n if (used == capacity)\n reserve(used+1);\n if(used == 0){\n current_index = 0;\n data[current_index] = entry;\n }else{\n current_index = used;\n data[current_index] = entry;\n }\n used++;\n }\n \n void sequence::remove_front(){\n if(is_item()){\n for(int i = 1; i < size(); i++)\n data[i-1] = data[i]; //shift down\n }\n used--;\n }\n \n double sequence::getItem(int index) const{\n assert(index < size());\n double item = data[index];\n return item;\n }\n \n void sequence::operator +=(const sequence& rhs){\n assert(rhs.size() <= (capacity - this->size()));\n for(double i = this->size(); i < (this->size() + rhs.size()); i++)\n this->attach_back(getItem(i));\n }\n \n sequence::value_type sequence::operator [](int index) const{\n assert(index < size());\n return data[index];\n }\n \n double sequence::mean() const{\n return summation(*this)/size();\n }\n \n double sequence::standardDeviation() const{\n double avg = mean(), stD = 0;\n \n for(int i = 0; i < size(); ++i)\n stD += pow(data[i] - avg, 2);\n \n return sqrt(stD/size());\n }\n \n double summation(const sequence &s){\n double sum = 0;\n for(double i = 0; i < s.size(); i++){\n sum += s[i];\n }\n return sum;\n }\n \n sequence operator +(const sequence& lhs, const sequence& rhs){\n assert(lhs.size() + rhs.size() < 50);\n sequence s1;\n for(int i = 0; i < lhs.size(); i++)\n s1.attach_back(lhs.getItem(i));\n for(int i = 0; i < rhs.size(); i++)\n s1.attach_back(rhs.getItem(i));\n // for(double j = lhs.size(); j < rhs.size(); j++)\n // s1.attach_back(rhs.getItem(j - lhs.size()));\n return s1;\n }\n \n}\n" }, { "alpha_fraction": 0.5885558724403381, "alphanum_fraction": 0.6012715697288513, "avg_line_length": 28.756755828857422, "blob_id": "eb175776eccca8cef328527144ea9665b911f342", "content_id": "85edc9c458fec9e6f9cd4130d152e9c761f62ed9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1102, "license_type": "no_license", "max_line_length": 96, "num_lines": 37, "path": "/C++ Data Structures/Homework_1/HW_5/sequence.hpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// sequence.hpp\n// HW_5\n//\n// Created by Mandeep Singh on 4/10/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#ifndef sequence_hpp\n#define sequence_hpp\n#include <cstdlib>\n#include <stdio.h>\nnamespace std{\n class sequence{\n public:\n // TYPEDEFS and MEMBER CONSTANTS\n typedef double value_type;\n typedef std::size_t size_type;\n static const size_type CAPACITY = 30; // CONSTRUCTOR\n sequence();\n // MODIFICATION MEMBER FUNCTIONS\n void start(){ current_index = 0; };\n void advance(){ if(is_item()) current_index++; };\n void insert(const value_type& entry);\n void attach(const value_type& entry);\n void remove_current();\n // CONSTANT MEMBER FUNCTIONS\n size_type size() const { return used; } ;\n bool is_item() const{ if((current_index + 1) <= used) return true; else return false; };\n value_type current() const { return data[current_index]; };\n private:\n value_type data[CAPACITY];\n size_type used;\n size_type current_index;\n };\n}\n#endif /* sequence_hpp */\n" }, { "alpha_fraction": 0.6248142719268799, "alphanum_fraction": 0.6274145841598511, "avg_line_length": 27.04166603088379, "blob_id": "39a70ddafa48098ed6602aa2b5238b6130a04af3", "content_id": "c8849ca59fa5753c08d0cd1f2b30b7531f06cdf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2692, "license_type": "no_license", "max_line_length": 85, "num_lines": 96, "path": "/SQL Databases/lab6/ShowSalary_Form.php", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n\t<meta charset=\"utf-8\"/>\n <title>Show Salary by Employee Name</title>\n </head>\n <body>\n<form method=\"post\" action=\"<?php echo htmlspecialchars($_SERVER[\"PHP_SELF\"]);?>\">\n Full Name: <input type=\"text\" name=\"fname\" id=\"fname\">\n <input type=\"submit\">\n </form>\n<?php\nif ($_SERVER[\"REQUEST_METHOD\"] == \"POST\") {\n # collect input data\n $empName = $_POST['fname'];\n\n if (!empty($empName)){\n\t\t $empName = prepareInput($empName);\n\t\t $salary = getSalaryFromDB($empName);\n $title = getTitleFromDB($empName);\n echo \"Name: $empName <br>\";\n\t\t echo \"Salary of $empName: $salary <br>\";\n echo \"Title of $empName: $title <br>\";\n\t }\n}\n\nfunction getTitleFromDB($name){\n //connect to your database\n $conn=oci_connect('username','password', '//dbserver.engr.scu.edu/db11g');\n if(!$conn) {\n print \"<br> connection failed:\";\n exit;\n }\n // Parse the SQL query\n $query = oci_parse($conn, \"SELECT title FROM AlphacoEmp where name= :bv\");\n\n oci_bind_by_name($query,':bv',$name);\n // Execute the query\n oci_execute($query);\n\n if (($row = oci_fetch_array($query, OCI_BOTH)) != false) {\n // We can use either numeric indexed starting at 0\n // or the column name as an associative array index to access the colum value\n // Use the uppercase column names for the associative array indices\n $title = $row['TITLE'];\n }\n else {\n echo \"No such employee <br>\\n\";\n }\n oci_free_statement($query);\n oci_close($conn);\n\n return $title;\n }\nfunction getSalaryFromDB($name){\n\t//connect to your database\n\t$conn=oci_connect('username','password', '//dbserver.engr.scu.edu/db11g');\n\tif(!$conn) {\n\t print \"<br> connection failed:\";\n exit;\n\t}\n\t//\t Parse the SQL query\n\t$query = oci_parse($conn, \"SELECT salary FROM AlphacoEmp where name= :bv\");\n\n\toci_bind_by_name($query,':bv',$name);\n\t// Execute the query\n\toci_execute($query);\n\n\tif (($row = oci_fetch_array($query, OCI_BOTH)) != false) {\n\t\t// We can use either numeric indexed starting at 0\n\t\t// or the column name as an associative array index to access the colum value\n\t\t// Use the uppercase column names for the associative array indices\n\t\t$salary = $row['SALARY'];\n\t}\n\telse {\n\t\techo \"No such employee <br>\\n\";\n\t}\n\toci_free_statement($query);\n\toci_close($conn);\n\n\treturn $salary;\n}\nfunction prepareInput($inputData){\n\t// Removes any leading or trailing white space\n\t$inputData = trim($inputData);\n\t// Removes any special characters that are not allowed in the input\n\n \t$inputData = htmlspecialchars($inputData);\n\n \treturn $inputData;\n}\n\n?>\n<!-- end PHP script -->\n </body>\n</html>\n" }, { "alpha_fraction": 0.7197580933570862, "alphanum_fraction": 0.7298387289047241, "avg_line_length": 26.61111068725586, "blob_id": "e145ddf865b19f964bf47c018076ee718eea2b49", "content_id": "a99a4c785d4e42870cec7a192c714970d2c946ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 496, "license_type": "no_license", "max_line_length": 82, "num_lines": 18, "path": "/COEN_178_Final_Project_mSingh/Functions/updateGold.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh*/\n/*COEN 178 Final Project*/\n/*updateGold Trigger*/\nCREATE OR REPLACE trigger updateGold\nafter update on customers\nfor each row\nbegin\n\t/*If custtype is being changed to gold from regular*/\n\tif :new.custtype = 'gold' and :old.custtype = 'regular'\n then\n\t/*Shipping Fee is now 0 since gold for customer who's custtype is being changed*/\n\tupdate itemorder\n\tset shippingfee = 0 \n where custid = :new.custid and (shippeddate is null or shippeddate >sysdate);\n\tend if;\nend;\n/\nshow error;" }, { "alpha_fraction": 0.6208388805389404, "alphanum_fraction": 0.6661118268966675, "avg_line_length": 45.21538543701172, "blob_id": "b8b56542fffca9f7d8125e28bab8768d9f472803", "content_id": "2b3c419396c1f23e8a069e96580e68b1d5eda535", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3004, "license_type": "no_license", "max_line_length": 166, "num_lines": 65, "path": "/Artificial Intelligence/Lab_6/lab_6.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras import datasets, layers, models\nfrom keras.utils import to_categorical\nfrom sklearn.metrics import confusion_matrix\n\ndef part1():\n fashion_mnist = tf.keras.datasets.fashion_mnist\n (training_images, training_labels), (testing_images, testing_labels) = fashion_mnist.load_data()\n training_images = training_images.reshape((60000, 28, 28, 1))\n testing_images = testing_images.reshape((10000, 28, 28, 1))\n training_images, testing_images = training_images / 255.0, testing_images / 255.0\n training_labels = to_categorical(training_labels)\n testing_labels = to_categorical(testing_labels)\n myModel = models.Sequential()\n myModel.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))\n myModel.add(layers.MaxPooling2D((2, 2)))\n myModel.add(layers.Conv2D(64, (3, 3), activation='relu'))\n myModel.add(layers.MaxPooling2D((2, 2)))\n myModel.add(layers.Conv2D(64, (3, 3), activation='relu'))\n myModel.add(layers.Flatten())\n myModel.add(layers.Dense(64, activation='relu'))\n myModel.add(layers.Dense(10, activation='softmax'))\n myModel.summary()\n myModel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n myModel.fit(training_images, training_labels, epochs = 10, batch_size = 64)\n test_loss, test_acc = myModel.evaluate(testing_images, testing_labels)\n print(test_acc)\n testMatrix = myModel.predict(testing_images)\n testHat = np.argmax(testMatrix, axis=1)\n labels = np.argmax(testing_labels, axis=1)\n confusionMatrix = confusion_matrix(labels, testHat)\n print(confusionMatrix)\n\ndef part2():\n fashion_mnist = tf.keras.datasets.fashion_mnist\n (training_images, training_labels), (testing_images, testing_labels) = fashion_mnist.load_data()\n\n training_images, testing_images = training_images.astype('float32') / 255.0, testing_images.astype('float32') / 255.0\n P = [10, 50, 200]\n for p in P:\n myModel = models.Sequential()\n myModel.add(layers.Flatten(input_shape=(28,28)))\n myModel.add(layers.Dense(p))\n myModel.add(layers.Dense(1568, activation=\"relu\"))\n myModel.add(layers.Dense(784))\n myModel.add(layers.Reshape((28,28), input_shape=(784,)))\n myModel.compile(optimizer='adam', loss='mse', metrics=['accuracy'])\n myModel.fit(training_images, training_images, epochs = 10, batch_size = 64, verbose = 0, shuffle = True, validation_data = (training_images, training_images))\n prediction = myModel.predict(testing_images)\n plt.figure(figsize=(40, 4))\n for x in range(10):\n if p is 10:\n z = plt.subplot(3, 20, x + 1)\n plt.imshow(testing_images[x].reshape(28, 28))\n plt.gray()\n z = plt.subplot(3, 20, 2*20+ x + 1)\n plt.imshow(prediction[x].reshape(28,28))\n plt.gray()\n plt.show()\n\n \npart1()\npart2()\n" }, { "alpha_fraction": 0.4392523467540741, "alphanum_fraction": 0.47663551568984985, "avg_line_length": 9.699999809265137, "blob_id": "39e9a34a6bcf8224f738cd3761d6b91936f3da4e", "content_id": "f83859e3774922709676f6cd802ed96a2ef6d79d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 107, "license_type": "no_license", "max_line_length": 21, "num_lines": 10, "path": "/Artificial Intelligence/Lab_1/module.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "a = 10\nb = 20\n\ndef adder(x, y):\n z = x + y\n return z\n\ndef multiplier(x, y):\n z = x*y\n return z\n" }, { "alpha_fraction": 0.6499999761581421, "alphanum_fraction": 0.6899999976158142, "avg_line_length": 24, "blob_id": "00c95a9cad1c6922da1d6ce3d4fa42a60319b4c2", "content_id": "f7df7a0fba67cdd520548584e1b8feb2baa4dfb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 100, "license_type": "no_license", "max_line_length": 29, "num_lines": 4, "path": "/Artificial Intelligence/Lab_1/test3_module.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "from module import *\nresult1 = adder(a, b)\nresult2 = multiplier(a, b)\nprint(result1, '\\n', result2)\n" }, { "alpha_fraction": 0.5539215803146362, "alphanum_fraction": 0.5980392098426819, "avg_line_length": 14.692307472229004, "blob_id": "fe64a7d69309d4f5cbb8db21518610c2ec320f30", "content_id": "18933a164af4c0a36fa256b0c29ebaaa5485600e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 205, "license_type": "no_license", "max_line_length": 49, "num_lines": 13, "path": "/C++ Data Structures/Lab_1/test.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// test.cpp\n// Lab_1\n//\n// Created by Mandeep Singh on 4/4/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include \"test.hpp\"\n\nvoid print_hello(){\n printf(\"print_hello just got called\\n\");\n}\n" }, { "alpha_fraction": 0.5502282977104187, "alphanum_fraction": 0.5958904027938843, "avg_line_length": 14.103447914123535, "blob_id": "46e4fe58c80f78cdff0c7efacfd85afb56780de1", "content_id": "53d90e0d95129c210cf1958877d0af44616cd883", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 439, "license_type": "no_license", "max_line_length": 49, "num_lines": 29, "path": "/C++ Data Structures/Lab_1/main.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// Lab_1\n//\n// Created by Mandeep Singh on 4/4/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include \"part1.hpp\"\n#include \"part2.hpp\"\n#include \"part3.hpp\"\n#include \"part4a.hpp\"\n#include \"part4b.hpp\"\n\nusing namespace std;\n\nint main(int argc, const char * argv[]) {\n \n part1();\n part2();\n part3();\n //part4a();\n //part4b();\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5717732310295105, "alphanum_fraction": 0.5934861302375793, "avg_line_length": 32.15999984741211, "blob_id": "af38ed7177fb49b6a5ef07e6c437b70a1d85dbc0", "content_id": "38f3d57f8e126ec33925119ceb47314190d4ad66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 829, "license_type": "no_license", "max_line_length": 181, "num_lines": 25, "path": "/SQL Databases/lab_1/load_data.php", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "<?php\n$conn=oci_connect('username','password', '//dbserver.engr.scu.edu/db11g');\nif($conn) {\n print \"<br> Connection to the database successful\";\n} else {\n $e = oci_error;\n print \"<br> connection failed:\";\n print htmlentities($e['message']);\n exit;\n}\n\necho \"<BR/>\";\n//Open and read contents of the text file, staff.txt\n$handle = fopen('./staff.txt', \"r\");\nfor($i =1;($data = fgetcsv($handle, 10000)) !== FALSE; $i++) {\n//\tPrepare the SQL statement to insert values \t\t\n$sql = \"INSERT INTO Staff_2010(Last,First,status,salary,salary_type,title) VALUES('\".$data[0].\"','\".$data[1].\"','\".$data[2].\"',\".$data[3].\",'\".$data[4].\"','\".$data[5].\"')\";\n$stid = oci_parse($conn, $sql);\n// Execute the statement\noci_execute($stid);\n}\noci_free_statement($stid);\noci_close($conn);\nfclose($handle);\n?>\n" }, { "alpha_fraction": 0.5061308145523071, "alphanum_fraction": 0.5705040693283081, "avg_line_length": 27.784313201904297, "blob_id": "11538252bd9c68a1e4afccdd37f229d65646fdfd", "content_id": "33f9fbf7aa7fdba7ce1027ba9892a280f68d905a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2937, "license_type": "no_license", "max_line_length": 106, "num_lines": 102, "path": "/Artificial Intelligence/Lab_5/facial_recognition.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "#\n# facial_recognition.py\n# Lab_5\n#\n# Created by Mandeep Singh on 11/8/19.\n# Copyright © 2019 Mandeep Singh. All rights reserved.\n#\n#cv2.imshow('img', training_set[2]); cv2.waitKey(0); cv2.destroyAllWindows()\nimport cv2\nimport numpy as np\n\nK=[1,2,3,6,10,20,30,50]\n\nfolders = ['att_faces_10/s1',\n 'att_faces_10/s2',\n 'att_faces_10/s3',\n 'att_faces_10/s4',\n 'att_faces_10/s5',\n 'att_faces_10/s6',\n 'att_faces_10/s7',\n 'att_faces_10/s8',\n 'att_faces_10/s9',\n 'att_faces_10/s10']\n\nimages = ['/1.pgm','/2.pgm','/3.pgm','/4.pgm','/5.pgm','/6.pgm','/7.pgm','/8.pgm','/9.pgm','/10.pgm']\n\nread_images = []\nfolder_counter = 0\nwhile folder_counter < 10:\n file_counter = 0\n while file_counter < 10:\n img = cv2.imread(folders[folder_counter] + images[file_counter])\n read_images.append(img)\n file_counter += 1\n folder_counter += 1\n\ntraining_images = []\nset_counter = 0\nfile_counter = 0\nx = [1,3,4,5,7,9]\nwhile file_counter < 10:\n count = 0\n while count < 6:\n training_images.append(read_images[x[count]-1])\n count += 1\n file_counter += 1\n if file_counter % 6 == 0:\n x[0]+=10\n x[1]+=10\n x[2]+=10\n x[3]+=10\n x[4]+=10\n x[5]+=10\n\ntraining_images = np.array(training_images)\ntraining_array = np.array(np.transpose([np.array(image).flatten() for image in training_images[:,:,:,0]]))\nmean = np.mean(training_array, axis = 1)\nmean = np.array(mean).reshape(10304, 1)\nU, S, Vh = np.linalg.svd(training_array, full_matrices = True)\nprint(\"U Shape: \", U.shape)\npercentageCorrect = {1:0,2:0,3:0,6:0,10:0,20:0,30:0,50:0}\n\ntesting_images = []\nfile_counter = 0\nx = [2,6,8,10]\nwhile file_counter < 10:\n count = 0\n while count < 4:\n testing_images.append(read_images[x[count]-1])\n count += 1\n file_counter += 1\n if file_counter % 4 == 0:\n x[0]+=10\n x[1]+=10\n x[2]+=10\n x[3]+=10\n\nfor num in range(1,10):\n testing_images = np.array(testing_images)\n testing_array = np.array([np.array(image).reshape(10304, 1) for image in testing_images[:,:,:,0]])\n testing_array = testing_array - mean\n for kval in K:\n sol = np.transpose(U[:,:kval])\n training_model = np.dot(sol, training_array)\n\n for test in testing_array:\n testing_projection = np.dot(sol, test)\n tile = np.tile(testing_projection,(1,60))\n\n dot = training_model - tile\n res = np.linalg.norm(dot, axis = 0)\n minimum = np.argmin(res,axis=0)\n k_nearest_neighbors = np.argsort(res)\n minimum_indices = k_nearest_neighbors.argsort()\n \n if (int(minimum/6)+1) == num:\n percentageCorrect[kval]+=1\n\n\nfor x in percentageCorrect:\n percentageCorrect[x] = percentageCorrect[x]/40\nprint(\"Percentage Correct (K-Rank,Percentage):\", percentageCorrect)\n" }, { "alpha_fraction": 0.3201153576374054, "alphanum_fraction": 0.4462869465351105, "avg_line_length": 20.33846092224121, "blob_id": "f968e4157e96d03d0fce3d78e9db8a29bf4b9b74", "content_id": "b3c6f3c25a7b7c43ce0d269d65a436b6a04c29e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1387, "license_type": "no_license", "max_line_length": 56, "num_lines": 65, "path": "/Computer Graphics Systems/HW_1/circle_fill.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "from PIL import Image #Import PIL library\nimport time\nimg = Image.new('RGB', (500, 500)) #Create back area box\npixels = img.load() #Load the pixels\n\n\ndef Midpoint(R):\n x = 0\n y = R\n h = 1.25 - R\n dE = 3\n dSE = -2 *(R) + 5\n \n while y > x:\n if h < 0:\n h += 2*x + 3\n dE = dE + 2\n dSE = dSE + 2\n else:\n h += 2*(x-y) + 5\n dE = dE + 2\n dSE = dSE + 4\n y = y - 1\n x = x + 1\n time.sleep(0.01)\n drawCircle(x,y)\n\n\ndef drawCircle(x,y):\n\n pixels[x+200,-y+200] = (255,0,0)\n pixels[-x+200,-y+200] = (255,0,0)\n temp = -x + 200\n while temp <= x+200:\n pixels[temp,-y+200] = (255,0,0)\n temp += 1\n\n pixels[y+200,-x+200] = (255,0,0)\n pixels[-y+200,-x+200] = (255,0,0)\n temp = -y + 200\n while temp <= y+200:\n pixels[temp,-x+200] = (255,0,0)\n temp += 1\n\n pixels[y+200,x+200] = (255,0,0)\n pixels[-y+200,x+200] = (255,0,0)\n temp = -y + 200\n while temp <= y+200:\n pixels[temp,x+200] = (255,0,0)\n temp += 1\n\n pixels[x+200,y+200] = (255,0,0)\n pixels[-x+200,y+200] = (255,0,0)\n temp = -x + 200\n while temp <= x+200:\n pixels[temp,y+200] = (255,0,0)\n temp += 1\n\ndef main():\n R = int(input(\"Enter Radius: \"))\n Midpoint(R)\n img.show()\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5447047352790833, "alphanum_fraction": 0.5628505349159241, "avg_line_length": 29.616161346435547, "blob_id": "43fe4c4ee0ccfc1b97997b30dfd1ae22427b72a2", "content_id": "0932c15ee5e96a56d7f951907ccf84da5db170cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3031, "license_type": "no_license", "max_line_length": 172, "num_lines": 99, "path": "/Computer Networks/Lab_1/main.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// Created by Behnam Dezfouli\n// CSEN, Santa Clara University\n//\n//\n// This program offers two options to the user:\n// -- Option 1: enables the user to copy a file to another file.\n// The user needs to enter the name of the source and destination files.\n// -- Option 2: enables the user to measure the performance of file copy.\n// In addition to the name of source and destination files, the user needs to enter the maximum source file size as well as the step size to increment the source file size.\n//\n//\n// double copier(FILE *s_file, FILE *d_file)\n// Precondition: s_file is a pointer to a file opened in read mode, d_file is a file pointer opened in write mode\n// Postcondition: Copies the contents of the file pointed to by s_file to the file pointed to by d_file\n//\n\n\n#include <stdio.h>\n#include <stdlib.h> // For exit()\n#include <time.h>\n\n#define SIZE 1\n#define DUM_CHAR 'A'\n\n\nvoid copier(FILE *s_file, FILE *d_file){\n char ch;\n while ((ch = fgetc(s_file)) != EOF)\n fputc(ch, d_file);\n}\n\n\nint main(){\n int option = 2;\n\n int maxFileSize = 1000000;\n int stepSize = 100000;\n clock_t start;\n clock_t end;\n double cpu_time_used;\n \n printf(\"Enter 1 to copy a file or enter 2 to measure the performance of file copy: \");\n scanf(\"%d\", &option);\n \n if ( option == 1 ){ // File copy\n\n FILE *s_file = fopen(\"/Users/msingh9001/Desktop/COEN_146L/Lab_1/Untitled.rtf\", \"r\");\n \n if(s_file == NULL){\n fclose(s_file);\n printf(\"Press any key to exit...\");\n exit(EXIT_FAILURE);\n }\n \n FILE *d_file = fopen(\"/Users/msingh9001/Desktop/COEN_146L/Lab_1/dest.rtf\", \"w\");\n \n// if(d_file == NULL){\n// fclose(d_file);\n// printf(\"Press any key to exit...\");\n// exit(EXIT_FAILURE);\n// }\n \n copier(s_file, d_file);\n printf(\"File has been copied\\n\");\n }\n \n else if ( option == 2 ){ // File copy with performance measurement\n\n printf(\"Please enter the maximum file size (in bytes): \");\n scanf(\"%d\", &maxFileSize);\n printf(\"Please enter the step size: \");\n scanf(\"%d\", &stepSize);\n \n FILE *s_file = fopen(\"/Users/msingh9001/Desktop/COEN_146L/Lab_1/Untitled.rtf\", \"r\");\n FILE *d_file = fopen(\"/Users/msingh9001/Desktop/COEN_146L/Lab_1/dest.rtf\", \"w\");\n \n int current_size = stepSize;\n while(current_size < maxFileSize){\n start = clock();\n int count = 0;\n char ch = fgetc(s_file);\n while(count <= current_size){\n fputc(ch, d_file);\n count++;\n }\n end = clock();\n cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;\n \n printf(\"The time to copy %d bytes was: %f\\n\", current_size, cpu_time_used);\n current_size += stepSize;\n }\n \n }else{\n printf(\"Invalid option!\\n\");\n exit(EXIT_FAILURE);\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.5530154705047607, "alphanum_fraction": 0.5593293905258179, "avg_line_length": 25.39655113220215, "blob_id": "867151c167835647b03472134ba4d73aced2e606", "content_id": "b4d0531b2a3f6c3f9e609ee5c423f7a9cf9f7d6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4594, "license_type": "no_license", "max_line_length": 95, "num_lines": 174, "path": "/C Data Structures/list.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// list.c\n//\n// Created by Mandeep Singh on 02/14/19.\n// Copyright © 2019 Mandeep Singh. All rights .\n//\n#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"list.h\" //Import libraries for usage\n\ntypedef struct list{ //Define our struct list\n int count; //Number of elements in list\n struct node *head; //Pointer to node structure\n int (*compare)(); //Pointer to compare function passed through\n}LIST;\n\ntypedef struct node{ //Define out struct node\n void *data; //pointer to data\n struct node *next; //pointer to next list elt\n struct node *prev; //pointer to prev list elt\n}NODE;\n\n//O(1)\nLIST *createList(int(*compare)()){ //Creates out set using variables initialized in struct list\n LIST *lp = malloc(sizeof(struct list)); //Allocate memory for list\n assert(lp != NULL); //Make sure list memory allocation is not NULL\n lp -> count = 0; //Initially set count to 0\n lp -> compare = compare;\n lp -> head = malloc(sizeof(struct node)); //Allocate memory for dummy node\n assert(lp -> head != NULL);\n lp -> head -> next = lp -> head; //Initially set head next pointer to head\n lp -> head -> prev = lp -> head; //Initially set head prev pointer to head\n return lp;\n}\n\n//O(n)\nvoid destroyList(LIST *lp){\n assert(lp != NULL);\n NODE *pDel = lp -> head -> next; //Set pDel to node we want to delete\n while(pDel != lp -> head){ //Starting from first node to last each node is freed\n NODE *pNext = pDel -> next;\n free(pDel);\n pDel = pNext;\n }\n free(lp -> head); //Free dummy node\n free(lp); //free list\n}\n\n//O(1)\nint numItems(LIST *lp){ //Return number of items in list\n return lp -> count;\n}\n\n//O(1)\nvoid addFirst(LIST *lp, void *item){\n NODE *pNew;\n pNew = malloc(sizeof(struct node));\n assert(pNew != NULL);\n \n pNew -> data = item;\n pNew -> next = lp -> head -> next;\n pNew -> prev = lp -> head;\n lp -> head -> next = pNew;\n pNew -> next -> prev = pNew;\n lp -> count++; //Add one from count to account for adding an elt\n}\n\n//O(1)\nvoid addLast(LIST *lp, void *item){\n NODE *pNew;\n pNew = malloc(sizeof(struct node));\n assert(pNew != NULL);\n \n pNew -> data = item;\n pNew -> next = lp -> head;\n pNew -> prev = lp -> head -> prev;\n lp -> head -> prev = pNew;\n pNew -> prev -> next = pNew;\n lp -> count++; //Add one from count to account for adding an elt\n}\n\n//O(1)\nvoid *removeFirst(LIST *lp){\n if(lp -> count == 0)\n return NULL;\n \n NODE *pDel = lp -> head -> next;\n lp -> head -> next = pDel -> next;\n pDel -> next -> prev = pDel -> prev;\n void* x = pDel -> data;\n free(pDel);\n lp -> count--; //Subtract one from count to account for deleting an elt\n return x;\n}\n\n//O(1)\nvoid *removeLast(LIST *lp){\n if(lp -> count == 0)\n return NULL;\n \n NODE *pDel = lp -> head -> prev;\n lp -> head -> prev = pDel -> prev;\n pDel -> prev -> next = pDel -> next;\n void* x = pDel -> data;\n free(pDel);\n lp -> count--; //Subtract one from count to account for deleting an elt\n return x;\n}\n\n//O(1)\nvoid *getFirst(LIST *lp){ //Use head next to return first elt\n assert(lp -> count > 0);\n return lp -> head -> next -> data;\n}\n\n//O(1)\nvoid *getLast(LIST *lp){ //Use head prev to return first elt\n assert(lp -> count > 0);\n return lp -> head -> prev -> data;\n}\n\n//O(n)\nvoid removeItem(LIST *lp, void* item){\n if(lp -> count == 0)\n return;\n \n NODE *pSearch = lp -> head -> next;\n \n while(pSearch != NULL){\n if(lp -> compare(pSearch -> data, item) == 0){\n NODE *pNext = pSearch -> next;\n NODE *pPrev = pSearch -> prev;\n pNext -> prev = pPrev;\n pPrev -> next = pNext;\n free(pSearch);\n lp -> count--;\n }else\n pSearch = pSearch -> next;\n }\n}\n\n//O(n)\nvoid *findItem(LIST *lp, void* item){\n if(lp -> count == 0)\n return NULL;\n \n NODE *pSearch = lp -> head -> next;\n \n while(pSearch != lp -> head){\n if(lp -> compare(pSearch -> data, item) == 0)\n return pSearch -> data;\n else\n pSearch = pSearch -> next;\n }\n return NULL;\n}\n\n//O(n)\nvoid *getItems(LIST *lp){\n void** ret = malloc(sizeof(void*)* lp -> count); //Allocate memory for array size of count\n assert(ret != NULL);\n \n int i = 0;\n NODE *pSearch = lp -> head -> next;\n while(pSearch != lp -> head){\n ret[i] = pSearch -> data;\n i++;\n pSearch = pSearch -> next;\n }\n return ret;\n}\n" }, { "alpha_fraction": 0.5649350881576538, "alphanum_fraction": 0.5687229633331299, "avg_line_length": 25.399999618530273, "blob_id": "6943649944f266bd0aac040910133072881c57c6", "content_id": "ec36d76b3c8242bc435c25daddf78b52ed6fbb68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1848, "license_type": "no_license", "max_line_length": 98, "num_lines": 70, "path": "/COEN_178_Final_Project_mSingh/Extra_Credit/getOrderInfo.php", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh*/\n/*COEN 178 Final Project*/\n/*PHP getOrderInfo*/\n<?php\n\nif ($_SERVER[\"REQUEST_METHOD\"] == \"POST\") {\n\n // collect input data from the form\n $itemid = $_POST['itemid'];\n $custid = $_POST['custid'];\n $orderid = $_POST['orderid'];\n $noofcopies = $_POST['noofcopies'];\n \n if (!empty($itemid)){\n $itemid = prepareInput($itemid);\n }\n if (!empty($custid)){\n $custid = prepareInput($custid);\n }\n if (!empty($orderid)){\n $orderid = prepareInput($orderid);\n }\n if (!empty($noofcopies)){\n $noofcopies = prepareInput($noofcopies);\n }\n\n insertItemOrderIntoDB($itemid,$custid, $orderid, $noofcopies);\n \n}\n\nfunction prepareInput($inputData){\n $inputData = trim($inputData);\n $inputData = htmlspecialchars($inputData);\n return $inputData;\n}\n\nfunction insertItemOrderIntoDB($itemid,$custid, $orderid, $noofcopies){\n $conn = oci_connect('username', 'password', '//dbserver.engr.scu.edu/db11g');\n \n if (!$conn) {\n $e = oci_error();\n trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);\n }\n if(!$conn) {\n print \"<br> connection failed:\";\n exit;\n }\n // Calling the PLSQL procedure, addItemOrder\n $sql = oci_parse($conn, 'begin addItemOrder(:item, :cust, :order, :no, sysdate, NULL); end;');\n\n oci_bind_by_name($sql, ':item', $itemid);\n oci_bind_by_name($sql, ':cust', $custid);\n oci_bind_by_name($sql, ':order', $orderid);\n oci_bind_by_name($sql, ':no', $noofcopies);\n\n // Execute the query\n $res = oci_execute($sql);\n \n if ($res){\n echo '<br><br> <p style=\"color:green;font-size:20px\">';\n echo \"Item Order Inserted </p>\";\n }\n else{\n $e = oci_error($query);\n echo $e['message'];\n }\n oci_free_statement($sql);\n OCILogoff($conn);\n}\n?>\n" }, { "alpha_fraction": 0.6935483813285828, "alphanum_fraction": 0.6935483813285828, "avg_line_length": 19.33333396911621, "blob_id": "ac2ff8c10b26284366ccc3c9dd4c272577c337cd", "content_id": "51a2ebbea6df3133c0f2557ca7656109f9e2672f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 62, "license_type": "no_license", "max_line_length": 45, "num_lines": 3, "path": "/Artificial Intelligence/Lab_2/test_case.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "import vaccum\n\ntest = vaccum.setdata(\"Dirty\", \"Dirty\", Left)\n\n" }, { "alpha_fraction": 0.6062004566192627, "alphanum_fraction": 0.6112473011016846, "avg_line_length": 29.021644592285156, "blob_id": "6f140bde92b1250b4038d62288f7be97dbe345bb", "content_id": "0b1a9c27179e57e31b4510643aec640745d53594", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6935, "license_type": "no_license", "max_line_length": 111, "num_lines": 231, "path": "/Artificial Intelligence/search_and_games/search.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "# search.py\n# ---------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\n\"\"\"\nIn search.py, you will implement generic search algorithms which are called by\nPacman agents (in searchAgents.py).\n\"\"\"\n\nimport util\nimport sys\nimport copy\n\nclass SearchProblem:\n \"\"\"\n This class outlines the structure of a search problem, but doesn't implement\n any of the methods (in object-oriented terminology: an abstract class).\n\n You do not need to change anything in this class, ever.\n \"\"\"\n\n def getStartState(self):\n \"\"\"\n Returns the start state for the search problem.\n \"\"\"\n util.raiseNotDefined()\n\n def goalTest(self, state):\n \"\"\"\n state: Search state\n\n Returns True if and only if the state is a valid goal state.\n \"\"\"\n util.raiseNotDefined()\n\n def getActions(self, state):\n \"\"\"\n Given a state, returns available actions.\n Returns a list of actions\n \"\"\" \n util.raiseNotDefined()\n\n def getResult(self, state, action):\n \"\"\"\n Given a state and an action, returns resulting state.\n \"\"\"\n util.raiseNotDefined()\n\n def getCost(self, state, action):\n \"\"\"\n Given a state and an action, returns step cost, which is the incremental cost \n of moving to that successor.\n \"\"\"\n util.raiseNotDefined()\n\n def getCostOfActions(self, actions):\n \"\"\"\n actions: A list of actions to take\n\n This method returns the total cost of a particular sequence of actions.\n The sequence must be composed of legal moves.\n \"\"\"\n util.raiseNotDefined()\n\nclass Node:\n \"\"\"\n Search node object for your convenience.\n\n This object uses the state of the node to compare equality and for its hash function,\n so you can use it in things like sets and priority queues if you want those structures\n to use the state for comparison.\n\n Example usage:\n >>> S = Node(\"Start\", None, None, 0)\n >>> A1 = Node(\"A\", S, \"Up\", 4)\n >>> B1 = Node(\"B\", S, \"Down\", 3)\n >>> B2 = Node(\"B\", A1, \"Left\", 6)\n >>> B1 == B2\n True\n >>> A1 == B2\n False\n >>> node_list1 = [B1, B2]\n >>> B1 in node_list1\n True\n >>> A1 in node_list1\n False\n \"\"\"\n def __init__(self, state, parent, action, path_cost):\n self.state = state\n self.parent = parent\n self.action = action\n self.path_cost = path_cost\n\n def __hash__(self):\n return hash(self.state)\n\n def __eq__(self, other):\n return self.state == other.state\n\n def __ne__(self, other):\n return self.state != other.state\n\n\ndef tinyMazeSearch(problem):\n \"\"\"\n Returns a sequence of moves that solves tinyMaze. For any other maze, the\n sequence of moves will be incorrect, so only use this for tinyMaze.\n \"\"\"\n from game import Directions\n s = Directions.SOUTH\n w = Directions.WEST\n return [s, s, w, s, w, w, s, w]\n\ndef breadthFirstSearch(problem):\n \"\"\"\n Search the shallowest nodes in the search tree first.\n\n You are not required to implement this, but you may find it useful for Q5.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n util.raiseNotDefined()\n\ndef nullHeuristic(state, problem=None):\n \"\"\"\n A heuristic function estimates the cost from the current state to the nearest\n goal in the provided SearchProblem. This heuristic is trivial.\n \"\"\"\n return 0\n\ndef iterativeDeepeningSearch(problem):\n \"\"\"\n Perform DFS with increasingly larger depth. Begin with a depth of 1 and increment depth by 1 at every step.\n\n Your search algorithm needs to return a list of actions that reaches the\n goal. Make sure to implement a graph search algorithm.\n\n To get started, you might want to try some of these simple commands to\n understand the search problem that is being passed in:\n\n print(\"Start:\", problem.getStartState())\n print(\"Is the start a goal?\", problem.goalTest(problem.getStartState()))\n print(\"Actions from start state:\", problem.getActions(problem.getStartState()))\n\n Then try to print the resulting state for one of those actions\n by calling problem.getResult(problem.getStartState(), one_of_the_actions)\n or the resulting cost for one of these actions\n by calling problem.getCost(problem.getStartState(), one_of_the_actions)\n\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n \n \n d = 0\n while d >= 0:\n print(\"Depth is:\", d)\n global a\n a = []\n res = d_limited_search(problem, d)\n d += 1\n if res != \"coff\":\n return res\n\ndef d_limited_search(problem, limit):\n s_node = Node(problem.getStartState(), None, None, 0)\n return recursive_dls(s_node, problem, limit)\n \ndef recursive_dls(node, problem, limit):\n if problem.goalTest(node.state):\n return a\n elif limit == 0:\n return \"coff\"\n else:\n coff_occured = False\n for action in problem.getActions(node.state):\n ns = problem.getResult(node.state, action)\n npc = problem.getCost(node.state, action)\n na = action\n np = node\n c = Node(ns, np, na, npc)\n a.append(action)\n res = recursive_dls(c, problem, limit - 1)\n if res == \"coff\":\n a.pop(-1)\n coff_occured = True\n elif res != \"failure\":\n return res\n if coff_occured == True:\n return \"coff\"\n else:\n return \"failure\"\n\n util.raiseNotDefined()\n\ndef aStarSearch(problem, heuristic=nullHeuristic):\n \"\"\"Search the node that has the lowest combined cost and heuristic first.\"\"\"\n \"*** YOUR CODE HERE ***\"\n b = util.PriorityQueue()\n n = problem.getStartState()\n b.push(n, 0)\n vis = {}\n p = {}\n vis[n] = 0\n p[n] = []\n while not b.isEmpty():\n n = b.pop()\n if problem.goalTest(n):\n return p[n]\n for action in problem.getActions(n):\n c_node = problem.getResult(n, action)\n cost_c_node = problem.getCostOfActions(p[n] + [action]) + heuristic(c_node, problem)\n if not c_node in vis or vis[c_node] > cost_c_node:\n p[c_node] = p[n] + [action]\n vis[c_node] = cost_c_node\n b.push(c_node, cost_c_node)\n\n util.raiseNotDefined()\n\n# Abbreviations\nbfs = breadthFirstSearch\nastar = aStarSearch\nids = iterativeDeepeningSearch\n" }, { "alpha_fraction": 0.5639943480491638, "alphanum_fraction": 0.5963431596755981, "avg_line_length": 21.935483932495117, "blob_id": "82265e924576b2724e4592ca876544defe4ed536", "content_id": "1825b0a62f16b9fd29e5959d52ece1237ca180f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1424, "license_type": "no_license", "max_line_length": 84, "num_lines": 62, "path": "/Operating Systems/Lab_5/producer_consumer.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//Name: Mandeep Singh\n//Date: 01/27/20\n//Title: Lab3 - Pthreads and inter-process Communication – Pipes\n//Description: Producer and Consumer problem using a single buffer for two processes\n\n#include <stdio.h>\n#include <stdlib.h>\n#define RAND_DIVISOR 100000000\n\nint mutex = 1, full = 0, empty = 3, x = 0, item;\nvoid producer2();\nvoid consumer2();\nint wait2(int);\nint signal2();\n\nint main(){\n printf(\"\\n1.Producer\\n2.Exit\");\n while(1){\n int rNum = rand() / RAND_DIVISOR;\n\n// Generate a random number\n item = rand();\n// Produces the item\n if((mutex == 1) && (empty != 0))\n producer2();\n else\n printf(\"Buffer is full\");\n// Consumes the item\n if((mutex == 1) && (full != 0))\n consumer2();\n else\n printf(\"The buffer is empty\");\n }\n return 0;\n}\n\nint wait2(int s){\n return(--s);\n}\n\nint signal2(int s){\n return(++s);\n}\n//Producer waits for signal and if buffer is not full produces item\nvoid producer2(){\n mutex=wait2(mutex);\n full=signal2(full);\n empty=wait2(empty);\n x++;\n printf(\"\\nProducer produces the item %d\",item);\n mutex=signal2(mutex);\n}\n\n//Consumer waits for signal and if buffer is not empty comsumes item\nvoid consumer2(){\n mutex = wait2(mutex);\n full=wait2(full);\n empty=signal2(empty);\n printf(\"\\nConsumer consumes item %d\",item);\n x--;\n mutex=signal2(mutex);\n}\n" }, { "alpha_fraction": 0.5307644605636597, "alphanum_fraction": 0.5515848398208618, "avg_line_length": 26.27118682861328, "blob_id": "60472ac4e1894e6bc949f8f5e71643e1962ab3ef", "content_id": "419905ea6891c4a907e7ec9930147a466e7e92bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3219, "license_type": "no_license", "max_line_length": 109, "num_lines": 118, "path": "/C Data Structures/huffman.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// huffman.c\n//\n// Created by Mandeep Singh on 03/07/19.\n// Copyright © 2019 Mandeep Singh. All rights .\n//\n//Utilizing priority queue with huffman coding to make a file compresser\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>//Import libraries for usage\n#include \"pack.h\"\n#include \"pqueue.h\"\n\nstruct node *mkNode(int data, struct node *left, struct node *right);\nint compare(struct node *node1, struct node *node2);\nvoid in(char *fIn, char *fOut);\nint depth(struct node *node);\nstruct node *nodes[257];\n\n//O(1)\nint main(int argc, char *argv[]){\n if(argc == 2){\n printf(\"Wrong args\\n\");\n return 1;\n }\n \n in(argv[1], argv[2]);\n return 0;\n}\n\n//O(1)\nstruct node *mkNode(int data, struct node *left, struct node *right){\n assert(left != NULL && right != NULL);\n struct node *newNode = malloc(sizeof(struct node));\n assert(newNode != NULL);\n newNode -> count = data;\n left -> parent = newNode;\n right -> parent = newNode;\n return newNode;\n}\n\n//O(1)\nint compare(struct node *node1, struct node *node2){\n assert(node1 != NULL && node2 != NULL);\n return (node1 -> count < node2 -> count) ? -1 : (node1 -> count > node2 -> count);\n}\n\n//O(1)\nint depth(struct node *node){\n if(node -> parent == NULL)\n return 0;\n return 1 + depth(node -> parent);\n}\n\n//O(n)\nvoid in(char *fIn, char *fOut){\n FILE *fp;\n \n fp = fopen(fIn, \"r\"); //Opens file\n if (fp == NULL)\n return;\n \n int arr[257]; //Creating array with each index holding the number of occurences for a different character\n \n for(int i = 0; i < 257; i++){\n arr[i] = 0;\n nodes[i] = NULL;\n }\n \n int j;\n while((j = fgetc(fp)) != EOF){ //Count number of occurences of each character\n arr[j]++;\n }\n \n for(int k = 0; k < 256; k++){ //creating leaves\n if(arr[k] != 0){\n struct node *leaf = malloc(sizeof(struct node));\n assert(leaf != NULL);\n leaf -> count = arr[k];\n nodes[k] = leaf;\n }\n }\n \n struct node *eLeaf = malloc(sizeof(struct node)); //creating the end leaf of the file\n assert(eLeaf != NULL);\n eLeaf -> count = 0;\n nodes[256] = eLeaf;\n fclose(fp);\n \n PQ *priorityQueue = createQueue(compare); //Creating the heap pq\n for(int l = 0; l < 257; l++) {\n if (nodes[l] != NULL) {\n addEntry(priorityQueue, nodes[l]);\n }\n }\n \n while(numEntries(priorityQueue) > 1) { //Creating the huffman tree with pq\n struct node *node1 = removeEntry(priorityQueue);\n struct node *node2 = removeEntry(priorityQueue);\n struct node *temp = mkNode((node1 -> count) + (node2 -> count), node1, node2);\n addEntry(priorityQueue, temp);\n }\n \n for(int m = 0; m < 257; m++) { //printing the data\n if (nodes[m] != NULL) {\n if (isprint(m)) {\n printf(\"\\'%c\\': \", m);\n } else {\n printf(\"%o: \", m);\n }\n printf(\"%d x %d bits = %d bits\\n\", arr[m], depth(nodes[m]), arr[m] * depth(nodes[m]));\n }\n }\n \n pack(fIn, fOut, nodes); //pack nodes\n destroyQueue(priorityQueue); //destroy the queue\n}\n" }, { "alpha_fraction": 0.5817757248878479, "alphanum_fraction": 0.5855140089988708, "avg_line_length": 26.435897827148438, "blob_id": "39c6c11f7f6f70970c04bfbb71c7ef91c228d8ce", "content_id": "0b31ba64daff6f5780554eb8540572323c8bf3e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4280, "license_type": "no_license", "max_line_length": 86, "num_lines": 156, "path": "/COEN_178_Final_Project_mSingh/Extra_Credit/showOrderInfo.php", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh\nCOEN 178 Final Project\nPHP showOrderInfo*/\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\"/>\n <title>Show Order Info</title>\n </head>\n <body>\n<form method=\"post\" action=\"<?php echo htmlspecialchars($_SERVER[\"PHP_SELF\"]);?>\">\n Order ID: <input type=\"text\" name=\"orderid\" id=\"orderid\">\n <input type=\"submit\">\n </form>\n<?php\nif ($_SERVER[\"REQUEST_METHOD\"] == \"POST\") {\n # collect input data\n $orderid = $_POST['orderid'];\n\n if (!empty($orderid)){\n $orderid = prepareInput($orderid);\n $itemid = getItemidFromDB($orderid);\n $custid = getCustidFromDB($orderid);\n $dateOfOrder = getDateoforderFromDB($orderid);\n $noOfItems = getNoofitemsFromDB($orderid);\n $shippingFee = getShippingfeeFromDB($orderid);\n echo \"Order ID: $orderid <br>\";\n echo \"Item ID: $itemid <br>\";\n echo \"Customer ID: $custid <br>\";\n echo \"Date of Order: $dateOfOrder <br>\";\n echo \"Number of Items: $noOfItems <br>\";\n echo \"Shipping Fee: $shippingFee <br>\";\n }\n}\n\nfunction getItemidFromDB($orderid){\n $conn=oci_connect('username','password', '//dbserver.engr.scu.edu/db11g');\n if(!$conn) {\n print \"<br> connection failed:\";\n exit;\n }\n $query = oci_parse($conn, \"SELECT itemid FROM itemOrder where orderid= :bv\");\n oci_bind_by_name($query,':bv',$orderid);\n oci_execute($query);\n\n if (($row = oci_fetch_array($query, OCI_BOTH)) != false) {\n $itemid = $row[0];\n }\n else {\n echo \"Error <br>\\n\";\n }\n oci_free_statement($query);\n oci_close($conn);\n\n return $itemid;\n }\n\nfunction getCustidFromDB($orderid){\n $conn=oci_connect('username','password', '//dbserver.engr.scu.edu/db11g');\n if(!$conn) {\n print \"<br> connection failed:\";\n exit;\n }\n $query = oci_parse($conn, \"SELECT custid FROM itemOrder where orderid= $orderid\");\n oci_execute($query);\n\n if (($row = oci_fetch_array($query, OCI_BOTH)) != false) {\n $custid = $row[0];\n }\n else {\n echo \"Error <br>\\n\";\n }\n oci_free_statement($query);\n oci_close($conn);\n\n return $custid;\n}\n\nfunction getDateoforderFromDB($orderid){\n $conn=oci_connect('username','password', '//dbserver.engr.scu.edu/db11g');\n if(!$conn) {\n print \"<br> connection failed:\";\n exit;\n }\n $query = oci_parse($conn, \"SELECT dateOfOrder FROM itemOrder where orderid= :bv\");\n oci_bind_by_name($query,':bv',$orderid);\n oci_execute($query);\n\n if (($row = oci_fetch_array($query, OCI_BOTH)) != false) {\n $dateOfOrder = $row['DATEOFORDER'];\n }\n else {\n echo \"Error <br>\\n\";\n }\n oci_free_statement($query);\n oci_close($conn);\n\n return $dateOfOrder;\n }\n\nfunction getNoofitemsFromDB($orderid){\n $conn=oci_connect('username','password', '//dbserver.engr.scu.edu/db11g');\n if(!$conn) {\n print \"<br> connection failed:\";\n exit;\n }\n $query = oci_parse($conn, \"SELECT noOfItems FROM itemOrder where orderid= :bv\");\n oci_bind_by_name($query,':bv',$orderid);\n oci_execute($query);\n\n if (($row = oci_fetch_array($query, OCI_BOTH)) != false) {\n $noOfItems = $row['NOOFITEMS'];\n }\n else {\n echo \"Error <br>\\n\";\n }\n oci_free_statement($query);\n oci_close($conn);\n\n return $noOfItems;\n}\n \nfunction getShippingfeeFromDB($orderid){\n $conn=oci_connect('username','password', '//dbserver.engr.scu.edu/db11g');\n if(!$conn) {\n print \"<br> connection failed:\";\n exit;\n }\n $query = oci_parse($conn, \"SELECT shippingFee FROM itemOrder where orderid= :bv\");\n oci_bind_by_name($query,':bv',$orderid);\n oci_execute($query);\n\n if (($row = oci_fetch_array($query, OCI_BOTH)) != false) {\n $shippingFee = $row['SHIPPINGFEE'];\n }\n else {\n echo \"Error <br>\\n\";\n }\n oci_free_statement($query);\n oci_close($conn);\n\n return $shippingFee;\n}\n \nfunction prepareInput($inputData){\n // Removes any leading or trailing white space\n $inputData = trim($inputData);\n // Removes any special characters that are not allowed in the input\n $inputData = htmlspecialchars($inputData);\n return $inputData;\n}\n\n?>\n<!-- end PHP script -->\n </body>\n</html>\n" }, { "alpha_fraction": 0.5356371402740479, "alphanum_fraction": 0.5626350045204163, "avg_line_length": 25.457143783569336, "blob_id": "084ddadd9f18198927b3020f08ec42b6cd60536d", "content_id": "194b070a00ed296376abe33a6afffd28c699ecc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 928, "license_type": "no_license", "max_line_length": 91, "num_lines": 35, "path": "/Operating Systems/Lab_3/lab3_part_4.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//Name: Mandeep Singh\n//Date: 01/27/20\n//Title: Lab3 - Pthreads and inter-process Communication – Pipes\n//Description: Pipes grep root to cat /etc/passwd\n#include <stdio.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <sys/wait.h>\n\nint main(int argc,char *argv[]){\n int fds[2];\n// Create pipe\n pipe(fds);\n if (fork() == 0) {\n// Close read and set output stream to go to write and run grep root\n dup2(fds[0], 0);\n close(fds[1]);\n execlp(\"grep\", \"grep\", \"root\", 0);\n }\n else if(fork() == 0){\n// Close write and read input stream and run cat /etc/passwd\n dup2(fds[1], 1);\n close(fds[0]);\n execlp(\"cat\", \"cat\", \"/etc/passwd\", 0);\n \n }else{\n// Parent Process closes both read and write and waits for child processes to finish\n close(fds[0]);\n close(fds[1]);\n wait(0);\n wait(0);\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.5831658244132996, "alphanum_fraction": 0.5896984934806824, "avg_line_length": 21.480226516723633, "blob_id": "c33ec28c6d64879f47864a345a0ca49245c06b91", "content_id": "372cf4ca533305deb33cad8b6b59170cabcc9d24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3980, "license_type": "no_license", "max_line_length": 115, "num_lines": 177, "path": "/Computer Networks/Lab_6/server.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "// SCU COEN 146\n//\n// This program implements the server side of stop & wait protocol\n// the server receives file contents from a client\n//\n//\n// For the stop and wait protocol, the assumestions are:\n// -- packet corruption, and packet loss\n\n\n#include\t\"tfv1.h\"\n\n// global variables\nint state = 0; // we only have two states: 0 and 1\nint sock;\nstruct sockaddr_in serverAddr;\nsocklen_t addr_size;\n\n// list of functions\nint main (int, char *[]);\nint my_receive (PACKET *);\nint calc_checksum (char *, int);\n\n\n\nint main (int argc, char *argv[])\n{\n\tFILE\t*fp;\n\tint\t\tn;\n\tPACKET\tbuf;\n\n\n if (argc != 2)\n {\n printf (\"need the port number\\n\");\n return 1;\n }\n\n \n // STUDENT WORK\n \n\n\t// create socket\n\tif ((sock = socket (AF_INET, SOCK_DGRAM, 0)) < 0)\n\t{\n\t\tprintf (\"socket error\\n\");\n\t\treturn 1;\n\t}\n\n\t// bind\n\tif (bind (sock, (struct sockaddr *)&serverAddr, sizeof (serverAddr)) != 0)\n\t{\n\t\tprintf (\"bind error\\n\");\n\t\treturn 1;\n\t}\n\n // NOTE: this program uses UDP socket, so there is no need to listen to incoming connections!\n \n\t// receive name of the file\n // my_receive() function ensures the received data chunks are not corrupted\n\tif ((n = my_receive (&buf)) <= 0)\n\t{\n\t\tprintf (\"could not get the name of the file\\n\");\n\t\treturn 1;\n\t}\n printf (\"File name has been received!\\n\");\n \n\n\t// open file\n\tif ((fp = fopen (buf.data, \"wb\")) == NULL)\n\t{\n\t\tprintf (\"error fopen\\n\");\n\t\treturn 1;\n\t}\n\n \n\tprintf (\"Receiving file %s ... \\n\", buf.data);\n // my_receive() function ensures the received data chunks are not corrupted\n\twhile ((n = my_receive (&buf)) > 0)\n\t{\n\t\tprintf (\"writing to file... n = %d\\n\", n);\n // STUDENT WORK\n fp = fopen(\"output.txt\", \"r\");\n write(fp, buff.data, buff.len);\n \n\t}\n\n\tclose (sock);\n\tfclose (fp);\n\n\treturn 0;\n}\n\n\n\n// my_receive() function ensures the received data chunks are not corrupted\nint my_receive (PACKET *recv_pck)\n{\n int cs_in;\n\tint cs_calc;\n\tint\td;\n\tint r;\n\tint nbytes;\n\n\tHEADER\t\t\tack_packet;\n\tstruct sockaddr\tret_addr;\n\tsocklen_t\t\taddr_size = sizeof (ret_addr);\n\n\n\twhile (1)\n\t{\n // ssize_t recvfrom(int socket, void *restrict buffer, size_t length,\n // int flags, struct sockaddr *restrict address, socklen_t *restrict address_len);\n // buffer: Points to the buffer where the message should be stored.\n // address: A null pointer, or points to a sockaddr structure in which the sending address is to be stored.\n // The length and format of the address depend on the address family of the socket.\n // address_len: Specifies the length of the sockaddr structure pointed to by the address argument.\n\t\tif ((nbytes = recvfrom (sock, recv_pck, sizeof(PACKET), 0, &ret_addr, &addr_size)) < 0)\n\t\t\treturn -1;\n\t\n printf (\"Received a UDP packet!\\n\");\n \n\t\tcs_in = recv_pck->header.checksum;\n\t\trecv_pck->header.checksum = 0;\n \n // recalculate checksum\n // STUDENT WORK\n \n // check if checksum matches, and the sequence number is correct too\n if (cs_in == cs_calc && recv_pck->header.seq_ack == state)\n\t\t{\n printf (\"Checksum passed! Sequence number matched!\\n\");\n\n\t\t\t// good packet\n // STUDENT WORK\n \n \n // simulating erroneous channel...corruption and loss\n // STUDENT WORK\n \n\t\t\t// now we are expecting the next packet\n // STUDENT WORK\n \n\t\t\treturn recv_pck->header.len;\n\t\t}\n\t\telse\n\t\t{\n printf (\"Checksum/sequence number check failed!\\n\");\n\n\t\t\t// bad packet\n // STUDENT WORK\n \n printf (\"Resending ack for sequence number: %d...\\n\", ack_packet.seq_ack );\n\n \n // simulating erroneous channel...corruption and loss\n // STUDENT WORK\n\n\t\t}\n\n\t}\n\n\treturn -1;\n}\n\n\n\nint calc_checksum (char *buf, int tbytes)\n{\n int i;\n char cs = 0;\n char *p;\n\n // STUDENT WORK\n \n return (int)cs;\n}\n\n" }, { "alpha_fraction": 0.5258554220199585, "alphanum_fraction": 0.5352457165718079, "avg_line_length": 32.08085250854492, "blob_id": "d8f39fd65d6230eb14aa4d8d5da18305c16eeb40", "content_id": "c8dbcab61936386ebff8ab839aa207c91fabdff5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7774, "license_type": "no_license", "max_line_length": 135, "num_lines": 235, "path": "/Computer Networks/Lab_3/http_server.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "// Created by Behnam Dezfouli\n// CSEN, Santa Clara University\n//\n\n// This program implements a web server\n//\n// The input arguments are as follows:\n// argv[1]: Sever's port number\n\n\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <errno.h>\n#include <string.h>\n#include <sys/types.h>\n#include <signal.h>\n#include <sys/stat.h> // to get file size\n\n\n#define COMMAND_BUFF 15000 // Size of the buffer used to store the result of command execution\n#define SOCK_READ_BUFF 4096 // Size of the buffer used to store the bytes read over socket\n#define REPLY_BUFF 20000 // Size of the buffer used to store the message sent to client\n#define FILE_READ 10\n\n#define HTML_FILE \"index.html\"\n\n\n// Socket descriptors\nint socket_fd = 0; // socket descriptor\nint connection_fd = 0; // new connection descriptor\n\n\nvoid INThandler(int sig)\n{\n char input;\n \n signal(sig, SIG_IGN);\n printf(\"Did you hit Ctrl-C?\\n\"\n \"Do you want to quit? [y/n] \");\n \n input = getchar();\n \n //STUDENT WORK\n if(input == 'y' || input == 'Y')\n EXIT_FAILURE;\n else\n signal(SIGINT, INThandler);\n}\n\n\n// main function ---------------\nint main (int argc, char *argv[])\n{\n \n // Register a function to handle SIGINT ( SIGNINT is interrupt the process )\n signal(SIGINT, INThandler);\n \n \n int net_bytes_read; // numer of bytes received over socket\n struct sockaddr_in serv_addr; // Address format structure\n char net_buff[SOCK_READ_BUFF]; // buffer to hold characters read from socket\n char message_buff[REPLY_BUFF]; // buffer to hold the message to be sent to the client\n \n char file_buff[FILE_READ]; // to hold the bytes read from source file\n FILE *source_file = fopen(HTML_FILE, \"r\"); // pointer to the source file\n \n \n // pointer to the file that will include the received bytes over socket\n FILE *dest_file;\n \n \n if (argc < 2) // Note: the name of the program is counted as an argument\n {\n printf (\"Port number not specified!\\n\");\n return 1;\n }\n \n \n \n // STUDENT WORK\n serv_addr.sin_family = AF_INET;\n serv_addr.sin_addr.s_addr = htonl (INADDR_ANY);\n serv_addr.sin_port = htons (atoi (argv[1]));\n \n \n \n // Create socket\n if ((socket_fd = socket (AF_INET, SOCK_STREAM, 0)) < 0)\n {\n printf (\"Error: Could not create socket! \\n\");\n return 1;\n }\n \n // To prevent \"Address in use\" error\n // The SO_REUSEADDR socket option, which explicitly allows a process to bind to a port which remains in TIME_WAIT\n // STUDENT WORK\n \n \n \n \n // bind it to all interfaces, on the specified port number\n // STUDENT WORK\n bind(socket_fd, (const struct sockaddr*)&serv_addr, sizeof (serv_addr));\n \n \n // Accept up to 1 connections\n if (listen(socket_fd, 1) < 0)\n {\n perror(\"Listen failed!\");\n exit(EXIT_FAILURE);\n }\n \n printf (\"Listening to incoming connections... \\n\");\n \n \n unsigned int option = 0; // Variable to hold user option\n printf(\"1: System network configuration \\n2: Regular HTTP server\\n\");\n scanf(\"%u\", &option);\n \n // The web server returns current processor and memory utilization\n if ( option == 1 )\n {\n printf(\"System network configuration (using ifconfig)... \\n\");\n }\n // The requested file is returned\n else if (option == 2)\n {\n printf(\"Regular server (only serving html files)... \\n\\n\");\n }\n else\n printf (\"Invalid Option! \\n\\n\");\n \n \n while (1)\n {\n // Accept incoming connection request from client\n // STUDENT WORK\n connection_fd = accept(socket_fd, (struct sockaddr *)NULL, NULL);\n memset (net_buff, '\\0', sizeof (net_buff));\n \n printf (\"Incoming connection: Accepted! \\n\");\n \n // Return system utilization info\n if ( option == 1 )\n {\n // run a command -- we run ifconfig here (you can try other commands as well)\n FILE *system_info;\n char line[500];\n char command[] = \"ifconfig\";\n \n system_info = popen(command, \"r\");\n \n if(system_info){\n while(fgets( line, sizeof line, system_info))//get each line o by one from the output of the command\n printf(\"%s\", line);\n \n \n // STUDENT WORK\n strncpy(message_buff, \"HTTP/1.1 200 OK\\n\", strlen(\"HTTP/1.1 200 OK\\n\"));\n strncpy(message_buff + strlen(message_buff), \"Server: SCU COEN Web Server\\n\", strlen(\"Server: SCU COEN Web Server\\n\"));\n strncpy(message_buff + strlen(message_buff), \"Content-length: \", strlen(\"Content-length: \"));\n char content_length[10] = {'0'};\n sprintf(content_length, \"%lu\\n\", sizeof(system_info));\n strncpy(message_buff + strlen(message_buff), content_length, strlen(content_length));\n write(socket_fd, message_buff, sizeof message_buff);\n \n shutdown (connection_fd, SHUT_RDWR);\n close (connection_fd);\n\n }else\n printf ( \"***** popen failed: *****\");\n \n shutdown (connection_fd, SHUT_RDWR);\n close (connection_fd);\n }\n \n else if (option == 2)\n {\n // To get the size of html file\n struct stat sbuf; /* file status */\n \n // make sure the file exists\n // HTML_FILE is index.html and is statically defined\n if (stat(HTML_FILE, &sbuf) < 0) {\n // STUDENT WORK\n strncpy(message_buff, \"HTTP/1.1 200 OK\\n\", strlen(\"HTTP/1.1 200 OK\\n\"));\n \n strncpy(message_buff + strlen(message_buff), \"Server: SCU COEN Web Server\\n\", strlen(\"Server: SCU COEN Web Server\\n\"));\n strncpy(message_buff + strlen(message_buff), \"Content-length: \", strlen(\"Content-length: \"));\n char content_length[10] = {'0'};\n sprintf(content_length, \"%d\\n\", (int)sbuf.st_size);\n strncpy(message_buff + strlen(message_buff), content_length, strlen(content_length));\n strncpy(message_buff + strlen(message_buff), \"Content-type: text/html\\n\", strlen(\"Content-type: text/plain\\n\"));\n write(socket_fd, message_buff, sizeof message_buff);\n }\n \n \n // Open the source file\n if (source_file == NULL)\n {\n printf (\"Error: could not open the source file!\\n\");\n \n // STUDENT WORK\n shutdown (connection_fd, SHUT_RDWR);\n close (connection_fd);\n return 1;\n }\n \n else\n {\n // STUDENT WORK\n dest_file = fopen(net_buff, \"wb\");\n printf(\"Here is the message: %s\\n\", net_buff);\n memset (net_buff, '\\0', sizeof(net_buff));\n \n while ((net_bytes_read = fread(net_buff, sizeof(char), 20, source_file)) > 0){\n write(socket_fd, net_buff, net_bytes_read);\n memset (net_buff, '\\0', sizeof (net_buff));\n }\n \n \n printf(\"Reply sent to the client!\\n\");\n }\n \n shutdown (connection_fd, SHUT_RDWR);\n close (connection_fd);\n }\n }\n \n close (socket_fd);\n}\n" }, { "alpha_fraction": 0.7148499488830566, "alphanum_fraction": 0.7448657155036926, "avg_line_length": 24.34000015258789, "blob_id": "a9e31c1ad0152ce5e84312536c12aed7e8b1e6a7", "content_id": "c79d38a3aece9d8d3d0629d458c85ea8a18675df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1266, "license_type": "no_license", "max_line_length": 61, "num_lines": 50, "path": "/COEN_178_Final_Project_mSingh/tables.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh*/\n/*COEN 178 Final Project*/\n/*createTables*/\n/*Create storeItems table*/\nCreate table storeItems(\n\tItemid varchar(10) primary key,\n\tPrice number(10, 2)\n);\n/*Create comicBook table*/\nCreate table comicbook(\n\tItemid varchar(10),\n\tISBN varchar(10) primary key,\n\tTitle varchar(20),\n\tPublisheddate date,\n\tNoofcopies int check (Noofcopies >= 0),\n\tForeign key (Itemid) References storeItems(Itemid)\n);\n/*Create Tshirt table*/\nCreate table Tshirt(\n\tItemid varchar(10),\n\tSizes int,\n\tForeign key(Itemid) References storeItems(Itemid)\n);\n/*Create Customers table*/\nCreate table Customers(\n\tCustid varchar(10) primary key,\n\tcusttype varchar(10) check(custtype in ('regular', 'gold')),\n\tphone varchar(10) unique not null,\n\tname varchar(20),\n\taddress varchar(50)\n);\n/*Create Goldcustomer table*/\nCreate table Goldcustomer(\n\tCustid varchar(20),\n\tDatejoined date,\n\tForeign key (custid) references customers (custid)\n);\n/*Create Itemorder table*/\nCreate table Itemorder(\n\tOrderid varchar (10) primary key,\n\tItemid varchar (10),\n\tCustid varchar (10),\n\tDateOfOrder date,\n\tNoofItems int,\n\tShippeddate date,\n\tShippingFee number(10, 2),\n\tcheck (shippeddate >= dateoforder),\n\tForeign key(custid) references customers(custid),\n\tForeign key(itemid) references storeItems(itemid)\n);" }, { "alpha_fraction": 0.5411103367805481, "alphanum_fraction": 0.5460295081138611, "avg_line_length": 21.95161247253418, "blob_id": "691e1623a1edaa1459ea9c3563e56584f7368695", "content_id": "01829ee38fc43436135a4c0503dfbe7d068fe028", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1423, "license_type": "no_license", "max_line_length": 81, "num_lines": 62, "path": "/COEN_178_Final_Project_mSingh/Extra_Credit/setShippingDate.php", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh*/\n/*COEN 178 Final Project*/\n/*PHP setShippingDate*/\n<?php\n\nif ($_SERVER[\"REQUEST_METHOD\"] == \"POST\") {\n\n // collect input data from the form\n $orderid = $_POST['orderid'];\n $date = $_POST['date'];\n \n if (!empty($orderid)){\n $orderid = prepareInput($orderid);\n }\n \n if (!empty($date)){\n $date = prepareInput($date);\n }\n \n setShippingDate($orderid, $date);\n \n}\n\nfunction prepareInput($inputData){\n $inputData = trim($inputData);\n $inputData = htmlspecialchars($inputData);\n return $inputData;\n}\n\nfunction setShippingDate($orderid, $date){\n $conn = oci_connect('username', 'password', '//dbserver.engr.scu.edu/db11g');\n \n if (!$conn) {\n $e = oci_error();\n trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);\n }\n if(!$conn) {\n print \"<br> connection failed:\";\n exit;\n }\n // Running PSQL function\n $sql = oci_parse($conn, 'begin setShippingDate(:order, :date,); end;');\n\n oci_bind_by_name($sql, ':order', $orderid);\n oci_bind_by_name($sql, ':date', $date);\n \n // Execute the query\n $res = oci_execute($sql);\n \n if ($res){\n echo '<br><br> <p style=\"color:green;font-size:20px\">';\n echo \"Updated Date </p>\";\n }\n else{\n $e = oci_error($query);\n echo $e['message'];\n }\n\n oci_free_statement($sql);\n OCILogoff($conn);\n}\n?>\n" }, { "alpha_fraction": 0.5396896600723267, "alphanum_fraction": 0.5466606616973877, "avg_line_length": 21.68877601623535, "blob_id": "f6694005fc935e64f0dd88a61524bfced90627e8", "content_id": "48b215b1028ded673d33276f7278e0cedda1de27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4448, "license_type": "no_license", "max_line_length": 102, "num_lines": 196, "path": "/C Data Structures/quicksort.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// table.c\n//\n// Created by Mandeep Singh on 03/14/19.\n// Copyright © 2019 Mandeep Singh. All rights .\n//\n//Implementing quicksort algorithm for use in array\n# include <stdio.h>\n# include <stdlib.h>\n# include <string.h>\n# include <assert.h>\n# include <stdbool.h>\n# include \"set.h\"\n# define EMPTY 0\n# define FILLED 1\n# define DELETED 2\n\nvoid swap(void *first, void *second);\nvoid quicksort(SET *sp, void** ret[], int first, int last);\nint partition(SET *sp, void** ret[], int first, int last);\n\nstruct set {\n int count; // number of elements in array\n int length; // length of allocated array\n void **data; // array of allocated elements\n char *flags; // state of each slot in array\n int (*compare)();\t\t// comparison function\n unsigned (*hash)();\t\t// hash function\n};\n\n\nstatic int search(SET *sp, void *elt, bool *found)\n{\n int available, i, locn, start;\n\n\n available = -1;\n start = (*sp->hash)(elt) % sp->length;\n\n for (i = 0; i < sp->length; i ++) {\n locn = (start + i) % sp->length;\n\n if (sp->flags[locn] == EMPTY) {\n *found = false;\n return available != -1 ? available : locn;\n\n } else if (sp->flags[locn] == DELETED) {\n if (available == -1)\n\t\tavailable = locn;\n\n } else if ((*sp->compare)(sp->data[locn], elt) == 0) {\n *found = true;\n return locn;\n }\n }\n\n *found = false;\n return available;\n}\n\n//O(n)\nSET *createSet(int maxElts, int (*compare)(), unsigned (*hash)())\n{\n int i;\n SET *sp;\n\n\n assert(compare != NULL && hash != NULL);\n\n sp = malloc(sizeof(SET));\n assert(sp != NULL);\n\n sp->data = malloc(sizeof(char *) * maxElts);\n assert(sp->data != NULL);\n\n sp->flags = malloc(sizeof(char) * maxElts);\n assert(sp->flags != NULL);\n\n sp->compare = compare;\n sp->hash = hash;\n sp->length = maxElts;\n sp->count = 0;\n\n for (i = 0; i < maxElts; i ++)\n sp->flags[i] = EMPTY;\n\n return sp;\n}\n\n//O(1)\nvoid destroySet(SET *sp)\n{\n assert(sp != NULL);\n\n free(sp->flags);\n free(sp->data);\n free(sp);\n}\n\n//O(1)\nint numElements(SET *sp)\n{\n assert(sp != NULL);\n return sp->count;\n}\n\n//O(n)\nvoid addElement(SET *sp, void *elt)\n{\n int locn;\n bool found;\n\n\n assert(sp != NULL && elt != NULL);\n locn = search(sp, elt, &found);\n\n if (!found) {\n\tassert(sp->count < sp->length);\n\n\tsp->data[locn] = elt;\n\tsp->flags[locn] = FILLED;\n\tsp->count ++;\n }\n}\n\n//O(n)\nvoid removeElement(SET *sp, void *elt)\n{\n int locn;\n bool found;\n\n\n assert(sp != NULL && elt != NULL);\n locn = search(sp, elt, &found);\n\n if (found) {\n\tsp->flags[locn] = DELETED;\n\tsp->count --;\n }\n}\n\n//O(n)\nvoid *findElement(SET *sp, void *elt)\n{\n int locn;\n bool found;\n assert(sp != NULL && elt != NULL);\n locn = search(sp, elt, &found);\n return found ? sp->data[locn] : NULL;\n}\n\n//O(nlogn)\nvoid quicksort(SET *sp, void** ret[], int first, int last){\n int pivot = partition(sp, ret, first, last); //Set pivot\n if(first < last){\n pivot = partition(sp, ret, first, last); //Set new pivot\n quicksort(sp, ret, first, pivot - 1); //quicksort for subarray\n quicksort(sp, ret, pivot + 1, last); //quicksort for subarray\n }\n}\n\n//O(logn)\nint partition(SET *sp, void** ret[], int first, int last){\n void* pivot = ret[last]; //Set pivot\n int low = first; //Set pointer to next lowest elt\n for(int i = first; i < last; i++){\n if((*sp->compare)(ret[i], pivot) < 0){ //If pivot is > ret[i]\n swap(&ret[i], &ret[low]); //Then swap\n low++; //Increment low\n }\n }\n swap(&ret[last], &ret[low]); //Swap last and low\n return low;\n}\n\n//O(1)\nvoid swap(void *first, void *second){\n void* temp = second; //Swap first and second\n second = first;\n first = temp;\n}\n\n//O(n)\nvoid *getElements(SET *sp){\n void*** ret = malloc(sizeof(void*)* sp -> count);//Allocate memory the size of count for array ret\n assert(ret != NULL);\n int i = 0, j = 0;\n for(i = 0; i < sp -> length; i++){\n if(sp -> flags[i] == FILLED){\n ret[j] = sp -> data[i];//If the flag[i] is FILLED, go to data[i] and copy to ret[j]\n j++;//This way every index of ret is only the FILLED data vals and no empty slots\n }\n }\n quicksort(sp, ret, 0, sp -> count - 1); //Call quicksort\n return ret; //Return ordered array\n}\n" }, { "alpha_fraction": 0.4938775599002838, "alphanum_fraction": 0.563265323638916, "avg_line_length": 16.5, "blob_id": "618605ca46e2411e1079877a4e5689ff08482e5c", "content_id": "60d8314cca7147dec600e899d9c8fdb7b05384b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 245, "license_type": "no_license", "max_line_length": 38, "num_lines": 14, "path": "/Artificial Intelligence/Lab_1/test.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "def intersect(seq1, seq2):\n res = []\n for x in seq1:\n if x in seq2:\n res.append(x)\n return res\n\ns1 = \"SPAM\"\ns2 = \"SCAM\"\nresult1 = intersect(s1, s2)\nprint(result1)\n\nresult2 = intersect([1, 2, 3], (1, 4))\nprint(result2)\n" }, { "alpha_fraction": 0.6256793737411499, "alphanum_fraction": 0.6304348111152649, "avg_line_length": 29.6875, "blob_id": "9daed2fe3ec611d28954afc27635e565e1984b96", "content_id": "ade245122baae38551a41824ed48b67b5b999c9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1472, "license_type": "no_license", "max_line_length": 155, "num_lines": 48, "path": "/COEN_178_Final_Project_mSingh/Functions/addItemOrder.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh*/\n/*COEN 178 Final Project*/\n/*addItemOrder Function*/\nCREATE OR REPLACE procedure addItemOrder(l_item in varchar, l_cust in varchar, l_order in varchar, l_no in int, l_orderdate in date, l_shippeddate in date)\nIS\n /*Defining*/\n\tl_bookno int;\n l_fee itemorder.shippingfee%type;\n\tl_type customers.custtype%type;\n comic int;\nbegin\n /*Find out customer type*/\n\tselect custtype into l_type \n from customers \n where custid = l_cust;\n /*Load number ordered into variable*/\n select noofcopies \n into l_bookno \n from comicbook \n where itemid = l_item;\n /*Set shipping fee based on customer type*/\n if l_type = 'regular' then\n\t\tl_fee := 10;\n\telse\n\t\tl_fee := 0;\n\tend if;\n /*Find out how many copies of each comicbook there are*/\n\tselect count(*) into comic from comicbook group by itemid having itemid = l_item;\n\tif comic = 1 \n then\n /*If the number ordered is less than number available*/\n if l_no <= l_bookno \n then\n /*Update value of comicbook*/\n update comicbook\n set noofcopies = noofcopies - l_no \n where itemid = l_item;\n /*There are not enough comicbooks for order*/\n else\n dbms_output.put_line('Not enough comic books');\n return;\n end if;\n\tend if;\n /*After all is run, insert into values*/\n insert into itemorder values (l_order, l_item, l_cust, l_orderdate, l_no, null, l_fee);\nend;\n/\nshow error;" }, { "alpha_fraction": 0.5904058814048767, "alphanum_fraction": 0.6060885787010193, "avg_line_length": 26.794872283935547, "blob_id": "d943088bc5cebede4ee1c3232f39baba72571bb1", "content_id": "33cb088442c3f6835b45b7e86a5463cbe5c01605", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1085, "license_type": "no_license", "max_line_length": 96, "num_lines": 39, "path": "/C++ Data Structures/Homework_1/HW_4/bag.hpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// bag.hpp\n// HW_4\n//\n// Created by Mandeep Singh on 4/10/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#ifndef bag_hpp\n#define bag_hpp\n\n#include <stdio.h>\n#include<cstdlib>\n\nnamespace std {\n class bag {\n public:\n // TYPEDEFS and MEMBER CONSTANTS\n typedef int value_type;\n typedef std::size_t size_type;\n static const size_type CAPACITY = 30; // CONSTRUCTOR\n bag() { used = 0; }\n // MODIFICATION MEMBER FUNCTIONS\n size_type erase(const value_type& target);\n bool erase_one(const value_type& target);\n void insert(const value_type& entry);\n // CONSTANT MEMBER FUNCTIONS\n size_type size() const { return used; } size_type count(const value_type& target) const;\n friend bag operator -(const bag& b1, const bag& b2);\n friend bag operator -=(bag& b1, const bag& b2);\n private:\n value_type data[CAPACITY]; // The array to store items\n size_type used; // How much of array is used\n };\n // NONMEMBER FUNCTIONS for the bag class\n \n \n}\n#endif /* bag_hpp */\n" }, { "alpha_fraction": 0.5247018933296204, "alphanum_fraction": 0.5247018933296204, "avg_line_length": 29.894737243652344, "blob_id": "7f930795535abaa42592b6cd026fcd1e72016ffc", "content_id": "8b729363406d0ecb25ae812d5a0d1d9f6b26e236", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 587, "license_type": "no_license", "max_line_length": 109, "num_lines": 19, "path": "/Java/2.15 Arithmetic/src/Arithmetic.java", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "import java.util.Scanner;\npublic class Arithmetic {\n public static void main(String[] args) {\n Scanner input = new Scanner(System.in);\n \n System.out.printf(\"Please enter an integer: \");\n int x = input.nextInt();\n System.out.printf(\"Please enter another integer: \");\n int y = input.nextInt();\n \n int a = x + y;\n int b = x - y;\n int c = x * y;\n int d = x / y;\n \n System.out.printf(\"The sum is %d, the difference is %d, the product is %d, and the quotient is %d.\\n\"\n ,a, b, c, d);\n }\n}\n" }, { "alpha_fraction": 0.5690115690231323, "alphanum_fraction": 0.5814781785011292, "avg_line_length": 26.390243530273438, "blob_id": "04b0451a2b61190994f1fb1131d51d06f5b532a8", "content_id": "99dcf54ec89e4a1d81d46fd59b66678a361de274", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1124, "license_type": "no_license", "max_line_length": 75, "num_lines": 41, "path": "/C++ Data Structures/Homework_2/HW_4/mystring.hpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// mystring.hpp\n// HW_4\n//\n// Created by Mandeep Singh on 4/18/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#ifndef mystring_hpp\n#define mystring_hpp\n\n#include <stdio.h>\n#include <iostream>\nnamespace std{\n class str{\n public:\n str(const char str[ ] = \" \");\n \n //CONSTANT MEMBER FUNCTIONS\n size_t length() const;\n char operator [ ](size_t position) const;\n \n //MODIFICATION MEMBER FUNCTIONS\n void operator +=(const str& addend);\n void operator +=(const char addend[ ]);\n void operator +=(char addend);\n void reserve(size_t n);\n \n //NONMEMBER FUNCTIONS\n friend string operator +(const str& s1, const str& s2);\n friend istream& operator >>(istream& ins, str& target);\n friend ostream& operator <<(ostream& outs, const str& source);\n istream& getline(istream& ins, str& target, char delimiter = '\\n');\n friend bool operator ==(const str& s1, const str& s2);\n private:\n int current_length;\n int allocated;\n char *characters;\n };\n}\n#endif /* mystring_hpp */\n" }, { "alpha_fraction": 0.5331991910934448, "alphanum_fraction": 0.5503017902374268, "avg_line_length": 29.121212005615234, "blob_id": "563913b7ce6b61304b9e2cec4e049533b10c7e1d", "content_id": "428269accbf9c5ecd38db4907a9b7c127a166f75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 994, "license_type": "no_license", "max_line_length": 83, "num_lines": 33, "path": "/Operating Systems/Lab_2/part5.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "# Name: Mandeep Singh\n# Date: 01/16/20\n# Title: Lab2 - System Calls\n# Description: This program creates exactly 7 processes\n#include <stdio.h>\n#include <sys/types.h> /* pid_t */\n#include <unistd.h> /* fork */\n#include <stdlib.h> /* atoi */\n#include <errno.h> /* errno */\n\nint main(int argc, char *argv[]){\n pid_t pid;\n int i, n = atoi(argv[1]);\n printf(\"Before forking. \\n\");\n#Loops three times and creates a process which then forks to create child processes\n for(i = 0; i < 3; i++){\n if(fork() == 0){\n printf(\"Child ID: %d \\tParent ID: %d\\n\", getpid(), getppid());\n exit(0);\n#We want one child to have no further children\n }if(fork() == 0){\n printf(\"Child ID: %d \\tParent ID: %d\\n\", getpid(), getppid());\n#We want this child to have further children\n }else{\n#We need to exit once loop finishes\n int status;\n waitpid(-1, &status, 0);\n break;\n \n }\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5448718070983887, "avg_line_length": 23, "blob_id": "4ec93872e75aa52a4b89a2ffb1155141dbe9616d", "content_id": "c98610c1c6a3fd051c6c9f2e4895ccddbd1ce154", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 312, "license_type": "no_license", "max_line_length": 42, "num_lines": 13, "path": "/Artificial Intelligence/Lab_1/minmax2.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "def minmax(test, array):\n res = array[0]\n for arg in array[1:]:\n if test(arg,res):\n res = arg\n return res\n\ndef lessthan(x,y): return x<y\ndef grtrthan(x,y): return x>y\n\nif __name__ == '__main__':\n print(minmax(lessthan, [4,2,1,5,6,3]))\n print(minmax(grtrthan, [4,2,1,5,6,3]))\n" }, { "alpha_fraction": 0.6331592798233032, "alphanum_fraction": 0.6370757222175598, "avg_line_length": 22.55384635925293, "blob_id": "018766cee3519e318194bc56864a91ca347b4092", "content_id": "5148e6726d66d3fe6890287f9f696c0dea367c33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1532, "license_type": "no_license", "max_line_length": 78, "num_lines": 65, "path": "/SQL Databases/lab8/addMovieReview.php", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "\n<?php\n\nif ($_SERVER[\"REQUEST_METHOD\"] == \"POST\") {\n\n // collect input data from the form\n\n\t// Get the movie name\n $movieName = $_POST['mname'];\n\n\t// Get the comment\n $comment = $_POST['comment'];\n\n if (!empty($movieName)){\n\t\t$movieName = prepareInput($movieName);\n }\n if (!empty($comment)){\n\t\t$comment = prepareInput($comment);\n }\n\t \n\t// Call the function to insert moviename and comments\n\t// into MovieReviews table\n\n\tinsertMovieReviewIntoDB($movieName,$comment);\n\t\n}\n\nfunction prepareInput($inputData){\n\t$inputData = trim($inputData);\n \t$inputData = htmlspecialchars($inputData);\n \treturn $inputData;\n}\n\nfunction insertMovieReviewIntoDB($movieName,$comment){\n\t//connect to your database. Type in sd username, password and the DB path\n\t$conn = oci_connect('msingh', 'Divgeet12', '//dbserver.engr.scu.edu/db11g');\n\t\n\tif (!$conn) {\n\t\t$e = oci_error();\n\t\ttrigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);\n\t} \n\tif(!$conn) {\n\t print \"<br> connection failed:\";\n exit;\n\t}\n\t// Calling the PLSQL procedure, addMovieReview\n\t$sql = oci_parse($conn, 'begin addMovieReview(:moviename, :comment); end;');\t\n\n\toci_bind_by_name($sql, ':moviename', $movieName);\n\toci_bind_by_name($sql, ':comment', $comment);\n\n\t// Execute the query\n\t$res = oci_execute($sql);\n\t\n\tif ($res){\n\t\techo '<br><br> <p style=\"color:green;font-size:20px\">';\n\t\techo \"Movie Review Inserted </p>\";\n\t}\n\telse{\n\t\t$e = oci_error($query);\n \techo $e['message'];\n\t}\n\toci_free_statement($sql);\n\tOCILogoff($conn);\n}\n?>\n" }, { "alpha_fraction": 0.6469072103500366, "alphanum_fraction": 0.6623711585998535, "avg_line_length": 21.823530197143555, "blob_id": "eca0e3294393ef5032ddc37c1e3963966d14bc31", "content_id": "076471e2b5d718d5beb9bc2e73b70cb1363d2c12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 388, "license_type": "no_license", "max_line_length": 70, "num_lines": 17, "path": "/Java/testCourseSelector/src/testcourseselector/TestCourseSelector.java", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "package testcourseselector;\n\nimport javax.swing.JFrame;\n\npublic class TestCourseSelector {\n\n public static void main(String[] args) {\n \n GUISelection courseSelector = new GUISelection();\n courseSelector.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n courseSelector.setSize(600,500);\n courseSelector.setVisible(true);\n \n \n }\n \n}\n" }, { "alpha_fraction": 0.6117478609085083, "alphanum_fraction": 0.626074492931366, "avg_line_length": 32.28571319580078, "blob_id": "638f774af8bfa348d571515f6e921cd42d47adfe", "content_id": "ec9b65419b9dbbe269f693aaa6a0c4001e76f56f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 698, "license_type": "no_license", "max_line_length": 106, "num_lines": 21, "path": "/SQL Databases/lab7/psql2.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "CREATE OR REPLACE TRIGGER LimitTest\n BEFORE INSERT OR UPDATE ON Course_Prereq \n FOR EACH ROW -- A row level trigger\nDECLARE \n v_MAX_PREREQS CONSTANT INTEGER := 2; \n v_CurNum INTEGER;\nBEGIN\n BEGIN\n SELECT COUNT(*) INTO v_CurNum FROM Course_Prereq WHERE courseNo = :new.CourseNo Group by courseNo;\n EXCEPTION -- Before you enter the first row, no data is found\n WHEN no_data_found THEN DBMS_OUTPUT.put_line('not found');\n v_CurNum := 0;\n END;\n if v_curNum > 0 THEN\n IF v_CurNum + 1 > v_MAX_PREREQS THEN\n RAISE_APPLICATION_ERROR(-20000,'Only 2 prereqs for course');\n END IF;\n END IF;\nEND;\n/\nSHOW ERRORS;" }, { "alpha_fraction": 0.6728420853614807, "alphanum_fraction": 0.7052631378173828, "avg_line_length": 25.977272033691406, "blob_id": "ab27f7a793ee46d5a9d14be3082cbfc9c5f5419b", "content_id": "61bf333bacd94a776be13ab8c40896ff0af20453", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2375, "license_type": "no_license", "max_line_length": 91, "num_lines": 88, "path": "/Computer Networks/Lab_5/SMTPClient-local.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "\n# Behnam Dezfouli\n# CSEN, Santa Clara University\n\n# This program implements a simple smtp mail client to send an email to a local smtp server\n\n# Note:\n# Run a local smtp mail server using the following command before running this code:\n# python -m smtpd -c DebuggingServer -n localhost:6000\n\n\nfrom socket import *\nimport ssl\n\n\n# Choose a mail server\nmailserver = 'localhost'\n\n\n# Create socket called clientSocket and establish a TCP connection with mailserver\n# STUDENT WORK\nclientSocket = socket(AF_INET, SOCK_STREAM)\nclientSocket.connect(('localhost', 6000))\n\n# Port number may change according to the mail server\n# STUDENT WORK\n#clientPort = 9001\n#clientSocket.bind((\"\", clientPort))\n\nrecv = clientSocket.recv(1024).decode()\nprint('..........0',recv)\nif recv[:3] != '220':\n print('220 reply not received from server.')\n\n\n# Send HELO command along with the server address\n# STUDENT WORK\nclientSocket.send('HELO <localhost>\\r\\n'.encode())\nrecv = clientSocket.recv(1024).decode()\nprint('........1',recv)\n#if recv[:3] != '250':\n# print('250 reply not received from server.')\n\n# Send MAIL FROM command and print server response\n# STUDENT WORK\nclientSocket.send('MAIL FROM:<reverse_path>\\r\\n'.encode())\nrecv = clientSocket.recv(1024).decode()\nprint('........1',recv)\n\n# Send RCPT TO command and print server response\n# STUDENT WORK\nclientSocket.send('RCPT TO:<forward_path>\\r\\n'.encode())\nrecv = clientSocket.recv(1024).decode()\nprint('........1',recv)\n\n# Send DATA command and print server response\n# STUDENT WORK\nclientSocket.send('DATA\\r\\n'.encode())\nrecv = clientSocket.recv(1024).decode()\nprint('........1',recv)\n\n# Send message data.\n# STUDENT WORK\nclientSocket.send('SUBJECT: Greetings to you!'.encode())\n#recv = clientSocket.recv(1024).decode()\n#print('........1',recv)\n\n# Message to send\n# STUDENT WORK\nclientSocket.send('\\nThis is line 1.'.encode())\n#recv = clientSocket.recv(1024).decode()\n#print('........1',recv)\n\n# Message ends with a single period\n# STUDENT WORK\nclientSocket.send('\\nThis is line 2.\\r\\n.\\r\\n'.encode())\nrecv = clientSocket.recv(1024).decode()\nprint('........1',recv)\n\n#clientSocket.send('\\r\\n.\\r\\n'.encode())\n#recv = clientSocket.recv(1024).decode()\n#print('........1',recv)\n\n# Send QUIT command and get server response\n# STUDENT WORK\nclientSocket.send('QUIT\\r\\n'.encode())\nrecv = clientSocket.recv(1024).decode()\nprint(recv)\nclientSocket.close()\n" }, { "alpha_fraction": 0.5653846263885498, "alphanum_fraction": 0.6038461327552795, "avg_line_length": 18.259260177612305, "blob_id": "3addde76ab5c2076c5d1ee9620018a192a1b64fa", "content_id": "ea21d21cd415a636c248828e65843c1261f82faf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 523, "license_type": "no_license", "max_line_length": 60, "num_lines": 27, "path": "/C++ Data Structures/Homework_1/HW_5/main.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// HW_5\n//\n// Created by Mandeep Singh on 4/10/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include <iostream>\n#include <cctype>\n#include <iostream>\n#include <cstdlib>\n#include \"sequence.hpp\"\n\nusing namespace std;\n\nint main(int argc, const char * argv[]) {\n sequence test; // A sequence that we’ll perform tests on\n \n test.insert(30);\n test.insert(90);\n test.insert(20);\n test.insert(10);\n test.insert(40);\n cout << test.size() << \"\\n\" << test.current() << endl;\n \n}\n" }, { "alpha_fraction": 0.44691869616508484, "alphanum_fraction": 0.4660797417163849, "avg_line_length": 25.094594955444336, "blob_id": "22fd52fb385e791b5a3acbc8f84687e1e779a783", "content_id": "2307b9df7552110a9cf172335200ec0772866abf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1932, "license_type": "no_license", "max_line_length": 111, "num_lines": 74, "path": "/C++ Data Structures/Homework_1/HW_4/bag.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// bag.cpp\n// HW_4\n//\n// Created by Mandeep Singh on 4/10/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include \"bag.hpp\"\n#include <algorithm> // Provides copy function #include <cassert> // Provides assert function #include \"bag1.h\"\nnamespace std {\n const bag::size_type bag::CAPACITY;\n bag::size_type bag::erase(const value_type& target)\n {\n size_type index = 0;\n size_type many_removed = 0;\n while (index < used) {\n if (data[index] == target) {\n --used;\n data[index] = data[used];\n ++many_removed;\n }\n else\n ++index;\n }\n return many_removed;\n }\n bool bag::erase_one(const value_type& target) {\n size_type index;\n index = 0;\n while ((index < used) && (data[index] != target))\n ++index;\n if (index == used)\n return false;\n --used;\n data[index] = data[used]; return true;\n }\n void bag::insert(const value_type& entry){\n assert(size( ) < CAPACITY);\n data[used] = entry;\n ++used;\n }\n bag::size_type bag::count(const value_type& target) const{\n size_type answer;\n size_type i;\n answer = 0;\n for (i = 0; i < used; ++i)\n if (target == data[i]) ++answer;\n return answer;\n }\n \n bag operator -(const bag& b1, const bag& b2){\n bag b3;\n assert(b1.size() + b2.size() <= bag::CAPACITY);\n for(int i = 0; i < b1.size(); i++){ b3.insert(b1.data[i]); }\n for(int j = 0; j < b2.size(); j++){\n int k = b2.data[j];\n b3.erase_one(k);\n }\n return b3;\n }\n \n bag operator -=(bag& b1, const bag& b2)\n {\n int j;\n \n for(int i = 0; i < b2.size(); i++)\n {\n j = b2.data[i];\n b1.erase_one(j);\n }\n return b1;\n }\n}\n" }, { "alpha_fraction": 0.6710526347160339, "alphanum_fraction": 0.6783625483512878, "avg_line_length": 33.25, "blob_id": "abe402abb110c62598cae0d34014aa527747479c", "content_id": "c71117335423b581f344c86d0cfb4841ccbc1cd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 684, "license_type": "no_license", "max_line_length": 142, "num_lines": 20, "path": "/SQL Databases/lab6/psql4.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "Create Or Replace Trigger Acct_Cust_Trig\nAFTER INSERT OR UPDATE ON Accounts_6\nFOR EACH ROW\nBEGIN\n If inserting then\n update totals_6\n set totalAmount = totalAmount + :new.amount\n where custno = :new.custno;\n\n insert into totals_6 (select :new.custno, :new.amount from dual where not exists (select * from TOTALS_6 where custno = :new.custno));\n END IF;\n if updating then\n/* If we are updating we want to correctly set the totalAmount to the new amount that may be >= or < old amountComplete the query */\n update totals_6\n set totalAmount = totalAmount + :new.amount\n where custno = :new.custno;\n END IF;\nEND;\n/\nshow errors;" }, { "alpha_fraction": 0.46051380038261414, "alphanum_fraction": 0.5033301711082458, "avg_line_length": 23.465116500854492, "blob_id": "f0021d0ac3bdcc1a36ee6c6e8abefc99b3c3168c", "content_id": "dc63a3ef198547ff2287b9628710eb8f78b436e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1051, "license_type": "no_license", "max_line_length": 123, "num_lines": 43, "path": "/Java/Midterm Problem 3/src/MidtermProblem3.java", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "public class MidtermProblem3 {\n public static void main(String[] args) {\n \n int counter1 = 0;\n int sum = 0;\n int[] array1 = new int[9];\n for(int i = 0; i < array1.length; i++) {\n array1[i] = (int)(Math.random() * 16 + 1);\n }\n System.out.printf(\"Generated numbers are:[ \");\n \n while(counter1 < 9)\n {\n System.out.print(array1[counter1]);\n System.out.print(\" \");\n counter1++;\n }\n System.out.print(\"]\");\n \n for(int j: array1)\n {\n sum += j;\n }\n \n double average = sum/9;\n System.out.printf(\"\\nTotal:%d Average:%.2f\", sum, average);\n \n int k = 0;\n int counter2 = 0;\n while(k < 9)\n {\n if(array1[k] > average)\n {\n counter2++;\n }\n k++;\n }\n System.out.printf(\"\\nNumbers above the average: %d\", counter2);\n \n int altSum = array1[0] - array1[1] + array1[2] - array1[3] + array1[4] - array1[5] + array1[6] - array1[7] + array1[8];\n System.out.printf(\"\\nAlternating Sum:%d\\n\", altSum);\n }\n}" }, { "alpha_fraction": 0.5428571701049805, "alphanum_fraction": 0.6095238327980042, "avg_line_length": 14, "blob_id": "9ef2b54b8396bca34013519815d6a540412df563", "content_id": "e65d3964f60e64def511c9be7538fe8c5619dc76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 211, "license_type": "no_license", "max_line_length": 49, "num_lines": 14, "path": "/C++ Data Structures/Lab_1/part2.hpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// part2.hpp\n// Lab_1\n//\n// Created by Mandeep Singh on 4/4/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#ifndef part2_hpp\n#define part2_hpp\n\n#include <stdio.h>\nvoid part2();\n#endif /* part2_hpp */\n" }, { "alpha_fraction": 0.5288461446762085, "alphanum_fraction": 0.5512820482254028, "avg_line_length": 21.285715103149414, "blob_id": "dbf9f49e270320d3336f3368d91bc3576129539f", "content_id": "a261886e5cfbaf5456ac64921dfe824e82a46eb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 312, "license_type": "no_license", "max_line_length": 45, "num_lines": 14, "path": "/Artificial Intelligence/Lab_1/class3.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "class Person:\n def __init__(self, name, jobs, age=None):\n self.name = name\n self.jobs = jobs\n self.age = age\n\n def info(self):\n return (self.name, self.jobs)\n\nrec1 = Person('Bob', ['dev', 'mgr'], 40.5)\nrec2 = Person('Sure', ['dev', 'cto'])\n\nprint(rec1.jobs)\nprint(rec2.info())\n" }, { "alpha_fraction": 0.44750431180000305, "alphanum_fraction": 0.5232357978820801, "avg_line_length": 17.15625, "blob_id": "95632f30ad8316939d90d12cfb961e7e2643ee2f", "content_id": "1fe4eeda9d7d74ea52b0eadcfd2fd1986a202b43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 582, "license_type": "no_license", "max_line_length": 49, "num_lines": 32, "path": "/C++ Data Structures/Homework_1/HW_4/main.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// HW_4\n//\n// Created by Mandeep Singh on 4/10/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include <iostream>\n#include \"bag.hpp\"\nusing namespace std;\nint main(int argc, const char * argv[]) {\n bag b1;\n bag b2;\n bag b3;\n b1.insert(3);\n b1.insert(8);\n b1.insert(7);\n b1.insert(10);\n b1.insert(11);\n std::cout << b1.size() << endl;\n b2.insert(10);\n b2.insert(12);\n b2.insert(3);\n b1 -= b2;\n std::cout << b1.size() << endl;\n b1.insert(6);\n b3 = b1 - b2;\n std::cout << b3.size() << endl;\n \n return 0;\n}\n" }, { "alpha_fraction": 0.704081654548645, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 48, "blob_id": "e45b27e34d83c8bb919d3e991f1ec13a1d7e54fe", "content_id": "87d243335face1170f32e2a0ce77873d83a819f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 98, "license_type": "no_license", "max_line_length": 69, "num_lines": 2, "path": "/SQL Databases/lab2/lab2_queries2.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "select * from L_EMP,L_DEPT;\nselect DISTINCT empName from L_EMP, L_DEPT where L_EMP.deptid = 'd3';\n" }, { "alpha_fraction": 0.7714285850524902, "alphanum_fraction": 0.7714285850524902, "avg_line_length": 22.33333396911621, "blob_id": "9c2e76a70b31467f15b7151269a804fee1ee6217", "content_id": "5c677f91ae7c3d999912317a9fc5bab428352776", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 70, "license_type": "no_license", "max_line_length": 41, "num_lines": 3, "path": "/Artificial Intelligence/Lab_1/test1_module.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "import module\nresult = module.adder(module.a, module.b)\nprint(result)\n" }, { "alpha_fraction": 0.7338529825210571, "alphanum_fraction": 0.7405345439910889, "avg_line_length": 63.14285659790039, "blob_id": "0fadca38b48a90b2c8d37cf05fa42cc509290c5e", "content_id": "dd36fa13759a1c02d1d4add043c4f06ddef18386", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3597, "license_type": "no_license", "max_line_length": 354, "num_lines": 56, "path": "/C++ Data Structures/Homework_2/HW_4/mystring.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// mystring.cpp\n// HW_4\n//\n// Created by Mandeep Singh on 4/18/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//FILE: mystring.h\n//CLASS PROVIDED: string (a simple version of the Standard Library string class)\n//CONSTRUCTOR for the string class:\n//string(const char str[ ] = \"\") -- default argument is the empty string.\n//Precondition: str is an ordinary null-terminated string. Postcondition: The string contains the sequence of chars from str.\n//CONSTANT MEMBER FUNCTIONS for the string class:\n//size_t length( ) const\n//Postcondition: The return value is the number of characters in the string.\n//char operator [ ](size_t position) const\n//Precondition: position < length( ).\n//Postcondition: The value returned is the character at the specified position of the string. A string’s positions start from 0 at the start of the sequence and go up to length( ) – 1 at the right end.\n//MODIFICATION MEMBER FUNCTIONS for the string class:\n//void operator +=(const string& addend)\n//Postcondition: addend has been catenated to the end of the string.\n//void operator +=(const char addend[ ])\n//Precondition: addend is an ordinary null-terminated string. Postcondition: addend has been catenated to the end of the string.\n//void operator +=(char addend)\n//Postcondition: The single character addend has been catenated to the end of the string.\n//void reserve(size_t n)\n//Postcondition: All functions will now work efficiently (without allocating new memory) until n characters are in the string.\n\n//NONMEMBER FUNCTIONS for the string class:\n//string operator +(const string& s1, const string& s2) Postcondition: The string returned is the catenation of s1 and s2.\n//istream& operator >>(istream& ins, string& target)\n//Postcondition: A string has been read from the istream ins, and the istream ins is then returned by the function. The reading operation skips white space (i.e., blanks, tabs, newlines) at the start of ins. Then the string is read up to the next white space or the end of the file. The white space character that terminates the string has not been read.\n//ostream& operator <<(ostream& outs, const string& source) Postcondition: The sequence of characters in source has been written to outs. The return value is the ostream outs.\n//istream& getline(istream& ins, string& target, char delimiter = '\\n')\n//Postcondition: A string has been read from the istream ins. The reading operation reads all characters (including white space) until the delimiter is read and discarded (but not added to the end of the string). The return value is the istream ins.\n//VALUE SEMANTICS for the string class:\n//Assignments and the copy constructor may be used with string objects.\n//COMPARISONS for the string class:\n//The six comparison operators (==, !=, >=, <=, >, and <) are implemented for the string class, using the usual lexicographic order on strings.\n//DYNAMIC MEMORY usage by the string class:\n//If there is insufficient dynamic memory, the following functions throw bad_alloc: the constructors, reserve, operator +=, operator +, and the assignment operator.\n#include \"mystring.hpp\"\n#include <cstring>\nnamespace std{\n\n str(const char str[]) // Library facilities used: cstring\n {\n current_length = strlen(str);\n allocated = current_length + 1;\n characters = new char[allocated];\n strcpy(characters, str);\n }\n \n bool str::operator ==(const str& s1, const str& s2) // Postcondition: The return value is true if s1 is identical to s2. // Library facilities used: cstring\n {\n return (strcmp(s1.characters, s2.characters) == 0); }\n}\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6311110854148865, "avg_line_length": 25.47058868408203, "blob_id": "30e499737abbd35f779dc5b9db13b8c1c86cc874", "content_id": "920d8d791c3d5ab4d9f7366f8fc71d7eb5cad241", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 451, "license_type": "no_license", "max_line_length": 92, "num_lines": 17, "path": "/C++ Data Structures/Lab_1/part4a.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// part4a.cpp\n// Lab_1\n//\n// Created by Mandeep Singh on 4/4/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n#include<iostream>\n#include \"part4a.hpp\"\n\nvoid part4a(){\n char* str;\n str = \"SC\"; //Trying to convert from string to char*\n *(str+3) ='U'; //We are trying to insert 'U' to index 3 of str which cannot be done\n //If we were to use a char array with allocated space then we could insert into an index\n std::cout<< str;\n}\n" }, { "alpha_fraction": 0.4721919298171997, "alphanum_fraction": 0.4858233332633972, "avg_line_length": 40.25, "blob_id": "5c0f5c6875c66d456425a45c1b6fd4855516cbb2", "content_id": "d96477042fca3071299bc9eff07a66932876f88c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1834, "license_type": "no_license", "max_line_length": 113, "num_lines": 44, "path": "/Java/Mod_37_Encryption/src/Mod_37_Encryption.java", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//@author Mandeep Singh\n\nimport java.util.Scanner;\n\npublic class Mod_37_Encryption {\n public static void main(String[] args) {\n System.out.printf(\"Welcome to the mod 37 encryption program. \\nDue to some technical issues,\"\n + \" we ask that you enter each character of your secret code at a time.\\n\"\n + \"We are sorry for the inconvenience and will fix this issue shortly.\\n\"\n + \"Sincerely,\\nGoogle Devs\\n\\n\");\n \n Scanner in = new Scanner(System.in);\n \n String plainText = \"\";//Variable that determines whether to continue or break loop\n String encryptedCode = \"\";\n \n while(!\"-1\".equals(plainText)){\n \n System.out.printf(\"Please enter your character to be encrypted(-1 to exit):\");\n plainText = in.nextLine();\n int i = 0, j = 0, key;\n \n //A character array of all possible inputs\n char[] characters = {'@', 'A', 'B', 'C', 'D', 'E', 'F','G','H','I','J','K','L',\n 'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9'};\n\n plainText = plainText.toUpperCase();//We make everything uppercase\n char[] plainTextChar = plainText.toCharArray();//Put the input into a character array\n \n while(i != plainText.length()) {\n while(j < 37){ \n if(plainTextChar[i] == characters[j]){\n key = (((13*j)+5)%37);\n encryptedCode = encryptedCode.concat(Character.toString(characters[key]));\n }\n j++;\n }\n i++;\n }\n }\n System.out.printf(encryptedCode);\n System.out.printf(\"\\n\");\n }\n} " }, { "alpha_fraction": 0.5309352278709412, "alphanum_fraction": 0.5539568066596985, "avg_line_length": 22.16666603088379, "blob_id": "02a54e4bfffddc82150a70bf540bd82bcd56a194", "content_id": "8fc9ac1f3dba0f86b77dc9313ae91760b0611286", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 696, "license_type": "no_license", "max_line_length": 77, "num_lines": 30, "path": "/C++ Data Structures/Homework_1/HW_1/3d_point.hpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// 3d_point.hpp\n// HW_1\n//\n// Created by Mandeep Singh on 4/7/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#ifndef _d_point_hpp\n#define _d_point_hpp\n\n#include <stdio.h>\nnamespace std{\n class point{\n public:\n point(double init_x = 0.0, double init_y = 0.0, double init_z = 0.0);\n void shift(double x_amt, double y_amt, double z_amt);\n void rotate_x(double degrees);\n void rotate_y(double degrees);\n void rotate_z(double degrees);\n double get_x() { return x; }\n double get_y() { return y; }\n double get_z() { return z; }\n private:\n double x;\n double y;\n double z;\n };\n}\n#endif /* _d_point_hpp */\n" }, { "alpha_fraction": 0.6720351576805115, "alphanum_fraction": 0.7496339678764343, "avg_line_length": 51.61538314819336, "blob_id": "149425655a987790a8425907e35da306b3fbf997", "content_id": "918ff0cdb1b2efe2f5dd2b749fa9252e2f50dac3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 683, "license_type": "no_license", "max_line_length": 67, "num_lines": 13, "path": "/SQL Databases/lab7/sql3.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "CREATE TABLE MyExpenses(category varchar(15), price NUMBER(10, 2));\ninsert into MyExpenses values ('Groceries', 60.23);\ninsert into MyExpenses values ('Groceries', 34.83);\ninsert into MyExpenses values ('Groceries', 94.32);\ninsert into MyExpenses values ('Groceries', 29.12);\ninsert into MyExpenses values ('Entertainment', 15.23);\ninsert into MyExpenses values ('Entertainment', 23.34);\ninsert into MyExpenses values ('Entertainment', 44.44);\ninsert into MyExpenses values ('Entertainment', 10.15);\ninsert into MyExpenses values ('Gas', 30.23);\ninsert into MyExpenses values ('Gas', 27.34);\ninsert into MyExpenses values ('Gas', 35.44);\ninsert into MyExpenses values ('Gas', 40.15);" }, { "alpha_fraction": 0.6908602118492126, "alphanum_fraction": 0.7069892287254333, "avg_line_length": 27.653846740722656, "blob_id": "e7e044e7b5ac7670b7e6627742bf070ccbb5c164", "content_id": "1e66515565cfd1c7d112cbc31d9303dab0d50e5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 744, "license_type": "no_license", "max_line_length": 100, "num_lines": 26, "path": "/SQL Databases/lab5/part1/psql2.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "Create or Replace Function calcSalaryRaise( p_name in AlphaCoEmp.name%type, percentRaise IN NUMBER) \nRETURN NUMBER \nIS \nl_salary AlphaCoEmp.salary%type; \nl_raise AlphaCoEmp.salary%type; \nl_cnt Integer; \nBEGIN \n-- Find the current salary of p_name from AlphaCoEMP table. \nSelect salary into l_salary from AlphaCoEmp \nwhere UPPER(name) = UPPER(p_name); \n-- Calculate the raise amount \nl_raise := l_salary * (percentRaise/100); \n-- Check if the p_name is in Emp_Work table. \n-- If so, add a $1000 bonus to the \n-- raise amount \nSelect count(*) into l_cnt from Emp_Work \nwhere UPPER(name) = UPPER(p_name); \nif l_cnt >= 1 THEN \nl_raise := l_raise + 1000; \nEnd IF; \n /* return a value from the function */\nreturn l_raise;\n \nEND; \n/ \nShow Errors;" }, { "alpha_fraction": 0.8359133005142212, "alphanum_fraction": 0.8374612927436829, "avg_line_length": 322.5, "blob_id": "7cc23a7e95e949ed744a076787a335f8bc432440", "content_id": "899d08f1d02cd0b77e2edfedb26936903b1ed55a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 646, "license_type": "no_license", "max_line_length": 631, "num_lines": 2, "path": "/C Data Structures/Term_Project/application_3/README.txt", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "Application 3:\rAssume a new college that is expanding frequently and dramatically on its student amount. This leads to two consequences. First, accurately estimating the total number of students is extremely difficult. Second, frequent insertions and deletions are performed. In addition, the college frequently requires calculating the largest age gap among its students. Assume that search operations are not performed frequently. Your implementation has to support searches on either student ID or age. The major interfaces provided by your code should include createDataSet, destroyDataSet, searchAge, searchID, insertion, deletion, maxAgeGap" }, { "alpha_fraction": 0.7056798338890076, "alphanum_fraction": 0.7194492220878601, "avg_line_length": 23.25, "blob_id": "9cd723a4217ab856d9b0c940a3ff5ef246ce6f1b", "content_id": "b3f0118c8a70fa9010c83e121edc231a8110f57c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 581, "license_type": "no_license", "max_line_length": 98, "num_lines": 24, "path": "/SQL Databases/lab7/psql3.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "CREATE OR REPLACE TRIGGER LimitTest\nFOR INSERT OR UPDATE \nON Course_Prereq\nCOMPOUND TRIGGER \n/* Declaration Section*/\nv_MAX_PREREQS CONSTANT INTEGER := 2; \nv_CurNum INTEGER := 1; \nv_cno INTEGER; \n--ROW level\nBEFORE EACH ROW IS\nBEGIN\n v_cno := :NEW.COURSENO;\nEND \nBEFORE EACH ROW; \n--Statement level\nAFTER STATEMENT IS\nBEGIN\n SELECT COUNT(*) INTO v_CurNum FROM Course_Prereq WHERE courseNo = v_cno Group by courseNo;\n IF v_CurNum > v_MAX_PREREQS THEN RAISE_APPLICATION_ERROR(-20000,'Only 2 prereqs for course');\n END IF;\nEND AFTER STATEMENT;\n END ;\n /\n Show Errors;" }, { "alpha_fraction": 0.5826547145843506, "alphanum_fraction": 0.5883550643920898, "avg_line_length": 32.87586212158203, "blob_id": "fd2f119519e6a50e442e6ef7002e0335a4aee7a1", "content_id": "a9cc99837589a946eec06392431cc682cad9fdc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4913, "license_type": "no_license", "max_line_length": 132, "num_lines": 145, "path": "/C Data Structures/generic-table.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// generic-table.c\n//\n// Created by Mandeep Singh on 02/08/19.\n// Copyright © 2019 Mandeep Singh. All rights .\n//\n#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"set.h\" //Import libraries for usage\n#define EMPTY 0\n#define FILLED 1\n#define DELETED 2\n\nstatic int search(SET *sp, void *elt, bool *found);//Initialize our private search function\n\ntypedef struct set{ //Define our struct set\n void **data;//Pointer to an array of character strings\n int length; //Length of array\n int count; //Number of elements in array\n char *flag;//Pointer to array of characters for flag array\n int (*compare)(); //Pointer to compare function passed through\n unsigned (*hash)(); //Pointer to hash function passed through\n}SET;\n\n//O(n)\nSET *createSet(int maxElts, int(*compare)(), unsigned(*hash)()){ //Creates out set using variables initialized in struct set\n SET *sp;\n sp = malloc(sizeof(SET));\n assert(sp != NULL);\n sp -> count = 0;\n sp -> length = maxElts;\n sp -> data = malloc(sizeof(void*)*maxElts);\n assert(sp -> data != NULL);\n sp -> flag = malloc(sizeof(void*)*maxElts);\n assert(sp -> flag != NULL);\n for(int z = 0; z < sp->length; z++)//Set all vals in flag array to EMPTY\n sp -> flag[z] = EMPTY;\n sp -> compare = compare;\n sp -> hash = hash;\n return sp;\n}\n\n//O(1)\nvoid destroySet(SET *sp){\n assert(sp != NULL);//Checking to see if array elts are NULL\n free(sp -> data);//Freeing up memory in hash table\n free(sp->flag);\n}\n\n//O(1)\nint numElements(SET *sp){\n assert(sp != NULL);\n return sp -> count;//Return the number of elements in array\n}\n\n//O(n) for worst case\nvoid addElement(SET *sp, void *elt){\n assert(sp != NULL && elt != NULL);\n bool found = false;//Found is false\n int index = search(sp, elt, &found);//Run search function\n if(found){\n // printf(\"This element already exists\");\n }else{\n sp -> data[index] = elt; //Set location of first empty/delete to elt\n sp -> flag[index] = FILLED;//Flag location is now FILLED\n sp -> count++;//Increase count by 1 to account for new elt\n }\n}\n\n//O(n) for worst case\nvoid removeElement(SET *sp, void *elt){\n assert(sp != NULL && elt != NULL);\n bool found = false;//Found is false\n int index = search(sp, elt, &found);//Run search function\n if(found){ //If found is true\n sp -> flag[index] = DELETED;//Set flag to deleted\n sp -> count--;//Decrease count by 1 to account for deleting an elt\n }else\n printf(\"That elt doesn't exist\\n\");\n}\n\n//O(n)\nvoid *findElement(SET *sp, void *elt){\n assert(sp != NULL && elt != NULL);\n bool found = false; //If found is false\n int index = search(sp, elt, &found);//Run search function\n if(found)\n return sp -> data[index];//Return the elt found\n else\n return 0;\n}\n\n//O(n)\nvoid *getElements(SET *sp){\n assert(sp != NULL);\n int i,j;//initializing counters\n void** ret = malloc(sizeof(void*)* sp -> count);//Allocate memory the size of count for array ret\n assert(ret != NULL);\n \n for(i = 0; i < sp -> length; i++){\n if(sp -> flag[i] == FILLED){\n ret[j] = sp -> data[i];//If the flag[i] is FILLED, go to data[i] and copy to ret[j]\n j++;//This way every index of ret is only the FILLED data vals and no empty slots\n }else\n continue;\n }\n return ret;//Return elt\n //we want to only have array of filled elts from hash table not empty or deleted vals\n //need two counters, one for table/flag and one for new array\n}\n\n//O(n)\nstatic int search(SET *sp, void *elt, bool *found){\n assert(sp != NULL && elt != NULL);\n unsigned hasher = sp->hash(elt); //creating var for the client provided hash func\n int mod = hasher % sp -> length; //modulos\n int b = -1;\n \n for(int j = 0; j < sp -> length; j++){ //loop through entire table (0->legnth) to search for elt\n int addy = (mod + j) % sp -> length; //Remod and have linear probing\n \n if(sp -> flag[addy] == FILLED){ //go through flags and know where the first delete or empty flag is in case elt doesnt exist\n if(sp->compare(elt, sp -> data[addy]) == 0){ //compare elt and data[addy]\n *found = true; //found is true\n return addy; //return loc of elt\n }else\n continue;\n }else if(sp -> flag[addy] == DELETED){ //if deleted\n if(b == -1){\n b = addy;//set b to the loc of first deleted\n }else\n continue;\n }else if(sp -> flag[addy] == EMPTY){ //if empty\n if(b == -1){\n b = addy;//sets loc of first empty\n }if(b != -1)\n continue;\n }\n }\n *found = false; //if elt DNE, found is false\n return b;//return loc of either first empty or deleted loc\n}\n" }, { "alpha_fraction": 0.6391554474830627, "alphanum_fraction": 0.6871401071548462, "avg_line_length": 42.5, "blob_id": "800fe615155dd13a74c51033f29ae58ba7d951a5", "content_id": "29d57198bd1652ef1df865e5fca31d7eae9c02d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 521, "license_type": "no_license", "max_line_length": 50, "num_lines": 12, "path": "/SQL Databases/midterm2_mSingh/extra_credit_mSingh/values_mSingh.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh Extra Credit*/\ninsert into Book values('b1', 'Book1', 'Author1');\ninsert into Book values('b2', 'Book2', 'Author2');\ninsert into Book values('b3', 'Book3', 'Author3');\ninsert into Applicant values('s1', 'name1');\ninsert into Applicant values('s2', 'name2');\ninsert into Applicant values('s3', 'name3');\ninsert into BooksRead values('s1', 'b1');\ninsert into BooksRead values('s1', 'b2');\ninsert into BooksRead values('s2', 'b1');\ninsert into BooksRead values('s2', 'b2');\ninsert into BooksRead values('s2', 'b3');" }, { "alpha_fraction": 0.5943094491958618, "alphanum_fraction": 0.6010230183601379, "avg_line_length": 27.962963104248047, "blob_id": "fe9d5bb03a23f4b06b9863bb8d3c37144e8d07db", "content_id": "de8af150c2ce4d4e55c782e9400aea694785c8fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3129, "license_type": "no_license", "max_line_length": 125, "num_lines": 108, "path": "/C Data Structures/unsorted.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// unsorted.c\n//\n// Created by Mandeep Singh on 01/16/19.\n// Copyright © 2019 Mandeep Singh. All rights .\n//\n#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"set.h\" //Call libraries\n\nstatic int search(SET *sp, char *elt, bool *found);//initializing our private search function\n\ntypedef struct set{ //initialize struct\n char **data;//Pointer to an array of character strings\n int length; //Length of array\n int count; //Number of elements in array\n}SET;\n\n//O(1)\nSET *createSet(int maxElts){ //Creates our set using variables defined in the struct\n SET *sp;\n sp = malloc(sizeof(SET));\n assert(sp != NULL);\n sp -> count = 0;\n sp -> length = maxElts;\n sp -> data = malloc(sizeof(char*)*maxElts);\n assert(sp -> data != NULL);\n return sp;\n}\n\n//O(n)\nvoid destroySet(SET *sp){ //destory set returns nothing hence void\n assert(sp != NULL);//Checking array has no NULL elts\n for(int i = 0; i < sp -> count; i++)\n free(sp -> data[i]);//Freeing up memory\n free(sp -> data);\n free(sp);\n}\n\n//O(1)\nint numElements(SET *sp){ //done\n assert(sp != NULL);\n return sp -> count;//Returns the number of elements in the array\n}\n\n//O(n)\nvoid addElement(SET *sp, char *elt){\n assert(sp != NULL && elt != NULL);\n bool found = false;\n int find = search(sp, elt, &found);//Search function is O(n)//Run search function\n if(found){\n //printf(\"This element already exists\");\n }\n else{\n sp -> data[sp -> count] = strdup(elt);\n sp -> count++;// Add 1 to count to account for the new element\n }\n}\n\n//O(n)\nvoid removeElement(SET *sp, char *elt){\n assert(sp != NULL && elt != NULL);\n bool found = false;\n int check = search(sp, elt, &found);//run search function\n if(check){\n sp -> data[check] = sp -> data[sp -> count - 1];//Take last element and move it to the index of elt we want to remove\n sp -> count--;//Shrink the array size by 1 to eliminate last elt\n }else{\n // printf(\"That element doesn't exist\");\n }\n}\n\n//O(n)\nchar *findElement(SET *sp, char *elt){\n assert(sp != NULL && elt != NULL);\n bool found = false;\n int find = search(sp, elt, &found);//run search function\n \n if(found)\n return sp -> data[find];//return elt at data[find]\n else\n return NULL;//return nothing\n}\n\n//O(1)\nchar **getElements(SET *sp){\n assert(sp != NULL);\n char** ret = malloc(sizeof(char*)* sp -> count);//allocating memory the size of original array for array ret\n memcpy(ret, sp -> data, sizeof(char*)* (sp -> count));//Copying the chunk of data from the original array to array ret\n return ret;\n}\n\n//o(n)\nstatic int search(SET *sp, char*elt, bool*found){\n assert(sp != NULL && elt != NULL);\n for(int i = 0; i < sp -> count; i++){\n int result = strcmp(sp -> data[i], elt);//Comparing the string elt with each elt in array to see if it already exists\n if(result == 0){\n *found = true;\n return i;//the index at which found becomes true is returned\n }\n }\n *found = false;\n return -1;\n}\n" }, { "alpha_fraction": 0.6019900441169739, "alphanum_fraction": 0.6137494444847107, "avg_line_length": 28.87837791442871, "blob_id": "1999a1335141aa9061e1d3cca391faf12744c220", "content_id": "693a5a9e56da7fbbe68969d5016fd152b2a56bcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2212, "license_type": "no_license", "max_line_length": 108, "num_lines": 74, "path": "/C Data Structures/Term_Project/application_2/dataset.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// dataset.c\n//\n// Created by Mandeep Singh on 03/10/19.\n// Copyright © 2019 Mandeep Singh. All rights .\n//\n//\n#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"dataset.h\" //Import libraries for usage\n\ntypedef struct set{ //Define our struct set\n int *data;//Pointer to an array of integers\n int length; //Length of array\n int count; //Number of elements in array\n}SET;\n\n//O(n)\nSET *createDataSet(int maxElts){ //Creates out set using variables initialized in struct set\n SET *sp;\n sp = malloc(sizeof(SET)); //Allocate memory for set\n assert(sp != NULL);\n sp -> count = 0; //Set count to 0\n sp -> length = maxElts; //Set length to maxElts\n sp -> data = malloc(sizeof(int*)* maxElts); //Allocate memory for array data\n assert(sp -> data != NULL);\n for(int i = 0; i < sp -> length; i++){\n sp -> data[i] = 0; //Set all vals in array data to 0\n }\n return sp;\n}\n\n//O(1)\nvoid destroyDataSet(SET *sp){\n assert(sp != NULL);//Checking to see if array elts are NULL\n free(sp -> data); //Free array data\n free(sp); //Free set sp\n printf(\"All records successfully destroyed\\n\");\n}\n\n//O(1) for worst case\nvoid addElement(SET *sp, int elt, int ID){\n assert(sp != NULL);\n sp -> data[ID] = elt; //Insert elt at loc ID\n sp -> count++;//Increase count by 1 to account for new elt\n}\n\n//O(1) for worst case\nvoid removeElement(SET *sp, int ID){\n assert(sp != NULL);\n int search = searchID(sp, ID); //Utilize search func\n if(search != 0){ //If search is true\n sp -> data[ID] = 0; //Set index at ID to 0\n printf(\"Record was found and deleted\\n\");\n sp -> count--; //Decrement to account for deleted elt\n }else\n printf(\"Deletion could not be done\\n\");\n}\n\n//O(1)\nint searchID(SET *sp, int ID){\n assert(sp != NULL);\n int temp = sp -> data[ID]; //Since we are using ID to index mapping in an unsorted array, search is O(1)\n \n if(temp == 0) //0 means no ID exists there\n printf(\"Student ID: %d\\nStudent Age: No student associated with this ID\\n\", ID);\n else //ID exists\n printf(\"Student ID: %d\\nStudent Age: %d\\n\", ID, temp);\n \n return temp;\n}\n" }, { "alpha_fraction": 0.5317854881286621, "alphanum_fraction": 0.5594251155853271, "avg_line_length": 23.78082275390625, "blob_id": "ceb1368da9ec022034376cf987b524b3f3bb19d0", "content_id": "07058baa2414ef2b7a095ba1f19055f721e9fdee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1811, "license_type": "no_license", "max_line_length": 84, "num_lines": 73, "path": "/Operating Systems/Lab_3/lab3_part_5.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//Name: Mandeep Singh\n//Date: 01/27/20\n//Title: Lab3 - Pthreads and inter-process Communication – Pipes\n//Description: Producer and Consumer problem using a single buffer for two processes\n\n#include <stdio.h>\n#include <stdlib.h>\n#define RAND_DIVISOR 100000000\n\nint mutex = 1, full = 0, empty = 3, x = 0, item;\nvoid producer2();\nvoid consumer2();\nint wait2(int);\nint signal2();\n\nint main(){\n int n;\n printf(\"\\n1.Producer\\n2.Exit\");\n while(1){\n int rNum = rand() / RAND_DIVISOR;\n\n// Generate a random number\n item = rand();\n printf(\"\\nEnter your choice:\");\n scanf(\"%d\", &n);\n// Different options: Have producer put something in buffer or exit\n switch(n){\n case 1:\n// Mutex should be 1 and should not be full\n if((mutex == 1) && (empty != 0))\n producer2();\n else\n printf(\"Buffer is full\");\n break;\n case 2:\n exit(0);\n break;\n }\n// Consumer will automatically take what is in buffer\n if((mutex == 1) && (full != 0))\n consumer2();\n else\n printf(\"The buffer is empty\");\n }\n return 0;\n}\n\nint wait2(int s){\n return(--s);\n}\n\nint signal2(int s){\n return(++s);\n}\n//Producer waits for signal and if buffer is not full produces item\nvoid producer2(){\n mutex=wait2(mutex);\n full=signal2(full);\n empty=wait2(empty);\n x++;\n printf(\"\\nProducer produces the item %d\",item);\n mutex=signal2(mutex);\n}\n\n//Consumer waits for signal and if buffer is not empty comsumes item\nvoid consumer2(){\n mutex = wait2(mutex);\n full=wait2(full);\n empty=signal2(empty);\n printf(\"\\nConsumer consumes item %d\",item);\n x--;\n mutex=signal2(mutex);\n}\n" }, { "alpha_fraction": 0.6327543258666992, "alphanum_fraction": 0.6575682163238525, "avg_line_length": 14.5, "blob_id": "4e0d45fbbc9279096f317246099ec4af3569fd1a", "content_id": "15207fe5db74d162160feda3e731c1aa6b549b80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 404, "license_type": "no_license", "max_line_length": 42, "num_lines": 26, "path": "/C Data Structures/Term_Project/application_1_sorted/dataset.h", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// dataset.c\n//\n// Created by Mandeep Singh on 03/10/19.\n// Copyright © 2019 Mandeep Singh. All rights .\n//\n//\n\n# ifndef DATASET_H\n# define DATASET_H\n\ntypedef struct set SET;\n\nSET *createDataSet(int maxElts);\n\nvoid destroyDataSet(SET *sp);\n\nvoid addElement(SET *sp, int age, int ID);\n\nvoid removeElements(SET *sp, int age);\n\nvoid searchAge(SET *sp, int age);\n\nvoid maxAgeGap(SET *sp);\n\n# endif /* DATASET_H */\n" }, { "alpha_fraction": 0.6967560052871704, "alphanum_fraction": 0.727785587310791, "avg_line_length": 27.360000610351562, "blob_id": "3cdf2243ee382ad3dc7d42b72bd4d6d9b915f146", "content_id": "50df6ec4abda08f1a1227b50bc1f709c974e2093", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1418, "license_type": "no_license", "max_line_length": 95, "num_lines": 50, "path": "/SQL Databases/lab5/part1/psql1.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "Create or Replace Procedure assignJobTitlesAndSalaries\nAS\ntype titlesList IS VARRAY(6) OF AlphaCoEmp.title%type;\ntype salaryList IS VARRAY(6) of AlphaCoEmp.salary%type;\nv_titles titlesList; \nv_salaries salaryList; \nCursor Emp_cur IS \nSelect * from AlphaCoEmp; \nl_emprec Emp_cur%rowtype; \nl_title AlphaCoEmp.title%type; \nl_salary AlphaCoEmp.salary%type; \nl_randomnumber INTEGER := 1; \nBEGIN \n/* Titles are stored in the v_titles array */\n/* Salaries for each title are stored in the v_salaries array.\nThe salary of v_titles[0] title is at v_salaries[0].\n*/\nv_titles := titlesList('advisor', 'director', 'assistant', 'manager', 'supervisor', 'intern'); \n\nv_salaries := salaryList(130000, 100000, 600000, 500000, 800000, 10000);\n\n/* use a for loop to iterate through the set */\nfor l_emprec IN Emp_cur \nLOOP \n\t/* We get a random number between 1-5 both inclusive */\nl_randomnumber := dbms_random.value(1,6);\n \n/* Get the title using the random value as the index into the\nv_tiles array */\nl_title := v_titles(l_randomnumber);\n/* Get the salary using the same random value as the index into the v_salaries array */\nl_salary := v_salaries(l_randomnumber); \n\n\t/* Update the employee title and salary using the l_title \nand l_salary */\nupdate AlphaCoEmp \nset title = l_title \nwhere name = l_emprec.name; \n\nupdate AlphaCoEmp \nset salary = l_salary \nwhere name = l_emprec.name; \n\n\nEND LOOP; \n\ncommit; \nEND; \n/ \nShow errors; " }, { "alpha_fraction": 0.4728209972381592, "alphanum_fraction": 0.5238987803459167, "avg_line_length": 18.57798194885254, "blob_id": "88dcd5e7ad078ff203d154b3dbe07a4ad238add3", "content_id": "e152c07c758e4b2ab50c31a566791ef2d2de621d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2135, "license_type": "no_license", "max_line_length": 51, "num_lines": 109, "path": "/C++ Data Structures/Lab_2/main.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// Lab_2\n//\n// Created by Mandeep Singh on 4/11/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n#include \"statistician.h\"\n#include \"random.h\"\n#include <iostream>\n\nusing namespace std;\nusing namespace coen79_lab2;\n\nvoid printStatisticianInfo(statistician & s) {\n cout << \"Sum: \" << s.sum() << endl;\n cout << \"Mean: \" << s.mean() << endl;\n cout << \"Smallest: \" << s.minimum() << endl;\n cout << \"Largest: \" << s.maximum() << endl;\n cout << endl;\n}\n\nvoid printNumbers(rand_gen &r, int num) {\n \n for (int i = 0; i < num; i++) {\n r.print_info();\n cout << \"Next: \" << r.next() << endl;\n cout << \"\\n\" << endl;\n }\n cout << endl;\n}\n\n// main function\nint main(int argc, const char * argv[])\n{\n //statistician start\n statistician s1, s2, s3;\n \n cout << \"--- s1 prints ---\" << endl;\n \n s1.next(1.1);\n printStatisticianInfo(s1);\n s1.next(-2.4);\n printStatisticianInfo(s1);\n s1.next(0.8);\n printStatisticianInfo(s1);\n \n cout << \"--- s2 prints ---\" << endl;\n \n s2.next(5.7);\n printStatisticianInfo(s2);\n s2.next(-3.8);\n printStatisticianInfo(s2);\n s2.next(4.9);\n printStatisticianInfo(s2);\n \n s3 = s1 + s2;\n \n cout << \"--- s3 print ---\" << endl;\n \n printStatisticianInfo(s3);\n \n cout << \"--- erase prints ---\" << endl;\n \n s1.reset();\n s1.next(5);\n printStatisticianInfo(s1);\n \n s2 = s1;\n printStatisticianInfo(s1);\n \n s1.reset();\n s2.reset();\n s1.next(4);\n s2.next(4);\n if (s1 == s2)\n cout << \"s1 is equal to s2\" << endl;\n \n cout << endl << \"--- scaling test ---\" << endl;\n \n s1.reset();\n s1.next(4);\n s1.next(-2);\n printStatisticianInfo(s1);\n s1 = -1 * s1;\n printStatisticianInfo(s1);\n \n //random start\n \n rand_gen rg(1, 40, 725, 729);\n rg.print_info();\n printNumbers(rg, 5);\n \n rg.set_seed(1);\n printNumbers(rg, 5);\n\n rg.set_seed(15);\n printNumbers(rg, 5);\n\n\n rand_gen rg2(14, 85, 637, 1947);\n\n printNumbers(rg2, 5);\n\n rg2.set_seed(14);\n printNumbers(rg2, 5);\n\n EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.5428571701049805, "alphanum_fraction": 0.6095238327980042, "avg_line_length": 14, "blob_id": "4634f695ffea6607a49fc6dbeae6259feab3872e", "content_id": "29b93c959c2745d9fe6ce862e1d607e5a0621f81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 211, "license_type": "no_license", "max_line_length": 49, "num_lines": 14, "path": "/C++ Data Structures/Lab_1/part3.hpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// part3.hpp\n// Lab_1\n//\n// Created by Mandeep Singh on 4/4/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#ifndef part3_hpp\n#define part3_hpp\n\n#include <stdio.h>\nvoid part3();\n#endif /* part3_hpp */\n" }, { "alpha_fraction": 0.36216217279434204, "alphanum_fraction": 0.38078078627586365, "avg_line_length": 25.015625, "blob_id": "3e25a17304d9fcdd5380a35d6cc2ebf3b002e24f", "content_id": "f52c939ee93476503114812bcfd1e66aea21a7f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1665, "license_type": "no_license", "max_line_length": 97, "num_lines": 64, "path": "/Operating Systems/Lab 8/second_hand.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n\ntypedef struct {\n int pageno;\n int refbit;\n} ref_page;\n\nint main(int argc, char *argv[]){\n\tint C_SIZE = atoi(argv[1]);\n ref_page cache[C_SIZE];\n int totalFaults = 0, totalRequests = 0;\n int nf = 0;\n int n, i, j, k = 0;\n \n for (n = 0; n < C_SIZE; n++){\n cache[n].pageno = -1;\n cache[n].refbit = 0;\n }\n char cache2[1000];\n while (fgets(cache2,100,stdin)){\n int page_num = atoi(cache2);\n totalRequests++;\n for (i = 0; i < C_SIZE; i++){\n if (page_num == cache[i].pageno){\n cache[i].refbit = 1;\n nf = 0;\n break;\n }\n if (i == C_SIZE - 1)\n nf = 1;\n }\n if (nf == 1){\n totalFaults++;\n printf(\"Page %d caused a page fault.\\n\", page_num);\n for (j = k ; j < C_SIZE; j++){\n if (cache[j].refbit == 1){\n cache[j].refbit = 0;\n k++;\n if (k == C_SIZE){\n k = 0;\n j = -1;\n }\n }\n else{\n cache[j].pageno = page_num;\n cache[j].refbit = 0;\n k++;\n if (k == C_SIZE){\n k = 0;\n }\n break;\n }\n\n }\n }\n }\n\n printf(\"%d Total Page Faults\", totalFaults);\n printf(\"\\nSecond Chance Hit rate = %f\\n\", (totalRequests-totalFaults)/(double)totalRequests);\n return 0;\n}\n" }, { "alpha_fraction": 0.5677472949028015, "alphanum_fraction": 0.7032418847084045, "avg_line_length": 53.727272033691406, "blob_id": "b5213f0376774af3157204f9a89f19a4104321ce", "content_id": "6cab3b787d445d53d354cf068abfb47566be3b0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1203, "license_type": "no_license", "max_line_length": 109, "num_lines": 22, "path": "/COEN_178_Final_Project_mSingh/values.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh*/\n/*COEN 178 Final Project*/\n/*Insert Values*/\n/*Inserting into storeItems*/\ninsert into storeItems values ('item1', 9.99);\ninsert into storeItems values ('item2', 19.99);\ninsert into storeItems values ('item5', 24.99);\ninsert into storeItems values ('item6', 15.99);\ninsert into storeItems values ('item9', 12.99);\n/*Inserting into comicbook*/\ninsert into comicbook values ('item1', '0019029129', 'Dragonball Z', '19-jan-2019', 2);\ninsert into comicbook values ('item2', '0018240582', 'Naruto', '15-may-2020', 5);\ninsert into comicbook values ('item6', '0014359302', 'Iron Man', '04-nov-2019', 10);\ninsert into comicbook values ('item9', '0012384958', 'Spider-man', '02-aug-2017', 7);\n/*Inserting into Tshirt*/\ninsert into Tshirt values ('item5', 20);\n/*Inserting into customers*/\ninsert into customers values ('c001', 'regular', '4085159662', 'Bob Duncan', '1334 First Street, Saratoga, CA');\ninsert into customers values ('c002', 'regular', '4088281912', 'Ronald McDonald', '1125, Main Avenue, Cupertino, CA');\ninsert into customers values ('c003', 'gold', '4086638840', 'Tony Stark', '2234 Malibu Way, Sunnyvale, CA');\n/*Inserting into golddcustomer*/\ninsert into goldcustomer values('c003', '13-dec-2012');" }, { "alpha_fraction": 0.8141592741012573, "alphanum_fraction": 0.8163716793060303, "avg_line_length": 225.5, "blob_id": "d34218fd3a5f3d74a284a8e50db956585a0be2b7", "content_id": "ab2b00a57e0a986c16cce7f74ce06b86f183fb0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 452, "license_type": "no_license", "max_line_length": 437, "num_lines": 2, "path": "/C Data Structures/Term_Project/application_2/README.txt", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "Application 2:\rAssume that the college takes very few transfer students and has most of its students stay for at least one year (Hints: no frequent insertion and deletion operations). And the maximum student number is given. But it does require a lot of search operations. Specifically, all of the searches are based on student IDs. The major interfaces provided by your code should include createDataSet, destroyDataSet, searchID, insertion, deletion." }, { "alpha_fraction": 0.6645962595939636, "alphanum_fraction": 0.6645962595939636, "avg_line_length": 24.473684310913086, "blob_id": "3fbddd8677dad497ae99273ee2574b75cf7c8537", "content_id": "b4b5e38961152d6cb009e7f486f73f8785afd6b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 483, "license_type": "no_license", "max_line_length": 92, "num_lines": 19, "path": "/SQL Databases/lab4/part2/psql2.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "Create or Replace Procedure setEmpSalary(p_name in VARCHAR, low in INTEGER, high in INTEGER)\nAS\n/* Define the local variables you need */\nCursor Emp_cur IS\n Select * from AlphaCoEmp;\n l_emprec Emp_cur%rowtype;\n l_salary AlphaCoEmp.salary%type;\nBEGIN\n for l_emprec IN Emp_cur \n loop\n l_salary := ROUND(dbms_random.value(low,high)); \n update AlphaCoEmp \n set salary = l_salary \n where name = p_name;\nEND LOOP;\n commit;\nEND;\n/\nshow errors;" }, { "alpha_fraction": 0.6046748161315918, "alphanum_fraction": 0.6121273636817932, "avg_line_length": 31.086956024169922, "blob_id": "57c315e1fd3286a417bf738a9a8828d453ebe290", "content_id": "7824d1c429441e8cb09bdf5af162b8d65a4ccbe2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2953, "license_type": "no_license", "max_line_length": 124, "num_lines": 92, "path": "/C Data Structures/set.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// set.c\n//\n// Created by Mandeep Singh on 02/21/19.\n// Copyright © 2019 Mandeep Singh. All rights .\n//\n#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h> //Import libraries for usage\n#include \"set.h\" //Import header file\n#include \"list.h\"\n\ntypedef struct set{ //Define our struct set\n void **data;//Pointer to an array of character strings\n int length; //Length of array\n int count; //Number of elements in array\n int (*compare)(); //Pointer to compare function passed through\n unsigned (*hash)(); //Pointer to hash function passed through\n}SET;\n\n//O(n)\nSET *createSet(int maxElts, int(*compare)(), unsigned(*hash)()){ //Creates out set using variables initialized in struct set\n SET *sp;\n sp = malloc(sizeof(SET));\n assert(sp != NULL);\n sp -> count = 0;\n sp -> length = maxElts/20;\n sp -> data = malloc(sizeof(LIST*)* (sp -> length)); //Allocate memory size of list for length elts\n assert(sp -> data != NULL); //Make sure data is not NULL\n for(int i = 0; i < sp -> length; i++) //Make list for each hash location\n sp -> data[i] = createList(compare);\n sp -> compare = compare;\n sp -> hash = hash;\n return sp;\n}\n\n//O(n)\nvoid destroySet(SET *sp){\n for(int i = 0; i < sp -> length; i++)//Destroy every list in table\n destroyList(sp -> data[i]);\n free(sp -> data);//Free up hash table\n free(sp); //Free set\n}\n\n//O(1)\nint numElements(SET *sp){\n return sp -> count;//Return the number of elements in array\n}\n\n//O(1)\nvoid addElement(SET *sp, void* elt){\n assert(sp != NULL && elt != NULL); //make sure set and elt are not NULL\n unsigned index;\n index = sp -> hash(elt) % sp -> length; //hash key to find address\n addFirst(sp -> data[index], elt); //Call addFirst list function\n sp -> count++; //Increase count by 1 to account for adding an elt\n}\n\n//O(1)\nvoid removeElement(SET *sp, void* elt){\n assert(sp != NULL && elt != NULL);\n unsigned index;\n index = sp -> hash(elt) % sp -> length;\n removeItem(sp -> data[index], elt); //Call removeItem list function\n sp -> count--;//Decrease count by 1 to account for deleting an elt\n}\n\n//O(n)\nvoid *findElement(SET *sp, void* elt){\n assert(sp != NULL && elt != NULL);\n unsigned index;\n index = sp -> hash(elt) % sp -> length;\n void* x = findItem(sp -> data[index], elt);//call findItem list function\n return x;//return found elt\n}\n\n//O(n)\nvoid *getElements(SET *sp){ //we want to only have array of elts from hash table\n assert(sp != NULL); //Make sure set sp is not NULL\n void** ret = malloc(sizeof(LIST*)* sp -> count);//Allocate memory the size of count for array ret\n assert(ret != NULL);\n \n int j = 0; //need two counters, one for new array and one for table\n for(int i = 0; i < sp -> length; i++){\n if(sp -> data[i] != NULL){\n ret[j] = getItems(sp -> data[i]);\n }\n }\n return ret;//Return elts\n}\n" }, { "alpha_fraction": 0.5598651170730591, "alphanum_fraction": 0.5699831247329712, "avg_line_length": 27.285715103149414, "blob_id": "bea49278104770c6efef9bdc3fc1c5eed33c0bf9", "content_id": "bfad965e02ae5921d17b1e5885a57d014caab35f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 593, "license_type": "no_license", "max_line_length": 84, "num_lines": 21, "path": "/Java/Circle Area/src/CircleArea.java", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "import java.util.Scanner;\npublic class CircleArea {\n public static void main(String[] args) {\n Scanner input = new Scanner(System.in);\n double radius = 0;\n \n while (radius != -1) {\n \n System.out.println(\"\\nEnter the radius value. Enter -1 to quit: \");\n radius = input.nextDouble();\n if (radius > 0 ) {\n System.out.printf(\"The area of the circle is %.2f\", circleArea(radius));\n }\n }\n }\npublic static double circleArea(double radius)\n {\n double area = Math.PI * Math.pow(radius, 2);\n return area;\n }\n}" }, { "alpha_fraction": 0.7112675905227661, "alphanum_fraction": 0.7112675905227661, "avg_line_length": 20.923076629638672, "blob_id": "992aed7a93e7a1cd054c3cf52314e401ee429522", "content_id": "12f20687c2c0ddfbdcc2810a4f9b386ad1e74aaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 284, "license_type": "no_license", "max_line_length": 58, "num_lines": 13, "path": "/SQL Databases/lab4/psql3.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "Create or Replace FUNCTION getEmpSalary(p_name in VARCHAR)\nReturn NUMBER IS\n/* Define the local variables you need */\n l_salary AlphaCoEmp.salary%type;\nBEGIN\n Select salary \n INTO l_salary\n FROM AlphaCoEmp\n where name = p_name;\n return l_salary;\nEND;\n/\nshow errors;" }, { "alpha_fraction": 0.5394126772880554, "alphanum_fraction": 0.5656877756118774, "avg_line_length": 25.95833396911621, "blob_id": "31e0dd573d9b4fc5e2307b299c461617e08a070a", "content_id": "bcc76bc840638df01a11e2ef6745bbf8bc012f96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 648, "license_type": "no_license", "max_line_length": 241, "num_lines": 24, "path": "/C++ Data Structures/Homework_1/HW_2/main.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// HW_2\n//\n// Created by Mandeep Singh on 4/7/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include <iostream>\n#include \"statistician.hpp\"\n\nusing namespace std;\n\nint main(int argc, const char * argv[]) {\n statistician s;\n s.next_number(-10);\n s.next_number(5);\n s.next_number(-5);\n s.next_number(10);\n s.next_number(5);\n s.next_number(-5);\n cout << \"Length is: \" << s.get_length() << \"\\nSum is: \" << s.get_sum() << \"\\nAverage is: \" << s.get_avg() << \"\\nSmallest is: \" << s.get_smallest() << \"\\nLargest is: \" << s.get_largest() << \"\\nLast Number is: \" << s.get_lastNum() << endl;\n EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.6844262480735779, "alphanum_fraction": 0.688524603843689, "avg_line_length": 16.5, "blob_id": "6f80c9f434a407b367ff60864634a40d747ef6f7", "content_id": "f2c19b9ade0431eac3affaf731190a948e0f7dae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 244, "license_type": "no_license", "max_line_length": 53, "num_lines": 14, "path": "/SQL Databases/lab7/psql1.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "CREATE OR REPLACE TRIGGER ItemOrder_after_insert_trig\nAFTER INSERT\n ON ItemOrder\n FOR EACH ROW\nDECLARE\n v_quantity Integer;\nBEGIN \n SELECT qty \n INTO v_quantity\n FROM ItemOrder\n WHERE orderNo = 'o1';\nEND;\n/\nShow Errors;" }, { "alpha_fraction": 0.6387900114059448, "alphanum_fraction": 0.6530249118804932, "avg_line_length": 23.478260040283203, "blob_id": "685ce7edd95fe04732f574f90e2f111d631f8283", "content_id": "d487e89714826a9bf996815ebd7e0ca5b238adb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 562, "license_type": "no_license", "max_line_length": 61, "num_lines": 23, "path": "/Java/13.19/src/Main.java", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.Timer;\n\npublic class Main {\n public static void main(String args[])\n { \n JFrame frame = new JFrame( \"ScreenSaver\");\n\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n \n ScreenSaver Test1 = new ScreenSaver();\n\n frame.add(Test1);\n frame.setSize(300,300);\n frame.setVisible(true);\n }\n\n}" }, { "alpha_fraction": 0.5310795903205872, "alphanum_fraction": 0.5430752635002136, "avg_line_length": 21.365854263305664, "blob_id": "8793966c8c8d91313b41b4e37cef996c1bf81a75", "content_id": "ca83692506f18ace7fc1d65ad249c42d598a3d30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 917, "license_type": "no_license", "max_line_length": 63, "num_lines": 41, "path": "/Operating Systems/Lab_9/part4.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <pthread.h>\n\ntypedef struct{\n int i;\n char **a;\n} arguments;\n\nvoid *go(void *arg) {\n arguments *argu = (arguments *) arg;\n int count = (*argu).i;\n int MAX = atoi((*argu).a[2]);\n int buff[MAX];\n char *file = (*argu).a[1];\n FILE *fp = fopen(file,\"rb\");\n char filename[20];\n sprintf(filename, \"%d%spart4output%d.bin\",count, file,MAX);\n FILE *wp = fopen(filename,\"wb\");\n while(fread(buff,MAX,1,fp)){\n fwrite(buff, MAX,1,wp);\n }\n fclose(fp);\n fclose(wp);\n return (NULL);\n}\n\nint main(int argc, char *argv[]){\n arguments argument;\n int x = atoi(argv[3]);\n pthread_t threads[x];\n int j;\n argument.a = argv;\n for (j = 0; j < x; j++){\n argument.i = j;\n pthread_create(&threads[j], NULL, go, &argument);\n }\n for (j = 0; j < x; j++)\n pthread_join(threads[j],NULL);\n return 0;\n}\n" }, { "alpha_fraction": 0.7120622396469116, "alphanum_fraction": 0.7120622396469116, "avg_line_length": 24.799999237060547, "blob_id": "56851112222845920cb9450e4c12e2aae12f7186", "content_id": "ca9c50055dd99b50e07bef04e97d1023fd4486ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 257, "license_type": "no_license", "max_line_length": 66, "num_lines": 10, "path": "/SQL Databases/Extra_Credit_1/psql1.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "Create or Replace FUNCTION Something (v_sno IN Supplier.SNO%TYPE) \nRETURN NUMBER IS l_cnt NUMBER;\nBEGIN\n Select count(city) into l_cnt\n From Supplier\n Where city = (Select city From Supplier where v_sno = sno);\n return l_cnt;\nEND;\n/\nshow errors;" }, { "alpha_fraction": 0.6933333277702332, "alphanum_fraction": 0.7133333086967468, "avg_line_length": 15.666666984558105, "blob_id": "be355a2eb96b5ddaa43e4a0e0d9e05919b6a4b14", "content_id": "337320776b6171f49c0502a57802cd4e4420a714", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 150, "license_type": "no_license", "max_line_length": 35, "num_lines": 9, "path": "/Artificial Intelligence/Lab_1/test2_module.py", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "c = 5\nd = 10\nfrom module import adder\nresult = adder(c, d)\nprint(result)\n\nfrom module import a, b, multiplier\nresult = multiplier(a, b)\nprint(result)\n" }, { "alpha_fraction": 0.6067415475845337, "alphanum_fraction": 0.6651685237884521, "avg_line_length": 39.45454406738281, "blob_id": "ab678d6cbb7ffcd1b45865525d368c2fa28930c5", "content_id": "e21124df0231969de766df717b2bf21444eb5d58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 445, "license_type": "no_license", "max_line_length": 42, "num_lines": 11, "path": "/SQL Databases/midterm2_mSingh/Number_8_mSingh/values_mSingh.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "/*Mandeep Singh Number 8*/\ninsert into Emp_Office values('E1', '10');\ninsert into Emp_Office values('E2', '10');\ninsert into Emp_Office values('E3', '12');\ninsert into Emp_Office values('E4', '12');\ninsert into Emp_Office values('E5', '15');\ninsert into Emp_Phone values('E1', 'P1');\ninsert into Emp_Phone values('E2', 'P2');\ninsert into Emp_Phone values('E3', 'P3');\ninsert into Emp_Phone values('E4', 'P3');\ninsert into Emp_Phone values('E5', 'P5');\n" }, { "alpha_fraction": 0.5067829489707947, "alphanum_fraction": 0.5145348906517029, "avg_line_length": 25.805194854736328, "blob_id": "3d94bc452f3807a7a376cf111aee19c6b18b11c8", "content_id": "6e10fd79bbb78523e837d801a006d74cbdfa1c69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2067, "license_type": "no_license", "max_line_length": 108, "num_lines": 77, "path": "/C++ Data Structures/Homework_2/HW_5/set.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// set.cpp\n// HW_2\n//\n// Created by Mandeep Singh on 4/17/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n\n#include \"set.hpp\"\n#include <algorithm> // Provides copy function\n#include <cassert> // Provides assert function\nnamespace std {\n \n const set::size_type set::DEFAULT_CAPACITY;\n \n set::set(size_type initial_capacity){\n used = 0;\n data = new value_type[initial_capacity];\n capacity = initial_capacity;\n }\n \n void set::reserve(size_type new_capacity){\n value_type *larger_array;\n if (new_capacity == capacity)\n return; // The allocated memory is already the right size. if (new_capacity < used)\n new_capacity = used; // Can’t allocate less than we are using.\n larger_array = new value_type[new_capacity]; copy(data, data + used, larger_array); delete [ ] data;\n data = larger_array;\n capacity = new_capacity;\n }\n \n //O(n)\n set::size_type set::erase(const value_type& target)\n {\n size_type index = 0;\n size_type many_removed = 0;\n while (index < used) {\n if (data[index] == target) {\n --used;\n data[index] = data[used];\n ++many_removed;\n }\n else\n ++index;\n }\n return many_removed;\n }\n \n //O(n)\n bool set::erase_one(const value_type& target) {\n size_type index;\n index = 0;\n while ((index < used) && (data[index] != target))\n ++index;\n if (index == used)\n return false;\n --used;\n data[index] = data[used]; return true;\n }\n \n //O(n)\n void set::insert(const value_type& entry){\n if (used == capacity)\n reserve(used+1);\n if(!contains(entry)){\n data[used] = entry;\n used++;\n }\n }\n \n //O(n)\n bool set::contains(const value_type& target) const{\n for (size_type i = 0; i < used; ++i)\n if (target == data[i]) return true;\n return false;\n }\n}\n" }, { "alpha_fraction": 0.5862764716148376, "alphanum_fraction": 0.5963672995567322, "avg_line_length": 30.460317611694336, "blob_id": "ceb8a88c0bb7e4901e68fbcd7b08a8d79e9a47a2", "content_id": "25cedf549c090d121f711dd7cb873302808fa973", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1983, "license_type": "no_license", "max_line_length": 96, "num_lines": 63, "path": "/C++ Data Structures/Homework_2/HW_5/sequence1.hpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// sequence1.h\n// Lab_3\n//\n// Created by Mandeep Singh on 4/18/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n// Sequence Class\n//\n#ifndef SEQUENCE1_H\n#define SEQUENCE1_H\n\n#include <iostream>\n\nnamespace std{\n class sequence{\n public:\n // TYPEDEF and MEMBER CONSTANTS\n typedef double value_type;\n typedef std::size_t size_type;\n static const size_type DEFAULT_CAPACITY = 50;\n sequence(size_type initial_capacity = DEFAULT_CAPACITY);\n ~sequence(){ delete [] data; };\n \n // MODIFICATION MEMBER FUNCTIONS\n void start(){ current_index = 0; };\n void end(){ current_index = used - 1; };\n void last(){ current_index = capacity - 1; };\n void advance();\n void retreat(){ if(current_index != 0) current_index--; };\n void insert(const value_type& entry);\n void attach(const value_type& entry);\n void remove_current();\n void insert_front(const value_type& entry);\n void attach_back(const value_type& entry);\n void remove_front();\n void reserve(size_type new_capacity);\n void operator +=(const sequence& rhs);\n \n // CONSTANT MEMBER FUNCTIONS\n double getItem(int index) const;\n size_type size() const { return used; } ;\n bool is_item() const{ if((current_index + 1) <= used) return true; else return false; };\n value_type current() const { return data[current_index]; };\n sequence::value_type operator[](const int index);\n double mean() const;\n size_type cap() const{ return capacity; }\n double standardDeviation() const;\n value_type operator [](int index) const;\n \n private:\n value_type *data;\n size_type capacity;\n size_type used;\n size_type current_index;\n };\n // NON-MEMBER FUNCTIONS\n double summation(const sequence &s);\n sequence operator +(const sequence& lhs, const sequence& rhs);\n \n}\n\n#endif\n" }, { "alpha_fraction": 0.5164473652839661, "alphanum_fraction": 0.5197368264198303, "avg_line_length": 25.05714225769043, "blob_id": "1956d1c88c5729ee24391ca4e37c6b88802ce206", "content_id": "66fd3a6961d8cb1b51ae64bb5cdfaeb61fda2d8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 912, "license_type": "no_license", "max_line_length": 77, "num_lines": 35, "path": "/Java/Midterm Problem 2/src/MidtermProblem2.java", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "import java.util.Scanner;\npublic class MidtermProblem2 {\n public static void main(String[] args) {\n Scanner input = new Scanner(System.in);\n\n System.out.printf(\"Enter number of rows: \");\n int rows = input.nextInt();\n System.out.printf(\"Enter number of columns: \");\n int columns = input.nextInt();\n \n printStarMatrix(rows, columns);\n \n }\n \n public static void printStarMatrix(int rows, int columns)\n {\n String asterisk = \"*\";\n for(int a = 0; a < rows; a++) \n {\n System.out.println(\"\");\n for (int b = 0; b <= columns; b++) \n {\n System.out.print(\"*\");\n }\n }\n System.out.println(\"\");\n }\n \n public static String printBorder(int rows, int columns, String character)\n {\n String border = character;\n \n return border;\n }\n}\n" }, { "alpha_fraction": 0.5285714268684387, "alphanum_fraction": 0.5428571701049805, "avg_line_length": 19.322580337524414, "blob_id": "2d84e1cd09840975c539e17d891a9e113e0f5cb9", "content_id": "8c77349d6bea226f5123dcf3844f0acdd9a3f7ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 630, "license_type": "no_license", "max_line_length": 57, "num_lines": 31, "path": "/Java/classChooserTest/src/ClassChooserTest.java", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n\npublic class ClassChooserTest{\n\n String[] classList = {\"\",\"Class1\",\"Class2\",\"Class3\"};\n JComboBox c = new JComboBox(classList);\n \n public ClassChooserTest(){\n frame();\n }\n \n public void frame()\n {\n JFrame f = new JFrame();\n f.setVisible(true);\n f.setSize(400, 400);\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n \n JPanel p = new JPanel();\n p.add(c);\n \n f.add(p);\n }\n public static void main(String[] args) {\n \n new ClassChooserTest();\n }\n\n}\n" }, { "alpha_fraction": 0.5436508059501648, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 15.800000190734863, "blob_id": "c4393aabbe2d42c5ec913d7602f637e3de8b07b9", "content_id": "219fa51150604219097024e684098eb62e796d47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 252, "license_type": "no_license", "max_line_length": 36, "num_lines": 15, "path": "/Operating Systems/Lab_9/part1.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n\n#define MAX 10000\n\n\nint main(int argc, char *argv[]){\n int buff[MAX];\n FILE *fp = fopen(argv[1], \"rb\");\n while(fgets(buff,MAX,fp)){\n //Only reading the files\n }\n fclose(fp);\n return 0;\n}\n" }, { "alpha_fraction": 0.5259259343147278, "alphanum_fraction": 0.5580247044563293, "avg_line_length": 22.14285659790039, "blob_id": "43fc2a44b60b30f20f55110b11eaa786a219f470", "content_id": "0ef4695e1b52393779c58bcc9f7efd268e743677", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 811, "license_type": "no_license", "max_line_length": 65, "num_lines": 35, "path": "/C Data Structures/insertion-sort.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// insertion-sort.c\n//\n// Created by Mandeep Singh on 03/19/19.\n// Copyright © 2018 Mandeep Singh. All rights .\n//\n//Utilizing the insertion sort algorithm to sort an integer array\n#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h> //Import libraries for usage\n#define NUM_OF_ELEMENTS 7\n\nvoid insertionSort(int arr[]);\n\nint main(){\n int myarray[NUM_OF_ELEMENTS] = {6, 4, 7, 9, 2, 0, 19};\n insertionSort(myarray);\n for(int i = 0; i < NUM_OF_ELEMENTS; i++)\n printf(\"%d\\n\", myarray[i]);\n}\n\n//O(n^2) & stable\nvoid insertionSort(int arr[]){\n int i, j, temp;\n for(i = 1; i < NUM_OF_ELEMENTS; i++){\n temp = arr[i];\n \n for(j = i - 1; temp < arr[j] && j >= 0; j--)\n arr[j + 1] = arr[j];\n\n arr[j + 1] = temp;\n }\n}\n" }, { "alpha_fraction": 0.4868255853652954, "alphanum_fraction": 0.6775407791137695, "avg_line_length": 65.5, "blob_id": "9a9b272486c22c7da2eba5db62110c27c2393032", "content_id": "dcdff89fd0bc52678b8bb345fa40a5a1d686dd07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 797, "license_type": "no_license", "max_line_length": 91, "num_lines": 12, "path": "/SQL Databases/lab7/sql1.sql", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "insert into EMP7 values ('e1','J.Smith','d1',100000);\ninsert into EMP7 values ('e2','M.Jones','d1',120000);\ninsert into EMP7 values ('e3','D.Clark','d2',200000);\ninsert into EMP7 values ('e4','C.Johnson','d1',120000);\ninsert into EMP7 values ('e5','W.Greenwalt','d2',200000);\ninsert into Project7 values ('pj1','Research', 1000000, '10-Jan-2019','20-Feb-2020','e1');\ninsert into Project7 values ('pj2','Research', 100000, '10-Feb-2019','20-Apr-2019','e2');\ninsert into Project7 values ('pj3','Research', 1000000, '10-Mar-2019','20-Apr-2020','e3');\ninsert into Project7 values ('pj4','Research', 100000, '10-May-2019','20-Jul-2019','e4');\ninsert into EMP_Project values ('pj2','e2',10000);\ninsert into EMP_Project values ('pj4','e1',10000);\ninsert into EMP_Project values ('pj3','e4',10000);" }, { "alpha_fraction": 0.538938045501709, "alphanum_fraction": 0.5973451137542725, "avg_line_length": 27.25, "blob_id": "361716a64d582035d0d527cebd4fbdacbc4d6386", "content_id": "ac6b461e4edc2305a556dd1b5075c1679f5d93a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1131, "license_type": "no_license", "max_line_length": 117, "num_lines": 40, "path": "/C Data Structures/Term_Project/application_1_sorted/college.c", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// college.c\n//\n// Created by Mandeep Singh on 03/14/19.\n// Copyright © 2019 Mandeep Singh. All rights .\n//\n//\n# include <stdio.h>\n# include <stdlib.h>\n# include <string.h>\n# include <stdbool.h>\n#include <time.h>\n# include \"dataset.h\"\n# define MAX_SIZE 3000\n\nint main()\n{\n SET *records;\n records = createDataSet(MAX_SIZE);\n \n /* Insert all records into the set. */\n \n int ID = 0;\n int age;\n srand(time(NULL));\n for(int i = 0; i < 1000; i++){\n int r = (rand() % 1) + 2; //A number between 0 and 1 randomly chosen and increased by 1 so range is [1,2]\n age = (rand() % 12) + 18; //A number between 0 and 12 randomly chosen and increased by 18 so range is [18,30]\n ID += r;\n addElement(records, age, ID);\n }\n \n age = (rand() % 12) + 18; //A number between 0 and 12 randomly chosen and increased by 18 so range is [18,30]\n searchAge(records, age);\n age = (rand() % 12) + 18; //A number between 0 and 12 randomly chosen and increased by 18 so range is [18,30]\n removeElements(records, age);\n maxAgeGap(records);\n destroyDataSet(records);\n exit(EXIT_SUCCESS);\n}\n" }, { "alpha_fraction": 0.5155279636383057, "alphanum_fraction": 0.5403726696968079, "avg_line_length": 25.83333396911621, "blob_id": "f1cbb281e25155cb38741a856a33fe693a9cb68b", "content_id": "594c999c58483c6e60e06b55d59d804532a62976", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 967, "license_type": "no_license", "max_line_length": 111, "num_lines": 36, "path": "/C++ Data Structures/Lab_1/part3.cpp", "repo_name": "msingh9001/Singh_Projects", "src_encoding": "UTF-8", "text": "//\n// part3.cpp\n// Lab_1\n//\n// Created by Mandeep Singh on 4/4/19.\n// Copyright © 2019 Mandeep Singh. All rights reserved.\n//\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <ctype.h>\n#include <stdio.h>\n#include \"part3.hpp\"\n\nusing namespace std;\n\nvoid part3(){\n string str;\n ifstream ifile;// declaring an object of class ifstream\n ifile.open(\"/Users/msingh9001/Desktop/COEN_179/Lab_1/Lab_1/GettysburgAddress.txt\");// open file for reading\n cout <<\"Reading data from a file :-\" << endl;\n \n while(!ifile.eof() && ifile >> str){// while the end of file [ eof() ] is not reached\n for(int i = 0; i < str.length(); i++){\n if(!isalnum(str[i]))\n str.erase(str.begin() + i);\n }\n if(str.length() > 9){\n for(int k = 0; k < str.length(); k++){\n printf(\"%c\", toupper(str[k]));\n }\n cout << \"\\n\" << endl;\n }\n }\n ifile.close();// close the file\n}\n" } ]
175
jeremyherbert/barbutils
https://github.com/jeremyherbert/barbutils
7a61d6371b653c2272121b38b0980170b9199f43
73cf07b2c8c53199103d13dca5efe09f9e4bdbaf
9e61f5e6043a5bacc26889b94817eb13c8915788
refs/heads/master
2020-12-13T04:10:35.820628
2020-01-16T12:03:53
2020-01-16T12:03:53
234,310,279
1
2
null
null
null
null
null
[ { "alpha_fraction": 0.571494460105896, "alphanum_fraction": 0.6328413486480713, "avg_line_length": 30.434782028198242, "blob_id": "fd189336069a4931616510f53f2d402e51b099c6", "content_id": "59f8612ab2bede33732e5a8125ec6c7e218d50a0", "detected_licenses": [ "MIT", "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2168, "license_type": "permissive", "max_line_length": 120, "num_lines": 69, "path": "/barbutils.py", "repo_name": "jeremyherbert/barbutils", "src_encoding": "UTF-8", "text": "# SPDX-License-Identifier: MIT\n\nimport struct\nimport numpy as np\n\nfrom typing import Union\n\n\ndef compute_barb_checksum(header: bytes) -> bytes:\n tmp = sum(struct.unpack(\"b\" * 56, header[:56]))\n return struct.pack(\"<i\", tmp)\n\n\ndef load_barb(payload: bytes):\n if len(payload) < 61:\n raise ValueError(\"payload is too short\")\n\n header = payload[:56]\n checksum = payload[56:60]\n waveform_data = payload[60:]\n\n if compute_barb_checksum(header) != checksum:\n raise ValueError(\"incorrect checksum\")\n\n sample_rate = struct.unpack(\"<d\", header[0x08:0x08+8])[0]\n maximum_voltage = struct.unpack(\"<f\", header[0x14:0x14+4])[0]\n minimum_voltage = struct.unpack(\"<f\", header[0x18:0x18+4])[0]\n\n scale_voltage = np.max([np.abs(maximum_voltage), np.abs(minimum_voltage)])\n\n normalised_waveform_data = scale_voltage * np.array([x[0] for x in struct.iter_unpack(\"<h\", waveform_data)]) / 2**15\n\n return sample_rate, normalised_waveform_data\n\n\ndef generate_barb(data: Union[np.array, list], sample_rate: float) -> bytes:\n if sample_rate < 10 or sample_rate > 1e9:\n raise ValueError(\"sample_rate must be between 10Hz and 1GHz\")\n\n if np.max(data) > 10 or np.min(data) < -10:\n raise ValueError(\"all elements of data must be between -10 and 10\")\n\n if len(data) == 0:\n raise ValueError(\"data is empty\")\n\n header = b\"\\x01\\x00\\x00\\x00\"\n header += b\"\\x04\\x00\\x00\\x00\"\n header += struct.pack(\"<d\", sample_rate)\n header += b\"\\xCD\\xCC\\x8C\\x3F\"\n header += struct.pack(\"<ff\", np.max(data), np.min(data))\n header += b\"\\x00\\x00\\x00\\x00\"\n header += b\"\\x16\\x00\\x00\\x00\"\n header += b\"\\x00\\x00\\x00\\x00\"\n header += b\"\\x00\\x00\\x00\\x00\"\n header += b\"\\x00\\x00\\x00\\x00\"\n header += struct.pack(\"<I\", len(data))\n header += b\"\\x00\\x00\\x00\\x00\"\n header += compute_barb_checksum(header)\n\n tmp_data = np.array(data, dtype=np.float64)\n tmp_data /= np.max(np.abs(tmp_data)*2)\n normalised_data = tmp_data\n scaled_data = np.array(normalised_data * (2**16 - 1), dtype=np.int16)\n\n payload = b\"\"\n for i in scaled_data:\n payload += struct.pack(\"<h\", i)\n\n return header + payload" }, { "alpha_fraction": 0.6138613820075989, "alphanum_fraction": 0.7143945097923279, "avg_line_length": 53.70833206176758, "blob_id": "a79ceaa026e465a41d158e92519c863de35eac27", "content_id": "64fd77562789f87360e0f56a19bd2eceb867dc69", "detected_licenses": [ "MIT", "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1313, "license_type": "permissive", "max_line_length": 255, "num_lines": 24, "path": "/README.md", "repo_name": "jeremyherbert/barbutils", "src_encoding": "UTF-8", "text": "# barbutils\n\nBARB files are binary arbitrary waveform files used by Agilent/Keysight waveform generators (also known as \"function generators\"). Files generated with this python script have been tested on a 33600-series generator. Script requires python 3.6+ and numpy.\n\nWarning: You likely can generate files which will be outside of the usable range of your device (for example, a sample rate too high). Use at your own risk.\n\n---\n\n### File structure\n\nAll multi-byte numbers are little-endian (LSB first).\n\nOffset | Length (bytes) | Type | Description\n--- | --- | --- | ---\n0x00 | 8 | ? | 01 00 00 00 <br> 04 00 00 00\n0x08 | 8 | IEEE754 double precision float | Sample rate in samples/sec\n0x10 | 4 | ? | CD CC 8C 3F\n0x14 | 4 | IEEE754 single precision float | Maximum voltage\n0x18 | 4 | IEEE754 single precision float | Minimum voltage\n0x1C | 24 | ? | 00 00 00 00 <br> 16 00 00 00 <br> 00 00 00 00 <br> 00 00 00 00 <br> 00 00 00 00\n0x30 | 4 | uint32 | Number of points in the waveform\n0x34 | 4 | ? | 00 00 00 00\n0x38 | 4 | int32 | For each byte in the first 56 bytes of the header, convert it to int8_t, then convert to int32_t, then add them all together \n0x3C | Number of waveform points * 2 | Array of int16 | Waveform points. All points are scaled relative to max(abs(maximum voltage), abs(minimum voltage))\n" }, { "alpha_fraction": 0.6907216310501099, "alphanum_fraction": 0.7036082744598389, "avg_line_length": 34.227272033691406, "blob_id": "8aae7a7803857457c08bc6e756459a3687d8f1ad", "content_id": "bba7e1bef0674b280744e7633802af7eb02c4311", "detected_licenses": [ "MIT", "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 776, "license_type": "permissive", "max_line_length": 77, "num_lines": 22, "path": "/tests.py", "repo_name": "jeremyherbert/barbutils", "src_encoding": "UTF-8", "text": "# SPDX-License-Identifier: MIT\n\nimport os\nfrom fixtures.testdata import barb_fixtures\nfrom barbutils import generate_barb, load_barb\nimport numpy as np\n\nscript_path = os.path.dirname(os.path.realpath(__file__))\n\nfor key in barb_fixtures.keys():\n generated = generate_barb(barb_fixtures[key][0], barb_fixtures[key][1])\n\n with open(os.path.join(script_path, \"fixtures\", key), \"rb\") as f:\n fixture = f.read()\n\n sample_rate, data = load_barb(fixture)\n assert sample_rate == barb_fixtures[key][1]\n np.testing.assert_allclose(data, barb_fixtures[key][0], rtol=1e-3)\n\n loaded_sample_rate, loaded_data = load_barb(generated)\n assert loaded_sample_rate == barb_fixtures[key][1]\n np.testing.assert_allclose(loaded_data, barb_fixtures[key][0], rtol=1e-3)\n\n" } ]
3
bamkannan/parsivel_disdrometer
https://github.com/bamkannan/parsivel_disdrometer
a7335658bd356d9d029a01657fa7179d82e83ed4
11742eb8d0150966f895bc0a1f4846f850849e1d
a7a2393a88513da72629394256d8ce3da65f08eb
refs/heads/master
2022-12-26T11:02:19.820390
2020-10-14T21:58:51
2020-10-14T21:58:51
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4743298590183258, "alphanum_fraction": 0.5102226138114929, "avg_line_length": 35.081966400146484, "blob_id": "4ece602f611467b17dec3a0bc45a6c148b0d1a5b", "content_id": "bc95674282beb5571389adc1cce30ffc108ac289", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4402, "license_type": "no_license", "max_line_length": 110, "num_lines": 122, "path": "/src/parsivel.py", "repo_name": "bamkannan/parsivel_disdrometer", "src_encoding": "UTF-8", "text": "import glob\nfrom netCDF4 import Dataset, num2date\nimport collections\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\n\n\ndef calc_nd(sr_event, size, dsize=.125, dt=60):\n area = (180 * (30 - (size / 2))) * 10 ** -6\n ND = 0\n for speed in sr_event.index:\n if pd.notnull(sr_event.loc[speed]):\n ND += sr_event.loc[speed] / (speed * area * dt * dsize)\n return ND\n\n\ndef lermithe(D):\n return 9.24*(1.-np.exp(-6.8 * (D/10.) ** 2 - 4.88 * (D/10.)))\n\n\ndef lina_filter(sizes, vels, tresh=2):\n filtered = []\n for idx, i in enumerate(sizes):\n lina_vel_up = lermithe(np.array(i)) + tresh\n lina_vel_down = lermithe(np.array(i)) - tresh\n fil = np.ma.masked_where(vels >= lina_vel_up, vels)\n fil = np.ma.masked_where(fil <= lina_vel_down, fil)\n filtered.append(np.ma.getmaskarray(fil))\n return np.array(filtered)\n\n\ndef paleta():\n cdict = {'red': ((0., 1, 1),\n (0.05, 1, 1),\n (0.11, 0, 0),\n (0.66, 1, 1),\n (0.89, 1, 1),\n (1, 0.5, 0.5)),\n 'green': ((0., 1, 1),\n (0.05, 1, 1),\n (0.11, 0, 0),\n (0.375, 1, 1),\n (0.64, 1, 1),\n (0.91, 0, 0),\n (1, 0, 0)),\n 'blue': ((0., 1, 1),\n (0.05, 1, 1),\n (0.11, 1, 1),\n (0.34, 1, 1),\n (0.65, 0, 0),\n (1, 0, 0))}\n\n return matplotlib.colors.LinearSegmentedColormap('my_colormap', cdict, 256)\n\n\ndef parsivel_2(file):\n nc = Dataset(file, 'r')\n sizes = [round(x, 4) for x in nc.variables['particle_size'][:]]\n d_sizes = [round(x, 4) for x in nc.variables['class_size_width'][:]]\n dt_sizes = dict(zip(sizes, d_sizes))\n vels = [round(x, 4) for x in nc.variables['raw_fall_velocity'][:]]\n lerm_vel = [round(x, 4) for x in nc.variables['fall_velocity_calculated'][:]]\n list_size = collections.OrderedDict(sorted(dt_sizes.items()))\n\n idx_header = pd.MultiIndex.from_product([sizes, vels], names=['Size', 'Speed'])\n times = []\n data_spec = []\n # Tokay filter for rainy minutes\n events = [i for i, e in enumerate(nc.variables['number_detected_particles']) if (e > 100) and\n (nc.variables['precip_rate'][i] > 0.5)]\n spectra_filter = lina_filter(sizes=sizes, vels=vels, tresh=2)\n\n for i in events:\n dates = nc.variables['time'][i]\n time = num2date(dates, nc.variables['time'].units)\n times.append(time)\n spectrum = np.array(nc.variables['raw_spectrum'][i][:])\n spectrum = np.ma.masked_array(spectrum, mask=spectra_filter.T, fill_value=0)\n spectrum = spectrum.filled()\n # plt.pcolormesh(sizes, vels, spectrum, cmap=paleta())\n # plt.plot(sizes, lermithe(np.array(sizes)))\n # plt.plot(sizes, lermithe(np.array(sizes)) + 2.1, 'r')\n # plt.plot(sizes, lermithe(np.array(sizes)) - 2.1, 'r')\n # plt.plot(sizes, lermithe(np.array(sizes)) + lermithe(np.array(sizes)) * 0.4, 'c')\n # plt.plot(sizes, lermithe(np.array(sizes)) - lermithe(np.array(sizes)) * 0.4, 'c')\n # plt.ylim([0, 10])\n # plt.xlim([0, 10])\n # plt.show()\n spectrum = np.ndarray.flatten(spectrum)\n data_spec.append(spectrum)\n\n dsd_data_final = pd.DataFrame(data=data_spec, columns=pd.MultiIndex.from_product([sizes, vels],\n names=['Size', 'Speed']),\n index=times)\n\n for event_ext in dsd_data_final.index:\n sr_nd = pd.Series(index=sorted(list_size))\n for size in list_size:\n df_size = dsd_data_final.xs(size, level=0, axis=1)\n sr_event = df_size.loc[event_ext]\n dsize = list_size[size]\n\n nd = calc_nd(sr_event=sr_event, size=size, dsize=dsize)\n sr_nd.loc[size] = nd\n fig, ax = plt.subplots()\n ax.scatter(x=sr_nd.index, y=sr_nd, marker='*')\n ax.set_yscale('log')\n plt.ylim(10 ** -1, 10 ** 4)\n plt.show()\n plt.close('all')\n \n#comment Lina\n\ndef main():\n file = glob.glob('../data/*.cdf')\n parsivel_2(file[0])\n\n\nif __name__ == '__main__':\n main()\n" } ]
1
angellox/dfs_completely
https://github.com/angellox/dfs_completely
f687e2f8966a3fe7896710ecea30152cf603b932
4a1e1863a1334488b327dd7731267f249bdf53ff
5e81c62f9df20aa2d1124d19b3ca439c586d2d75
refs/heads/main
2023-03-27T17:48:46.612918
2021-04-01T17:57:55
2021-04-01T17:57:55
353,783,343
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7878788113594055, "alphanum_fraction": 0.7878788113594055, "avg_line_length": 48.5, "blob_id": "b231330bcf9eb717c2261f707b0cb5d74f68a7fd", "content_id": "e4010e01a256b239d596a0c97da5c3c050404d70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 99, "license_type": "no_license", "max_line_length": 81, "num_lines": 2, "path": "/README.md", "repo_name": "angellox/dfs_completely", "src_encoding": "UTF-8", "text": "# dfs_completely\nAlgorithm of DFS with condictions: euclidean distance &amp; id greater, id fewer.\n" }, { "alpha_fraction": 0.603253185749054, "alphanum_fraction": 0.6140971183776855, "avg_line_length": 35.568965911865234, "blob_id": "e434f7a3d0f4a588f612a8c829c48f812cdfe6ee", "content_id": "aae20776da0f7df8a677ef7b3f125caa6212499f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4245, "license_type": "no_license", "max_line_length": 162, "num_lines": 116, "path": "/dfs_algorithm.py", "repo_name": "angellox/dfs_completely", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'Ángel Cruz'\n\nimport ast, resource,operator, sys\nfrom scipy.spatial import distance\nfrom collections import defaultdict\n\nsys.setrecursionlimit(10 ** 6)\n#GLOBALS\nleaf = []\nchildren = defaultdict(list)\n#FUNCTION DOES THE READING OF THE FILE.\ndef readFile(archivo):\n f = open(archivo)\n return f.readlines()\n\ndef createGraph(preGraph, Graph):\n current = [ 0, (0, 0) ] #[NODE'S ID, (X,Y)]\n while current[0] != len(preGraph):\n neighbors = []\n #preNeighbors={} #LINEA agregada PARA EVALUAR POR DISTANCIA\n current = preGraph.pop(0) #NODE'S ID\n Graph[current[0]] = neighbors\n for element in preGraph:\n if distance.euclidean(current[1], element[1]) < 100:\n #preNeighbors[element[0]]=distance.euclidean(current[1], element[1]) #LINEA agregada PARA EVALUAR POR DITANCIA\n neighbors.append( element[0] ) #se debe comentar para evaluar por ditancia\n neighbors.sort(reverse = False) #FALSE BY MIN, AND TRUE BY MAX. #se debe comentar para evaluar por ditancia\n #vecinos_sort = sorted(preNeighbors.items(), key=operator.itemgetter(1), reverse=False) #true-by max, false-by min LINEA agregada PARA EVALUAR POR DITANCIA\n #for vecinitos in vecinos_sort: #LINEA agregada PARA EVALUAR POR DITANCIA\n #neighbors.append(int(vecinitos[0])) #LINEA agregada PARA EVALUAR POR DITANCIA\n\n preGraph.append(current)\n \n return Graph\n\n\n#stack [2,4] | visited [1,3,5,6,4,2] | current = 4\ndef dfs(Graph_Ready, visited, n):\n global leaf, children\n flag = 1\n Graph = Graph_Ready\n neighborsList = list(Graph_Ready.values())\n visited.add(n)\n\n print(n, end='-> ')\n\n for neighbour in neighborsList[n - 1]: #[2,3]\n if neighbour not in visited:\n children[n].append(neighbour)\n flag = 0\n dfs( Graph, visited, neighbour )\n\n if ( flag == 1 ):\n leaf.append(n)\n print(\"\\n\")\n\ndef FindMaxChildren(children):\n nodes_deadheat = [] # ALMACENA A LOS NODOS QUE ENCUENTRA EN CASO DE EMPATE.\n key_list = list(children.keys()) #NODES\n lst = list(children.values()) #NEIGHBOURS\n maxList = max(lst, key = len)\n #print(len(maxList))\n for element in lst:\n if len(maxList) == len(element):\n position = lst.index(element)\n node = key_list[position]\n nodes_deadheat.append(node)\n print('Node: ', node, '| Numbers of children: ', len(maxList), '| Children: ', element)\n\n #print(nodes_deadheat)\n if nodes_deadheat: #EN CASO DE EMPATE.\n node_max = max(nodes_deadheat) #IMPRIMIMOS NODO MÁXIMO.\n node_min = min(nodes_deadheat) #IMPRIMIMOS NODO MÍN.\n print('\\nNode Max: ', node_max, '| Node Min: ', node_min)\n else:\n print('Node: ', key_list[lst.index(maxList)] , '| Numbers of children: ', len(maxList), '| Children: ', maxList)\n\n\ndef amountOfNodes(children):\n nodes_amount = [] # ALMACENA A LOS NODOS QUE TIENEN MÁS DE 1 HIJO.\n key_list = list(children.keys()) #NODES\n lst = list(children.values()) #NEIGHBOURS\n\n for element in lst:\n if len(element) >= 2:\n position = lst.index(element)\n node = key_list[position]\n nodes_amount.append(node)\n\n print(\"Amount of nodes with more than 1 child: \", len(nodes_amount))\n\nif __name__ == '__main__':\n file_ready = readFile('Network11.txt')\n preGraph = []\n Graph = {}\n visited = set()\n\n for line in file_ready:\n idNode = int(line.split(\":\")[0]) #BY OBTAINING NODE'S ID.\n coordinates = ast.literal_eval(line.split(\":\")[1].rstrip()) #BY OBTAINING NODE'S ID.\n items = [idNode, coordinates]\n preGraph.append(items)\n\n Graph_Ready = createGraph(preGraph, Graph)\n print(\"Graph Created: \",Graph_Ready, \"\\n\")\n print(\"---THE ROUTE GETS BY DFS IS: ---\\n\")\n dfs(Graph_Ready, visited, 291) #(graph, visited, root_to_start)\n print(\"\\n----------------------------------------------\\n\")\n print(\"Container Leaves: \", leaf)\n print(\"Leaves' Number: \", len( leaf ))\n print(\"\\n\")\n print('Nodes with their children: ' + str(dict(children)))\n print(\"\\n\")\n FindMaxChildren(children)\n amountOfNodes(children)\n" } ]
2
reeshabhranjan/Shortest-path-algorithm
https://github.com/reeshabhranjan/Shortest-path-algorithm
c2f519a22a2dcdc0023d2fba9482ed9c6238b123
9d1bd3a78203709cd52704e9341abbf23bfab116
57f0e5b053531fca3cc34b0920398d536818a945
refs/heads/master
2021-07-21T17:29:21.496092
2017-10-31T12:14:53
2017-10-31T12:14:53
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5898311138153076, "alphanum_fraction": 0.5964786410331726, "avg_line_length": 18.741134643554688, "blob_id": "9414d94f6aef7e99ee85d33d1fce55e371945a0c", "content_id": "d4a6dfda1aa6463540201bc582173f4d0dfff537", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5566, "license_type": "no_license", "max_line_length": 129, "num_lines": 282, "path": "/main_file.py", "repo_name": "reeshabhranjan/Shortest-path-algorithm", "src_encoding": "UTF-8", "text": "###############################################################################################################\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n# \t NAME: REESHABH KUMAR RANJAN\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t #\n# \t ROLL NUMBER: 2017086\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \t #\n# \t\t\t\t\t\t\t\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t #\n# \t\t \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n###############################################################################################################\n\n\n\nfrom sys import maxsize as infinity\nundefined=-1\n\ndef input_elements():\n\n\t\"\"\"\n\n\tPrecondition: Please enter positive weights.\n\n\tFunction to input elements. It processes the input and assigns them to proper lists, namely masterNodeList and masterWeightList.\n\tIt returns both.\n\n\t\"\"\"\n\n\tn=int(input())\n\t\n\tnext_jump=[0]\n\ttracked=[0]\n\n\tmasterNodeList=[]\n\tmasterWeightList=[]\n\n\twhile len(next_jump)>0:\n\n\t\tt=int(input())\n\t\t\n\t\trawNodeInput=[]\n\t\trawWeightInput=[]\n\n\t\tfor i in range(t):\n\t\t\t\n\t\t\ttemp=input()\n\t\t\trawInput=[int(j) for j in temp.split()]\n\n\t\t\trawNodeInput.append(rawInput[0])\n\t\t\trawWeightInput.append(rawInput[1])\n\n\t\tfor i in rawNodeInput:\n\t\t\t\n\t\t\tif distinct(i,tracked):\n\t\t\t\ttracked.append(i)\n\t\t\t\tnext_jump.append(i)\n\n\t\tnext_jump.pop(0)\t\n\t\tmasterNodeList.append(rawNodeInput)\n\t\tmasterWeightList.append(rawWeightInput)\n\n\tsource=int(input(\"\\nNow enter source: \"))\n\n\tprint()\n\tprint(\"___________________________________\")\n\tprint(\"Entered information:\")\n\tprint(\"Number of nodes:\",n)\n\tprint(\"Source:\",source)\n\tprint(\"Connections:\",masterNodeList)\n\tprint(\"weights:\",masterWeightList)\n\tprint(\"___________________________________\")\n\tprint()\n\n\tchoice=input(\"Want to start inputting all over again? (y for 'yes', otherwise 'no')\")\n\n\tif choice=='y':\n\t\tn,source,masterNodeList,masterWeightList=input_elements()\n\n\treturn n,source,masterNodeList,masterWeightList\n\ndef find_min(x):\n\n\t\"\"\"\n\n\tPrecondition: x is a list\n\n\tFinds the minimum value in a given list.\n\n\t\"\"\"\n\n\tminimum=infinity\n\tfor i in x:\n\t\tif i<minimum:\n\t\t\tminimum=i\n\n\treturn minimum\n\ndef empty_list(x):\n\n\t\"\"\"\n\n\tPreconditions: x is a list\n\n\tChecks if all the values in x are popped or not.\n\tIf yes, then it returns True, otherwise False.\n\n\t\"\"\"\n\n\tglobal infinity\n\tglobal undefined\n\n\tcondition=True\n\tfor i in x:\n\t\tif i!=\"popped\":\n\t\t\tcondition=False\n\t\t\treturn condition\n\treturn condition\n\ndef distinct(a,b): # to check if a is in b or not\n\t\n\t\"\"\"\n\n\tPreconditions: b is a list\n\n\tChecks the presence of an element a in the list b.\n\tIt returns True if a is absent in b, otherwise returns False (that a is already present in b)\n\n\t\"\"\"\n\n\tglobal infinity\n\tglobal undefined\n\n\tif a not in b:\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef dijkstra(n,source,connections,weights):\n\n\t\"\"\"\n\n\tPreconditions: \tn is a whole number\n\t\t\tsource is an integer\n\t\t\tconnections is nested list\n\t\t\tweights is nested list\n\t\t\tconnections and weights should have same dimensions\n\t\t\tweights are positive\n\n\tThis functions calculates distances as per the Dijkstra algorithm and returns the list of calculated distances.\n\n\t\"\"\"\n\t\n\tQ=[]\n\tdist=[]\n\n\tfor i in range(n):\n\t\tQ.append(i)\n\t\tdist.append(infinity)\n\n\tfor i in range(len(Q)):\n\t\tif Q[i]==source:\n\t\t\tdist[i]=0\n\n\tsequence=Q[:]\n\t\n\tprev=[-1]\n\tvisited=[]\n\n\tdist2=dist[:]\n\n\twhile not empty_list(Q):\n\n\t\tindex=dist.index(find_min(dist))\n\n\t\tif index>len(connections)-1:\n\t\t\tdist2[index]=dist[index]\n\t\t\tQ[index]=\"popped\"\n\t\t\tdist[index]=infinity+1\n\t\t\tbreak\n\n\n\t\tchild=connections[index]\n\n\t\tfor j in range(len(child)):\n\n\t\t\t\tpossible_dist=dist2[index]+weights[index][j]\n\t\t\t\t\n\t\t\t\tcurrent_value=child[j]\n\t\t\t\tcurrent_index=sequence.index(current_value)\n\t\t\t\tcurrent_dist=dist2[current_index]\n\n\t\t\t\tif possible_dist<current_dist:\n\t\t\t\t\tdist[current_index]=possible_dist\n\t\t\t\t\tdist2[current_index]=possible_dist\t\t\t\t\t\n\n\t\tQ[index]=\"popped\"\n\t\tdist[index]=infinity+1\n\n\tfor i in range(len(dist2)):\n\t\tif dist2[i]>=infinity:\n\t\t\tdist2[i]=\"infinity\"\n\n\tif __name__ == '__main__':\n\t\tprint(\"Nodes:\",sequence)\n\telse:\n\t\tprint(\"\\t\\tNodes:\",sequence)\n\n\treturn dist2\n\ndef bfs(n,source,connections,weights):\n\n\t\"\"\"\n\n\tPreconditions: \tn is a whole number\n\t\t\tsource is an integer\n\t\t\tconnections is nested list\n\t\t\tweights is nested list\n\t\t\tconnections and weights should have same dimensions\n\t\t\tweights are positive\n\n\tThis functions calculates distances as per the BFS algorithm and returns the list of calculated distances.\n\n\t\"\"\"\n\n\tQ=[source]\n\tvisited=[source]\n\n\tsequence=[]\n\tdist=[]\n\n\tfor i in range(n):\n\t\tsequence.append(i)\n\t\tdist.append(infinity)\n\n\tfor i in range(len(sequence)):\n\t\tif sequence[i]==source:\n\t\t\tdist[i]=0\n\n\twhile(len(Q)>0):\n\t\tjump=sequence.index(Q[0])\n\n\t\tif jump>len(connections)-1:\n\t\t\tQ.remove(Q[0])\n\t\t\tbreak\n\n\t\tfor x in connections[jump]:\n\n\n\t\t\tif distinct(x,visited):\n\t\t\t\tQ.append(x)\n\t\t\t\tvisited.append(x)\n\n\t\t\t\tcurr_index=connections[jump].index(x)\n\t\t\t\tcurr_index2=sequence.index(x)\n\t\t\t\tcurrent_distance=dist[curr_index2]\n\t\t\t\tpossible_distance=dist[jump]+weights[jump][curr_index]\n\n\t\t\t\tif possible_distance<current_distance:\n\t\t\t\t\tdist[curr_index2]=possible_distance\n\n\t\tQ.remove(Q[0])\n\n\tfor i in range(len(dist)):\n\t\tif dist[i]>=infinity:\n\t\t\tdist[i]=\"infinity\"\n\n\tif __name__ == '__main__':\n\t\tprint(\"Nodes:\",sequence)\n\telse:\n\t\tprint(\"\\t\\tNodes:\",sequence)\n\t\t\n\treturn dist\n\nif __name__ == '__main__':\n\n\tn,source,connections,weights=input_elements()\n\n\tprint(\"Dijkstra:\",dijkstra(n,source,connections,weights))\n\tprint(\"BFS\",bfs(n,source,connections,weights))" } ]
1
RCdiy/Python-Web-Scrapers
https://github.com/RCdiy/Python-Web-Scrapers
cfb91628e9949ebd6a5570865058c06e5dab312a
54fda03bcb12f8bf9b87bf24ffc6d2e5578177bc
69958456be36565946a0ab75846a5238a72e8398
refs/heads/main
2023-02-23T02:41:16.038440
2021-01-19T22:05:18
2021-01-19T22:05:18
331,074,283
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5931592583656311, "alphanum_fraction": 0.6213883757591248, "avg_line_length": 32.12565612792969, "blob_id": "a0c4bb13816e58c81b3ad84fe8cfd46bfdd3452d", "content_id": "38dc50f9549116dec7dc79b78caa9a360ba0e136", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31634, "license_type": "no_license", "max_line_length": 147, "num_lines": 955, "path": "/modules/web_scrapers.py", "repo_name": "RCdiy/Python-Web-Scrapers", "src_encoding": "UTF-8", "text": "class _print:\n\tdef __init__(self):\n\t\tpass\n\n\tdef _abc(dictionary,indent=''):\n\t\t\tprint(indent,type(dictionary), end='')\n\t\t\tfor key in dictionary:\n\t\t\t\tspace = indent + ' '\n\t\t\t\tprint('\\n',space, key, end='')\n\t\t\t\tspace += ' '\n\t\t\t\tif type(dictionary[key]) == dict:\n\t\t\t\t\t_print._abc(dictionary=dictionary[key],indent=space)\n\t\t\t\telse:\n\t\t\t\t\tprint('\\n', space, dictionary[key])\n\t\n\n\n\tdef _indented(*args,indent=''):\n\t\tprint('web_scrapers', end='')\n\t\tspace = indent + ' '\n\t\tfor arg in args:\n\t\t\tspace = space + ' '\n\t\t\tif type(arg) == dict:\n\t\t\t\t_print._abc(dictionary=arg,indent=space)\n\t\t\telse:\n\t\t\t\tprint(':\\n',space, arg, end='')\n\t\tprint('\\n')\n\t\t\t# if type(message) == dict:\n\t\t\t# \tprint()\n\t\t\t# \tself._dictionary(message, indent=space)\n\t\t\t# else:\n\t\t\t# \tprint(':\\n',indent, message, end='')\n\n\nclass timer:\n\t\"\"\"\n\tA timer that can be used to determin elapsed time.\n\t\ttimer(duration_seconds:float)\n\n\t\tExample:\n\t\t\tfrom modules.web_scrapers import timer\n\t\t\tx = timer(2)\n\t\t\tx.start()\n\t\t\tprint('Timer started :', x.started())\n\t\t\tx.wait(1)\n\t\t\tprint('Time elapsed: ', x.elapsed())\n\t\t\tprint('Time remaining: ', x.remaining())\n\t\t\tprint('The timer is done (maybe):', x.done())\n\t\t\tprint('Waiting till done.')\n\t\t\tx.wait_till_done()\n\t\t\tprint('Timer done:', x.done())\n\n\t\t\timport modules.web_scrapers as scrapers\n\t\t\tx = scrapers.timer(2)\n\t\"\"\"\n\tfrom datetime import datetime\n\tfrom datetime import timezone\n\tfrom time import sleep\n\t_utc = timezone.utc\n\t_timer = datetime\n\t\n\tdef __init__(self, duration_seconds:float):\n\t\tself._timer_start_time = None\n\t\tself.duration_seconds = duration_seconds\n\n\tdef current_time(self) -> datetime:\n\t\t\"\"\"\n\t\tReturns the current time as a datetime object.\n\t\t\"\"\"\n\t\treturn self._timer.now(self._utc)\n\n\tdef current_time_posix(self) -> float:\n\t\t\"\"\"\n\t\tReturns the current POSIX time seconds.\n\t\t\"\"\"\n\t\treturn self.current_time().timestamp()\n\n\tdef current_time_iso(self) -> str:\n\t\t\"\"\"\n\t\tReturns the current time is ISO format.\n\t\t2021-00-11-14:30-05:00\n\t\t\"\"\"\n\t\treturn self.current_time().replace(microsecond=0).isoformat(' ')\n\n\tdef start_time(self) -> datetime:\n\t\t\"\"\"\n\t\tReturns the timer start time as a datetime object.\n\t\t\"\"\"\n\t\treturn self.timer_start_time\n\n\tdef start_time_posix(self) -> float:\n\t\t\"\"\"\n\t\tReturns the timer start time in POSIX time seconds.\n\t\t\"\"\"\n\t\treturn self.start_time().timestamp()\n\n\tdef start_time_iso(self) -> str:\n\t\t\"\"\"\n\t\tReturns the timer start time in an ISO format.\n\t\t2021-00-11-14:30-05:00\n\t\t\"\"\"\n\t\treturn self.start_time().replace(microsecond=0).isoformat(' ')\n\n\tdef started(self) -> bool:\n\t\t\"\"\"\n\t\tReturns True or False. True is start has been called.\n\t\t\"\"\"\n\t\tif self.start_time() == None:\n\t\t\treturn False\n\t\treturn True\n\n\tdef start(self, duration_seconds:float=None) -> None:\n\t\t\"\"\"\n\t\tSets the timer to zero.\n\t\t\"\"\"\n\t\tself.timer_start_time = self.current_time()\n\t\tif duration_seconds != None:\n\t\t\tself.duration_seconds = duration_seconds\n\t\tif self.duration_seconds == None:\n\t\t\t_print._indented( 'class timer', 'start()','Warning: A count down duration has not been set.')\n\n\tdef elapsed_seconds(self) -> float:\n\t\t\"\"\"\n\t\tSeconds since last reset.\n\t\t\"\"\"\n\t\treturn self.current_time_posix() - self.start_time_posix()\n\n\tdef remaining_seconds(self) -> float:\n\t\t\"\"\"\n\t\tSeconds remaining. A negative number is seconds past timer end.\n\t\t\"\"\"\n\t\treturn self.duration_seconds - self.elapsed_seconds()\n\n\tdef wait(self, seconds:float) -> None:\n\t\t\"\"\"\n\t\tWaits the duration provided.\n\t\t\"\"\"\n\t\tself.sleep(seconds)\n\n\tdef wait_till_done(self) -> None:\n\t\t\"\"\"\n\t\tWaits till the count down reaches zero.\n\t\t\"\"\"\n\t\tself.wait(self.remaining_seconds())\n\n\tdef check_done(self) -> bool:\n\t\t\"\"\"\n\t\tChecks if the count down has reached zero.\n\t\t\"\"\"\n\t\tif self.remaining_seconds() > 0:\n\t\t\treturn False\n\t\telse:\n\t\t\tself.started_utc_now = None\n\t\t\treturn True\n\n\nclass _web:\n\timport requests\n\tdef __init__(self, random_headers:bool=True, time_out:tuple=(10,10), url_update_interval:float=60):\n\t\t\"\"\"\n\t\tTime out (x,y):\n\t\t\tx - seconds to wait for a response.\n\t\t\ty - seconds to wait for the content.\n\t\t\"\"\"\n\t\tself.use_random_headers = random_headers\n\t\tself.time_out = time_out\n\t\tself.url_update_interval = url_update_interval\n\t\tself.urltimers = {}\n\n\t\tself.timer = timer(url_update_interval)\n\n\t\tself.previous_user_agent_index = 0\n\t\tself.user_agents = [\n\t\t\t\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.2 Safari/605.1.15\",\n\t\t\t\"Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.2 Mobile/15E148 Safari/604.1\",\n\t\t\t\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36\",\n\t\t\t\"Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/87.0.4280.77 Mobile/15E148 Safari/604.1\",\n\t\t\t\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134\",\n\t\t\t\"Mozilla/5.0 (X11; CrOS x86_64 13310.93.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.133 Safari/537.36\",\n\t\t\t]\n\t\tself.header = {\n\t\t\t\"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n\t\t\t\"Accept-Encoding\": \"gzip, deflate\",\n\t\t\t\"Accept-Language\": \"en-ca\",\n\t\t\t\"Upgrade-Insecure-Requests\": \"1\",\n\t\t\t\"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.2 Safari/605.1.15\"\n\t\t\t}\n\n\tdef _get_random_user_agent(self) -> str:\n\t\t\"\"\"\n\t\tReturns a random user agent.\n\t\t\"\"\"\n\t\tnum = self.timer.current_time_posix()\n\t\tnum = int( ( num - int(num) ) * 10**6 )\n\n\t\tidx = num % len(self.user_agents)\n\t\tif idx == self.previous_user_agent_index :\n\t\t\tidx = (num + 1) % len(self.user_agents)\n\t\t\tself.previous_user_agent_index = idx\n\n\t\treturn self.user_agents[idx]\n\n\tdef _get_header(self) -> dict:\n\t\t\"\"\"\n\t\tReturns a header with a random user agent.\n\t\t\"\"\"\n\t\tif self.use_random_headers:\n\t\t\tself.header[\"User-Agent\"] = self._get_random_user_agent()\n\t\treturn self.header\n\n\tdef _get_website(self, url:str, header:dict=None) -> str:\n\t\t'''\n\t\tReturns the contents website.\n\t\tIf the url update interval has not been completed 'None' is returned.\n\t\t'''\n\t\t# Don't access website too often\n\t\tif self.urltimers.get(url) == None:\n\t\t\tself.urltimers[url] = timer(self.url_update_interval)\n\t\telse:\n\t\t\tif not self.urltimers[url].check_done():\n\t\t\t\t# _print._indented('class _web', '_get_website('+url+', '+str(type(header))+')', \n\t\t\t\t# \t'if not self.urltimers[url].check_done()')\n\t\t\t\treturn None\n\n\t\t# Asign header\n\t\tif header == None:\n\t\t\theader =self._get_header()\n\t\n\t\ttry:\n\t\t\twebsite = self.requests.get( url, timeout=self.time_out, headers=header)\n\t\texcept:\n\t\t\t_print._indented('class _web', '_get_website('+url+', '+type(header)+')', \n\t\t\t\t'website = self.requests.get('+url+', '+str(self.time_out)+','+type(header)+')')\n\t\t\treturn None\n\n\t\tif not website.ok:\n\t\t\t_print._indented('class _web', '_get_website('+url+', '+ str(type(header))+')','not website.ok',website.text[:200])\n\n\t\tself.urltimers[url].start()\n\n\t\treturn str(website.text)\n\n\nclass equity:\n\tfrom datetime import datetime\n\tfrom datetime import timezone\n\timport html\n\n\tclass market_watch:\n\t\t\"\"\"\n\t\tStock data scrapped from MarketWatch.\n\t\t\tmarket_watch(random_headers:bool=True, update_delay_seconds:int=60)\n\n\t\t\tValues:\n\t\t\t\tname : tesla inc.\n\t\t\t\tsymbol : tsla\n\t\t\t\tcurrency : usd\n\t\t\t\tprice : 702.00\n\t\t\t\tprice_change : 7.22\n\t\t\t\tprice_change_percent : 1.04%\n\t\t\t\tprice_time_iso : 2020-12-31-10:24-05:00\n\t\t\t\texchange : nasdaq\n\n\t\t\t\tparsely-tags : pagetype: quotes, us:tsla, stock, us: u.s.: nasdaq, nas, page-overview\n\t\t\t\tchartingsymbol : stock/us/xnas/tsla\n\t\t\t\tinstrumenttype : stock\n\t\t\t\texchangecountry : us\n\t\t\t\texchangeiso : xnas\n\n\t\t\tExample:\n\t\t\t\tfrom modules.web_scrapers import equity\n\t\t\t\tscraper = equity.market_watch(random_headers=True)\n\t\t\t\tstock = scraper.get_stock('aapl')\n\t\t\t\tfor key in stock:\n\t\t\t\t\tprint(key.ljust(20),' : ',stock[key])\n\t\t\t\tdel scraper\n\t\t\t\tdel stock\n\n\t\t\t\timport modules.web_scrapers as scrapers\n\t\t\t\tscraper = scrapers.equity.market_watch(random_headers=True)\n\t\t\t\tstock = scraper.get_stock('avst', 'uk')\n\t\t\t\tfor key in stock:\n\t\t\t\t\tprint(key.ljust(20),' : ',stock[key])\n\t\t\"\"\"\n\n\t\tdef __init__(self, random_headers:bool=True, update_delay_seconds:int=60):\n\t\t\t\"\"\"\n\t\t\tUse Market Watch to get stock information.\n\t\t\t\tWhen random_headers is True a header is chosen randomly and used with each website access.\n\n\t\t\t\tTo reduce load on the website server update_delay_seconds prevents access using the\n\t\t\t\tsame symbol if the specified number of seconds has not elapsed since the last access.\n\t\t\t\"\"\"\n\t\t\tweb = _web(random_headers=random_headers, url_update_interval=update_delay_seconds)\n\t\t\tself.get_website = web._get_website\n\n\t\t\tself.url = 'https://www.marketwatch.com/investing/stock/'\n\t\t\tself.stock_list = {}\n\n\t\tdef get_stock(self, symbol:str, country:str=None, header:dict=None) -> dict:\n\t\t\t\"\"\"\n\t\t\tGet the latest information on the stock symbol string.\n\t\t\t\tThe optional country code defaults to US.\n\t\t\t\t\tCA, AU, FR, DE, HK, IT, JP, NL, NZ, NO, ZA, ES, SE, CH, UK\n\n\t\t\t\tReturns a dictionatry with keys:\n\t\t\t\t\tparsely-tags, chartingsymbol, instrumenttype, exchangecountry, exchangeiso,\n\t\t\t\t\tquotetime, name, symbol, currency, price, price_change, price_change_percent,\n\t\t\t\t\tprice_time_iso, exchange\n\n\t\t\t\t\tOptional:\n\t\t\t\t\t\tUses the supplied browser header.\n\t\t\t\t\t\tIf a header is not provided then a random one gets used.\n\n\t\t\t\tExample:\n\t\t\t\t\tfrom modules.web_scrapers import equity\n\t\t\t\t\tscraper = equity.market_watch(random_headers=True)\n\t\t\t\t\tstock = scraper.get_stock('aapl')\n\t\t\t\t\tfor key in stock:\n\t\t\t\t\t\tprint(key.ljust(20),' : ',stock[key])\n\n\t\t\t\t\timport modules.web_scrapers as scrapers\n\t\t\t\t\tscraper = scrapers.equity.market_watch(random_headers=True)\n\t\t\t\"\"\"\n\t\t\tsymbol = symbol.casefold()\n\t\t\tif country != None:\n\t\t\t\tcountry = country.casefold()\n\t\t\tticker_symbol = symbol\n\n\t\t\turl = self.url + symbol\n\n\t\t\tif country != None:\n\t\t\t\turl= url + '?countrycode=' + country\n\n\n\t\t\t# Website text\n\t\t\thtml = self.get_website(url, header=header)\n\t\t\tif html == None:\n\t\t\t\tif self.stock_list[url] != None:\n\t\t\t\t\treturn self.stock_list[url]\n\t\t\t\telse:\n\t\t\t\t\t_print._indented('class equity', 'market_watch', 'get_stock(' + symbol + ', ' + country + ', ' + str(type(header)+')',\n\t\t\t\t\t'html = self.get_website(' + url + ',' + 'header=' + str(type(header)) + ').casefold()',\n\t\t\t\t\t'if html == None:') )\n\t\t\t\treturn None\n\t\t\thtml = html.casefold()\n\t\t\t# Start parsing\n\t\t\tdata_string = html[ html.find('<meta name=\\\"parsely-tags\\\"') : ]\n\t\t\tdata_string = data_string[ : data_string.find('<meta name=\\\"description\\\"') ]\n\n\t\t\tlines = data_string.split('<meta name=')\n\n\t\t\tstock = {}\n\t\t\tfor line in lines:\n\t\t\t\tif line != '':\n\t\t\t\t\tdata = line.split('\\\"')\n\t\t\t\t\tkey = data[1]\n\t\t\t\t\tvalue = data[3].replace('&#x9;', '') # remove the tab\n\t\t\t\t\tvalue = equity.html.unescape(value)\n\t\t\t\t\tstock[key] = value\n\n\t\t\t# Test we have the expected keys\n\t\t\tif stock.get('tickersymbol') == None:\n\t\t\t\t_print._indented('market_watch', str('get_stock(' + symbol + ', ' + country + ', ' + str(type(header)) + ')'), \n\t\t\t\t'stock.get(\\'tickersymbol\\') == None' )\n\t\t\t\treturn None\n\t\t\telif stock['tickersymbol'] != symbol:\n\t\t\t\t_print._indented('market_watch', str('get_stock(' + symbol + ', ' + country + ', ' + str(type(header)) + ')'), \n\t\t\t\t\t'elif stock[\\'tickersymbol\\'] = ' + stock['tickersymbol'] + '!= '+symbol)\n\t\t\t\treturn None\n\n\t\t\t# Price\n\t\t\t# Stock price with only digits and a period\n\t\t\tprice =stock.pop('price')\n\t\t\ttry:\n\t\t\t\tx = float(price)\n\t\t\texcept:\n\t\t\t\tfor c in range(0,len(price)):\n\t\t\t\t\tif not price[0].isdigit():\n\t\t\t\t\t\tprice = price[1:]\n\t\t\t\t\tif not price[-1].isdigit():\n\t\t\t\t\t\tprice = price[:-1]\n\t\t\t\tprice = price.replace(',','')\n\t\t\t\n\t\t\t# ISO Date Time Format\n\t\t\t# From:\n\t\t\t# \tjan 12, 2021 4:35 p.m. gmt\n\t\t\t# \t(utc+00:00) dublin, edinburgh, lisbon, london\n\t\t\t# To:\n\t\t\t# \t2021-01-12-16:35-05:00\n\t\t\ttz = stock.pop('exchangetimezone')\n\t\t\ttz = tz.split('(')[1].split(')')[0][-6:]\n\n\t\t\tqt = stock['quotetime']\n\t\t\tqt = qt[:qt.find('.m.')] + 'm '\n\t\t\tqt = qt + tz\n\n\t\t\ttime_iso = equity.datetime.strptime(qt, '%b %d, %Y %I:%M %p %z')\n\t\t\ttime_iso = str(time_iso.replace(microsecond=0).astimezone(equity.timezone.utc).isoformat(' '))\n\n\t\t\t# Matching keys with data from other sources\n\t\t\tstock['name']=stock.pop('name')\n\t\t\tstock['symbol']=stock.pop('tickersymbol')\n\t\t\tstock['currency']=stock.pop('pricecurrency')\n\t\t\tstock['price'] = price\n\t\t\tstock['price_change']=stock.pop('pricechange')\n\t\t\tstock['price_change_percent']=stock.pop('pricechangepercent')\n\t\t\tstock['exchange'] = stock.pop('exchange')\n\t\t\tstock['price_time_iso'] = time_iso\n\t\t\tstock['quotetime'] = stock.pop('quotetime')\n\t\t\tself.stock_list[url] = stock\n\t\t\treturn stock\n\n\n\tclass yahoo_finance:\n\t\t\"\"\"\n\t\tStock data scrapped from Yahoo Finance\n\t\t\tyahoo_finance(random_headers:bool=True, update_delay_seconds:int=60)\n\n\t\t\tValues:\n\t\t\t\tname : tesla, inc.\n\t\t\t\tsymbol : tsla\n\t\t\t\tcurrency : usd\n\t\t\t\tprice : 701.20\n\t\t\t\tprice_change : 6.42\n\t\t\t\tprice_change_percent : 0.92%\n\t\t\t\tprice_time_iso : 2020-12-31-10:33-05:00\n\t\t\t\texchange : nasdaqgs\n\n\t\t\t\tsourceinterval : 15\n\t\t\t\tquotesourcename : nasdaq real time price\n\t\t\t\tregularmarketopen : {'raw': 699.99, 'fmt': '699.99'}\n\t\t\t\tregularmarkettime : {'raw': 1609428782, 'fmt': '10:33am est'}\n\t\t\t\tfiftytwoweekrange : {'raw': '70.102 - 703.7399', 'fmt': '70.10 - 703.74'}\n\t\t\t\tsharesoutstanding : {'raw': 947900992, 'fmt': '947.901m', 'longfmt': '947,900,992'}\n\t\t\t\tregularmarketdayhigh : {'raw': 703.7399, 'fmt': '703.74'}\n\t\t\t\tlongname : tesla, inc.\n\t\t\t\texchangetimezonename : america\\u002fnew_york\n\t\t\t\tregularmarketpreviousclose : {'raw': 694.78, 'fmt': '694.78'}\n\t\t\t\tfiftytwoweekhighchange : {'raw': -2.539917, 'fmt': '-2.54'}\n\t\t\t\texchangetimezoneshortname : est\n\t\t\t\tfiftytwoweeklowchange : {'raw': 631.098, 'fmt': '631.10'}\n\t\t\t\texchangedatadelayedby : 0\n\t\t\t\tregularmarketdaylow : {'raw': 691.13, 'fmt': '691.13'}\n\t\t\t\tpricehint : 2\n\t\t\t\tregularmarketvolume : {'raw': 11294432, 'fmt': '11.294m', 'longfmt': '11,294,432'}\n\t\t\t\tisloading : False\n\t\t\t\ttriggerable : True\n\t\t\t\tfirsttradedatemilliseconds : 1277818200000\n\t\t\t\tregion : ca\n\t\t\t\tmarketstate : regular\n\t\t\t\tmarketcap : {'raw': 664668209152, 'fmt': '664.668b', 'longfmt': '664,668,209,152'}\n\t\t\t\tquotetype : equity\n\t\t\t\tinvalid : False\n\t\t\t\tlanguage : en-ca\n\t\t\t\tfiftytwoweeklowchangepercent : {'raw': 9.002568, 'fmt': '900.26%'}\n\t\t\t\tregularmarketdayrange : {'raw': '691.13 - 703.7399', 'fmt': '691.13 - 703.74'}\n\t\t\t\tmessageboardid : finmb_27444752\n\t\t\t\tfiftytwoweekhigh : {'raw': 703.7399, 'fmt': '703.74'}\n\t\t\t\tfiftytwoweekhighchangepercent : {'raw': -0.00360917, 'fmt': '-0.36%'}\n\t\t\t\tuuid : ec367bc4-f92c-397c-ac81-bf7b43cffaf7\n\t\t\t\tmarket : us_market\n\t\t\t\tfiftytwoweeklow : {'raw': 70.102, 'fmt': '70.10'}\n\t\t\t\ttradeable : False\n\n\t\t\tExample:\n\t\t\t\tfrom modules.web_scrapers import equity\n\t\t\t\tscraper = equity.yahoo_finance(random_headers=True)\n\t\t\t\tstock = scraper.get_stock('aapl')\n\t\t\t\tfor key in stock:\n\t\t\t\t\tprint(key.ljust(20),' : ',stock[key])\n\t\t\t\tdel scraper\n\t\t\t\tdel stock\n\n\t\t\t\timport modules.web_scrapers as scrapers\n\t\t\t\tscraper = scrapers.equity.yahoo_finance(random_headers=True)\n\t\t\"\"\"\n\n\t\tdef __init__(self,random_headers:bool=True, update_delay_seconds:int=60):\n\t\t\t\"\"\"\n\t\t\tUse Yahoo Finance to get stock information.\n\t\t\t\tWhen random_headers is True a header is chosen randomly and used with each website access.\n\n\t\t\t\tTo reduce load on the website server update_delay_seconds prevents access using the\n\t\t\t\tsame symbol if the specified number of seconds has not elapsed since the last access.\n\t\t\t\"\"\"\n\t\t\tweb = _web(random_headers=random_headers, url_update_interval=update_delay_seconds)\n\t\t\tself.get_website = web._get_website\n\n\t\t\tself.host = 'ca.finance.yahoo.com'\n\t\t\tself.url1 = 'https://' + self.host + '/quote/'\n\t\t\tself.url2 = '/sustainability?p='\n\n\t\t\tself.time_out = (2,4)\n\n\t\t\tfrom json import loads\n\t\t\tself.loads = loads\n\n\t\t\tself.stock_list = {}\n\t\t\t\n\t\tdef get_stock(self, symbol:str, header:dict=None) -> dict :\n\t\t\t\"\"\"\n\t\t\tGet the latest information on the stock symbol string.\n\t\t\t\tReturns a dictionatry with keys:\n\t\t\t\t\tname,\t\tsymbol, \tcurrency, exchange,\n\t\t\t\t\tprice, \tprice_change,\t\tprice_change_percent, price_time_iso,\n\n\t\t\t\t\tregularmarketpreviousclose : {'raw':, 'fmt':},\n\t\t\t\t\tregularmarketopen : {'raw':, 'fmt':},\n\t\t\t\t\tregularmarketdaylow : {'raw':, 'fmt':},\n\t\t\t\t\tregularmarketdayhigh : {'raw':, 'fmt':},\n\t\t\t\t\tregularmarketdayrange : {'raw':, 'fmt':},\n\t\t\t\t\tregularmarketvolume : {'raw':, 'fmt':},\n\t\t\t\t\tregularmarkettime : {'raw':, 'fmt':},\n\n\t\t\t\t\tfiftytwoweekrange : {'raw':, 'fmt':},\n\t\t\t\t\tfiftytwoweeklow : {'raw':, 'fmt':},\n\t\t\t\t\tfiftytwoweeklowchange : {'raw':, 'fmt':},\n\t\t\t\t\tfiftytwoweeklowchangepercent : {'raw':, 'fmt':},\n\t\t\t\t\tfiftytwoweekhigh : {'raw':, 'fmt':},\n\t\t\t\t\tfiftytwoweekhighchange : {'raw':, 'fmt':},\n\t\t\t\t\tfiftytwoweekhighchangepercent : {'raw':, 'fmt':},\n\n\t\t\t\t\tsharesoutstanding : {'raw':, 'fmt':},\n\t\t\t\t\tmarketcap : {'raw':, 'fmt':},\n\t\t\t\t\tsourceinterval,\n\t\t\t\t\tquotesourcename,\n\t\t\t\t\tsharesoutstanding,\n\t\t\t\t\tlongname,\n\t\t\t\t\texchangetimezonename,\n\t\t\t\t\texchangetimezoneshortname,\n\t\t\t\t\texchangedatadelayedby,\n\t\t\t\t\tpricehint,\n\t\t\t\t\tisloading,\n\t\t\t\t\ttriggerable,\n\t\t\t\t\tfirsttradedatemilliseconds,\n\t\t\t\t\tregion,\n\t\t\t\t\tmarketstate,\n\t\t\t\t\tmarketcap,\n\t\t\t\t\tquotetype,\tinvalid,\n\t\t\t\t\tlanguage,\n\t\t\t\t\tmessageboardid,\n\t\t\t\t\tuuid,\n\t\t\t\t\tmarket,\n\t\t\t\t\ttradeable\n\n\t\t\t\tOptional:\n\t\t\t\t\tUses the supplied browser header.\n\t\t\t\t\tIf a header is not provided then a random one gets used.\n\n\t\t\t\t\tExample:\n\t\t\t\t\t\timport yahoo_finance as yf\n\t\t\t\t\t\tyf.yahoo_finance().get_stock('tsla')\n\t\t\t\t\t\tyf.yahoo_finance().get_stock('avst.l')\n\t\t\t\"\"\"\n\t\t\tsymbol = symbol.casefold()\n\t\t\tticker_symbol = symbol\n\n\t\t\turl = self.url1 + ticker_symbol + self.url2 + ticker_symbol\n\n\t\t\t# Website html\n\t\t\thtml = self.get_website(url, header=header).casefold()\n\t\t\t\n\t\t\tif html == None:\n\t\t\t\tif self.stock_list[url] != None:\n\t\t\t\t\treturn self.stock_list[url]\n\t\t\t\telse:\n\t\t\t\t\t_print._indented('class equity', 'yahoo_finance', 'get_stock(' + symbol + ', ' + str(type(header) + ')',\n\t\t\t\t\t'html = self.get_website(' + url + ',' + 'header=' + str(type(header)) + ').casefold()',\n\t\t\t\t\t'if html == None:') )\n\t\t\t\treturn None\n\n\t\t\tdata_string1 = html[ html.find('\\\"quotedata\\\":{'): ]\n\t\t\tdata_string2 = data_string1[:data_string1.find(',\\\"mktmdata\\\"')]\n\n\t\t\tdic_str = data_string2[data_string2.find('{'):]\n\n\t\t\ttry:\n\t\t\t\tstock = self.loads(dic_str)\n\t\t\texcept:\n\t\t\t\t_print._indented('yahoo_finance', 'get_stock(' + symbol + ', ' +str(type(header)) + ')', \n\t\t\t\t\t'try','stock = self.loads(dic_str)', 'data_string1', data_string1, 'data_string2', data_string2, \n\t\t\t\t\t'dic_str', dic_str, 'html[:100]', html[:100])\n\t\t\t\treturn None\n\t\t\tdel html\n\t\t\tdel dic_str\n\t\t\t# Test we have the expected keys\n\t\t\tif stock.get(symbol) == None:\n\t\t\t\t_print._indented('yahoo_finance', 'get_stock('+symbol+', '+str(type(header))+')', \n\t\t\t\t\t'stock.get(\\''+symbol+'\\') == None', stock)\n\t\t\t\treturn None\n\t\t\telif stock[symbol]['symbol'] != symbol:\n\t\t\t\t_print._indented('yahoo_finance', 'get_stock('+symbol+', '+str(type(header))+')', \n\t\t\t\t\t'elif stock[symbol][\\'symbol\\'] != symbol:', stock[symbol]['symbol']+' != '+symbol)\n\t\t\t\treturn None\n\n\t\t\tstock = stock[symbol]\n\n\t\t\t# ISO Format\n\t\t\t# 2020-12-30-16:00-05:00\n\t\t\tlt = int( stock['regularmarkettime']['raw'] )\n\t\t\tdt_iso = equity.datetime.fromtimestamp(lt,tz=equity.timezone.utc).isoformat(' ')\n\n\t\t\t# Matching keys with data from other sources\n\t\t\tstock['name']=stock.pop('shortname')\n\t\t\tstock['symbol']=stock.pop('symbol')\n\t\t\tstock['currency']=stock.pop('currency')\n\t\t\tstock['price']=str(stock.pop('regularmarketprice')['raw'])\n\t\t\tstock['price_change']=stock.pop('regularmarketchange')['fmt']\n\t\t\tstock['price_change_percent']=stock.pop('regularmarketchangepercent')['fmt']\n\t\t\tstock.pop('exchange')\n\t\t\tstock['exchange'] = stock.pop('fullexchangename')\n\t\t\tstock['price_time_iso'] = dt_iso\n\t\t\tstock['regularmarkettime'] = stock.pop('regularmarkettime')\n\t\t\tself.stock_list[url] = stock\n\t\t\treturn stock\n\n\nclass crypto:\n\tclass business_insider:\n\t\t\"\"\"\n\t\tCryptocurrency scraped from Business Insider.\n\t\t\tbusiness_insider(random_headers:bool=True, update_delay_seconds:int=60)\n\n\t\t\tDictionary keys:\n\t\t\t\tname : bitcoin\n\t\t\t\tprice : 38966.5195\n\t\t\t\tchange : -412.53\n\t\t\t\tchange_percent : -1.05\n\t\t\t\tmarket_cap : 704230000000\n\t\t\t\tcirculating : 18072712\n\t\t\t\tvolume : 18880000000\n\t\t\t\tutc_iso : 2021-01-08-18:02:20.067122+00:00\n\n\t\t\tExample:\n\t\t\t\tfrom modules.web_scrapers import crypto\n\t\t\t\tscraper = crypto.business_insider(random_headers=True)\n\t\t\t\tcrypto = scraper.get_crypto('btc-usd')\n\t\t\t\tfor key in crypto:\n\t\t\t\t\tprint(key.ljust(15),' : ',crypto[key])\n\n\t\t\t\timport modules.web_scrapers as scrapers\n\t\t\t\tscraper = scrapers.crypto.business_insider()\n\t\t\"\"\"\n\t\tdef __init__(self,random_headers:bool=True, update_delay_seconds:int=60):\n\t\t\t\"\"\"\n\t\t\tUse Market Watch to get stock information.\n\t\t\tWhen random_headers is True a header is chosen randomly and used with each website access.\n\n\t\t\tTo reduce load on the website server update_delay_seconds prevents access using the\n\t\t\tsame symbol if the specified number of seconds has not elapsed since the last access.\n\t\t\t\"\"\"\n\n\t\t\tself.web = _web(random_headers=random_headers, url_update_interval=update_delay_seconds)\n\t\t\tself.get_website = self.web._get_website\n\n\t\t\t# https://markets.businessinsider.com/cryptocurrencies\n\t\t\t# https://markets.businessinsider.com/currencies/btc-usd\n\t\t\tself.url_crypto_list = 'https://markets.businessinsider.com/cryptocurrencies'\n\t\t\tself.time_out = (4,4)\n\t\t\tself.crypto_value_sections_list = []\n\t\t\tself.values_dict = { 'symbol':0, 'name':1 , 'price':4, 'change':7,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'change_percent':10, 'market_cap':11, 'circulating':12, \n\t\t\t\t\t\t\t\t\t\t\t\t\t'volume':13, 'utc_iso':-1 \n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\tself.most_active_cryptos = {}\n\t\t\tself.most_active_cryptos_limit = 100\n\t\t\tself.timer = timer(update_delay_seconds)\n\t\t\tself.update_delay_seconds = update_delay_seconds\n\n\t\tdef _parse_value(self,section_index:int) -> str:\n\t\t\tif section_index == -1: # utc_iso key\n\t\t\t\treturn self.timer.start_time_iso()\n\n\t\t\tvalue_section = self.crypto_value_sections_list[section_index]\n\t\t\tvalue_list = value_section.split('<')\n\t\t\tvalue = value_list[0]\n\t\t\tdel value_list\n\n\t\t\tif section_index == self.values_dict['symbol']:\n\t\t\t\tsymbol_section_list = value.split('\\\"')\n\t\t\t\tsymbol_link = symbol_section_list[1]\n\t\t\t\tdel symbol_section_list\n\n\t\t\t\tsymbol_link_sections = symbol_link.split('/')\n\n\t\t\t\treturn symbol_link_sections[2]\n\n\n\t\t\tif section_index > self.values_dict['name']:\n\t\t\t\tif value[-1] == 'b':\n\t\t\t\t\treturn str( int(float(value[:-1]) * 10**9) )\n\n\t\t\t\tif value[-1] == 'm':\n\t\t\t\t\treturn str( float(value[:-1]) * 10**6 )\n\n\t\t\treturn value\n\n\t\tdef get_most_active_cryptos(self, limit:int, header:dict=None, show_warnings:bool=False) -> dict:\n\t\t\t\"\"\"\n\t\t\tGet the latest information on the most active cryptocuttencies.\n\n\t\t\t\tReturns a dictionatry with keys:\n\t\t\t\t\t'name' : {'symbol': , 'price':, 'change':, 'change_percent':, 'market_cap':,\n\t\t\t\t\t\t\t\t\t\t\t'circulating':, 'volume':}\n\n\t\t\t\t\t'bitcoin' : {'symbol':'tbc-usd', price':'34164.5391', 'change':'2105.41',\n\t\t\t\t\t\t\t\t\t\t\t'change_percent':'6.57', 'market_cap':'617450000000',\n\t\t\t\t\t\t\t\t\t\t\t'circulating':'18072712', 'volume':'18880000000'}\n\n\t\t\t\t\tOptional:\n\t\t\t\t\t\tUses the supplied browser header.\n\n\t\t\t\tExample:\n\t\t\t\t\tfrom modules.web_scrapers import crypto\n\t\t\t\t\tscraper = crypto.business_insider(random_headers=True)\n\t\t\t\t\tcrypto = scraper.get_crypto('btc-usd')\n\t\t\t\t\tfor key in crypto:\n\t\t\t\t\t\tprint(key.ljust(15),' : ',crypto[key])\n\n\t\t\t\t\timport modules.web_scrapers as scrapers\n\t\t\t\t\tscraper = scrapers.crypto.business_insider()\n\t\t\t\t\tcrypto = scraper.get_crypto('eth-usd')\n\t\t\t\"\"\"\n\t\t\tself.most_active_cryptos_limit = limit\n\t\t\thtml = self.get_website(self.url_crypto_list, header=header)\n\n\t\t\tif html == None:\n\t\t\t\treturn self.most_active_cryptos\n\n\t\t\tself.timer.start()\n\t\t\thtml = html.casefold()\n\n\t\t\t# Get cryptos section\n\t\t\thtml_sections_list = html.split('<tbody class=\"table__tbody\">')\n\t\t\tdel html\n\t\t\tif show_warnings:\n\t\t\t\tif len(html_sections_list) != 4:\n\t\t\t\t\t_print._indented('crypto', 'business_insider', 'get_most_active_cryptos('+str(limit)+', '+type(header)+', '+ str(show_warnings)+')',\n\t\t\t\t\t\t'HTML sections warning', 'Website data not as expected.',\n\t\t\t\t\t\t'4 sections expected, have ',len(html_sections_list))\n\n\t\t\tcryptos_section = html_sections_list[1]\n\t\t\tdel html_sections_list\n\t\t\tcryptos_section = cryptos_section.replace(',','').replace(' %','')\n\n\t\t\t# Get crypto sections\n\t\t\tcrypto_sections_list = cryptos_section.split('<a')\n\t\t\tdel cryptos_section\n\n\t\t\tnumber_crypto_sections = len(crypto_sections_list) - 1\n\t\t\tif number_crypto_sections < limit:\n\t\t\t\tlimit = number_crypto_sections\n\t\t\tlimit +=1\n\n\t\t\t# Get crypto sections symbols, values\n\t\t\tfor crypto_section in crypto_sections_list[1:limit]:\n\n\t\t\t\tself.crypto_value_sections_list = crypto_section.split('\">')\n\n\t\t\t\tif show_warnings :\n\t\t\t\t\tif len(self.crypto_value_sections_list) != 18:\n\t\t\t\t\t\t_print._indented('\\nValues sections warning:\\n\\tWebsite data not as expected.')\n\t\t\t\t\t\t_print._indented('\\t18 sections expected, have ',len(self.crypto_value_sections_list))\n\n\t\t\t\tfor key in self.values_dict:\n\t\t\t\t\tif key == 'symbol':\n\t\t\t\t\t\tsymbol = self._parse_value(self.values_dict[key] )\n\t\t\t\t\t\tself.most_active_cryptos[symbol] = {}\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.most_active_cryptos[symbol][key] = self._parse_value(self.values_dict[key] )\n\n\t\t\treturn self.most_active_cryptos\n\n\t\tdef find_symbol_for(self,limit:int, name:str) -> list:\n\t\t\t\"\"\"\n\t\t\tReturns a list of symbols from the last most active crypto currency data set\n\t\t\tthat match in part or whole the name supplied.\n\t\t\t\"\"\"\n\t\t\tself.most_active_cryptos_limit = limit\n\t\t\tself.most_active_cryptos = self.get_most_active_cryptos(self.most_active_cryptos_limit)\n\n\t\t\tlist = []\n\t\t\tfor symbol in self.most_active_cryptos :\n\t\t\t\tcrypto_name = self.most_active_cryptos[symbol]['name']\n\t\t\t\tif crypto_name.find(name) >= 0:\n\t\t\t\t\tlist.append((symbol, crypto_name))\n\t\t\treturn list\n\n\t\tdef get_price_for(self,symbol:str) -> str:\n\t\t\t\"\"\"\n\t\t\tReturns the price as a string.\n\t\t\t\"\"\"\n\t\t\tself.most_active_cryptos = self.get_most_active_cryptos(self.most_active_cryptos_limit)\n\n\t\t\treturn self.most_active_cryptos[symbol]['price']\n\n\t\tdef get_crypto(self,symbol:str) -> dict:\n\t\t\t\"\"\"\n\t\t\tReturns the dictionary of a crypto symbol.\n\t\t\t\"\"\"\n\t\t\tself.most_active_cryptos = self.get_most_active_cryptos(self.most_active_cryptos_limit)\n\n\t\t\treturn self.most_active_cryptos[symbol]\n\n\n# timer and web\nif __name__ == '__main__' :\n\tprint('\\ntimer and web')\n\tprint('=============')\n\t# input('Press enter to continue.')\n\n\tw = _web(random_headers=True, url_update_interval=3)\n\tx = timer(5)\n\tprint('Getting a website:\\n',w._get_website('http://httpbin.org/headers') )\n\tx.start()\n\tprint('Timer started :', x.started())\n\tx.wait(1)\n\tprint('Time elapsed: ', x.elapsed_seconds())\n\tprint('\\nGetting the website again:',w._get_website('http://httpbin.org/headers') )\n\tprint('\\nTime remaining: ', x.remaining_seconds())\n\tprint('The timer is done (maybe):', x.check_done())\n\tprint('Waiting till done.')\n\tx.wait_till_done()\n\tprint('Timer done:', x.check_done())\n\tprint('Lets try getting the website again:\\n',w._get_website('http://httpbin.org/headers') )\n\tprint('Timer started at: ', x.start_time_iso())\n\tprint('Current time: ', x.current_time_iso())\n\tprint('POSIX time: ', x.current_time_posix())\n\n# market_watch\nif __name__ == '__main__' :\n\tprint('\\nmarket_watch')\n\tprint('============')\n\t# input('Press enter to continue.')\n\n\tdef example(symbol,country=None,random_headers=False):\n\t\t\"\"\"\n\t\tPrints all the available dictionary keys.\n\n\t\tRun from the command line:\n\t\t\t\tpython3 yahoo_finance.py\n\n\t\t\"\"\"\n\n\t\tif random_headers:\n\t\t\tsite = equity.market_watch(random_headers=True)\n\t\telse:\n\t\t\tsite = equity.market_watch()\n\t\tstock = site.get_stock(symbol,country)\n\t\tprint()\n\t\tfor key in stock :\n\t\t\tpad=''\n\t\t\tfor x in range(0,20-len(key)):\n\t\t\t\tpad = pad + ' '\n\t\t\tprint(key, pad, ' : ', stock[key])\n\t\tprint()\n\n\tprint(\"\\nexample('avst', 'uk', random_headers=False)\")\n\tprint('------------------------------------------')\n\texample('avst', 'uk', random_headers=False)\n\n\tprint(\"\\nexample('aapl',random_headers=True)\")\n\tprint('-----------------------------------')\n\texample('aapl',random_headers=True)\n\n# yahoo_finance\nif __name__ == '__main__' :\n\tprint('\\nyahoo_finance')\n\tprint('=============')\n\t# input('Press enter to continue.')\n\n\tdef example(symbol,random_headers=False):\n\t\t\"\"\"\n\t\tPrints all the available dictionary keys.\n\n\t\tRun from the command line:\n\t\t\t\tpython3 yahoo_finance.py\n\n\t\t\"\"\"\n\t\tif random_headers:\n\t\t\tsite = equity.yahoo_finance(random_headers=True)\n\t\telse:\n\t\t\tsite = equity.yahoo_finance()\n\t\tstock = site.get_stock(symbol)\n\t\tprint()\n\t\tfor key in stock :\n\t\t\tpad=''\n\t\t\tfor x in range(0,20-len(key)):\n\t\t\t\tpad = pad + ' '\n\t\t\tprint(key, pad, ' : ', stock[key])\n\t\tprint()\n\n\tprint(\"\\nexample('avst.l', random_headers=False)\")\n\tprint('--------------------------------------')\n\texample('avst.l', random_headers=False)\n\n\tprint(\"\\nexample('aapl',random_headers=True)\")\n\tprint('-----------------------------------')\n\texample('aapl',random_headers=True)\n\n# business_insider\nif __name__ == '__main__' :\n\tprint('\\nbusiness_insider')\n\tprint('================')\n\t# input('Press enter to continue.')\n\n\tdef example(limit:int, random_headers=False, find:str=None):\n\t\t\"\"\"\n\t\tPrints all the available dictionary keys.\n\n\t\tRun from the command line:\n\t\t\t\tpython3 crypto.py\n\n\t\t\"\"\"\n\t\tprint()\n\t\tprint('Example limit: '+ str(limit))\n\t\tif random_headers:\n\t\t\tsource = crypto.business_insider(random_headers=True)\n\t\telse:\n\t\t\tsource = crypto.business_insider()\n\n\t\tcryptos = source.get_most_active_cryptos(limit=limit)\n\n\t\tif find != None:\n\t\t\tfound = source.find_symbol_for(limit,find)\n\n\t\tfor key in cryptos:\n\t\t\tcryptos[key]['name'] = cryptos[key]['name'].ljust(20)\n\t\t\tcryptos[key]['price'] = cryptos[key]['price'].rjust(10)\n\t\t\tcryptos[key]['change'] = cryptos[key]['change'].rjust(8)\n\t\t\tcryptos[key]['change_percent'] = cryptos[key]['change_percent'].rjust(8)\n\t\t\tcryptos[key]['market_cap'] = cryptos[key]['market_cap'].rjust(12)\n\t\t\tcryptos[key]['circulating'] = cryptos[key]['circulating'].rjust(12)\n\t\t\tcryptos[key]['volume'] = cryptos[key]['volume'].rjust(12)\n\n\t\t\tprint(key.rjust(10)+' :',cryptos[key])\n\n\t\tif find != None:\n\t\t\t\tfirst_symbol = found[0][0].strip()\n\t\t\t\tprint('\\nSearched for: '+find+'\\nFound: ',found)\n\t\t\t\tprint('First symbol found is ' + first_symbol + ' for ' + found[0][1].strip() +'.')\n\t\t\t\tprint('The price is $',source.get_price_for(first_symbol))\n\t\tprint()\n\t\tprint('Note: In this example the fields have been padded with spaces.')\n\t\tprint(' The actual data does not have padding.')\n\t\tprint()\n\n\tprint(\"\\nexample(4,random_headers=True)\")\n\tprint('------------------------------')\n\texample(4,random_headers=True)\n\n\tprint(\"\\nexample(limit=4,find='it',random_headers=True))\")\n\tprint('-----------------------------------------------')\n\texample(limit=4,find='it',random_headers=True)" }, { "alpha_fraction": 0.5724381804466248, "alphanum_fraction": 0.6077738404273987, "avg_line_length": 16.6875, "blob_id": "21a796e0097a0139604a1efbaf815a3c5c43032b", "content_id": "77f651cb5293ad6b7ce572a1531261a658650e7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 283, "license_type": "no_license", "max_line_length": 88, "num_lines": 16, "path": "/all_examples.sh", "repo_name": "RCdiy/Python-Web-Scrapers", "src_encoding": "UTF-8", "text": "#!/bin/sh\ncwd=`pwd`/\nfiles=`ls $cwd/example*.py`\necho $files\npython3=\"/usr/local/opt/python@3.9/Frameworks/Python.framework/Versions/3.9/bin/python3\"\ncmds=\"\"\ni=1;\nfor file in $files #\"$@\" \ndo\n if [ $? -eq 0 ]\n then \n echo $file\n $python3 $file\n\t\t\tsleep 1\n fi\ndone\n" }, { "alpha_fraction": 0.7199074029922485, "alphanum_fraction": 0.7291666865348816, "avg_line_length": 24.47058868408203, "blob_id": "587e42a54c36d2882b9654f735d9ea187f01c590", "content_id": "4fd7a0686cdf26cc4f8d9dfbe2299da1978ccf89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 432, "license_type": "no_license", "max_line_length": 54, "num_lines": 17, "path": "/example_crypto.py", "repo_name": "RCdiy/Python-Web-Scrapers", "src_encoding": "UTF-8", "text": "from modules.web_scrapers import crypto\nscraper = crypto.business_insider(random_headers=True)\ncrypto = scraper.get_crypto('btc-usd')\n\nprint('\\n'+ __file__)\n\nfor key in crypto:\n\tprint(key.ljust(15),' : ',crypto[key])\ndel scraper\ndel crypto\n\nimport modules.web_scrapers as scrapers\nscraper = scrapers.crypto.business_insider()\ncrypto = scraper.get_crypto('eth-usd')\nprint()\nfor key in crypto:\n\tprint(key.ljust(15),' : ',crypto[key])" }, { "alpha_fraction": 0.7371007204055786, "alphanum_fraction": 0.7403767108917236, "avg_line_length": 26.133333206176758, "blob_id": "53b071bde331b8ee51d1a7d1ab1f6eed9efb3844", "content_id": "1ae0dec3bdf7ece2f5314d696086e8f825bc42c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1221, "license_type": "no_license", "max_line_length": 71, "num_lines": 45, "path": "/README.md", "repo_name": "RCdiy/Python-Web-Scrapers", "src_encoding": "UTF-8", "text": "# Python Web Scrapers\n\n* This module scrapes websites for data.\n* A delay between scrapping the same URL is used to reduce server load.\n* Random headers are used to reduce the likelihood of being blocked.\n\n# Equity (Stocks)\n\n## Market Watch\nhttps://www.marketwatch.com\n```python\nfrom modules.web_scrapers import equity\nscraper = equity.market_watch(random_headers=True)\nstock = scraper.get_stock('aapl')\nfor key in stock:\n\tprint(key.ljust(20),' : ',stock[key])\n\nimport modules.web_scrapers as scrapers\nscraper = scrapers.equity.market_watch(random_headers=True)\n```\n### Documentation\n```python\n\n```\n## Yahoo Finance\nhttps://ca.finance.yahoo.com\n```python\nfrom modules.web_scrapers import equity\nscraper = equity.yahoo_finance(random_headers=True)\nstock = scraper.get_stock('aapl')\nfor key in stock:\n\tprint(key.ljust(20),' : ',stock[key])\n\nimport modules.web_scrapers as scrapers\nscraper = scrapers.equity.yahoo_finance(random_headers=True)\n```\n\n---\n**Not being maintained**\n* This code is unlikely to be maintained.\n* If you send in a pull request it is unlikely I will look at it.\n* If you create an issue it is unlikely I will look at it.\n\n**Using & Forking**\n* You may use this code or fork it without crediting me.\n" }, { "alpha_fraction": 0.7119815945625305, "alphanum_fraction": 0.7211981415748596, "avg_line_length": 24.58823585510254, "blob_id": "ebd01d18af401c801ed5c5e4e4224872f3ae16df", "content_id": "37db855431c27c3d5bf811492cf02c7376334a81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 434, "license_type": "no_license", "max_line_length": 59, "num_lines": 17, "path": "/example_market_watch.py", "repo_name": "RCdiy/Python-Web-Scrapers", "src_encoding": "UTF-8", "text": "from modules.web_scrapers import equity\nscraper = equity.market_watch(random_headers=True)\nstock = scraper.get_stock('aapl')\n\nprint('\\n'+ __file__)\n\nfor key in stock:\n\tprint(key.ljust(20),' : ',stock[key])\ndel scraper\ndel stock\n\nimport modules.web_scrapers as scrapers\nscraper = scrapers.equity.market_watch(random_headers=True)\nstock = scraper.get_stock('avst', 'uk')\nprint()\nfor key in stock:\n\tprint(key.ljust(20),' : ',stock[key])" }, { "alpha_fraction": 0.43425077199935913, "alphanum_fraction": 0.46177369356155396, "avg_line_length": 18.235294342041016, "blob_id": "94988e61aa743ff0b6088906fec46f156be16195", "content_id": "78215a5d746a1738733b55730985a4606dbc1024", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 327, "license_type": "no_license", "max_line_length": 88, "num_lines": 17, "path": "/all.sh", "repo_name": "RCdiy/Python-Web-Scrapers", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nfiles=`ls *.py`\necho $files\npython3=\"/usr/local/opt/python@3.9/Frameworks/Python.framework/Versions/3.9/bin/python3\"\n\nclear\necho ##################################################################################\n\nfor file in $files #\"$@\" \ndo\n if [ $? -eq 0 ]\n then \n $python3 $file\n\t\t\tsleep 1\n fi\ndone\n" }, { "alpha_fraction": 0.44297993183135986, "alphanum_fraction": 0.4613180458545685, "avg_line_length": 31.943395614624023, "blob_id": "786d61fb08820d40e3b44517c71f889f9829f37d", "content_id": "55f275c9375afa96dffab5413c8ccc3356cf1bd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1745, "license_type": "no_license", "max_line_length": 120, "num_lines": 53, "path": "/compare_mw_yf_by_country.py", "repo_name": "RCdiy/Python-Web-Scrapers", "src_encoding": "UTF-8", "text": "from modules.web_scrapers import equity\nmw = equity.market_watch\nfrom modules.web_scrapers import equity\nyf = equity.yahoo_finance\n\ncountries = {\n 'US':{'mw':'abc', 'yf':'abc'},\n 'CA':{'mw':'abx', 'yf':'abx.to'},\n 'UK':{'mw':'abc', 'yf':'abc.l'},\n 'DE':{'mw':'aba', 'yf':'aba.f'},\n 'ES':{'mw':'ams', 'yf':'ams.mc'},\n 'FR':{'mw':'air', 'yf':'air.pa'},\n 'IT':{'mw':'atl', 'yf':'atl.mi'},\n 'NL':{'mw':'abn', 'yf':'abn.as'},\n 'NO':{'mw':'ade', 'yf':'ade.ol'},\n 'SE':{'mw':'abb', 'yf':'abb.st'},\n 'CH':{'mw':'ams', 'yf':'ams.sw'},\n 'ZA':{'mw':'abg', 'yf':'abg.jo'},\n 'HK':{'mw':'1234', 'yf':'1234.hk'},\n 'JP':{'mw':'4321', 'yf':'4321.t'},\n 'AU':{'mw':'anz', 'yf':'anz.ax'},\n 'NZ':{'mw':'anz', 'yf':'anz.nz'}\n }\n\nprint('\\n'+ __file__)\n\nfor c in countries:\n if True:\n s_mw = countries[c]['mw']\n s_yf = countries[c]['yf']\n stock_mw = mw(random_headers=True).get_stock(s_mw,c)\n stock_yf = yf(random_headers=True).get_stock(s_yf)\n\n p_mw = stock_mw['price']\n cu_mw = stock_mw['currency']\n time_mw = stock_mw['price_time_iso'] \n t_mw = time_mw[:-6] + ' ' + time_mw[-6:] \n e_mw = stock_mw['exchange']\n n_mw = stock_mw['name']\n\n p_yf = stock_yf['price']\n cu_yf = stock_yf['currency']\n time_yf = stock_yf['price_time_iso']\n t_yf = time_yf[:-6] + ' ' + time_yf[-6:]\n e_yf = stock_yf['exchange']\n n_yf = stock_yf['name']\n\n print(c + ' : ' + s_mw.ljust(7) + p_mw.rjust(10) + cu_mw.center(5) + t_mw + ' ' + e_mw.ljust(32) + ' ' + n_mw )\n print(c + ' : ' + s_yf.ljust(7) + p_yf.rjust(10) + cu_yf.center(5) + t_yf + ' ' + e_yf.ljust(32) + ' ' + n_yf )\n print('')\n\n\nprint('')" }, { "alpha_fraction": 0.7175925970077515, "alphanum_fraction": 0.7268518805503845, "avg_line_length": 24.47058868408203, "blob_id": "723c69b83f0d2e20d4924a5428752f8e4be9e643", "content_id": "608cff1a0d9098f2e9c8372bf5d5908d5d113e84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 432, "license_type": "no_license", "max_line_length": 60, "num_lines": 17, "path": "/example_yahoo_finance.py", "repo_name": "RCdiy/Python-Web-Scrapers", "src_encoding": "UTF-8", "text": "from modules.web_scrapers import equity\nscraper = equity.yahoo_finance(random_headers=True)\nstock = scraper.get_stock('aapl')\n\nprint('\\n'+ __file__)\n\nfor key in stock:\n\tprint(key.ljust(30),' : ',stock[key])\ndel scraper\ndel stock\n\nimport modules.web_scrapers as scrapers\nscraper = scrapers.equity.yahoo_finance(random_headers=True)\nstock = scraper.get_stock('avst.l')\nprint()\nfor key in stock:\n\tprint(key.ljust(30),' : ',stock[key])" }, { "alpha_fraction": 0.6271604895591736, "alphanum_fraction": 0.6320987939834595, "avg_line_length": 22.171428680419922, "blob_id": "07a538be3913a2ca5c3ce6632cb70ba849d52933", "content_id": "5adc9e895f5f22c9599dd309b4aba9c1f97c67c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 810, "license_type": "no_license", "max_line_length": 78, "num_lines": 35, "path": "/compare_mw_yf.py", "repo_name": "RCdiy/Python-Web-Scrapers", "src_encoding": "UTF-8", "text": "\"\"\"\nPrints values from keys common to Market Watch and Yahoo Finance using a stock\nnot traded on the US stock exchange.\nMarket Watch\n symbol = 'avst'\n country = 'uk'\nYahoo Finance\n symbol = 'avst.l'\n\"\"\"\nimport modules.web_scrapers as scrapers\nscraper_mw = scrapers.equity.market_watch(random_headers=True)\nscraper_yf = scrapers.equity.yahoo_finance(random_headers=True)\n\nsymbol_mw = 'ams'\ncountry = 'es'\nsymbol_yf = 'ams.mc' \n\nstock_mw = scraper_mw.get_stock(symbol_mw,country)\nstock_yf = scraper_yf.get_stock(symbol_yf)\n\ncomparison = {}\n\nprint('\\n'+ __file__)\n\nfor key in stock_yf :\n try:\n yf = stock_yf[key]\n mw = stock_mw[key]\n key = key.ljust(20)\n print(key,\" mw : \", mw)\n key = \" \".ljust(20)\n print(key,\" yf : \", yf)\n except:\n pass\nprint('')" } ]
9
fransiskusalvin/List_Spinner
https://github.com/fransiskusalvin/List_Spinner
402210f9951029809efe6e633896b68eb50c7c8d
2be0ecfb664089d5cbc3cbd4f338b5436f5feeea
caf904fe81c417128823b7183e2891cef10fd51b
refs/heads/main
2023-03-28T03:21:37.446392
2021-03-30T11:13:58
2021-03-30T11:13:58
339,269,632
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5132075548171997, "alphanum_fraction": 0.5622641444206238, "avg_line_length": 27.55555534362793, "blob_id": "1214fa2d6160a02c141a9b6aaff57f5532f7d577", "content_id": "9b80655cd824ac438a54069b39edba2a19aba433", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 530, "license_type": "no_license", "max_line_length": 101, "num_lines": 18, "path": "/Exam_No_2_List_Spinner_Fransiskus Alvin.py", "repo_name": "fransiskusalvin/List_Spinner", "src_encoding": "UTF-8", "text": "def counterClockwise(Angka):\r\n angka_baru = []\r\n for i in range((len(Angka) - 1), -1, -1): \r\n temporary = [] ##Membuat list baru setiap perubahan i\r\n for j in range(len(Angka)):\r\n temporary.append(Angka[j][i]) ## Memasukkan nilai yang diinginkan ke dalam list temporary\r\n # print(temporary)\r\n angka_baru.append(temporary)\r\n return(angka_baru)\r\n\r\nList_Awal = [\r\n [1, 2, 3, 4],\r\n [5, 6, 7, 8],\r\n [9, 10, 11, 12],\r\n [13, 14, 15, 16]\r\n]\r\n\r\nprint(counterClockwise(List_Awal))" }, { "alpha_fraction": 0.692307710647583, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 16.33333396911621, "blob_id": "9a5338deea956887e0292eb4fa8e1840eaca1ff2", "content_id": "094b6f92bc0aa14b96c9ce67bd6b621828a5ae3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 52, "license_type": "no_license", "max_line_length": 35, "num_lines": 3, "path": "/README.md", "repo_name": "fransiskusalvin/List_Spinner", "src_encoding": "UTF-8", "text": "# List_Spinner\n\nExam Modul 1 JCDS12 Purwadhika No 2\n" } ]
2
diegoalmeidas/AgendaADS
https://github.com/diegoalmeidas/AgendaADS
ad48560e203bc2550bc463c68122ebde29158feb
3e65fb82e0fbb5dc9aebe51ca1b98c8f84198a27
cef3b3d26ab3bc84eb87a06b9a6b19ed0b5af4d0
refs/heads/master
2020-03-26T15:35:34.904240
2018-08-21T21:55:06
2018-08-21T21:55:06
145,052,581
0
0
null
2018-08-17T00:28:11
2018-08-19T13:58:15
2018-08-20T22:56:52
Python
[ { "alpha_fraction": 0.5824074149131775, "alphanum_fraction": 0.6032407283782959, "avg_line_length": 25.69230842590332, "blob_id": "cb3109b5ec391b913f243ce8245b0992b1342204", "content_id": "68279a28050735228aa3ca0d08e6e89228c9d556", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2161, "license_type": "no_license", "max_line_length": 65, "num_lines": 78, "path": "/funcoes.py", "repo_name": "diegoalmeidas/AgendaADS", "src_encoding": "UTF-8", "text": "#Danilo Silva Babilius\t\tRA1800140\r\n#Diego de Almeida Saraiva\tRA1800054\r\n#Rodrigo Rodrigues da Silva\tRA1800409\r\n#Rogerio Alves Santos\t\tRA1800386\r\n#William Bruce Ogura\t\tRA1800114\r\n\r\nimport csv\r\n\r\n#Mensagem de Bem Vindo e Opcoes ao Usuario\r\ndef bemvindo():\r\n\tprint(\"Bem Vindo a Agenda\")\r\n\tprint(\"Selecione uma Opcao\")\r\n\tprint(\"1 Adicionar um novo contato\")\r\n\tprint(\"2 Listar os contatos da agenda\")\r\n\tprint(\"4 Apagar um contato\")\r\n\tprint(\"5 Buscar um contato\")\r\n\r\n \r\n#Funcoes do processo\r\ndef adicionar():\r\n\tprint(\"Adicionar um registro\")\r\n\tagenda = open(\"agendatelefonica.csv\",'a')\r\n\tnome = input(\"Nome do Contato:\")\r\n\ttelefone = input(\"Digite o telefone:\")\r\n\tprint(\"Contato salvo com nome:\",nome,\" e numero\",telefone)\r\n\tagenda.write(nome)\r\n\tagenda.write(\",\")\r\n\tagenda.write(telefone)\r\n\tagenda.write(\",\")\r\n\tagenda.write(\"\\n\")\r\n\tagenda.close()\r\n\t\r\n# Listar linhas da agenda\r\ndef numlinhas():\r\n\tarquivo = open(\"agendatelefonica.csv\", \"r\")\r\n\tn_linhas = sum(1 for linha in arquivo)\r\n\tarquivo.close()\r\n\treturn n_linhas\r\n\r\n\r\ndef listar():\r\n\tqtdlinhas = numlinhas()\r\n\tprint(\"Lista de Contatos\")\r\n\tagenda = open(\"agendatelefonica.csv\")\r\n\tnumero = 0\r\n\twhile numero < qtdlinhas:\r\n\t\tprint (agenda.readline())\r\n\t\tnumero = numero + 1\r\n\tprint(\"Listado correctamente\")\t\r\n\tagenda.close()\r\n\r\ndef deletar():\r\n with open(\"agendatelefonica.csv\",\"r\") as agenda:\r\n reader = csv.reader(agenda)\r\n data = list(reader)\r\n nome=str(\"\")\r\n while nome not in ([row[0] for row in data]):\r\n nome = input(\"Nome do contato a ser deletado: \")\r\n data.pop([row[0] for row in data].index(nome))\r\n with open(\"agendatelefonica.csv\",\"w\",newline=\"\") as file:\r\n writer = csv.writer(file)\r\n for row in data :\r\n writer.writerow(row)\r\n print(\"Contato removido com sucesso!!\")\r\n bemvindo()\r\ndef falha():\r\n\tprint(\"Opcao Incorreta\")\r\n\r\ndef encontrar(busca):\r\n agenda = open(\"agendatelefonica.csv\")\r\n lista = (agenda.readlines())\r\n nome = False\r\n for i in range (0,len(lista)):\r\n if busca in lista[i]:\r\n print(lista[i])\r\n nome = True\r\n if nome == False:\r\n print(\"Nome não encontrado\")\r\n" } ]
1
yasseres/Guessing-Numbers
https://github.com/yasseres/Guessing-Numbers
a5639ebaa1e192fa9de8f8ba6236e7ffe99a2f1e
f3ac67fcd7ec4d16889af503c316859347a44398
8641b805df28e78ca4aec2391b2787c9cc4b7398
refs/heads/main
2023-07-15T23:07:54.757149
2021-08-29T19:25:27
2021-08-29T19:25:27
401,123,144
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7314189076423645, "alphanum_fraction": 0.7415540814399719, "avg_line_length": 47.58333206176758, "blob_id": "74fe5c8e7c207cc8885b0115074b871ac7f907e3", "content_id": "aeb093c458518b2dcc5d63e86d95833f4362ec70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 592, "license_type": "no_license", "max_line_length": 184, "num_lines": 12, "path": "/README.md", "repo_name": "yasseres/Guessing-Numbers", "src_encoding": "UTF-8", "text": "# Guessing-Numbers\nMy aim is to make an ai that can find out what happend to a number.\nSo its my first time using github. I dont know if anyone will see this.\n\nI made a script called making Numbers.py\n This Script makes numbers and puts them into Numbers.csv\n \n\n\nNow i want an ai to read these Numbers. And then find a patterns. I want the Ai to understand what happend to 3 that it ended up 38, What happend to 6 that it ended up 41... and so on.\n\nI tried for a few hours and could not get anywhere. If someone could direct me into the right direction, that would be amazing. :)\n \n" }, { "alpha_fraction": 0.5014577507972717, "alphanum_fraction": 0.533527672290802, "avg_line_length": 18.294116973876953, "blob_id": "73560412b6edea38663ebf1dd092ae556577a67a", "content_id": "410ade4910d51971ab972a0586ca7d1b929eef55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 343, "license_type": "no_license", "max_line_length": 69, "num_lines": 17, "path": "/making Numbers.py", "repo_name": "yasseres/Guessing-Numbers", "src_encoding": "UTF-8", "text": "import csv\r\n\r\nz = 0\r\n\r\nfor x in range(10000):\r\n\r\n z = z + 3\r\n\r\n Number = z\r\n \r\n Input1 = z+5*7\r\n\r\n with open (\"Numbers.csv\", \"a\", newline=\"\") as f:\r\n fieldnames = [\"to be issued\", \"Result\"]\r\n writer = csv.DictWriter(f, fieldnames=fieldnames)\r\n\r\n writer.writerow({\"to be issued\" : Number, \"Result\" : Input1})" } ]
2
scullion/lrfu
https://github.com/scullion/lrfu
9976802f21c8ab7a7d0dde4a0f6a507bcbf6f07b
953b13b580db764afcd353d1c6f1d019773b7473
cb8ddc7773ad21aaeb3c14b229a647e06047be81
refs/heads/master
2020-04-05T23:44:30.807623
2015-02-01T00:00:18
2015-02-01T00:05:28
30,047,904
10
0
null
null
null
null
null
[ { "alpha_fraction": 0.5035030245780945, "alphanum_fraction": 0.5109761953353882, "avg_line_length": 26.805194854736328, "blob_id": "8d618652930738f15919c5004355223f1e8575b5", "content_id": "f62b912ae7f45fdd9dbc5e8a382a21e328cf541f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2141, "license_type": "no_license", "max_line_length": 65, "num_lines": 77, "path": "/lrfu.py", "repo_name": "scullion/lrfu", "src_encoding": "UTF-8", "text": "from itertools import count\nfrom heapq import heapify, nsmallest\n\ntry:\n from collections import MutableMapping\nexcept ImportError:\n from UserDict import DictMixin\n MutableMapping = None\n \nclass LRFUCache(MutableMapping or DictMixin):\n def __init__(self, control=1e-3, limit=16):\n self.data = {}\n self.limit = limit\n assert limit > 0\n self.base = 0.5 ** control\n self.time = count().next\n \n def __getitem__(self, key):\n entry = crf, atime, key, value = self.data[key]\n entry[1] = now = self.time()\n entry[0] = 1.0 + self.base ** (now - atime) * crf\n return value\n \n def __setitem__(self, key, value):\n data = self.data\n if key in data:\n data[key][3] = value\n else:\n if len(data) == self.limit:\n self.compact()\n data[key] = [1.0, self.time(), key, value]\n \n def __delitem__(self, key):\n del self.data[key]\n \n def compact(self):\n data = self.data\n base = self.base\n while True:\n now = self.time()\n entries = [(base ** (now - atime) * crf, key) for \n crf, atime, key, value in data.itervalues()]\n heapify(entries)\n delete_count = len(entries) - (self.limit >> 1)\n if delete_count <= 0:\n break \n try:\n for crf, key in nsmallest(delete_count, entries):\n del data[key]\n except KeyError:\n continue\n break\n \n def __len__(self):\n return len(self.data)\n \n def __iter__(self):\n return iter(self.data)\n \n def keys(self):\n return self.data.keys()\n \n def __contains__(self, key):\n return key in self.data\n\n def iterkeys(self):\n return iter(self.data)\n \n def itervalues(self):\n return self.data.itervalues()\n \n def iteritems(self):\n for crf, atime, key, value in self.data.itervalues():\n yield (key, value)\n \n def __repr__(self):\n return repr(self.data)\n" }, { "alpha_fraction": 0.7744185924530029, "alphanum_fraction": 0.7976744174957275, "avg_line_length": 42, "blob_id": "49113abecf6eeadb234462124c2bbef95f4e0334", "content_id": "577849e161ddb748063aaf0658abdae4e21353c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 430, "license_type": "no_license", "max_line_length": 80, "num_lines": 10, "path": "/README.md", "repo_name": "scullion/lrfu", "src_encoding": "UTF-8", "text": "## LRFUCache\n\nThis is a simple Python implementation of a cache based on the \n[LRFU](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.55.1478) \nreplacement policy. It has a relatively low overhead compared to linked list \nbased cache implementations.\n\nOverhead is reduced by evicting periodically in bulk. As such the cache will\ntypically contain fewer items than permitted by the upper bound supplied to the \nconstructor.\n" } ]
2
Trollicorn/SoftDev2
https://github.com/Trollicorn/SoftDev2
120f5e8a020326106b354db3c83006ce8b6b34b4
b29d3c05e6f33007c238b121b885cda13df1a540
6ef9dfae3393e35d8acdc4266a31571aa0ff200c
refs/heads/master
2020-04-19T12:52:34.735707
2019-05-02T17:16:14
2019-05-02T17:16:14
168,202,765
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.782608687877655, "alphanum_fraction": 0.8260869383811951, "avg_line_length": 22, "blob_id": "168dd211e98862dffdf73f99b6333b006095d90f", "content_id": "f6a25bbd3e87899df9bb8f3fb95a487e441ff55a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 46, "license_type": "no_license", "max_line_length": 34, "num_lines": 2, "path": "/README.md", "repo_name": "Trollicorn/SoftDev2", "src_encoding": "UTF-8", "text": "# SoftDev2\nSoftware Development, 2nd Semester\n" }, { "alpha_fraction": 0.6269716024398804, "alphanum_fraction": 0.6458990573883057, "avg_line_length": 25.41666603088379, "blob_id": "ae10520b6d9c072461cb8dfe5624cab50b4978b4", "content_id": "cb89448e7b968797d11d186c155bfbc12acf02d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1268, "license_type": "no_license", "max_line_length": 96, "num_lines": 48, "path": "/02_canvas/dotconn.js", "repo_name": "Trollicorn/SoftDev2", "src_encoding": "UTF-8", "text": "// azrael --- Jason Tung and Mohammed Uddin\n// SoftDev2 pd7\n//K #02: Connecting the Dots\n// 2019-01-31\n\n//getting references to html elements\nvar c = document.getElementById(\"playground\");\nvar ctx = c.getContext(\"2d\");\n\nvar first = \"yes\"\nvar prev = {\"x\":0, \"y\":0}\nvar cbtn = document.getElementById(\"clear\");\n\nvar w = c.getAttribute(\"width\");\nvar h = c.getAttribute(\"height\");\n\n//set the fill colors now\nctx.fillStyle = \"red\";\nctx.strokeStyle = \"black\";\n\n//add listened to clear button to wipe the page\ncbtn.addEventListener('click', function () {\n ctx.clearRect(0, 0, w, h);\n first = \"yes\";\n});\n\n\n//adds event listener to canvas to draw on it when theres a click\nc.addEventListener('click', function (e) {\n //OFFSETX/OFFSETY --- gets mousex and mousey relative to the event e rather than the webpage\n var cds = {\"x\":e.offsetX, \"y\":e.offsetY};\n\n ctx.beginPath();\n ctx.ellipse(cds.x, cds.y, 10, 10, 0, 0, 2 * Math.PI);\n ctx.fill(); //fills circle but this erases the line this is so sad\n ctx.closePath();\n\n if (first != \"yes\"){ //if not first click, draw line to click\n ctx.moveTo(cds.x,cds.y);\n ctx.lineTo(prev.x,prev.y);\n ctx.stroke();\n ctx.closePath();\n }else{ //if first click, skip above\n first = \"no\";\n }\n prev.x = cds.x;\n prev.y = cds.y;\n});\n" }, { "alpha_fraction": 0.6117936372756958, "alphanum_fraction": 0.6380016207695007, "avg_line_length": 26.133333206176758, "blob_id": "86d3d138d99132e78f556d04a8f86f254a99d4f3", "content_id": "036d331975218fded8fd38b768f836d1ecb28642", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1221, "license_type": "no_license", "max_line_length": 78, "num_lines": 45, "path": "/09_svg/stuff.js", "repo_name": "Trollicorn/SoftDev2", "src_encoding": "UTF-8", "text": "// Mohammed Uddin\n// SoftDev2 pd7\n//K #09: Connect the Dots\n// 2019-03-13\n\n//getting references to html elements\nvar savage = document.getElementById(\"vimage\");\n\nvar first = \"yes\"\nvar prev = {\"x\":0, \"y\":0}\n\nsavage.addEventListener('click',function(e){\n var cds = {\"x\":e.offsetX, \"y\":e.offsetY}\n var c = document.createElementNS(\"http://www.w3.org/2000/svg\", \"circle\");\n c.setAttribute(\"cx\", cds.x);\n c.setAttribute(\"cy\", cds.y);\n c.setAttribute(\"r\", 10);\n c.setAttribute(\"fill\", \"red\");\n c.setAttribute(\"stroke\", \"black\");\n savage.appendChild(c);\n\n if (first != \"yes\"){ //if not first click, draw line to click\n var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');\n line.setAttribute('x1', prev.x);\n line.setAttribute('x2', cds.x);\n line.setAttribute('y1', prev.y);\n line.setAttribute('y2', cds.y);\n line.setAttribute('stroke', 'black');\n savage.appendChild(line);\n }else{ //if first click, skip above\n first = \"no\";\n }\n prev.x = cds.x;\n prev.y = cds.y;\n});\n\noofers = document.getElementById(\"clear\");\noofers.addEventListener('click',function(){\n while (savage.lastChild){\n savage.removeChild(savage.lastChild);\n }\n prev.x = 0;\n prev.y = 0;\n first = \"yes\";\n});\n" }, { "alpha_fraction": 0.61519455909729, "alphanum_fraction": 0.6324892044067383, "avg_line_length": 23.907691955566406, "blob_id": "a1326df04897243fec17b6da5a164eea6b8b4b16", "content_id": "afa76f9999d4213a7a799a4366ada804f11c5f27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1619, "license_type": "no_license", "max_line_length": 75, "num_lines": 65, "path": "/11_svg-anim/stuff.js", "repo_name": "Trollicorn/SoftDev2", "src_encoding": "UTF-8", "text": "// Mohammed Uddin\n// SoftDev2 pd7\n//K #10: Ask Circles [Change || Die]\n// 2019-03-14\n\n//getting references to html elements\nvar savage = document.getElementById(\"vimage\");\nvar creaty = true;\nvar move = \"no\";\n\nsavage.addEventListener('click',function(e){\n var cds = {\"x\":e.offsetX, \"y\":e.offsetY};\n if (creaty){\n circlify(cds.x,cds.y);\n }else{\n creaty = true;\n }\n});\n\nvar circlify = function(x,y){\n var c = document.createElementNS(\"http://www.w3.org/2000/svg\", \"circle\");\n c.setAttribute(\"cx\", x);\n c.setAttribute(\"cy\", y);\n c.setAttribute(\"r\", 20);\n c.setAttribute(\"fill\", \"purple\");\n c.setAttribute(\"stroke\", \"black\");\n c.setAttribute(\"first\", \"yes\");\n c.setAttribute(\"vx\",1);\n c.setAttribute(\"vy\",1);\n c.addEventListener('click',function(e){\n creaty = false;\n if (c.getAttribute(\"first\")==\"yes\"){\n c.setAttribute(\"first\",\"no\");\n c.setAttribute(\"fill\",\"green\");\n }\n else{\n savage.removeChild(c);\n x = Math.floor(Math.random()*500);\n y = Math.floor(Math.random()*500);\n circlify(x,y);\n }\n });\n savage.appendChild(c);\n return c;\n};\n\nvar move = function(c){\n c.setAttribute(\"cx\",c.getAttribute(\"cx\")+c.getAttribute(\"vx\"));\n c.setAttribute(\"cy\",c.getAttribute(\"cy\")+c.getAttribute(\"vy\"));\n savage.appendChild(c);\n}\n\noofers = document.getElementById(\"clear\");\noofers.addEventListener('click',function(){\n while (savage.lastChild){\n savage.removeChild(savage.lastChild);\n }\n});\n\nmovers = document.getElementById(\"move\");\nmovers.addEventListener('click',function(){\n for (int i = 0; i < savage.children.length; i++){\n move(savage.children[i]);\n }\n});\n" }, { "alpha_fraction": 0.5883211493492126, "alphanum_fraction": 0.6335766315460205, "avg_line_length": 15.707317352294922, "blob_id": "40b4f203a510397cc503430f4e96d38ae98ac9d0", "content_id": "0900d52ae8bc787a1fdfdc5a314fb82203c04583", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 685, "license_type": "no_license", "max_line_length": 25, "num_lines": 41, "path": "/22_closure/ok.py", "repo_name": "Trollicorn/SoftDev2", "src_encoding": "UTF-8", "text": "def repeat(word):\n\tdef ok(x):\n\t\treturn word * x\n\treturn ok\nprint('\\nTEST REPEAT\\n')\nr1 = repeat('hello')\nr2 = repeat('goodbye')\nprint(r1(2))\nprint(r2(2))\nprint(repeat('cool')(3))\n\ndef make_counter():\n\tx = 0\n\tdef count():\n\t\tnonlocal x\n\t\tx += 1\n\t\treturn x\n\tdef see():\n\t\tnonlocal x\n\t\treturn x\n\treturn [count,see]\nprint('\\nTEST COUNTER\\n')\nprint('COUNTER 0')\nctrl = make_counter()\nprint(ctrl[0]())\nprint(ctrl[0]())\nprint(ctrl[0]())\nprint('ACCESS 0')\nprint(ctrl[1]())\nprint('COUNTER 1')\nctrl2 = make_counter()\nprint(ctrl2[0]())\nprint(ctrl2[0]())\nprint('COUNTER 0')\nprint(ctrl[0]())\nprint('COUNTER 1')\nprint(ctrl2[0]())\nprint('ACCESS 0')\nprint(ctrl[1]())\nprint('ACCESS 1')\nprint(ctrl2[1]())\n" }, { "alpha_fraction": 0.7092198729515076, "alphanum_fraction": 0.7730496525764465, "avg_line_length": 22.5, "blob_id": "26bbced127746d432b1a9b3a7ba36eaf6454c99e", "content_id": "5afbaea82158c270860b3ba98418fc3e7bf4fda3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 141, "license_type": "no_license", "max_line_length": 45, "num_lines": 6, "path": "/06_mongo/mongo.py", "repo_name": "Trollicorn/SoftDev2", "src_encoding": "UTF-8", "text": "import pymongo\n\nSERVER_ADDR = \"157.230.51.119\"\nconnection = pymongo.MongoClient(SERVER_ADDR)\ndb = connection.test\ncollection = db. restaurants\n" }, { "alpha_fraction": 0.5181818008422852, "alphanum_fraction": 0.5742424130439758, "avg_line_length": 24.384614944458008, "blob_id": "c6b52bfb2e142447d865844209da2d7debad0467", "content_id": "c004c53f412e53b606d3c0814fd3dd988badaa0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1320, "license_type": "no_license", "max_line_length": 88, "num_lines": 52, "path": "/16_listcomp/listcomp.py", "repo_name": "Trollicorn/SoftDev2", "src_encoding": "UTF-8", "text": "from functools import reduce\nfrom operator import mul\n\ndef min(pw):\n\t\"\"\"\n\treturn if password has\n\ta mix of uppwer and lowercase letters\n\tand at least 1 number\n\t\"\"\"\n\tlis = [2 if c.isdigit() else 3 if c.islower() else 5 if c.isupper() else 7 for c in pw]\n\tpro = reduce(mul,lis)\n\ta= float(pro)/(2*3*5)\n\tb= pro//(2*3*5)*1.0\n\treturn a==b\n\nprint (\"abc is \" + str(min(\"abc\")) + \" and should be False\") #False\nprint (\"AbC is \" + str(min(\"AbC\")) + \" and should be False\") #False\nprint (\"b12 is \" + str(min(\"b12\")) + \" and should be False\") #False\nprint (\"rpBc4 is \" + str(min(\"rpBc4\")) + \" and should be True\") #True\n\ndef strong(pw):\n\t\"\"\"\n\treturn if password is strong\n\t\"\"\"\n\tlis = [2 if c.isdigit() else 3 if c.islower() else 5 if c.isupper() else 7 for c in pw]\n\tpro = reduce(mul,lis)\n\tstrn = 0\n\tif pro % 2 == 0:\n\t\tstrn += 1\n\tif pro % 4 == 0:\n\t\tstrn += 1\n\tif pro % 3 == 0:\n\t\tstrn += 1\n\tif pro % 9 == 0:\n\t\tstrn += 1\n\tif pro % 5 == 0:\n\t\tstrn += 1\n\tif pro % 25 == 0:\n\t\tstrn += 1\n\tif pro % 7 == 0:\n\t\tstrn += 1\n\tif pro % 49 == 0:\n\t\tstrn += 1\n\tif pro % (2*3*5*7) == 0:\n\t\tstrn += 1\n\tif strn == 9:\n\t\tstrn += 1\n\treturn strn\n\nprint(\"hello is \" + str(strong(\"hello\")) + \" and should be 2\") #2\nprint(\"hello12 is \" + str(strong(\"hello12\")) + \" and should be 4\") #4\nprint(\"HelLo0,3! is \" + str(strong(\"HelLo0,3!\")) + \" and should be 10\") #10\n" }, { "alpha_fraction": 0.6223776340484619, "alphanum_fraction": 0.6993007063865662, "avg_line_length": 22.83333396911621, "blob_id": "76752a971ffb41e74000ff80063edbab27659fd7", "content_id": "f5934035977f2846b38808e1d7a07c61cd4104f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 143, "license_type": "no_license", "max_line_length": 48, "num_lines": 6, "path": "/other/draw.js", "repo_name": "Trollicorn/SoftDev2", "src_encoding": "UTF-8", "text": "const canvas = document.getElementById(\"slate\");\nconst ctx = canvas.getContext(\"2d\");\n\nvar doot = function(){\n\tctx.fillRect(40,70,100,300);\n};\n" }, { "alpha_fraction": 0.572864294052124, "alphanum_fraction": 0.6281406879425049, "avg_line_length": 17.090909957885742, "blob_id": "def635434b22381374c86f013b3008b975827b5b", "content_id": "0185c594995a0c693d0a42941b43f318a560929d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 199, "license_type": "no_license", "max_line_length": 73, "num_lines": 11, "path": "/18/work.py", "repo_name": "Trollicorn/SoftDev2", "src_encoding": "UTF-8", "text": "from math import log2\n\ndef pythag(n):\n return [\"google it\"]\n\ndef quicksort(lis):\n return [x for x in range(int(log2(len(lis)))) for y in range(0,2*x),]\n\n\nl =[4,2,6,2,8,3,7]\nprint(quicksort(l))\n" }, { "alpha_fraction": 0.5722146034240723, "alphanum_fraction": 0.5942228436470032, "avg_line_length": 21.71875, "blob_id": "b122645fce6dd37dd1a715cb790590a812b0eeb7", "content_id": "68deaba563db76197308ad76f045f378d7d6ca8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 727, "license_type": "no_license", "max_line_length": 103, "num_lines": 32, "path": "/23_memoize/ok.py", "repo_name": "Trollicorn/SoftDev2", "src_encoding": "UTF-8", "text": "import random\n\ndef headify(f):\n txt = f()\n def inner():\n return '<h1>' + txt + '</h1>'\n return inner\n@headify\ndef greet():\n greetings = ['print(\"Hello\")','print \"Hello\"','System.out.println(\"Hello\")','console.log(\"Hello\")']\n return random.choice(greetings)\ndef greet2():\n greetings = ['print(\"Hello\")','print \"Hello\"','System.out.println(\"Hello\")','console.log(\"Hello\")']\n return random.choice(greetings)\n\n#print(greet())\n#print(greet2())\n\ndef memoize(f):\n memo = {0:0,1:1,2:1}\n def helper(x):\n if x not in memo:\n memo[x]=f(x)\n return memo[x]\n return helper\n@memoize\ndef fibrec(n):\n return fibrec(n-1)+fibrec(n-2)\n\n#print(fibrec(40))\nfib = fibrec\nprint(fib(40))\n" }, { "alpha_fraction": 0.6064257025718689, "alphanum_fraction": 0.6318607926368713, "avg_line_length": 18.153846740722656, "blob_id": "f02abae383200cb7c5452eab524726133dfe96ec", "content_id": "eff24d272f184c61a52649828fec0bc8b1931b4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 747, "license_type": "no_license", "max_line_length": 54, "num_lines": 39, "path": "/00_canvas/old/clickdraw.js", "repo_name": "Trollicorn/SoftDev2", "src_encoding": "UTF-8", "text": "const canvas = document.getElementById(\"slate\");\nconst ctx = canvas.getContext(\"2d\");\nvar r = canvas.getBoundingClientRect();\nvar x = r[\"x\"];\nvar y = r[\"y\"];\nvar dot = 0;\nvar w = 50;\nvar h = 100;\n\nvar clear = function(e){\n\tctx.clearRect(0,0,canvas.width,canvas.height);\n};\n\nvar button = document.getElementById(\"clear\");\nbutton.addEventListener('click',clear);\n\nvar toggle = function(e){\n\tif (dot == 0){\n\t\tw = 1;\n\t\th = 1;\n\t\tdot = 1;\n\t}\n\telse{\n\t\tw = 50;\n\t\th = 100;\n\t\tdot = 0;\n\t}\n};\n\nvar toggler = document.getElementById(\"switch\");\ntoggler.addEventListener('click',toggle);\n\n\nvar draw = function(e){\n\tconsole.log(\"(\" + e.clientX + \",\" + e.clientY + \")\");\n\tctx.fillRect(e.clientX - x, e.clientY - y, w,h);\n};\n\ncanvas.addEventListener('click',draw);\n" }, { "alpha_fraction": 0.5207546949386597, "alphanum_fraction": 0.5640251636505127, "avg_line_length": 31.317073822021484, "blob_id": "863c28dfdd64dbcb30b75a04e03663b3b12871e0", "content_id": "79af116eeaa57a1c86ed7f41c1272b6f9c2c9479", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3975, "license_type": "no_license", "max_line_length": 100, "num_lines": 123, "path": "/17_listcomp/work.py", "repo_name": "Trollicorn/SoftDev2", "src_encoding": "UTF-8", "text": "# Team Flute - Kevin Lin, Mohammed Uddin\n# SoftDev2 pd7\n# K17 -- PPFTLCW\n# 2019-04-15\n\ndef prob1loop(n):\n out = []\n for i in range(0, 2 * n, 2):\n out.append(str(i) * 2)\n return out\n\ndef prob1comp(n):\n return [str(i) * 2 for i in range(0, 2 * n, 2)]\n\ndef prob2loop(n):\n out = []\n for i in range(n):\n out.append(7 + i * 10)\n return out\n\ndef prob2comp(n):\n return [7 + i * 10 for i in range(n)]\n\ndef prob3loop(n):\n out = []\n for i in range(n):\n for j in range(3):\n out.append(i * j)\n return out\n\ndef prob3comp(n):\n return [i * j for i in range(n) for j in range(3)]\n\ndef prob4loop():\n composites = set()\n primes = []\n for i in range(2,101):\n if i in composites: #Check if number is already declared as a composite\n continue\n curr = 2 * i\n while curr < 101: #Eliminates all multiples of the prime from the sieve\n composites.add(curr)\n curr += i\n return sorted(list(composites))\n\ndef prob4comp():\n return [x for x in range(4,101) if len([1 for i in range(2, x) if x % i == 0]) != 0]\n\ndef prob5loop():\n composites = set()\n primes = [2]\n for i in range(3,101,2):\n if i in composites: #Check if number is already declared as a composite\n continue\n primes.append(i)\n curr = 2 * i\n while curr < 101: #Eliminates all multiples of the prime from the sieve\n composites.add(curr)\n curr += i\n return primes\n\ndef prob5comp():\n return [2] + [x for x in range(3,101,2) if len([1 for i in range(3, x, 2) if x % i == 0]) == 0]\n\ndef prob6loop(n):\n end = int(n ** .5 // 1) #Endpoint is sqrt(n)\n div = set()\n for i in range(1, end + 1):\n if n % i == 0: #Add divisor and quotient if divisible\n div.add(i)\n div.add(int(n / i))\n div = list(div)\n div.sort()\n return div\n\ndef prob6comp(n):\n return sorted(list({f(x) for x in range(1, int(n ** .5 // 1) + 1) #All numbers from 1 to sqrt(n)\n for f in (lambda x: x if n % x == 0 else None, #Run both functions on n\n lambda x: int(n / x) if n % x == 0 else None)\n if f(x) != None})) #Do not add x to the list if functions return None\n\ndef prob7loop(matrix):\n out = []\n for i in range(len(matrix[0])):\n out.append([]) #Empty lists to be filled\n for j in range(len(matrix)):\n out[i].append(matrix[j][i])\n return out\n\ndef prob7comp(matrix):\n return [[matrix[j][i] for j in range(len(matrix))] #Create list of a column of a matrix\n for i in range(len(matrix[0]))] #For every row in the matrix\n\ndef matrixToString(matrix):\n out = []\n for i in matrix:\n for j in i:\n out.append(str(j))\n out.append('\\t')\n out.append('\\n')\n return ''.join(out)\n\nmatrix = [[1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n [17, 18, 19, 20]]\n\nprint('Problem 1 Loop Result with n = 5:\\n' + str(prob1loop(5)), '\\n')\nprint('Problem 1 Comp Result with n = 5:\\n' + str(prob1comp(5)), '\\n')\nprint('Problem 2 Loop Result with n = 5:\\n' + str(prob2loop(5)), '\\n')\nprint('Problem 2 Comp Result with n = 5:\\n' + str(prob2comp(5)), '\\n')\nprint('Problem 3 Loop Result with n = 3:\\n' + str(prob3loop(3)), '\\n')\nprint('Problem 3 Comp Result with n = 3:\\n' + str(prob3comp(3)), '\\n')\nprint('Problem 4 Loop Result:\\n' + str(prob4loop()), '\\n')\nprint('Problem 4 Comp Result:\\n' + str(prob4comp()), '\\n')\nprint('Problem 5 Loop Result:\\n' + str(prob5loop()), '\\n')\nprint('Problem 5 Comp Result:\\n' + str(prob5comp()), '\\n')\nprint('Problem 6 Loop Result with n = 36:\\n' + str(prob6loop(36)), '\\n')\nprint('Problem 6 Comp Result with n = 36:\\n' + str(prob6comp(36)), '\\n')\nprint('Original Matrix:\\n' + matrixToString(matrix))\nprint('Problem 7 Loop Result:\\n' + matrixToString(prob7loop(matrix)))\nprint('Problem 7 Comp Result:\\n' + matrixToString(prob7comp(matrix)))\n" }, { "alpha_fraction": 0.5517241358757019, "alphanum_fraction": 0.610472559928894, "avg_line_length": 30.31999969482422, "blob_id": "c2b7a175630df0a54ff1624a288d03037a112feb", "content_id": "17afef6925d32ff89009614f3b7fcfea8290e45e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 783, "license_type": "no_license", "max_line_length": 77, "num_lines": 25, "path": "/19_listcomp/work.py", "repo_name": "Trollicorn/SoftDev2", "src_encoding": "UTF-8", "text": "#team arzeal mohammed uddin and the odor e peter\n#union\nu=lambda l,s:[i for i in s if i not in l]+l\nprint(u([1,2,3],[3,4,5]))\n#intersection\ni=lambda l,s:[i for i in s if i in l]\nprint(i([1,2,3],[3,4,5]))\n#set_difference\nd=lambda l,s:[i for i in l if i not in s]\nprint(d([1,2,3],[3,4,5]))\n#symmetry\nsd=lambda l,s:[i for i in s if i not in l]+[i for i in l if i not in s]\nprint(sd([1,2,3],[3,4,5]))\n#cartesian product\ncp=lambda l,s:[(i,j)for i in l for j in s]\nprint(cp([1,2,3],[3,4,5]))\n#this makes a matrix okok\nm=lambda l,s:[[i*j for i in l]for j in s]\nprint(m([1,2,3],[3,4,5]))\n# dot prod uctr\ndp=lambda l,s:sum(l[i]*s[i] for i in range(len(l)))if len(l)==len(s)else None\nprint(dp([1,2,3],[3,4,5]))\n# normalzieds a set\nnrmlz=lambda l:[i/(sum(j*j for j in l))**0.5 for i in l]\nprint(nrmlz([3,4]))\n" }, { "alpha_fraction": 0.7193300127983093, "alphanum_fraction": 0.7247623205184937, "avg_line_length": 16.65322494506836, "blob_id": "5b5fc37bec8c5dc4e233fe2d67d3eb84f6f7a8c4", "content_id": "de04526e48eb6bf4d4671d4b32f6621c8fbf53df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 2209, "license_type": "no_license", "max_line_length": 66, "num_lines": 124, "path": "/oofnotlct/notes.txt", "repo_name": "Trollicorn/SoftDev2", "src_encoding": "UTF-8", "text": "Aim: Memoization++ And Life Beyond\nDN: File yesterday's work under 23_memoization\n\ngj fellas u chose college now dont worry about other path\n\nMS = Morgan Stanley\nis investment bank\ninvestment bank have no retail component\nissa bank\n\nlots alumn at MS\noof finance crash phase out program\nwoah MS internship on again!!!\n\npick 20 of batch and they select 10 oof\nveri rare thing\nlook good on resume \n\nMS: resumes\n-action words\n-less is more\n-only list tech/lang if u know it\n-dont leave out tech/lang u know\n-appropriate email\n-PROOFREAD\n-goal of resume? (most important point(tooks lots of guesses))\n-need not fill page\n-name and contact info clear at top\n\naction words = passive vs active\nactive shows you did\n\ndont go over a page\n\nno lies bro thats bad\nso list stuff you know\n-can safely list java\n-also python\n-html,css,flask\n-js good too bro\n\nno forget listing stuff u know\nprofessional email -> your name @domain\n\nremember to put contact info\nclear and to the point\n\n\nJ\nO\nB\n\n-formal vs startup\n^attire-wise\n MS is formal, dress nicely\n-etiquette\n^very different in formal v startup\n-you rep StuyCS\n-eduWorld != workPlace\n-fdbk loop\n^ask for feedback without being annoying\n\n\nThe caching version:\ndef memoize(f):\n\tmemo = {}\n\tdef helper(x):\n\t\tif x not in memo:\n\t\t\tmemo[x] = f(x)\n\t\treturn memo[x]\n\treturn helper\n\ndef fib(n):\n\tif n==0:\n\t\treturn 0\n\telif n == 1:\n\t\treturn 1\n\telse:\n\treturn fib(n-1) + fib(n2)\n\nThe slicker version:\ndef memoize(f):\n\tmemo = {}\n\tdef helper(x)L\n\t\tif x not in memo:\n\t\t\tmemo[x] = f(x)\n\t\treturn memo[x]\n\treturn helper\n@memoize\ndef fib(\n\n\n\nN: ememoization advantages\n-retain expressive elgance of orig fib implementationi\n-gain dynamic programmin/cachign speed improvement\n\nN:when to memoize?\n-fxn is deterministic(\n\ndetour...\nQ:\n*args = lets u not specify argument, gives access to list of args \nie \ndef fxn(*args):\n\t...\n\na generalized memoizer:\ndef memoize(fxn):\n\tcache={}\n\tdef memoized fxn(*args):\n\t\tif args in cache:\n\t\t\treturn cache[args]\n\t\tresult = fxn(*args)\n\t\tcache[args] = result\n\t\treturn result\n\treturn memoized fxn\n\ntask:\nbrainstorm for final projects\n\nQ: what makes a good one?\n-scalability \n-utility (real-world applicabiltiy) [cool but need not]\n-simplicity \n-...\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" } ]
14
rbuerki/automate-campaign-druckfiles
https://github.com/rbuerki/automate-campaign-druckfiles
7698018d2d973da6a0c63e654e806854350ce5b7
02eade8b37f90739fa4761cb6f9ee46bab3af3f0
8b79e2ba7c37df82b41b71be6ccf943521206ad0
refs/heads/master
2022-12-15T18:46:58.856968
2020-09-09T16:14:42
2020-09-09T16:14:42
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7004844546318054, "alphanum_fraction": 0.713593602180481, "avg_line_length": 35.17525863647461, "blob_id": "11feb690d987449a7ded25778167dd0a17d7b320", "content_id": "be7823340c1a4838a840ef56b8aa4d07ae083c52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3509, "license_type": "no_license", "max_line_length": 221, "num_lines": 97, "path": "/README.md", "repo_name": "rbuerki/automate-campaign-druckfiles", "src_encoding": "UTF-8", "text": "# Application for generation of Campaign-\"Druckfiles\"\n\nAug 2020, Version 0.1\n\n## Introduction\n\nApp to convert zip files containing CSVs into XLSX-\"Druckfiles\", cleaning and validating the data during the process.\nAdditionally a \"feedback\" excel file is generated, documenting the problematic data entries and if they have been deleted or not.\n\n## Run\n\nThe app can be run from the main folder (containing this README file) by typing the following exemplary command in the CLI.\n\n```python\npython src -c \"TEST_1\" -p \"data/\"\n```\n\nThe command takes two parameters:\n\n- `-c` / `--campaign`: a string with the name of the campaign (used to create output_folders).\n- `-p` / `--path`: a string containing the path to the directory containing the input zip-files.\n\n(Note: multiple use of already existing path-campaign-combinations will overwrite the existing data.)\n\n## Output\n\nIn the `path` directory:\n\n- A new folder called `[campaign]_druckfiles` containing the processed XLSX-files for all input CSV files\n- A `feedback_[timestamp].xlsx` with overall count summary and a list of validated / cleaned data entries (on separate worksheet each)\n- A (for the moment) quite useless `log.log` (that could be further fleshed out in the future)\n\n## What has to be true?\n\nFor the app to work, following conditions have to be met:\n\n- The input files have to be stored as csv files within zip files in one directory (no matter how many zip files)\n- All input files have to be in csv format, you can not have other file formats within the zip files\n- All input files need to have at least the following columns:\n - `memberid`\n - `MemberName`\n - `MemberStatus`\n - `DeviceID`\n - `DataMatrix`\n - `AddressLine1`\n - `Street`\n - `PostBox`\n - `ZipCity`\n - `Email`\n\n## What get's done?\n\n1) Reading all csv files from all zip files into a dictionary of pd.DataFrames\n2) Initializing some output stuff, creating the output folder\n3) Iterating through each csv\n 1) Cleaning mail addressess using a regEX pattern and dropping all invalid addresses\n 2) Handle problematic data, listing members with ...\n 1) City but no Zip\n 2) Zip but no City\n 3) Zip and / or City but no address (--> street / post box / address line 1)\n 4) Address but no Zip and City --> ARE DELETED\n 5) No Adress, Zip and City --> ARE DELETED\n 6) Invalid DataMatrices (--> `memberid` / `DeviceID` not in string or non-numeric chars in string) --> ARE DELETED\n 7) Any kind of `employee` status\n 3) Saving each dataframe to XLSX in the `druckfiles` folder\n4) Saving the `feedback.xlsx`\n\n## Build\n\nThe application is built with Python 3.8 and only requires the following third-party libraries:\n\n- `numpy`\n- `pandas`\n- `xlsxwriter`\n\n## Testing and development\n\nA `tests` folder is set-up for unittesting with `pytest` but not fully implemented. Instead the testing has been performed with the `dev_notebook.ipynb` and towards completion of the project with the `test_notebook.ipynb`\n\nThere is a testfile `df_pytest.csv` in the `tests/data` folder containing 9 rows of data, prepared as follows:\n\n Mail cleaning:\n - 1 invalid email (row 4)\n\n Address checks:\n - 1 city_no_zip (row 0)\n - 1 zip_no_city (row 1)\n - 1 zipCity_no_address (row 2)\n - 1 address_no_zipCity (row 3) -> DELETE\n - 1 no_address_at_all (row 4) -> DELETE\n\n Matrix checks, 2 invalid matrices\n - 1 non-numeric (row 7) -> DELETE\n - 1 memberid not in matrix (row 8) -> DELETE\n\n Employee count:\n - 2 employees (rows 0, 1)\n" }, { "alpha_fraction": 0.7266666889190674, "alphanum_fraction": 0.7266666889190674, "avg_line_length": 28.799999237060547, "blob_id": "3edbe42dd42b9a76d4916a8625b72be2ff776dac", "content_id": "d153e616a9297cd00e6ee768fb37423f2a27bae9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 150, "license_type": "no_license", "max_line_length": 70, "num_lines": 5, "path": "/pytest.ini", "repo_name": "rbuerki/automate-campaign-druckfiles", "src_encoding": "UTF-8", "text": "[pytest]\n\naddopts = --color=yes --cov=src --cov-report=xml --cov-report=term -ra\n\nfilterwarnings = ignore:.*U.*mode is deprecated:DeprecationWarning\n\n" }, { "alpha_fraction": 0.6123265624046326, "alphanum_fraction": 0.6133937835693359, "avg_line_length": 25.77142906188965, "blob_id": "57e586ac2315dc0040998d48a694a7b1f8d65a6b", "content_id": "27b4299ad3261025bf873e92a03a357525f68717", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3748, "license_type": "no_license", "max_line_length": 88, "num_lines": 140, "path": "/src/__main__.py", "repo_name": "rbuerki/automate-campaign-druckfiles", "src_encoding": "UTF-8", "text": "import argparse\nimport datetime as dt\nimport logging\nimport os\nfrom typing import Any\n\n# from typing import List\n# from gooey import Gooey\nimport foos # noqa\n\n\n# INITIALIZE ARGPARSER\n\n\narg_parser = argparse.ArgumentParser(\n description=(\n \"Create XLSX Druckfiles for PKZ by passing a campaign name \"\n \" and the path containing the initial CSV zipfiles.\"\n )\n)\n\narg_parser.add_argument(\n \"-c\", \"--campaign\", help=\"Campaign name (str)\", type=str, nargs=1\n)\narg_parser.add_argument(\n \"-p\",\n \"--path\",\n help=\"Path to folder containing the zipfiles (str)\",\n type=str,\n nargs=1,\n)\n\n# INITIALIZE LOGGING\n\n\ndef initialize_logger(path):\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n\n # Create console handler\n sh = logging.StreamHandler()\n sh.setLevel(logging.INFO)\n logger.addHandler(sh)\n\n # Create file handler\n fh = logging.FileHandler(\n os.path.join(path, \"log.log\"), \"w\", encoding=None, delay=\"true\"\n )\n fh.setLevel(logging.DEBUG)\n formatter = logging.Formatter(\"%(levelname)s - %(message)s\")\n fh.setFormatter(formatter)\n logger.addHandler(fh)\n return logger\n\n\n# DEFINE MAIN\n\n\ndef main(campaign_name: str, path: str, logger: Any):\n\n logger.debug(f\"{campaign_name}\".upper())\n logger.debug(f\"{dt.datetime.strftime(dt.datetime.now(), '%Y-%m-%d, %H-%M-%S')}\\n\")\n\n out_path = foos.create_output_folder(campaign_name, path)\n (\n df_city_no_zip,\n df_zip_no_city,\n df_zipCity_no_address,\n df_address_no_zipCity,\n df_no_address_at_all,\n df_invalid_matrices,\n df_employees,\n ) = foos.initialize_output_dfs()\n\n df_dict = foos.create_dict_with_all_df(path)\n df_summary = foos.create_df_summary(df_dict)\n\n logger.info(f\"Success loading {len(df_dict)} segment files.\")\n\n for name, df in df_dict.items():\n\n logger.info(f\"Processing segment {name} ...\")\n\n df = foos.clean_email_column(df)\n\n df_address = foos.create_temp_df_for_address_handling(df)\n df_matrix = foos.create_temp_df_for_datamatrix_check(df)\n\n df_city_no_zip = foos.append_to_df_city_no_zip(df_address, name, df_city_no_zip)\n df_zip_no_city = foos.append_to_df_zip_no_city(df_address, name, df_zip_no_city)\n df_zipCity_no_address = foos.append_to_df_zipCity_no_address(\n df_address, name, df_zipCity_no_address\n )\n (\n df_address_no_zipCity,\n members_no_zipCity,\n ) = foos.append_to_df_address_no_zipCity(\n df_address, name, df_address_no_zipCity\n )\n (\n df_no_address_at_all,\n members_no_address_at_all,\n ) = foos.append_to_df_no_address_at_all(df_address, name, df_no_address_at_all)\n (\n df_invalid_matrices,\n members_with_invalid_matrices,\n ) = foos.append_to_df_invalid_matrices(df_matrix, name, df_invalid_matrices)\n df_employees = foos.append_to_df_employees(df, name, df_employees)\n\n df = foos.delete_problematic_entries(\n df,\n members_no_zipCity,\n members_no_address_at_all,\n members_with_invalid_matrices,\n )\n\n foos.save_df_to_excel(df, name, out_path)\n\n foos.save_feedback_xlsx(\n df_summary,\n df_city_no_zip,\n df_zip_no_city,\n df_zipCity_no_address,\n df_address_no_zipCity,\n df_no_address_at_all,\n df_invalid_matrices,\n df_employees,\n path,\n )\n\n logging.info(\"\\nAll complete!\")\n\n\nif __name__ == \"__main__\":\n args = arg_parser.parse_args()\n campaign_name = args.campaign[0]\n path = args.path[0]\n logger = initialize_logger(path)\n\n main(campaign_name, path, logger)\n" }, { "alpha_fraction": 0.5639019012451172, "alphanum_fraction": 0.5790297389030457, "avg_line_length": 24.223684310913086, "blob_id": "d8ca2775c105023c631e676f46f9b9f13117e2fb", "content_id": "f8da029b4e2e988dfb4b4dac7fb4e161c70a18f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1918, "license_type": "no_license", "max_line_length": 78, "num_lines": 76, "path": "/tests/test_foos.py", "repo_name": "rbuerki/automate-campaign-druckfiles", "src_encoding": "UTF-8", "text": "import os\n\nimport numpy as np\n\n# import pandas as pd\n\nfrom src import foos # noqa\n\ncampaign_name = \"INM_unittest\"\npath = r\"tests/data/\"\n\n\ndef test_create_output_folder(campaign_name, path):\n out_path = foos.create_output_folder(campaign_name, path)\n assert os.path.exists(out_path)\n\n\ndef test_initialize_output_dfs():\n (\n df_city_no_zip,\n df_zip_no_city,\n df_zipCity_no_address,\n df_address_no_zipCity,\n df_no_address_at_all,\n df_invalid_matrices,\n df_employees,\n ) = foos.initialize_output_dfs()\n assert df_city_no_zip.shape[1] == 3\n assert df_zip_no_city.shape[1] == 3\n assert df_zipCity_no_address.shape[1] == 3\n assert df_address_no_zipCity.shape[1] == 3\n assert df_no_address_at_all.shape[1] == 3\n assert df_invalid_matrices.shape[1] == 4\n assert df_employees.shape[1] == 5\n\n\ndef test__load_csv_into_df():\n df_pytest = foos._load_csv_into_df(\"/data/df_pytest.csv\", \"df_pytest.csv\")\n assert df_pytest.shape[0] == 8\n\n\ndef test_clean_email_column(df_pytest):\n df_pytest = foos.clean_email_column(df_pytest)\n assert df_pytest[\"Email\"].values == np.array(\n [\n \"lucamanes@yahoo.fr\",\n np.NaN,\n \"bruno.truessel@bluewin.ch\",\n np.NaN,\n np.NaN,\n np.NaN,\n np.NaN,\n \"sybille.theubet@bluewin.ch\",\n \"Mon.e.mail@gmx.com\",\n ]\n )\n\n\ndef test_create_temp_df_for_address_handling(df_pytest):\n df_address = foos.create_temp_df_for_address_handling(df_pytest)\n assert df_address.columns() == [\n \"memberid\",\n \"ZipCity\",\n \"AddressLine1\",\n \"PostBox\",\n \"Street\",\n \"zip\",\n \"city\",\n ]\n assert df_address.loc[8, \"zip\"] == 1203\n assert df_address.loc[8, \"city\"] == \"Genève\"\n\n\ndef test_append_to_df_city_no_zip(df_pytest):\n df = foos.append_to_df_city_no_zip(df_pytest)\n assert df[\"memberid\"].values == np.array([683415])\n" }, { "alpha_fraction": 0.6459537744522095, "alphanum_fraction": 0.676300585269928, "avg_line_length": 20.625, "blob_id": "984f03aa97887f14f012d3dd7eed9889faff3a78", "content_id": "edb4d61ae1072d61b4e1bcb51ab796286864fda8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 692, "license_type": "no_license", "max_line_length": 72, "num_lines": 32, "path": "/tests/conftest.py", "repo_name": "rbuerki/automate-campaign-druckfiles", "src_encoding": "UTF-8", "text": "# import numpy as np\n# import pandas as pd\n# import pytest\n\nimport os\nimport sys\n\nsys.path.append(os.path.dirname(os.path.realpath(__file__)) + \"/../src\")\n# sys.path.append(os.path.abspath(\"../src\"))\n\n\n\"\"\"\nThe file `df_pytest.csv` on which the unit tests are based,\ncontains 9 rows of data, prepared as follows:\n\nMail cleaning:\n- 1 invalid email (row 4)\n\nAddress checks:\n- 1 city_no_zip (row 0)\n- 1 zip_no_city (row 1)\n- 1 zipCity_no_address (row 2)\n- 1 address_no_zipCity (row 3) -> DELETE\n- 1 no_address_at_all (row 4) -> DELETE\n\nMatrix checks, 2 invalid matrices\n- 1 non-numeric (row 7) -> DELETE\n- 1 memberid not in matrix (row 8) -> DELETE\n\nEmployee count:\n- 2 employees (rows 0, 1)\n\"\"\"\n" }, { "alpha_fraction": 0.6348761320114136, "alphanum_fraction": 0.6378147602081299, "avg_line_length": 34.90647506713867, "blob_id": "e203268bfd648f8b8cc37073f81f1c446370180e", "content_id": "0d651f20aa5e937343e068af1ec4e0b2f5b4ea9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14973, "license_type": "no_license", "max_line_length": 88, "num_lines": 417, "path": "/src/foos.py", "repo_name": "rbuerki/automate-campaign-druckfiles", "src_encoding": "UTF-8", "text": "import datetime as dt\nimport glob\nimport os\nimport re\nfrom typing import Any, Dict, Set, Tuple\nfrom zipfile import ZipFile\n\nimport numpy as np\nimport pandas as pd\n\ncampaign_name = \"INM_TEST\"\npath = r\"tests/data/\"\n\n\ndef create_output_folder(campaign_name: str, path: str) -> str:\n \"\"\"Create a new folder for the resulting xlsx-files, using the same\n location where the input zip folders are stored and named using the\n campaign_name. Return the created output path.\n \"\"\"\n folder_name = \"\".join([campaign_name, \"_druckfiles\"])\n path = os.path.split(path)[0]\n out_path = os.path.join(path, folder_name)\n if not os.path.exists(out_path):\n os.makedirs(out_path)\n return out_path\n\n\ndef initialize_output_dfs() -> Tuple[pd.DataFrame]:\n \"\"\"Return a tuple of empty dataframes where problematic records\n will be stored for feedback.\n \"\"\"\n df_city_no_zip = pd.DataFrame(columns=[\"memberid\", \"source\", \"action\"])\n df_zip_no_city = pd.DataFrame(columns=[\"memberid\", \"source\", \"action\"])\n df_zipCity_no_address = pd.DataFrame(columns=[\"memberid\", \"source\", \"action\"])\n df_address_no_zipCity = pd.DataFrame(columns=[\"memberid\", \"source\", \"action\"])\n df_no_address_at_all = pd.DataFrame(columns=[\"memberid\", \"source\", \"action\"])\n df_invalid_matrices = pd.DataFrame(\n columns=[\"memberid\", \"DataMatrix\", \"source\", \"action\"]\n )\n df_employees = pd.DataFrame(\n columns=[\"memberid\", \"MemberName\", \"MemberStatus\", \"source\", \"action\"]\n )\n return (\n df_city_no_zip,\n df_zip_no_city,\n df_zipCity_no_address,\n df_address_no_zipCity,\n df_no_address_at_all,\n df_invalid_matrices,\n df_employees,\n )\n\n\ndef create_dict_with_all_df(path: str) -> Dict[str, pd.DataFrame]:\n \"\"\"Gobble up all zip folders in the given path and combine all\n their csv files in a dictionary with filename as key and dataframe\n as value.\"\"\"\n all_zips = glob.glob(os.path.join(path, \"*.zip\"))\n df_dict = {}\n for zip_ in all_zips:\n dfs = _return_dfs_from_zipfolder(zip_)\n # df_dict |= dfs # will work with Python 3.9\n df_dict = {**df_dict, **dfs}\n return df_dict\n\n\ndef _return_dfs_from_zipfolder(zip_path: str) -> Dict[str, pd.DataFrame]:\n \"\"\"Return a dictionary of filenames and dataframes for csv files\n inside a zip_folder. Pass the path to the zip folder as input. This\n function is called within `create_dict_with_all_df`.\n \"\"\"\n zipfolder = ZipFile(zip_path)\n df_dict = {}\n for csv_info in zipfolder.infolist():\n csv_name = csv_info.filename\n unzipped = zipfolder.open(csv_name)\n df = _load_csv_into_df(unzipped, csv_name)\n df_dict[csv_name] = df\n\n assert len(df_dict) == len(zipfolder.infolist()) # TODO: maybe check / log function\n\n return df_dict\n\n\ndef _load_csv_into_df(csv_file: Any, csv_name: str) -> pd.DataFrame:\n \"\"\"Load data from a csv file and return a dataframe. This function\n is called within `return_dfs_from_zipfolder`.\n \"\"\"\n try:\n df = pd.read_csv(csv_file, sep=\"|\", header=0, dtype=str, encoding=\"UTF-8\")\n except ValueError as e:\n print(f\"ERROR! Could not read the file {csv_name}: {e}\")\n raise\n return df\n\n\ndef create_df_summary(df_dict):\n \"\"\"Return a dataframe with overview of segments and member count.\"\"\"\n summary_list = []\n for name, df in df_dict.items():\n summary = {}\n summary[\"name\"] = name.split(\".\")[0]\n summary[\"n_members_at_load\"] = df.shape[0]\n summary_list.append(summary)\n df_summary = pd.DataFrame(summary_list, columns=[\"name\", \"n_members_at_load\"])\n\n super_summary = {\n \"name\": \"Total\",\n \"n_members_at_load\": df_summary[\"n_members_at_load\"].sum(),\n }\n df_summary = df_summary.append(super_summary, ignore_index=True)\n return df_summary\n\n\ndef clean_email_column(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Return a cleaned `Email` column where all entries with an\n invalid pattern are replaced by np.NaN.\n \"\"\"\n try:\n df[\"Email\"] = df[\"Email\"].apply(_clean_email_strings)\n return df\n except ValueError:\n print(\"'Email' column not found, please check the input file structures.\")\n\n\ndef _clean_email_strings(mail: str) -> str:\n \"\"\"Checks entries to `Email` column for pattern validity, if\n they are invalid the entry is replaced by np.NaN. This funcion\n is called within `clean_email_column`.\n \"\"\"\n MAIL_PATTERN = r\"[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\"\n regex_mail = re.compile(MAIL_PATTERN, flags=re.IGNORECASE)\n\n try:\n return regex_mail.findall(mail)[0]\n except IndexError: # set invalid values (return empty list) to NaN\n return np.NaN\n except TypeError: # handle missing values (findall() fails)\n return np.NaN\n\n\ndef create_temp_df_for_address_handling(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Return a dataframe with address columns only, split `ZipCity`\n into two columns `zip` and `city` using regex patterns.\n \"\"\"\n try:\n df_address = df[\n [\"memberid\", \"ZipCity\", \"AddressLine1\", \"PostBox\", \"Street\"]\n ].copy()\n except ValueError:\n print(\"Some address columns not found, please check the input file structures.\")\n\n df_address[\"zip\"] = df_address[\"ZipCity\"].apply(_get_zips)\n df_address[\"city\"] = df_address[\"ZipCity\"].apply(_get_cities)\n df_address[[\"zip\", \"city\"]] = df_address[[\"zip\", \"city\"]].replace(\"\", np.NaN)\n\n # Make sure all white-space only strings are set to np.nan\n return df_address.applymap(lambda x: np.nan if str(x).isspace() else x)\n\n\ndef _get_zips(x):\n \"\"\"Return numeric values from a sring.\"\"\"\n try:\n zip_ = re.sub(\"[^0-9]\", \"\", x)\n return zip_\n except TypeError:\n return np.NaN\n\n\ndef _get_cities(x):\n \"\"\"Return non-numeric values from a sring.\"\"\"\n try:\n city = re.sub(r\"[^[\\u00C0-\\u017FA-Za-z\\-\\.\\'\\s]\", \"\", x)\n return city\n except TypeError:\n return np.NaN\n\n\ndef append_to_df_city_no_zip(\n df_address: pd.DataFrame, name: str, df_city_no_zip: pd.DataFrame\n) -> pd.DataFrame:\n \"\"\"Append members with City but no Zip to the respective output df.\n (These members will NOT be deleted later on.)\n \"\"\"\n city_no_zip = df_address.loc[\n (df_address[\"zip\"].isnull()) & df_address[\"city\"].notnull()\n ][[\"memberid\"]]\n city_no_zip[\"source\"] = name\n city_no_zip[\"action\"] = \"not deleted\"\n df_city_no_zip = pd.concat([df_city_no_zip, city_no_zip], ignore_index=True)\n return df_city_no_zip.drop_duplicates()\n\n\ndef append_to_df_zip_no_city(\n df_address: pd.DataFrame, name: str, df_zip_no_city: pd.DataFrame\n) -> pd.DataFrame:\n \"\"\"Append members with Zip but no City to the respective output df.\n (These members will NOT be deleted later on.)\n \"\"\"\n zip_no_city = df_address.loc[\n (df_address[\"city\"].isnull()) & df_address[\"zip\"].notnull()\n ][[\"memberid\"]]\n zip_no_city[\"source\"] = name\n zip_no_city[\"action\"] = \"not deleted\"\n df_city_no_zip = pd.concat([df_zip_no_city, zip_no_city], ignore_index=True)\n return df_city_no_zip.drop_duplicates()\n\n\ndef append_to_df_zipCity_no_address(\n df_address: pd.DataFrame, name: str, df_zipCity_no_address: pd.DataFrame\n) -> pd.DataFrame:\n \"\"\"Append members with Zip & City but no other address parts to the\n respective output df. (These members will NOT be deleted later on.)\n \"\"\"\n zipCity_no_address = df_address.loc[\n (df_address[\"city\"].notnull())\n & (df_address[\"zip\"].notnull())\n & (df_address[\"AddressLine1\"].isnull())\n & (df_address[\"PostBox\"].isnull())\n & (df_address[\"Street\"].isnull())\n ][[\"memberid\"]]\n zipCity_no_address[\"source\"] = name\n zipCity_no_address[\"action\"] = \"not deleted\"\n df_zipCity_no_address = pd.concat(\n [df_zipCity_no_address, zipCity_no_address], ignore_index=True\n )\n return df_zipCity_no_address.drop_duplicates()\n\n\ndef append_to_df_address_no_zipCity(\n df_address: pd.DataFrame, name: str, df_address_no_zipCity: pd.DataFrame\n) -> pd.DataFrame:\n \"\"\"Append members without Zip & City but other address parts to the\n respective output df. (These members will be DELETED later on. That's\n why we also return a set of the respective member ids.)\n \"\"\"\n address_no_zipCity = df_address.loc[\n (df_address[\"ZipCity\"].isnull())\n & (\n (df_address[\"AddressLine1\"].notnull())\n | (df_address[\"PostBox\"].notnull())\n | (df_address[\"Street\"].notnull())\n )\n ][[\"memberid\"]]\n address_no_zipCity[\"source\"] = name\n address_no_zipCity[\"action\"] = \"DELETED\"\n df_address_no_zipCity = pd.concat(\n [df_address_no_zipCity, address_no_zipCity], ignore_index=True\n )\n return (\n df_address_no_zipCity.drop_duplicates(),\n set(address_no_zipCity[\"memberid\"].tolist()),\n )\n\n\ndef append_to_df_no_address_at_all(\n df_address: pd.DataFrame, name: str, df_no_address_at_all: pd.DataFrame\n) -> pd.DataFrame:\n \"\"\"Append members with no address info at all to the respective\n output df. (These members will be DELETED later on. That's why\n we also return a set of the respective member ids.)\n \"\"\"\n no_address_at_all = df_address.loc[\n (df_address[\"ZipCity\"].isnull())\n & (df_address[\"AddressLine1\"].isnull())\n & (df_address[\"PostBox\"].isnull())\n & (df_address[\"Street\"].isnull())\n ][[\"memberid\"]]\n no_address_at_all[\"source\"] = name\n no_address_at_all[\"action\"] = \"DELETED\"\n df_no_address_at_all = pd.concat(\n [df_no_address_at_all, no_address_at_all], ignore_index=True\n )\n return (\n df_no_address_at_all.drop_duplicates(),\n set(no_address_at_all[\"memberid\"].tolist()),\n )\n\n\ndef create_temp_df_for_datamatrix_check(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Return a dataframe with datamatrix-relevant columns only.\"\"\"\n try:\n df_matrix = df[[\"memberid\", \"DeviceID\", \"DataMatrix\"]].copy()\n except ValueError:\n print(\n (\n \"Some matrix-relevant columns not found, \",\n \"please check the input file structures.\",\n )\n )\n return df_matrix\n\n\ndef append_to_df_invalid_matrices(\n df_matrix: pd.DataFrame, name: str, df_invalid_matrices: pd.DataFrame\n) -> pd.DataFrame:\n \"\"\"Append members with invalid datamatrix to the respective output df.\n (These members will be DELETED later on. That's why we also return a\n set of the respective member ids.)\n \"\"\"\n members_with_invalid_matrices = _get_members_with_invalid_matrices(df_matrix)\n invalid_matrices = df_matrix.loc[\n df_matrix[\"memberid\"].isin(members_with_invalid_matrices)\n ][[\"memberid\", \"DataMatrix\"]]\n invalid_matrices[\"source\"] = name\n invalid_matrices[\"action\"] = \"DELETED\"\n df_invalid_matrices = pd.concat(\n [df_invalid_matrices, invalid_matrices], ignore_index=True\n )\n return (\n df_invalid_matrices.drop_duplicates(),\n members_with_invalid_matrices,\n )\n\n\ndef _get_members_with_invalid_matrices(df_matrix: pd.DataFrame) -> Set:\n \"\"\"Check if `memberid` and `DeviceID` are in datamatrix and that\n the datamatrix contains only numeric characters. Return a set of\n `memberid` where the matrix is invalid. This function is called\n within `append_to_df_invalid_matrices`.\n \"\"\"\n members_with_invalid_data = []\n for row in df_matrix.itertuples(index=False):\n if not row[0] in row[2] or not row[1] in row[2] or not row[2].isnumeric():\n members_with_invalid_data.append(row[0])\n return set(members_with_invalid_data)\n\n\ndef append_to_df_employees(\n df: pd.DataFrame, name: str, df_employees: pd.DataFrame\n) -> pd.DataFrame:\n \"\"\"Append members with employee status to the respective output df.\n (These members will NOT be deleted later on.)\n \"\"\"\n employees = df.loc[\n df[\"MemberStatus\"].str.endswith(\"Employee\") == True # noqa E712\n ][[\"memberid\", \"MemberName\", \"MemberStatus\"]]\n employees[\"source\"] = name\n employees[\"action\"] = \"not_deleted\"\n df_employees = pd.concat([df_employees, employees], ignore_index=True)\n return df_employees.drop_duplicates()\n\n\ndef delete_problematic_entries(\n df: pd.DataFrame,\n members_no_address_at_all: Set,\n members_no_zipCity: Set,\n members_with_invalid_matrices: Set,\n) -> pd.DataFrame:\n \"\"\"Return dataframe where all members that have to be deleted\n because of invalid addresses or datamatrices are eliminated.\n \"\"\"\n members_to_delete = members_no_address_at_all.union(members_no_zipCity).union(\n members_with_invalid_matrices\n )\n\n df = df.loc[~df[\"memberid\"].isin(members_to_delete)]\n return df\n\n\ndef save_df_to_excel(df: pd.DataFrame, name: str, out_path: str):\n \"\"\"Save transformed dataframe to excel, with all values to string.\"\"\"\n df = df.applymap(lambda x: str(x))\n df = df.replace(\"nan\", \"\")\n sheetname = name.rpartition(\".\")[0]\n filename = name.replace(\"csv\", \"xlsx\")\n full_path = os.path.join(out_path, filename)\n writer = pd.ExcelWriter(full_path, engine=\"xlsxwriter\")\n df.to_excel(\n writer,\n sheet_name=sheetname,\n index=False,\n engine=\"xlsxwriter\",\n encoding=\"UTF-8\",\n )\n\n # Setting col witdh to max_len of col values + 1, with a min of 15\n sheet = writer.sheets[sheetname] # for\n for pos, col in enumerate(df):\n max_len = df[col].astype(str).map(len).max()\n sheet.set_column(pos, pos, max([15, max_len + 1]))\n\n writer.save()\n\n\ndef save_feedback_xlsx(\n df_summary: pd.DataFrame,\n df_city_no_zip: pd.DataFrame,\n df_zip_no_city: pd.DataFrame,\n df_zipCity_no_address: pd.DataFrame,\n df_address_no_zipCity: pd.DataFrame,\n df_no_address_at_all: pd.DataFrame,\n df_invalid_matrices: pd.DataFrame,\n df_employees: pd.DataFrame,\n path: str,\n):\n \"\"\"Create and save an excel file with all problematic entries, one\n sheet per dataframe.\n \"\"\"\n full_path = os.path.join(\n path,\n f\"feedback_{dt.datetime.strftime(dt.datetime.now(), '%Y-%m-%d-%H-%M-%S')}.xlsx\",\n )\n writer = pd.ExcelWriter(full_path, engine=\"xlsxwriter\")\n df_summary.to_excel(writer, sheet_name=\"SUMMARY\", index=False)\n df_invalid_matrices.to_excel(writer, sheet_name=\"invalid_matrices\", index=False)\n df_address_no_zipCity.to_excel(writer, sheet_name=\"address_no_zipCity\", index=False)\n df_no_address_at_all.to_excel(writer, sheet_name=\"no_address_at_all\", index=False)\n df_zipCity_no_address.to_excel(writer, sheet_name=\"zipCity_no_address\", index=False)\n df_zip_no_city.to_excel(writer, sheet_name=\"zip_no_city\", index=False)\n df_city_no_zip.to_excel(writer, sheet_name=\"city_no_zip\", index=False)\n df_employees.to_excel(writer, sheet_name=\"employees\", index=False)\n\n for sheet in writer.sheets.values():\n sheet.set_column(\"A:E\", 35)\n\n writer.save()\n" } ]
6
leonardoribeiro1505/Restasys
https://github.com/leonardoribeiro1505/Restasys
5ec60a86091bce5980a1aa26b78fcaed13c94aed
b42a6b37cb2f57084fa987b30746862d0051810f
60cc1fcdcca38b246113d53ee982a26a71c830e0
refs/heads/master
2021-06-03T00:09:50.618803
2016-06-03T17:38:32
2016-06-03T17:38:32
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6324042081832886, "alphanum_fraction": 0.6324042081832886, "avg_line_length": 21.076923370361328, "blob_id": "0aa6b4fc24872899a2259ea343951339a8624f6d", "content_id": "8def068fe1a91d1d4ed76881893e4c239bc9aa7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 574, "license_type": "no_license", "max_line_length": 59, "num_lines": 26, "path": "/restasysapp/forms.py", "repo_name": "leonardoribeiro1505/Restasys", "src_encoding": "UTF-8", "text": "from django import forms\nfrom .models import Mesa, Pratos, Pedidos, Pedidos_Fechados\n\nclass MesaForm(forms.ModelForm):\n\n class Meta:\n model = Mesa\n fields = ('numero',)\n\nclass PratosForm(forms.ModelForm):\n\n class Meta:\n model = Pratos\n fields = ('nome', 'valor', 'ingredientes')\n\nclass PedidosForm(forms.ModelForm):\n\n class Meta:\n model = Pedidos\n fields = ('mesa_id', 'pratos_id', 'valor_total')\n\nclass PedidoFechadoForm(forms.ModelForm):\n\n class Meta:\n model = Pedidos_Fechados\n fields = ('pedidos_id',)\n" }, { "alpha_fraction": 0.656753420829773, "alphanum_fraction": 0.6716232895851135, "avg_line_length": 26.827587127685547, "blob_id": "7347220d71bb9a17c3d1b9117b47b06be472d47a", "content_id": "7c970a9d4384ab5ea70fe0c6c14e42f9682e19bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 807, "license_type": "no_license", "max_line_length": 69, "num_lines": 29, "path": "/restasysapp/models.py", "repo_name": "leonardoribeiro1505/Restasys", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass Mesa(models.Model):\n numero = models.CharField(max_length=10)\n\n def __str__(self):\n return self.numero\n\nclass Pratos(models.Model):\n nome = models.CharField(max_length=100)\n valor = models.DecimalField(max_digits=5, decimal_places=2)\n ingredientes = models.CharField(max_length=500)\n\n def __str__(self):\n return self.nome\n\nclass Pedidos(models.Model):\n mesa_id = models.ForeignKey('Mesa')\n pratos_id = models.ForeignKey('Pratos')\n valor_total = models.DecimalField(max_digits=5, decimal_places=2)\n\n def __str__(self):\n return self.mesa_id.numero+\" - \"+self.pratos_id.nome\n\nclass Pedidos_Fechados(models.Model):\n pedidos_id = models.ForeignKey('Pedidos')\n\n def __str__(self):\n return self.pedidos_id.mesa_id\n" }, { "alpha_fraction": 0.6268267035484314, "alphanum_fraction": 0.6323068737983704, "avg_line_length": 33.21428680419922, "blob_id": "56be588ef5b20caff9f77df89f6fcae0183acf55", "content_id": "4c229249101d2750614e189ebf8e86e0b63e8226", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3832, "license_type": "no_license", "max_line_length": 91, "num_lines": 112, "path": "/restasysapp/views.py", "repo_name": "leonardoribeiro1505/Restasys", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, get_object_or_404\n\nfrom .models import Mesa, Pratos, Pedidos, Pedidos_Fechados\nfrom .forms import MesaForm, PratosForm, PedidosForm, PedidoFechadoForm\n\n\ndef index(request):\n return render(request, 'restasysapp/home.html', {})\n\ndef mesa_novo(request):\n if request.method == \"POST\":\n form = MesaForm(request.POST)\n if form.is_valid():\n mesa = form.save()\n form = MesaForm()\n else:\n form = MesaForm()\n return render(request, 'restasysapp/mesa_novo.html', {'form': form})\n\ndef prato_novo(request):\n if request.method == \"POST\":\n form = PratosForm(request.POST)\n if form.is_valid():\n pratos = form.save()\n form = PratosForm()\n else:\n form = PratosForm()\n return render(request, 'restasysapp/prato_novo.html', {'form': form})\n\ndef pedido_novo(request):\n if request.method == \"POST\":\n form = PedidosForm(request.POST)\n if form.is_valid():\n pedidos = form.save()\n form = PedidosForm()\n else:\n form = PedidosForm()\n return render(request, 'restasysapp/pedido_novo.html', {'form': form})\n\ndef mesa_list(request):\n mesas = Mesa.objects.all()\n return render(request, 'restasysapp/mesa_list.html', {'mesas':mesas})\n\ndef pratos_list(request):\n pratos = Pratos.objects.all()\n return render(request, 'restasysapp/pratos_list.html', {'pratos':pratos})\n\ndef pedidos_list(request):\n pedidos = Pedidos.objects.all()\n return render(request, 'restasysapp/pedidos_list.html', {'pedidos':pedidos})\n\ndef mesa_detalhe(request, pk):\n mesa = get_object_or_404(Mesa, pk=pk)\n return render(request, 'restasysapp/mesa_detalhe.html', {'mesa':mesa})\n\ndef mesa_editar(request, pk):\n mesa = get_object_or_404(Mesa, pk=pk)\n if request.method == \"POST\":\n form = MesaForm(request.POST, instance=mesa)\n if form.is_valid():\n mesa = form.save(commit=False)\n mesa = form.save()\n form = MesaForm()\n else:\n form = MesaForm(instance=mesa)\n return render(request, 'restasysapp/mesa_novo.html', {'form': form})\n\ndef prato_detalhe(request, pk):\n prato = get_object_or_404(Pratos, pk=pk)\n return render(request, 'restasysapp/prato_detalhe.html', {'prato':prato})\n\ndef prato_editar(request, pk):\n prato = get_object_or_404(Pratos, pk=pk)\n if request.method == \"POST\":\n form = PratosForm(request.POST, instance=prato)\n if form.is_valid():\n prato = form.save(commit=False)\n prato = form.save()\n form = PratosForm()\n else:\n form = PratosForm(instance=prato)\n return render(request, 'restasysapp/prato_novo.html', {'form': form})\n\ndef pedido_detalhe(request, pk):\n pedido = get_object_or_404(Pedidos, pk=pk)\n return render(request, 'restasysapp/pedido_detalhe.html', {'pedido':pedido})\n\ndef pedido_editar(request, pk):\n pedido = get_object_or_404(Pedidos, pk=pk)\n if request.method == \"POST\":\n form = PedidosForm(request.POST, instance=pedido)\n if form.is_valid():\n pedido = form.save(commit=False)\n pedido = form.save()\n form = PedidosForm()\n else:\n form = PedidosForm(instance=pedido)\n return render(request, 'restasysapp/pedido_novo.html', {'form': form})\n\ndef fechar_pedido(request):\n if request.method == \"POST\":\n form = PedidoFechadoForm(request.POST)\n if form.is_valid():\n fechar = form.save()\n form = PedidoFechadoForm()\n else:\n form = PedidoFechadoForm()\n return render(request, 'restasysapp/fechar_pedido.html', {'form': form})\n\ndef fechado_list(request):\n fechados = Pedidos_Fechados.objects.all()\n return render(request, 'restasysapp/pedidos_fechados_list.html', {'fechados':fechados})\n" }, { "alpha_fraction": 0.6024321913719177, "alphanum_fraction": 0.6136576533317566, "avg_line_length": 47.59090805053711, "blob_id": "3547a55832dfbca4c2d01ba89af58f0cf97b4f40", "content_id": "753fd43b0cdaf2aea3c4fb332332b99e13ca393a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1069, "license_type": "no_license", "max_line_length": 85, "num_lines": 22, "path": "/restasysapp/urls.py", "repo_name": "leonardoribeiro1505/Restasys", "src_encoding": "UTF-8", "text": "from django.conf.urls import include, url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index),\n url(r'^mesa/novo/$', views.mesa_novo, name='mesa_novo'),\n url(r'^prato/novo/$', views.prato_novo, name='prato_novo'),\n url(r'^pedido/novo/$', views.pedido_novo, name='pedido_novo'),\n url(r'^mesa/list/$', views.mesa_list, name='mesa_list'),\n url(r'^pratos/list/$', views.pratos_list, name='pratos_list'),\n url(r'^pedidos/list/$', views.pedidos_list, name='pedidos_list'),\n url(r'^mesa/(?P<pk>[0-9]+)/$', views.mesa_detalhe),\n url(r'^mesa/(?P<pk>[0-9]+)/edit/$', views.mesa_editar, name='mesa_editar'),\n url(r'^prato/(?P<pk>[0-9]+)/$', views.prato_detalhe),\n url(r'^prato/(?P<pk>[0-9]+)/edit/$', views.prato_editar, name='prato_editar'),\n url(r'^pedido/(?P<pk>[0-9]+)/$', views.pedido_detalhe),\n url(r'^pedido/(?P<pk>[0-9]+)/edit/$', views.pedido_editar, name='pedido_editar'),\n url(r'^pedido/fechar/$', views.fechar_pedido, name='fechar_pedido'),\n url(r'^fechados/list/$', views.fechado_list, name='fechado_list'),\n\n\n]\n" }, { "alpha_fraction": 0.530913233757019, "alphanum_fraction": 0.5382869839668274, "avg_line_length": 34.979591369628906, "blob_id": "544c80d46f17746675e732d4a997a102bf5dd194", "content_id": "8b6471c6a1b21572718459530ffa0c085b7cf37a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1763, "license_type": "no_license", "max_line_length": 114, "num_lines": 49, "path": "/restasysapp/migrations/0001_initial.py", "repo_name": "leonardoribeiro1505/Restasys", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Mesa',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('numero', models.CharField(max_length=10)),\n ],\n ),\n migrations.CreateModel(\n name='Pedidos',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('valor_total', models.DecimalField(decimal_places=2, max_digits=5)),\n ('mesa_id', models.ForeignKey(to='restasysapp.Mesa')),\n ],\n ),\n migrations.CreateModel(\n name='Pedidos_Fechados',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('pedidos_id', models.ForeignKey(to='restasysapp.Pedidos')),\n ],\n ),\n migrations.CreateModel(\n name='Pratos',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('nome', models.CharField(max_length=100)),\n ('valor', models.DecimalField(decimal_places=2, max_digits=5)),\n ('ingredientes', models.CharField(max_length=500)),\n ],\n ),\n migrations.AddField(\n model_name='pedidos',\n name='pratos_id',\n field=models.ForeignKey(to='restasysapp.Pratos'),\n ),\n ]\n" }, { "alpha_fraction": 0.8186046481132507, "alphanum_fraction": 0.8186046481132507, "avg_line_length": 29.714284896850586, "blob_id": "86d57fb179a648ac2e8308927dd2680a1e5c358b", "content_id": "120638db66c8d39414cacc63afd2f574e7cf90b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 215, "license_type": "no_license", "max_line_length": 59, "num_lines": 7, "path": "/restasysapp/admin.py", "repo_name": "leonardoribeiro1505/Restasys", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Mesa, Pratos, Pedidos, Pedidos_Fechados\n\nadmin.site.register(Mesa)\nadmin.site.register(Pratos)\nadmin.site.register(Pedidos)\nadmin.site.register(Pedidos_Fechados)\n" } ]
6
RightToResearch/django-opencon2016-app
https://github.com/RightToResearch/django-opencon2016-app
acc54bd800c957cb17dd2529014ab14305e7509a
8f8deb5ee61ed5ebd22a6eb7c0cf2d9a7ea01f1c
e46bd0577bc6e3c12a356e3305735d1ffa23767c
refs/heads/master
2020-12-24T10:55:03.157485
2016-11-07T21:21:09
2016-11-07T21:21:09
73,121,381
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.627312958240509, "alphanum_fraction": 0.6311343312263489, "avg_line_length": 35.02898406982422, "blob_id": "5d45c41de8b389ad4769f4f062b38620fd40ca3e", "content_id": "7df73858d7837b199bc56889a840e1bde37820e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9944, "license_type": "permissive", "max_line_length": 119, "num_lines": 276, "path": "/web/src/application/views.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "import json\nimport pytz\n\nfrom datetime import datetime\n\nfrom dal import autocomplete\nfrom django.conf import settings\nfrom django.core.urlresolvers import Http404\nfrom django.db.models import Q\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.core.urlresolvers import reverse_lazy, reverse\nfrom django.views.generic import FormView, TemplateView\nfrom django.utils import timezone\n\nfrom .forms import ApplicationForm\nfrom .helpers import is_valid_email_address\nfrom .models import Airport, Draft, Application, Institution, Organization, Country, Reference\nfrom . import constants\n\n\n# todo: find better solution for prefilling fields!\ndef post_to_json(post):\n dictionary = {}\n for key in post.keys():\n data = post.getlist(key)\n dictionary[key] = data\n return json.dumps(dictionary)\n\n\nfrom .models import MULTIFIELD_NAMES\ndef load_json_to_initial(data):\n global MULTIFIELD_NAMES\n MULTIFIELD_NAMES += ['skills_0', 'gender_0', 'how_did_you_find_out_0', ]\n for key in data.keys():\n if key not in MULTIFIELD_NAMES:\n data[key] = data[key][0]\n\n data['skills'] = [data.get('skills_0', ''), data.get('skills_1', '')]\n data['gender'] = [data.get('gender_0', ''), data.get('gender_1', '')]\n data['how_did_you_find_out'] = [data.get('how_did_you_find_out_0', ''), data.get('how_did_you_find_out_1', '')]\n\n return data\n\n\nclass ApplicationView(FormView):\n \"\"\"View shows the application itself\"\"\"\n form_class = ApplicationForm\n template_name = 'application/application_form.html'\n\n def get_referral(self, referral=None):\n if referral is None or not Reference.objects.filter(key=referral).exists():\n return {}\n reference = Reference.objects.get(key=referral)\n return {\n 'image': reference.image,\n 'name': reference.name,\n 'text': reference.text,\n }\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context.update({\n 'action_url': self.request.get_full_path(),\n 'organization': self.get_referral(self.kwargs.get('referral')),\n })\n return context\n\n def get_success_url(self):\n \"\"\"Get the success url with the right primary key so a customized thank you message can be shown\"\"\"\n application_pk = self.application.pk\n return reverse('application:thank_you', kwargs={'pk': application_pk})\n\n def remove_form_errors(self, form):\n \"\"\"Removes the errors from the form except for email and acknowledgement which is required for draft as well\"\"\"\n for field in form:\n if field.name in ['email', 'acknowledgements']:\n continue\n form.errors[field.name] = form.error_class()\n return form\n\n def save_draft(self, form):\n \"\"\"\n Tries to save the draft. Checks whether the email and acknowledgement is valid.\n Returns the whether the draft was saved, the form itself and the the draft if it was created.\n \"\"\"\n form = self.remove_form_errors(form)\n\n email = form.data['email']\n acknowledgements = form.data.getlist('acknowledgements')\n\n if is_valid_email_address(email) and len(acknowledgements) == 4:\n draft, created = Draft.objects.get_or_create(email=email)\n if created:\n draft.data = post_to_json(self.request.POST)\n draft.save()\n return True, form, draft\n\n form.add_error('email', 'An draft application associated with your e-mail address has '\n 'already been saved on our servers. If you cannot access it, contact us. ')\n return False, form, None\n\n def is_after_deadline(self):\n deadline_unaware = datetime.strptime(constants.APPLICATION_DEADLINE, '%Y/%m/%d %H:%M')\n deadline = pytz.utc.localize(deadline_unaware)\n\n referral = self.kwargs.get('referral', '')\n\n try:\n reference = Reference.objects.get(key=referral)\n if reference.deadline:\n deadline = reference.deadline\n except Reference.DoesNotExist:\n pass\n\n return timezone.now() > deadline\n\n def form_invalid(self, form):\n \"\"\"\n Handles the form when it's invalid. For save,\n it tries to save a draft for submit it invokes super().form_invalid()\n \"\"\"\n if '_save' in self.request.POST:\n valid, form, draft = self.save_draft(form)\n if valid:\n return render(self.request, 'application/form_saved.html', {'draft': draft})\n return super().form_invalid(form)\n\n def form_valid(self, form):\n \"\"\"\n If the form was saved, it saves a draft and renders a info message.\n If the form was submitted, it saves it and set a inactive flag for draft.\n \"\"\"\n if '_save' in self.request.POST:\n _, _, draft = self.save_draft(form)\n return render(self.request, 'application/form_saved.html', {'draft': draft})\n elif '_submit':\n self.application = form.save()\n email = form.data['email']\n if Draft.objects.filter(email=email).exists():\n draft = Draft.objects.get(email=email)\n draft.inactive = True\n draft.save()\n return super().form_valid(form)\n\n def dispatch(self, request, *args, **kwargs):\n if self.is_after_deadline():\n return redirect(settings.REDIRECT_URL)\n\n return super().dispatch(request, *args, **kwargs)\n\n\nclass PreFilledApplicationView(ApplicationView):\n \"\"\"View for handling the application with prefilled data from draft\"\"\"\n def get_draft(self):\n \"\"\"Gets the draft based on uuid and raises a 404 if the draft does not exists\"\"\"\n try:\n draft_uuid = self.kwargs.get('uuid')\n draft = Draft.all_objects.get(uuid=draft_uuid)\n return draft\n except (ValueError, Draft.DoesNotExist):\n raise Http404\n\n def save_draft(self, form):\n \"\"\"Saves the draft and makes sure the email wasn't changed\"\"\"\n form = self.remove_form_errors(form)\n draft_uuid = self.kwargs.get('uuid')\n draft = Draft.objects.get(uuid=draft_uuid)\n\n # Do not change email doesn't matter what\n mutable = self.request.POST._mutable\n self.request.POST._mutable = True\n self.request.POST['email'] = draft.email\n self.request.POST._mutable = mutable\n draft.data = post_to_json(self.request.POST)\n draft.save()\n return True, form, draft\n\n def get_initial(self):\n \"\"\"Loads the initial data from draft\"\"\"\n draft = self.get_draft()\n draft_data = json.loads(draft.data)\n return load_json_to_initial(draft_data)\n\n def get(self, request, uuid, *args, **kwargs):\n draft = self.get_draft()\n if draft.inactive:\n return render(self.request, 'application/already_submitted.html', {})\n return super().get(request, *args, **kwargs)\n\n def dispatch(self, request, *args, **kwargs):\n data = json.loads(self.get_draft().data)\n referral = data.get('referred_by', [''])[0]\n self.kwargs['referral'] = referral\n return super().dispatch(request, *args, **kwargs)\n\n\nclass ReferralApplicationView(ApplicationView):\n \"\"\"View shows the application with referral code\"\"\"\n def get_initial(self):\n referral = self.kwargs.get('referral')\n return {'referred_by': referral}\n\n\ndef check_email(request, email):\n if Application.objects.filter(email=email).exists():\n context = {}\n return render(request, 'application/popup_already_submitted.html', context)\n\n if Draft.objects.filter(email=email).exists():\n context = {'draft': Draft.objects.get(email=email)}\n return render(request, 'application/popup_saved_draft.html', context)\n\n context = {}\n return render(request, 'application/popup_alright.html', context)\n\n\ndef send_email(request, email):\n draft = get_object_or_404(Draft, email=email)\n status = draft.send_access()\n if status:\n template_name = 'application/access_sent.html'\n else:\n template_name = 'application/access_not_sent.html'\n return render(request, template_name, {})\n\n\nclass AirportAutocomplete(autocomplete.Select2QuerySetView):\n def get_queryset(self):\n qs = Airport.objects.all()\n if self.q:\n qs = qs.filter(Q(name__icontains=self.q) | Q(iata_code__istartswith=self.q))\n return qs\n\n\nclass InstitutionAutocomplete(autocomplete.Select2QuerySetView):\n def has_add_permission(self, request):\n return True\n\n def get_queryset(self):\n qs = Institution.objects.filter(show=True)\n if self.q:\n qs = qs.filter(Q(name__icontains=self.q))\n return qs\n\n\nclass OrganizationAutocomplete(autocomplete.Select2QuerySetView):\n def has_add_permission(self, request):\n return True\n\n def get_queryset(self):\n qs = Organization.objects.filter(show=True)\n if self.q:\n qs = qs.filter(Q(name__icontains=self.q))\n return qs\n\n\nclass CountryAutocomplete(autocomplete.Select2QuerySetView):\n def get_queryset(self):\n qs = Country.objects.all()\n if self.q:\n qs = qs.filter(Q(name__icontains=self.q))\n return qs\n\n\nclass ThankYou(TemplateView):\n template_name = 'application/thank_you.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context.update({'application': self.application})\n return context\n\n def get(self, request, pk, *args, **kwargs):\n self.application = get_object_or_404(Application, pk=pk)\n return redirect('http://www.opencon2016.org/thank_you?referral=' + str(self.application.my_referral))\n # return super().get(request, *args, **kwargs)\n" }, { "alpha_fraction": 0.694915235042572, "alphanum_fraction": 0.694915235042572, "avg_line_length": 18.66666603088379, "blob_id": "2487c9a6794ab724ba56068c13ca51a6de1ab0a7", "content_id": "7d823c1ba000a0a5cdf7b085e58b8e59378e0b80", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 236, "license_type": "permissive", "max_line_length": 45, "num_lines": 12, "path": "/web/src/rating/templatetags/opencon.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from django import template\n\n\nregister = template.Library()\n\n\n@register.assignment_tag\ndef i_rated(ratings, application):\n for rating in ratings:\n if rating.application == application:\n return True\n return False\n" }, { "alpha_fraction": 0.6763636469841003, "alphanum_fraction": 0.6836363673210144, "avg_line_length": 16.1875, "blob_id": "d19f1087ba5e5b3e8fd78f600ccfbc66d24fbf11", "content_id": "ba1b8dbd1f192e5ff7779344406aef286d403ba5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 275, "license_type": "permissive", "max_line_length": 83, "num_lines": 16, "path": "/web/src/opencon_project/settings/developer.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "import string\nimport random\n\nfrom opencon_project.settings.base import *\n\n\nSECRET_KEY = os.environ.get(\n 'SECRET_KEY',\n ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(50))\n)\n\nINSTALLED_APPS += [\n 'debug_toolbar',\n]\n\n# SEND_EMAILS = False\n" }, { "alpha_fraction": 0.628731369972229, "alphanum_fraction": 0.6436567306518555, "avg_line_length": 30.52941131591797, "blob_id": "a874b5bffe6547420177059f6a93280142b56e16", "content_id": "47dd9d8915ddba79ede5d95abe153d2eaab0d7b5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 536, "license_type": "permissive", "max_line_length": 71, "num_lines": 17, "path": "/web/src/application/management/commands/recalculate_ratings.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from django.core.management.base import BaseCommand, CommandError\nfrom ...models import Application\n\n\nclass Command(BaseCommand):\n help = 'Recalculate ratings for applications'\n\n def handle(self, *args, **options):\n applications = Application.objects.all()\n app_count = applications.count()\n\n for i, application in enumerate(applications):\n application.save()\n if i % 20 == 0:\n print('Recalculated: {0:.2f}%'.format(i/app_count*100))\n\n print('Recalculation done!')\n" }, { "alpha_fraction": 0.629607617855072, "alphanum_fraction": 0.6373364925384521, "avg_line_length": 48.47058868408203, "blob_id": "a51f5aa72c91d0665cccaed3ef6bd7a76e8462ff", "content_id": "7b407c9dc28f98ca5dffa9acd42514a29b734722", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1682, "license_type": "permissive", "max_line_length": 102, "num_lines": 34, "path": "/web/src/application/urls.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.conf.urls import url\nfrom django.views.generic.base import RedirectView\nfrom . import views\nfrom .models import Institution, Organization\n\n\nurlpatterns = [\n # #todo -- instead of hard-coded `url='/apply/'` use a reference to the view name (reverse_lazy?)\n url(r'^$', RedirectView.as_view(url='/apply/', permanent=False), name='root'),\n url(r'^apply/$', views.ApplicationView.as_view(), name='application'),\n url(r'^check_email/(?P<email>[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+)$',\n views.check_email, name='check_email'),\n url(r'^send_email/(?P<email>[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+)$',\n views.send_email, name='send_email'),\n url(r'^airport-autocomplete/$', views.AirportAutocomplete.as_view(), name='airport-autocomplete'),\n url(r'^country-autocomplete/$', views.CountryAutocomplete.as_view(), name='country-autocomplete'),\n url(r'^institution-autocomplete/$',\n views.InstitutionAutocomplete.as_view(\n model=Institution,\n create_field='name',\n ),\n name='institution-autocomplete'),\n url(r'^organization-autocomplete/$',\n views.OrganizationAutocomplete.as_view(\n model=Organization,\n create_field='name',\n ),\n name='organization-autocomplete'),\n url(r'^referral/(?P<referral>\\w{1,' + str(settings.MAX_CUSTOM_REFERRAL_LENGTH) + '})$',\n views.ReferralApplicationView.as_view(), name='referral'),\n url(r'^saved/(?P<uuid>[^/]+)/$', views.PreFilledApplicationView.as_view(), name='access_draft'),\n url(r'^thank-you/(?P<pk>\\d+)', views.ThankYou.as_view(), name='thank_you'),\n]\n" }, { "alpha_fraction": 0.6865671873092651, "alphanum_fraction": 0.7044776082038879, "avg_line_length": 32.5, "blob_id": "a3b4f667c6073f92c82d56b3f69d56950b5e1af9", "content_id": "37caf63349ce7fd3d45a12ea78393bdd16d1856f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 670, "license_type": "permissive", "max_line_length": 57, "num_lines": 20, "path": "/web/src/rating/test_validators.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from .validators import rating_validator, ValidationError\nfrom django.test import SimpleTestCase\n\n\nclass TestRatingValidator(SimpleTestCase):\n def test_rating_validator_high(self):\n with self.assertRaises(ValidationError):\n rating_validator(11)\n\n with self.assertRaises(ValidationError):\n rating_validator(10.1)\n\n def test_rating_validator_negative(self):\n with self.assertRaises(ValidationError):\n rating_validator(-0.1)\n\n def test_rating_validator_valid(self):\n self.assertIsNone(rating_validator(0))\n self.assertIsNone(rating_validator(7.3))\n self.assertIsNone(rating_validator(10))\n" }, { "alpha_fraction": 0.7694013118743896, "alphanum_fraction": 0.7738358974456787, "avg_line_length": 29.066667556762695, "blob_id": "b69c8ecde912ce3bace3d209cf6c473ad9a5ff9f", "content_id": "4cf301caf4528b4097d46fb60ae2db3e9b852bbb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 902, "license_type": "permissive", "max_line_length": 103, "num_lines": 30, "path": "/web/src/opencon_project/wsgi.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "\"\"\"\nWSGI config for opencon_project project.\n\nIt exposes the WSGI callable as a module-level variable named ``application``.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/\n\"\"\"\n\nimport os\n\nimport dotenv\n\nfrom django.conf import settings\nfrom django.core.wsgi import get_wsgi_application\nfrom whitenoise import WhiteNoise\nfrom whitenoise.django import DjangoWhiteNoise\n\n\ndotenv.read_dotenv(os.path.join(os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env')))\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"opencon_project.settings.developer\")\n\n# IMPORTANT: whitenoise only scans for media files upon startup, so newly added files won't be detected\n# see https://github.com/evansd/whitenoise/issues/32\napplication = WhiteNoise(\n DjangoWhiteNoise(get_wsgi_application()),\n root=settings.MEDIA_ROOT,\n prefix=settings.MEDIA_URL,\n)\n" }, { "alpha_fraction": 0.5862069129943848, "alphanum_fraction": 0.7413793206214905, "avg_line_length": 18.66666603088379, "blob_id": "a16a5fc9ac3dd2fe8a9a8a1fe87f59119b69365e", "content_id": "b397da6a57865d20cb5d0151f437cf7d73867e48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 58, "license_type": "permissive", "max_line_length": 25, "num_lines": 3, "path": "/web/src/requirements.devel.txt", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "coverage==4.0.3\ndjango-debug-toolbar==1.4\nsqlparse==0.1.19" }, { "alpha_fraction": 0.7035573124885559, "alphanum_fraction": 0.7035573124885559, "avg_line_length": 30.5, "blob_id": "8bcc289cd9e23b5738421540b102ad77749d7788", "content_id": "40aaf68c9e99911ea9c75963f2759de8e966145b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 253, "license_type": "permissive", "max_line_length": 54, "num_lines": 8, "path": "/web/src/application/helpers.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "\ndef is_valid_email_address(email):\n from django.core.validators import validate_email\n from django.core.exceptions import ValidationError\n try:\n validate_email(email)\n return True\n except ValidationError:\n return False\n" }, { "alpha_fraction": 0.609843909740448, "alphanum_fraction": 0.6410564184188843, "avg_line_length": 60.703704833984375, "blob_id": "6bea9677f6107e2b66ee2f8ed5f9627c30d2a91a", "content_id": "f4d3c30ceec7dab40e0440d83967b487d9cd2b57", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1666, "license_type": "permissive", "max_line_length": 156, "num_lines": 27, "path": "/web/src/application/static/js/thankyou.js", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "// ThankYou page is now being hosted by NationBuilder. Some information is being sent there in the URL and needs to be parsed using JavaScript.\n// https://web.archive.org/web/20160527200317/http://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-url-parameter#comment40513532_20336097\nfunction urldecode(str) {\n return decodeURIComponent((str+'').replace(/\\+/g, '%20'));\n};\n$(window).ready(function() {\n var url = window.location.search;\n var url = urldecode(url);\n // extract parameters\n var firstname = (url.split('firstname=')[1]||'').split('&')[0]\n var lastname = (url.split('lastname=')[1]||'').split('&')[0]\n var preferredname = (url.split('preferredname=')[1]||'').split('&')[0]\n var country = (url.split('country=')[1]||'').split('&')[0]\n var referral = (url.split('referral=')[1]||'').split('&')[0]\n // if no values are specified in the URL, set defaults\n var firstname = firstname ? firstname : 'Applicant';\n var lastname = lastname ? lastname : '';\n var country = country ? country : 'your country';\n var preferredname = preferredname ? preferredname : 'Applicant';\n var referral = referral ? referral : 'abc123';\n // .replace(\"[FirstName]\", firstname) does only 1 replacement; use #regex with \"/g\" (global) flag\n // \"[\" and \"]\" need to be escaped\n $('#content').html($('#content').html().replace(/\\[FirstName\\]/g, firstname));\n $('#content').html($('#content').html().replace(/\\[LastName\\]/g, lastname));\n $('#content').html($('#content').html().replace(/\\[PreferredName\\]/g, preferredname));\n $('#content').html($('#content').html().replace(/\\[Referral\\]/g, referral));\n});\n" }, { "alpha_fraction": 0.5902145504951477, "alphanum_fraction": 0.5912949442863464, "avg_line_length": 45.27857208251953, "blob_id": "9210f2c675ef0c9ea6e940419bd8c392aeda7a2e", "content_id": "a97d6004d0a4a98fb219b2065bbd5bf0be99a907", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6495, "license_type": "permissive", "max_line_length": 115, "num_lines": 140, "path": "/web/src/application/forms.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from django import forms\nfrom .models import Application, Airport, Institution, Organization, Country\nfrom .forms_field_other import OptionalChoiceField, OptionalMultiChoiceField\nfrom django.forms.widgets import CheckboxSelectMultiple, HiddenInput, RadioSelect, Select\n\nfrom dal import autocomplete\nimport ast\nfrom .data import *\nfrom .models import STATUS_CHOICES\n\n\nclass ApplicationForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n if kwargs.get('instance'):\n kwargs['initial'] = {\n 'occupation': ast.literal_eval(kwargs.get('instance').occupation or '[]'),\n 'degree': ast.literal_eval(kwargs.get('instance').degree or '[]'),\n 'participation': ast.literal_eval(kwargs.get('instance').participation or '[]'),\n 'expenses': ast.literal_eval(kwargs.get('instance').expenses or '[]'),\n 'opt_outs': ast.literal_eval(kwargs.get('instance').opt_outs or '[]'),\n 'acknowledgements': ast.literal_eval(kwargs.get('instance').acknowledgements or '[]'),\n }\n\n super().__init__(*args, **kwargs)\n\n self.fields['gender'] = OptionalChoiceField(\n label='Gender^',\n choices=GENDER_CHOICES,\n )\n\n self.fields['skills'] = OptionalMultiChoiceField(\n choices=SKILLS_CHOICES,\n label='Do you have any of the following skills?^',\n help_text='Check all that apply.',\n )\n\n self.fields['how_did_you_find_out'] = OptionalMultiChoiceField(\n choices=HOW_DID_YOU_FIND_OUT_CHOICES,\n label='How did you find out about OpenCon 2016?^',\n help_text='Check all that apply.',\n )\n\n self.fields['airport'] = forms.ModelChoiceField(\n queryset=Airport.objects.all(),\n widget=autocomplete.ModelSelect2(url='application:airport-autocomplete'),\n label='Closest international airport to the city you indicated in the previous question.',\n help_text='This question helps us understand how for you would need to travel. Begin by '\n 'typing the name of the city and suggestions will show up. Click the correct one. '\n 'You can also search by the three-letter IATA code (for example “LHR” for London). '\n 'If your airport does not show up, please type “Other Airport” and specify your '\n 'airport in the comments box below. Please enter an airport regardless of how close '\n 'you are located to Washington, DC, and note that U.S. regional/national airports '\n 'are permitted.',\n )\n self.fields['institution'] = forms.ModelChoiceField(\n queryset=Institution.objects.all(),\n widget=autocomplete.ModelSelect2(url='application:institution-autocomplete'),\n label='Primary Institution / Employer / Affiliation',\n help_text='Begin by typing the full name (no abbreviations) of the primary institution or '\n 'organization where you work or go to school. A list of suggestions will show up '\n 'as you type. If the correct name appears, click to select. If it does not appear, '\n 'finish typing the full name and click the option to “Create” the name. You may need '\n 'to scroll down to find this option.',\n )\n self.fields['organization'] = forms.ModelChoiceField(\n queryset=Organization.objects.all(),\n widget=autocomplete.ModelSelect2(url='application:organization-autocomplete'),\n label='Other Primary Affiliation / Organization / Project (Optional)',\n help_text='If you have another primary affiliation or project, you may list it here. Similar to the '\n 'question above, begin by typing the full name. If the correct name shows up automatically, '\n 'click to select. If not, then finish typing and click “Create.” If you have multiple other '\n 'affiliations, list only the most important one here. You may list any additional '\n 'affiliations in the Comments Box at the end of the application.',\n required=False,\n )\n\n\n class Meta:\n model = Application\n fields = (\n 'email',\n 'first_name',\n 'last_name',\n 'nickname',\n 'alternate_email',\n 'twitter_username',\n 'institution',\n 'organization',\n 'area_of_interest',\n 'description',\n 'interested',\n 'goal',\n 'participation',\n 'participation_text',\n 'citizenship',\n 'residence',\n 'gender',\n 'occupation',\n 'degree',\n 'experience',\n 'fields_of_study',\n # 'ideas',\n 'skills',\n 'how_did_you_find_out',\n # 'visa_requirements',\n 'scholarship',\n 'expenses',\n 'location',\n 'airport',\n 'additional_info',\n 'opt_outs',\n 'acknowledgements',\n 'referred_by',\n )\n widgets = {\n 'referred_by': HiddenInput,\n 'occupation': CheckboxSelectMultiple(choices=OCCUPATION_CHOICES),\n 'experience': RadioSelect(choices=EXPERIENCE_CHOICES),\n 'citizenship': Select(choices=COUNTRY_CHOICES),\n 'residence': Select(choices=COUNTRY_CHOICES),\n 'fields_of_study': Select(choices=FIELDS_OF_STUDY_CHOICES),\n 'degree': CheckboxSelectMultiple(choices=DEGREE_CHOICES),\n 'area_of_interest': RadioSelect(choices=AREA_OF_INTEREST_CHOICES),\n 'participation': CheckboxSelectMultiple(choices=PARTICIPATION_CHOICES),\n # 'visa_requirements': RadioSelect(choices=VISA_CHOICES),\n 'expenses': CheckboxSelectMultiple(choices=EXPENSES_CHOICES),\n 'scholarship': RadioSelect,\n 'opt_outs': CheckboxSelectMultiple(choices=OPT_OUTS_CHOICES),\n 'acknowledgements': CheckboxSelectMultiple(choices=ACKNOWLEDGEMENT_CHOICES),\n }\n\n\nclass ChangeStatusAdminForm(forms.ModelForm):\n class Meta:\n model = Application\n fields = ('status', 'status_reason')\n widgets = {\n 'status': Select(choices=STATUS_CHOICES),\n }\n" }, { "alpha_fraction": 0.5563910007476807, "alphanum_fraction": 0.5864661931991577, "avg_line_length": 21.16666603088379, "blob_id": "7af5c25c8f859f95c42b2f5ae3ee5ee0aeed39a2", "content_id": "9a3b8bf95978f5c7906745484ef1f27797b11d0a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 133, "license_type": "permissive", "max_line_length": 37, "num_lines": 6, "path": "/web/src/rating/templates/rating/logged_out.html", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\n\n{% block content %}\n <h1>You were logged out</h1>\n <h4>Thank you for your help.</h4>\n{% endblock %}\n" }, { "alpha_fraction": 0.5203081369400024, "alphanum_fraction": 0.5280112028121948, "avg_line_length": 43.625, "blob_id": "e758dba71c8618c01c62c207b3454be76d32df74", "content_id": "b7e5d1cccc288f0605d2f88520c5625709d95ea8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1428, "license_type": "permissive", "max_line_length": 84, "num_lines": 32, "path": "/web/src/application/management/commands/add_airports.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from django.core.management.base import BaseCommand, CommandError\nfrom ...models import Airport\n\n\nclass Command(BaseCommand):\n help = 'Add airports to database from /data/airport_list.txt'\n\n def handle(self, *args, **options):\n index = 0\n with open('data/airport_blacklist.txt') as file:\n filecontent = file.read()\n blacklist = [x.strip() for x in filecontent.strip().splitlines()\n if not x.strip().startswith('#') and len(x.strip())==3]\n with open('data/airport_list.txt') as file:\n print('Deleting old airports...')\n Airport.objects.all().delete()\n for row in file.readlines():\n data = row.split(',')\n airport_name, city, country, iata_code = (data[1].strip('\"'), \n data[2].strip('\"'), data[3].strip('\"'), data[4].strip('\"'))\n name = city + ' (' + airport_name + '), ' + country\n if iata_code and iata_code not in blacklist:\n airport = Airport.objects.create(iata_code=iata_code, name=name)\n airport.save()\n\n if index%100 == 0:\n print('Importing airport: {}'.format(index))\n index+= 1\n\n # Finally, add \"Other\" option\n airport = Airport.objects.create(iata_code='---', name='Other airport')\n airport.save()\n" }, { "alpha_fraction": 0.7185792326927185, "alphanum_fraction": 0.7185792326927185, "avg_line_length": 32.272727966308594, "blob_id": "3f57919f4fe8f599151f545e87f6daae3092cf3f", "content_id": "5a0639b527d465e60af6ecb8836dea0bd4b9594c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 366, "license_type": "permissive", "max_line_length": 59, "num_lines": 11, "path": "/web/src/application/test_helpers.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from .helpers import is_valid_email_address\nfrom django.test import SimpleTestCase\n\n\nclass EmailValidatorTest(SimpleTestCase):\n def test_invalid_email(self):\n self.assertFalse(is_valid_email_address(''))\n self.assertFalse(is_valid_email_address('no@mail'))\n\n def test_valid_email(self):\n self.assertTrue(is_valid_email_address('valid@email.com'))\n" }, { "alpha_fraction": 0.7137014269828796, "alphanum_fraction": 0.7137014269828796, "avg_line_length": 27.764705657958984, "blob_id": "cf3e5c4491d72742edca065166f52482a348ec8a", "content_id": "5e8d00492647f393ca95a9a428fb831f118bbcfa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 491, "license_type": "permissive", "max_line_length": 63, "num_lines": 17, "path": "/CONTRIBUTORS.md", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "# OpenCon Rating App contributors (sorted alphabetically)\n\n* **[Nicole Allen](https://github.com/txtbks)**\n\n * Designer of the application logic\n\n* **[Jan Gondol](https://github.com/jangondol)**\n\n * Developer, server admin\n\n* **[Zoltan Onody](https://github.com/ZoltanOnody)**\n\n * Senior developer & Django architect\n * Note: after the migration from a private repository,\n Zoltan's commits may be displayed under Jan Gondol's name\n\nFor additional contributors, see the repo's history of commits.\n" }, { "alpha_fraction": 0.6986142992973328, "alphanum_fraction": 0.7147806286811829, "avg_line_length": 32.30769348144531, "blob_id": "6326c53399bd2b85a8b242f55cda33302b0ef2a8", "content_id": "697c624b88116ed24c57983ad11367af604a2adb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 866, "license_type": "permissive", "max_line_length": 110, "num_lines": 26, "path": "/web/src/rating/admin.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import User, Step1Rating, Step2Rating\n\n\nclass UserAdmin(admin.ModelAdmin):\n list_display = ('nick', 'email', 'first_name', 'last_name', 'organizer', 'invitation_sent', 'disabled_at')\n\n\nadmin.site.register(User, UserAdmin)\n\n\nclass Step1RatingAdmin(admin.ModelAdmin):\n list_display = ('id', 'created_by', 'application', 'rating')\n list_per_page = 500 # pagination\n search_fields = ('application__first_name', 'application__last_name', 'application__email', )\n\n\nadmin.site.register(Step1Rating, Step1RatingAdmin)\n\n\nclass Step2RatingAdmin(admin.ModelAdmin):\n list_display = ('id', 'created_by', 'application', 'rating')\n list_per_page = 500 # pagination\n search_fields = ('application__first_name', 'application__last_name', 'application__email', )\n\nadmin.site.register(Step2Rating, Step2RatingAdmin)\n" }, { "alpha_fraction": 0.7215189933776855, "alphanum_fraction": 0.746835470199585, "avg_line_length": 30.600000381469727, "blob_id": "9612838fbd38d11dc1b5e3a264ce7603f51573b0", "content_id": "130b1d795844988f4a1c6b463c525b391762ab36", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 158, "license_type": "permissive", "max_line_length": 56, "num_lines": 5, "path": "/web/src/opencon_project/settings/production.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from opencon_project.settings.base import *\n\nDEBUG = False\nALLOWED_HOSTS = ['.opencon2016.org'] # production domain\nSECRET_KEY = os.environ.get('SECRET_KEY')\n" }, { "alpha_fraction": 0.6181944608688354, "alphanum_fraction": 0.6271525621414185, "avg_line_length": 35.734825134277344, "blob_id": "0ca4de199932f68d0bdd7ae31dacbc4102093e4e", "content_id": "e28bdf40985ccd5c3067ad580cfe9f16bfa67884", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11498, "license_type": "permissive", "max_line_length": 125, "num_lines": 313, "path": "/web/src/rating/views.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.db.models import Count\nfrom django.http import Http404\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.views.generic import View, TemplateView, ListView\n\nfrom application.models import Application\n\nfrom .forms import Step1RateForm, Step2RateForm, ChangeStatusForm\nfrom .models import User, Step1Rating, Step2Rating\n\nfrom abc import ABC, abstractproperty, abstractmethod\n\nfrom application.models import DISPLAYED_FIELDS_ROUND_1, DISPLAYED_FIELDS_ROUND_2\n\n\nclass AuthenticatedMixin(View, ABC):\n\n @abstractproperty\n def permission(self):\n pass\n\n def get(self, request, *args, **kwargs):\n if self.permission is None:\n raise AssertionError('Permission level was not set.')\n self.get_user(request) # is logged in?\n return super().get(request, *args, **kwargs)\n\n def get_user(self, request=None):\n if request is not None:\n user_pk = request.session.get('user_pk')\n self.user = get_object_or_404(User, pk=user_pk, disabled_at=None)\n\n if not hasattr(self, 'user'):\n raise AssertionError(\n 'You are trying to get the user but you have to invoke this function with request first.'\n )\n\n if self.permission == 1 and self.user.is_round_1_reviewer:\n return self.user\n elif self.permission == 2 and self.user.is_round_2_reviewer:\n return self.user\n raise Http404\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context.update({'user': self.user})\n return context\n\n\nclass Login(View):\n def get(self, request, uuid):\n user = get_object_or_404(User, uuid=uuid)\n request.session['user_pk'] = user.pk\n if user.is_round_1_reviewer:\n return redirect('rating:rate_round1')\n elif user.is_round_2_reviewer:\n return redirect('rating:rate_round2')\n raise Http404\n\n\nclass Logout(View):\n def get(self, request):\n del request.session['user_pk']\n return redirect('rating:logged_out')\n\n\nclass AbstractRateView(AuthenticatedMixin, View, ABC):\n displayed_data = DISPLAYED_FIELDS_ROUND_1\n\n @abstractproperty\n def rate_form_class(self):\n pass\n\n @abstractproperty\n def skip_url(self):\n pass\n\n @abstractmethod\n def rate(self, request, user, rating_pk):\n pass\n\n @abstractmethod\n def get(self, request, rating_pk=None):\n pass\n\n def get_context_data(self, created_by, application, rate_form=None):\n if not rate_form:\n rate_form = self.rate_form_class(\n initial={\n 'created_by': created_by.id,\n 'application': application.id,\n }\n )\n context = {\n 'user': created_by,\n 'rate_count': created_by.rated.count(),\n 'application_data': application.get_data(self.displayed_data),\n 'forms': {\n 'rate': rate_form,\n 'status': ChangeStatusForm(\n initial={\n 'choice': application.status,\n 'application': application.pk\n }\n ),\n },\n 'skip_url': self.skip_url,\n }\n\n return context\n\n def change_status(self, request, user, rating_pk):\n application = get_object_or_404(Application, pk=request.POST['application'])\n\n form = ChangeStatusForm(request.POST)\n if user.organizer and form.is_valid():\n ip = request.META.get('HTTP_X_REAL_IP') or request.META['REMOTE_ADDR']\n application.change_status(form.cleaned_data['choice'], user, ip, form.cleaned_data['reason'])\n\n return self.get(request, rating_pk)\n\n def post(self, request, rating_pk=None):\n user = super().get_user(request)\n if request.POST.get('choice'):\n return self.change_status(request, user, rating_pk)\n else:\n return self.rate(request, user, rating_pk)\n\n\nclass RateView(AbstractRateView):\n rate_form_class = Step1RateForm\n permission = 1\n skip_url = reverse_lazy('rating:rate_round1')\n\n def get(self, request, rating_pk=None):\n user = super().get_user(request)\n\n if rating_pk is None:\n unrated = Application.objects.get_unrated(user).order_by('?').first()\n else:\n unrated = get_object_or_404(Step1Rating, pk=rating_pk, created_by=user)\n if not unrated.application.need_rating1:\n return render(request, 'rating/cannot_rate.html', context={'user': user})\n\n if unrated:\n template_name = 'rating/rate.html'\n\n if rating_pk is None:\n context = self.get_context_data(user, unrated)\n else:\n rate_form = Step1RateForm(instance=unrated)\n context = self.get_context_data(user, unrated.application, rate_form)\n else:\n template_name = 'rating/all_rated.html'\n context = {'user': user}\n\n return render(request, template_name, context=context)\n\n def rate(self, request, user, rating_pk):\n if rating_pk is None:\n rate_form = Step1RateForm(request.POST)\n else:\n rating = get_object_or_404(Step1Rating, pk=rating_pk, created_by=user)\n rate_form = Step1RateForm(request.POST, instance=rating)\n\n if rate_form.is_valid():\n rating = rate_form.save(commit=False)\n rating.created_by = user\n rating.ipaddress = request.META.get('HTTP_X_REAL_IP') or request.META['REMOTE_ADDR']\n rating.save()\n else:\n application = rate_form.cleaned_data['application']\n context = self.get_context_data(user, application, rate_form=rate_form)\n return render(request, 'rating/rate.html', context=context)\n\n return redirect('rating:rate_round1')\n\n\nclass AbstractRate2View(AbstractRateView):\n permission = 2\n rate_form_class = Step2RateForm\n skip_url = reverse_lazy('rating:rate_round2')\n displayed_data = DISPLAYED_FIELDS_ROUND_2\n # displayed_data = None # for displaying all the data\n\n def get_context_data(self, created_by, application, rate_form=None):\n context = super().get_context_data(created_by, application, rate_form)\n all_reviews = application.ratings2.all()\n context.update({'all_reviews': all_reviews})\n return context\n\n\nclass Rate2View(AbstractRate2View):\n def get(self, request, rating_pk=None):\n user = super().get_user(request)\n context = {'user': user}\n template_name = 'rating/rate.html'\n if rating_pk is None: # new rating\n application = Application.objects.get_unrated2(user).order_by('?').first()\n if application:\n context = self.get_context_data(user, application)\n else:\n template_name = 'rating/all_rated.html'\n else: # old rating\n rating = get_object_or_404(Step2Rating, pk=rating_pk, created_by=user)\n rate_form = Step2RateForm(instance=rating)\n context = self.get_context_data(user, rating.application, rate_form)\n\n return render(request, template_name, context=context)\n\n def rate(self, request, user, rating_pk):\n if rating_pk is None:\n rate_form = Step2RateForm(request.POST)\n else:\n rating = get_object_or_404(Step2Rating, pk=rating_pk, created_by=user)\n rate_form = Step2RateForm(request.POST, instance=rating)\n\n if rate_form.is_valid():\n rating = rate_form.save(commit=False)\n rating.created_by = user\n rating.ipaddress = request.META.get('HTTP_X_REAL_IP') or request.META['REMOTE_ADDR']\n rating.save()\n else:\n application = rate_form.cleaned_data['application']\n context = self.get_context_data(user, application, rate_form=rate_form)\n return render(request, 'rating/rate.html', context=context)\n\n return redirect('rating:rate_round2')\n\n\nclass Rate2SelectView(AbstractRate2View):\n def get(self, request, rating_pk):\n user = super().get_user(request)\n application = Application.objects.get(pk=rating_pk)\n\n try:\n old_rating = Step2Rating.objects.get(application=application, created_by=user)\n rate_form = Step2RateForm(instance=old_rating)\n context = self.get_context_data(user, application, rate_form)\n except Step2Rating.DoesNotExist:\n context = self.get_context_data(user, application)\n\n return render(request, 'rating/rate.html', context=context)\n\n def rate(self, request, user, application_pk):\n application = Application.objects.get(pk=application_pk)\n\n try:\n old_rating = Step2Rating.objects.get(application=application, created_by=user)\n rate_form = Step2RateForm(request.POST, instance=old_rating)\n except Step2Rating.DoesNotExist:\n rate_form = Step2RateForm(request.POST)\n\n if rate_form.is_valid():\n rating = rate_form.save(commit=False)\n rating.created_by = self.get_user()\n rating.ipaddress = request.META.get('HTTP_X_REAL_IP') or request.META['REMOTE_ADDR']\n rating.save()\n else:\n context = self.get_context_data(user, application, rate_form=rate_form)\n return render(request, 'rating/rate.html', context=context)\n\n return redirect('rating:previous2', rating_pk=application.pk)\n\n\nclass Stats(AuthenticatedMixin, TemplateView):\n template_name = 'rating/stats.html'\n permission = 1\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n users = User.objects.annotate(finished_count=Count('rated')).prefetch_related('rated')\n users = users.filter(finished_count__gte=1).order_by('-finished_count')[:settings.LEADERBOARD_ROUND1_MAX_DISPLAYED]\n context.update({'ranking': users})\n return context\n\n\nclass Stats2(AuthenticatedMixin, TemplateView):\n template_name = 'rating/stats2.html'\n permission = 2\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n users = User.objects.annotate(finished_count2=Count('rated2')).prefetch_related('rated2')\n users = users.filter(finished_count2__gte=1).order_by('-finished_count2')[:settings.LEADERBOARD_ROUND2_MAX_DISPLAYED]\n context.update({'ranking': users})\n return context\n\n\nclass PreviousRatings(AuthenticatedMixin, ListView):\n template_name = 'rating/ratings_list.html'\n permission = 1\n\n def get_queryset(self):\n user = self.get_user()\n return Step1Rating.objects.filter(created_by=user).prefetch_related('application', 'application__institution')\n\n\nclass AllRound2(AuthenticatedMixin, ListView):\n template_name = 'rating/application_list.html'\n permission = 2\n\n def get_queryset(self):\n return Application.objects.get_all_round2().prefetch_related('institution')\n\n def get_context_data(self, **kwargs):\n user_id = self.get_user().pk\n user = User.objects.prefetch_related('rated2', 'rated2__application').get(pk=user_id)\n context = super().get_context_data(**kwargs)\n context.update({'user': user})\n return context\n" }, { "alpha_fraction": 0.6028528809547424, "alphanum_fraction": 0.6077327132225037, "avg_line_length": 39.984615325927734, "blob_id": "7bc2672548994a22a1d15d7e53efbf8e20cc14bf", "content_id": "df53cb557bb173bb08bc598fa4643df70e7c8174", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2664, "license_type": "permissive", "max_line_length": 116, "num_lines": 65, "path": "/web/src/application/forms_field_other.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from django.core.exceptions import ValidationError\nfrom django import forms\nimport ast\n\n\nclass OptionalChoiceWidget(forms.MultiWidget):\n def __init__(self, widgets, attrs=None):\n widgets[1].attrs['class'] = 'form-control'\n super().__init__(widgets, attrs)\n\n def decompress(self, value):\n if value:\n value = ast.literal_eval(value)\n try: # todo: log this situation and find out when it occures.\n return [value[0], value[1]]\n except:\n return [None, None]\n return [None, None]\n\n\nclass OptionalChoiceField(forms.MultiValueField):\n def __init__(self, choices, *args, **kwargs):\n fields = [\n forms.ChoiceField(choices=choices, widget=forms.RadioSelect, required=False),\n forms.CharField(required=False, widget=forms.TextInput, help_text='Other')\n ]\n self.widget = OptionalChoiceWidget(widgets=[f.widget for f in fields])\n super().__init__(required=False, fields=fields, *args, **kwargs)\n\n def compress(self, data_list):\n if not data_list:\n raise ValidationError('This field is required.')\n\n if 'other' in data_list[0]:\n if not data_list[1]:\n raise ValidationError('You have to fill in the input if you select \"Other\".')\n else:\n if data_list[1]:\n raise ValidationError('You have to select \"Other\" if you want to fill in the input.')\n return data_list[0], data_list[1]\n\n\nclass OptionalMultiChoiceField(forms.MultiValueField):\n def __init__(self, choices, required=False, *args, **kwargs):\n self.required = required\n fields = [\n forms.MultipleChoiceField(choices=choices, widget=forms.widgets.CheckboxSelectMultiple, required=False),\n forms.CharField(required=False, widget=forms.TextInput, help_text='Other')\n ]\n self.widget = OptionalChoiceWidget(widgets=[f.widget for f in fields])\n super().__init__(required=False, fields=fields, *args, **kwargs)\n\n def compress(self, data_list):\n if self.required:\n if not data_list:\n raise ValidationError('You have to select an option or enter text for this field.')\n if data_list:\n if 'other' in data_list[0]:\n if not data_list[1]:\n raise ValidationError('You have to fill in the input if you select \"Other\".')\n else:\n if data_list[1]:\n raise ValidationError('You have to select \"Other\" if you want to fill in the input.')\n return data_list[0], data_list[1]\n return None, None\n" }, { "alpha_fraction": 0.5291666388511658, "alphanum_fraction": 0.5308333039283752, "avg_line_length": 37.709678649902344, "blob_id": "d28f1b0d20acdff67b5b047482c19d8bccb04bc7", "content_id": "b2bcb1dd8f6ee0774152a92b59aa0c0e2d2b2845", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1200, "license_type": "permissive", "max_line_length": 101, "num_lines": 31, "path": "/web/src/application/management/commands/add_drafts.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "import csv\nimport json\nimport uuid\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom ...models import Draft\n\n\nclass Command(BaseCommand):\n help = 'Add drafts from /data/draft_list.txt'\n\n def handle(self, *args, **options):\n with open('data/draft_list.txt') as file:\n Draft.objects.all().delete()\n reader = csv.reader(file, delimiter=',', quotechar='\"')\n header=next(reader, None)\n for row in reader:\n email=row[0]\n data={}\n for i, column in enumerate(row):\n if row[i]:\n data[header[i]] = [row[i]]\n data = json.dumps(data) # reason: convert from single-quoted to double-quoted strings\n try:\n draft, created = Draft.objects.get_or_create(email=email, data=data)\n # no need to specify 'uuid=str(uuid.uuid4().hex)', 'created at', 'updated at'\n # also: no need to specify csrfmiddlewaretoken in the data\n if created:\n draft.save()\n except:\n print('Failed to import ' + email)\n" }, { "alpha_fraction": 0.5973154306411743, "alphanum_fraction": 0.6174496412277222, "avg_line_length": 28.799999237060547, "blob_id": "b498f52052f018f2b46fe341b9a2b6a6248851cd", "content_id": "18723e5720320d18b0d94816417339166b526325", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 298, "license_type": "permissive", "max_line_length": 55, "num_lines": 10, "path": "/web/src/rating/validators.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\n\n\ndef rating_validator(value):\n if not(0 <= value <= 10):\n raise ValidationError(\n _('%(value)s is not in range <0, 10>'),\n params={'value': value},\n )\n" }, { "alpha_fraction": 0.643478274345398, "alphanum_fraction": 0.643478274345398, "avg_line_length": 34.38461685180664, "blob_id": "40c9f80e9987cc0848d5b3612349f9befc6fb3f4", "content_id": "972f3a11a8d08e4a2a01a793e980a8ccbcb504b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 460, "license_type": "permissive", "max_line_length": 66, "num_lines": 13, "path": "/web/src/application/management/commands/add_countries.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from django.core.management.base import BaseCommand, CommandError\nfrom ...models import Country\n\n\nclass Command(BaseCommand):\n help = 'Add countries to database from /data/country_list.txt'\n\n def handle(self, *args, **options):\n with open('data/country_list.txt') as file:\n Country.objects.all().delete()\n for row in file.readlines():\n country = Country.objects.create(name=row)\n country.save()\n" }, { "alpha_fraction": 0.4133738577365875, "alphanum_fraction": 0.4154002070426941, "avg_line_length": 29.84375, "blob_id": "576e5aa455913b2b5143b62b1ca55085ddb54378", "content_id": "072725f3b0727f8e3bc797967c915e15f0ec6f44", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 987, "license_type": "permissive", "max_line_length": 111, "num_lines": 32, "path": "/web/src/rating/templates/rating/ratings_list.html", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "{% extends \"rating/base.html\" %}\n\n{% block content %}\n {% if object_list %}\n <table class=\"table\">\n <thead>\n <tr>\n <th>#</th>\n <th>Name</th>\n <th>Country</th>\n <th>Affiliation</th>\n <th>Rating</th>\n <th>Acceptance</th>\n </tr>\n </thead>\n <tbody>\n {% for object in object_list %}\n <tr>\n <td>{{ forloop.counter }}</td>\n <td><a href=\"{% url 'rating:previous' object.pk %}\">{{ object.application.full_name }}</a></td>\n <td>{{ object.application.residence }}</td>\n <td>{{ object.application.institution }}</td>\n <td>{{ object.rating }}</td>\n <td>{{ object.acceptance }}</td>\n </tr>\n {% endfor %}\n </tbody>\n </table>\n {% else %}\n <h1>You haven't rated any application yet.</h1>\n {% endif %}\n{% endblock %}\n" }, { "alpha_fraction": 0.5971544981002808, "alphanum_fraction": 0.6048780679702759, "avg_line_length": 32.24324417114258, "blob_id": "e0634b17955297cdfabf7265d8d751d8c7a14c5d", "content_id": "4063d46ddaf7bda7082f35cbd8fd9d0968fa8bdb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2460, "license_type": "permissive", "max_line_length": 104, "num_lines": 74, "path": "/web/src/rating/forms.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from application.models import STATUS_CHOICES\nfrom django import forms\nfrom django.forms import widgets\nfrom .models import Step1Rating, Step2Rating\nfrom .models import RATING_METADATA_1_CHOICES, RATING_METADATA_2_CHOICES\n\nimport ast\n\n\nclass Step1RateForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n if kwargs.get('instance'):\n kwargs['initial'] = {\n 'rating_metadata_1': ast.literal_eval(kwargs.get('instance').rating_metadata_1 or '[]'),\n }\n\n super().__init__(*args, **kwargs)\n\n class Meta:\n model = Step1Rating\n fields = [\n 'application',\n 'rating',\n 'acceptance',\n 'acceptance_reason',\n 'rating_metadata_1',\n ]\n widgets = {\n 'application': widgets.HiddenInput,\n 'rating_metadata_1': widgets.CheckboxSelectMultiple(choices=RATING_METADATA_1_CHOICES),\n }\n\n def clean_acceptance_reason(self):\n reason = self.cleaned_data['acceptance_reason']\n if self.cleaned_data['acceptance'] == 'yes' and not reason:\n raise forms.ValidationError('This field is required.')\n return reason\n\n\nclass Step2RateForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n if kwargs.get('instance'):\n kwargs['initial'] = {\n 'rating_metadata_2': ast.literal_eval(kwargs.get('instance').rating_metadata_2 or '[]'),\n }\n\n super().__init__(*args, **kwargs)\n\n class Meta:\n model = Step2Rating\n fields = [\n 'application',\n 'rating',\n 'acceptance',\n 'acceptance_reason',\n 'rating_metadata_2',\n ]\n widgets = {\n 'application': widgets.HiddenInput,\n 'rating_metadata_2': widgets.CheckboxSelectMultiple(choices=RATING_METADATA_2_CHOICES),\n }\n\n def clean_acceptance_reason(self):\n reason = self.cleaned_data['acceptance_reason']\n if self.cleaned_data['acceptance'] == 'yes' and not reason:\n raise forms.ValidationError('This field is required.')\n return reason\n\n\nclass ChangeStatusForm(forms.Form):\n STATUS_CHOICES_NO_DELETED = STATUS_CHOICES[:-1]\n choice = forms.ChoiceField(choices=STATUS_CHOICES_NO_DELETED, label='Current status')\n reason = forms.CharField(widget=widgets.Textarea, required=False)\n application = forms.CharField(widget=forms.HiddenInput)\n" }, { "alpha_fraction": 0.6561264991760254, "alphanum_fraction": 0.6561264991760254, "avg_line_length": 37.92307662963867, "blob_id": "7ffa5517a23bd3e3704eb8f23228e0f0850aca22", "content_id": "e5dc95e098c4086ca027703ea9488389d47dc953", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 506, "license_type": "permissive", "max_line_length": 95, "num_lines": 13, "path": "/web/src/application/management/commands/add_organizations.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from django.core.management.base import BaseCommand, CommandError\nfrom ...models import Organization\n\n\nclass Command(BaseCommand):\n help = 'Add countries to database from /data/organization_list.txt'\n\n def handle(self, *args, **options):\n with open('data/organization_list.txt') as file:\n for row in file.readlines():\n organization, created = Organization.objects.get_or_create(name=row, show=True)\n if created:\n organization.save()\n" }, { "alpha_fraction": 0.5236051678657532, "alphanum_fraction": 0.5278970003128052, "avg_line_length": 34.846153259277344, "blob_id": "d4cecb30d1c74255b1282877459690dee0286632", "content_id": "e62ed53438d4001b2d48d22de58bb9cce0d18215", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 932, "license_type": "permissive", "max_line_length": 130, "num_lines": 26, "path": "/web/src/rating/management/commands/add_users.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "import csv\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom ...models import User\n\n\nclass Command(BaseCommand):\n help = 'Add users to database from /data/user_list.txt'\n\n def handle(self, *args, **options):\n with open('data/user_list.txt') as file:\n reader = csv.reader(file, delimiter=',', quotechar='\"')\n header=next(reader, None)\n # print('Deleting old users...')\n # User.objects.all().delete()\n for row in reader:\n email=row[0]\n first_name=row[1]\n last_name=row[2]\n nick=row[3]\n try:\n user, created = User.objects.get_or_create(email=email, first_name=first_name, last_name=last_name, nick=nick)\n if created:\n user.save()\n except:\n print('Failed to import ' + email)\n" }, { "alpha_fraction": 0.7204724550247192, "alphanum_fraction": 0.7677165269851685, "avg_line_length": 45.181819915771484, "blob_id": "bf602373a8d18ba95aa8cbbc8d741f8a284d236d", "content_id": "a10b616dae36e1c3748b1a6765df000624e28af2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 508, "license_type": "permissive", "max_line_length": 111, "num_lines": 11, "path": "/web/src/application/constants.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "# #todo -- make these constants configurable via admin\n# https://django-constance.readthedocs.io/en/latest/\n# note that the constants below are example only (different constants were used during the application process)\n\nMAX_REVIEWS_ROUND_ONE = 2\nMAX_REVIEWS_ROUND_TWO = 2\nRATING_R1_LOW_THRESHOLD = 1\nNEEDED_RATING_TO_ROUND2 = 7\nNEEDED_RATING_FOR_THIRD_REVIEW_ROUND1 = 5\nNEEDED_DIFFERENCE_FOR_THIRD_REVIEW_ROUND1 = 2\nAPPLICATION_DEADLINE = '2016/07/12 10:00' # YEAR/MONTH/DAY HOUR:MINUTE -- 24h format, UTC\n" }, { "alpha_fraction": 0.6227545142173767, "alphanum_fraction": 0.6297405362129211, "avg_line_length": 32.822784423828125, "blob_id": "9128b9f0a9f805c4eb827a79f067778327ec7b45", "content_id": "45e536ca1d5cf3409107df4c7a57001095410141", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8020, "license_type": "permissive", "max_line_length": 157, "num_lines": 237, "path": "/web/src/rating/models.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "import math\nimport uuid\n\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom django.core.urlresolvers import reverse\nfrom django.db import models\nfrom django.template.loader import render_to_string\nfrom .validators import rating_validator\n\n\nRATING_METADATA_1_CHOICES = [\n ('needs_followup', 'This application includes interesting projects or ideas that should be followed up on (include notes above)'),\n ('strong_application', 'This is an especially strong application and it should be sent to the Organizing Committee immediately'),\n ('know_applicant_or_conflict', 'I personally know this applicant or have a conflict of interest'),\n ('problem_spotted', 'There is a problem with this application'),\n]\n\nRATING_METADATA_2_CHOICES = [\n ('award_certificate', 'This applicant has done meaningful work to advance Open Access, Open Education or Open Data and should be awarded a certificate'),\n ('add_to_shortlist', 'This applicant should be added to the short list'),\n ('know_applicant_or_conflict', 'I personally know this applicant or have a conflict of interest'),\n ('problem_spotted', 'There is a problem with this application'),\n]\n\n\nclass TimestampMixin(models.Model):\n \"\"\" Mixin for saving the creation time and the time of the last update \"\"\"\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n class Meta:\n abstract = True\n\n\nclass User(TimestampMixin, models.Model):\n \"\"\"\n Users allowed to rate applications.\n \"\"\"\n uuid = models.UUIDField(default=uuid.uuid4)\n first_name = models.CharField(max_length=100, blank=True, null=True)\n last_name = models.CharField(max_length=100, blank=True, null=True)\n nick = models.CharField(max_length=200, blank=True, null=True)\n email = models.EmailField()\n\n is_round_1_reviewer = models.BooleanField(default=True)\n is_round_2_reviewer = models.BooleanField(default=False)\n\n organizer = models.BooleanField(default=False)\n invitation_sent = models.BooleanField(default=False)\n\n disabled_at = models.DateTimeField(blank=True, null=True)\n\n def invite(self):\n \"\"\"\n Send invite mail to application email address.\n \"\"\"\n if not settings.REVIEWER_MAIL_ENABLED:\n return\n\n context = {\n \"user\": self,\n \"link\": \"{}{}\".format(\n settings.BASE_URL,\n reverse(\"rating:rate\", args=[self.uuid])\n )\n }\n\n subject = render_to_string(\n \"rating/email/invite.subject\", context\n ).strip()\n message = render_to_string(\"rating/email/invite.message\", context)\n\n send_mail(\n subject,\n message,\n settings.FROM_MAIL,\n [self.email],\n fail_silently=False\n )\n self.invitation_sent = True\n self.save()\n\n def __str__(self):\n return self.nick\n\n def avg(self):\n count = self.rated.count()\n if count == 0:\n return 0\n\n return sum(rating.rating for rating in self.rated.all()) / count\n\n def avg2(self):\n count = self.rated2.count()\n if count == 0:\n return 0\n\n return sum(rating.rating for rating in self.rated2.all()) / count\n\n def standard_deviation(self):\n count = self.rated.count()\n if count == 0:\n return 0\n\n ratings = self.rated.all()\n mean = sum(rating.rating for rating in ratings) / count\n sm = sum((mean-rating.rating)**2 for rating in ratings)\n return math.sqrt(sm/count)\n\n def standard_deviation2(self):\n count = self.rated2.count()\n if count == 0:\n return 0\n\n ratings = self.rated2.all()\n mean = sum(rating.rating for rating in ratings) / count\n sm = sum((mean-rating.rating)**2 for rating in ratings)\n return math.sqrt(sm/count)\n\n\nSTATE_CHOICES = (\n (True, u'Yes'),\n (False, u'No'),\n)\n\n\nclass Step1Rating(TimestampMixin, models.Model):\n \"\"\"\n Application rating.\n \"\"\"\n created_by = models.ForeignKey(\n User,\n related_name=\"rated\"\n )\n application = models.ForeignKey(\n \"application.Application\",\n related_name=\"ratings\"\n )\n rating = models.DecimalField(\n verbose_name='How would you rate this application?',\n help_text='Please either enter whole numbers (e.g. 6) or enter decimal numbers up to one place using '\n 'a period (e.g. 6.7). Note the system may reject decimals entered using a comma.',\n decimal_places=1,\n max_digits=3,\n validators=[rating_validator]\n )\n ACCEPTANCE_CHOICE = [\n ('yes', 'Yes'),\n ('neutral', 'Neutral'),\n ('no', 'No')\n ]\n acceptance = models.CharField(\n verbose_name='Do you think this application should be considered for acceptance?',\n choices=ACCEPTANCE_CHOICE,\n default=ACCEPTANCE_CHOICE[1][0],\n max_length=10,\n )\n acceptance_reason = models.TextField(\n verbose_name='Please explain why this application should/shouldn’t be considered to acceptance:',\n help_text='This question is mandatory if you answered Yes to question 2. If you said No or Neutral, '\n 'you can either explain your answer or leave it blank.',\n blank=True, null=True,\n )\n rating_metadata_1 = models.TextField(\n verbose_name='Please check below if any apply:',\n help_text='',\n blank=True, null=True,\n )\n # #todo -- consider removing comments from the model (they aren't being used at the moment)\n comments = models.TextField(\n verbose_name='Any other comments?',\n blank=True, null=True,\n )\n\n ipaddress = models.GenericIPAddressField(blank=True, null=True)\n\n def save(self, *args, **kwargs):\n obj = super().save(*args, **kwargs)\n self.application.save() # when save is envoked ratings are recalculated\n return obj\n\n\nclass Step2Rating(TimestampMixin, models.Model):\n \"\"\"\n Application rating.\n \"\"\"\n created_by = models.ForeignKey(\n User,\n related_name=\"rated2\"\n )\n application = models.ForeignKey(\n \"application.Application\",\n related_name=\"ratings2\"\n )\n rating = models.DecimalField(\n verbose_name='How would you rate this application?',\n help_text='Please either enter whole numbers (e.g. 6) or enter decimal numbers up to one place using '\n 'a period (e.g. 6.7). Note the system may reject decimals entered using a comma.',\n decimal_places=1,\n max_digits=3,\n validators=[rating_validator]\n )\n ACCEPTANCE_CHOICE = [\n ('yes', 'Yes'),\n ('neutral', 'Neutral'),\n ('no', 'No')\n ]\n acceptance = models.CharField(\n verbose_name='Do you think this application should be considered for acceptance?',\n choices=ACCEPTANCE_CHOICE,\n default=ACCEPTANCE_CHOICE[1][0],\n max_length=10,\n )\n acceptance_reason = models.TextField(\n verbose_name='Please explain why this application should/shouldn’t be considered to acceptance:',\n help_text='This question is mandatory if you answered Yes to question 2. If you said No or Neutral, '\n 'you can either explain your answer or leave it blank.',\n blank=True, null=True,\n )\n rating_metadata_2 = models.TextField(\n verbose_name='Please check below if any apply:',\n help_text='',\n blank=True, null=True,\n )\n # #todo -- consider removing comments from the model (they aren't being used at the moment)\n comments = models.TextField(\n verbose_name='Any other comments?',\n blank=True, null=True,\n )\n\n ipaddress = models.GenericIPAddressField(blank=True, null=True)\n\n def save(self, *args, **kwargs):\n obj = super().save(*args, **kwargs)\n self.application.save() # when save is envoked ratings are recalculated\n return obj\n" }, { "alpha_fraction": 0.49400797486305237, "alphanum_fraction": 0.5013315677642822, "avg_line_length": 31.65217399597168, "blob_id": "0af54425fac4890002ebfaff146aa6fd2b792410", "content_id": "37e030aee31835b64520ee759e71afaa88c55326", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1502, "license_type": "permissive", "max_line_length": 159, "num_lines": 46, "path": "/web/src/application/static/js/main.js", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "$( document ).ready(function() {\n console.log( \"ready!\" );\n\n $(\"#check_mail\").on('click', function(){\n var email = $('#id_email').val();\n $('#myModal').remove();\n $.ajax({\n type: 'GET',\n url: '/check_email/' + email,\n success: function(result){\n $('body').append(result);\n $('#myModal').modal();\n },\n error: function(xhr, ajaxOptions, thrownError){\n if(xhr.status == 404){\n console.log('not a valid email');\n }\n }\n });\n console.log('ooooh');\n });\n\n $('#skip').on('click', function(){\n $('#myModal').modal('show');\n });\n\n if(window.location.href.indexOf('saved') != -1){\n $('#check_mail').remove();\n $('#id_email').prop('readonly', true);\n }\n\n if(window.location.href.indexOf('saved') == -1 && window.location.href.indexOf('rate') == -1 && $('#id_email').length && $('#id_email').val().length < 5){\n $('#overlapping_div').addClass('overlap');\n }\n\n $(\".se-pre-con\").fadeOut(1000);\n});\n\nfunction remove_overlap(){\n $('.overlap').remove();\n var lowercase_email_string = $('#id_email').val().toLowerCase();\n $('#id_email').val(lowercase_email_string);\n // #todo -- more sophisticated lowercase logic may be implemented on the backend but it's probably not necessary at the moment\n $('#id_email').prop('readonly', true);\n $('#check_mail').remove();\n}\n" }, { "alpha_fraction": 0.6311526298522949, "alphanum_fraction": 0.6317756772041321, "avg_line_length": 26.672412872314453, "blob_id": "6bd5141e876faf93d8efd977849085d67cf85f92", "content_id": "d5cbde211e74dfc5834a73907eef36eb1f51c29b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1605, "license_type": "permissive", "max_line_length": 97, "num_lines": 58, "path": "/web/src/application/validators.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from django.core import validators\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ungettext_lazy\n\nimport ast\n\n\nclass MaxChoicesValidator(validators.BaseValidator):\n message = ungettext_lazy(\n 'Ensure this value has at most %(limit_value)d choice (it has %(show_value)d).', # NOQA\n 'Ensure this value has at most %(limit_value)d choices (it has %(show_value)d).', # NOQA\n 'limit_value'\n )\n code = 'max_choices'\n\n def compare(self, a, b):\n return a > b\n\n def clean(self, x):\n lst = ast.literal_eval(x)\n return len(lst)\n\n\nclass MinChoicesValidator(validators.BaseValidator):\n message = ungettext_lazy(\n 'Ensure this value has at least %(limit_value)d choice (it has %(show_value)d).',\n 'Ensure this value has at least %(limit_value)d choices (it has %(show_value)d).',\n 'limit_value'\n )\n code = 'min_choices'\n\n def compare(self, a, b):\n return a < b\n\n def clean(self, x):\n lst = ast.literal_eval(x)\n return len(lst)\n\n\nclass EverythingCheckedValidator(validators.BaseValidator):\n message = ungettext_lazy(\n 'Ensure that you checked the choice.',\n 'Ensure that you checked all the choices.',\n )\n code = 'everything_checked'\n\n def compare(self, a, b):\n return a != b\n\n def clean(self, x):\n lst = ast.literal_eval(x)\n return len(lst)\n\n\ndef none_validator(x):\n x = ast.literal_eval(x)\n if 'none' in x and len(x) > 1:\n raise ValidationError('You cannot choose both \"None\" and another option.')\n" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7599999904632568, "avg_line_length": 71.22222137451172, "blob_id": "f0f2a4de22fe9f2151a7683b48e81e9160af5459", "content_id": "fb0ae641c4ef003406c6a7a342c0e5de6782888c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1950, "license_type": "permissive", "max_line_length": 448, "num_lines": 27, "path": "/README.md", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "## Installation\n\n- install Pillow prerequisites: `apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk`\n- `virtualenv -p python3 venv`\n- `source venv/bin/activate`\n- `pip install -r requirements.txt`\n- `pip install -r requirements.devel.txt` # not needed in production\n- add `.env` file to the directory where manage.py is\n- `.env` file: add `SECRET_KEY`\n- `.env` file: add path to `DJANGO_SETTINGS_MODULE` (default is `opencon_project.settings.developer`)\n- on a new machine (with empty database): `./manage.py add_airports`, `./manage.py add_institutions`, `./manage.py add_organizations`\n- note: `./manage.py add_countries` is not needed (because autocomplete was removed & countries are now in a dropdown menu)\n- `./manage.py migrate`\n- `./manage.py collectstatic` (needed in production for static file serving using WhiteNoise)\n- `./manage.py runserver`\n\n## Working with the app\n\n- before accessing the admin interface: `./manage.py createsuperuser`\n- add rating users: http(s)://server:port/admin/rating/user/ -- then check UUIDs\n- log in as rating user: http(s)://server:port/rate/login/11112222333344445555666677778888/\n\nNote: Be absolutely sure to install up-to-date requirements from requirements.txt. For example, as of 2016-05-15, this project requires *modified* `django-bootstrap-form` forked by @ZoltanOnody (otherwise on forms, the sequence \"verbose_name -> help_text -> form field\" will not be displayed in the correct order). If a different version of `django-bootstrap-form` is already installed, uninstall and re-install it to display form fields correctly.\n\n## Modifying the app\n\nAfter changing the `recalculate_ratings` function (in `application/models.py`), e.g. when the the logic of moving ratings between round 1 and round 2 is modified, it's necessary to recalculate the values already stored in the database using `./manage.py recalculate_ratings`.\n" }, { "alpha_fraction": 0.4405043423175812, "alphanum_fraction": 0.45784083008766174, "avg_line_length": 17.128570556640625, "blob_id": "81493220c923228618e9c7accb88a56c280d6a86", "content_id": "f34c7cfd00b762d13ac56f65b65cd673d49c24d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1269, "license_type": "permissive", "max_line_length": 75, "num_lines": 70, "path": "/web/src/rating/urls.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "\"\"\"\nApplication urlconfig\n\"\"\"\nfrom django.conf.urls import url\n\nfrom . import views\n\n\nurlpatterns = [\n url(\n r'^login/(?P<uuid>[0-9a-f-]{32})/$',\n views.Login.as_view(),\n name='login',\n ),\n url(\n r\"^logout/$\",\n views.Logout.as_view(),\n name=\"logout\"\n ),\n\n url(\n r\"^round1/$\",\n views.RateView.as_view(),\n name=\"rate_round1\"\n ),\n url(\n r\"^round2/$\",\n views.Rate2View.as_view(),\n name=\"rate_round2\"\n ),\n url(\n r\"^stats/$\",\n views.Stats.as_view(),\n name=\"stats\"\n ),\n url(\n r\"^stats2/$\",\n views.Stats2.as_view(),\n name=\"stats2\"\n ),\n\n url(\n r\"^old/$\",\n views.PreviousRatings.as_view(),\n name=\"previous\"\n ),\n url(\n r\"^all2/$\",\n views.AllRound2.as_view(),\n name=\"all2\"\n ),\n\n url(\n r\"^old2/(?P<rating_pk>[0-9]+)/$\",\n views.Rate2SelectView.as_view(),\n name=\"previous2\"\n ),\n\n url(\n r'^logged_out/$',\n views.TemplateView.as_view(template_name='rating/logged_out.html'),\n name='logged_out'\n ),\n\n url(\n r\"^old/(?P<rating_pk>[0-9]+)/$\",\n views.RateView.as_view(),\n name=\"previous\"\n ),\n]\n" }, { "alpha_fraction": 0.6520000100135803, "alphanum_fraction": 0.6520000100135803, "avg_line_length": 37.46154022216797, "blob_id": "ef2c2ded5023d91e989965ad4bfab8888304301b", "content_id": "ce6205b009676d8fe2fcaafa835e874a0f69b14e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 500, "license_type": "permissive", "max_line_length": 93, "num_lines": 13, "path": "/web/src/application/management/commands/add_institutions.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from django.core.management.base import BaseCommand, CommandError\nfrom ...models import Institution\n\n\nclass Command(BaseCommand):\n help = 'Add countries to database from /data/institution_list.txt'\n\n def handle(self, *args, **options):\n with open('data/institution_list.txt') as file:\n for row in file.readlines():\n institution, created = Institution.objects.get_or_create(name=row, show=True)\n if created:\n institution.save()\n" }, { "alpha_fraction": 0.6374269127845764, "alphanum_fraction": 0.6578947305679321, "avg_line_length": 29.176469802856445, "blob_id": "fd1359b0921f489300103188019f457ee3362b95", "content_id": "f8ada86f4069d23ac3366701808d3c606d8e9d06", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1026, "license_type": "permissive", "max_line_length": 92, "num_lines": 34, "path": "/web/src/application/test_validators.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from .validators import MaxChoicesValidator, MinChoicesValidator, EverythingCheckedValidator\nfrom django.test import SimpleTestCase\nfrom django.core.validators import ValidationError\n\n\nclass FormValidatorsTest(SimpleTestCase):\n def test_max_choice(self):\n validator = MaxChoicesValidator(2)\n\n self.assertIsNone(validator('[0]'))\n self.assertIsNone(validator('[0, 1]'))\n\n with self.assertRaises(ValidationError):\n validator('[0, 1, 2]')\n\n def test_min_choice(self):\n validator = MinChoicesValidator(2)\n\n self.assertIsNone(validator('[0, 1]'))\n self.assertIsNone(validator('[0, 1, 2]'))\n\n with self.assertRaises(ValidationError):\n validator('[0]')\n\n def test_every_choice(self):\n validator = EverythingCheckedValidator(2)\n\n self.assertIsNone(validator('[0, 1]'))\n\n with self.assertRaises(ValidationError):\n validator('[0]')\n\n with self.assertRaises(ValidationError):\n validator('[0, 1, 2]')\n" }, { "alpha_fraction": 0.6020066738128662, "alphanum_fraction": 0.8210702538490295, "avg_line_length": 53.3636360168457, "blob_id": "197e98bc103fc57b094da6f5d51def4dfeaec5a6", "content_id": "cf493049b65f44e1ca0cacb9f41780272521e0d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 598, "license_type": "permissive", "max_line_length": 165, "num_lines": 11, "path": "/web/src/requirements.txt", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "Django==1.9.11\ndjango-autocomplete-light==3.2.1\ngit+git://github.com/ZoltanOnody/django-bootstrap-form.git@4ae507a8ef09da5fe7825d5e74f3dd6d8950550e\n# BEFORE PATCH: https://web.archive.org/web/20161107194502/https://codeload.github.com/ZoltanOnody/django-bootstrap-form/zip/3b685646ac3df755e705f4d0f5989e3900a2b74e\n# AFTER PATCH: https://web.archive.org/web/20161107194554/https://codeload.github.com/ZoltanOnody/django-bootstrap-form/zip/4ae507a8ef09da5fe7825d5e74f3dd6d8950550e\ndjango-dotenv==1.4.1\ndjango-select-multiple-field==0.4.2\nPillow==3.4.2\npytz==2016.7\nwhitenoise==3.2.2\ngunicorn==19.6.0\n" }, { "alpha_fraction": 0.6768764853477478, "alphanum_fraction": 0.6802423596382141, "avg_line_length": 28.709999084472656, "blob_id": "f633bba38fdb4b9fee3c73dbffdcbfe1085b9639", "content_id": "3c2bcd10a0e58e0823296dda9d9159be6a70b72e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2971, "license_type": "permissive", "max_line_length": 97, "num_lines": 100, "path": "/web/src/application/admin.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Institution, Organization, Application, Country, Draft, Reference\nfrom .forms import ApplicationForm, ChangeStatusAdminForm\n\n\nclass DraftAdmin(admin.ModelAdmin):\n list_display = ('email', 'uuid', 'created_at', 'updated_at', 'inactive')\n fields = ('email', 'uuid', 'created_at', 'updated_at', 'data', 'inactive')\n readonly_fields = ('email', 'uuid', 'created_at', 'updated_at', 'inactive')\n list_per_page = 500 # pagination\n search_fields = ('email', 'uuid')\n\n def has_delete_permission(self, request, obj=None):\n return False\n\n def has_add_permission(self, request):\n return False\n\nadmin.site.register(Draft, DraftAdmin)\n\n\nclass InstitutionAdmin(admin.ModelAdmin):\n pass\n\nadmin.site.register(Institution, InstitutionAdmin)\n\n\nclass OrganizationAdmin(admin.ModelAdmin):\n pass\n\nadmin.site.register(Organization, OrganizationAdmin)\n\n\nclass CountryAdmin(admin.ModelAdmin):\n readonly_fields = ('name', )\n\n def has_delete_permission(self, request, obj=None):\n return False\n\n def has_add_permission(self, request):\n return False\n\n\nadmin.site.register(Country, CountryAdmin)\n\n\nclass ApplicationAdmin(admin.ModelAdmin):\n list_display = ('full_name', 'email', 'status', 'created_at', 'get_rating1',\n 'need_rating1', 'get_rating2', 'need_rating2')\n readonly_fields = ('created_at', 'get_data', 'status', 'status_at', 'status_by', 'status_ip')\n form = ApplicationForm\n search_fields = ('first_name', 'last_name', 'email', )\n\n def has_delete_permission(self, request, obj=None):\n return False\n\n def has_add_permission(self, request):\n return False\n\nadmin.site.register(Application, ApplicationAdmin)\n\n\nclass ChangeStatus(Application):\n class Meta:\n proxy = True\n\n\nclass ChangeStatusAdmin(admin.ModelAdmin):\n list_editable = ('status', )\n list_display = ('full_name', 'email', 'status')\n readonly_fields = ('status_by', 'status_ip', 'status_at')\n list_per_page = 500 # pagination\n search_fields = ('first_name', 'last_name', 'email', )\n form = ChangeStatusAdminForm\n\n def get_changelist_form(self, request, **kwargs):\n kwargs.setdefault('form', ChangeStatusAdminForm)\n return super().get_changelist_form(request, **kwargs)\n\n def get_queryset(self, request):\n return Application.objects.get_all()\n\n def response_change(self, request, obj):\n ip = request.META.get('HTTP_X_REAL_IP') or request.META['REMOTE_ADDR']\n obj.change_status(obj.status, None, ip, obj.status_reason)\n return super().response_change(request, obj)\n\n def has_delete_permission(self, request, obj=None):\n return False\n\n def has_add_permission(self, request):\n return False\n\nadmin.site.register(ChangeStatus, ChangeStatusAdmin)\n\n\nclass ReferenceAdmin(admin.ModelAdmin):\n list_display = ('key', 'name')\n\nadmin.site.register(Reference, ReferenceAdmin)\n" }, { "alpha_fraction": 0.6586414575576782, "alphanum_fraction": 0.6620808243751526, "avg_line_length": 36.51612854003906, "blob_id": "cad40e587d498dc96e3d397c4f8b684ae53c6325", "content_id": "a2b25bb148776900e223f36f8ff5899f7783e345", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1163, "license_type": "permissive", "max_line_length": 75, "num_lines": 31, "path": "/web/src/rating/test_views.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "from django.test import TestCase\nfrom .models import User\nfrom django.core.urlresolvers import reverse\n\n\nclass TestLoginView(TestCase):\n def test_valid_user_login(self):\n user = User.objects.create(email='no@mail.com')\n url = reverse('rating:login', kwargs={'uuid': user.uuid.hex})\n redirect_url = reverse('rating:rate_round1')\n response = self.client.get(url)\n self.assertEqual(self.client.session['user_pk'], user.pk)\n self.assertRedirects(response, redirect_url)\n\n def test_invalid_user_login(self):\n user = User(email='no@mail.com')\n url = reverse('rating:login', kwargs={'uuid': user.uuid.hex})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 404)\n\n\nclass TestLogoutView(TestCase):\n def test_logout_after_login(self):\n user = User.objects.create(email='no@mail.com')\n login_url = reverse('rating:login', kwargs={'uuid': user.uuid.hex})\n login_response = self.client.get(login_url)\n\n logout_url = reverse('rating:logout')\n logout_response = self.client.get(logout_url)\n\n self.assertIsNone(self.client.session.get('user_pk'))\n" }, { "alpha_fraction": 0.7259056568145752, "alphanum_fraction": 0.7313739061355591, "avg_line_length": 44.71875, "blob_id": "d22acb5b84432641090775e717a10aac83c2732a", "content_id": "86a112823529d2e9738b904175bea329ef9c37a1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1463, "license_type": "permissive", "max_line_length": 147, "num_lines": 32, "path": "/web/src/opencon_project/urls.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "\"\"\"opencon_project URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\nfrom django.conf.urls.static import static\n\nfrom django.views.generic import TemplateView\nfrom django.conf import settings\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^', include('application.urls', namespace='application')),\n url(r'^rate/', include('rating.urls', namespace='rating')),\n # url(r'^$', TemplateView.as_view(template_name='base.html'), name='front'),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # todo: not sure if serving media files this way in production is efficent enough\n\nurlpatterns += staticfiles_urlpatterns() # now efficiently serving static files using whitenoise (alternatives: dj-static, nginx)\n" }, { "alpha_fraction": 0.630204975605011, "alphanum_fraction": 0.6415111422538757, "avg_line_length": 27.402088165283203, "blob_id": "c4a7799d2d2c944cfec6d4b21fa155c6f1a8e4bb", "content_id": "588b82ad590e10d96cbdb8dbd0925ca2ce81582d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10891, "license_type": "permissive", "max_line_length": 116, "num_lines": 383, "path": "/web/src/application/data.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "\nOCCUPATION_CHOICES = [\n ('undergraduate', 'Undergraduate Student (studying for bachelor’s degree)'),\n ('master', 'Masters / Professional Student (studying for master’s or professional degree)'),\n ('phd', 'PhD Candidate (studying for PhD)'),\n ('postdoc', 'Post-Doc'),\n ('professor', 'Professor / Teacher'),\n ('research', 'Researcher'),\n ('librarian', 'Librarian'),\n ('nonacademic', 'Non-Academic University Staff'),\n ('publisher', 'Publisher'),\n ('government', 'Government Employee / Civil Servant'),\n ('nonprofit', 'Non Profit / NGO Employee'),\n ('journalist', 'Journalist / Blogger'),\n ('doctor', 'Doctor / Medical Professional'),\n ('lawyer', 'Lawyer / Legal Professional'),\n ('philanthropist', 'Philanthropist'),\n ('developer', 'Software / Technology Developer'),\n ('businessman', 'Businessperson / Entrepreneur'),\n ('none', 'None of these describes me'),\n]\n\nDEGREE_CHOICES = [\n ('bachelor', 'Bachelor’s Degree (BA, BS, etc.)'),\n ('master', 'Master’s Degree (MBA, MFA, etc.)'),\n ('professional', 'Professional Degree (MD, JD, etc.)'),\n ('phd', 'PhD'),\n ('other_postgraduate', 'Other Postgraduate Degree'),\n ('other_professional', 'Other Professional Certification'),\n ('none', 'None of the above'),\n]\n\nEXPERIENCE_CHOICES = [\n ('0', '0 (still in school full time or just starting first career)'),\n ('upto5', '1-5 years'),\n ('upto10', '6-10 years'),\n ('upto15', '11-15 years'),\n ('more16', '16+ years'),\n]\n\nFIELDS_OF_STUDY_CHOICES = [\n (None, 'Please select an option below'),\n ('01', 'Agricultural Sciences - Agricultural biotechnology'),\n ('02', 'Agricultural Sciences - Agriculture, forestry, and fisheries'),\n ('03', 'Agricultural Sciences - Animal and dairy science'),\n ('04', 'Agricultural Sciences - Other agricultural sciences'),\n ('05', 'Agricultural Sciences - Veterinary science'),\n ('06', 'Engineering/Technology - Chemical engineering'),\n ('07', 'Engineering/Technology - Civil engineering'),\n ('08', 'Engineering/Technology - Electrical engineering, electronic engineering, information engineering'),\n ('09', 'Engineering/Technology - Environmental biotechnology'),\n ('10', 'Engineering/Technology - Environmental engineering'),\n ('11', 'Engineering/Technology - Industrial Biotechnology'),\n ('12', 'Engineering/Technology - Materials engineering'),\n ('13', 'Engineering/Technology - Mechanical engineering'),\n ('14', 'Engineering/Technology - Medical engineering'),\n ('15', 'Engineering/Technology - Nano-technology'),\n ('16', 'Engineering/Technology - Other engineering and technologies'),\n ('17', 'Humanities - Art (arts, history of arts, performing arts, music)'),\n ('18', 'Humanities - History and archaeology'),\n ('19', 'Humanities - Languages and literature'),\n ('20', 'Humanities - Other humanities'),\n ('21', 'Humanities - Philosophy, ethics and religion'),\n ('22', 'Medicine/Health Sciences - Basic medicine'),\n ('23', 'Medicine/Health Sciences - Clinical medicine'),\n ('24', 'Medicine/Health Sciences - Health biotechnology'),\n ('25', 'Medicine/Health Sciences - Health sciences'),\n ('26', 'Medicine/Health Sciences - Other medical sciences'),\n ('27', 'Natural Sciences - Biological sciences'),\n ('28', 'Natural Sciences - Chemical sciences'),\n ('29', 'Natural Sciences - Computer and information sciences (incl. library and information science)'),\n ('30', 'Natural Sciences - Earth and related environmental sciences'),\n ('31', 'Natural Sciences - Mathematics'),\n ('32', 'Natural Sciences - Other natural sciences'),\n ('33', 'Natural Sciences - Physical sciences'),\n ('34', 'Social Sciences - Economics and business'),\n ('35', 'Social Sciences - Educational sciences'),\n ('36', 'Social Sciences - Law'),\n ('37', 'Social Sciences - Media and communications'),\n ('38', 'Social Sciences - Other social sciences'),\n ('39', 'Social Sciences - Political Science'),\n ('40', 'Social Sciences - Psychology'),\n ('41', 'Social Sciences - Social and economic geography'),\n ('42', 'Social Sciences - Sociology'),\n ('none', 'None of these describe my field of study'),\n]\n\nAREA_OF_INTEREST_CHOICES = [\n ('open_access', 'Open Access'),\n ('open_education', 'Open Education'),\n ('open_research', 'Open Research Data'),\n ('open_government', 'Open Government Data'),\n ('open_science', 'Open Research / Open Science'),\n ('open_source', 'Free and Open Source Software'),\n]\n\nPARTICIPATION_CHOICES = [\n ('openaccessweek', 'Open Access Week'),\n ('openeducationweek', 'Open Education Week'),\n ('opendataday', 'Open Data Day'),\n ('none', 'None of the above'),\n]\n\nVISA_CHOICES = [\n ('local_person', 'I have a U.S. or Canadian passport and/or will already be in the U.S. in November 2016'),\n ('visa_waiver', 'I am eligible to travel to the U.S. under the Visa Waiver Program'),\n ('have_visa', 'I already have a U.S. visa that will be valid through November 2016'),\n ('need_visa', 'I do not have a visa and would need one to travel to the U.S.'),\n ('not_sure', 'I’m not sure'),\n]\n\nSKILLS_CHOICES = [\n ('advocacy', 'Advocacy and Policy'),\n ('blogging', 'Blogging'),\n ('comms', 'Communications / Media Relations'),\n ('community', 'Community / Grassroots Organizing'),\n ('socialmedia', 'Social Media Campaigns'),\n ('fudraising', 'Fundraising'),\n ('events', 'Event Logistics'),\n ('volunteers', 'Volunteer Management'),\n ('graphics', 'Graphic Design'),\n ('video', 'Video Editing'),\n ('research', 'Research About Open Access / Open Education / Open Data'),\n ('software', 'Software Development'),\n ('other', 'Other'),\n]\n\nEXPENSES_CHOICES = [\n ('transport', 'Transportation to and from Washington, D.C.'),\n ('accomodation', 'Accommodation during the conference'),\n ('conference_fee', 'Conference fee (approx. $300 and includes most meals)'),\n ('visa_fee', 'Visa application fee, if needed (typically $190)'),\n ('none', 'None of the above'),\n]\n\nACKNOWLEDGEMENT_CHOICES = [\n ('ack_privacy', 'I understand that my contact information and other information I provide in this application '\n 'will be handled according to OpenCon’s Privacy Policy.'),\n ('ack_share_reviewers', 'I understand that the information I provide in this application will be shared with '\n 'members of the OpenCon 2016 Application Review Team for purposes of evaluation.'),\n ('ack_share_sponsors', 'I understand that if I have requested a scholarship, the information I provide in this '\n 'application may be shared with sponsors for the purposes of selecting a participant to sponsor.'),\n ('ack_opendata', 'I understand that my responses to the questions marked with a caret (^) may be released '\n 'publicly as Open Data under a CC0 license.'),\n]\n\nOPT_OUTS_CHOICES = [\n ('no_mailinglists', 'Please DO NOT add me to the OpenCon and Right to Research Coalition mailing lists.'),\n ('no_opportunities', 'Please DO NOT use my application to consider me for future opportunities relating to the '\n 'mission of OpenCon (e.g. scholarships to related conferences, events in your area, opportunities for '\n 'collaboration).'),\n]\n\nHOW_DID_YOU_FIND_OUT_CHOICES = [\n ('websearch', 'Internet Search'),\n ('twitter', 'Twitter'),\n ('facebook', 'Facebook'),\n ('blogpost', 'Blog Post'),\n ('mailinglist', 'E-mail List'),\n ('webcast', 'Webcast'),\n ('poster', 'Poster'),\n ('friend', 'Friend / Colleague'),\n ('organization', 'Organization'),\n ('other', 'Other'),\n]\n\nGENDER_CHOICES = [\n ('male', 'Male'),\n ('female', 'Female'),\n ('noanswer', 'Prefer not to answer'),\n ('other', 'I will write my gender in the box below'),\n]\n\nCOUNTRY_LIST=\"\"\"\n Afghanistan\n Albania\n Algeria\n Andorra\n Angola\n Antigua and Barbuda\n Argentina\n Armenia\n Aruba\n Australia\n Austria\n Azerbaijan\n Bahamas, The\n Bahrain\n Bangladesh\n Barbados\n Belarus\n Belgium\n Belize\n Benin\n Bhutan\n Bolivia\n Bosnia and Herzegovina\n Botswana\n Brazil\n Brunei\n Bulgaria\n Burkina Faso\n Burma\n Burundi\n Cambodia\n Cameroon\n Canada\n Cape Verde\n Central African Republic\n Chad\n Chile\n China\n Colombia\n Comoros\n Congo, Democratic Republic of the\n Congo, Republic of the\n Costa Rica\n Cote d'Ivoire\n Croatia\n Cuba\n Curacao\n Cyprus\n Czech Republic\n Denmark\n Djibouti\n Dominica\n Dominican Republic\n East Timor\n Ecuador\n Egypt\n El Salvador\n Equatorial Guinea\n Eritrea\n Estonia\n Ethiopia\n Fiji\n Finland\n France\n Gabon\n Gambia\n Georgia\n Germany\n Ghana\n Greece\n Grenada\n Guatemala\n Guinea\n Guinea-Bissau\n Guyana\n Haiti\n Holy See\n Honduras\n Hong Kong\n Hungary\n Iceland\n India\n Indonesia\n Iran\n Iraq\n Ireland\n Israel\n Italy\n Jamaica\n Japan\n Jordan\n Kazakhstan\n Kenya\n Kiribati\n Kosovo\n Kuwait\n Kyrgyzstan\n Laos\n Latvia\n Lebanon\n Lesotho\n Liberia\n Libya\n Liechtenstein\n Lithuania\n Luxembourg\n Macau\n Macedonia\n Madagascar\n Malawi\n Malaysia\n Maldives\n Mali\n Malta\n Marshall Islands\n Mauritania\n Mauritius\n Mexico\n Micronesia\n Moldova\n Monaco\n Mongolia\n Montenegro\n Morocco\n Mozambique\n Namibia\n Nauru\n Nepal\n Netherlands\n Netherlands Antilles\n New Zealand\n Nicaragua\n Niger\n Nigeria\n North Korea\n Norway\n Oman\n Pakistan\n Palau\n Palestinian Territories\n Panama\n Papua New Guinea\n Paraguay\n Peru\n Philippines\n Poland\n Portugal\n Qatar\n Romania\n Russia\n Rwanda\n Saint Kitts and Nevis\n Saint Lucia\n Saint Vincent and the Grenadines\n Samoa\n San Marino\n Sao Tome and Principe\n Saudi Arabia\n Senegal\n Serbia\n Seychelles\n Sierra Leone\n Singapore\n Sint Maarten\n Slovakia\n Slovenia\n Solomon Islands\n Somalia\n South Africa\n South Korea\n South Sudan\n Spain\n Sri Lanka\n Sudan\n Suriname\n Swaziland\n Sweden\n Switzerland\n Syria\n Taiwan\n Tajikistan\n Tanzania\n Thailand\n Timor-Leste\n Togo\n Tonga\n Trinidad and Tobago\n Tunisia\n Turkey\n Turkmenistan\n Tuvalu\n Uganda\n Ukraine\n United Arab Emirates\n United Kingdom\n United States of America\n Uruguay\n Uzbekistan\n Vanuatu\n Venezuela\n Vietnam\n Yemen\n Zambia\n Zimbabwe\n Country Not Listed\n\"\"\"\n\nCOUNTRY_CHOICES = [(None, 'Please select an option below')]\nCOUNTRY_CHOICES += [((c.strip(), c.strip())) for c in COUNTRY_LIST.strip().split('\\n')]\n# note \"Other\" option added to the original list of countries (because of the instructions)\n" }, { "alpha_fraction": 0.6177377104759216, "alphanum_fraction": 0.6301076412200928, "avg_line_length": 42.06346130371094, "blob_id": "e7949127e9da8b58dd8631cd66a15665adecf878", "content_id": "1da531e66e6a35939d1f88837d3b8eed091f7cfd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22439, "license_type": "permissive", "max_line_length": 321, "num_lines": 520, "path": "/web/src/application/models.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "import string\nimport uuid\nimport random\nimport datetime\n\nfrom django.conf import settings\nfrom django.core.mail import EmailMessage\nfrom django.core.validators import MinLengthValidator\nfrom django.db import models\nfrom django.db.models import Q\nfrom django.template.loader import render_to_string\nfrom django.utils import timezone\nfrom .validators import MaxChoicesValidator, MinChoicesValidator, EverythingCheckedValidator, none_validator\n\nfrom .data import *\nfrom .constants import *\n\n\nSTATUS_CHOICES = [\n ('regular', 'Regular'), # First one is default\n ('blacklisted', 'Blacklist'),\n ('whitelist2', 'Whitelist for round 2'),\n ('whitelist3', 'Whitelist for round 3'),\n ('deleted', 'Deleted'),\n]\n\n\nclass HideInactive(models.Manager):\n def get_queryset(self):\n queryset = super().get_queryset()\n return queryset.filter(inactive=False)\n\n\nclass TimestampMixin(models.Model):\n \"\"\" Mixin for saving the creation time and the time of the last update \"\"\"\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n class Meta:\n abstract = True\n\n\nclass Draft(TimestampMixin, models.Model):\n email = models.EmailField(unique=True)\n data = models.TextField()\n uuid = models.UUIDField(default=uuid.uuid4)\n inactive = models.BooleanField(default=False)\n sent_email_data = models.DateTimeField(blank=True, null=True)\n\n objects = HideInactive()\n all_objects = models.Manager()\n\n def __str__(self):\n return self.email\n\n def send_access(self):\n if self.sent_email_data:\n can_send = timezone.now() - self.sent_email_data > datetime.timedelta(minutes=settings.SEND_ACCESS_INTERVAL)\n else:\n can_send = True\n\n if can_send:\n self.sent_email_data = timezone.now()\n self.save()\n if settings.SEND_EMAILS:\n message = render_to_string('application/email/draft.txt', {'uuid': self.uuid, 'email': self.email,})\n email = EmailMessage(\n subject='OpenCon 2016 Draft Application',\n body=message,\n from_email=settings.DEFAULT_FROM_EMAIL,\n to=[self.email],\n )\n email.content_subtype = \"html\"\n email.send(fail_silently=True)\n return True\n return False\n\n\nclass Airport(models.Model):\n iata_code = models.CharField(max_length=10)\n name = models.CharField(max_length=100)\n\n def __str__(self):\n return '[{}] {}'.format(self.iata_code, self.name)\n\n\nclass Institution(models.Model):\n name = models.CharField(max_length=300)\n show = models.BooleanField(default=False) # shown in autocomplete or not\n\n def __str__(self):\n return self.name\n\n\nclass Organization(models.Model):\n name = models.CharField(max_length=300)\n show = models.BooleanField(default=False) # shown in autocomplete or not\n\n def __str__(self):\n return self.name\n\n\nclass Country(models.Model):\n name = models.CharField(max_length=120)\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name_plural = 'Countries'\n\n# todo: update this form\nMULTIFIELD_NAMES = ['occupation', 'degree', 'participation', 'gender', 'expenses', 'skills', 'opt_outs', 'acknowledgements', ]\nDISPLAYED_FIELDS_ROUND_1 = ['first_name', 'last_name', 'institution', 'organization', 'area_of_interest', 'description', 'interested', 'goal', 'participation', 'participation_text', 'citizenship', 'residence', 'occupation', 'degree', 'experience', 'fields_of_study', 'additional_info', 'twitter_username',]\nDISPLAYED_FIELDS_ROUND_2 = ['first_name', 'last_name', 'institution', 'organization', 'area_of_interest', 'description', 'interested', 'goal', 'participation', 'participation_text', 'citizenship', 'residence', 'occupation', 'degree', 'experience', 'fields_of_study', 'scholarship', 'additional_info', 'twitter_username',]\n\nclass ApplicationManager(models.Manager):\n def get_queryset(self):\n return super().get_queryset().exclude(status='deleted')\n\n def get_all(self):\n return super().get_queryset()\n\n def get_unrated(self, user):\n return self.get_queryset().filter(need_rating1=True).exclude(ratings__created_by=user)\n\n def get_unrated2(self, user):\n return self.get_all_round2().filter(need_rating2=True).exclude(ratings2__created_by=user)\n\n def get_all_round2(self):\n queryset = self.get_queryset().filter(need_rating1=False)\n return queryset.filter(Q(rating1__gte=NEEDED_RATING_TO_ROUND2) | Q(status__exact='whitelist2'))\n\n\nclass Application(TimestampMixin, models.Model):\n # field no. 1\n email = models.EmailField(\n verbose_name='E-Mail Address',\n help_text='Please fill in your e-mail address and click “Start Application” to unlock the rest of the form.',\n unique=True,\n )\n # field no. 2\n first_name = models.CharField(\n verbose_name='First / Given Name',\n max_length=50,\n )\n # field no. 3\n last_name = models.CharField(\n verbose_name='Last / Family Name',\n max_length=50,\n )\n # field no. 4\n nickname = models.CharField(\n verbose_name='Nickname / Preferred Name (Optional)',\n help_text='If you would like us to call you something different than the first name you entered above, '\n 'please tell us here. For example, if your name is “Michael” and you want to be called “Mike.”',\n max_length=50,\n blank=True, null=True,\n )\n # field no. 5\n alternate_email = models.EmailField(\n verbose_name='Alternate E-mail Address (Optional)',\n help_text='If you use another e-mail address that you would like to have on record, please enter it '\n 'here. We will only use this address if we cannot reach you at the address you provided above.',\n blank=True, null=True,\n )\n # field no. 6\n twitter_username = models.CharField(\n verbose_name='Twitter Username (Optional)',\n help_text='Include the username only, for example “@open_con”.',\n max_length=50,\n blank=True, null=True,\n )\n # field no. 7\n institution = models.ForeignKey( # update the related name and verbose name in forms.py\n 'Institution',\n related_name='person',\n blank=True, null=True,\n )\n # field no. 8\n # #todo -- consider renaming \"organization\" (affiliation_2?) + also \"institution\" (affiliation_1?)\n organization = models.ForeignKey( # update the related name and verbose name in forms.py\n 'Organization',\n related_name='person',\n blank=True, null=True,\n )\n # field no. 9\n area_of_interest = models.TextField(\n verbose_name='What is your primary area of interest?^',\n help_text='If there are multiple areas you are interested in, please select the one that best describes '\n 'your interest. Please note that OpenCon focuses on these issues in the specific context of '\n 'research and education.',\n )\n # field no. 10\n description = models.TextField(\n verbose_name='Describe yourself in 1-2 sentences.',\n help_text='Maximum 280 characters (~40 words). It’s up to you what information to provide. Many people '\n 'write something similar to their Twitter or Facebook bio.',\n max_length=280,\n validators=[MinLengthValidator(10)],\n )\n # field no. 11\n interested = models.TextField(\n verbose_name='Why are you interested in Open Access, Open Education and/or Open Data and how does it '\n 'relate to your work? If you are already involved in these issues, tell us how.',\n help_text='Maximum 1600 characters (~250 words). There are many reasons why Open is important. This '\n 'question is asking specifically why Open is important to *you*. Please use your own words '\n 'to describe your perspective and experience.',\n max_length=1600,\n validators=[MinLengthValidator(10)],\n )\n # field no. 12\n goal = models.TextField(\n verbose_name='The biggest goal of OpenCon is to catalyze action. What ideas do you have for advancing '\n 'Open Access, Open Education and/or Open Data, and how would you use your experience at '\n 'OpenCon to have an impact?',\n help_text='Maximum 1600 characters (~250 words).',\n max_length=1600,\n validators=[MinLengthValidator(10)],\n )\n # field no. 13\n # this is an optional question where we don't mention \"(Optional)\" in the verbose_name\n participation = models.TextField(\n verbose_name='Are you planning to participate in any of the following events in the next year? Have '\n 'you participated in any of them in the past?^',\n help_text='Check all that apply.',\n validators=[MinChoicesValidator(1), none_validator],\n )\n # field no. 14\n participation_text = models.TextField(\n verbose_name='For the events you checked, please explain how you participated and/or how you plan to '\n 'participate.',\n help_text='Maximum 600 characters (~100 words).',\n max_length=600,\n blank=True, null=True,\n )\n # field no. 15 (formerly 16)\n citizenship = models.TextField(\n verbose_name='Country of Citizenship^',\n help_text='Please select the country where you are a citizen (i.e. where your passport is from). If your '\n 'country isn’t listed, select “Country Not Listed” and indicate your country in the Comments '\n 'Box at the end of the application form.',\n )\n # field no. 16 (formerly 17)\n residence = models.TextField(\n verbose_name='Country of Residence^',\n help_text='Please select the country where you currently reside. If you are a resident of multiple '\n 'countries, pick the one where you will spend the most time this year. If your country isn’t '\n 'listed, see the previous question for instructions.',\n )\n # field no. 17 (formerly 15)\n # Has special field\n gender = models.CharField(\n max_length=80\n )\n # field no. 18\n occupation = models.TextField(\n verbose_name='What is your primary occupation?^',\n help_text='Please check the occupation that best describes what you do. If there are multiple options '\n 'that equally describe you, you may select up to three.',\n validators=[MaxChoicesValidator(3), none_validator],\n )\n # field no. 19\n degree = models.TextField(\n verbose_name='Which academic degrees have you attained, if any?^',\n help_text='Only check the degrees you have already been awarded. Note that there are no minimum academic '\n 'requirements to attend OpenCon, this question just helps us understand more about you.',\n validators=[none_validator],\n )\n # field no. 20\n experience = models.TextField(\n verbose_name='How many years have you worked in a career full time? For the purposes of this question, '\n 'please do *not* include time when you were a full time student or working full time as '\n 'a PhD candidate.^',\n help_text='If you have worked in multiple careers, please add the years together. Note that there is no '\n 'minimum career experience required to attend OpenCon, this question just helps us understand '\n 'more about you.',\n max_length=80,\n )\n # field no. 21\n fields_of_study = models.TextField(\n verbose_name='Which option below best describes your field of expertise or study?^',\n # #fyi -- \"none_validator\" not needed for this field -- this is Select, not CheckboxSelectMultiple\n )\n # field no. x (DELETED)\n # ideas = models.TextField(\n # verbose_name='What ideas do you have for getting involved in Open Access, Open Education and/or Open Data? '\n # 'If you are already involved, tell us how.',\n # help_text='Maximum 1200 characters (~200 words).',\n # max_length=1200,\n # validators=[MinLengthValidator(10)],\n # )\n # field no. 22\n skills = models.TextField(\n # verbose_name and help_text are defined in forms.py\n )\n # field no. 23\n how_did_you_find_out = models.TextField(\n # verbose_name and help_text are defined in forms.py\n blank=True, null=True,\n )\n # # field no. x (DELETED)\n # visa_requirements = models.TextField(\n # verbose_name='Visa requirements',\n # help_text='Please review information on U.S. Visa eligibility and the Visa Waiver Program (ESTA) select '\n # 'the option below that best describes you. Note that requirements have recently changed. If you '\n # 'are still not sure, select “I’m not sure”.',\n # )\n # field no. 24\n # #todo -- rename field more appropriately?\n scholarship = models.CharField(\n verbose_name='OpenCon is a global event that seeks to bring together participants regardless of their '\n 'ability to pay for travel and expenses. Therefore, we seek to allocate our limited '\n 'scholarship funding carefully to the participants who need it most. How likely would '\n 'you be able to raise or contribute funding to your attendance at OpenCon 2016 if invited?',\n help_text='If you are applying for a sponsored scholarship from a university or organization, please select '\n '“I couldn’t cover any of my expenses and could only attend if a full scholarship is provided.”',\n choices=(\n ('i_can_pay_everything', 'I could cover all of my expenses and do not need any scholarship funding'),\n ('i_can_pay_large_part', 'I could likely cover a large part of my expenses'),\n ('i_can_pay_small_part', 'I could likely cover a small part of my expenses'),\n ('i_can_pay_nothing', 'I couldn’t cover any of my expenses and could only attend if a full scholarship is provided'),\n ),\n default=None,\n max_length=20, # longest string above ('i_can_pay_everything') is 20 characters long\n )\n # field no. 25\n expenses = models.TextField(\n verbose_name='Which expenses would you need a scholarship to pay for?',\n help_text='Please select the expenses for which you would need scholarship funding in order to attend. If you are applying '\n 'for a sponsored scholarship from a university or organization, please select all of the expenses below. Please '\n 'note that scholarships do not include incidental expenses such as airport transit or meals outside of the conference.',\n validators=[none_validator],\n )\n # field no. 26\n location = models.CharField(\n verbose_name='OpenCon 2016 takes place in Washington, DC. If invited to attend, what city would you travel '\n 'to and from to get there?',\n help_text='Please list city, state/province (if applicable) AND country. For example, “San Francisco, '\n 'CA, United States”.',\n max_length=200,\n )\n # field no. 27\n airport = models.ForeignKey(\n 'Airport',\n # verbose_name and help_text are defined in forms.py\n )\n # field no. 28\n additional_info = models.TextField(\n verbose_name='Comments Box (Optional)',\n help_text='Use this box for any additional information you would like to share about yourself, '\n 'projects you work on, or other information that could impact your attendance or participation '\n 'at OpenCon 2016, if invited. Maximum 900 characters, ~150 words.',\n max_length=900,\n blank=True, null=True\n )\n # field no. 29\n opt_outs = models.TextField(\n verbose_name='Opt-Outs',\n help_text='Please check the boxes below to opt-out.',\n blank=True, null=True\n )\n # field no. 30\n acknowledgements = models.TextField(\n help_text='Please check the boxes below to acknowledge your understanding. All boxes must be checked. '\n 'To review OpenCon’s Privacy Policy, click here: http://www.opencon2016.org/privacy',\n validators=[EverythingCheckedValidator(len(ACKNOWLEDGEMENT_CHOICES))],\n )\n\n referred_by = models.CharField(\n max_length=settings.MAX_CUSTOM_REFERRAL_LENGTH,\n blank=True, null=True,\n )\n\n my_referral = models.CharField(\n max_length=10,\n )\n\n data_sent_at = models.DateTimeField(null=True, blank=True)\n\n def save(self, *args):\n if not self.my_referral:\n possible_characters = string.ascii_letters + string.digits\n self.my_referral = ''.join(random.choice(possible_characters) for _ in range(5))\n\n self.recalculate_ratings()\n\n if self.data_sent_at is None:\n self.data_sent_at = timezone.now()\n self.send_data_by_mail()\n\n super().save(*args)\n\n def __str__(self):\n return self.full_name()\n\n def full_name(self):\n return ' '.join([self.first_name, self.last_name])\n\n def send_data_by_mail(self):\n if settings.SEND_EMAILS:\n message = render_to_string('application/email/data.txt', {'object': self, 'first_name': self.first_name, 'nickname': self.nickname, 'my_referral': self.my_referral,})\n email = EmailMessage(\n subject='OpenCon 2016 Application Received',\n body=message,\n from_email=settings.DEFAULT_FROM_EMAIL,\n to=[self.email],\n bcc=settings.EMAIL_DATA_BACKUP,\n )\n email.content_subtype = \"html\"\n email.send(fail_silently=True)\n\n def recalculate_ratings(self):\n try:\n rating1 = sum(r.rating for r in self.ratings.all()) / self.ratings.count()\n except ZeroDivisionError:\n rating1 = 0\n\n try:\n rating2 = sum(r.rating for r in self.ratings2.all()) / self.ratings2.count()\n except ZeroDivisionError:\n rating2 = 0\n\n self.rating1 = rating1\n self.rating2 = rating2\n\n # Normally, every application should have a certain number of reviews\n self.need_rating1 = self.ratings.count() < MAX_REVIEWS_ROUND_ONE\n self.need_rating2 = self.ratings2.count() < MAX_REVIEWS_ROUND_TWO\n\n # However, there are exceptions...\n # If this is a very low quality application\n if self.rating1 <= RATING_R1_LOW_THRESHOLD:\n # And it has exactly 1 review\n if self.ratings.count() == 1:\n # no other reviews are needed (i.e., do not get a second review)\n self.need_rating1 = False\n\n # Or if the rating is in the middle range <X,Y)\n elif NEEDED_RATING_FOR_THIRD_REVIEW_ROUND1 <= self.rating1 < NEEDED_RATING_TO_ROUND2:\n # And it has exactly 2 reviews\n if self.ratings.count() == 2:\n ratings = list(self.ratings.all())\n r1 = ratings[0].rating\n r2 = ratings[1].rating\n\n # And the difference between them is big enough\n if abs(r1-r2) > NEEDED_DIFFERENCE_FOR_THIRD_REVIEW_ROUND1:\n # it needs a 3rd review (\"third opinion\")\n self.need_rating1 = True\n\n if self.status == 'blacklisted':\n self.rating1 = 0\n self.rating2 = 0\n self.need_rating1 = False\n self.need_rating2 = False\n elif self.status == 'whitelist2':\n self.need_rating1 = False\n elif self.status == 'whitelist3':\n self.need_rating1 = False\n self.need_rating2 = False\n\n rating1 = models.FloatField(default=0)\n rating2 = models.FloatField(default=0)\n need_rating1 = models.BooleanField(default=True)\n need_rating2 = models.BooleanField(default=True)\n\n def get_rating1(self):\n return round(self.rating1, 1)\n\n def get_rating2(self):\n return round(self.rating2, 1)\n\n objects = ApplicationManager()\n\n def get_data(self, fields=None):\n fields = fields or [x for x in self.__dict__.keys() if not x.startswith('_')]\n data = []\n for field_name in fields:\n current_field = {}\n clean = self._meta.get_field(field_name)\n value = getattr(self, field_name)\n if field_name=='area_of_interest':\n value=''.join([item[1] for item in AREA_OF_INTEREST_CHOICES if item[0] == value])\n if field_name=='experience':\n value=''.join([item[1] for item in EXPERIENCE_CHOICES if item[0] == value])\n if field_name=='fields_of_study':\n value=''.join([item[1] for item in FIELDS_OF_STUDY_CHOICES if item[0] == value])\n if value:\n current_field.update({'title': clean.verbose_name, 'content': value, 'name': field_name})\n if clean.help_text:\n current_field.update({'help': clean.help_text})\n if current_field:\n data.append(current_field)\n return data\n\n status = models.TextField(choices=STATUS_CHOICES, default=STATUS_CHOICES[0][0])\n status_reason = models.TextField(null=True, blank=True)\n status_by = models.ForeignKey('rating.User', related_name='statuses', null=True, blank=True)\n status_ip = models.GenericIPAddressField(blank=True, null=True)\n status_at = models.DateTimeField(blank=True, null=True)\n\n def change_status(self, to, by, ip, reason):\n self.status = to\n self.status_by = by\n self.status_ip = ip\n self.status_at = timezone.now()\n self.status_reason = reason\n self.save()\n\n\nclass Reference(TimestampMixin, models.Model):\n key = models.CharField(max_length=settings.MAX_CUSTOM_REFERRAL_LENGTH, unique=True)\n name = models.CharField(max_length=100, blank=True, null=True)\n text = models.TextField(blank=True, null=True)\n image = models.ImageField(upload_to='organizations/', blank=True, null=True)\n deadline = models.DateTimeField(blank=True, null=True)\n\n def __str__(self):\n return '{1} - {0}'.format(self.name, self.key)\n" }, { "alpha_fraction": 0.7795031070709229, "alphanum_fraction": 0.782608687877655, "avg_line_length": 28.272727966308594, "blob_id": "6b997756a9c2539e4d315fb1fb2d9091fd1f910d", "content_id": "58ac05ee740af06911d1b4c73ae2657c1f44b808", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 322, "license_type": "permissive", "max_line_length": 56, "num_lines": 11, "path": "/web/src/cleanup_migrations.sh", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\nrm db.sqlite3\nrm -R application/migrations\nrm -R rating/migrations\n./manage.py makemigrations application\n./manage.py makemigrations rating\n./manage.py migrate\n./manage.py add_countries\n./manage.py add_institutions\n./manage.py add_organizations\n./manage.py createsuperuser --user admin --email admin@example.com\n" }, { "alpha_fraction": 0.6387520432472229, "alphanum_fraction": 0.6444991827011108, "avg_line_length": 47.720001220703125, "blob_id": "09bab175df53317bb3ce403e5779ce5d7970355e", "content_id": "daff563f960df48c197b16e0007a581f1bc6b82e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1218, "license_type": "permissive", "max_line_length": 168, "num_lines": 25, "path": "/web/src/application/management/commands/print_drafts.py", "repo_name": "RightToResearch/django-opencon2016-app", "src_encoding": "UTF-8", "text": "import ast\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom ...models import Draft\n\nclass Command(BaseCommand):\n help = 'Prints drafts to STDOUT. Usage: python3 manage.py print_drafts > drafts_export.tsv'\n\n def handle(self, *args, **options):\n fields=\"\"\"email first_name last_name nickname alternate_email twitter_username institution organization area_of_interest description interested\n goal participation participation_text citizenship residence gender_0 gender_1 occupation degree experience fields_of_study skills_0 skills_1\n how_did_you_find_out_0 how_did_you_find_out_1 scholarship expenses location airport additional_info opt_outs acknowledgements referred_by\"\"\".strip().split()\n drafts = Draft.objects.all()\n print('uuid\\t', end='')\n for field in fields:\n print(field + '\\t', end='')\n print('')\n for draft in drafts:\n uuid=draft.uuid\n data=ast.literal_eval(draft.data)\n print(str(draft.uuid) + '\\t', end='')\n for field in fields:\n value=str(data.get(field, \"['*NONEXISTENT*']\"))\n print(value + '\\t', end='')\n print('')\n" } ]
42
nbaak/discordbot
https://github.com/nbaak/discordbot
38435ded162ccf15859d12da238c6f59a2e7af74
f5a3dea141d6c9d951e0bb2e88f5210699d326bb
476ef749ff4a44d6538e2fc75a26db712ad71a9c
refs/heads/master
2023-08-28T14:05:53.137265
2021-10-13T12:39:37
2021-10-13T12:39:37
415,034,368
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5942249298095703, "alphanum_fraction": 0.5942249298095703, "avg_line_length": 29.627906799316406, "blob_id": "7f4976c19c9cdd8e318616d5ae979ba06a2e5f4c", "content_id": "a1427ca5a59173da570aab97513401a6e1d5eb94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1316, "license_type": "no_license", "max_line_length": 94, "num_lines": 43, "path": "/src/cogs/ai.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "from discord.ext import commands\nfrom ai.Bottler import Bottler\nimport CONFIG\n\nclass AI(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n MODEL_FILE_NAME = 'model/chatbot.model'\n TOKEN_FILE_NAME = 'pattern.tokens'\n LABELS_FILE_NAME = 'labels.tokens'\n INTENTS_FILE = 'intents.json'\n self.ai = Bottler(MODEL_FILE_NAME, TOKEN_FILE_NAME, LABELS_FILE_NAME, INTENTS_FILE)\n\n # Events\n @commands.Cog.listener()\n async def on_ready(self):\n print(f'Extension {self.__class__.__name__} loaded')\n\n \n @commands.Cog.listener('on_message')\n async def answer(self, message):\n if not message.author.bot and not message.content.startswith(self.bot.command_prefix):\n channel = message.channel.name\n if not CONFIG.AI_CHANNELS:\n await self._answer(message)\n elif channel in CONFIG.AI_CHANNELS:\n await self._answer(message) \n \n \n async def _answer(self, message):\n content = message.content\n channel = message.channel\n author = message.author.display_name\n \n reply = self.ai.answer(content.lower(), author)\n if reply:\n await channel.send(reply)\n\n\n\ndef setup(bot):\n bot.add_cog(AI(bot))" }, { "alpha_fraction": 0.5125208497047424, "alphanum_fraction": 0.5141903162002563, "avg_line_length": 23.95833396911621, "blob_id": "abdbf4cd87a5b1f58176f4f1e97fc609cf7e1ae6", "content_id": "b5da0a78b63c387695292a6b177024e623993cb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 599, "license_type": "no_license", "max_line_length": 75, "num_lines": 24, "path": "/src/lib/Wikipedia.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "\nimport wikipedia\nimport random\n\n\nclass WikipediaWrapper:\n \n @staticmethod\n def search(topic):\n try:\n wikis = wikipedia.search(topic)\n \n num_wikis = len(wikis)\n \n # get ONE of them\n wiki = random.choice(wikis)\n summary = wikipedia.summary(wiki, sentences=3)\n page = wikipedia.page(wiki)\n \n content = f\"{page.title}\\n{page.summary.strip()}\\n\\n{page.url}\"\n except Exception as e:\n content = \"something went wrong :(\"\n \n \n return content" }, { "alpha_fraction": 0.6399999856948853, "alphanum_fraction": 0.648888885974884, "avg_line_length": 21.5, "blob_id": "dce3533f28d3ee79da0863056b43ffb8babd6fc5", "content_id": "4a8c8071fd7ee7fa9f22262f2a9e1cc07726805a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 225, "license_type": "no_license", "max_line_length": 92, "num_lines": 10, "path": "/start-bot-container.sh", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nTHIS_DIR=$(dirname $(readlink -f $0))\n\nif [ ! -d ./data ]; then\n mkdir ${THIS_DIR}/data\nfi\n\ndocker rm -f discordbot\ndocker run -it -v ${THIS_DIR}/src/:/bot --name discordbot -d k3nny/discordbot python main.py\n" }, { "alpha_fraction": 0.632478654384613, "alphanum_fraction": 0.632478654384613, "avg_line_length": 15.714285850524902, "blob_id": "efaa56aed880931a13f0f42f85e2a6ffacacd3c5", "content_id": "1f5d438d1b1da5417641840ba10bc4ea2c0f7455", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 117, "license_type": "no_license", "max_line_length": 65, "num_lines": 7, "path": "/src/CONFIG.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "# Configuration\nAPI_TOKEN = ''\nPREFIX = '!'\n\n\n# AI\nAI_CHANNELS = ['development'] # All Channels, if list is empty\n" }, { "alpha_fraction": 0.5262646079063416, "alphanum_fraction": 0.5262646079063416, "avg_line_length": 32.79999923706055, "blob_id": "7bec0a06df9635e2daa9f3812adef2cc14a42427", "content_id": "b62e3edc190c12ea06201440b1fca17a7d9833af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1028, "license_type": "no_license", "max_line_length": 194, "num_lines": 30, "path": "/src/test/test_rhyme.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "\nimport unittest\nfrom lib.Rhymes import Rhymes\n\n\nclass TetstRhymes(unittest.TestCase):\n \n def test_rhyme_augen_german(self):\n word = \"augen\"\n possible_words = [\"taugen\", \"lauben\", \"rauben\", \"tauben\", \"hauben\", \"saugen\", \"laugen\", \"glauben\", \"klauben\", \"stauben\", \"trauben\", \"strauben\", \"auslaugen\", \"schrauben\", \"schnauben\"]\n \n rhyme = Rhymes.reime(word)\n \n assert rhyme in possible_words\n assert rhyme != word\n \n \n def test_rhyme_urlaub_german(self):\n word = \"urlaub\"\n \n rhyme = Rhymes.reime(word)\n \n assert rhyme != word\n \n def test_rhyme_no_rhyme_german(self):\n # if the algorithm does not find anything, return None\n word = \"NONONONONONONONONASDONAOSDNAOSDNAOSDNAODNAONAOSDNOASDNOASDN\"\n \n rhyme = Rhymes.reime(word)\n \n assert rhyme == \"kein Reim gefunden\"\n \n" }, { "alpha_fraction": 0.7009872794151306, "alphanum_fraction": 0.7038081884384155, "avg_line_length": 19.257143020629883, "blob_id": "34cd2c2a3bda5b5fa7ea6a228101fdcd1d2b3e22", "content_id": "fa7c5273f45a38f3e4885507b459b0d317014c07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 709, "license_type": "no_license", "max_line_length": 51, "num_lines": 35, "path": "/src/main.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport discord\nimport os\nfrom discord.ext import commands\n\nimport CONFIG\n\nintents = discord.Intents.default()\n\nbot = commands.Bot(\n command_prefix=CONFIG.PREFIX,\n intents=intents\n\n)\n\n@bot.command()\n@commands.is_owner()\nasync def load(ctx, extension):\n bot.load_extension(f'cogs.{extension}')\n\n@bot.command()\n@commands.is_owner()\nasync def unload(ctx, extension):\n bot.unload_extension(f'cogs.{extension}')\n\n@bot.command()\n@commands.is_owner()\nasync def reload(ctx, extension):\n bot.reload_extension(f'cogs.{extension}')\n\nfor filename in os.listdir('./cogs'):\n if filename.endswith('.py'):\n bot.load_extension(f'cogs.{filename[:-3]}')\n\nbot.run(CONFIG.API_TOKEN)\n" }, { "alpha_fraction": 0.6159090995788574, "alphanum_fraction": 0.6159090995788574, "avg_line_length": 19, "blob_id": "cb741d9162bab2a91acfec0674c9c9e04a12ccfb", "content_id": "fbb6aee20795f3873e380b0698aacd78d25c5205", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 442, "license_type": "no_license", "max_line_length": 60, "num_lines": 22, "path": "/src/cogs/default.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "from discord.ext import commands\n\n\nclass Default(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n\n # Events\n @commands.Cog.listener()\n async def on_ready(self):\n print(f'Extension {self.__class__.__name__} loaded')\n\n # Commands\n @commands.command(brief='check Bot-Status')\n async def alive(self, ctx):\n await ctx.message.add_reaction('✅')\n\n\n\ndef setup(bot):\n bot.add_cog(Default(bot))\n" }, { "alpha_fraction": 0.6477064490318298, "alphanum_fraction": 0.6477064490318298, "avg_line_length": 23.68181800842285, "blob_id": "aa1315719d095718d7ecaca358a1ee093e723531", "content_id": "61eecd44eae4349dcb7ffaf3f5a3cd1ac4ee5e48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 545, "license_type": "no_license", "max_line_length": 93, "num_lines": 22, "path": "/src/cogs/wikipedia.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": " \nfrom lib.Wikipedia import WikipediaWrapper\n\nfrom discord.ext import commands\n\n\nclass Wikipedia(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n\n # Events\n @commands.Cog.listener()\n async def on_ready(self):\n print(f'Extension {self.__class__.__name__} loaded')\n\n @commands.command(name=\"wiki\", brief=\"wiki <topic>\", help='Search Wikipedia for a topic')\n async def wiki(self, ctx, topic): \n await ctx.send(WikipediaWrapper.search(topic))\n\n\ndef setup(bot):\n bot.add_cog(Wikipedia(bot))\n" }, { "alpha_fraction": 0.5140402913093567, "alphanum_fraction": 0.5180045962333679, "avg_line_length": 27.244897842407227, "blob_id": "5a152f099247a9de975820cf6ce6510c06884a60", "content_id": "590feb6ee8587095c784ab71406634680df1ed3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3027, "license_type": "no_license", "max_line_length": 98, "num_lines": 98, "path": "/src/learn.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "import nltk\nnltk.data.path.append('/nltk')\nfrom nltk.stem.snowball import GermanStemmer\n#from nltk.stem.lancaster import LancasterStemmer # english stemmer\n\nfrom lib.Tokenizer import Tokenizer\nfrom ai.Model import Model\nfrom ai.Bottler import Bottler\n#from lib.FileGuard import FileGuard\n\nimport numpy as np\nimport json\n\nMODEL_FILE_NAME = 'model/chatbot.model'\nTOKEN_FILE_NAME = 'pattern.tokens'\nLABELS_FILE_NAME = 'labels.tokens'\nINTENTS_FILE = 'intents.json'\nEPOCHS = 2000\n\ndef get_json_data(json_file):\n with open(json_file) as file:\n data = json.load(file)\n \n return data\n \ndef learn(): \n tokenizer = Tokenizer()\n label_tokenizer = Tokenizer()\n \n try:\n tokenizer.load(TOKEN_FILE_NAME)\n label_tokenizer.load(LABELS_FILE_NAME)\n model = Model(MODEL_FILE_NAME, tokenizer.get_data_size(), label_tokenizer.get_data_size())\n \n except:\n stemmer = GermanStemmer()\n \n data = get_json_data(INTENTS_FILE)\n \n docs_x = []\n docs_y = [] \n \n for intent in data['intents']: \n \n for pattern in intent['patterns']:\n pattern_tokens = tokenizer.classify(pattern.lower())\n docs_x.append(pattern_tokens)\n docs_y.append(label_tokenizer.classify(intent['tag']))\n \n \n training = []\n output = []\n \n for x, y in zip(docs_x, docs_y):\n training.append(tokenizer.tokens_to_1hot(x))\n output.append(label_tokenizer.tokens_to_1hot(y))\n \n \n # lits to np arrays\n training = np.array(training)\n output = np.array(output)\n \n # get a model\n model = Model(MODEL_FILE_NAME, len(training[0]), len(output[0]))\n \n # fit data to model\n model.get_model().fit(training, output, n_epoch=EPOCHS, batch_size=8, show_metric=False)\n \n # save it all\n model.save()\n tokenizer.save(TOKEN_FILE_NAME)\n label_tokenizer.save(LABELS_FILE_NAME)\n \n # check \n for x,y in zip(docs_x, docs_y):\n print (f\"x: {tokenizer.get_value(x)}, y: {label_tokenizer.get_value(y)}\")\n \n print (\"M\", len(training[0]), len(output[0]))\n\n\ndef chat():\n from tensorflow.python.framework import ops\n ops.reset_default_graph()\n \n bottler = Bottler(MODEL_FILE_NAME, TOKEN_FILE_NAME, LABELS_FILE_NAME, INTENTS_FILE)\n \n recv = \"\"\n while True:\n recv = input(\"> \")\n if recv.lower() == 'quit' or recv.lower() == '':\n break\n \n result = bottler.answer(recv.lower(), 'Lauch', .9)\n print(result)\n \nif __name__ == '__main__':\n learn()\n chat()\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n " }, { "alpha_fraction": 0.5732899308204651, "alphanum_fraction": 0.5732899308204651, "avg_line_length": 19.33333396911621, "blob_id": "08aa1eaea2026a42f942aa2658261149d56e0a8f", "content_id": "d4195c5e136f87f85064039c2d78e3986dfd9572", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 307, "license_type": "no_license", "max_line_length": 64, "num_lines": 15, "path": "/src/test/test_wikipedia.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "\nimport wikipedia\n\nfrom lib.Wikipedia import WikipediaWrapper\nimport random\n\n\ntopics = [\"Obama\", \"Linux\", \"Discord\", \"Star Citizen\"]\n\n\nprint(\"\\n\\n+++++++++++++++++++++++++++++++++++++++++++++++\\n\\n\")\n\nfor topic in topics:\n print(f\"TEST: {topic}\")\n print(WikipediaWrapper.search(topic))\n print(\"\")\n\n" }, { "alpha_fraction": 0.6041666865348816, "alphanum_fraction": 0.6041666865348816, "avg_line_length": 10.75, "blob_id": "61d81e7f086b2b5f497656bcca4b80b3af9d58e5", "content_id": "623ab0ba5d65825310e6d285ba49ac5771faf03a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 48, "license_type": "no_license", "max_line_length": 17, "num_lines": 4, "path": "/cleanup.sh", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nrm src/*.tokens\nrm -r src/model/*\n\n" }, { "alpha_fraction": 0.7215189933776855, "alphanum_fraction": 0.746835470199585, "avg_line_length": 18.75, "blob_id": "8059a4dbb9aa3327caf055017fc980ed0f88a4a6", "content_id": "a1dab5af611997ed245790816b71d593699a0345", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 79, "license_type": "no_license", "max_line_length": 34, "num_lines": 4, "path": "/build-container.sh", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ndocker rmi -f k3nny/discordbot\ndocker build -t k3nny/discordbot .\n" }, { "alpha_fraction": 0.6983568072319031, "alphanum_fraction": 0.7136150002479553, "avg_line_length": 34.29166793823242, "blob_id": "a56416f2510a02e5636ed60f88436b22d885f610", "content_id": "7d6793f0eb07ea2764eef2c8890a83c19d788567", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 852, "license_type": "no_license", "max_line_length": 231, "num_lines": 24, "path": "/README.md", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "# Just another Discord Bot\n\n## Requirements\n* Python 3.6\n * discord.py >= 1.7\n * requests\n * wikipedia\n * nltk\n * tensorflow\n\n## Usage\n1. Get your API Key for your Bot Application from the [Developers Page](https://discord.com/developers/applications).\n2. CONFIG.py\n 1. Add API Key to Config.\n 2. Set your AI response channel.\n3. Edit the intents.json to your needs. (It's just a default file in german atm).\n4. Docker\n 1. Build Docker Container with build-container.sh.\n 2. Learn AI with learn-ai-containered.sh\n 3. Start the Container with start-bot-container.sh\n \n \n## Some Words on AI\nThis AI is just a very simple Classifier, it trys to match incomming words to known patterns. If you want to use this AI properly, you need a lot of Data and Training. The pre set intents.json is not nearly big enough to be useful.\n\n " }, { "alpha_fraction": 0.7327021360397339, "alphanum_fraction": 0.7348871231079102, "avg_line_length": 27.020408630371094, "blob_id": "48045c0a147e3467bb0c61ab28f17ee7e0c415b8", "content_id": "7884ef9ab0e88de6156637ab5fac5974691d33ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1373, "license_type": "no_license", "max_line_length": 120, "num_lines": 49, "path": "/src/test/test_nltk.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "import nltk\nfrom nltk.stem.lancaster import LancasterStemmer\nfrom nltk.stem.snowball import GermanStemmer\n\nfrom lib.Tokenizer import Tokenizer\n\n#nltk.data.path.append('./nltk')\n#nltk.download('punkt', download_dir=\"./nltk\")\n#nltk.download('wordnet', download_dir=\"./nltk\")\n\n#stemmer = LancasterStemmer()\nstemmer = GermanStemmer()\n\nsentences = [\"Dies ist ein Test Satz in deusch!\", \"ein einer eine einiges\", \"der die das\", \"wer wie was wieso wesshalb\"]\n\nsentences.append(\"Hallo ich bin ein Text.\")\nsentences.append(\"Hi, wie geht es?\")\nsentences.append(\"Programme\")\nsentences.append(\"Program\")\nsentences.append(\"Programierer\")\nsentences.append(\"Programiererin\")\nsentences.append(\"Text text texte texten\")\n#\\nThis is an english sentences with some interesting things and stuff.\\nsentence sentences \"\n\n\nprint(sentences)\n\n# tokenizer = Tokenizer()\n#\n# for sentence in sentences:\n# tokens = tokenizer.classify(sentences)\n# print (tokens)\n#\n# re_sentence = tokenizer.get_value(tokens)\n# print(re_sentence)\n#\n# print(tokenizer.get_full_lenght_array())\n# print(tokenizer.get_data_size())\n#\n# print(tokenizer.sentence_to_1hot(\"ein Test\"))\n# print(tokenizer.sentence_to_1hot(\"Test\"))\n# print(tokenizer.sentence_to_1hot(\"zweiter Test\"))\n\n\nfor sentence in sentences:\n print('normal:', sentence)\n stemmed = stemmer.stem(sentence)\n print('stemmed:', stemmed)\n print()\n" }, { "alpha_fraction": 0.6473397016525269, "alphanum_fraction": 0.6473397016525269, "avg_line_length": 33.093021392822266, "blob_id": "f961aa62d624c33d57abfd14c0620e5991e6732e", "content_id": "67cd75dd7dad4ff25e4102d3502b69054460a0ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1466, "license_type": "no_license", "max_line_length": 107, "num_lines": 43, "path": "/src/cogs/admin.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom typing import Optional\n\nfrom discord import Embed, Member\nfrom discord.ext import commands\n\n\nclass Admin(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_ready(self):\n print(f'Extension {self.__class__.__name__} loaded')\n\n @commands.command(name='userinfo', brief='Userinfo', help='get info for user')\n @commands.is_owner()\n async def user_info(self, ctx, target: Optional[Member]):\n target = target or ctx.author\n\n e = Embed(title=\"User Information\", color=target.color, timestamp=datetime.utcnow())\n e.set_thumbnail(url=target.avatar_url)\n\n e.set_author(name=target.display_name)\n e.add_field(name='ID', value=target.id)\n e.add_field(name='Bot', value=target.bot)\n\n e.add_field(name='Created at', value=target.created_at.strftime(\"%d/%m/%Y %H:%M:%S\"), inline=False)\n if hasattr(target, 'joined_at'):\n e.add_field(name='Joined at', value=target.joined_at.strftime(\"%d/%m/%Y %H:%M:%S\"))\n\n await ctx.send(embed=e)\n\n @commands.command(name='clear', brief='delete <x> messages', help='delete last <x> messages')\n @commands.is_owner()\n async def purge_messages(self, ctx, count: Optional[int]):\n deleted = await ctx.channel.purge(limit=count)\n await ctx.author.send('Deleted {} Messages'.format(len(deleted)))\n\n\ndef setup(bot):\n bot.add_cog(Admin(bot))\n" }, { "alpha_fraction": 0.5476056337356567, "alphanum_fraction": 0.5504225492477417, "avg_line_length": 33.80392074584961, "blob_id": "6f4787dcab1df9acb514622a30a6fa6b4c9597cd", "content_id": "979ef650af8be70fc1c3b6b8cd062ae321647834", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1775, "license_type": "no_license", "max_line_length": 108, "num_lines": 51, "path": "/src/ai/Bottler.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "\nimport json\nimport random\n\nfrom lib.Tokenizer import Tokenizer\nfrom ai.Model import Model\n\nfrom tensorflow.python.framework import ops\nops.reset_default_graph()\n\ndef json_load(file):\n with open(file, 'r') as f:\n return json.load(f)\n\n\nclass Bottler:\n \n def __init__(self, model_path, word_tokens_path, label_tokens_path, intents):\n self.tokenizer = Tokenizer()\n self.label_tokenizer = Tokenizer()\n \n self.__load(model_path, word_tokens_path, label_tokens_path)\n self.intents = json_load(intents)\n \n \n def answer(self, text, user = None, threshold = .75):\n prolly_tokens = self.tokenizer.sentence_to_1hot(text)\n # print(prolly_tokens)\n if max(prolly_tokens):\n result, probability = self.model.predict_max([prolly_tokens]) \n label = self.label_tokenizer.get_value([result])[0]\n \n if probability >= threshold:\n for intent in self.intents['intents']:\n if intent['tag'] == label:\n if label == \"greeting\" and user:\n if random.random() > .5:\n return f\"Hallo {user}!\"\n else:\n return random.choice(intent['responses'])\n else:\n return random.choice(intent['responses'])\n \n return None\n \n \n \n def __load(self, model_path, word_tokens_path, label_tokens_path):\n self.tokenizer.load(word_tokens_path)\n self.label_tokenizer.load(label_tokens_path)\n self.model = Model(model_path, self.tokenizer.get_data_size(), self.label_tokenizer.get_data_size())\n self.model.load()" }, { "alpha_fraction": 0.6264089941978455, "alphanum_fraction": 0.6264089941978455, "avg_line_length": 24.79166603088379, "blob_id": "6ce41e7538c97fbe573ccb7cd87072eca31a8719", "content_id": "0e275284dcecc2a75beac9798852cc39ea90bd87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 621, "license_type": "no_license", "max_line_length": 61, "num_lines": 24, "path": "/src/cogs/rhyme.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": " \nfrom lib.Rhymes import Rhymes\nfrom discord.ext import commands\n\n\nclass Rhyme(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n\n # Events\n @commands.Cog.listener()\n async def on_ready(self):\n print(f'Extension {self.__class__.__name__} loaded')\n\n @commands.command(brief='!reime <word> - german rhymes')\n async def reime(self, ctx, word):\n await ctx.send(Rhymes.reime(word))\n \n @commands.command(brief='!rhyme <word> - english rhymes')\n async def rhyme(self, ctx, word):\n await ctx.send(Rhymes.rhyme(word))\n\ndef setup(bot):\n bot.add_cog(Rhyme(bot))\n" }, { "alpha_fraction": 0.5081782341003418, "alphanum_fraction": 0.5087422728538513, "avg_line_length": 24.130434036254883, "blob_id": "c6bb23aab3d206e34b1017b00ab26f7aa2585fcc", "content_id": "7b3bebdc54456921662a81a8c1251cfd8b8eb61c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1774, "license_type": "no_license", "max_line_length": 127, "num_lines": 69, "path": "/src/lib/Rhymes.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "import pronouncing\nimport random\nimport requests\nimport duden\nfrom bs4 import BeautifulSoup as bs\n\n\nclass Rhymes(): \n \n @staticmethod \n def rhyme(word):\n return Rhymes.rhyme_en(word)\n \n @staticmethod \n def reime(word):\n rhyme = Rhymes.rhyme_de(word)\n if rhyme:\n return rhyme\n else:\n return \"kein Reim gefunden\"\n \n @staticmethod\n def rhyme_en(word):\n try:\n return random.choice(pronouncing.rhymes(word))\n \n except Exception as e:\n print (f\"Exception {e}\")\n return \"no Rhyme found :(\"\n \n \n @staticmethod\n def rhyme_de(word):\n url = f\"https://www.was-reimt-sich-auf.de/{word}.html\"\n \n req = requests.get(url)\n soup = bs(req.content, 'html.parser')\n\n\n elements = soup.find_all(class_='good-rhyme')\n \n if not elements:\n elements = soup.find(class_='rhymes').find_all('li')\n \n if elements:\n rhymes = []\n for element in elements:\n try:\n if word != element['data-rhyme']:\n rhymes.append(element['data-rhyme'])\n except:\n pass\n \n return random.choice(rhymes)\n else:\n return None\n \n\n @staticmethod \n def syllables(word):\n return Rhymes.syllables_de(word)\n \n @staticmethod \n def syllables_de(word):\n w = duden.get(word)\n try:\n return ' '.join(w.word_separation)\n except:\n return f\"{word} ist kein bekanntes Wort oder es ist nicht richtig geschrieben. Groß-/Kleinschreibung sind wichtig!\"\n \n \n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6127989888191223, "alphanum_fraction": 0.6147382259368896, "avg_line_length": 31.723403930664062, "blob_id": "1938f8c1734a4da4ee265261219081be171e1b04", "content_id": "c908415088f7a233190616520be85cec992c98cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1547, "license_type": "no_license", "max_line_length": 112, "num_lines": 47, "path": "/src/ai/Model.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "\nimport tflearn\nimport tensorflow as tf\nimport pickle\nimport numpy as np\n\n\nclass Model(): \n \n def __init__(self, filename, input_size=None, output_size=None):\n self.model = self.__create_network(input_size, output_size)\n \n self.filename = filename\n self.inputs = input_size\n self.outputs = output_size\n \n def __create_network(self, input_size, output_size):\n net = tflearn.input_data(shape=[None, input_size])\n net = tflearn.fully_connected(net, 8)\n net = tflearn.fully_connected(net, 8)\n net = tflearn.fully_connected(net, output_size, activation=\"softmax\")\n net = tflearn.regression(net)\n \n model = tflearn.DNN(net)\n return model\n \n def predict(self, data):\n return self.model.predict(data)\n \n def predict_max(self, data):\n probabilities_data = self.predict(data)[0] # get probabilites for all possible outcomes\n probability_index = np.argmax(probabilities_data) # returns the index with the highest probability\n probability_of_index = probabilities_data[probability_index]\n \n # debug..\n print(f\"index: {probability_index}, probability: {probability_of_index}\")\n print(probabilities_data)\n \n return probability_index, probability_of_index\n \n def get_model(self):\n return self.model\n \n def save(self):\n self.model.save(self.filename)\n \n def load(self): \n self.model.load(self.filename)\n " }, { "alpha_fraction": 0.41605839133262634, "alphanum_fraction": 0.43065693974494934, "avg_line_length": 25.19230842590332, "blob_id": "e863e4683f680be275789231b78515986b52ec12", "content_id": "c51d3f1aaa108ff62089ffff22c4ffcdf3022a35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1370, "license_type": "no_license", "max_line_length": 127, "num_lines": 52, "path": "/src/lib/Dice.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "import random\nimport re\n\n\nclass Dice:\n \n def __init__(self):\n pass \n \n @staticmethod\n def roll(dice = None):\n result = Dice.is_valid(dice)\n \n if dice == None:\n return \"1d6\", random.randint(1,6)\n \n elif result: \n dices = int(result[1])\n eyes = int(result[2])\n \n if isinstance(dices, int) and isinstance(eyes, int) and dices >= 0 and eyes >= 0 and dices <= 100 and eyes <= 1000:\n results = []\n output = \"\"\n for _ in range(dices):\n d = random.randint(1, eyes)\n results.append(d)\n \n results.sort(reverse=True)\n output = Dice.to_string(results)\n string = f\"{output} total: {sum(results)}\" \n return f\"{dices}d{eyes}\", string\n \n else:\n return None, \"no valid dice\"\n \n @staticmethod\n def to_string(contents):\n output = \"\"\n for value in contents:\n output += f\"{value} \"\n \n return output\n \n \n @staticmethod\n def is_valid(dice):\n if dice:\n pattern = \"([0-9]+)d([0-9]+)\"\n return re.match(pattern, dice)\n \n else:\n return False\n " }, { "alpha_fraction": 0.6800000071525574, "alphanum_fraction": 0.7519999742507935, "avg_line_length": 16.928571701049805, "blob_id": "3d529095a3873ba34d4f80162702d5695001857a", "content_id": "e629e8a3c188c545d798fe4e0beaed11c8034597", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 250, "license_type": "no_license", "max_line_length": 81, "num_lines": 14, "path": "/Dockerfile", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "FROM python:3.8\n\nRUN mkdir /bot\n\nRUN chown -R 1000:1000 /bot\nRUN chmod +s /bot\n\nRUN pip install nltk numpy tflearn tensorflow duden pronouncing discord wikipedia\n\n# for now as root.. even if this is not a good solution,\n#USER 1000:1000\n\n\nWORKDIR /bot" }, { "alpha_fraction": 0.5310296416282654, "alphanum_fraction": 0.5334978699684143, "avg_line_length": 30.29213523864746, "blob_id": "c35a0e5e0b8fc86cae90d38e7668549cf445c809", "content_id": "95c6f3621d8ef9ae3ae20e8392b7c15605eeb0fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2836, "license_type": "no_license", "max_line_length": 99, "num_lines": 89, "path": "/src/lib/Tokenizer.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "import pickle\nimport nltk\nfrom nltk.stem.lancaster import LancasterStemmer\nfrom nltk.stem.snowball import GermanStemmer\n\nclass Tokenizer():\n \n def __init__(self, language=\"german\", nltk_path=\"./nltk\", stemming=False):\n nltk.data.path.append(nltk_path)\n nltk.download('punkt', download_dir=nltk_path)\n nltk.download('wordnet', download_dir=nltk_path)\n \n self.language = language\n self.stemming = stemming\n \n if language == 'german':\n self.stemmer = GermanStemmer()\n \n else:\n self.stemmer = LancasterStemmer()\n \n self.data = {}\n self.classify_index = -1\n \n \n def classify(self, text, lower=False):\n if lower:\n return self.__classify(text.lower())\n else:\n return self.__classify(text)\n \n def __classify(self, text, add=True):\n tokens = nltk.word_tokenize(text, language=self.language)\n classifiers = []\n \n for token in tokens:\n if token and token not in self.data and add:\n self.classify_index += 1\n self.data[token] = self.classify_index\n \n #print(f\"classify index {self.classify_index}, key: {self.data[token]}, data: {token}\")\n try:\n classifiers.append(self.data[token])\n #print (f\"append: {self.data[token]}\")\n #print (classifiers)\n except:\n pass\n \n return classifiers\n \n def get_value(self, classifiers = []):\n # reverse dict\n reversed_data = dict((v,k) for k, v in self.data.items())\n strings = []\n for classifier in classifiers:\n if classifier in reversed_data:\n strings.append(reversed_data[classifier])\n \n return strings\n \n def get_full_lenght_array(self):\n return [0 for _ in self.data]\n \n def get_data_size(self):\n return len(self.data)\n \n def tokens_to_1hot(self, tokens):\n onehot = self.get_full_lenght_array()\n \n for token in tokens:\n onehot[token] = 1\n \n return onehot\n \n def sentence_to_1hot(self, text):\n tokens = self.__classify(text, False)\n return self.tokens_to_1hot(tokens)\n \n def save(self, filename):\n d_store = {'data': self.data,\n 'index': self.classify_index}\n with open(filename, 'wb') as file:\n pickle.dump(d_store, file, protocol=pickle.HIGHEST_PROTOCOL)\n \n def load(self, filename):\n with open(filename, 'rb') as file:\n d_store = pickle.load(file)\n self.data = d_store['data']\n self.classify_index = d_store['index']\n \n \n \n " }, { "alpha_fraction": 0.6191275119781494, "alphanum_fraction": 0.6258389353752136, "avg_line_length": 26.090909957885742, "blob_id": "57d9c3884b4156b772fe7a5842c99836c36a81a6", "content_id": "cae6b3175ee3f82f65438a2acc67e139cce767a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 596, "license_type": "no_license", "max_line_length": 97, "num_lines": 22, "path": "/src/cogs/dice.py", "repo_name": "nbaak/discordbot", "src_encoding": "UTF-8", "text": "from lib.Dice import Dice as D\nfrom discord.ext import commands\n\n\nclass Dice(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n\n # Events\n @commands.Cog.listener()\n async def on_ready(self):\n print(f'Extension {self.__class__.__name__} loaded')\n\n @commands.command(brief='!roll <dice:optional> - Roll some dice, default 1d6', aliases=['r'])\n async def roll(self, ctx, dice = '1d6'):\n dice, result = D.roll(dice)\n await ctx.send(f\"{ctx.message.author.display_name} used a {dice} and got {result}\")\n\n\ndef setup(bot):\n bot.add_cog(Dice(bot))\n" } ]
23
GJguojin/zymk
https://github.com/GJguojin/zymk
71d5152dbad468cee6c743637ba6c3709448251d
63f83968f687809aa15961573d1da8bb57e353da
2ee205d23fbe232163fabca81b1d9321fb3a47cd
refs/heads/master
2020-04-07T23:00:53.541136
2018-11-23T07:04:59
2018-11-23T07:04:59
158,794,229
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4933774769306183, "alphanum_fraction": 0.5045153498649597, "avg_line_length": 26.8869571685791, "blob_id": "1a2869c48c9ed517a5269a30248f6afff59d5995", "content_id": "bff45aad35fd9aa2e55d2ca940f14eacd2eecfdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3582, "license_type": "no_license", "max_line_length": 119, "num_lines": 115, "path": "/src/com/gj/zymk/zymk.py", "repo_name": "GJguojin/zymk", "src_encoding": "UTF-8", "text": "'''\r\nCreated on 2018年11月23日\r\n\r\n@author: Administrator\r\n'''\r\n#coding=utf-8\r\n\r\nimport requests\r\nfrom urllib import parse\r\nimport urllib.request #获取网址模块\r\nfrom bs4 import BeautifulSoup\r\nfrom selenium import webdriver\r\nimport os\r\n\r\nclass Zymk:\r\n #知音漫客列表url\r\n url =''\r\n #漫画存储位置\r\n outPath=''\r\n \r\n #下载数量 0表示全部\r\n limit=0\r\n\r\n __title=''\r\n \r\n '''\r\n 获取章节页面\r\n '''\r\n def getHtml(self):\r\n papg = urllib.request.urlopen(self.url) #打开图片的网址\r\n html = papg.read() #用read方法读成网页源代码,格式为字节对象\r\n html = html.decode('UTF-8') #定义编码格式解码字符串(字节转换为字符串)\r\n return html\r\n \r\n \r\n def getChapterList(self):\r\n soup = BeautifulSoup(self.getHtml(), 'html.parser')\r\n #print(soup.prettify())\r\n browser = webdriver.Firefox()\r\n #browser.minimize_window()\r\n count =0\r\n try:\r\n for chapter in soup.find(id='chapterList'):\r\n #print(chapter)\r\n self.title = chapter.find('a').get('title')\r\n imgUrl = self.url+chapter.find('a').get('href')\r\n if self.title.isdigit() == False:\r\n self.title = self.title.replace(self.title.split(\"话\")[0],('%03d' %int(self.title.split(\"话\")[0])),1)\r\n #print(title)\r\n #print(imgUrl)\r\n browser.get(imgUrl)\r\n browser.implicitly_wait(10)\r\n self.downloadImage(browser.page_source)\r\n \r\n count =count+1\r\n if self.limit != 0 and count >= self.limit:\r\n break\r\n finally:\r\n browser.close()\r\n \r\n '''\r\n 下载图片\r\n ''' \r\n def downloadImage(self,pageSource):\r\n #print(pageSource)\r\n soup = BeautifulSoup(pageSource, 'html.parser')\r\n img = \"https:\"+soup.find(\"img\", \"comicimg\").get('src')\r\n self.storeImage(img)\r\n \r\n '''\r\n 储存图片\r\n '''\r\n def storeImage(self,url):\r\n url = parse.unquote(url)\r\n print(url)\r\n count=1\r\n res = self.sendRequest(self.handleUrl(url,count))\r\n if res.status_code != 200:\r\n print(\"链接不存在:\"+url)\r\n \r\n if not os.path.exists(self.outPath):\r\n os.makedirs(self.outPath) \r\n \r\n while res.status_code == 200:\r\n path = self.outPath+self.title+'_'+('%02d' %count)+'.jpg'\r\n print(path)\r\n f = open(path,'ab') #存储图片,多媒体文件需要参数b(二进制文件)\r\n f.write(res.content) #多媒体存储content\r\n f.close()\r\n count = count+1\r\n res=self.sendRequest(self.handleUrl(url,count))\r\n \r\n def handleUrl(self,url,count):\r\n urlStrs = url.split('/')\r\n imgName = urlStrs[len(urlStrs)-1]\r\n return url.replace(imgName,imgName.replace(imgName.split(\".\")[0],str(count)))\r\n \r\n def sendRequest(self,url):\r\n return requests.get(url)\r\n \r\n def dealUrl(self,url):\r\n if not url.endswith(\"/\"):\r\n url = url+\"/\" \r\n return url\r\n '''\r\n 构造方法\r\n ''' \r\n def __init__(self,url,outPath):\r\n self.url = self.dealUrl(url)\r\n self.outPath= self.dealUrl(outPath)\r\n \r\n \r\nzymk = Zymk('https://www.zymk.cn/1/','D:/漫画/斗破苍穹/')\r\nzymk.limit =2\r\nzymk.getChapterList()\r\n" } ]
1
GageDeZoort/plot_ZH
https://github.com/GageDeZoort/plot_ZH
50f006de141ecf45a868732ad284a69fabbe7584
3c909dd4e3bb1f10db2d627c7640aff1b244b118
c610943757863ba9f7efbc6c4c7b4608cb38ceb8
refs/heads/master
2022-12-01T05:25:10.931511
2020-08-10T17:12:18
2020-08-10T17:12:18
276,743,800
0
0
null
2020-07-02T20:56:19
2020-07-16T00:43:23
2020-08-10T17:12:18
Python
[ { "alpha_fraction": 0.6194229125976562, "alphanum_fraction": 0.6477128863334656, "avg_line_length": 41.526947021484375, "blob_id": "8f1412945c90fe5293c526e23a5fc7ecfeed1935", "content_id": "babfeff909d9f2aa307b71809995229684b4baf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7105, "license_type": "no_license", "max_line_length": 103, "num_lines": 167, "path": "/make_hists.py", "repo_name": "GageDeZoort/plot_ZH", "src_encoding": "UTF-8", "text": "import sys\nimport argparse\nimport uproot\nimport numpy as np\nimport yaml\nfrom tqdm import tqdm\nimport pickle\nimport ROOT\nimport boost_histogram as bh\nimport mplhep as hep\nfrom matplotlib import pyplot as plt\n\nfrom models.fitter import Fitter\nfrom models.sample import Sample\nfrom models.group import Group\nfrom models.data import Data\nfrom models.reducible import Reducible\nsys.path.append(\"../../TauPOG/TauIDSFs/python/\")\nfrom TauIDSFTool import TauIDSFTool\nfrom TauIDSFTool import TauESTool\nimport ScaleFactor as SF\n \n# >> python MHBG.py configs/config_MHBG.yaml\nparser = argparse.ArgumentParser('MHBG.py')\nadd_arg = parser.add_argument\nadd_arg('config', nargs='?', default='configs/config_MHBG.yaml')\nargs = parser.parse_args()\nwith open(args.config) as f:\n config = yaml.load(f)\n\n# read in parameters from config file\nera, era_int = str(config['year']), config['year']\ntight_cuts, loose_cuts = not config['loose_cuts'], config['loose_cuts']\nloose_cuts = config['loose_cuts']\ndata_driven = config['data_driven']\nshift_ES = config['shift_ES']\nanalysis = config['analysis']\nsign = config['sign']\ntau_ID_SF = config['tau_ID_SF']\nLT_cut = config['LT_cut']\nredo_fit = config['redo_fit']\nfitter = config['fitter']\ndata_dir = config['data_dir']\nmass = config['mass']\n\nif shift_ES not in ['None', 'Down', 'Up']:\n raise ValueError(\"{0} is not a valid tau_ES (please use 'None', 'Down', or 'Up')\"\n .format(tau_ES))\n\ncategories = {1:'eeet', 2:'eemt', 3:'eett', 4:'eeem', \n 5:'mmet', 6:'mmmt', 7:'mmtt', 8:'mmem'}\nlumi = {'2016' : 35.92*10**3, '2017' : 41.53*10**3, '2018' : 59.74*10**3}\n\n# configure the tau energy scale by year\ncampaign = {2016:'2016Legacy', 2017:'2017ReReco', 2018:'2018ReReco'}\nt_ES_tool = TauESTool(campaign[era_int]) # properly ID'd taus\nf_ES_tool = TauESTool(campaign[era_int]) # incorrectly ID'd taus\n\n# configure the TauID Scale Factor (SF) Tool\nantiJet_SF = TauIDSFTool(campaign[era_int], 'DeepTau2017v2p1VSjet', 'Medium')\nantiEle_SF = TauIDSFTool(campaign[era_int], 'antiEleMVA6', 'Loose')\nantiMu_SF = TauIDSFTool(campaign[era_int], 'antiMu3', 'Tight')\n\n# trigger scale factors\nmu_files = {2016:'SingleMuon_Run2016_IsoMu24orIsoMu27.root',\n 2017:'SingleMuon_Run2017_IsoMu24orIsoMu27.root',\n 2018:'SingleMuon_Run2018_IsoMu24orIsoMu27.root'}\nele_files = {2016:'SingleElectron_Run2016_Ele25orEle27.root',\n 2017:'SingleElectron_Run2017_Ele32orEle35.root',\n 2018:'SingleElectron_Run2018_Ele32orEle35.root'}\ntrigger_SF = {'dir':'../tools/ScaleFactors/TriggerEffs/',\n 'fileMuon':'Muon/{0:s}'.format(mu_files[era_int]),\n 'fileElectron':'Electron/{0:s}'.format(ele_files[era_int])}\n\nmu_trig_SF = SF.SFs()\nmu_trig_SF.ScaleFactor(\"{0:s}{1:s}\".format(trigger_SF['dir'],\n trigger_SF['fileMuon']))\nele_trig_SF = SF.SFs()\nele_trig_SF.ScaleFactor(\"{0:s}{1:s}\".format(trigger_SF['dir'],\n trigger_SF['fileElectron']))\n\n# build diTau mass fitter\nFastMTT = Fitter(config['fitter'], ES_tool=t_ES_tool, shift=shift_ES, save_table=False, redo_fit=False)\n\n# build analyzers for each MC group\nreducible = Reducible(categories, antiJet_SF, antiEle_SF, antiMu_SF, fitter=FastMTT)\nrare = Group(categories, antiJet_SF, antiEle_SF, antiMu_SF, fitter=FastMTT)\nsignal = Group(categories, antiJet_SF, antiEle_SF, antiMu_SF, fitter=FastMTT)\nZZ = Group(categories, antiJet_SF, antiEle_SF, antiMu_SF, fitter=FastMTT)\nMC_groups = {\"Reducible\" : reducible, \"Rare\" : rare, \"Signal\" : signal, \"ZZ\" : ZZ}\n\n# open sample csv file\nfor line in open(\"../MC/MCsamples_{0:s}_{1:s}.csv\".format(era, analysis), 'r').readlines():\n vals = line.split(',')\n if (vals[5].lower() == 'ignore'): continue\n nickname, group = vals[0], vals[1]\n if (analysis == 'AZH' and 'AToZh' in nickname):\n if (str(mass) not in nickname): continue \n xsec, total_weight = float(vals[2]), float(vals[4])\n sample_weight = lumi[era]*xsec/total_weight \n path = \"../MC/condor/{0:s}/{1:s}_{2:s}/{1:s}_{2:s}.root\".format(analysis, nickname, era)\n sample = Sample(nickname, path, xsec, total_weight, sample_weight,\n lookup_path=\"lookup_tables\")\n MC_groups[group].add_sample(sample)\n print(\" ... added {0} to {1}\".format(nickname, group))\n\nreducible.reweight_nJets(lumi[era])\n#signal.reweight_samples(10.0)\n\nfor group in MC_groups.keys():\n print(\"Analyzing {0} events\".format(group.lower())) \n\n # add \"free\" hists from ntuple\n for var, hist in config['var_hists'].items():\n MC_groups[group].add_hist(var, hist[0], hist[1], hist[2], from_ntuple=True)\n\n if (group != \"Signal\"): continue\n MC_groups[group].process_samples(tight_cuts=tight_cuts, sign=sign, data_driven=data_driven, \n tau_ID_SF=tau_ID_SF, redo_fit=redo_fit, LT_cut=LT_cut)\n\n# build a data analyzer\n#data_path = data_dir + \"/condor/{0:s}/{1:s}/{1:s}_data.root\".format(analysis, era)\n#data = Data(categories, antiJet_SF, antiEle_SF, antiMu_SF, era_int)\n#data_sample = Sample('data', data_path, 1.0, 1.0, 1.0)\n#data.add_sample(data_sample)\n#data.process_samples(tight_cuts=tight_cuts, sign=sign, data_driven=data_driven,\n# tau_ID_SF=tau_ID_SF, redo_fit=redo_fit, LT_cut=LT_cut)\n\n\n# ---------- output histograms ---------- \ndef output_hists(group, hists, cat=None):\n outdir = \"/eos/uscms/store/user/jdezoort/AZH_hists\"\n with open(\"{0}/{1}_{2}_M{3}_{4}.pkl\"\n .format(outdir, analysis, era, mass, group), 'wb') as f:\n pickle.dump(hists, f, protocol=pickle.HIGHEST_PROTOCOL)\n\ndef output_root(group, hists, cat=None):\n outdir = \"/eos/uscms/store/user/jdezoort/AZH_hists\"\n root_file = uproot.recreate(\"{0}/{1}_{2}_M{3}_{4}.root\"\n .format(outdir, analysis, era, mass, group))\n for name, hists_per_cat in hists.items():\n print(name, hists_per_cat)\n for cat, hist in hists_per_cat.items():\n #print(cat, hist)\n root_file[\"{0}_{1}\".format(cat, name)] = hist.to_numpy()\n \noutdir = \"/eos/uscms/store/user/jdezoort/AZH_hists\"\nfor group in MC_groups.keys(): \n output_hists(group.lower(), MC_groups[group].get_hists())\n output_root(group.lower(), MC_groups[group].get_hists())\n #output_hists(\"data\", data.get_hists())\n\n\"\"\"def pickle_hists(cat, hists, tag):\n for name, hist in hists.items():\n print(\"histograms/{0}_{1}_{2}.pkl\".format(tag, cat, name), hist)\n with open(\"histograms/{0}_{1}_{2}.pkl\".format(tag, cat, name), 'wb') as f:\n pickle.dump(hist, f, protocol=pickle.HIGHEST_PROTOCOL)\n\n# write output to pickle file\nfor cat in categories.values():\n outfile = open(\"histograms/{0}_hists.pkl\".format(cat), \"w+\")\n pickle_hists(cat, data.get_core_hists(cat), \"data\")\n pickle_hists(cat, data.get_extra_hists(cat), \"data\")\n for group in MC_groups.keys():\n pickle_hists(cat, MC_groups[group].get_core_hists(cat), group.lower())\n pickle_hists(cat, MC_groups[group].get_extra_hists(cat), group.lower())\n\"\"\" \n\n\n" }, { "alpha_fraction": 0.5379334092140198, "alphanum_fraction": 0.5774115920066833, "avg_line_length": 40.028167724609375, "blob_id": "53baf1ab33b112e69c3c4cbf3d1354e2b48edc8e", "content_id": "c312a88b76cb3c76937e2b277049b32053deb964", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2913, "license_type": "no_license", "max_line_length": 93, "num_lines": 71, "path": "/models/data.py", "repo_name": "GageDeZoort/plot_ZH", "src_encoding": "UTF-8", "text": "import sys\nimport uproot\nimport numpy as np\nimport yaml\nfrom tqdm import tqdm\nimport ROOT\nimport boost_histogram as bh\n\nfrom .fitter import Fitter\nfrom .sample import Sample\nfrom .group import Group\nsys.path.append(\"../../TauPOG/TauIDSFs/python/\")\nfrom TauIDSFTool import TauIDSFTool\nfrom TauIDSFTool import TauESTool\nimport ScaleFactor as SF\nimport fakeFactor2\n\nclass Data(Group):\n def __init__(self, categories, antiJet_SF, antiEle_SF, antiMu_SF, year, fitter=None):\n Group.__init__(self, categories, antiJet_SF, antiEle_SF, antiMu_SF, fitter=None)\n self.year = year\n self.h_group = []\n\n def get_fake_weights(self, f1, f2):\n w1 = f1/(1.0-f1)\n w2 = f2/(1.0-f2)\n return w1, w2, w1*w2\n\n def apply_fake_weights(self, sample, tight1, tight2, WP=16):\n fe, fm, ft_et, ft_mt, f1_tt, f2_tt = 0.0390, 0.0794, 0.1397, 0.1177, 0.0756, 0.0613\n fW1, fW2, fW0 = {}, {}, {}\n fW1['et'], fW2['et'], fW0['et'] = self.get_fake_weights(fe, ft_et)\n fW1['mt'], fW2['mt'], fW0['mt'] = self.get_fake_weights(fm, ft_mt)\n fW1['tt'], fW2['tt'], fW0['tt'] = self.get_fake_weights(f1_tt, f2_tt)\n fW1['em'], fW2['em'], fW0['em'] = self.get_fake_weights(fe, fm)\n\n self.h_group = np.array(['Reducible' for _ in range(sample.n_entries)])\n for i, (t1, t2) in enumerate(zip(tight1, tight2)):\n if (not t1) and t2: sample.weights[i] = fW1[sample.tt[i]]\n elif t1 and (not t2): sample.weights[i] = fW2[sample.tt[i]]\n elif not (t1 or t2): sample.weights[i] = -fW0[sample.tt[i]]\n else:\n sample.weights[i] = 1.0\n self.h_group[i] = 'data'\n\n def process_samples(self, tight_cuts, sign, data_driven, tau_ID_SF, redo_fit, LT_cut):\n progress_bar= tqdm(self.samples.items())\n for name, sample in progress_bar:\n if (sample.n_entries < 1): continue\n progress_bar.set_description(\"{0}\".format(name.ljust(20)[:20]))\n sample.weights = np.ones(sample.n_entries)\n sample.parse_categories(self.categories, sample.events.array('cat'))\n\n self.fill_cutflow(0.5, sample)\n\n if (tight_cuts):\n self.sign_cut(sample, sign, fill_value=1.5)\n self.btag_cut(sample, fill_value=2.5)\n self.lepton_cut(sample, fill_value=3.5)\n tight1, tight2 = self.get_tight_taus(sample)\n\n if (data_driven):\n self.apply_fake_weights(sample, tight1, tight2, WP=16)\n else:\n h_group = ['data' for _ in range(sample.n_entries)]\n self.tau_cut(sample, tight1, tight2, fill_value=4.5)\n\n self.fill_cutflow(5.5, sample)\n self.H_LT_cut(LT_cut, sample, fill_value=6.5)\n #self.mtt_fit_cut(sample, fill_value=7.5)\n self.fill_hists(sample, blind=True)\n" }, { "alpha_fraction": 0.5696594715118408, "alphanum_fraction": 0.5857022404670715, "avg_line_length": 43.97468185424805, "blob_id": "4d048e58671e07dd03a254dd80a005d81cd61664", "content_id": "2908609897e51ca5364239c7610f994fdf6a72cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3553, "license_type": "no_license", "max_line_length": 93, "num_lines": 79, "path": "/models/reducible.py", "repo_name": "GageDeZoort/plot_ZH", "src_encoding": "UTF-8", "text": "import sys\nimport uproot\nimport numpy as np\nfrom tqdm import tqdm\nimport ROOT\nimport boost_histogram as bh\n\nfrom .fitter import Fitter\nfrom .sample import Sample\nfrom .group import Group\nsys.path.append(\"../../TauPOG/TauIDSFs/python/\")\nfrom TauIDSFTool import TauIDSFTool\nfrom TauIDSFTool import TauESTool\nimport ScaleFactor as SF\n\nclass Reducible(Group):\n def __init__(self, categories, antiJet_SF, antiEle_SF, antiMu_SF, fitter=None):\n Group.__init__(self, categories, antiJet_SF, antiEle_SF, antiMu_SF, fitter)\n\n def reweight_nJets(self, lumi):\n for i in range(1, 5):\n DYnJets = \"DY{0:d}JetsToLL\".format(i)\n norm_1 = self.samples['DYJetsToLL'].total_weight/self.samples['DYJetsToLL'].x_sec\n norm_2 = self.samples[DYnJets].total_weight/self.samples[DYnJets].x_sec\n self.samples[DYnJets].sample_weight = lumi/(norm_1 + norm_2)\n\n for i in range(1, 4):\n WnJets = \"W{0:d}JetsToLNu\".format(i)\n norm_1 = self.samples['WJetsToLNu'].total_weight/self.samples['WJetsToLNu'].x_sec\n norm_2 = self.samples[WnJets].total_weight/self.samples[WnJets].x_sec\n self.samples[WnJets].sample_weight = lumi/(norm_1 + norm_2)\n\n def process_samples(self, tight_cuts, sign, data_driven, tau_ID_SF, redo_fit, LT_cut):\n progress_bar= tqdm(self.samples.items())\n for name, sample in progress_bar:\n if (sample.n_entries < 1): continue\n progress_bar.set_description(\"{0}\".format(name.ljust(20)[:20]))\n if (name == \"DYJetsToLL\" or name == \"WJetsToLNu\"):\n self.reweight_nJet_events(sample, sample.events.array('LHE_Njets'))\n sample.weights *= sample.events.array('weightPUtrue')\n sample.weights *= sample.events.array('Generator_weight')\n sample.parse_categories(self.categories, sample.events.array('cat'))\n self.fill_cutflow(0.5, sample)\n\n if (tight_cuts):\n self.sign_cut(sample, sign, fill_value=1.5)\n self.btag_cut(sample, fill_value=2.5)\n self.lepton_cut(sample, fill_value=3.5)\n tight1, tight2 = self.get_tight_taus(sample)\n self.tau_cut(sample, tight1, tight2, fill_value=4.5)\n\n if (data_driven):\n self.data_driven_cut(sample, fill_value=5.5)\n match_3 = sample.events.array('gen_match_3')\n match_4 = sample.events.array('gen_match_4')\n \n # tau_4: must be real tau\n sample.mask[((sample.tt == 'et') | (sample.tt == 'mt'))\n & match_4 != 5] = False\n # tau_3,4: must be real taus\n sample.mask[(sample.tt == 'tt') & (match_3 != 5) & (match_4 != 5)] = False\n\n if tau_ID_SF: self.add_SFs(sample)\n\n self.H_LT_cut(LT_cut, sample, fill_value=6.5)\n self.fitter.fit(sample)\n self.mtt_fit_cut(sample, fill_value=7.5)\n self.fill_hists(sample)\n\n def reweight_nJet_events(self, sample, LHE_nJets):\n for j in np.where(LHE_nJets > 0)[0]:\n nJets = LHE_nJets[j]\n if (sample.name == \"DYJetsToLL\"):\n DYnJets = \"DY{0}JetsToLL\".format(nJets)\n self.samples[sample.name].weights[j] = self.samples[DYnJets].sample_weight\n\n if (sample.name == \"WJetsToLNu\"):\n WnJets = \"W{0}JetsToLNu\".format(nJets)\n self.samples[sample.name].weights[j] = self.samples[WnJets].sample_weight\n" }, { "alpha_fraction": 0.544071614742279, "alphanum_fraction": 0.5521252751350403, "avg_line_length": 37.534481048583984, "blob_id": "6efd860a55c8ae180c984f1999a44aabc2baea25", "content_id": "1e64689361251f2f289df191efcbee844a2d417f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2235, "license_type": "no_license", "max_line_length": 79, "num_lines": 58, "path": "/models/sample.py", "repo_name": "GageDeZoort/plot_ZH", "src_encoding": "UTF-8", "text": "import uproot\nimport pickle\nimport numpy as np\n\nclass Sample(object):\n def __init__(self, name, path, x_sec, total_weight, sample_weight, \n lookup_path=\"../lookup_tables\"):\n self.name = name\n self.path = path\n self.x_sec = x_sec\n self.total_weight = total_weight\n self.sample_weight = sample_weight\n self.weights = np.array([])\n self.mask = np.array([])\n self.mtt_fit = np.array([])\n self.m4l = np.array([])\n self.mA = np.array([])\n self.mA_c = np.array([])\n self.get_events()\n self.lookup_path = lookup_path\n self.lookup_table = {}\n try: \n lookup_table_file = open(\"{0}/{1}_masses.pkl\"\n .format(lookup_path, self.name), 'rb')\n self.lookup_table = pickle.load(lookup_table_file)\n lookup_table_file.close()\n except: \n print(\"WARNING: creating new lookup table for {0}\"\n .format(self.name))\n self.n_recalculated = 0\n\n\n def show(self):\n print(\"{0} (x_sec = {1:2.2f}, weight = {2:2.2f})\"\n .format(self.name, self.x_sec, self.sample_weight))\n\n def get_events(self):\n try: self.events = uproot.open(self.path)[\"Events\"]\n except AttributeError:\n print(\"ERROR: failed to open file {0:s}\".format(self.path))\n self.n_entries = self.events.numentries\n self.weights = np.ones(self.n_entries)\n self.mask = np.ones(self.n_entries, dtype=bool)\n self.mtt_fit = np.zeros(self.n_entries)\n self.m4l = np.zeros(self.n_entries)\n self.mA = np.zeros(self.n_entries)\n self.mA_c = np.zeros(self.n_entries)\n \n def parse_categories(self, categories, evt_cat_array):\n self.cats = np.array([categories[cat] for cat in evt_cat_array])\n self.ll = np.array([cat[:2] for cat in self.cats])\n self.tt = np.array([cat[2:] for cat in self.cats])\n\n def write_lookup_table(self):\n with open(\"{0}/{1}_masses.pkl\"\n .format(self.lookup_path, self.name), 'wb') as f:\n pickle.dump(self.lookup_table, f, protocol=pickle.HIGHEST_PROTOCOL)\n f.close()\n" }, { "alpha_fraction": 0.4380596876144409, "alphanum_fraction": 0.457782506942749, "avg_line_length": 46.070350646972656, "blob_id": "0a4126ecc6b5a8626680a5cd7dbc23687d88a5aa", "content_id": "7174a5cba6c07690bdc627f230ede5cc0ada0ba4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9380, "license_type": "no_license", "max_line_length": 93, "num_lines": 199, "path": "/models/fitter.py", "repo_name": "GageDeZoort/plot_ZH", "src_encoding": "UTF-8", "text": "import os\nimport numpy as np\nimport ROOT\nimport pickle\nfrom .sample import Sample\nfrom tqdm import tqdm\n\nclass Fitter:\n def __init__(self, mode, ES_tool=None, shift='None', \n save_table=False, redo_fit=True):\n self.mode = mode\n self.ES_tool = ES_tool\n self.shift = shift\n self.save_table = save_table\n self.redo_fit = redo_fit\n\n # load in the SVfit dependencies...\n if (mode == 'SVfit'):\n SV_dir = \"TauAnalysis/ClassicSVfit/src/\"\n SV_files = [\"SVfitIntegratorMarkovChain\",\"ClassicSVfitIntegrand\", \n \"ClassicSVfit\", \"svFitAuxFunctions\", \"MeasuredTauLepton\", \n \"svFitHistogramAdapter\"]\n ROOT.gInterpreter.ProcessLine(\".include .\")\n for SV_file in SV_files:\n path = \"{0}{1}.cc++\".format(SV_dir, SV_file)\n ROOT.gInterpreter.ProcessLine(\".L {0}\".format(path))\n \n # ...or load in the FastMTT dependencies\n elif (mode == 'FastMTT'):\n for baseName in ['../SVFit/MeasuredTauLepton', \n '../SVFit/svFitAuxFunctions'\n ,'../SVFit/FastMTT'] :\n if os.path.isfile(\"{0:s}_cc.so\".format(baseName)) :\n ROOT.gInterpreter.ProcessLine(\".L {0:s}_cc.so\"\n .format(baseName))\n else :\n ROOT.gInterpreter.ProcessLine(\".L {0:s}.cc++\"\n .format(baseName))\n # otherwise, throw error\n else:\n print(\"ERROR: initializing fitter with invalid mode '{0}'\"\n .format(mode))\n\n\n def fit(self, s):\n \n # grab event info\n run, evt, lumi = s.events.array('run'), s.events.array('evt'), s.events.array('lumi')\n \n # grab MET info\n met, metphi = s.events.array('met'), s.events.array('metphi')\n measuredMETx, measuredMETy = met*np.cos(metphi), met*np.sin(metphi)\n covMET_00, covMET_01 = s.events.array('metcov00'), s.events.array('metcov01')\n covMET_10, covMET_11 = s.events.array('metcov10'), s.events.array('metcov11')\n \n # grab the lepton arrays\n ele_mass, muo_mass = 0.511*10**-3, 0.105\n pt_1, pt_2 = s.events.array('pt_1'), s.events.array('pt_2')\n eta_1, eta_2 = s.events.array('eta_1'), s.events.array('eta_2')\n phi_1, phi_2 = s.events.array('phi_1'), s.events.array('phi_2')\n \n # grab the tau arrays\n pt_3, pt_4 = s.events.array('pt_3'), s.events.array('pt_4')\n eta_3, eta_4 = s.events.array('eta_3'), s.events.array('eta_4')\n phi_3, phi_4 = s.events.array('phi_3'), s.events.array('phi_4')\n m_3, m_4 = s.events.array('m_3'), s.events.array('m_4')\n dm_3, dm_4 = s.events.array('decayMode_3'), s.events.array('decayMode_4')\n match_3, match_4 = s.events.array('gen_match_3'), s.events.array('gen_match_4')\n \n # grab original mass fit\n m_sv = s.events.array('m_sv')\n progress_bar = tqdm(np.arange(s.n_entries)[s.mask])\n for i in progress_bar:\n\n # attempt to find value in lookup table\n found_masses = False\n if (self.mode == \"SVfit\"):\n tag = str(run[i]) + str(evt[i]) + str(lumi[i])\n try: \n masses = s.lookup_table[tag]\n s.mtt_fit[i] = masses['mtt_fit']\n s.mA[i] = masses['mA']\n s.mA_c[i] = masses['mA_c']\n found_masses = True\n except:\n s.n_recalculated += 1\n \n if (s.n_recalculated % 2500 == 0 and\n s.n_recalculated >= 2500): s.write_lookup_table()\n \n # if FastMTT, em channel is good-to-go\n if (s.tt[i] == 'em' and self.mode == 'FastMTT'): \n s.mtt_fit[i] = m_sv[i]\n continue\n\n # grab the ll 4-vectors\n l1, l2 = ROOT.TLorentzVector(), ROOT.TLorentzVector()\n if (s.ll[i] == 'ee'):\n l1.SetPtEtaPhiM(pt_1[i], eta_1[i], phi_1[i], ele_mass)\n l2.SetPtEtaPhiM(pt_2[i], eta_2[i], phi_2[i], ele_mass)\n elif (s.ll[i] == 'mm'):\n l1.SetPtEtaPhiM(pt_1[i], eta_1[i], phi_1[i], muo_mass)\n l2.SetPtEtaPhiM(pt_2[i], eta_2[i], phi_2[i], muo_mass)\n \n # build tau 4-vectors\n t1, t2 = ROOT.TLorentzVector(), ROOT.TLorentzVector()\n t1.SetPtEtaPhiM(pt_3[i], eta_3[i], phi_3[i], m_3[i])\n t2.SetPtEtaPhiM(pt_4[i], eta_4[i], phi_4[i], m_4[i])\n\n # apply tau ES corrections\n if (s.tt[i] != 'em'):\n if (s.tt[i] == 'tt'): \n t1 *= self.ES_tool.getTES(pt_3[i], dm_3[i], match_3[i])\n t2 *= self.ES_tool.getTES(pt_4[i], dm_4[i], match_4[i])\n\n # store raw 4l mass\n s.m4l[i] = (l1 + l2 + t1 + t2).M()\n if ((l1+l2+t1+t2).M() < 100): \n print(\"eh!!\", s.m4l[i], s.ll[i]+s.tt[i], l1, l2, t1, t2)\n\n # continue past the mass fit if we already found one\n if (found_masses): continue\n\n # build ROOT objects\n covMET = ROOT.TMatrixD(2,2)\n VectorOfTaus = ROOT.std.vector('MeasuredTauLepton')\n tau_pair = VectorOfTaus()\n covMET[0][0] = covMET_00[i]\n covMET[0][1] = covMET_01[i]\n covMET[1][0] = covMET_10[i]\n covMET[1][1] = covMET_11[i]\n ele_decay = ROOT.MeasuredTauLepton.kTauToElecDecay\n mu_decay = ROOT.MeasuredTauLepton.kTauToMuDecay\n had_decay = ROOT.MeasuredTauLepton.kTauToHadDecay\n \n if (s.tt[i] == 'et' or s.tt[i] == 'em'):\n tau_pair.push_back(ROOT.MeasuredTauLepton(ele_decay, t1.Pt(), \n t1.Eta(), t1.Phi(), \n ele_mass))\n elif (s.tt[i] == 'mt'): \n tau_pair.push_back(ROOT.MeasuredTauLepton(mu_decay, t1.Pt(), \n t1.Eta(), t1.Phi(), \n muo_mass))\n elif (s.tt[i] == 'tt'): \n tau_pair.push_back(ROOT.MeasuredTauLepton(had_decay, t1.Pt(), \n t1.Eta(), t1.Phi(), \n t1.M()))\n if (s.tt[i] != 'em'):\n tau_pair.push_back(ROOT.MeasuredTauLepton(had_decay, t2.Pt(), \n t2.Eta(), t2.Phi(), \n t2.M()))\n elif (s.tt[i] == 'em'):\n tau_pair.push_back(ROOT.MeasuredTauLepton(mu_decay, t2.Pt(),\n t2.Eta(), t2.Phi(),\n muo_mass))\n\n # run SVfit algorithm\n if (self.mode == 'SVfit'):\n svFitAlgo = ROOT.ClassicSVfit(0)\n svFitAlgo.addLogM_fixed(True, 6.)\n svFitAlgo.integrate(tau_pair, measuredMETx[i], measuredMETy[i], covMET)\n mass = svFitAlgo.getHistogramAdapter().getMass()\n s.mtt_fit[i] = mass\n \n # calculate A mass\n tt = ROOT.TLorentzVector()\n tt.SetPtEtaPhiM(svFitAlgo.getHistogramAdapter().getPt(),\n svFitAlgo.getHistogramAdapter().getEta(),\n svFitAlgo.getHistogramAdapter().getPhi(),\n svFitAlgo.getHistogramAdapter().getMass())\n s.mA[i] = (l1 + l2 + tt).M()\n \n # perform a constrained di-tau mass fit\n massConstraint = 125\n svFitAlgo.setDiTauMassConstraint(massConstraint)\n svFitAlgo.integrate(tau_pair, measuredMETx[i], measuredMETy[i], covMET)\n mass_c = svFitAlgo.getHistogramAdapter().getMass()\n\n # calculate constrained A mass \n tt_c = ROOT.TLorentzVector()\n tt_c.SetPtEtaPhiM(svFitAlgo.getHistogramAdapter().getPt(),\n svFitAlgo.getHistogramAdapter().getEta(),\n svFitAlgo.getHistogramAdapter().getPhi(),\n svFitAlgo.getHistogramAdapter().getMass())\n s.mA_c[i] = (l1 + l2 + tt_c).M()\n \n tag = str(run[i]) + str(evt[i]) + str(lumi[i])\n s.lookup_table[tag] = {'mtt_fit':s.mtt_fit[i], \n 'mA':s.mA[i], 'mA_c':s.mA_c[i]}\n \n # run FastMTT algorithm\n elif (self.mode == 'FastMTT'):\n FMTT = ROOT.FastMTT()\n FMTT.run(tau_pair, measuredMETx[i], measuredMETy[i], covMET)\n ttP4 = FMTT.getBestP4()\n s.mtt_fit[i] = ttP4.M()\n \n # in case we've added to the lookup table, write it out\n if (self.mode == 'SVfit'): s.write_lookup_table()\n \n" }, { "alpha_fraction": 0.5169517397880554, "alphanum_fraction": 0.5475717782974243, "avg_line_length": 46.277976989746094, "blob_id": "591eb58f810e68de8de6c20466f592cef0a1048f", "content_id": "c9e6bc37ab174cb6cff67e1549a8724578f5494d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13096, "license_type": "no_license", "max_line_length": 99, "num_lines": 277, "path": "/models/group.py", "repo_name": "GageDeZoort/plot_ZH", "src_encoding": "UTF-8", "text": "import sys\nimport uproot\nimport numpy as np\nimport yaml\nfrom tqdm import tqdm\nimport ROOT\nimport boost_histogram as bh\n\nfrom .fitter import Fitter\nfrom .sample import Sample\n\nsys.path.append(\"../../TauPOG/TauIDSFs/python/\")\nfrom TauIDSFTool import TauIDSFTool\nfrom TauIDSFTool import TauESTool\nimport ScaleFactor as SF\nimport fakeFactor2\n\nclass Group(object):\n def __init__(self, categories, antiJet_SF, antiEle_SF, antiMu_SF, fitter=None):\n self.categories = categories\n self.antiJet_SF = antiJet_SF\n self.antiEle_SF = antiEle_SF\n self.antiMu_SF = antiMu_SF\n self.samples = {}\n self.fitter = fitter\n \n # mtt: fitted di-tau mass\n self.mtt_fit_hists = {cat:bh.Histogram(bh.axis.Regular(10, 0, 200)) \n for cat in categories.values()}\n # m4l: (raw di-lepton + raw di-tau) mass\n self.m4l_hists = {cat:bh.Histogram(bh.axis.Regular(50, 0, 500))\n for cat in categories.values()}\n # mA: (raw di-lepton + fitted di-tau) mass\n self.mA_hists = {cat:bh.Histogram(bh.axis.Regular(50, 0, 500))\n for cat in categories.values()}\n # mA_c: (raw di-lepton + fitted di-tau w/ constraint) mass\n self.mA_c_hists = {cat:bh.Histogram(bh.axis.Regular(50, 0, 500))\n for cat in categories.values()}\n \n self.LT_hists = {cat:bh.Histogram(bh.axis.Regular(10, 0, 200))\n for cat in categories.values()}\n self.ESratio_hists = {cat:bh.Histogram(bh.axis.Regular(200, 0.9, 1.1))\n for cat in categories.values()}\n self.cutflow_hists = {cat:bh.Histogram(bh.axis.Regular(20, 0.0, 20.0))\n for cat in categories.values()}\n \n self.hists = {\"mtt_fit\" : self.mtt_fit_hists, \"m4l\" : self.m4l_hists,\n \"mA\" : self.mA_hists, \"mA_c\" : self.mA_c_hists,\n \"LT\" : self.LT_hists, \"ESratio\" : self.ESratio_hists, \n \"cutflow\" : self.cutflow_hists}\n self.hists_from_ntuple = []\n\n def get_hists(self, cat=None):\n if cat: return {name:hist[cat] for name, hist in self.hists.items()}\n else: return self.hists\n\n def add_hist(self, var, nbins, low, high, from_ntuple=True):\n new_hists = {cat:bh.Histogram(bh.axis.Regular(nbins, low, high))\n for cat in self.categories.values()}\n self.hists[var] = new_hists\n if (from_ntuple): self.hists_from_ntuple.append(var)\n \n def add_sample(self, sample):\n if (sample.n_entries == 0):\n print(\"WARNING: {0} has {1} entries\"\n .format(sample.name, sample.n_entries))\n self.samples[sample.name] = sample\n\n def reweight_samples(self, factor):\n for sample in self.samples.values():\n sample.weights *= factor\n\n def fill_cutflow(self, fill_value, sample):\n for cat in self.categories.values():\n good_evts = (sample.cats == cat) & sample.mask\n to_fill = np.ones(np.count_nonzero(good_evts)) * fill_value\n self.cutflow_hists[cat].fill(to_fill, weight=sample.weights[good_evts])\n\n def sign_cut(self, sample, sign, fill_value):\n q_3, q_4 = sample.events.array('q_3'), sample.events.array('q_4')\n signs = np.dot(q_3, q_4)\n if (sign == 'SS'): sample.mask[signs < 0] = False\n elif (sign == 'OS'): sample.mask[signs > 0] = False\n self.fill_cutflow(fill_value, sample)\n\n def btag_cut(self, sample, fill_value):\n nbtag = sample.events.array('nbtag')\n try: condition = (nbtag[:,0] > 0)\n except: condition = (nbtag > 0)\n sample.mask[condition] = False\n self.fill_cutflow(fill_value, sample)\n\n def lepton_cut(self, s, fill_value):\n iso_1, iso_2 = s.events.array('iso_1'), s.events.array('iso_2')\n global_1, global_2 = s.events.array('isGlobal_1'), s.events.array('isGlobal_2')\n tracker_1, tracker_2 = s.events.array('isTracker_2'), s.events.array('isTracker_2')\n disc_1 = s.events.array('Electron_mvaFall17V2noIso_WP90_1')\n disc_2 = s.events.array('Electron_mvaFall17V2noIso_WP90_2')\n\n # tight muon selections\n mm_iso = (iso_1 > 0.2) | (iso_2 > 0.2)\n if (s.name == \"W1JetsToLNu\"):\n print(\"iso_1\", iso_1)\n print(\"(iso_1 > 0.2)\", (iso_1 > 0.2))\n print(\"mm_iso=\", mm_iso)\n mm_io = ((global_1 < 1) & (tracker_1 < 1)) | ((global_2 < 1) & (tracker_2 < 1))\n mm_selections = (mm_iso | mm_io) & (s.ll == 'mm')\n\n # tight electron selections\n ee_iso = (iso_1 > 0.15) | (iso_2 > 0.15)\n ee_selections = (ee_iso | (disc_1 < 1) | (disc_2 < 1)) & (s.ll == 'ee')\n\n s.mask[(ee_selections | mm_selections)] = False\n self.fill_cutflow(fill_value, s)\n\n def get_tight_taus(self, sample):\n iso_3 = sample.events.array('iso_3')\n iso_4 = sample.events.array('iso_4')\n vsJet_3 = sample.events.array('idDeepTau2017v2p1VSjet_3') \n vsJet_4 = sample.events.array('idDeepTau2017v2p1VSjet_4')\n vsMu_3 = sample.events.array('idDeepTau2017v2p1VSmu_3')\n vsMu_4 = sample.events.array('idDeepTau2017v2p1VSmu_4')\n vsEle_3 = sample.events.array('idDeepTau2017v2p1VSe_3')\n vsEle_4 = sample.events.array('idDeepTau2017v2p1VSe_4')\n global_3 = sample.events.array('isGlobal_3')\n global_4 = sample.events.array('isGlobal_4')\n tracker_3 = sample.events.array('isTracker_3')\n tracker_4 = sample.events.array('isTracker_4')\n disc_3 = sample.events.array('Electron_mvaFall17V2noIso_WP90_3')\n\n # tight em selections\n em_tight1 = (sample.tt == 'em') & (iso_3 < 0.15) & (disc_3 > 0)\n em_tight2 = (sample.tt == 'em') & (iso_4 < 0.15) & ((global_4 > 0) | (tracker_4 > 0))\n\n # tight mt selections\n mt_tight1 = (sample.tt == 'mt') & (iso_3 < 0.15) & ((global_3 > 0) | (tracker_3 > 0))\n mt_tight2 = (sample.tt == 'mt') & (vsJet_4 >= 15) & (vsMu_4 >= 0) & (vsEle_4 >= 0)\n\n # tight et selections\n et_tight1 = (sample.tt == 'et') & (iso_3 < 0.15) & (disc_3 > 0)\n et_tight2 = (sample.tt == 'et') & (vsJet_4 >= 15) & (vsMu_4 >= 0) & (vsEle_4 >= 0)\n\n # tight tt selections\n tt_tight1 = (sample.tt == 'tt') & (vsJet_3 >= 15) & (vsMu_3 >= 0) & (vsEle_3 >= 0)\n tt_tight2 = (sample.tt == 'tt') & (vsJet_4 >= 15) & (vsMu_4 >= 0) & (vsEle_4 >= 0)\n\n tight1 = em_tight1 | mt_tight1 | et_tight1 | tt_tight1\n tight2 = em_tight2 | mt_tight2 | et_tight2 | tt_tight2\n return tight1, tight2\n\n def tau_cut(self, sample, tight1, tight2, fill_value=0):\n tight = tight1 & tight2 \n not_tight = np.array([not t for t in tight], dtype=bool)\n sample.mask[not_tight] = False\n self.fill_cutflow(fill_value, sample)\n return tight1, tight2\n\n def data_driven_cut(self, sample, fill_value):\n \n # match arrays contain <e,mu,tau>_genPartFlav variables\n match_3 = sample.events.array('gen_match_3')\n match_4 = sample.events.array('gen_match_4')\n\n # cut if electron/muon from prompt tau\n em_cut = (sample.tt == 'em') & ((match_4 == 15) | (match_3 == 15))\n \n # cut if (electron/muon from prompt tau) | (unmatched/jet-faked tau) \n et_mt_cut = ((sample.tt == 'et') | (sample.tt == 'mt')) & ((match_3 == 15) | (match_4 > 5))\n sample.mask[et_mt_cut | em_cut] = False\n\n # cut if either tau unmatched/jet-faked\n sample.mask[(sample.tt == 'tt') & ((match_3 > 5) | (match_4 > 5))] = False\n self.fill_cutflow(fill_value, sample)\n \n def add_SFs(self, sample):\n pt_3, pt_4 = sample.events.array('pt_3'), sample.events.array('pt_4')\n eta_3, eta_4 = sample.events.array('eta_3'), sample.events.array('eta_4')\n match_3 = sample.events.array('gen_match_3')\n match_4 = sample.events.array('gen_match_4')\n\n for i in np.arange(sample.n_entries)[sample.mask]:\n if (sample.tt[i] == 'et' or sample.tt[i] == 'mt'):\n\n # tau_4: prompt electron or tau decay electron\n if (match_4[i] == 1 or match_4[i] == 3):\n sample.weights[i] *= self.antiEle_SF.getSFvsEta(eta_4[i], match_4[i])\n # tau_4: prompt muon or tau decay muon\n if (match_4[i] == 2 or match_4[i] == 4):\n sample.weights[i] *= self.antiMu_SF.getSFvsEta(eta_4[i], match_4[i])\n \n elif (sample.tt[i] == 'tt'):\n sample.weights[i] *= self.antiJet_SF.getSFvsPT(pt_3[i], match_3[i]) \n sample.weights[i] *= self.antiJet_SF.getSFvsPT(pt_4[i], match_4[i])\n \n # tau_3: prompt electron or tau decay electron\n if (match_3[i] == 1 or match_3[i] == 3):\n sample.weights[i] *= self.antiEle_SF.getSFvsEta(eta_3[i], match_3[i])\n # tau_3: prompt muon or tau decay muon\n if (match_3[i] == 2 or match_3[i] == 4):\n sample.weights[i] *= self.antiMu_SF.getSFvsEta(eta_3[i], match_3[i])\n # tau_4: prompt electron or tau decay electron\n if (match_4[i] == 1 or match_4[i] == 3):\n sample.weights[i] *= self.antiEle_SF.getSFvsEta(eta_4[i], match_4[i])\n # tau_4: prompt muon or tau decay muon\n if (match_4[i] == 2 or match_4[i] == 4):\n sample.weights[i] *= self.antiMu_SF.getSFvsEta(eta_4[i], match_4[i])\n \n def H_LT_cut(self, LT_cut, sample, fill_value):\n pt_3, pt_4 = sample.events.array('pt_4'), sample.events.array('pt_3')\n to_cut = ((pt_3 + pt_4) < LT_cut) & (sample.tt == 'tt')\n sample.mask[to_cut] = False\n self.fill_cutflow(fill_value, sample)\n \n def mtt_fit_cut(self, sample, fill_value):\n mtt_low = (sample.mtt_fit < 90)\n mtt_high = (sample.mtt_fit > 180)\n out_of_range = (mtt_low) | (mtt_high)\n for i in range(100):\n print(sample.mtt_fit[i], mtt_low[i], mtt_high[i], out_of_range[i])\n \n sample.mask[out_of_range] = False\n self.fill_cutflow(fill_value, sample)\n\n def fill_hists(self, sample, blind=False):\n for cat in self.categories.values():\n good_evts = (sample.cats == cat) & sample.mask\n weights = sample.weights[good_evts]\n\n mtt_fit_old = sample.events.array('m_sv')\n if (blind): good_evts = good_evts & ((mtt_fit_old < 80.) | \n (mtt_fit_old > 140.))\n\n # fit the diTau mass spectrum\n self.mtt_fit_hists[cat].fill(sample.mtt_fit[good_evts], weight=weights)\n self.ESratio_hists[cat].fill(sample.mtt_fit[good_evts] /\n mtt_fit_old[good_evts])\n self.m4l_hists[cat].fill(sample.m4l[good_evts], weight=weights)\n self.mA_hists[cat].fill(sample.mA[good_evts], weight=weights)\n self.mA_c_hists[cat].fill(sample.mA_c[good_evts], weight=weights)\n \n LT = sample.events.array('pt_3') + sample.events.array('pt_4')\n self.LT_hists[cat].fill(LT[good_evts], weight=weights) \n \n # fill extra_hists\n for name, hist in self.hists.items():\n if (name not in self.hists_from_ntuple): continue\n try: hist[cat].fill(sample.events.array(name)[good_evts],\n weight=weights)\n except KeyError: \n print(\"Cannot access {0} in sample.events\".format(name))\n \n def process_samples(self, tight_cuts, sign, data_driven, tau_ID_SF, redo_fit, LT_cut):\n progress_bar= tqdm(self.samples.items())\n for name, sample in progress_bar:\n if (sample.n_entries < 1): continue\n progress_bar.set_description(\"{0}\".format(name.ljust(20)[:20]))\n sample.weights *= sample.sample_weight\n sample.weights *= sample.events.array('weightPUtrue')\n sample.weights *= sample.events.array('Generator_weight')\n sample.parse_categories(self.categories, sample.events.array('cat'))\n self.fill_cutflow(0.5, sample)\n\n if (tight_cuts):\n self.sign_cut(sample, sign, fill_value=1.5)\n self.btag_cut(sample, fill_value=2.5)\n self.lepton_cut(sample, fill_value=3.5)\n tight1, tight2 = self.get_tight_taus(sample)\n self.tau_cut(sample, tight1, tight2, fill_value=4.5)\n\n if (data_driven):\n self.data_driven_cut(sample, fill_value=5.5)\n if tau_ID_SF: self.add_SFs(sample)\n\n self.H_LT_cut(LT_cut, sample, fill_value=6.5)\n self.fitter.fit(sample)\n self.mtt_fit_cut(sample, fill_value=7.5)\n self.fill_hists(sample, blind=False)\n" }, { "alpha_fraction": 0.5425174236297607, "alphanum_fraction": 0.5735332369804382, "avg_line_length": 34.09090805053711, "blob_id": "1dd9fe2ca1952473b4e1a88fe3ac541f6b13837e", "content_id": "d3e0b57734221b2515cba14a3c59752e440970f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3869, "license_type": "no_license", "max_line_length": 75, "num_lines": 110, "path": "/make_plots.py", "repo_name": "GageDeZoort/plot_ZH", "src_encoding": "UTF-8", "text": "import os \nimport pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nimport boost_histogram as bh\nimport ROOT as root\nfrom ROOT import gROOT\nimport mplhep as hep\nimport aghast\n\n# plot styling \nplt.style.use(hep.style.CMS) \nplt.rcParams.update({\n 'font.size': 14,\n 'mathtext.default' : 'regular',\n 'axes.titlesize': 18,\n 'axes.labelsize': 18,\n 'xtick.labelsize': 12,\n 'ytick.labelsize': 12\n})\n\ndef combine_cats(hists):\n all_cats_hist = hists['eemt']\n for cat, cat_hist in hists.items():\n if (cat=='eemt'): continue\n all_cats_hist += cat_hist\n return all_cats_hist\n\ndef get_hists(year, mass, group):\n path = \"/eos/uscms/store/user/jdezoort/AZH_hists\"\n hists_path = path + \"/AZH_{0}_M{1}_{2}.pkl\".format(year, mass, group)\n hists_file = open(hists_path, 'rb')\n try: hists = pickle.load(hists_file)\n except EOFError: print(\"Error: {0} not found\".format(hists_path))\n else: print(\"READING {0}\".format(hists_path))\n return hists\n\ndef make_plot(hist, cat, var, xlabel, ylabel=\"Events\", tag=\"\"):\n #plt.style.use([hep.style.ROOT, hep.style.firamath])\n f, ax = plt.subplots()\n ax.bar(hist.axes[0].centers, hist.view(), width=hist.axes[0].widths,\n color=\"mediumseagreen\", edgecolor=\"black\", linewidth=5)\n hep.cms.label(loc=0, year='2018')\n print(xlabel.encode('unicode_escape').decode())\n plt.xlabel(xlabel.encode('unicode_escape').decode())\n plt.ylabel(ylabel)\n plt.ylim(bottom=0)\n plt.savefig(\"plots/{0}_{1}_{2}.png\".format(tag, cat, var), dpi=1200)\n plt.show()\n plt.clf()\n\ndef make_mass_plots(m4l, mA, mA_c, cat, mass=300, year=2018, show=False):\n f, ax = plt.subplots()\n plt.step(m4l.axes[0].edges[:-1], m4l, where='mid',\n color='orange', lw=3, label='$M_{lltt}$')\n plt.step(mA.axes[0].edges[:-1], mA, where='mid',\n color='mediumseagreen', lw=3, label='$M_{lltt}^{fit}$')\n plt.step(mA_c.axes[0].edges[:-1], mA_c, where='mid',\n color='slateblue', lw=3, label='$M_{lltt}^{constrained}$')\n hep.cms.label(loc=0, year='2018')\n plt.xlabel(\"Mass [GeV]\", ha='right', x=1.0)\n plt.ylabel(\"Events\") #, va='top', ha='left', y=0.8)\n plt.title(\"{0}, {1} GeV\".format(cat, mass))\n ax.legend(loc='upper left', prop={'size' : 20})\n plt.savefig(\"plots/AZH_{0}_{1}_{2}_masses.png\".format(year, mass, cat))\n if (show): plt.show()\n plt.clf()\n\ndef make_pyROOT_plot(hist, cat, var, xlabel, ylabel=\"Events\", tag=\"\"):\n canvas = TCanvas(\"canvas\", \"canvas\")\n \n\ngroups = ['signal']\n#masses = [220, 240, 260, 280, 300, 320, 340, 350, 400]\nmasses = [240, 300]\nyears = [2018]\ncategories = {1:'eeet', 2:'eemt', 3:'eett', 4:'eeem',\n 5:'mmet', 6:'mmmt', 7:'mmtt', 8:'mmem'}\n\n\"\"\"for group in groups:\n for year in years:\n for mass in masses:\n hists = get_hists(year, mass, group)\n for cat in categories.values():\n make_mass_plots(hists['m4l'][cat], hists['mA'][cat], \n hists['mA_c'][cat], cat, \n mass=str(mass), year=str(year))\n\"\"\"\n\nfor group in groups:\n for year in years:\n for mass in masses:\n hists = get_hists(year, mass, group)\n m4l = combine_cats(hists['m4l'])\n mA = combine_cats(hists['mA'])\n mA_c = combine_cats(hists['mA_c'])\n make_mass_plots(m4l, mA, mA_c, 'all', \n mass=str(mass), year=str(year))\n\n\"\"\"for group in groups:\n hists = get_hists(group)\n var_list = hists.keys()\n for var in var_list:\n var_hists = hists[var]\n print(\"...plotting {0}\".format(var))\n for cat in categories.values():\n hist = var_hists[cat]\n make_plot(hist, cat, var, labels[var], tag=\"AZH_2018\")\n \"\"\" \n" }, { "alpha_fraction": 0.7274119257926941, "alphanum_fraction": 0.7825421094894409, "avg_line_length": 35.27777862548828, "blob_id": "77794b06f0959b95659a819ee211558609c67f3b", "content_id": "7978bbbe3082bbaab16d2df819271c2690fd2ee9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 653, "license_type": "no_license", "max_line_length": 93, "num_lines": 18, "path": "/README.md", "repo_name": "GageDeZoort/plot_ZH", "src_encoding": "UTF-8", "text": "# plot_ZH\nA set of classes and scripts to perform the ZHtoTauTau and AtoZHtoTauTau analyses. \n\n## Quickstart\n``` \nexport SCRAM_ARCH=sl6_amd64_gcc700\ncmsrel CMSSW_10_2_14\ncd CMSSSW_10_2_14/src\ngit clone https://github.com/princeton-cms-run2/ZH_Run2.git -b devel\ngit clone https://github.com/cms-tau-pog/TauIDSFs TauPOG/TauIDSFs\ngit clone https://github.com/SVfit/ClassicSVfit TauAnalysis/ClassicSVfit -b release_2018Mar20\ngit clone https://github.com/SVfit/SVfitTF TauAnalysis/SVfitTF\ncmsenv\nscram b -j 8\ncd ZH_Run2\ngit clone https://github.com/GageDeZoort/plot_ZH.git\nsource /cvmfs/sft.cern.ch/lcg/views/LCG_92python3/x86_64-slc6-gcc62-opt/setup.sh\n```\n" } ]
8
meitalhoffman/AsylumViz
https://github.com/meitalhoffman/AsylumViz
4e438efe2b0844e5da6a64eea6ff5546c383fefc
01e9857388fb5b12dff7b280b280b74dd177eb92
40170c0c55eb0a21babcc4f50a3d265ff7097d8c
refs/heads/master
2021-12-28T19:37:28.345944
2020-05-11T04:46:31
2020-05-11T04:46:31
180,399,065
1
0
MIT
2019-04-09T15:38:38
2020-05-11T04:46:35
2022-01-13T12:51:48
JavaScript
[ { "alpha_fraction": 0.4761216640472412, "alphanum_fraction": 0.5104596614837646, "avg_line_length": 32.79534912109375, "blob_id": "7232b8a9f093baf9f331d3b1a571254a1f820ad5", "content_id": "135d25188043be181247e3d0d7372ae72de11fa9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 14532, "license_type": "permissive", "max_line_length": 201, "num_lines": 430, "path": "/js/vis3.js", "repo_name": "meitalhoffman/AsylumViz", "src_encoding": "UTF-8", "text": "\n//visualization 3 - animated legal process\nvar caseInfo;\nvar cases;\n\nvar buckets;\nvar levels;\n\nvar marginX;\nvar marginY;\n\nvar width;\nvar height;\n\nvar velocity = 5;\n\n//colors: declare all color variables\nvar start = \"#F8F4F3\"\nvar A0 = \"#F9BCA0\"\nvar A1 = \"#F3A57F\"\nvar A2 = \"#DB6E5A\"\nvar A3 = \"#CE5246\"\nvar A4 = \"#C13738\"\nvar D0 = \"#C7DEEC\"\nvar D1 = \"#92C9DE\"\nvar D2 = \"#76B3D0\"\nvar D3 = \"#3F8FBE\"\nvar D4 = \"#3C8FC3\"\n\n\nfunction preload(){\n caseInfo = loadTable(\"https://gist.githubusercontent.com/meitalhoffman/6553d3b820e7c652f0a23f4f666f1058/raw/8ee2508602de97381e69b199b11971fb5201486d/legalProcessAnimationInfo.csv\", \"csv\", \"header\")\n}\n\nfunction setup(){\n let myCanvas = createCanvas(600, 700)\n myCanvas.parent(\"#animation\")\n width = 600\n height = 700\n marginX = 30;\n marginY = 30;\n cases = []\n buckets = {}\n levels = []\n initializeBuckets()\n initializeLevels()\n loadData()\n\n}\n\nfunction draw() {\n background(55)\n buckets[\"Referred\"].draw()\n buckets[\"Approved\"].draw()\n buckets[\"Denied\"].draw()\n for(let c in cases){\n cases[c].draw()\n cases[c].update()\n }\n for(let l in levels){\n levels[l].updateHover()\n levels[l].draw()\n }\n}\n\nfunction mouseClicked(){\n for(let l in levels){\n if(levels[l].over){\n levels[l].restartCases()\n }\n }\n}\n\nfunction loadData(){\n let rowCount = caseInfo.getRowCount()\n for(let i = 0; i < rowCount; i++){\n var row = caseInfo.rows[i]\n let rowVal = round(row.get(0)/100)\n let stops = []\n stops.push(row.get(1))\n stops.push(row.get(2))\n stops.push(row.get(3))\n stops.push(row.get(4))\n stops.push(row.get(5));\n for(let c = 0; c < rowVal; c++){\n cases.push(new applicant(stops, 5))\n }\n\n }\n}\n\nfunction initializeBuckets(){\n var referral = new bucket((width/2-120), (height-marginY-80), 240, 80, -1, \"Referred to Immigration Court\")\n var approved = new bucket(marginX, (height-marginY-80), 120, 80, -1, \"Asylum Approved\")\n var denied = new bucket((width-marginX-120), (height-marginY-80), 120, 80, -1, \"Asylum Denied\")\n buckets[\"Referred\"] = referral\n buckets[\"Approved\"] = approved\n buckets[\"Denied\"] = denied\n}\n\nfunction initializeLevels(){\n // levels = [[\"New Application\", \"Pending Application\"],\n // [\"Affirmative\", \"Defensive\"],\n // [\"Interview Scheduled\", \"Uninterviewed Referral\", \"Filing Deadline Referral\", \"Interviewed\"],\n // [\"Interview Conducted\", \"Interview Cancelled\", \"No Show\", \"Credible Fear\", \"No Credible Fear\"],\n // [\"USCIS\", \"Applicant\"]]\n var pendingApps = new bucket(marginX, marginY, 120, 50, 0, \"Pending Application\", \"#f8f4f1\")\n var newApps = new bucket(width/2, marginY, 120, 50, 0, \"New Applications\", \"#f8f4f1\")\n var affirmative = new bucket(width/2 - 100, 100+marginY, 120, 40, 1, \"Affirmative\", \"#c5dfec\")\n var defensive = new bucket(width/2 + 90, 100+marginY, 120, 40, 1, \"Defensive\", \"#f6c0a6\")\n var dInterviews = new bucket(width/2 + 110, 190+marginY, 120, 40, 2, \"Interviews Conducted\", \"#dc6e57\")\n var aInterviews = new bucket(width/2 - 150, 190+marginY, 120, 40, 2, \"Interviews Scheduled\", \"#97c7de\")\n var aNoShow = new bucket(width/2 - 50, 280+marginY, 80, 40, 3, \"No Show\", \"#3d89bb\")\n var aCancelled = new bucket(width/2 - 150, 280+marginY, 80, 40, 3, \"Cancelled\", \"#1b5a9d\")\n var aConducted = new bucket(width/2 - 250, 280+marginY, 80, 40, 3, \"Conducted\", \"#0a396d\")\n var dNoFear = new bucket(width/2 + 150, 370+marginY, 120, 40, 3, \"Fear Not Established\", \"#ce5246\")\n var dFear = new bucket(width/2, 370+marginY, 120, 40, 3, \"Fear Established\", \"#720421\")\n\n levels.push(pendingApps)\n levels.push(newApps)\n levels.push(affirmative)\n levels.push(defensive)\n levels.push(aInterviews)\n levels.push(dInterviews)\n levels.push(aConducted)\n levels.push(aCancelled)\n levels.push(aNoShow)\n levels.push(dFear)\n levels.push(dNoFear)\n}\n\nclass bucket{\n constructor(_x, _y, _width, _height, _l, _text, _c){\n this.x = _x\n this.y = _y\n this.w = _width\n this.h = _height\n this.l = _l\n this.text = _text\n this.color = _c\n this.cases = []\n this.over = false\n }\n\n draw(){\n fill(0)\n stroke(0)\n if(this.l == -1) fill(0)\n else fill(this.color)\n rect(this.x, this.y, this.w, this.h)\n if(this.l == -1) fill(255)\n else if(this.l == 0) fill(0)\n else if(this.l == 1) fill(0)\n else if(this.l == 2) fill(0)\n else if(this.l == 3) fill(255)\n // fill(255)\n if(this.text == \"Pending Application\" | this.text == \"Interviews Scheduled\" | this.text == \"Interviews Conducted\"){\n let splitStrings = split(this.text, ' ')\n let textW0 = textWidth(splitStrings[0])\n text(splitStrings[0], this.x+(this.w/2 - textW0/2), this.y+15)\n let textW1 = textWidth(splitStrings[1])\n text(splitStrings[1], this.x+(this.w/2 - textW1/2), this.y+30)\n } else if (this.text == \"Fear Not Established\"){\n let splitStrings = split(this.text, ' ')\n let textW0 = textWidth(splitStrings[0] + ' ' + splitStrings[1])\n text(splitStrings[0] + ' ' + splitStrings[1], this.x+(this.w/2 - textW0/2), this.y+15)\n let textW1 = textWidth(splitStrings[2])\n text(splitStrings[2], this.x+(this.w/2 - textW1/2), this.y+30)\n }else {\n let textW = textWidth(this.text)\n text(this.text, this.x+(this.w/2 - textW/2), this.y+15)\n }\n }\n\n isOver(){\n if(mouseX >= this.x && mouseX <= this.x+this.w && mouseY >= this.y && mouseY <= this.y+this.h){\n return true\n } else {\n return false\n }\n }\n\n updateHover(){\n this.over = this.isOver()\n }\n\n restartCases(){\n for(let c in this.cases){\n if(this.l == 0){\n this.cases[c].currentLevel = this.l\n this.cases[c].getFirstStop()\n this.cases[c].done = false\n } else {\n this.cases[c].currentLevel = this.l - 1\n this.cases[c].x = this.getRandomX()\n this.cases[c].y = this.getRandomY()\n this.cases[c].done = false\n this.cases[c].nextColor = null\n this.cases[c].newTarget()\n // this.cases[c] = this.color\n }\n }\n }\n\n getRandomX(){\n return this.x + random(this.w -10)\n }\n\n getRandomY(){\n return this.y + random(this.h)\n }\n\n getFinalY(){\n return this.y + 30 + random(this.h-30)\n }\n}\n\n//class holding 10 applicants\nclass applicant{\n constructor(_path, _radius){\n this.path = _path\n this.radius = _radius\n this.x = 0\n this.y = 0\n this.targetX = 0\n this.targetY = 0\n this.dirX = 0\n this.dirY = 0\n this.currentLevel = 0\n this.color = start\n this.nextColor = start\n this.done = false\n this.getBuckets()\n this.getFirstStop()\n }\n\n getBuckets(){\n if(this.path[0] == \"New Application\"){\n levels[1].cases.push(this)\n } else {\n levels[0].cases.push(this)\n }\n if(this.path[1] == \"Affirmative\"){\n levels[2].cases.push(this)\n } else {\n levels[3].cases.push(this)\n }\n if(this.path[2] == \"Interview Scheduled\"){\n levels[4].cases.push(this)\n } else if(this.path[2] == \"Interviewed\"){\n levels[5].cases.push(this)\n } if(this.path[3] == \"Interview Conducted\"){\n levels[6].cases.push(this)\n } else if(this.path[3] == \"Interview Cancelled\"){\n levels[7].cases.push(this)\n } else if(this.path[3] == \"No Show\"){\n levels[8].cases.push(this)\n } else if(this.path[3] == \"Credible Fear\"){\n levels[9].cases.push(this)\n } else if(this.path[3] == \"No Credible Fear\"){\n levels[10].cases.push(this)\n }\n\n }\n\n getFirstStop(){\n if(this.path[0] == \"New Application\"){\n this.x = levels[1].getRandomX()\n this.y = levels[1].getRandomY()\n this.color = levels[1].color\n }\n else {\n this.x = levels[0].getRandomX()\n this.y = levels[0].getRandomY()\n this.color = levels[0].color\n }\n if(this.path[1] == \"Affirmative\"){\n this.targetX = levels[2].getRandomX()\n this.targetY = levels[2].getRandomY()\n this.nextColor = levels[2].color\n } else{\n this.targetX = levels[3].getRandomX()\n this.targetY = levels[3].getRandomY()\n this.nextColor = levels[3].color\n }\n this.getNewDir()\n }\n\n draw(){\n fill(this.color)\n ellipse(this.x, this.y, this.radius, this.radius)\n }\n\n update(){\n if(abs(this.x - this.targetX) < 5 && abs(this.y - this.targetY) < 5){\n // console.log(\"made it to the target!\")\n if(this.done){\n // console.log(\"done\")\n this.dirX = 0\n this.dirY = 0\n }\n else {\n // console.log(\"getting new target\")\n this.newTarget()\n }\n }\n this.x = this.x - this.dirX\n this.y = this.y - this.dirY\n }\n\n newTarget(){\n this.currentLevel = this.currentLevel + 1\n // console.log(\"new level is: \"+str(this.currentLevel))(\n if(this.nextColor != null) this.color = this.nextColor\n\n switch(this.currentLevel){\n case 1:\n if(this.path[2] == \"Interview Scheduled\"){\n // console.log(\"interview scheduled\")\n this.targetX = levels[4].getRandomX()\n this.targetY = levels[4].getRandomY()\n this.nextColor = levels[4].color\n this.getNewDir()\n\n } else if(this.path[2].includes(\"Referral\" )){\n // console.log(\"referred\")\n this.targetX = buckets[\"Referred\"].getRandomX()\n this.targetY = buckets[\"Referred\"].getFinalY()\n // this.nextColor = levels[4].color\n this.getNewDir()\n this.currentLevel = -1\n\n } else if(this.path[2] == \"Interviewed\"){\n // console.log(\"interviewed\")\n this.targetX = levels[5].getRandomX()\n this.targetY = levels[5].getRandomY()\n this.nextColor = levels[5].color\n this.getNewDir()\n\n } else if(this.path[2] == \"no data\"){\n this.targetX = width - marginX - random(3)\n this.targetY = this.y + random(50)\n // this.nextColor = D3\n this.getNewDir()\n this.currentLevel = -1\n }\n break;\n case 2:\n if(this.path[3] == \"Interview Conducted\"){\n this.targetX = levels[6].getRandomX()\n this.targetY = levels[6].getRandomY()\n this.nextColor = levels[6].color\n this.getNewDir()\n } else if(this.path[3] == \"Interview Cancelled\"){\n this.targetX = levels[7].getRandomX()\n this.targetY= levels[7].getRandomY()\n this.nextColor = levels[7].color\n this.getNewDir()\n } else if(this.path[3] == \"No Show\"){\n this.targetX = levels[8].getRandomX()\n this.targetY = levels[8].getRandomY()\n this.nextColor = levels[8].color\n this.getNewDir()\n } else if(this.path[3] == \"no data\"){\n if(this.x < width/2){\n this.targetX = marginX + random(3)\n } else {\n this.targetX = width -marginX - random(3)\n }\n this.targetY = this.y + random(50)\n this.getNewDir()\n } else if(this.path[3] == \"Credible Fear\"){\n this.targetX = levels[9].getRandomX()\n this.targetX = levels[9].getRandomY()\n this.nextColor = levels[9].color\n this.getNewDir()\n }\n else if(this.path[3] == \"No Credible Fear\"){\n this.targetX = levels[10].getRandomX()\n this.targetY = levels[10].getRandomY()\n this.nextColor = levels[10].color\n this.getNewDir()\n }\n break;\n case 3:\n this.currentLevel = -1\n if(this.path[4] == \"Approved\"){\n this.targetX = buckets[\"Approved\"].getRandomX()\n this.targetY = buckets[\"Approved\"].getFinalY()\n } else if(this.path[4] == \"Denied\" | this.path[4] == \"No Show Denial\"){\n this.targetX = buckets[\"Denied\"].getRandomX()\n this.targetY = buckets[\"Denied\"].getFinalY()\n } else if(this.path[4] == \"Referred\"){\n this.targetX = buckets[\"Referred\"].getRandomX()\n this.targetY = buckets[\"Referred\"].getFinalY()\n } else if(this.path[4] == \"USCIS\" | this.path[4] == \"Applicant\" | this.path[4] == \"no data\"){\n if(this.x < width/2){\n this.targetX = marginX + random(3)\n } else {\n this.targetX = width - marginX - random(3)\n }\n this.targetY = this.y + random(100)\n }\n this.getNewDir()\n break;\n case 0:\n //they have found their target! just jitter\n this.done = true\n this.jitter()\n break;\n }\n \n\n }\n\n jitter(){\n this.targetX = this.x + random(2)\n this.targetY = this.y + random(2)\n this.getNewDir()\n }\n\n getNewDir(){\n let xdist = this.x - this.targetX;\n let ydist = this.y - this.targetY;\n let angle = atan2(ydist, xdist);\n this.dirX = cos(angle)*(velocity);\n this.dirY = sin(angle)*(velocity);\n }\n\n\n}" }, { "alpha_fraction": 0.6078431606292725, "alphanum_fraction": 0.6143791079521179, "avg_line_length": 29.799999237060547, "blob_id": "065815ad17c312f659db5ef12f9f4017c9673468", "content_id": "08da07f46787b88f41cfab4424643140cac58a76", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 153, "license_type": "permissive", "max_line_length": 87, "num_lines": 5, "path": "/config.py", "repo_name": "meitalhoffman/AsylumViz", "src_encoding": "UTF-8", "text": "'''\nfile to hold the secret API info to use to grab NYTimes information for visualization 1\n'''\nNYTInfo = {\"Key\": \"rwx4VNrcEGeezchjkplNhGqOUvjJAMai\",\n \"Secret\": \"1ObsvicrqgGWPVdQ\"}" }, { "alpha_fraction": 0.5486168265342712, "alphanum_fraction": 0.5663191676139832, "avg_line_length": 45.354068756103516, "blob_id": "be8385d6bf873fcf923c0b01c4636fa0f5062f09", "content_id": "8ca871c2355db580fe3883bacdc592015f602586", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 19398, "license_type": "permissive", "max_line_length": 361, "num_lines": 418, "path": "/index.html", "repo_name": "meitalhoffman/AsylumViz", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n <meta name=\"description\" content=\"Exploring the Inequities in the United States Asylum System. A final project for Big Data, Visualization, and Society Sping 2019.\">\n <meta name=\"author\" content=\"Meital Hoffman\">\n\n <title>Unequal Justice: Exploring the Inequities in the United States </title>\n\n <!-- Bootstrap core CSS -->\n <link href=\"vendor/bootstrap/css/bootstrap.min.css\" rel=\"stylesheet\">\n\n <!-- Custom fonts for this template -->\n <link href=\"vendor/fontawesome-free/css/all.min.css\" rel=\"stylesheet\">\n <link href=\"https://fonts.googleapis.com/css?family=Varela+Round\" rel=\"stylesheet\">\n <link href=\"https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i\" rel=\"stylesheet\">\n\n <!-- Custom styles for this template -->\n <link href=\"css/grayscale.css\" rel=\"stylesheet\">\n <link href=\"css/custom.css\" rel=\"stylesheet\">\n\n <script src=\"https://d3js.org/d3.v5.min.js\" charset=\"utf-8\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.1/p5.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.1/addons/p5.dom.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.1/addons/p5.sound.min.js\"></script>\n <script src=\"js/headlinesToView.js\"> </script>\n\n</head>\n\n<body id=\"page-top\">\n\n <!-- Navigation -->\n <nav class=\"navbar navbar-expand-lg navbar-light fixed-top\" id=\"mainNav\">\n <div class=\"container\">\n <a class=\"navbar-brand js-scroll-trigger\" href=\"#page-top\">Unequal Justice</a>\n <button class=\"navbar-toggler navbar-toggler-right\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarResponsive\" aria-controls=\"navbarResponsive\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n Menu\n <i class=\"fas fa-bars\"></i>\n </button>\n <div class=\"collapse navbar-collapse\" id=\"navbarResponsive\">\n <ul class=\"navbar-nav ml-auto\">\n <li class=\"nav-item\">\n <a class=\"nav-link js-scroll-trigger\" href=\"#story\">Story</a>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link js-scroll-trigger\" href=\"#def\">Definitions</a>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link js-scroll-trigger\" href=\"#signup\">Sources</a>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link js-scroll-trigger\" href=\"#about\">About the Project</a>\n </li>\n </ul>\n </div>\n </div>\n </nav>\n\n <!-- Header -->\n <header class=\"masthead\">\n <div class=\"container d-flex h-100 align-items-center\">\n <div class=\"mx-auto text-center\">\n <h1 class=\"mx-auto my-0 text-uppercase\">Unequal Justice</h1>\n <h2 class=\"text-white-50 mx-auto mt-2 mb-5\">Exploring the Inequities in the United States Asylum System</h2>\n <!-- <a href=\"#about\" class=\"btn btn-primary js-scroll-trigger\">Get Started</a> -->\n </div>\n </div>\n </header>\n\n <!--Starting with a Quote-->\n <section id=\"quote\" class=\"about-section text-center\">\n <div class=\"container\">\n <div class=\"row\">\n <div class=\"col-lg-8 mx-auto\">\n <h2 class=\"text-white mb-4\">They told me, ‘you don’t have any rights here, and you don’t have any rights to stay with your son.’ …For me I died at that moment. They ripped my heart out of me. …For me, it would have been better if I had dropped dead. For me, the world ended at that point. …How can a mother not have the right to be with her son?”</h2>\n <p class=\"text-white-50\"> Valquiria, a 39-year-old Brazilian asylum-seeker, detained since March 2018, when US authorities forcibly separated her from her 6-year-old son, after they requested asylum at a port-of-entry in El Paso, Texas.</p>\n </div>\n </div>\n <img src=\"img1/child2.jpg\" class=\"img-fluid\" alt=\"\">\n </div>\n </section>\n\n <!-- About Section -->\n <section id=\"story\" class=\"about-section text-center\">\n <div class=\"container\">\n <div class=\"row\">\n <div class=\"col-lg-8 mx-auto\">\n <h2 class=\"text-white mb-4\">Asylum Seekers in the United States</h2>\n <p class=\"text-white\"> Asylum laws are an increasingly relevant political topic: globally and nationally. \n With recent violence and political turmoil in places like Syria and Venezuela, global asylum seekers, those fleeing persecution in their home countries,\n have been steadily increasing. The UN estimates that today there are 3.1 million asylum seekers worldwide. In the United States, asylum applications have fluctuated in the past 4 years.\n </p>\n <div id=\"overtime\"></div>\n <script src=\"js/vis0.js\"></script>\n </div>\n <div class=\"col-lg-8 mx-auto\">\n <p class=\"text-white\">\n Most notably, there was a sharp decline in total and defensive asylum applications from January 2017 to April 2017. \n This is the same time of Trump's controversial 'Muslim Ban' and Executive Order 13767, which made it more difficult\n to claim asylum at the border.\n </p> \n </div>\n <img src=\"img1/tweet.jpg\" class=\"rounded mx-auto d-block\">\n </div>\n <div class=\"row\">\n <div class=\"col-lg-8 mx-auto\">\n <p class = \"text-white\">\n <br/>\n <br/>\n During his campaign and tenure in office, Trump has repeatedly called out asylum seekers for 'scamming' the system.\n This highlights one of the injustices that asylum seekers face when seeking refuge in the United States.\n </p>\n <h2 class=\"text-white mb-4\">Vulnerability to Political Climate</h2>\n <p class=\"text-white\">\n The Executive Branch's rhetoric around asylum seekers can influence policy and popular discourse.\n For people seeking asylum, their legal process\n and outcomes may change drastically under different presidents.\n </p>\n <div id=\"defensive\"></div>\n <script src=\"js/vis1aa.js\"></script>\n <div id=\"affirmative\"></div>\n <script src=\"js/visualization1.js\"></script>\n <div class=\"row\">\n <p class = 'text-white'>\n For affirmative asylum seekers, it may be getting more difficult to navigate \n the complex legal system. This is shown through the increased number of applicants\n who are referred to immigration court because they filed too late and those who are being\n denied asylum because they were not present at their interview. <br> <br>\n Interestingly, while ~12% more applicants are classified as \"No Show Denial\" from 2015 to 2019,\n there is only a ~3% increase in affirmative applicants who did not\n show to their interview for the same time period, as seen in the graph below.\n </p>\n <div id=\"ainterview\"> </div>\n <script src = \"js/vis1bb.js\" ></script>\n <p class=\"text-white\">\n The media may respond to the agenda of the Executive Branch, or may highlight topics which allows them\n to become agenda-setters for political figures. Click on a bar (above) to see an article (below) from the New York\n Times from the same month about asylum.\n </p>\n <div id=\"apic\"></div>\n </div>\n <div class=\"row\">\n <p class = 'text-white'>\n <br>\n Besides the vulnerability to popular discourse as established by the media and key\n political figures, asylum seekers are often left on their own to navigate\n the complicated immigration bureaucracy. This is the root to another injustice faced by\n those seeking asylum in the US.\n </p>\n </div>\n <img src=\"img1/courtroom.jpg\" class=\"img-fluid\" alt=\"\">\n </div>\n <div class=\"row\">\n <div class=\"col-lg-8 mx-auto\">\n\n <h2 class=\"text-white mb-4\">Bureaucratic Inefficiencies</h2>\n <p class=\"text-white\">\n Even for well versed legal experts, the asylum system is complicated. For those\n entering the country without any information and potentially\n no grasp on the language, it is no doubt extremely confusing. \n <br> <br>\n Use the animation below to explore the known and unknown legal paths of asylum seekers in 2018.\n Each dot represents 100 cases. Click on the stops to see where asylum seekers go from there.\n </p>\n <div id=\"animation\"></div>\n <script src=\"js/vis3.js\"></script>\n <p class=\"text-white\">\n The cases stuck on the edge represent asylum seekers for whom the outcome of their case is unknown.\n <br>The data available on asylum seekers leaves many gaps where numbers do not quite add up.\n It is impossible to know how many of the unaccounted for cases are in detention.\n <br>\n <br>\n As shown above, most asylum cases are referred to an immigration judge who will make a final ruling on their case.\n This can often take years, as there are hundreds and thousands of backlogged cases.\n <br>\n <br>\n Additionally, different immigration courts and officials across the country\n often have very distinct outcomes. This is another way in which asylum seekers\n are not afforded the American ideal of due process.\n <br>\n <br>\n <br>\n The most vulnerable populations are subject to an unjust and voltile system, both depriving\n them of their rights to a fair trial and due process of the law as is stated in the \n United States Constitution.\n <br>\n \n </p>\n </div>\n </div>\n </section>\n\n <!-- Projects Section -->\n <section id=\"def\" class=\"projects-section bg-light\">\n <div class=\"container\">\n\n <!-- Featured Project Row -->\n <div class=\"row align-items-center no-gutters mb-4 mb-lg-5\">\n <div class=\"col-xl-8 col-lg-7\">\n <img class=\"img-fluid mb-3 mb-lg-0\" src=\"img1/migrant.jpg\" alt=\"\">\n </div>\n <div class=\"col-xl-4 col-lg-5\">\n <div class=\"featured-text text-center text-lg-left\">\n <h4>Asylum Seeker</h4>\n <p class=\"text-black-50 mb-0\">According to the Refugee Act of 1980: anyone who “is unable or unwilling to return to… that country because of persecution or a well-founded fear of persecution on account of race, religion, nationality, membership in a particular social group, or political opinion”\n </p>\n </div>\n </div>\n </div>\n\n <!-- Project One Row -->\n <div class=\"row justify-content-center no-gutters mb-5 mb-lg-0\">\n <div class=\"col-lg-6\">\n <img class=\"img-fluid\" src=\"img1/border2.jpg\" alt=\"\">\n </div>\n <div class=\"col-lg-6\">\n <div class=\"bg-black text-center h-100 project\">\n <div class=\"d-flex h-100\">\n <div class=\"project-text w-100 my-auto text-center text-lg-left\">\n <h4 class=\"text-white\">Defensive Asylum</h4>\n <p class=\"mb-0 text-white-50\">Someone who is undocumented in the country, apprehended by immigration officials (ICE), and at risk of deportation or \n someone who is apprehended at the border and asks to be granted asylum.\n </p>\n <hr class=\"d-none d-lg-block mb-0 ml-0\">\n </div>\n </div>\n </div>\n </div>\n </div>\n\n <!-- Project Two Row -->\n <div class=\"row justify-content-center no-gutters\">\n <div class=\"col-lg-6\">\n <img class=\"img-fluid\" src=\"img1/uscis.jpg\" alt=\"\">\n </div>\n <div class=\"col-lg-6 order-lg-first\">\n <div class=\"bg-black text-center h-100 project\">\n <div class=\"d-flex h-100\">\n <div class=\"project-text w-100 my-auto text-center text-lg-right\">\n <h4 class=\"text-white\">Credible Fear Review</h4>\n <p class=\"mb-0 text-white-50\">Defensive asylum seekers must prove that they have a credible fear of\n persecution were they to return home. This is an intital screening interview done with an immigration officer\n in the event that the applicant is in the 'Expedited Removals' process.\n If they are found to have a credible fear, then they are referred to an immigration judge who will make the final\n decision on their case.\n </p>\n <hr class=\"d-none d-lg-block mb-0 mr-0\">\n </div>\n </div>\n </div>\n </div>\n </div>\n <!-- Project One Row -->\n <div class=\"row justify-content-center no-gutters mb-5 mb-lg-0\">\n <div class=\"col-lg-6\">\n <img class=\"img-fluid\" src=\"img1/visa.jpg\" alt=\"\">\n </div>\n <div class=\"col-lg-6\">\n <div class=\"bg-black text-center h-100 project\">\n <div class=\"d-flex h-100\">\n <div class=\"project-text w-100 my-auto text-center text-lg-left\">\n <h4 class=\"text-white\">Affirmative Asylum</h4>\n <p class=\"mb-0 text-white-50\">Someone who is in the US on another visa and wants to change their status\n to be an asylee. They must file an application within one year of their other visa expiring. \n </p>\n <hr class=\"d-none d-lg-block mb-0 ml-0\">\n </div>\n </div>\n </div>\n </div>\n </div>\n \n <!-- Project Two Row -->\n <div class=\"row justify-content-center no-gutters\">\n <div class=\"col-lg-6\">\n <img class=\"img-fluid\" src=\"img1/court.jpg\" alt=\"\">\n </div>\n <div class=\"col-lg-6 order-lg-first\">\n <div class=\"bg-black text-center h-100 project\">\n <div class=\"d-flex h-100\">\n <div class=\"project-text w-100 my-auto text-center text-lg-right\">\n <h4 class=\"text-white\">Affirmative Asylum Interview</h4>\n <p class=\"mb-0 text-white-50\">\n Affirmative asylum applicants are interviewed by immigration officers to determine if they\n eligible for asylum status. If the immigration officer does not think they are eligible,\n they will be referred to an immigration judge who will make the final decision on their case.\n </p>\n <hr class=\"d-none d-lg-block mb-0 mr-0\">\n </div>\n </div>\n </div>\n </div>\n </div>\n\n </div>\n </section>\n\n <section id=\"signup\" class=\"projects-section bg-light\">\n <div class=\"container\">\n \n <!-- Featured Project Row -->\n <div class=\"row align-items-center no-gutters mb-4 mb-lg-5\">\n <div class=\"col-xl-8 col-lg-7\">\n <img class=\"img-fluid mb-3 mb-lg-0\" src=\"img1/data.jpg\" alt=\"\">\n </div>\n <div class=\"col-xl-4 col-lg-5\">\n <div class=\"featured-text text-center text-lg-left\">\n <h4>Data Sources</h4>\n <p class=\"text-black-50 mb-0\">\n Data came from USCIS and DHS.\n Special thanks to Shaw Drake from Border Rights Center of the ACLU of Texas for helping us understand what was going on.\n </p>\n </div>\n </div>\n </div>\n\n </div>\n </section>\n\n <!-- Signup Section -->\n <section id=\"about\" class=\"signup-section\">\n <div class=\"container\">\n <div class=\"row\">\n <div class=\"col-md-10 col-lg-8 mx-auto text-center\">\n\n <!-- <i class=\"far fa-paper-plane fa-2x mb-2 text-white\"></i> -->\n <h2 class=\"text-white mb-5\">Final Project for Big Data, Visualization, and Society Spring 2019</h2>\n<!-- \n <form class=\"form-inline d-flex\">\n <input type=\"email\" class=\"form-control flex-fill mr-0 mr-sm-2 mb-3 mb-sm-0\" id=\"inputEmail\" placeholder=\"Enter email address...\">\n <button type=\"submit\" class=\"btn btn-primary mx-auto\">Subscribe</button>\n </form> -->\n\n </div>\n </div>\n </div>\n </section>\n\n <!-- Contact Section -->\n <section class=\"contact-section bg-black\">\n <div class=\"container\">\n\n <div class=\"row\">\n\n <!-- <div class=\"col-md-4 mb-3 mb-md-0\">\n <div class=\"card py-4 h-100\">\n <div class=\"card-body text-center\">\n <i class=\"fas fa-map-marked-alt text-primary mb-2\"></i>\n <h4 class=\"text-uppercase m-0\">Address</h4>\n <hr class=\"my-4\">\n <div class=\"small text-black-50\">4923 Market Street, Orlando FL</div>\n </div>\n </div>\n </div> -->\n\n <div class=\"col-md-4 mb-1 mb-md-0\">\n <div class=\"card py-4 h-100\">\n <div class=\"card-body text-center\">\n <i class=\"fas fa-envelope text-primary mb-2\"></i>\n <h4 class=\"text-uppercase m-0\">Email</h4>\n <hr class=\"my-4\">\n <div class=\"small text-black-50\">\n <a href=\"#\">meital@mit.edu</a>\n </div>\n </div>\n </div>\n </div>\n\n <!-- <div class=\"col-md-4 mb-3 mb-md-0\">\n <div class=\"card py-4 h-100\">\n <div class=\"card-body text-center\">\n <i class=\"fas fa-mobile-alt text-primary mb-2\"></i>\n <h4 class=\"text-uppercase m-0\">Phone</h4>\n <hr class=\"my-4\">\n <div class=\"small text-black-50\">+1 (555) 902-8832</div>\n </div>\n </div>\n </div>\n </div> -->\n\n <!-- <div class=\"social d-flex justify-content-center\">\n <a href=\"#\" class=\"mx-2\">\n <i class=\"fab fa-twitter\"></i>\n </a>\n <a href=\"#\" class=\"mx-2\">\n <i class=\"fab fa-facebook-f\"></i>\n </a>\n <a href=\"#\" class=\"mx-2\">\n <i class=\"fab fa-github\"></i>\n </a>\n </div> -->\n\n </div>\n </section>\n\n <!-- Footer -->\n <footer class=\"bg-black small text-center text-white-50\">\n <div class=\"container\">\n Copyright &copy; Meital Hoffman 2019\n </div>\n </footer>\n\n <!-- Bootstrap core JavaScript -->\n <script src=\"vendor/jquery/jquery.min.js\"></script>\n <script src=\"vendor/bootstrap/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Plugin JavaScript -->\n <script src=\"vendor/jquery-easing/jquery.easing.min.js\"></script>\n\n <!-- Custom scripts for this template -->\n <script src=\"js/grayscale.min.js\"></script>\n\n</body>\n\n</html>\n" }, { "alpha_fraction": 0.5530434846878052, "alphanum_fraction": 0.573913037776947, "avg_line_length": 29.236841201782227, "blob_id": "f35b4e91cdbc647e8ad9579b9ce92c0c445af5d8", "content_id": "40d89bcaf9b19cfcb550f4fe8c0782fc7411ac27", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2300, "license_type": "permissive", "max_line_length": 82, "num_lines": 76, "path": "/getNYTimesArticles.py", "repo_name": "meitalhoffman/AsylumViz", "src_encoding": "UTF-8", "text": "'''\nthis is a script to get the NYTimes data about asylum seekers for each month from \nJanuary 2015 until January 2019\nCreated by: Meital Hoffman\nCreated on: 5/4/2019\n'''\nimport config\nimport requests\nimport random\nimport time\n\nkey = config.NYTInfo[\"Key\"]\nsecretKey = config.NYTInfo[\"Secret\"]\nbaseURL = \"https://api.nytimes.com/svc/archive/v1/\"\nend = \".json?api-key=\"+key\n\nasylum = {}\n\n#iterate through the years we have\n# for year in range(2015, 2020):\n# #iterate through each month\n# for month in range(1, 13):\n# print(\"getting article for: \"+str(month)+\"/\" + str(year))\n# time.sleep(6)\n# monthly = []\n# middle = \"/\" + str(year) + \"/\" + str(month)\n# resp = requests.get(baseURL + middle + end)\n# if resp.status_code != 200:\n# # This means something went wrong.\n# print('GET /tasks/ {}'.format(resp.status_code))\n\n# json = resp.json()[\"response\"][\"docs\"]\n# addedArticle = False\n# for article in json:\n# for keyword in article[\"keywords\"]:\n# if(addedArticle):\n# break\n# if(\"Asylum, Right of\" in keyword[\"value\"]):\n# monthly.append(article)\n# addedArticle = True\n# addedArticle = False\n# file = open(str(month) + \"-\" + str(year)+\".txt\", \"w\")\n# file.write(str(monthly))\n# file.close\n# if(month == 1 and year == 2019):\n# break\n\n\naddOn = \"/2018/3.json?api-key=\"+key\n\nresp = requests.get(baseURL+addOn)\nif resp.status_code != 200:\n # This means something went wrong.\n raise ApiError('GET /tasks/ {}'.format(resp.status_code))\n\njson = resp.json()[\"response\"][\"docs\"]\nasylum = []\naddedArticle = False\nfor article in json:\n # headlines.append(article[\"headline\"][\"main\"])\n print(\"checking article\")\n for keyword in article[\"keywords\"]:\n print(\"checking keyword\")\n if(addedArticle):\n print(\"already added this one\")\n break\n if(\"Immigration\" in keyword[\"value\"]):\n print(\"found a match, adding article\")\n asylum.append(article)\n addedArticle = True\n addedArticle = False\n \n\ndisplay = open(\"3-2018.txt\", \"w\")\ndisplay.write(str(asylum))\ndisplay.close() \n\n" }, { "alpha_fraction": 0.5492879748344421, "alphanum_fraction": 0.5837135314941406, "avg_line_length": 32.49074172973633, "blob_id": "3cc43c70f005734547652bfca77eb09a84f2e165", "content_id": "11ffa11f0c25a36972a65d294451b4896fa64e04", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7233, "license_type": "permissive", "max_line_length": 172, "num_lines": 216, "path": "/js/vis1aa.js", "repo_name": "meitalhoffman/AsylumViz", "src_encoding": "UTF-8", "text": "function getData1aa(data) {\n let vars = [\"Percent Credible Fear\", \"Percent No Fear\", \"Percent Closing\"]\n let result = []\n for(let i = 0; i < data.length; i++){\n var row = {\n Date: parseTime(data[i].Month + \" \" + data[i].Year),\n }\n for(let v in vars){\n row[vars[v]] = +(data[i][vars[v]])\n }\n result.push(row)\n }\n // console.log(result)\n return result.reverse()\n }\n\nvar keyDates = {\n \"Obama shifts priority to detaining migrants at the border\": \"February 2015\",\n \"ICE officials round up families who were denied asylum\": \"December 2015\",\n \"Supreme Court does not uphold Obama's defered action plan, DAPA\": \"June 2016\",\n \"Trump Elected\": \"November 2016\",\n \"Trump signs Executive Order 13767, making asylum harder to claim\": \"January 2017\",\n \"Trump signs the Muslim travel ban\": \"January 2017\",\n \"Zero Tolerance family seperation policy piloted in El Paso\": \"July 2017\",\n \"Trump announces the end of DACA\": \"September 2017\",\n \"Jeff Sessions increases immigration judge's yearly quota\": \"April 2018\",\n \"Trump introduces Family Seperation Policy\": \"April 2018\",\n \"Session rules that domestic abuse victims no longer qualify for asylum\": \"June 2018\",\n \"Trump ends Family Seperation Policy\": \"June 2018\",\n \"Trump begins 'Remain in Mexico' policy\": \"January 2019\"\n}\n\n// Our D3 code will go here.\nd3.csv(\"https://gist.githubusercontent.com/meitalhoffman/55cd0943982f8b9fa6dcf87b2c571289/raw/797304f0853ecf05ede2a3eda5c8cb5494399b4f/vis1aa.csv\").then(function(rawData) {\n\nlet data1a = getData1aa(rawData)\n\n// Setup svg using Bostock's margin convention\n\nvar margin = {top: 20, right: 160, bottom: 35, left: 30};\n\nvar width = 960 - margin.left - margin.right,\n height = 500 - margin.top - margin.bottom;\n\nvar svg = d3.select(\"#defensive\")\n .append(\"svg\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", height + margin.top + margin.bottom)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n\nlet sections1a = [\"Percent Credible Fear\", \"Percent No Fear\", \"Percent Closing\"]\n\n// Transpose the data into layers\nvar dataset1a = d3.stack().keys(sections1a)(data1a)\n\nlet xAxis = g => g\n .attr(\"transform\", `translate(0,${height - margin.bottom})`)\n .attr(\"stroke\", d3.rgb(\"#ffffff\"))\n .attr(\"opacity\", \".7\")\n .call(d3.axisBottom(xAxisScale)\n .ticks(5)\n .tickFormat(d3.timeFormat('%B %Y')))\n .call(g => g.selectAll(\".domain\").remove())\n\nlet yAxis = g => g\n .attr(\"transform\", `translate(${margin.left},0)`)\n .attr(\"stroke\", d3.rgb(\"#ffffff\"))\n .attr(\"opacity\", \".7\")\n .call(d3.axisLeft(y).ticks(null, \"s\"))\n .call(g => g.selectAll(\".domain\").remove())\n\n// Set x, y and colors\nvar x = d3.scaleBand()\n .domain(data1a.map(d => d.Date))\n .range([margin.left, width - margin.right])\n .padding(0.1)\n\nvar xAxisScale = d3.scaleTime()\n .domain([parseTime(\"January 2015\"), parseTime(\"January 2019\")])\n .range([margin.left+3, width - margin.right-3])\n\n\nvar y = d3.scaleLinear()\n .domain([0, d3.max(dataset1a, d => d3.max(d, d => d[1]))])\n .rangeRound([height - margin.bottom, margin.top])\n\nvar colors = [\"#720421\", \"#ae172a\", \"#dc6e57\"];\nfunction color(key){\n let i = sections1a.indexOf(key)\n return colors[i]\n}\n\n// Define and draw axes\nsvg.append(\"g\")\n .attr(\"class\", \"y axis\")\n .call(yAxis);\n\nsvg.append(\"g\")\n .attr(\"class\", \"x axis\")\n .attr(\"transform\", \"translate(0,\" + height + \")\")\n .call(xAxis);\n\n\n// Create groups for each series, rects for each segment \nvar groups = svg.selectAll(\"g.percent\")\n .data(dataset1a)\n .enter().append(\"g\")\n .attr(\"class\", \"percent\")\n .style(\"fill\", function(d, i) { return color(d.key); })\n\nvar rect = groups.selectAll(\"rect\")\n .data(function(d) { return d; })\n .enter()\n .append(\"rect\")\n .attr(\"x\", (d, i) => x(d.data.Date))\n .attr(\"y\", d => y(d[1]))\n .attr(\"height\", d => y(d[0]) - y(d[1]))\n .attr(\"width\", x.bandwidth())\n // .on(\"mouseover\", d => tooltip.style(\"visibility\", \"visible\").text(format(d.data.Date)))\n .on(\"mouseover\", d => tooltip.style(\"visibility\", \"visible\").text(getHoverText(d)))\n .on(\"mousemove\", d => tooltip.style(\"top\", (d3.event.pageY-10)+\"px\").style(\"left\",(d3.event.pageX+10)+\"px\").text(getHoverText(d)))\n .on(\"mouseout\", d => tooltip.style(\"visibility\", \"hidden\"));\n\nvar formatHeadline = d3.timeFormat('%m-%Y')\n\nfunction getHoverText(d){\n let text = format(d.data.Date) + \": \" + String((d[1] - d[0]).toFixed(3)) + \"%\"\n return text\n}\n\n//format the date objects\nvar format = d3.timeFormat('%B %Y')\n// Draw legend\nvar legend = svg => {\n const g = svg\n .attr(\"font-family\", \"sans-serif\")\n .attr(\"font-size\", 10)\n .attr(\"text-anchor\", \"end\")\n .attr(\"transform\", `translate(${width + 40},${margin.top})`)\n .selectAll(\"g\")\n .data(dataset1a.slice().reverse())\n .join(\"g\")\n .attr(\"transform\", (d, i) => `translate(0,${i * 30})`);\n \n g.append(\"rect\")\n .attr(\"x\", -19)\n .attr(\"width\", 19)\n .attr(\"height\", 19)\n .attr(\"fill\", d => color(d.key));\n \n g.append(\"text\")\n .attr(\"x\", -24)\n .attr(\"y\", 9.5)\n .attr(\"fill\", \"#ffffff\")\n .attr(\"dy\", \"0.35em\")\n .text(d => getLegendText(d.key));\n }\n\n function getLegendText(key){\n if(key == \"Percent No Fear\") return \"Credible Fear Not Established\"\n else if(key == \"Percent Credible Fear\") return \"Credible Fear Established\"\n else if(key == \"Percent Closing\") return \"Cases Closed\"\n }\n\n// Prep the tooltip bits, initial display is hidden\nvar tooltip = d3.select(\"body\")\n .append(\"div\")\n .style(\"position\", \"absolute\")\n .style(\"z-index\", \"1\")\n .style(\"visibility\", \"hidden\")\n .style(\"background\",\"white\")\n .style(\"opacity\",\"0.6\")\n .style(\"padding\",\"5px\")\n .style(\"font-family\", \"'Open Sans', sans-serif\")\n .style(\"font-size\", \"12px\"); \n\nsvg.append(\"g\")\n .call(legend);\n\n svg.append(\"text\")\n .attr(\"font-family\", \"sans-serif\")\n .attr(\"font-size\", 10)\n .attr(\"x\", 0+margin.left) \n .attr(\"y\", 5 - (margin.top / 2))\n .attr(\"stroke\", d3.rgb(\"#ffffff\"))\n .attr(\"text-anchor\", \"left\") \n .style(\"font-size\", \"16px\") \n .text(\"Defensive Asylum Outcomes\");\n\n svg.append(\"text\") \n .attr(\"font-family\", \"sans-serif\")\n .attr(\"font-size\", 10) \n .attr(\"transform\",\n \"translate(\" + ((width/2) - 30) + \" ,\" + \n (height + margin.top - 10) + \")\")\n .attr(\"stroke\", d3.rgb(\"#ffffff\"))\n .style(\"opacity\", \".5\")\n .style(\"font-size\", \"13px\") \n .style(\"text-anchor\", \"middle\")\n .text(\"Date\");\n \n // text label for the y axis\n svg.append(\"text\")\n .attr(\"font-family\", \"sans-serif\")\n .attr(\"font-size\", 10)\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"y\", 0 - margin.left)\n .attr(\"x\",0 - (height / 2))\n .attr(\"dy\", \"1em\")\n .attr(\"stroke\", d3.rgb(\"#ffffff\"))\n .style(\"opacity\", \".5\")\n .style(\"font-size\", \"13px\") \n .style(\"text-anchor\", \"middle\")\n .text(\"Percent of Applications\"); \n});" } ]
5
ed-george/adbp
https://github.com/ed-george/adbp
4be828256d35d9a8184fbf4ef248952235165486
a005af7c8f372c3b2fd5fc0ecb3c7a6950ba5cf8
fa0ac7fe7f1050b64ab151c28f37f6850abb14dc
refs/heads/main
2023-08-27T18:05:02.740575
2021-10-07T06:03:27
2021-10-07T06:03:27
386,385,235
4
1
Apache-2.0
2021-07-15T18:15:38
2021-07-16T08:00:51
2021-10-06T03:12:05
Python
[ { "alpha_fraction": 0.5121951103210449, "alphanum_fraction": 0.6829268336296082, "avg_line_length": 19.5, "blob_id": "e31a465543ba9a1cab6d5a57c4f9c30c4a73694c", "content_id": "fb78077ea33c598254022adc92b2142c28f802cb", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 41, "license_type": "permissive", "max_line_length": 27, "num_lines": 2, "path": "/requirements.txt", "repo_name": "ed-george/adbp", "src_encoding": "UTF-8", "text": "click==8.0.1\npure_python_adb==0.3.0.dev0\n" }, { "alpha_fraction": 0.6804393529891968, "alphanum_fraction": 0.7128661274909973, "avg_line_length": 23.83116912841797, "blob_id": "b76fcfc9a18256a34167001e914593f4f0267e4e", "content_id": "70d0dafe1dda56758b7444508163b224b07eb278", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1915, "license_type": "permissive", "max_line_length": 309, "num_lines": 77, "path": "/README.md", "repo_name": "ed-george/adbp", "src_encoding": "UTF-8", "text": "# adbp\nA Python script to make working with proxies on your Android devices _much_ easier!\n\n----\n\n# Installation\n\n### Pre-Requisites\n\n* [adb](https://developer.android.com/studio/command-line/adb)\n* [Python 3](https://www.python.org/downloads/)\n\n### Install packages\n\n```\npip install -r requirements.txt\n```\n\n# Usage\n\n\n```\nUsage: adbp.py [OPTIONS] COMMAND [ARGS]...\n\n A tool to add/remove proxies on Android devices via adb\n\nOptions:\n --help Show this message and exit.\n\nCommands:\n add Adds a proxy\n remove Removes any proxy\n```\n\n## Add a proxy\n\n```\nUsage: adbp.py add [OPTIONS]\n\n Enables a proxy on connected devices via adb\n\nOptions:\n --serial TEXT Device Serial\n --ip TEXT IP Address\n --port INTEGER Proxy Port\n --help Show this message and exit.\n```\n\n**Examples:**\n\n`python3 adbp.py add` - Adds proxy with default ip address and port 8888 to **all** connected devices\n\n`python3 adbp.py add --serial 1234` - Adds proxy with default ip address and port 8888 to connected device with serial id 1234\n\n`python3 adbp.py add --serial 1234 --ip 192.168.0.1 --port 8080` - Adds proxy of 192.168.0.1:8080 to connected device with serial id 1234\n\n## Remove a proxy\n\n```\nUsage: adbp.py remove [OPTIONS]\n\n Removes any proxy on connected devices via adb\n\nOptions:\n --serial TEXT Device Serial\n --help Show this message and exit.\n```\n\n**Examples:**\n\n`python3 adbp.py remove` - Removes any configured proxy on **all** connected devices\n\n`python3 adbp.py remove --serial 1234` - Removes any configured proxy on connected device with serial id 1234\n\n## Contributing 🛠\n\nI welcome contributions and discussion for new features or bug fixes. It is recommended to file an issue first to prevent unnecessary efforts, but feel free to put in pull requests in the case of trivial changes. In any other case, please feel free to open discussion and I will get back to you when possible.\n" }, { "alpha_fraction": 0.5737639665603638, "alphanum_fraction": 0.5877193212509155, "avg_line_length": 27.488636016845703, "blob_id": "cfd863da2cd284a95aee9262812aade3dab20424", "content_id": "56973621ccc0f07f0d8a279294f7cbcd940f7784", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2508, "license_type": "permissive", "max_line_length": 75, "num_lines": 88, "path": "/adbp.py", "repo_name": "ed-george/adbp", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport click\nimport socket\n\nfrom ppadb.client import Client as AdbClient\n\n# Globals #\nADB_HOST = \"127.0.0.1\"\nADB_PORT = 5037\n\n####################################################################\n\n@click.group()\ndef adbp():\n \"\"\"A tool to add/remove proxies on Android devices via adb\"\"\"\n\n@adbp.command('remove', short_help='Removes any proxy')\n@click.option('--serial', default='', help='Device Serial')\ndef remove(serial):\n \"\"\"Removes any proxy on connected devices via adb\"\"\"\n apply_rule(serial, '', 0)\n\n@adbp.command('add', short_help='Adds a proxy')\n@click.option('--serial', default='', help='Device Serial')\n@click.option('--ip', default='', help='IP Address')\n@click.option('--port', default=8888, help='Proxy Port')\ndef add(serial, ip, port):\n \"\"\"Enables a proxy on connected devices via adb\"\"\"\n if ip == '':\n ip = get_local_ip(lambda: click.echo('Using default IP'))\n apply_rule(serial, ip, port)\n\n##################################################################### \n\n# Applies proxy rule to selected device(s) with supplied ip and port\ndef apply_rule(serial, ip, port):\n if serial != '':\n # Single rule\n create_proxy(serial, ip, port)\n else:\n # Multi-device rule\n for device in get_devices():\n create_proxy(device.serial, ip, port)\n\n\n# Return a sanitised list of connected devices\ndef get_devices():\n client = AdbClient(host=ADB_HOST, port=ADB_PORT)\n return client.devices()\n\n# Create proxy via adb\ndef create_proxy(serial, ip, port):\n click.echo('Creating proxy rule for %s %s:%d' % (serial, ip, port))\n cmd = 'settings put global http_proxy %s:%d' % (ip, port)\n return run_cmd(cmd, serial, lambda: click.echo('Success'))\n\n# Run a term command\ndef run_cmd(cmd, serial, func = lambda: ()):\n client = AdbClient(host=ADB_HOST, port=ADB_PORT)\n device = client.device(serial)\n output = device.shell(cmd)\n \n if output != '':\n show_error(output)\n else:\n func()\n\n return output \n\ndef show_error(msg):\n click.echo('*** Error %s ***' % msg)\n\ndef get_local_ip(func = lambda: ()):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n try:\n s.connect(('10.255.255.255', 1))\n local_ip = s.getsockname()[0]\n except Exception:\n local_ip = '127.0.0.1'\n show_error(\"Local IP Address is set to localhost(%s)\" % (local_ip))\n finally:\n s.close()\n func()\n return local_ip\n\nif __name__ == '__main__':\n adbp()\n\n" } ]
3
KazeofHope/Gun-Range
https://github.com/KazeofHope/Gun-Range
0f460b8f6e212de82a9fd0f8d22463f0b1aea61b
279eaeaddb0adfe1ea142282c449b144ba991f3f
9f4df9cda0aacf04f72b0c318b374855a7727af7
refs/heads/master
2022-12-14T17:33:15.962500
2020-08-29T00:04:56
2020-08-29T00:04:56
290,622,458
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.41609445214271545, "alphanum_fraction": 0.4215374290943146, "avg_line_length": 23.354564666748047, "blob_id": "713146063a6ce2d231f3ec80b07f429c4f24a82d", "content_id": "e79945ed73539996f8053706b231460f3d46365b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11942, "license_type": "no_license", "max_line_length": 242, "num_lines": 471, "path": "/Gun_Proficiency.py", "repo_name": "KazeofHope/Gun-Range", "src_encoding": "UTF-8", "text": "import json\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nclass Testing_Ground:\r\n def __init__(self):\r\n self.prev_data = {\r\n\"Shooting Range Data\" :\r\n{\r\n \"Pistol\" :\r\n {\r\n \"Classic\" : {\r\n \"Data\" : {\r\n \"Easy\" : [\r\n\r\n ],\r\n \"Medium\" : [\r\n\r\n ],\r\n \"Hard\" : [\r\n\r\n ]\r\n }\r\n },\r\n \"Shorty\" : {\r\n \"Data\" : {\r\n \"Easy\" : [\r\n\r\n ], \"Medium\" : [\r\n\r\n ], \"Hard\" : [\r\n\r\n ]\r\n }\r\n },\r\n \"Frenzy\" : {\r\n \"Data\" : {\r\n \"Easy\" : [\r\n\r\n ],\r\n \"Medium\" : [\r\n\r\n ],\r\n \"Hard\" : [\r\n\r\n ]\r\n }\r\n },\r\n \"Ghost\" : {\r\n \"Data\" : {\r\n \"Easy\" : [\r\n\r\n ],\r\n \"Medium\" : [\r\n\r\n ],\r\n \"Hard\" : [\r\n\r\n ]\r\n }\r\n },\r\n \"Sheriff\" : {\r\n \"Data\" : {\r\n \"Easy\" : [\r\n\r\n ],\r\n \"Medium\" : [\r\n\r\n ],\r\n \"Hard\" : [\r\n\r\n ]\r\n }\r\n }\r\n },\r\n \"SMG\" : {\r\n \"Stinger\" : {\r\n \"Data\" : {\r\n \"Easy\" : [\r\n\r\n ],\r\n \"Medium\" : [\r\n\r\n ],\r\n \"Hard\" : [\r\n\r\n ]\r\n }\r\n },\r\n \"Spectre\" : {\r\n \"Data\" : {\r\n \"Easy\" : [\r\n\r\n ],\r\n \"Medium\" : [\r\n\r\n ],\r\n \"Hard\" : [\r\n\r\n ]\r\n }\r\n }\r\n },\r\n \"Shotgun\" : {\r\n \"Bucky\" : {\r\n \"Data\" : {\r\n \"Easy\" : [\r\n\r\n ],\r\n \"Medium\" : [\r\n\r\n ],\r\n \"Hard\" : [\r\n\r\n ]\r\n }\r\n },\r\n \"Judge\" : {\r\n \"Data\" : {\r\n \"Easy\" : [\r\n\r\n ],\r\n \"Medium\" : [\r\n\r\n ],\r\n \"Hard\" : [\r\n\r\n ]\r\n }\r\n }\r\n },\r\n \"AR\" : {\r\n \"Bulldog\" : {\r\n \"Data\" : {\r\n \"Easy\" : [\r\n\r\n ],\r\n \"Medium\" : [\r\n\r\n ],\r\n \"Hard\" : [\r\n\r\n ]\r\n }\r\n },\r\n \"Guardian\" : {\r\n \"Data\" : {\r\n \"Easy\" : [\r\n\r\n ],\r\n \"Medium\" : [\r\n\r\n ],\r\n \"Hard\" : [\r\n\r\n ]\r\n }\r\n },\r\n \"Phantom\" : {\r\n \"Data\" : {\r\n \"Easy\" : [\r\n\r\n ],\r\n \"Medium\" : [\r\n\r\n ],\r\n \"Hard\" : [\r\n\r\n ]\r\n }\r\n },\r\n \"Vandel\" : {\r\n \"Data\" : {\r\n \"Easy\" : [\r\n\r\n ],\r\n \"Medium\" : [\r\n\r\n ],\r\n \"Hard\" : [\r\n\r\n ]\r\n }\r\n }\r\n },\r\n \"Sniper\" : {\r\n \"Marshal\" : {\r\n \"Data\" : {\r\n \"Easy\" : [\r\n\r\n ],\r\n \"Medium\" : [\r\n\r\n ],\r\n \"Hard\" : [\r\n\r\n ]\r\n }\r\n },\r\n \"Operator\" : {\r\n \"Data\" : {\r\n \"Easy\" : [\r\n\r\n ],\r\n \"Medium\" : [\r\n\r\n ],\r\n \"Hard\" : [\r\n\r\n ]\r\n }\r\n }\r\n },\r\n \"LMG\" : {\r\n \"Ares\" : {\r\n \"Data\" : {\r\n \"Easy\" : [\r\n\r\n ],\r\n \"Medium\" : [\r\n\r\n ],\r\n \"Hard\" : [\r\n\r\n ]\r\n }\r\n },\r\n \"Odin\" : {\r\n \"Data\" : {\r\n \"Easy\" : [\r\n\r\n ],\r\n \"Medium\" : [\r\n\r\n ],\r\n \"Hard\" : [\r\n\r\n ]\r\n }\r\n }\r\n }\r\n}\r\n}\r\n self.associated_filepath = None\r\n self.gun_types = list(self.prev_data.get(list((self.prev_data.keys()))[0]).keys())\r\n self.gun_names = []\r\n self.current_gun = None\r\n self.current_training_mode = None\r\n self.new_data = []\r\n\r\n for i in self.gun_types:\r\n self.gun_names.extend(list(self.prev_data.get(list(self.prev_data.keys())[0]).get(i).keys()))\r\n\r\n def download_data(self, filepath): # downloads list from json file\r\n self.associated_filepath = filepath\r\n with open(\"{}\".format(self.associated_filepath)) as f:\r\n self.prev_data = json.load(f)\r\n\r\n def exporting_data(self, filepath):\r\n for i in self.prev_data.get(\"Shooting Range Data\"):\r\n if self.current_gun in (self.prev_data.get(\"Shooting Range Data\" ).get(i)):\r\n self.prev_data.get(\"Shooting Range Data\" ).get(i).get(self.current_gun).get(\"Data\").get(self.current_training_mode).extend(self.new_data)\r\n\r\n new_data = self.prev_data\r\n\r\n with open(f'{filepath}', 'w') as json_file:\r\n json.dump(new_data, json_file)\r\n\r\n def practice_session_start(self):\r\n def find_average_scores(current_gun):\r\n averages = []\r\n for i in (self.prev_data.get(list(self.prev_data.keys())[0])):\r\n if current_gun in (self.prev_data.get(list(self.prev_data.keys())[0]).get(i)):\r\n for j in list(self.prev_data.get(list(self.prev_data.keys())[0]).get(i).get(current_gun).get(\"Data\").keys()):\r\n if len(self.prev_data.get(list(self.prev_data.keys())[0]).get(i).get(current_gun).get(\"Data\").get(j)) == 0:\r\n averages.append(\"No Data\")\r\n else:\r\n averages.append(sum(self.prev_data.get(list(self.prev_data.keys())[0]).get(i).get(current_gun).get(\"Data\").get(j))/len(self.prev_data.get(list(self.prev_data.keys())[0]).get(i).get(current_gun).get(\"Data\").get(j)))\r\n return averages\r\n\r\n print(\r\n \"Welcome to your personal Valorant Shooting Range Data Recorder\\n\"\r\n \"Which gun would you like to practice on in this session?\\n\"\r\n f\"{self.gun_names}\"\r\n )\r\n while True:\r\n self.current_gun = input()\r\n if self.current_gun in self.gun_names:\r\n break\r\n else:\r\n print(\"Improper Input\")\r\n\r\n avg = find_average_scores(self.current_gun)\r\n\r\n print(\r\n f\"Training with {self.current_gun}\"\r\n f\"\\tYour Average Scores by difficulty\\n\"\r\n f\"Easy || Medium || Hard\\n\"\r\n f\"{avg}\"\r\n )\r\n\r\n print(\r\n \"Which mode are you going to train in?\\n\"\r\n \"Easy || Medium || Hard\"\r\n )\r\n while True:\r\n self.current_training_mode = input()\r\n if self.current_training_mode == \"Easy\" or \"Medium\" or \"Hard\":\r\n break\r\n else:\r\n print(\"Improper Input\")\r\n\r\n i = 0\r\n while True:\r\n if i == 0:\r\n print(f\"Training Round {i} - Warm up\")\r\n self.warmup_score = input(\"Input warm up score: \")\r\n\r\n elif i > 0:\r\n print(f\"Training Round {i}\")\r\n while True:\r\n n = int(input(\"Input Score: \"))\r\n if n > -1 and n < 31:\r\n break\r\n else:\r\n print(\"Improper Input\")\r\n self.new_data.append(n)\r\n\r\n i = i + 1\r\n\r\n while True:\r\n user_input = input(\"Would you like to continue? (Y/N) \")\r\n if user_input == \"Y\" or user_input == \"N\":\r\n break\r\n else:\r\n \"Improper Input\"\r\n\r\n if user_input == \"N\":\r\n break\r\n\r\n\r\n\r\n print(\r\n f\"Results of Training Session\\n\"\r\n f\"# of Rounds: {i}\\n\"\r\n f\"Scores: {self.new_data}\\n\"\r\n f\"\\n\"\r\n f\"Would you like to export this data to your dataset? (Y/N) \\n\"\r\n )\r\n while True:\r\n user_input = input()\r\n if user_input == \"Y\" or user_input == \"N\":\r\n break\r\n else:\r\n \"Improper Input\"\r\n\r\n if user_input == \"Y\":\r\n self.exporting_data(self.associated_filepath)\r\n else:\r\n print(f\"New Scores for {self.current_gun}: {self.new_data}\")\r\n\r\n def visualize_all_scores(self):\r\n def autolabel(rects):\r\n \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\r\n for rect in rects:\r\n height = rect.get_height()\r\n ax.annotate('{}'.format(height),\r\n xy=(rect.get_x() + rect.get_width() / 2, height),\r\n xytext=(0, 3), # 3 points vertical offset\r\n textcoords=\"offset points\",\r\n ha='center', va='bottom')\r\n\r\n easy_data = []\r\n medium_data = []\r\n hard_data = []\r\n labels = []\r\n\r\n for i in self.prev_data.get(\"Shooting Range Data\"):\r\n for j in self.prev_data.get(\"Shooting Range Data\").get(i):\r\n labels.append(j)\r\n a = len(self.prev_data.get(\"Shooting Range Data\").get(i).get(j).get(\"Data\").get(\"Easy\"))\r\n b = len(self.prev_data.get(\"Shooting Range Data\").get(i).get(j).get(\"Data\").get(\"Medium\"))\r\n c = len(self.prev_data.get(\"Shooting Range Data\").get(i).get(j).get(\"Data\").get(\"Hard\"))\r\n if a > 0:\r\n easy_data.append(sum(self.prev_data.get(\"Shooting Range Data\").get(i).get(j).get(\"Data\").get(\"Easy\"))/a)\r\n else:\r\n easy_data.append(0)\r\n\r\n if b > 0:\r\n medium_data.append(sum(self.prev_data.get(\"Shooting Range Data\").get(i).get(j).get(\"Data\").get(\"Medium\"))/b)\r\n else:\r\n medium_data.append(0)\r\n\r\n if c > 0:\r\n hard_data.append(sum(self.prev_data.get(\"Shooting Range Data\").get(i).get(j).get(\"Data\").get(\"Hard\"))/c)\r\n else:\r\n hard_data.append(0)\r\n\r\n X = np.arange(len(labels))\r\n width = 0.25\r\n\r\n fig, ax = plt.subplots()\r\n ax.bar(X - width/2, easy_data, width, label= 'Easy', color= 'g')\r\n ax.bar(X + width/2, medium_data, width, label= 'Medium', color= 'y')\r\n ax.bar(X + 3*width/2, hard_data, width, label= 'Hard', color= 'r')\r\n\r\n ax.set_ylabel('Scores')\r\n ax.set_title('Scores by Gun')\r\n plt.ylim(0, 30)\r\n ax.set_xticks(X + width / 2)\r\n ax.set_xticklabels(labels)\r\n plt.grid(color='grey', linestyle='-', linewidth=0.25)\r\n ax.legend()\r\n\r\n plt.show()\r\n\r\n def visualize_category(self, category = None):\r\n labels = []\r\n easy_data = []\r\n medium_data = []\r\n hard_data = []\r\n sect_data = self.prev_data.get(\"Shooting Range Data\").get(category)\r\n for i in sect_data:\r\n labels.append(i)\r\n if len(sect_data.get(i).get(\"Data\").get(\"Easy\")) > 0:\r\n easy_data.append(sum(sect_data.get(i).get(\"Data\").get(\"Easy\"))/len(sect_data.get(i).get(\"Data\").get(\"Easy\")))\r\n else:\r\n easy_data.append(0)\r\n\r\n if len(sect_data.get(i).get(\"Data\").get(\"Medium\")) > 0:\r\n medium_data.append(sum(sect_data.get(i).get(\"Data\").get(\"Medium\"))/len(sect_data.get(i).get(\"Data\").get(\"Medium\")))\r\n else:\r\n medium_data.append(0)\r\n\r\n if len(sect_data.get(i).get(\"Data\").get(\"Hard\")) > 0:\r\n hard_data.append(sum(sect_data.get(i).get(\"Data\").get(\"Hard\"))/len(sect_data.get(i).get(\"Data\").get(\"Hard\")))\r\n else:\r\n hard_data.append(0)\r\n\r\n X = np.arange(len(labels))\r\n width = 0.25\r\n\r\n fig, ax = plt.subplots()\r\n ax.bar(X - width/2, easy_data, width, label= 'Easy', color= 'g')\r\n ax.bar(X + width/2, medium_data, width, label= 'Medium', color= 'y')\r\n ax.bar(X + 3*width/2, hard_data, width, label= 'Hard', color= 'r')\r\n\r\n ax.set_ylabel('Scores')\r\n ax.set_title(f'Scores by {category}')\r\n plt.ylim(0, 30)\r\n ax.set_xticks(X + width / 2)\r\n ax.set_xticklabels(labels)\r\n plt.grid(color='grey', linestyle='-', linewidth=0.25)\r\n ax.legend()\r\n\r\n plt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n filepath = r\"C:\\Users\\vsbas\\PycharmProjects\\ECE homework 241 11\\Stupid Projects\\gun_skill_data.json\"\r\n training_session = Testing_Ground()\r\n training_session.download_data(filepath)\r\n training_session.visualize_all_scores()\r\n # training_session.visualize_category(\"AR\")\r\n training_session.practice_session_start()\r\n training_session.visualize_all_scores()\r\n" } ]
1
olgazawislak/Knapsack_problem
https://github.com/olgazawislak/Knapsack_problem
07e10de13ce071849aa746146cab090a62eb570e
fcd1e66343be50f1924f4649fb6a010bb0ea7e7c
ae5835c0e6e14fcc71165d1a873c643929f3afed
refs/heads/master
2020-05-16T14:11:04.914605
2019-05-16T11:22:16
2019-05-16T11:22:16
183,092,604
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8040540814399719, "alphanum_fraction": 0.8040540814399719, "avg_line_length": 73, "blob_id": "cf3685192f7e0f02e5476b679761310ce4ff3bcb", "content_id": "d3438fc6a3f8cf82c3b3d82e1130148fe650da00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 148, "license_type": "no_license", "max_line_length": 128, "num_lines": 2, "path": "/README.md", "repo_name": "olgazawislak/Knapsack_problem", "src_encoding": "UTF-8", "text": "# Knapsack problem\nHere are my solutions to problem how transport cows from earth to alien planet when we know limit of the weight for a spaceship.\n" }, { "alpha_fraction": 0.6078886389732361, "alphanum_fraction": 0.6125289797782898, "avg_line_length": 27.799999237060547, "blob_id": "319ebf9ae7087c77f5a5a98b18248c21da7a59f4", "content_id": "0296a602d1fefb218e078be27ff32bb19ea4d4a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 431, "license_type": "no_license", "max_line_length": 80, "num_lines": 15, "path": "/ps1_test.py", "repo_name": "olgazawislak/Knapsack_problem", "src_encoding": "UTF-8", "text": "import unittest\nfrom ps1 import greedy_cow_transport, cows_dict\n\n\nclass TestCowTransportAlgorithms(unittest.TestCase):\n\n\n def test_greedy_cow_transport(self):\n order_of_transport = [[\"Millie\"], [\"Maggie\", \"Milkshake\"],\n [\"Moo Moo\", \"Lola\"], [\"Florence\"]]\n self.assertEqual(greedy_cow_transport(cows_dict, 5), order_of_transport)\n\n\n if __name__ == \"__main__\":\n unittest.main()" } ]
2
XENON169/BANK-ATM-
https://github.com/XENON169/BANK-ATM-
99231c750f8fa32e6c79dfc4aee8f729745ef2a0
4e883f3d8c7f0c9b81e08653430b90cb55013db1
f78c2db3b723f30da10c22ad426c655a417c2f41
refs/heads/main
2023-04-14T17:02:09.809130
2021-04-21T08:46:04
2021-04-21T08:46:04
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5974658727645874, "alphanum_fraction": 0.6013644933700562, "avg_line_length": 30.090909957885742, "blob_id": "77f8d41e4ee9cf67e6eb1f95f0ca1ec0ad20bc13", "content_id": "3bc09098e69648e65b23e9fea3ac78f216068147", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1026, "license_type": "no_license", "max_line_length": 66, "num_lines": 33, "path": "/main (4).py", "repo_name": "XENON169/BANK-ATM-", "src_encoding": "UTF-8", "text": "import random\nclass Atm(object):\n def __init__(self, balance, accNo):\n #self.cashWithdrawal = cashWithdrawal\n self.balance = balance\n self.accNo = accNo\n #self.ongoingLoan = ongoingLoan\n\n def withdrawal(self, amount):\n newAmount = int(self.balance) - amount\n print (\"remaining balance: \" + str(newAmount))\n def checkBalance(self):\n balance = self.balance\n print(\"Rs.\" + \" \" + \" \" + \"balance is available\")\n\ndef main():\n accountNo = input(\"enter your account number: \")\n balance = input(\"enter your balance: \")\n newUser = Atm(balance, accountNo)\n print(\"Choose your activity: \")\n print(\"1: balance, 2: wthdrawal\")\n activity = int(input(\"enter the activity number: \"))\n if activity == 1: \n newUser.checkBalance()\n elif activity == 2: \n amount = int(input(\"enter the amount to be withdrawed: \"))\n newUser.withdrawal(amount)\n\n else: \n print(\"no such activity found\")\n\nif __name__ == \"__main__\": \n main()\n" } ]
1
zahinruslee/ITT440_LAB5
https://github.com/zahinruslee/ITT440_LAB5
40f351a54859cd38f98d7337e0f5511b39ea993f
4f77aacf730e3ff47a330e8b5610246be6dda9dd
ae2e66bc9fb4aa49b0e7838c7e5911926222455b
refs/heads/main
2023-05-12T12:11:27.715406
2021-06-05T09:07:21
2021-06-05T09:07:21
373,850,659
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6713504791259766, "alphanum_fraction": 0.6963309645652771, "avg_line_length": 19.317461013793945, "blob_id": "0314a62d4057ba2656b01ec8b01a9593724efbac", "content_id": "f2114f08683f241f90d4ca550b97fa18dd174c77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1281, "license_type": "no_license", "max_line_length": 112, "num_lines": 63, "path": "/ITT440_LAB5/lab5_4c.py", "repo_name": "zahinruslee/ITT440_LAB5", "src_encoding": "UTF-8", "text": "import socket\nimport sys\nimport json\nimport tqdm\nimport os\n\nSEPARATOR = \"<SEPARATOR>\"\nBUFFER_SIZE = 4096 # send 4096 bytes each time step\n\n# create client socket\ns = socket.socket()\n\n# the ip address of server\nhost = '192.168.56.102'\n\n# the port\nport = 5060\n\n# connect to socket\nprint(f\"[+] Connecting to {host}:{port}\") \ns.connect((host, port))\nprint(\"[+] Connected.\")\n\n# prompt filename from user\nfilename = input(\"Enter the filename with extension: \")\nprint(\"Filename : \", filename)\n\n# get the file size\nfilesize = os.path.getsize(filename)\n\n# send the filename and filesize\ns.send(f\"{filename}{SEPARATOR}{filesize}\".encode())\n\n#start sending the file\nprogress = tqdm.tqdm(range(filesize), f\"Sending {filename}\", unit = \"B\", unit_scale = True, unit_divisor = 1024)\nwith open(filename, \"rb\") as f:\n\tfor _ in progress:\n\t\t# read the bytes from the file\n\t\tbytes_read = f.read(BUFFER_SIZE)\n\t\tif not bytes_read:\n\t\t\t# file transmitting is done\n\t\t\tbreak\n\t\t# we use sendall to assure transmission in\n\t\t# busy networks\n\t\ts.sendall(bytes_read)\n\n\t\t# update the progress bar\n\t\tprogress.update(len(bytes_read))\n\n\n#data = s.recv(1024)\n#data = data.decode(\"utf-8\")\n\n#s.send(b'Thank you from client!');\n\n#dataJ = json.loads(data)\n\n#print(type(data))\n#print(data)\n\n\n# close the socket\ns.close()\n\n" }, { "alpha_fraction": 0.6963298320770264, "alphanum_fraction": 0.7139266133308411, "avg_line_length": 23.55555534362793, "blob_id": "3691568833b630c1da455277a5f3ab398699812c", "content_id": "98b7f58017cc274fe27f3ff32e95b87c0a6971d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1989, "license_type": "no_license", "max_line_length": 114, "num_lines": 81, "path": "/ITT440_LAB5/lab5_4s.py", "repo_name": "zahinruslee/ITT440_LAB5", "src_encoding": "UTF-8", "text": "import socket\nimport sys\nimport json\nimport tqdm\nimport os\n\nmydata = {\"id\":\"505012\", \"name\":\"Azizi\", \"age\":\"29\"}\nsendData = json.dumps(mydata)\n\n# create server socket(TCP socket)\ns = socket.socket()\nprint(f\"[+] Socket successfully created\")\n\n# the server port\nport = 5060\n\n# bind the socket\ns.bind(('', port))\nprint(f\"[+] socket binded to \" + str(port))\n\n# receive 4096 bytes each time\nBUFFER_SIZE = 4096\n\nSEPARATOR = \"<SEPARATOR>\"\n\n# enabling the server to accept connections\n# 5 here is teh number of unaccepted connections that\n# the system will allow before refusing new connections\ns.listen(5)\nprint(f\"[+] Socket is listening | Port: {port}\")\n\n# accept connections if there is any\nclient_socket, address = s.accept()\n\n# if below code is executed, that means the sender is connected\nprint(f\"[+] {address} is connected.\")\n\n# receive the file infos\n# receive using client socket (not server socket)\nreceived = client_socket.recv(BUFFER_SIZE).decode()\nfilename, filesize = received.split(SEPARATOR)\n\n# remove absolute path if there is\nfilename = os.path.basename(filename)\n\n# convert to integer\nfilesize = int(filesize)\n\n# start receiving the file from teh socket\n# and writing to the file stream\nprogress = tqdm.tqdm(range(filesize), f\"Receiving {filename}\", unit = \"B\", unit_scale = True, unit_divisor = 1024)\nwith open(filename, \"wb\") as f:\n\tfor _ in progress:\n\t\t# read 1024 bytes from the socket (receive)\n\t\tbytes_read = client_socket.recv(BUFFER_SIZE)\n\t\tif not bytes_read:\n\t\t\t# nothing is received\n\t\t\t# file trasmitting is done\n\t\t\tprint(\"File received successfully\")\n\t\t\tbreak\n\n\t\t# write to the file the bytes we just received\n\t\tf.write(bytes_read)\n\n\t\t# update the progress bar\n\t\tprogress.update(len(bytes_read))\n\n# close the client socket\nclient_socket.close()\n\n# close the server socket\\\ns.close()\n\n#while True:\n#\tc, addr = s.accept()\n#\tprint(\"Got connection from \" + str(addr))\n\n#\tc.sendall(bytes(sendData, encoding = \"utf-8\"))\n#\tbuffer = c.recv(1024)\n#\tprint(buffer)\n#c.close()\n" } ]
2
ETAChalmers/dassmusik
https://github.com/ETAChalmers/dassmusik
589c40c4a0a33e2d12633a9b21b64597fa8c1d20
97ab63dfef0e443fefd08e89d63d3dc2b8f723fc
d930bdb55a7450f940ca244e21a86db2b62b2c89
refs/heads/master
2020-05-25T12:00:16.290127
2016-11-12T13:01:56
2016-11-12T13:01:56
32,551,212
1
1
null
2015-03-19T23:15:38
2015-03-20T12:29:14
2016-11-12T13:01:56
Python
[ { "alpha_fraction": 0.44117647409439087, "alphanum_fraction": 0.5, "avg_line_length": 13.571428298950195, "blob_id": "1f148bb082adc8c6a54b0fb0413fc7d73bf77594", "content_id": "f26fdb860baa01aba8943a4530795830c432bf10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 102, "license_type": "no_license", "max_line_length": 41, "num_lines": 7, "path": "/stop.sh", "repo_name": "ETAChalmers/dassmusik", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nfor ((i=85; i>=0; i--))\ndo\n sleep 0.02\n amixer -q set 'PCM' ${i}% > /dev/null\ndone\n" }, { "alpha_fraction": 0.4060402810573578, "alphanum_fraction": 0.4278523623943329, "avg_line_length": 30.36842155456543, "blob_id": "0d43c9960e3ad4581b74f9776523ce8a56bbd853", "content_id": "a50e4f63353c9818236c067401e2abfd4d76c866", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 596, "license_type": "no_license", "max_line_length": 59, "num_lines": 19, "path": "/packetizer.py", "repo_name": "ETAChalmers/dassmusik", "src_encoding": "UTF-8", "text": "class Packetizer:\n def __init__( self ):\n self.buffer = ''\n\n def push( self, str ):\n self.buffer += str\n\n def pop( self ):\n (first, s, last) = self.buffer.partition( \"\\n\" )\n if last != '':\n self.buffer = last\n fields = first.split( ' ' )\n if fields[0].lower() == 'pkt':\n id = int( fields[1], 16 )\n ext = int( fields[2], 16 )\n flagb = int( fields[3], 16 )\n data = [ int( x, 16 ) for x in fields[4:] ]\n return (id, ext, flagb, data)\n return None\n" }, { "alpha_fraction": 0.42574256658554077, "alphanum_fraction": 0.5148515105247498, "avg_line_length": 13.428571701049805, "blob_id": "c090f32f646e00178aac6ef979ce7e25b3f7037a", "content_id": "7558d7ecfc95d4da8de19cc2ed4f82fb5ed0efc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 101, "license_type": "no_license", "max_line_length": 29, "num_lines": 7, "path": "/start.sh", "repo_name": "ETAChalmers/dassmusik", "src_encoding": "UTF-8", "text": "#!/bin/bash\nsleep 0.7\nfor ((i=50; i<=85; i++))\ndo\n# sleep 0.01\n amixer -q set 'PCM' ${i}%\ndone\n" }, { "alpha_fraction": 0.523809552192688, "alphanum_fraction": 0.7023809552192688, "avg_line_length": 27, "blob_id": "b858e57238600a55bd1f0c9aac2e522892a7d31b", "content_id": "32edf10d0ed0fd86c549127256c9d2060d71abac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 84, "license_type": "no_license", "max_line_length": 41, "num_lines": 3, "path": "/run_dassmusik.sh", "repo_name": "ETAChalmers/dassmusik", "src_encoding": "UTF-8", "text": "#!/bin/bash\npython ./dassmusik.py 192.168.30.161 1200\nsh ./run_dassmusik.sh && exit\n" }, { "alpha_fraction": 0.7303664684295654, "alphanum_fraction": 0.7350785136222839, "avg_line_length": 32.50877380371094, "blob_id": "f682ff6e92e36904019a93967fedf089e75ad7a1", "content_id": "0868cbf4b308bb92a1afdb558bce35ad1482415b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1910, "license_type": "no_license", "max_line_length": 172, "num_lines": 57, "path": "/README.md", "repo_name": "ETAChalmers/dassmusik", "src_encoding": "UTF-8", "text": "# Dassmusik\nThis is the wonderful set of scripts that gives the bathroom at ETA its lovely soundtrack.\n\n\n## Depedencies\n* python 2.x\n* screen\n* mplayer\n* alsamixer + utils\n\n## Setup\nFollow the steps below! \n\n### 1. Get the Dassmusik repo \nClone the Dassmusik repo to a folder of your choice:\n\n git clone https://github.com/ETAChalmers/dassmusik.git\n\n### 2. Configure Dassmusik\nThere are a few things that are installation specific, if you're at ETA then you might not need to worry.\n\n#### dassmusik.py\nChange ```musicDirectory```to the directory containing music to be played. Make sure to use the globbing ** found in bash to traverse all subdirectories as well.\n\n musicDirectory = '<path to your music directory>'\n\n#### start.sh & stop.sh\nMake sure that the volume to control is set to the proper name, in rthe RPi case, this is PCM. The limits of ```i```can be set according to what value makes the sound clip.\n\n amixer -q set 'PCM' ${i}% > /dev/null\n\n#### run_dassmusik.sh\nPoint the python script arguments to the candaemon source.\n\n python ./dassmusik.py <CanDaemon IP> <CanDaemon Port>\n\n#### start_dassmusik_screen.sh\nUpdate the variable ```DASSMUSIK_FOLDER``` to point to the folder where dassmusik resides. This is in order to be able to call the script from anywhere.\n\n DASSMUSIK_FOLDER=/home/eta/dassmusik\n\n### 3. Configure mplayer\nEdit your ```~/.mplayer/config``` and add the following lines:\n \n af-add=volnorm=2:0.75\n ao=alsa\n\nThis enables volume normalization and sets ALSA as audio output driver.\n\n### 4. Set Dassmusik to start on boot.\nThe easiest way to do this is to use the user crontab.\n\nRun ```crontab -e``` and enter the following line, adjusted for where you put the Dassmusik folder:\n\n @reboot /home/eta/dassmusik/start_dassmusik_screen.sh\n\nThis will start a screen running Dassmusik on computer start, emitting lovely music when the bathroom door is closed!\n" }, { "alpha_fraction": 0.6113914847373962, "alphanum_fraction": 0.6261715888977051, "avg_line_length": 28.510639190673828, "blob_id": "1b43a37fb676c07892184f60fd1c05c552c123d2", "content_id": "b219bb241e6e917b7c438f5e1005b8b172a1dc54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2774, "license_type": "no_license", "max_line_length": 131, "num_lines": 94, "path": "/dassmusik.py", "repo_name": "ETAChalmers/dassmusik", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport socket\nimport sys\nimport time\nimport datetime\n\nimport packetizer\nimport subprocess\n\npiz = packetizer.Packetizer()\nNumRuns = 0\n\ndef untilNone( fnc ):\n res = fnc()\n while res != None:\n yield res\n res = fnc()\n\ntry:\n host = sys.argv[1]\n port = int( sys.argv[2] )\nexcept:\n print \"Script to play music accoring to opening and closing of bathroom door.\"\n print \"Depends upon having a can->telnet interface using the auml homeautomation protocol.\"\n print \"Usage: dassmusik.py candaemon_ip candaemon_port \"\n sys.exit(1)\n\nattemptTimeout = 15 # Time in seconds.\nmusicDirectory = '/home/eta/musik/**' # Directory in which music to play can be found.\n\nprint \"Starting dassmusik.py\"\nconnected = False\nwhile not connected:\n try:\n sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )\n sock.connect( (host, port) )\n connected = True\n print \"Connected to %s:%s\" % (host, port)\n except socket.error, msg:\n print \"Socket error: \", msg\n print \"Trying again in %s seconds.\" % (attemptTimeout)\n time.sleep(attemptTimeout)\n print \"\\r\\nNew attempt to connect to %s:%s\" % (host, port)\n\ndef startMplayer():\n print \"Starting mplayer process.\"\n MusicCmd = 'mplayer -quiet -slave -softvol -shuffle %s' % musicDirectory\n MusicProcess = subprocess.Popen(MusicCmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)\n time.sleep(2) # Wait for mplayer to start properly.\n MusicProcess.stdin.write('pause\\n')\n print \"mplayer process started.\"\n return MusicProcess\n\ndef stopAudio():\n subprocess.call(['./stop.sh'])\n MusicProcess.stdin.write('pause\\n')\n\ndef startAudio():\n global NumRuns\n NumRuns = NumRuns + 1\n MusicProcess.stdin.write('mute 1\\n')\n MusicProcess.stdin.write('pt_step 1\\n')\t\n MusicProcess.stdin.write('mute 0\\n')\n subprocess.call(['./start.sh'])\n\nMusicProcess = startMplayer()\n\ndata = sock.recv( 1024 )\n\n# Print text headers\nprint \"CAN Source: %s:%s\" % (host, port)\n\noldState = 1;\nwhile len( data ):\n piz.push( data )\n\n for (id, ext, f, data) in untilNone( piz.pop ):\n if (id & 0xFFFFFF00) == 0x14006400: # type=chn, chn=toanod 0x0064\n newState = data[1]\n if newState != oldState: # Changed state\n if newState == 0:\n print \"%s - Closed\" % datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')\n startAudio()\n if newState == 1:\n print \"%s - Open - #%s\" % (datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), NumRuns)\n stopAudio()\n oldState = newState\n\n data = sock.recv( 1024 )\n\nsock.close()\n\nsys.exit( 0 );\n" }, { "alpha_fraction": 0.6877323389053345, "alphanum_fraction": 0.6914498209953308, "avg_line_length": 23.454545974731445, "blob_id": "bf92ec07aa23de704e485bcdad7e63be242e2183", "content_id": "10a90f796df330b966104a18706c8ad7ba152bfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 269, "license_type": "no_license", "max_line_length": 48, "num_lines": 11, "path": "/start_dassmusik_screen.sh", "repo_name": "ETAChalmers/dassmusik", "src_encoding": "UTF-8", "text": "#!/bin/bash\nDASSMUSIK_FOLDER=/home/eta/dassmusik\nscreen -ls | grep -q dassmusik\nif [ $? -eq 1 ]\nthen\n echo \"Starting dassmusik screen.\"\n cd $DASSMUSIK_FOLDER\n screen -d -m -S dassmusik ./run_dassmusik.sh\nelse\n echo \"Dassmusik screen is already running.\"\nfi\n" } ]
7
pobc/Excel_data
https://github.com/pobc/Excel_data
2849068f3d012928afd1288af8f529ad539ad4c2
779c3071df38ab630430fcd3010f8fe7e7310bf3
b890bb5f06b08331eae83cb0be3dbdfa05c3f12f
refs/heads/master
2020-04-11T15:01:03.738048
2018-12-15T06:32:54
2018-12-15T06:32:54
161,876,679
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6019269824028015, "alphanum_fraction": 0.6211967468261719, "avg_line_length": 24.28205108642578, "blob_id": "ebbaba2751e35b96c4679281f4a7fc57dc7f254c", "content_id": "d7193b14df872488f9912a409c7b777888cb3f96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2236, "license_type": "no_license", "max_line_length": 68, "num_lines": 78, "path": "/process_excel/HandleExcel.py", "repo_name": "pobc/Excel_data", "src_encoding": "UTF-8", "text": "\"\"\"\n操作excel\n1.读取excel内容\n2.处理数据\n3.存数据\n\"\"\"\nimport openpyxl as xl\n\n# xl.load_workbook(r\"D:\\work\\text.xlsx\").get_sheet_by_name(\"Sheet1\")\n# xl.load_workbook(r\"D:\\work\\text.xlsx\").get_sheet_by_name(\"Sheet2\")\n\n# 读取excel\nsheets = xl.load_workbook(r\"D:\\work\\text.xlsx\")\n\n# 定位sheet1\nsheet1 = sheets.get_sheet_by_name(\"Sheet1\")\n\"\"\"\n print(\"abc 定位\")\n print(sheet1[\"A2\"].value)\n print(sheet1[\"B2\"].value)\n print(sheet1[\"C2\"].value)\n print(sheet1[\"D2\"].value)\n print(\"====================\")\n print(sheet1.cell(row=2, column=1).value)\n print(sheet1.cell(row=2, column=2).value)\n print(sheet1.cell(row=2, column=3).value)\n print(sheet1.cell(row=2, column=4).value)\n\"\"\"\n# 最大列\nmax_col_number = sheet1.max_column\n# 最大行\nmax_row_number = sheet1.max_row\n# ctrl + D 约定\n# print(max_col_number)\nprint(\"max_row_number:\" + str(max_row_number))\n\n# 最多读取多少列\nmax_read_count = 4\n\ntotalDataSave = []\nfor i in range(2, max_row_number + 1):\n rowData = []\n tableData = []\n for j in range(1, max_col_number + 1):\n rowValue = sheet1.cell(row=i, column=j).value\n # 只存前面4列的值\n if j <= max_read_count and rowValue is not None:\n rowData.append(rowValue)\n # 根据表的数量 进行复制 表名\n if j > max_read_count and rowValue is not None:\n tableData.append(rowValue)\n\n for vv in tableData:\n # 复制rowData 到 newRowData\n newRowData = rowData[:]\n newRowData.append(vv)\n totalDataSave.append(newRowData)\n print(newRowData)\n\n # 当没有表的时候,也要存在一行\n if tableData.__len__() == 0:\n newRowData = rowData[:]\n totalDataSave.append(newRowData)\n print(newRowData)\n\nprint(\"处理成功了,开始保存,将处理好的数据保存至新的excel\")\n# 新建excel\nwb = xl.Workbook()\n# 获取当前显示的sheet\nnewSheet = wb.active\n# 将数据 保存进 sheet\ntitle_list = [\"一级域名\", \"二级域名\", \"三级域名\", \"四级域名\", \"表名\"]\nnewSheet.append(title_list)\nfor hh in totalDataSave:\n newSheet.append(hh)\n# 保存\nwb.save(r\"D:\\work\\ok_excel.xlsx\")\nprint(\"保存成功\")\n" }, { "alpha_fraction": 0.6111111044883728, "alphanum_fraction": 0.6111111044883728, "avg_line_length": 11.333333015441895, "blob_id": "8a8a33b57964dc710ebdad16bcd77d3daff19631", "content_id": "2a150b9d3e1080abe7ba7c59a129ae0a64abae34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 40, "license_type": "no_license", "max_line_length": 20, "num_lines": 3, "path": "/process_excel/Test.py", "repo_name": "pobc/Excel_data", "src_encoding": "UTF-8", "text": "a = []\na.append(\"yyyGED发放\")\nprint(a)" } ]
2
HeimirDavid/task-manager
https://github.com/HeimirDavid/task-manager
ad746076de67fd1b149d240ae296a71dd0929575
375081d40dc39a84670cfcb32e0634a2e9aa2811
94b618f716ccbc2064317846713c0a5a0701ab62
refs/heads/master
2023-05-10T06:37:38.920641
2020-03-05T19:51:03
2020-03-05T19:51:03
243,573,284
0
0
null
2020-02-27T17:15:23
2020-03-05T19:51:16
2023-05-01T21:22:21
HTML
[ { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.7762237787246704, "avg_line_length": 46.66666793823242, "blob_id": "439d3d7ac958ceece204ce637bb9207482afbd57", "content_id": "766936b2f854d9348885674de8dd23a5389a7739", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 143, "license_type": "no_license", "max_line_length": 131, "num_lines": 3, "path": "/env.py", "repo_name": "HeimirDavid/task-manager", "src_encoding": "UTF-8", "text": "import os\n\nos.environ[\"MONGO_URI\"] = \"mongodb+srv://root:<password>@myfirstcluster-qce1p.mongodb.net/task_manager?retryWrites=true&w=majority\"\n" } ]
1
appsmatics/udacity
https://github.com/appsmatics/udacity
c6dba6c871e612ed217c240a2785d4cdb8961c30
aeae3c8c1beb4c80ab60e0735deab61483fcf267
dee80b966d142c3ae890cff9dfcfa8c7e2dcf4a9
refs/heads/master
2021-07-21T03:52:28.478141
2017-10-30T11:20:45
2017-10-30T11:20:45
106,370,758
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8125, "alphanum_fraction": 0.8125, "avg_line_length": 15, "blob_id": "84fd557c47ddadc02e5a9838d001cd6ac4ab486e", "content_id": "e49acf0275397431297862ce31f75a6b05b83d34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 32, "license_type": "no_license", "max_line_length": 21, "num_lines": 2, "path": "/README.md", "repo_name": "appsmatics/udacity", "src_encoding": "UTF-8", "text": "# udacity\nLearning from udacity\n" }, { "alpha_fraction": 0.6859229803085327, "alphanum_fraction": 0.6958831548690796, "avg_line_length": 28.47058868408203, "blob_id": "b311b0aa3ded69646ccb16e61b33b188245cb9b3", "content_id": "be17ed0b921b9e9cd3d2e17a96f846787ca7dbca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1506, "license_type": "no_license", "max_line_length": 81, "num_lines": 51, "path": "/ud120/ud120-projects/datasets_questions/explore_enron_data.py", "repo_name": "appsmatics/udacity", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n\"\"\" \n Starter code for exploring the Enron dataset (emails + finances);\n loads up the dataset (pickled dict of dicts).\n\n The dataset has the form:\n enron_data[\"LASTNAME FIRSTNAME MIDDLEINITIAL\"] = { features_dict }\n\n {features_dict} is a dictionary of features associated with that person.\n You should explore features_dict as part of the mini-project,\n but here's an example to get you started:\n\n enron_data[\"SKILLING JEFFREY K\"][\"bonus\"] = 5600000\n \n\"\"\"\n\nimport pickle\n\nenron_data = pickle.load(open(\"../final_project/final_project_dataset.pkl\", \"r\"))\nprint \"data points=%d\" % len(enron_data)\ncount = 0\nfor person in enron_data:\n\tif enron_data[person][\"poi\"]==True:\n\t\tcount=count+1\n\t#print \"%d\" % len(person_data)\nprint \"Count of pois=%d\" % count\n\nvalid_salary=0\nvalid_email=0;\nno_total_payments=0\nfor person in enron_data:\n\tif enron_data[person]['salary'] != \"NaN\":\n\t\tvalid_salary=valid_salary+1\n\tif enron_data[person]['email_address'] != \"NaN\":\n\t\tvalid_email=valid_email+1\n\tif enron_data[person]['total_payments'] == \"NaN\":\n\t\tno_total_payments=no_total_payments+1\n\t#print \"%s total_payments=%s\" % (person,enron_data[person]['total_payments'])\n\t\t\nprint \"no_total_payments=%d\" % no_total_payments\n\nprint \"valid salary %d\" % valid_salary\nprint \"valid email %d\" % valid_email\n\n\nprint len(enron_data[person])\nprint enron_data['SKILLING JEFFREY K']['total_payments'];\nprint enron_data['FASTOW ANDREW S']['total_payments'];\n\nprint enron_data['LAY KENNETH L'];\n\n\n\n" }, { "alpha_fraction": 0.6247190833091736, "alphanum_fraction": 0.6314606666564941, "avg_line_length": 28, "blob_id": "02d28427d563db9a793f7b7989b70da829b72cef", "content_id": "e965c30c00024c7c8713b9d3c0d2d9782654258c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1335, "license_type": "no_license", "max_line_length": 66, "num_lines": 46, "path": "/nd013/P5/CarND-Vehicle-Detection/heatmap.py", "repo_name": "appsmatics/udacity", "src_encoding": "UTF-8", "text": "import numpy as np\n\n# class to maintain a list and accumulation of N recent heatmaps\n# A threshold can also be applied to the accumulated heatmap\n# i.e. heatmap[:,:] < threshold = 0\n\nclass HeatMapAccumulator:\n\n max_hetamaps=0\n threshold=0\n heatmap_array = []\n heatmap_sum = None\n\n def __init__(self, size=10, threshold=5):\n self.max_hetamaps = size\n self.threshold = threshold\n self.heatmap_array = []\n self.heatmap_sum = None\n\n\n # bounded to size max_hetamaps\n def add_heatmap (self, heatmap):\n\n if (len(self.heatmap_array) == 0):\n self.heatmap_sum = np.copy(heatmap)\n self.heatmap_array.append(heatmap)\n return\n\n if (len(self.heatmap_array) == self.max_hetamaps):\n heat = self.heatmap_array.pop(0)\n self.heatmap_sum = np.subtract(self.heatmap_sum, heat)\n\n self.heatmap_sum = np.add(self.heatmap_sum, heatmap)\n self.heatmap_array.append(heatmap)\n\n\n def get_summed_heat_map_after_threshold (self):\n heatmap = np.copy(self.heatmap_sum)\n return self.apply_threshold(heatmap, self.threshold)\n\n\n def apply_threshold(self, heatmap, threshold):\n # Zero out pixels below the threshold\n heatmap[heatmap < threshold] = 0\n # Return thresholded map\n return heatmap\n\n" }, { "alpha_fraction": 0.7440147399902344, "alphanum_fraction": 0.7483118772506714, "avg_line_length": 26.559322357177734, "blob_id": "d4c374f350dbb0bffd54706427afd8324fe9cf30", "content_id": "f88212c8824456f1c65fe2762348ee33d6b3b4c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1629, "license_type": "no_license", "max_line_length": 81, "num_lines": 59, "path": "/ud120/ud120-projects/evaluation/evaluate_poi_identifier.py", "repo_name": "appsmatics/udacity", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n\n\"\"\"\n Starter code for the evaluation mini-project.\n Start by copying your trained/tested POI identifier from\n that which you built in the validation mini-project.\n\n This is the second step toward building your POI identifier!\n\n Start by loading/formatting the data...\n\"\"\"\n\nimport pickle\nimport sys\nsys.path.append(\"../tools/\")\nfrom feature_format import featureFormat, targetFeatureSplit\n\ndata_dict = pickle.load(open(\"../final_project/final_project_dataset.pkl\", \"r\") )\n\n### add more features to features_list!\nfeatures_list = [\"poi\", \"salary\"]\n\ndata = featureFormat(data_dict, features_list)\nlabels, features = targetFeatureSplit(data)\n\n\n\n### your code goes here \n### it's all yours from here forward!\nfrom sklearn.model_selection import train_test_split\ndata_split = train_test_split(features, labels, test_size=0.3, random_state=42)\nfeatures_train, features_test, labels_train, labels_test = data_split\n\n#print (features_train)\n#print (features_test)\n\nfrom sklearn import tree\nclf = tree.DecisionTreeClassifier()\nclf.fit(features_train, labels_train)\npred = clf.predict(features_test)\n\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\n\nacc = accuracy_score(labels_test, pred)\nprint \"Accuracy is %f\" % acc\n\nprecision = precision_score(labels_test, pred)\nprint \"Precision is %f\" % precision\n\nrecall = recall_score(labels_test, pred)\nprint \"Recall is %f\" % recall\n\n#accuracy of zeros predicted for all\nzeros = [0]*29\nacc = accuracy_score(labels_test, zeros)\nprint \"Accuracy for all zeros predicted is %f\" % acc\n\n\n\n" }, { "alpha_fraction": 0.6207584738731384, "alphanum_fraction": 0.6467065811157227, "avg_line_length": 26.814815521240234, "blob_id": "560c345c87f41e25b8fe53cae1c1fdd5dc8e679d", "content_id": "4b85ff3f13abc71987dbfed651c9c5bb26c73335", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1503, "license_type": "no_license", "max_line_length": 76, "num_lines": 54, "path": "/ud120/ud120-projects/svm/svm_author_id.py", "repo_name": "appsmatics/udacity", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n\"\"\" \n This is the code to accompany the Lesson 2 (SVM) mini-project.\n\n Use a SVM to identify emails from the Enron corpus by their authors: \n Sara has label 0\n Chris has label 1\n\"\"\"\n \nimport sys\nfrom time import time\nsys.path.append(\"../tools/\")\nfrom email_preprocess import preprocess\n\n\n### features_train and features_test are the features for the training\n### and testing datasets, respectively\n### labels_train and labels_test are the corresponding item labels\nfeatures_train, features_test, labels_train, labels_test = preprocess()\n\n\n\n\n#########################################################\n### your code goes here ###\n\n#########################################################\n\n#paring down the data\n#print \"reducing training data to 1/100th\"\n#features_train = features_train[:len(features_train)/100] \n#labels_train = labels_train[:len(labels_train)/100] \nprint \"training set size=%d\" % len(features_train)\n\nfrom sklearn.svm import SVC\nC=10000.0\nkernel=\"rbf\"\nprint \"kernel=%s, C=%f\" % (kernel, C)\nclf = SVC(C=C, kernel=kernel)\nt1 = time()\nclf.fit(features_train, labels_train)\nt2=time()\npred = clf.predict(features_test)\nt3=time()\nprint \"SVM fit time is %f\" % (t2-t1) \nprint \"SVM predict time is %f\" % (t3-t2) \n\nfrom sklearn.metrics import accuracy_score\naccuracy = accuracy_score(labels_test, pred)\nprint \"Accuracy is %f\" % accuracy\n\nprint \"pred[10]=%d, [26]=%d, [50]=%d\" % (pred[10], pred[26], pred[50])\nprint \"predications for Chris(1)=%d\" % sum(pred)\n\n" }, { "alpha_fraction": 0.5893349647521973, "alphanum_fraction": 0.6056497693061829, "avg_line_length": 39.67280960083008, "blob_id": "d3eec4481a6f8b35fe97723af63bcc305446e64f", "content_id": "e63d8a99ac1d3e23e40ce94f103883c03e25501b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26479, "license_type": "no_license", "max_line_length": 144, "num_lines": 651, "path": "/nd013/P5/CarND-Vehicle-Detection/find_car.py", "repo_name": "appsmatics/udacity", "src_encoding": "UTF-8", "text": "### Various module imports ###\nimport numpy as np\nimport cv2\nimport glob\nimport time\n\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom skimage.feature import hog\nfrom sklearn.svm import LinearSVC\n\n\n# Some constants\nCOLOR_RED=(255,0,0)\nCOLOR_GREEN=(0,255,0)\nCOLOR_BLUE=(0,0,255)\nCOLOR_ORANGE=(255,127,0)\nCOLOR_PURPLE=(127,0,255)\nPICKLE_FILE='training_data/saved_model.p'\n\n\n\n####### Globals ########\n# reference to the model and scaler needed after training.\n# these are read in from the trained model that is saved as a pickle file\nsvc=None\nX_scaler=None\n\n\n#One place to define the various parameters\ndef get_the_parameters():\n color_space = 'YCrCb' # Can be RGB, HSV, LUV, HLS, YUV, YCrCb\n orient = 9 # HOG orientations\n pix_per_cell = 8 # HOG pixels per cell\n cell_per_block = 2 # HOG cells per block\n hog_channel = \"ALL\" # Can be 0, 1, 2, or \"ALL\"\n spatial_size = (16, 16) # Spatial binning dimensions\n hist_bins = 32 # Number of histogram bins\n spatial_feat = True # Spatial features on or off\n hist_feat = True # Histogram features on or off\n hog_feat = True # HOG features on or off\n return (color_space,\n orient, pix_per_cell, cell_per_block, hog_channel\n ,spatial_size, hist_bins\n , spatial_feat, hist_feat, hog_feat)\n\n\n#Find all the car and not_car image names from the training_data folder\ndef car_notcar_image_names():\n car_images = ['training_data/vehicles/GTI_Far/*.png',\n 'training_data/vehicles/GTI_Left/*.png',\n 'training_data/vehicles/GTI_Right/*.png',\n 'training_data/vehicles/GTI_MiddleClose/*.png',\n 'training_data/vehicles/KITTI_extracted/*.png',\n ]\n not_car_images = ['training_data/non-vehicles/Extras/*.png',\n 'training_data/non-vehicles/GTI/*.png',\n 'training_data/non-vehicles/hard_neg/*.png'\n ]\n\n cars = []\n notcars = []\n\n for car_image in car_images:\n for image in glob.glob(car_image):\n cars.append(image)\n\n for not_car_image in not_car_images:\n for image in glob.glob(not_car_image):\n notcars.append(image)\n\n return (cars, notcars)\n\n\n# Get the HOG features for this channel of image\n# Note supplied image is 2d for one color channel\ndef get_hog_features(img, orient, pix_per_cell, cell_per_block,\n vis=False, feature_vec=True):\n # Call with two outputs if vis==True\n if vis == True:\n features, hog_image = hog(img, orientations=orient,\n pixels_per_cell=(pix_per_cell, pix_per_cell),\n cells_per_block=(cell_per_block, cell_per_block),\n transform_sqrt=True,\n visualise=True, feature_vector=feature_vec)\n return features, hog_image\n # Otherwise call with one output\n else:\n features = hog(img, orientations=orient,\n pixels_per_cell=(pix_per_cell, pix_per_cell),\n cells_per_block=(cell_per_block, cell_per_block),\n transform_sqrt=True,\n visualise=False, feature_vector=feature_vec)\n return features\n\n\n# Define a function to compute binned color features\ndef bin_spatial(img, size=(32, 32)):\n # Use cv2.resize().ravel() to create the feature vector\n features = cv2.resize(img, size).ravel()\n # Return the feature vector\n return features\n\n\n# Define a function to compute color histogram features\n# NEED TO CHANGE bins_range if reading .png files with mpimg!\ndef color_hist(img, nbins=32, bins_range=(0, 1)):\n # Compute the histogram of the color channels separately\n channel1_hist = np.histogram(img[:,:,0], bins=nbins, range=bins_range)\n channel2_hist = np.histogram(img[:,:,1], bins=nbins, range=bins_range)\n channel3_hist = np.histogram(img[:,:,2], bins=nbins, range=bins_range)\n # Concatenate the histograms into a single feature vector\n hist_features = np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0]))\n # Return the individual histograms, bin_centers and feature vector\n return hist_features\n\n\n\n# return a features array of concatenated individual features.\n# Note the features array is not normalised\ndef single_img_features(img, color_space='RGB',\n spatial_feat=True, spatial_size=(32, 32),\n hist_feat=True, hist_bins=32,\n hog_feat=True, orient=9, pix_per_cell=8, cell_per_block=2, hog_channel=0):\n #1) Define an empty list to receive features\n img_features = []\n #2) Apply color conversion if other than 'RGB'\n if color_space != 'RGB':\n if color_space == 'HSV':\n feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n elif color_space == 'LUV':\n feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2LUV)\n elif color_space == 'HLS':\n feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n elif color_space == 'YUV':\n feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2YUV)\n elif color_space == 'YCrCb':\n feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)\n else: feature_image = np.copy(img)\n #3) Compute spatial features if flag is set\n if spatial_feat == True:\n spatial_features = bin_spatial(feature_image, size=spatial_size)\n #4) Append features to list\n img_features.append(spatial_features)\n #5) Compute histogram features if flag is set\n if hist_feat == True:\n hist_features = color_hist(feature_image, nbins=hist_bins)\n #6) Append features to list\n img_features.append(hist_features)\n #7) Compute HOG features if flag is set\n if hog_feat == True:\n if hog_channel == 'ALL':\n hog_features = []\n for channel in range(feature_image.shape[2]):\n hog_features.extend(get_hog_features(feature_image[:,:,channel],\n orient, pix_per_cell, cell_per_block,\n vis=False, feature_vec=True))\n else:\n hog_features = get_hog_features(feature_image[:,:,hog_channel], orient,\n pix_per_cell, cell_per_block, vis=False, feature_vec=True)\n #8) Append features to list\n img_features.append(hog_features)\n\n #9) Return concatenated array of features\n concat = np.concatenate(img_features)\n return concat\n\n\n\n\n# Define a function to extract features from a list of images\n# Have this function call bin_spatial() and color_hist()\ndef extract_features_all_imagenames(imgs, color_space='RGB', spatial_size=(32, 32),\n hist_bins=32, orient=9,\n pix_per_cell=8, cell_per_block=2, hog_channel=0,\n spatial_feat=True, hist_feat=True, hog_feat=True):\n # Create a list to append feature vectors to\n features = []\n # Iterate through the list of images\n for file in imgs:\n file_features = []\n # Read in each one by one\n image = mpimg.imread(file)\n file_features = single_img_features(image, color_space=color_space,\n spatial_size=spatial_size, hist_bins=hist_bins,\n orient=orient, pix_per_cell=pix_per_cell,\n cell_per_block=cell_per_block,\n hog_channel=hog_channel, spatial_feat=spatial_feat,\n hist_feat=hist_feat, hog_feat=hog_feat)\n features.append(file_features)\n # Return list of feature vectors\n return features\n\n\n#Perform the training on the car and not_car images.\n#Take a random sample of 0.80% of the data for the training\n#From both the car and not_car images\ndef train_data_set_and_generate_model():\n import pickle\n\n (cars,notcars) = car_notcar_image_names()\n print(\"Car images: \", len(cars),\" / Non-car images: \",len(notcars))\n\n # Reduce the sample size because\n # The quiz evaluator times out after 13s of CPU time\n # sample_size = 3000\n # cars = cars[0:sample_size]\n # notcars = notcars[0:sample_size]\n\n (color_space,\n orient, pix_per_cell, cell_per_block, hog_channel\n , spatial_size, hist_bins\n , spatial_feat, hist_feat, hog_feat) = get_the_parameters()\n\n #Get a random state\n rand_state = np.random.randint(0, 100)\n\n cars_train, cars_test, _, _ = train_test_split(cars, cars, test_size=0.2, random_state=rand_state)\n not_cars_train, not_cars_test, _, _ = train_test_split(notcars, notcars, test_size=0.25, random_state=rand_state)\n\n car_features = extract_features_all_imagenames (cars_train, color_space=color_space,\n spatial_size=spatial_size, hist_bins=hist_bins,\n orient=orient, pix_per_cell=pix_per_cell,\n cell_per_block=cell_per_block,\n hog_channel=hog_channel, spatial_feat=spatial_feat,\n hist_feat=hist_feat, hog_feat=hog_feat)\n notcar_features = extract_features_all_imagenames (not_cars_train, color_space=color_space,\n spatial_size=spatial_size, hist_bins=hist_bins,\n orient=orient, pix_per_cell=pix_per_cell,\n cell_per_block=cell_per_block,\n hog_channel=hog_channel, spatial_feat=spatial_feat,\n hist_feat=hist_feat, hog_feat=hog_feat)\n\n #combine the features for car and not_car images\n X_train_us = np.vstack((car_features, notcar_features)).astype(np.float64)\n # Fit a per-column scaler\n X_scaler = StandardScaler().fit(X_train_us)\n # Apply the scaler to X\n X_train = X_scaler.transform(X_train_us)\n\n # Define the labels vector\n y_train = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features))))\n\n\n #Repeat for test\n car_features = extract_features_all_imagenames(cars_test, color_space=color_space,\n spatial_size=spatial_size, hist_bins=hist_bins,\n orient=orient, pix_per_cell=pix_per_cell,\n cell_per_block=cell_per_block,\n hog_channel=hog_channel, spatial_feat=spatial_feat,\n hist_feat=hist_feat, hog_feat=hog_feat)\n notcar_features = extract_features_all_imagenames(not_cars_test, color_space=color_space,\n spatial_size=spatial_size, hist_bins=hist_bins,\n orient=orient, pix_per_cell=pix_per_cell,\n cell_per_block=cell_per_block,\n hog_channel=hog_channel, spatial_feat=spatial_feat,\n hist_feat=hist_feat, hog_feat=hog_feat)\n\n # combine the features for car and not_car images\n X_test_us = np.vstack((car_features, notcar_features)).astype(np.float64)\n # Fit a per-column scaler\n # Apply the scaler to X\n X_test = X_scaler.transform(X_test_us)\n\n # Define the labels vector\n y_test = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features))))\n\n\n # Use a linear SVC\n svc = LinearSVC()\n # Check the training time for the SVC\n t1 = time.time()\n svc.fit(X_train, y_train)\n t2 = time.time()\n print(round(t2 - t1, 2), 'Seconds to train SVC...')\n # Check the score of the SVC\n print('Test Accuracy of SVC = ', round(svc.score(X_test, y_test), 4))\n # Check the prediction time for a single sample\n t3 = time.time()\n print(\"Dumping model to pickle file: \", PICKLE_FILE)\n file = open(PICKLE_FILE, \"wb\")\n pickle.dump((svc,X_scaler), file)\n return (svc, X_scaler)\n\n\n\ndef train_data_set_and_generate_model_old ():\n import pickle\n\n (cars,notcars) = car_notcar_image_names()\n print(\"Car images: \", len(cars),\" / Non-car images: \",len(notcars))\n\n # Reduce the sample size because\n # The quiz evaluator times out after 13s of CPU time\n # sample_size = 3000\n # cars = cars[0:sample_size]\n # notcars = notcars[0:sample_size]\n\n (color_space,\n orient, pix_per_cell, cell_per_block, hog_channel\n , spatial_size, hist_bins\n , spatial_feat, hist_feat, hog_feat) = get_the_parameters()\n\n car_features = extract_features_all_imagenames (cars, color_space=color_space,\n spatial_size=spatial_size, hist_bins=hist_bins,\n orient=orient, pix_per_cell=pix_per_cell,\n cell_per_block=cell_per_block,\n hog_channel=hog_channel, spatial_feat=spatial_feat,\n hist_feat=hist_feat, hog_feat=hog_feat)\n notcar_features = extract_features_all_imagenames (notcars, color_space=color_space,\n spatial_size=spatial_size, hist_bins=hist_bins,\n orient=orient, pix_per_cell=pix_per_cell,\n cell_per_block=cell_per_block,\n hog_channel=hog_channel, spatial_feat=spatial_feat,\n hist_feat=hist_feat, hog_feat=hog_feat)\n\n #combine the features for car and not_car images\n X = np.vstack((car_features, notcar_features)).astype(np.float64)\n # Fit a per-column scaler\n X_scaler = StandardScaler().fit(X)\n # Apply the scaler to X\n scaled_X = X_scaler.transform(X)\n\n # Define the labels vector\n y = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features))))\n\n # Split up data into randomized training and test sets\n rand_state = np.random.randint(0, 100)\n X_train, X_test, y_train, y_test = train_test_split(\n scaled_X, y, test_size=0.2, random_state=rand_state)\n\n print('Using:', orient, 'orientations', pix_per_cell,\n 'pixels per cell and', cell_per_block, 'cells per block')\n print('Feature vector length:', len(X_train[0]))\n # Use a linear SVC\n svc = LinearSVC()\n # Check the training time for the SVC\n t1 = time.time()\n svc.fit(X_train, y_train)\n t2 = time.time()\n print(round(t2 - t1, 2), 'Seconds to train SVC...')\n # Check the score of the SVC\n print('Test Accuracy of SVC = ', round(svc.score(X_test, y_test), 4))\n # Check the prediction time for a single sample\n t3 = time.time()\n print(\"Dumping model to pickle file: \", PICKLE_FILE)\n file = open(PICKLE_FILE, \"wb\")\n pickle.dump((svc,X_scaler), file)\n return (svc, X_scaler)\n\n\n\n#Return all the sliding windows given the corner coordinate and the window size.\ndef get_sliding_windows_for_size (img, x_start_stop=[None, None], y_start_stop=[None, None],\n xy_window=(64, 64), xy_overlap=(0.5, 0.5)):\n # If x and/or y start/stop positions not defined, set to image size\n if x_start_stop[0] == None:\n x_start_stop[0] = 0\n if x_start_stop[1] == None:\n x_start_stop[1] = img.shape[1]\n if y_start_stop[0] == None:\n y_start_stop[0] = 0\n if y_start_stop[1] == None:\n y_start_stop[1] = img.shape[0]\n # Compute the span of the region to be searched\n xspan = x_start_stop[1] - x_start_stop[0]\n yspan = y_start_stop[1] - y_start_stop[0]\n # Compute the number of pixels per step in x/y\n nx_pix_per_step = np.int(xy_window[0]*(1 - xy_overlap[0]))\n ny_pix_per_step = np.int(xy_window[1]*(1 - xy_overlap[1]))\n # Compute the number of windows in x/y\n nx_buffer = np.int(xy_window[0]*(xy_overlap[0]))\n ny_buffer = np.int(xy_window[1]*(xy_overlap[1]))\n nx_windows = np.int((xspan-nx_buffer)/nx_pix_per_step)\n ny_windows = np.int((yspan-ny_buffer)/ny_pix_per_step)\n # Initialize a list to append window positions to\n window_list = []\n # Loop through finding x and y window positions\n # Note: you could vectorize this step, but in practice\n # you'll be considering windows one by one with your\n # classifier, so looping makes sense\n for ys in range(ny_windows):\n for xs in range(nx_windows):\n # Calculate window position\n startx = xs*nx_pix_per_step + x_start_stop[0]\n endx = startx + xy_window[0]\n starty = ys*ny_pix_per_step + y_start_stop[0]\n endy = starty + xy_window[1]\n # Append window position to list\n window_list.append(((startx, starty), (endx, endy)))\n # Return the list of windows\n return window_list\n\n\n\n# Given a set of Sliding windows identify the ones that\n# the model predicts as containing a car\n# Return the windows that have been identified as containing a car\ndef search_windows_for_match (img, windows, clf, scaler, color_space='RGB',\n spatial_size=(32, 32), hist_bins=32,\n hist_range=(0, 256), orient=9,\n pix_per_cell=8, cell_per_block=2,\n hog_channel=0, spatial_feat=True,\n hist_feat=True, hog_feat=True):\n\n #1) Create an empty list to receive positive detection windows\n on_windows = []\n #2) Iterate over all windows in the list\n for window in windows:\n #3) Extract the test window from original image\n test_img = cv2.resize(img[window[0][1]:window[1][1], window[0][0]:window[1][0]], (64, 64))\n #4) Extract features for that window using single_img_features()\n features = single_img_features(test_img, color_space=color_space,\n spatial_size=spatial_size, hist_bins=hist_bins,\n orient=orient, pix_per_cell=pix_per_cell,\n cell_per_block=cell_per_block,\n hog_channel=hog_channel, spatial_feat=spatial_feat,\n hist_feat=hist_feat, hog_feat=hog_feat)\n #5) Scale extracted features to be fed to classifier\n test_features = scaler.transform(np.array(features).reshape(1, -1))\n #6) Predict using your classifier\n prediction = clf.predict(test_features)\n #7) If positive (prediction == 1) then save the window\n if prediction == 1:\n on_windows.append(window)\n #8) Return windows for positive detections\n return on_windows\n\n\n\n# Run the sliding windows for multiple window sizes and start_stop positions\n# And return all the windows that identify as having a car in them\n# Multiple overlapping windows will be returned by this function.\ndef multi_sliding_windows(image):\n sliding_window_params = \\\n [\n {'x_start_stop': [600, 1100], 'y_start_stop': [384, 496], 'xy_overlap': (0.8, 0.8), 'xy_window': (80, 80), 'color': COLOR_BLUE},\n {'x_start_stop': [600, 1180], 'y_start_stop': [384, 554], 'xy_overlap': (0.8, 0.8), 'xy_window': (128, 128), 'color': COLOR_GREEN},\n {'x_start_stop': [580, 1280], 'y_start_stop': [440, 640], 'xy_overlap': (0.8, 0.8), 'xy_window': (160, 160), 'color': COLOR_ORANGE},\n {'x_start_stop': [520, 1280], 'y_start_stop': [460, 708], 'xy_overlap': (0.8, 0.8), 'xy_window': (192, 192), 'color': COLOR_PURPLE}\n ]\n\n (color_space,\n orient, pix_per_cell, cell_per_block, hog_channel\n , spatial_size, hist_bins\n , spatial_feat, hist_feat, hog_feat) = get_the_parameters()\n\n hot_windows_accum=[]\n for param in sliding_window_params:\n x_start_stop= param['x_start_stop']\n y_start_stop = param['y_start_stop']\n xy_overlap=param['xy_overlap']\n xy_window=param['xy_window']\n # if (xy_window[0] != 64):\n # continue\n windows = get_sliding_windows_for_size (image, x_start_stop=x_start_stop, y_start_stop=y_start_stop,\n xy_window=xy_window, xy_overlap=xy_overlap)\n\n hot_windows = search_windows_for_match (image, windows, svc, X_scaler, color_space=color_space,\n spatial_size=spatial_size, hist_bins=hist_bins,\n orient=orient, pix_per_cell=pix_per_cell,\n cell_per_block=cell_per_block,\n hog_channel=hog_channel, spatial_feat=spatial_feat,\n hist_feat=hist_feat, hog_feat=hog_feat)\n hot_windows_accum.extend(hot_windows)\n\n return hot_windows_accum\n\n\ndef debug_show_multiwindows (image, hot_windows, color=(0,0,255), line_thickness=6):\n draw_image = np.copy(image)\n window_img = draw_boxes(draw_image, hot_windows, color=color, line_thickness=4)\n plt.imshow(window_img)\n plt.show()\n\n#######################################################\n\n#Utility function to draw colored outline boxes on the image\ndef draw_boxes(img, bboxes, color=(0, 0, 255), line_thickness=6):\n # Iterate through the bounding boxes\n for bbox in bboxes:\n # Draw a rectangle given bbox coordinates\n cv2.rectangle(img, bbox[0], bbox[1], color, line_thickness)\n # Return the image copy with boxes drawn\n return img\n\n\ndef add_heat(heatmap, bbox_list):\n # Iterate through list of bboxes\n for box in bbox_list:\n # Add += 1 for all pixels inside each bbox\n # Assuming each \"box\" takes the form ((x1, y1), (x2, y2))\n heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1\n\n # Return updated heatmap\n return heatmap # Iterate through list of bboxes\n\n\ndef apply_threshold(heatmap, threshold):\n # Zero out pixels below the threshold\n heatmap[heatmap < threshold] = 0\n # Return thresholded map\n return heatmap\n\n\n\ndef draw_labeled_bboxes(img, labels):\n # Iterate through all detected cars\n for car_number in range(1, labels[1] + 1):\n # Find pixels with each car_number label value\n nonzero = (labels[0] == car_number).nonzero()\n # Identify x and y values of those pixels\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n # Define a bounding box based on min/max x and y\n bbox = ((np.min(nonzerox), np.min(nonzeroy)), (np.max(nonzerox), np.max(nonzeroy)))\n # Draw the box on the image\n cv2.rectangle(img, bbox[0], bbox[1], (0, 0, 255), 6)\n # Return the image\n return img\n\n\n\n#define a global here\nimport heatmap\nheatmap_accumulator = None\n\ndef draw_heat_map(image, box_list):\n from scipy.ndimage.measurements import label\n # Read in image similar to one shown above\n heat = np.zeros_like(image[:, :, 0]).astype(np.float)\n\n # Add heat to each box in box list\n heat = add_heat(heat, box_list)\n\n heatmap_accumulator.add_heatmap(heat)\n\n # Apply threshold to help remove false positives\n #heat = apply_threshold(heat, 1)\n\n # Visualize the heatmap when displaying\n #heatmap = np.clip(heat, 0, 255)\n\n heatmapsum=heatmap_accumulator.get_summed_heat_map_after_threshold()\n heatmap=heatmapsum\n # Find final boxes from heatmap using label function\n labels = label(heatmap)\n labelled_img = draw_labeled_bboxes(np.copy(image), labels)\n return (labelled_img, heatmap)\n\n\n\n\n\ndef initialize_model():\n import os\n import pickle\n if os.path.isfile(PICKLE_FILE):\n global svc\n global X_scaler\n # load the classifier later\n print(\"Loading saved model from pickle data\")\n file = open(PICKLE_FILE, \"rb\")\n svc, X_scaler = pickle.load(file)\n else:\n print(\"No saved model found .. run training\")\n svc, X_scaler = train_data_set_and_generate_model()\n\n\n\n##################################################\ndef process_jpeg_image(orig_image):\n\n # Uncomment the following line if you extracted training\n # data from .png images (scaled 0 to 1 by mpimg) and the\n # image you are searching is a .jpg (scaled 0 to 255)\n image = orig_image.astype(np.float32)/255\n\n hot_windows_accum=multi_sliding_windows(image)\n\n # box_list = pickle.load(open(\"bbox_pickle.p\", \"rb\"))\n window_img = draw_boxes(np.copy(orig_image), hot_windows_accum, color=COLOR_BLUE, line_thickness=4)\n\n box_list = hot_windows_accum\n\n labelled_image, heat_map_image = draw_heat_map(np.copy(orig_image), box_list)\n return window_img, heat_map_image, labelled_image\n\n\ndef process_video_image(orig_image):\n window_img, heat_map_image, labelled_image = process_jpeg_image(orig_image)\n return labelled_image\n\n\nfrom moviepy.editor import VideoFileClip\ndef createVideo():\n video_fname = 'test_videos/project_video.mp4'\n video_outfile = 'test_videos_output/project_video.mp4'\n\n # video_fname = 'test_videos/test_video.mp4'\n # video_outfile = 'test_videos_output/test_video.mp4'\n\n clip1 = VideoFileClip(video_fname)\n\n processed_clip = clip1.fl_image(process_video_image) # NOTE: this function expects color images!\n processed_clip.write_videofile(video_outfile, audio=False)\n\n\ndef test_image(image_name='test_images/test1.jpg'):\n\n #for images create a new one each image (ie no accumulation)\n global heatmap_accumulator\n heatmap_accumulator = heatmap.HeatMapAccumulator(size=1, threshold=1)\n\n\n image = mpimg.imread(image_name)\n window_img, heat_map_image, labelled_image = process_jpeg_image(image)\n fig = plt.figure(figsize=(12,6))\n plt.subplot(131)\n plt.imshow(window_img)\n plt.title('Detected')\n plt.subplot(132)\n plt.imshow(heat_map_image, cmap='hot')\n plt.title('Heat Map')\n plt.subplot(133)\n plt.imshow(labelled_image)\n plt.title('Labelled')\n fig.tight_layout()\n plt.show()\n\n\ndef test_images():\n image_names=['test_images/test1.jpg', 'test_images/test2.jpg', 'test_images/test3.jpg', 'test_images/test4.jpg'\n ,'test_images/test5.jpg','test_images/test6.jpg']\n #image_names=['test_images/test1.jpg']\n\n for image_name in image_names:\n test_image(image_name)\n\n\n\ninitialize_model()\n\n#test_images()\n\n#For Video need only 1 acculumator for all frames\nheatmap_accumulator = heatmap.HeatMapAccumulator(size=28, threshold=24)\ncreateVideo()\n\n" } ]
6
sharanjitsandhu/Data-Structures
https://github.com/sharanjitsandhu/Data-Structures
ad7ee2e18cc095b34fbf473bf87802276575979a
4b7e15fab2be42ae9e7e2a968c7bba0e4f76a507
26cf74566092973fed8a3b3eba3a993b61859c52
refs/heads/master
2022-02-12T10:23:21.701079
2019-07-26T00:17:28
2019-07-26T00:17:28
198,285,175
0
0
null
2019-07-22T18:59:30
2019-07-22T18:59:33
2019-07-26T00:17:28
Python
[ { "alpha_fraction": 0.5449790954589844, "alphanum_fraction": 0.5460250973701477, "avg_line_length": 27.117647171020508, "blob_id": "692d82e5113988832a501208061d2f3d4ed1dc4f", "content_id": "36057ee3edb98de2077ec931ac11145a836bf180", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1912, "license_type": "no_license", "max_line_length": 84, "num_lines": 68, "path": "/queue/queue.py", "repo_name": "sharanjitsandhu/Data-Structures", "src_encoding": "UTF-8", "text": "class Node:\n\n def __init__(self, data=None):\n '''initialize node with data and next pointer'''\n self.data = data\n self.next = None\n\n\nclass Queue:\n\n def __init__(self):\n '''initialize queue with head and tail'''\n print(\"Queue created\")\n self.head = None\n self.tail = None\n\n def enqueue(self, item):\n '''append item to the tail of the queue'''\n if not isinstance(item, Node):\n item = Node(item)\n print(f\"Appending {item.data} to the tail of the Queue\")\n if self.is_empty():\n self.head = item\n else:\n self.tail.next = item\n self.tail = item\n\n def dequeue(self):\n '''remove and return the node at head of the queue'''\n if not self.is_empty():\n print(f\"Removing node at head of the Queue\")\n curr = self.head\n self.head = self.head.next\n curr.next = None\n return curr.data\n else:\n return \"Queue is empty\"\n\n def is_empty(self):\n '''return True if queue is empty, else return false'''\n return self.head == None\n\n # def len(self):\n # '''len returns the number of items in the queue'''\n # self.size\n\n# class Queue:\n# def __init__(self):\n# self.size = 0\n# # what data structure should we\n# # use to store queue elements?\n# self.storage = []\n\n# def enqueue(self, item):\n# '''enqueue should add an item to the back of the queue'''\n# return self.storage.append(item)\n\n# def dequeue(self):\n# '''dequeue should remove and return an item from the front of the queue'''\n# if self.storage:\n# return self.storage.pop(0)\n\n# def len(self):\n# '''len returns the number of items in the queue'''\n# return len(self.storage)\n\n\n# ''' adding and removing item using Lists '''\n" }, { "alpha_fraction": 0.5734997987747192, "alphanum_fraction": 0.5751107335090637, "avg_line_length": 31.671052932739258, "blob_id": "48ec4a90d6985c40cb2c72415ac2c3d3d9a7f726", "content_id": "15781a60dc74a6ffa09756abdf67b9da9e777a30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2483, "license_type": "no_license", "max_line_length": 77, "num_lines": 76, "path": "/binary_search_tree/binary_search_tree.py", "repo_name": "sharanjitsandhu/Data-Structures", "src_encoding": "UTF-8", "text": "class BinarySearchTreeNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n# 'insert' adds the input value to the binary search tree,\n# adhering to the rules of the ordering of elements in a binary search tree.\n def insert(self, value):\n if value >= self.value:\n if self.right:\n self.right.insert(value)\n else:\n self.right = BinarySearchTreeNode(value)\n elif value < self.value:\n if self.left:\n self.left.insert(value)\n else:\n self.left = BinarySearchTreeNode(value)\n\n # def insert(self, value):\n # if value < self.value:\n # if not self.left:\n # self.left = BinarySearchTreeNode(value)\n # else:\n # # recursive to keep going until we find an empty spot\n # self.left.insert(value)\n\n # else:\n # if not self.right:\n # self.right = BinarySearchTreeNode(value)\n # else:\n # self.right.insert(value)\n\n# 'contains' searches the binary search tree for the input value,\n# returning a boolean indicating whether the value exists in the tree or not.\n def contains(self, target):\n if target == self.value:\n return True\n\n if target > self.value:\n if self.right:\n return self.right.contains(target)\n else:\n return False\n elif target < self.value:\n if self.left:\n return self.left.contains(target)\n else:\n return False\n\n# 'get_max' returns the maximum value in the binary search tree.\n def get_max(self):\n if self.right:\n return self.right.get_max()\n else:\n return self.value\n\n# for_each performs a traversal of every node in the tree,\n# executing the passed-in callback function on each tree node value.\n# There is a myriad(a lot) of ways to perform tree traversal;\n# in this case any of them should work.\n# This algo is recursive\n# each time we'll be looking at the sub tree of the main tree.\n def for_each(self, cb):\n # in-order traversal(left, root, right)\n if self.left:\n self.left.for_each(cb)\n cb(self.value)\n if self.right:\n self.right.for_each(cb)\n\n# tree = BinarySearchTreeNode(8)\n# tree.insert(15)\n# tree.insert(6)\n# print(tree.left.value)\n" }, { "alpha_fraction": 0.6020098328590393, "alphanum_fraction": 0.6099556088447571, "avg_line_length": 38.99065399169922, "blob_id": "9bfdea1fbc3fd396e3c1d51b3c0870a5fef6ff40", "content_id": "c32ee2de9cc6b32d7c9fca468c4f631f21b9b7c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4279, "license_type": "no_license", "max_line_length": 110, "num_lines": 107, "path": "/heap/max_heap.py", "repo_name": "sharanjitsandhu/Data-Structures", "src_encoding": "UTF-8", "text": "class Heap:\n def __init__(self):\n self.storage = []\n\n# insert adds the input value into the heap;\n# this method should ensure that the inserted value is in the correct spot in the heap\n def insert(self, value):\n # recieve a piece of value, append it to the end of the heap\n self.storage.append(value)\n # bubble(float) it up to its proper position by calling the _bubble_up function\n # self._bubble_up(len(self.storage)-1)\n return self._bubble_up(self.get_size()-1)\n\n# delete removes and returns the 'topmost' value from the heap;\n# this method needs to ensure that the heap property is maintained after the topmost element has been removed.\n # def delete(self):\n # # 1st possibility: if there are two or more values in the heap\n # # in that case we want to swap the max value to the very end of the heap before we delete(pop)it off\n # # and then we want to sift down(float down) the value that we swapped into the top position\n # # 2nd possibility: if there is only one value in the heap\n # # in this case we can simply pop the top value off the heap and will have the empty heap after that\n # # 3rd possibility: if we trying to delete an empty heap\n # # in which case we just wanna return False\n # if len(self.storage) > 2:\n # self.__swap(1, len(self.storage) - 1)\n # max = self.storage.pop()\n # self._sift_down(1)\n # elif len(self.storage) == 2:\n # max = self.storage.pop()\n # else:\n # max = False\n # return max\n\n def delete(self):\n if self.storage[0]:\n value = self.storage[0]\n if self.get_size() <= 1:\n self.storage = []\n else:\n self.storage[0] = self.storage.pop(self.get_size()-1)\n self._sift_down(0)\n return value\n\n # def __swap(self, i, j):\n # self.storage[i], self.storage[j] = self.storage[j], self.storage[i]\n\n# get_max returns the maximum value in the heap in constant time.\n def get_max(self):\n # checking if we have altleast one value on the heap\n # if we have it return the first value on the heap list\n if self.storage[0]:\n return self.storage[0]\n else:\n # if not simply return False because the heap is empty\n return False\n\n# get_size returns the number of elements stored in the heap.\n def get_size(self):\n return len(self.storage)\n\n\n# _bubble_up moves the element at the specified index \"up\" the heap by swapping it with its parent\n# if the parent's value is less than the value at the specified index.\n\n\n def _bubble_up(self, index):\n # 1st possibility: the index we passed in is the index 0\n # in which case there's no bubbling(floating) to be done\n # it's already at the top\n\n # will start by finding the parent index of the index we're trying to float\n parent = (index - 1) // 2\n # now we wanna check if the index we passed in is just 0\n if index <= 0:\n return\n elif self.storage[index] > self.storage[parent]:\n self.storage[index], self.storage[parent] = self.storage[parent], self.storage[index]\n self._bubble_up(parent)\n\n# _sift_down grabs the indices of this element's children and determines which child has a larger value.\n# If the larger child's value is larger than the parent's value,\n# the child element is swapped with the parent\n\n def _sift_down(self, index):\n left = (index * 2) + 1\n right = (index * 2) + 2\n largest = index\n if len(self.storage) > left and self.storage[largest] < self.storage[left]:\n largest = left\n if len(self.storage) > right and self.storage[largest] < self.storage[right]:\n largest = right\n if largest != index:\n self.storage[index], self.storage[largest] = self.storage[largest], self.storage[index]\n self._sift_down(largest)\n\n\n'''\nMax heap is FAST\n-->> Insert in O(log n)\n-->> Get Max in O(1)\n-->> Remove Max in O(log n)\n--> Easy to implement using an array\n--> eg: if i = 4\n parent(i) = i / 2\n left_child(i) = i * 2\n right_child(i) = i * 2 + 1\n'''\n" } ]
3