diff --git "a/840.jsonl" "b/840.jsonl" new file mode 100644--- /dev/null +++ "b/840.jsonl" @@ -0,0 +1,729 @@ +{"seq_id":"54019932","text":"import os\n\nimport synapse.common as s_common\nimport synapse.cortex as s_cortex\n\nimport synapse.lib.module as s_module\n\nimport synapse.tests.utils as s_t_utils\n\nclass FooMod(s_module.CoreModule):\n mod_name = 'foo'\n\n def preCoreModule(self):\n if os.environ.get('SYN_TEST_MOD_FAIL_PRE'):\n raise Exception('preCoreModuleFail')\n\n def initCoreModule(self):\n if os.environ.get('SYN_TEST_MOD_FAIL_INIT'):\n raise Exception('initCoreModuleFail')\n\nclass BarMod(s_module.CoreModule):\n confdefs = (\n ('hehe', {'defval': 'haha'}),\n ('duck', {}),\n )\n\n def initCoreModule(self):\n self.data = {}\n\n def onfini():\n self.data['fini'] = True\n\n self.core.onfini(onfini)\n\nfoo_ctor = 'synapse.tests.test_lib_module.FooMod'\nbar_ctor = 'synapse.tests.test_lib_module.BarMod'\n\nclass CoreModTest(s_t_utils.SynTest):\n\n async def test_basics(self):\n async with self.getTestCore() as core: # type: s_cortex.Cortex\n\n testmod = core.getCoreMod('synapse.tests.utils.TestModule')\n self.isinstance(testmod, s_module.CoreModule)\n # modname from class name\n self.eq(testmod.mod_name, 'testmodule')\n\n foomod = await core.loadCoreModule(foo_ctor)\n # modname from explicit modname\n self.eq(foomod.mod_name, 'foo')\n # modpaths are dynamically made on demand\n self.false(os.path.isdir(foomod._modpath))\n mpath = foomod.getModPath()\n self.isin(os.path.join('mods', 'foo'), mpath)\n self.true(os.path.isdir(foomod._modpath))\n\n # preload a config file for the BarModule\n dirn = s_common.gendir(core.dirn, 'mods', 'barmod')\n s_common.yamlsave({'test': 1, 'duck': 'quack'}, dirn, 'conf.yaml')\n\n barmod = await core.loadCoreModule(bar_ctor)\n\n self.eq(barmod.data, {})\n self.eq(barmod.conf, {'test': 1,\n 'hehe': 'haha',\n 'duck': 'quack',\n })\n\n self.eq(barmod.data, {'fini': True})\n\n async def test_load_failures(self):\n async with self.getTestCore() as core: # type: s_cortex.Cortex\n with self.setTstEnvars(SYN_TEST_MOD_FAIL_PRE=1) as cm:\n with self.getAsyncLoggerStream('synapse.cortex', 'preCoreModuleFail') as stream:\n self.none(await core.loadCoreModule(foo_ctor))\n self.true(await stream.wait(1))\n self.none(core.getCoreMod(foo_ctor))\n\n with self.setTstEnvars(SYN_TEST_MOD_FAIL_INIT=1) as cm:\n with self.getAsyncLoggerStream('synapse.cortex', 'initCoreModuleFail') as stream:\n self.none(await core.loadCoreModule(foo_ctor))\n self.true(await stream.wait(1))\n self.none(core.getCoreMod(foo_ctor))\n\n with self.getTestDir(mirror='testcore') as dirn:\n conf = s_common.yamlload(dirn, 'cell.yaml')\n conf['modules'].append(foo_ctor)\n s_common.yamlsave(conf, dirn, 'cell.yaml')\n conf = s_common.yamlload(dirn, 'cell.yaml')\n\n with self.setTstEnvars(SYN_TEST_MOD_FAIL_PRE=1) as cm:\n with self.getAsyncLoggerStream('synapse.cortex', 'preCoreModuleFail') as stream:\n async with await s_cortex.Cortex.anit(dirn) as core:\n self.true(await stream.wait(1))\n self.none(core.getCoreMod(foo_ctor))\n\n with self.setTstEnvars(SYN_TEST_MOD_FAIL_INIT=1) as cm:\n with self.getAsyncLoggerStream('synapse.cortex', 'initCoreModuleFail') as stream:\n async with await s_cortex.Cortex.anit(dirn) as core:\n self.true(await stream.wait(1))\n self.none(core.getCoreMod(foo_ctor))\n","sub_path":"synapse/tests/test_lib_module.py","file_name":"test_lib_module.py","file_ext":"py","file_size_in_byte":3923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"122111810","text":"numero = input()\n\nc_zero, c_um = 0, 0\n\nfor caracter in numero:\n if caracter == \"1\":\n c_um += 1\n\nif c_um % 2 == 0:\n numero = numero + \"0\"\n\nelse:\n numero = numero + \"1\"\n\nprint(numero)","sub_path":"URI Online Judge - Beecrowd/Python 3/1307 - Tudo o que Você Precisa é Amor - Python 3.py","file_name":"1307 - Tudo o que Você Precisa é Amor - Python 3.py","file_ext":"py","file_size_in_byte":197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"241951452","text":"from app import app\n\nfrom flask import render_template, url_for\nfrom flask import session, jsonify, redirect\n\nimport os\n\nfrom app import db\n\nfrom .forms import CompetitionForm, TeamForm, DataEntryForm, ParameterForm\n\n# ------------------------------------------------------------------------------------------------------\n# Competition (database)\n# ------------------------------------------------------------------------------------------------------\n\n@app.route('/')\ndef index():\n return database()\n \n@app.route('/database/create', methods=['GET', 'POST'])\ndef database_create():\n \"\"\"\n Create a new database (competition) named *dbname*.\n \"\"\"\n form = CompetitionForm()\n \n if form.validate_on_submit():\n # Process the form ...\n \n # Need to save whatever the current dbname is as get_db will change this.\n cur_db = db.DATABASE\n db.get_db(form.data['name'])\n db.get_db(cur_db) # change it back.\n \n return redirect('/database')\n \n # New database(?)\n return render_template('database_create.html', form=form)\n \n \n \n@app.route('/database')\ndef database():\n db_list = [(c, c.replace('.db', '')) for c in filter(lambda x: x if x.endswith('.db') else None, os.listdir(os.path.join('.', app.config['COMPETITION_DIR'])))]\n \n if 'database_name' not in session:\n session['database_name'] = db.DATABASE + '.db'\n \n return render_template('database.html', competitions=db_list, current_db=session['database_name'])\n\n# ------------------------------------------------------------------------------------------------------\n# Teams\n# ------------------------------------------------------------------------------------------------------\n\n@app.route('/teams')\ndef teams():\n \n return render_template('teams.html', my_team=session.get('my-team'), dbname=db.DATABASE)\n \n@app.route('/teams/create', methods=['GET', 'POST'])\ndef teams_create():\n \"\"\"\n Create a new database (competition) named *dbname*.\n \"\"\"\n form = TeamForm()\n \n if form.validate_on_submit():\n # Process the form ...\n print('Creating/editing team id=\"{}\" name=\"{}\"'.format(form.data['teamId'], form.data['name']))\n c = db.get_db()\n r = c.execute('insert into teams (teamId, name) values (?, ?)', (form.data['teamId'], form.data['name']))\n c.commit()\n return redirect(url_for('teams'))\n \n # New database(?)\n return render_template('team_create.html', form=form)\n\n# ------------------------------------------------------------------------------------------------------\n# Raw Scores (Data)\n# ------------------------------------------------------------------------------------------------------\n\n \n@app.route('/data')\ndef data():\n c = db.get_db()\n r = c.execute('select * from raw_scores')\n \n form = DataEntryForm()\n form.teamId.choices = [(-1, 'Select team ...')] + [(r['teamId'], ('{} ({})'.format(r['name'], r['teamId'])) if r['name'] else r['teamId']) for r in db.query_db('select teamId, name from teams order by teamId')]\n \n return render_template('data.html', form=form, dbname=session.get('database_name', 'roborank').replace('.db', ''))\n \n# ------------------------------------------------------------------------------------------------------\n# Ranking & Analytics\n# ------------------------------------------------------------------------------------------------------\n\n@app.route('/analyze')\ndef analyze():\n params = ParameterForm()\n params.zero_balls.default = session.get('params.zero-balls', 0)\n params.autonomous_points.default = session.get('params.autonomous-points', 1)\n params.climb_points.default = session.get('params.climb-points', 1)\n params.spin_col_points.default = session.get('params.spin-rot-points', 1)\n params.spin_rot_points.default = session.get('params.spin-col-points', 1)\n params.process()\n \n return render_template('analyze.html', dbname=db.DATABASE, form=params)\n \n# ------------------------------------------------------------------------------------------------------\n# About ...\n# ------------------------------------------------------------------------------------------------------\n\n@app.route('/about')\ndef about():\n return render_template('about.html')\n\n ","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"585450826","text":"from flask import Flask, render_template, abort, json\nimport os\nimport magic\nfrom PIL import Image\nfrom PIL.ExifTags import TAGS\nimport hashlib\nfrom math import ceil\n\napp = Flask(__name__)\nm = magic.Magic(mime=True)\n\ndef _get_exif(i):\n ret = {}\n info = i._getexif()\n for tag, value in info.items():\n decoded = TAGS.get(tag, tag)\n ret[decoded] = value\n return ret\n\ndef _img_cmp(x,y):\n return cmp(x[2], y[2])\n\ndef _path_list():\n return [o for o in os.listdir(os.path.join(\"static\", \"pictures\")) if os.path.isdir(os.path.join(\"static\", \"pictures\", o))]\n\ndef _img_list(path):\n images = []\n for root, dirs, files in os.walk(os.path.join(\"static\", \"pictures\", path)):\n for f in files:\n infile = os.path.join(root, f)\n outfile = os.path.join(\"static\", \"thumbs\", hashlib.sha224(infile).hexdigest() + \".jpg\")\n if m.from_file(infile) in [\"image/png\", \"image/jpeg\", \"image/gif\"]:\n im = Image.open(infile)\n metadata = _get_exif(im)\n try:\n open(outfile)\n except:\n size = 220, 220\n try:\n im.thumbnail(size, Image.ANTIALIAS)\n im.save(outfile, \"JPEG\")\n except IOError:\n pass\n images.append((\"/\"+infile, \"/\"+outfile, metadata['DateTime']))\n return sorted(images, cmp=_img_cmp)\n\ndef update_images():\n for p in _path_list():\n filename = os.path.basename(p) + \".json\"\n with open(os.path.join(\"static\", \"thumbs\", filename), 'w') as f:\n json.dump(_img_list(p), f)\n\ndef _get_images(path):\n filename = path + \".json\"\n return json.load(open(os.path.join(\"static\", \"thumbs\", filename)))\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\", paths=_path_list())\n\n@app.route(\"//\")\ndef img(path):\n try:\n return render_template(\"img.html\", images=_get_images(path))\n except:\n abort(404)\n\nif __name__ == \"__main__\":\n app.run(debug=True, host=\"0.0.0.0\")\n\n","sub_path":"taiwan.py","file_name":"taiwan.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"125420488","text":"from flask import Flask\nfrom flask.globals import request\nfrom flask.templating import render_template \nimport librosa\nimport numpy as np\nimport pickle\n\nfilename=(\"models/emotionmodel.pkl\")\ns=pickle.load(open(filename,'rb'))\n\nvalues = {\"fearful\": \"https://firebasestorage.googleapis.com/v0/b/myproject-d9de9.appspot.com/o/59-596556_fear-clipart-fear-emotion-cartoon-face-of-fear-removebg-preview.png?alt=media&token=c451d9cc-5fa7-47e1-bfa6-4be37e358ea8\",\n \"calm\": \"https://d29fhpw069ctt2.cloudfront.net/clipart/100203/preview/smiling_face_of_a_child_2_preview_9c89.png\",\n \"happy\": \"https://firebasestorage.googleapis.com/v0/b/myproject-d9de9.appspot.com/o/565-5650281_happy-boy-clipart-can-do-it-png-transparent-removebg-preview.png?alt=media&token=5964f656-e102-4f85-bb5c-ad4209209e39\",\n \"sad\": \"https://firebasestorage.googleapis.com/v0/b/myproject-d9de9.appspot.com/o/202-2022552_emotional-clipart-sad-dad-sad-clip-art-removebg.png?alt=media&token=3f1938a7-790e-4923-aea7-7f81ee2807b9\",\n \"angry\": \"https://firebasestorage.googleapis.com/v0/b/myproject-d9de9.appspot.com/o/clipart466731.png?alt=media&token=8dd82f61-b3ef-46f2-86c7-e1cd61f24ff3\",\n \"disguist\":\"asdfg\"\n }\n\ndef extract_feature(file_name, mfcc, chroma):\n X,sample_rate=librosa.load(file_name)\n if chroma:\n stft=np.abs(librosa.stft(X))\n result=np.array([])\n if mfcc:\n mfccs=np.mean(librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=40).T, axis=0)\n result=np.hstack((result, mfccs))\n if chroma:\n chroma=np.mean(librosa.feature.chroma_stft(S=stft, sr=sample_rate).T,axis=0)\n result=np.hstack((result, chroma))\n return result\n\napp = Flask(__name__) \n\n@app.route('/')\ndef index():\n result=False\n return render_template('inputfile.html',result1=result)\n\n@app.route('/',methods=[\"post\"]) \ndef home():\n r=[0,0]\n result=True\n audio=request.files.get('shashifile')\n feature=extract_feature(audio, mfcc=True, chroma=True)\n p=s.predict([feature])\n # r=\"https://d29fhpw069ctt2.cloudfront.net/clipart/100203/preview/smiling_face_of_a_child_2_preview_9c89.png\"\n r=[p[0],values[p[0]]]\n return render_template('inputfile.html',result1=result,r1=r)\n\n \nif __name__ =='__main__': \n app.run(debug = True) ","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"116656774","text":"COMMAND_INFO = [\n {\n \"name\": \"getchannelid\",\n \"description\": \"gets the ID of the current channel\",\n \"aliases\": [\"gci\"],\n \"parameters\": [],\n \"usage\":[\n {\n \"cmd\": \"!gci\",\n \"result\": \"prints the channel ID\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"getuser_id\",\n \"description\": \"gets the ID of yourself, or another user\",\n \"aliases\": [\"ui\"],\n \"parameters\": [\n {\n \"name\": \"[user]\",\n \"description\": \"the user you want to get the id of\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!ui\",\n \"result\": \"prints your user ID\"\n },\n {\n \"cmd\": \"!ui @user\",\n \"result\": \"prints the user ID of @user\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"about\",\n \"description\": \"prints information about Pi-Bot\",\n \"aliases\": [],\n \"parameters\": [],\n \"usage\":[\n {\n \"cmd\": \"!about\",\n \"result\": \"prints information about Pi-Bot\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"fish\",\n \"description\": \"feeds bear one fish\",\n \"aliases\": [],\n \"parameters\": [],\n \"usage\":[\n {\n \"cmd\": \"!fish\",\n \"result\": \"feeds bear another fish\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": True\n },\n {\n \"name\": \"help\",\n \"description\": \"provides help for a command\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"[command]\",\n \"description\": \"the command you want help with\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!help\",\n \"result\": \"provides help with the `help` command\"\n },\n {\n \"cmd\": \"!help fish\",\n \"result\": \"provides help with the `fish` command\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": True\n },\n {\n \"name\": \"exalt\",\n \"description\": \"exalts a user\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"user\",\n \"description\": \"the user you would like to exalt\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!exalt @user\",\n \"result\": \"exalts @user\"\n }\n ],\n \"access\":[\n \"Administrator\",\n \"Global Moderator\",\n \"Wiki/Gallery Moderator\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"unexalt\",\n \"description\": \"unexalts a user\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"user\",\n \"description\": \"the user you would like to unexalt\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!unexalt @user\",\n \"result\": \"unexalts @user\"\n }\n ],\n \"access\":[\n \"Administrator\",\n \"Global Moderator\",\n \"Wiki/Gallery Moderator\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"mute\",\n \"description\": \"mutes a user\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"user\",\n \"description\": \"the user that needs to be muted\"\n },\n {\n \"name\": \"time\",\n \"description\": \"the length of the mute\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!mute @user \\\"1 day\\\"\",\n \"result\": \"mutes @user for 1 day\"\n },\n {\n \"cmd\": \"!mute @user \\\"indef\\\"\",\n \"result\": \"mutes @user for an indefinite amount of time\"\n }\n ],\n \"access\":[\n \"Administrator\",\n \"Global Moderator\",\n \"Wiki/Gallery Moderator\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"selfmute\",\n \"description\": \"Mutes the user who calls it\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"time\",\n \"description\": \"the length of the mute\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!selfmute \\\"1 day\\\"\",\n \"result\": \"mutes the user who sends command for 1 day\"\n },\n {\n \"cmd\": \"!selfmute \\\"indef\\\"\",\n \"result\": \"mutes the user who sends command for an indefinite amount of time\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"unmute\",\n \"description\": \"unmutes a user\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"user\",\n \"description\": \"the user that needs to be unmuted\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!unmute @user\",\n \"result\": \"unmutes @user\"\n }\n ],\n \"access\":[\n \"Administrator\",\n \"Global Moderator\",\n \"Wiki/Gallery Moderator\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"ban\",\n \"description\": \"bans a user\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"user\",\n \"description\": \"the user that needs to be banned\"\n },\n {\n \"name\": \"reason\",\n \"description\": \"the reason for the ban\"\n },\n {\n \"name\": \"time\",\n \"description\": \"the length for the ban\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!ban @user \\\"spamming\\\" \\\"7 days\\\"\",\n \"result\": \"bans @user for \\\"spamming\\\" for 7 days\"\n },\n {\n \"cmd\": \"!ban @user \\\"spamming\\\" \\\"indef\\\"\",\n \"result\": \"bans @user for \\\"spamming\\\" for an infinite amount of time\"\n }\n ],\n \"access\":[\n \"Administrator\",\n \"Global Moderator\",\n \"Wiki/Gallery Moderator\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"unban\",\n \"description\": \"unbans a user\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"user id\",\n \"description\": \"the id of the user that needs to be unbanned\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!unban 12345678910\",\n \"result\": \"unbans @user\"\n }\n ],\n \"access\":[\n \"Administrator\",\n \"Global Moderator\",\n \"Wiki/Gallery Moderator\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"states\",\n \"description\": \"toggles specific state roles for a user\",\n \"aliases\": [\"state\"],\n \"parameters\": [\n {\n \"name\": \"state1\",\n \"description\": \"the first state role to toggle for a user\"\n },\n {\n \"name\": \"\",\n \"description\": \"the second state role to toggle for a user\"\n },\n {\n \"name\": \"\",\n \"description\": \"the nth state role to toggle for a user\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!state FL\",\n \"result\": \"toggles the Florida role on a user\"\n },\n {\n \"cmd\": \"!state FL NJ CA-S\",\n \"result\": \"toggles the Florida, New Jersey, and California South roles on a user\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": True\n },\n {\n \"name\": \"nuke\",\n \"description\": \"nukes up to 100 of the last messages in a channel\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"# of messages\",\n \"description\": \"the number of messages to nuke\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!nuke 10\",\n \"result\": \"nukes the 10 most recent messages\"\n }\n ],\n \"access\":[\n \"Administrator\",\n \"Global Moderator\",\n \"Wiki/Gallery Moderator\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"division\",\n \"description\": \"gives the user a division role\",\n \"aliases\": [\"div\"],\n \"parameters\": [\n {\n \"name\": \"division\",\n \"description\": \"the division to apply\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!division a\",\n \"result\": \"gives the user the Division A role\"\n },\n {\n \"cmd\": \"!division d\",\n \"result\": \"gives the user the Division D role\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": True\n },\n {\n \"name\": \"dogbomb\",\n \"description\": \"dog bombs a user :dog:\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"user\",\n \"description\": \"the user to dog bomb!\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!dogbomb @user\",\n \"result\": \"dog bombs @user!\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"shibabomb\",\n \"description\": \"shiba bombs a user :dog2:\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"user\",\n \"description\": \"the user to shiba bomb!\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!shibabomb @user\",\n \"result\": \"shiba bombs @user!\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"events\",\n \"description\": \"assigns or removes event roles to the user\",\n \"aliases\": [\"event\", \"e\"],\n \"parameters\": [\n {\n \"name\": \"event1\",\n \"description\": \"The first event to assign\"\n },\n {\n \"name\": \"[event2]\",\n \"description\": \"The second (optional) event to assign\"\n },\n {\n \"name\": \"[eventn]\",\n \"description\": \"The nth (optional) event to assign\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!events pm\",\n \"result\": \"assigns the Protein Modeling role to the user if they do not have it, else removes it\"\n },\n {\n \"cmd\": \"!events pm gm\",\n \"result\": \"assigns the Protein Modeling role to the user if they do not have it, else removes it, and does the same for the Geologic Mapping role\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": True\n },\n {\n \"name\": \"kick\",\n \"description\": \"kicks a user from the server\",\n \"aliases\": [\"k\"],\n \"parameters\": [\n {\n \"name\": \"user\",\n \"description\": \"the user to kick\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!kick @user \\\"reason\\\"\",\n \"result\": \"kicks @user from the server due to reason \\\"reason\\\"\"\n }\n ],\n \"access\":[\n \"Administrator\",\n \"Global Moderator\",\n \"Wiki/Gallery Moderator\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"prepembed\",\n \"description\": \"allows a customizable embed to be sent to a channel for better message formatting\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"channel\",\n \"description\": \"the channel to send the embed\"\n },\n {\n \"name\": \"json\",\n \"description\": \"the json used to generate the embed (remember that all keys and values in the object should be in double quotes)\"\n },\n {\n \"name\": \"title (in json)\",\n \"description\": \"the title of the embed\"\n },\n {\n \"name\": \"titleUrl (in json)\",\n \"description\": \"the URL to link the title to\"\n },\n {\n \"name\": \"thumbnailUrl (in json)\",\n \"description\": \"the URL of the thumbnail image\"\n },\n {\n \"name\": \"description (in json)\",\n \"description\": \"the text body of the embed\"\n },\n {\n \"name\": \"author (in json)\",\n \"description\": \"can be set to \\\"me\\\" to set authorName to your username and authorIcon to your profile picture automatically\"\n },\n {\n \"name\": \"authorName / authorIcon / authorUrl (in json)\",\n \"description\": \"the name / icon URL / URL of the author of the embed\"\n },\n {\n \"name\": \"fields (in json)\",\n \"description\": \"array of objects consisting of a name, value, and inline value used to generate the fields of the embed\"\n },\n {\n \"name\": \"hexColor (in json)\",\n \"description\": \"the hex color to set the embed to, such as #ffffff or #000bbb\"\n },\n {\n \"name\": \"webColor (in json)\",\n \"description\": \"the web color to set the embed to, such as magenta or steelBlue\"\n },\n {\n \"name\": \"footerText / footerUrl (in json)\",\n \"description\": \"the footer text or url of the embed\"\n },\n ],\n \"usage\":[\n {\n \"cmd\": \"!prepembed #announcements {\\\"title\\\": \\\"Happy Saturday!\\\"}\",\n \"result\": \"sends an embed with the title \\\"Happy Saturday!\\\" to the #announcements channel\"\n }\n ],\n \"access\":[\n \"Administrator\",\n \"Global Moderator\",\n \"Wiki/Gallery Moderator\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"report\",\n \"description\": \"sends a report to staff\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \" message\",\n \"description\": \"the message to send to staff\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!report \\\"message\\\"\",\n \"result\": \"sends a report containing the message to staff\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": True\n },\n {\n \"name\": \"games\",\n \"description\": \"adds or removes the calling user to/from the games channel\",\n \"aliases\": [],\n \"parameters\": [],\n \"usage\":[\n {\n \"cmd\": \"!games\",\n \"result\": \"adds or removes the user to/from the games channel\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"ping\",\n \"description\": \"allows users to add/remove/list their ping expressions/words\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"command\",\n \"description\": \"the ping command to run - can be `add`, `addregex`, `list`, or `remove`\"\n },\n {\n \"name\": \"\",\n \"description\": \"if adding/deleting a ping expression, it should be included\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!ping add \\\"florida\\\"\",\n \"result\": \"adds \\\"florida\\\" to the user's ping list\"\n },\n {\n \"cmd\": \"!ping addregex \\\"^\\d{5}(?:[-\\s]\\d{4})?$\\\"\",\n \"result\": \"adds \\\"^\\d{5}(?:[-\\s]\\d{4})?$\\\" (a formula to match zip codes) to the user's ping list\"\n },\n {\n \"cmd\": \"!ping remove \\\"florida\\\"\",\n \"result\": \"removes \\\"florida\\\" from the user's ping list\"\n },\n {\n \"cmd\": \"!ping list\",\n \"result\": \"lists all of the user's pings\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": True\n },\n {\n \"name\": \"pronouns\",\n \"description\": \"allows users to add/remove pronoun roles\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"pronoun\",\n \"description\": \"the pronoun to add (this can be set to `remove` to remove all pronoun roles)\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!pronouns she\",\n \"result\": \"gives you the `She / Her / Hers` role\"\n },\n {\n \"cmd\": \"!pronouns remove\",\n \"result\": \"removes all of your pronoun roles\"\n },\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": True\n },\n {\n \"name\": \"wiki\",\n \"description\": \"searches the wiki or returns a wiki page link or summary\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"command\",\n \"description\": \"the command to run - can be `link`, `summary`, or `search`\"\n },\n {\n \"name\": \"term\",\n \"description\": \"the page to reference, or the term to search with\"\n },\n {\n \"name\": \"[wikiPage2]\",\n \"description\": \"if acceptable in the context, the second wiki page to get\"\n },\n {\n \"name\": \"[wikiPageN]\",\n \"description\": \"if acceptable in the context, the nth wiki page to get\"\n }\n ],\n \"flags\": [\n {\n \"name\": \"multiple\",\n \"description\": \"specifies each term is a different page title, and you are expecting multiple URLs\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!wiki link Troy Invitational\",\n \"result\": \"gives you the link to the `Troy Invitational` wiki page\"\n },\n {\n \"cmd\": \"!wiki summary Florida\",\n \"result\": \"gives you a summary of the `Florida` page\"\n },\n {\n \"cmd\": \"!wiki link Food Science\",\n \"result\": \"gives you the link to the `Food Science` wiki page\"\n },\n {\n \"cmd\": \"!wiki link \\\"Food Science\\\" WWPN -multiple\",\n \"result\": \"gives you the links to the `Food Science` and `WWPN` wiki pages\"\n },\n {\n \"cmd\": \"!wiki summary \\\"Southeast Florida Regional\\\" WWPN -multiple\",\n \"result\": \"gives you the summaries of the `Southeast Florida Regional` and `WWPN` wiki pages\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"profile\",\n \"description\": \"retrieves a user's profile information\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"[user]\",\n \"description\": \"the optional user's profile information you'd like to retrieve\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!profile\",\n \"result\": \"returns the caller's profile information\"\n },\n {\n \"cmd\": \"!profile @user\",\n \"result\": \"returns @user's profile information\"\n },\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"list\",\n \"description\": \"gives the user a list of commands/states/events\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"[information]\",\n \"description\": \"the information the user would like to retrieve\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!list\",\n \"result\": \"returns commands accessible to the caller\"\n },\n {\n \"cmd\": \"!list states\",\n \"result\": \"returns the list of state roles/channels to the caller\"\n },\n {\n \"cmd\": \"!list events\",\n \"result\": \"returns the list of event roles to the caller\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": True\n },\n {\n \"name\": \"count\",\n \"description\": \"returns a member count for the server\",\n \"aliases\": [],\n \"parameters\": [],\n \"usage\": [{\n \"cmd\": \"!count\",\n \"result\": \"returns the current member count\"\n }],\n \"access\": [\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"wikipedia\",\n \"description\": \"returns informtion about a wikipedia page\",\n \"aliases\": [\"wp\"],\n \"parameters\": [\n {\n \"name\": \"command\",\n \"description\": \"the command to run - can be `search`, `summary`, or `link`\"\n },\n {\n \"name\": \"page\",\n \"description\": \"the page to reference\"\n }\n ],\n \"usage\": [\n {\n \"cmd\": \"!wp search \\\"calculus\\\"\",\n \"result\": \"searches Wikipedia for pages relating to `calculus`\"\n },\n {\n \"cmd\": \"!wp summary \\\"Astronomy\\\"\",\n \"result\": \"returns the summmary for the `Astronomy` Wikipedia page\"\n },\n {\n \"cmd\": \"!wp summary \\\"FTOC\\\"\",\n \"result\": \"returns the summmary for the `Fundamental Theorem of Calculus` Wikipedia page\"\n },\n {\n \"cmd\": \"!wp link \\\"Red fox\\\"\",\n \"result\": \"returns the link for the `Red fox` Wikipedia page\"\n }\n ],\n \"access\": [\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"hello\",\n \"description\": \"makes the bot say hi - can be used to check if the bot is functioning\",\n \"aliases\": [],\n \"parameters\": [],\n \"usage\": [{\n \"cmd\": \"!hi\",\n \"result\": \"the bot says hi!\"\n }],\n \"access\": [\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"refresh\",\n \"description\": \"refreshes data from pi-bot's administrative panel\",\n \"aliases\": [],\n \"parameters\": [],\n \"usage\": [{\n \"cmd\": \"!refresh\",\n \"result\": \"refreshes the data\"\n }],\n \"access\":[\n \"Administrator\",\n \"Global Moderator\",\n \"Wiki/Gallery Moderator\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"me\",\n \"description\": \"refrences a user's actions from the third person\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"message\",\n \"description\": \"the message to implement\"\n }\n ],\n \"usage\": [\n {\n \"cmd\": \"!me can't believe that happened!\",\n \"result\": \"@user can't believe that happened!\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": True\n },\n {\n \"name\": \"dnd\",\n \"description\": \"toggles Do Not Disturb mode for pings\",\n \"aliases\": [\"donotdisturb\"],\n \"parameters\": [],\n \"usage\": [\n {\n \"cmd\": \"!dnd\",\n \"result\": \"toggles Do Not Disturb mode for pings\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": True\n },\n {\n \"name\": \"slowmode\",\n \"description\": \"toggles slowmode for a channel\",\n \"aliases\": [\"slow\", \"sm\"],\n \"parameters\": [\n {\n \"name\": \"seconds\",\n \"description\": \"the amount of seconds to enable slowmode for\"\n }\n ],\n \"usage\": [\n {\n \"cmd\": \"!slowmode\",\n \"result\": \"toggles a 10 second slowmode\"\n },\n {\n \"cmd\": \"!slowmode 35\",\n \"result\": \"enables a 35 second slowmode\"\n },\n {\n \"cmd\": \"!slowmode 0\",\n \"result\": \"removes any slowmode effects\"\n }\n ],\n \"access\":[\n \"Administrator\",\n \"Global Moderator\",\n \"Wiki/Gallery Moderator\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"school\",\n \"description\": \"gets school data in wiki format\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"school name (in quotes)\",\n \"description\": \"the school name to search for **(note: if you cannot find the school you are looking for at first, broaden your search by removing terms such as \\\"school\\\" or \\\"elementary\\\")**\"\n },\n {\n \"name\": \"state abbreviation\",\n \"description\": \"the abbreviation of the state the school is in\"\n }\n ],\n \"usage\": [\n {\n \"cmd\": \"!school \\\"Boca Raton Community High\\\" \\\"FL\\\"\",\n \"result\": \"returns school listings for `Boca Raton Community High` in `FL`\"\n },\n {\n \"cmd\": \"!school \\\"Interlake High\\\" \\\"WA\\\"\",\n \"result\": \"returns school listings for `Interlake High` in `WA`\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"invite\",\n \"description\": \"returns the server's invite link\",\n \"aliases\": [\"link\", \"server\", \"invitelink\"],\n \"parameters\": [],\n \"usage\": [{\n \"cmd\": \"!link\",\n \"result\": \"https://discord.gg/9Z5zKtV\"\n }],\n \"access\": [\n \"Member\"\n ],\n \"inQuickList\": True\n },\n {\n \"name\": \"lock\",\n \"description\": \"locks the current channel to non-staff\",\n \"aliases\": [],\n \"parameters\": [],\n \"usage\": [{\n \"cmd\": \"!lock\",\n \"result\": \"locks the current channel to non-staff\"\n }],\n \"access\": [\n \"Administrator\",\n \"Global Moderator\",\n \"Wiki/Gallery Moderator\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"unlock\",\n \"description\": \"unlocks the current channel to non-staff\",\n \"aliases\": [],\n \"parameters\": [],\n \"usage\": [{\n \"cmd\": \"!unlock\",\n \"result\": \"unlocks the current channel to non-staff\"\n }],\n \"access\": [\n \"Administrator\",\n \"Global Moderator\",\n \"Wiki/Gallery Moderator\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"clrreact\",\n \"description\": \"clears the reactions on a given message\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"message ID\",\n \"description\": \"the ID of the message to remove reactions from\"\n },\n {\n \"name\": \"user list\",\n \"description\": \"the list of users to remove reactions from\"\n }\n ],\n \"usage\": [\n {\n \"cmd\": \"!clrreact 1234567890\",\n \"result\": \"clears all reactions on message id 1234567890\"\n },\n {\n \"cmd\": \"!clrreact 1234567890 @Nydauron\",\n \"result\": \"clears all reactions from Nydauron on message id 1234567890\"\n }\n ],\n \"access\": [\n \"Administrator\",\n \"Global Moderator\",\n \"Wiki/Gallery Moderator\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"obb\",\n \"description\": \"returns the link to the Scioly.org Open Bulletin Board\",\n \"aliases\": [],\n \"parameters\": [],\n \"usage\": [{\n \"cmd\": \"!obb\",\n \"result\": \"https://scioly.org/obb\"\n }],\n \"access\": [\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"forums\",\n \"description\": \"returns the link to the Scioly.org forums\",\n \"aliases\": [],\n \"parameters\": [],\n \"usage\": [{\n \"cmd\": \"!forums\",\n \"result\": \"https://scioly.org/forums\"\n }],\n \"access\": [\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"exchange\",\n \"description\": \"returns the link to the Scioly.org Test Exchange\",\n \"aliases\": [\"tests\", \"testexchange\"],\n \"parameters\": [],\n \"usage\": [{\n \"cmd\": \"!exchange\",\n \"result\": \"https://scioly.org/tests\"\n }],\n \"access\": [\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"gallery\",\n \"description\": \"returns the link to the Scioly.org Image Gallery\",\n \"aliases\": [],\n \"parameters\": [],\n \"usage\": [{\n \"cmd\": \"!gallery\",\n \"result\": \"https://scioly.org/gallery\"\n }],\n \"access\": [\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"getemojiid\",\n \"description\": \"gets the ID of the given emoji\",\n \"aliases\": [\"gei\", \"eid\"],\n \"parameters\": [\n {\n \"name\": \"emoji\",\n \"description\": \"the emoji to get the ID of\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!eid :test_emoji:\",\n \"result\": \"prints the ID of :test_emoji:\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"latex\",\n \"description\": \"produces a LaTeX (math-formatted) output based on given code\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"code\",\n \"description\": \"LaTeX code to run\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!latex 2 + 2 = 4\",\n \"result\": \"Prints `2 + 2 = 4` in LaTeX\"\n },\n {\n \"cmd\": \"!latex 4 - 1 = 3 \\\\text{ quick maffs}\",\n \"result\": \"Prints `$4 - 1 = 3 quick maffs` in LaTeX\"\n }\n ],\n \"access\": [\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"tournament\",\n \"description\": \"allows the user to add/remove themselves from tournament channels, or request new channels\",\n \"aliases\": [\"tournaments\", \"tc\"],\n \"parameters\": [\n {\n \"name\": \"name1\",\n \"description\": \"the channel name of the tournament to toggle/request\"\n },\n {\n \"name\": \"[name2]\",\n \"description\": \"the optional channel name of the second tournament to toggle/request\"\n },\n {\n \"name\": \"[name_n]\",\n \"description\": \"the optional channel name of the nth tournament to toggle/request\"\n }\n ],\n \"usage\": [\n {\n \"cmd\": \"!tournament mit\",\n \"result\": \"toggles the #mit channel for the user\"\n },\n {\n \"cmd\": \"!tournament all\",\n \"result\": \"toggles all tournament channels for the user\"\n },\n {\n \"cmd\": \"!tournament mit new-tourney\",\n \"result\": \"toggles the #mit channel for the user and requests a #new-tourney channel\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": True\n },\n {\n \"name\": \"tla\",\n \"description\": \"allows staff to add tournament names to the tournament list\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"name\",\n \"description\": \"the channel name to add to the list\"\n },\n {\n \"name\": \"uid\",\n \"description\": \"the ID of the user who requested the channel\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!tla new-tourney 1234567890\",\n \"result\": \"adds the `#new-tourney` channel to the tournaments list in `1234567890`'s name\"\n },\n ],\n \"access\":[\n \"Administrator\",\n \"Global Moderator\",\n \"Wiki/Gallery Moderator\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"tlr\",\n \"description\": \"allows staff to remove tournament names from the tournament list\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"name\",\n \"description\": \"the channel name to add to the list\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!tlr new-tourney\",\n \"result\": \"removes the `#new-tourney` channel from the tournaments list\"\n },\n ],\n \"access\":[\n \"Administrator\",\n \"Global Moderator\",\n \"Wiki/Gallery Moderator\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"vc\",\n \"description\": \"creates/deletes a voice channel based on the current text channel\",\n \"aliases\": [],\n \"parameters\": [],\n \"usage\":[\n {\n \"cmd\": \"!vc\",\n \"result\": \"closes/opens a new voice channel for the current channel\"\n },\n ],\n \"access\":[\n \"Administrator\",\n \"Global Moderator\",\n \"Wiki/Gallery Moderator\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"resultstemplate\",\n \"description\": \"makes a `Full results template` template for copying to the wiki based on Scilympiad results\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"url\",\n \"description\": \"the results URL\"\n }\n ],\n \"usage\":[\n {\n \"cmd\": \"!resultstemplate scilympiad.com/results/...\",\n \"result\": \"makes a template based on the results at the given link\"\n },\n ],\n \"access\":[\n \"Member\",\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"rule\",\n \"description\": \"shows a specified rule\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"num\",\n \"description\": \"the rule num to show\"\n }\n ],\n \"usage\": [\n {\n \"cmd\": \"!rule 1\",\n \"result\": \"shows rule 1\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"graphscilympiad\",\n \"description\": \"makes a point graph of Scilympiad results\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"url\",\n \"description\": \"the URL of the results\"\n },\n {\n \"name\": \"title\",\n \"description\": \"the title of the graph\"\n }\n ],\n \"usage\": [\n {\n \"cmd\": \"!graphscilympiad https://scilympiad.com/bearso/Info/Results/907e1af2-0c19-4be6-ad87-a5b52e140bf1 '2021 BEARSO Final Points - Division C'\",\n \"result\": \"makes a graph of the 2021 BEARSO Division C results\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"tag\",\n \"description\": \"uses a tag (a pre-determined message that is attached to a specific keyword)\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"name\",\n \"description\": \"the name of the tag to pull\"\n },\n ],\n \"usage\": [\n {\n \"cmd\": \"!tag jam\",\n \"result\": \"pulls the `jam` tag\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"magic8ball\",\n \"description\": \"rolls the magic 8 ball\",\n \"aliases\": [],\n \"parameters\": [],\n \"usage\": [\n {\n \"cmd\": \"!magic8ball\",\n \"result\": \"rolls the magic 8 ball once\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"userfromid\",\n \"description\": \"gets the user with the specified ID\",\n \"aliases\": [\"ufi\"],\n \"parameters\": [\n {\n \"name\": \"id\",\n \"description\": \"the id of the user to get\"\n }\n ],\n \"usage\": [\n {\n \"cmd\": \"!userfromid 1234567890\",\n \"result\": \"returns the user (mentions them)\"\n }\n ],\n \"access\":[\n \"Wiki/Gallery Moderator\",\n \"Global Moderator\",\n \"Administrator\",\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"info\",\n \"description\": \"shows information about the server\",\n \"aliases\": [],\n \"parameters\": [],\n \"usage\": [\n {\n \"cmd\": \"!info\",\n \"result\": \"shows info about the server\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"xkcd\",\n \"description\": \"shows an xkcd comic\",\n \"aliases\": [],\n \"parameters\": [\n {\n \"name\": \"num\",\n \"description\": \"the number of the xkcd comic to show\"\n }\n ],\n \"usage\": [\n {\n \"cmd\": \"!xkcd\",\n \"result\": \"shows a random xkcd comic\"\n },\n {\n \"cmd\": \"!xkcd 2000\",\n \"result\": \"shows xkcd comic #2000\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n },\n {\n \"name\": \"rand\",\n \"description\": \"Generates a random number\",\n \"aliases\": [\"random\"],\n \"parameters\": [\n {\n \"name\": \"min\",\n \"description\": \"the lower bound (inclusive)\"\n },\n {\n \"name\": \"max\",\n \"description\": \"the upper bound (inclusive)\"\n }\n ],\n \"usage\": [\n {\n \"cmd\": \"!rand\",\n \"result\": \"Generates a random number in the interval [1, 10]\"\n },\n {\n \"cmd\": \"!rand 50 100\",\n \"result\": \"Generates a random number in the interval [50, 100]\"\n }\n ],\n \"access\":[\n \"Member\"\n ],\n \"inQuickList\": False\n }\n]","sub_path":"commandinfo.py","file_name":"commandinfo.py","file_ext":"py","file_size_in_byte":39777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"534441518","text":"# -*- coding: utf-8 -*-\n\"\"\"Test `openid.oidutil` module.\"\"\"\nimport random\nimport string\nimport unittest\n\nfrom openid import oidutil\n\n\nclass TestBase64(unittest.TestCase):\n \"\"\"Test `toBase64` and `fromBase64` functions.\"\"\"\n\n def test_base64(self):\n allowed_s = string.ascii_letters + string.digits + '+/='\n allowed_d = {}\n for c in allowed_s:\n allowed_d[c] = None\n isAllowed = allowed_d.has_key\n\n def checkEncoded(s):\n for c in s:\n assert isAllowed(c), s\n\n cases = [\n '',\n 'x',\n '\\x00',\n '\\x01',\n '\\x00' * 100,\n ''.join(map(chr, range(256))),\n ]\n\n for s in cases:\n b64 = oidutil.toBase64(s)\n checkEncoded(b64)\n s_prime = oidutil.fromBase64(b64)\n assert s_prime == s, (s, b64, s_prime)\n\n # Randomized test\n for _ in xrange(50):\n n = random.randrange(2048)\n s = ''.join(map(chr, map(lambda _: random.randrange(256), range(n))))\n b64 = oidutil.toBase64(s)\n checkEncoded(b64)\n s_prime = oidutil.fromBase64(b64)\n assert s_prime == s, (s, b64, s_prime)\n\n\nsimple = 'http://www.example.com/'\nappend_args_cases = [\n ('empty list',\n (simple, []),\n simple),\n\n ('empty dict',\n (simple, {}),\n simple),\n\n ('one list',\n (simple, [('a', 'b')]),\n simple + '?a=b'),\n\n ('one dict',\n (simple, {'a': 'b'}),\n simple + '?a=b'),\n\n ('two list (same)',\n (simple, [('a', 'b'), ('a', 'c')]),\n simple + '?a=b&a=c'),\n\n ('two list',\n (simple, [('a', 'b'), ('b', 'c')]),\n simple + '?a=b&b=c'),\n\n ('two list (order)',\n (simple, [('b', 'c'), ('a', 'b')]),\n simple + '?b=c&a=b'),\n\n ('two dict (order)',\n (simple, {'b': 'c', 'a': 'b'}),\n simple + '?a=b&b=c'),\n\n ('escape',\n (simple, [('=', '=')]),\n simple + '?%3D=%3D'),\n\n ('escape (URL)',\n (simple, [('this_url', simple)]),\n simple + '?this_url=http%3A%2F%2Fwww.example.com%2F'),\n\n ('use dots',\n (simple, [('openid.stuff', 'bother')]),\n simple + '?openid.stuff=bother'),\n\n ('args exist (empty)',\n (simple + '?stuff=bother', []),\n simple + '?stuff=bother'),\n\n ('args exist',\n (simple + '?stuff=bother', [('ack', 'ack')]),\n simple + '?stuff=bother&ack=ack'),\n\n ('args exist',\n (simple + '?stuff=bother', [('ack', 'ack')]),\n simple + '?stuff=bother&ack=ack'),\n\n ('args exist (dict)',\n (simple + '?stuff=bother', {'ack': 'ack'}),\n simple + '?stuff=bother&ack=ack'),\n\n ('args exist (dict 2)',\n (simple + '?stuff=bother', {'ack': 'ack', 'zebra': 'lion'}),\n simple + '?stuff=bother&ack=ack&zebra=lion'),\n\n ('three args (dict)',\n (simple, {'stuff': 'bother', 'ack': 'ack', 'zebra': 'lion'}),\n simple + '?ack=ack&stuff=bother&zebra=lion'),\n\n ('three args (list)',\n (simple, [('stuff', 'bother'), ('ack', 'ack'), ('zebra', 'lion')]),\n simple + '?stuff=bother&ack=ack&zebra=lion'),\n]\n\n\nclass AppendArgsTest(unittest.TestCase):\n \"\"\"Test `appendArgs` function.\"\"\"\n\n def runTest(self):\n for name, args, expected in append_args_cases:\n result = oidutil.appendArgs(*args)\n self.assertEqual(expected, result, '{} {}'.format(name, args))\n\n\nclass TestUnicodeConversion(unittest.TestCase):\n\n def test_toUnicode(self):\n # Unicode objects pass through\n self.assertIsInstance(oidutil.toUnicode(u'fööbär'), unicode)\n self.assertEquals(oidutil.toUnicode(u'fööbär'), u'fööbär')\n # UTF-8 encoded string are decoded\n self.assertIsInstance(oidutil.toUnicode('fööbär'), unicode)\n self.assertEquals(oidutil.toUnicode('fööbär'), u'fööbär')\n # Other encodings raise exceptions\n self.assertRaises(UnicodeDecodeError, lambda: oidutil.toUnicode(u'fööbär'.encode('latin-1')))\n\n\nclass TestSymbol(unittest.TestCase):\n def testCopyHash(self):\n import copy\n s = oidutil.Symbol(\"Foo\")\n d = {s: 1}\n d_prime = copy.deepcopy(d)\n self.assertIn(s, d_prime, \"%r isn't in %r\" % (s, d_prime))\n\n t = oidutil.Symbol(\"Bar\")\n self.assertNotEqual(hash(s), hash(t))\n\n\n# XXX: there are more functions that could benefit from being better\n# specified and tested in oidutil.py These include, but are not\n# limited to appendArgs\n","sub_path":"openid/test/test_oidutil.py","file_name":"test_oidutil.py","file_ext":"py","file_size_in_byte":4437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"616774818","text":"import re\n\nimport injector\nimport yaml\n\n\nclass Config:\n def __init__(self, action):\n self.action = action\n\n\nclass Action:\n def __init__(self, evaluated_field):\n self.evaluated_field = evaluated_field\n\n self.rules = []\n\n def add_rule(self, rule):\n self.rules.append(rule)\n\n\nclass ActionRule:\n def __init__(self, field, pattern, weight):\n self.field = field\n self.pattern = pattern\n self.weight = weight\n\n self.compiled_pattern = re.compile(re.escape(self.pattern))\n\n\n@injector.singleton\nclass ConfigLoader:\n def __init__(self):\n pass\n\n def load(self, file):\n with open(file) as stream:\n data = yaml.load(stream)\n\n action = Action(evaluated_field=data[\"action\"][\"evaluated_field\"])\n\n for rule_data in data[\"action\"][\"rules\"]:\n action.add_rule(\n ActionRule(\n field=rule_data[\"field\"],\n pattern=rule_data[\"pattern\"],\n weight=rule_data[\"weight\"]\n )\n )\n\n return Config(action=action)\n","sub_path":"app/config/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"140714892","text":"#first model\n#encoder: four conv layers 3-16-32-64-128-FC\n#decoder: four deconv layers FC-128-64-32-16-3\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass DAE(nn.Module):\n def __init__(self, IMAGE_SIZE):\n super(DAE, self).__init__()\n\n self.image_dim = IMAGE_SIZE # a 28x28 image corresponds to 4 on the FC layer, a 64x64 image corresponds to 13\n # can calculate this using output_after_conv() in utils.py\n self.latent_dim = 100\n self.noise_scale = 0\n self.batch_size = 50\n \n self.del1_size = int(IMAGE_SIZE / 4)\n self.del2_size = int(IMAGE_SIZE / 2)\n\n self.encoder_l1 = nn.Sequential(\n nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1),\n nn.ReLU())\n self.encoder_l2 = nn.Sequential(\n nn.Conv2d(16, 32, kernel_size=3, stride=1, padding=1),\n nn.ReLU())\n self.encoder_l3 = nn.Sequential(\n nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1),\n nn.ReLU())\n self.encoder_l4 = nn.Sequential(\n nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1),\n nn.ReLU())\n self.fc1 = nn.Linear(128*self.del1_size*self.del1_size, self.latent_dim)\n self.fc2 = nn.Linear(self.latent_dim, 128*self.del1_size*self.del1_size)\n self.decoder_l1 = nn.Sequential(\n nn.ConvTranspose2d(129, 64, kernel_size=3, stride=2, padding=1, output_padding = 1),\n nn.ReLU())\n #self.m1 = nn.MaxPool2d(3, stride=2)\n self.decoder_l2 = nn.Sequential(\n nn.ConvTranspose2d(65, 32, kernel_size=3, stride=2, padding=1, output_padding = 1),\n nn.ReLU())\n #self.m1 = nn.MaxPool2d(3, stride=2)\n self.decoder_l3 = nn.Sequential(\n nn.ConvTranspose2d(33, 16, kernel_size=3, stride=1, padding=1),\n nn.ReLU())\n #self.m1 = nn.MaxPool2d(3, stride=2)\n self.decoder_l4 = nn.Sequential(\n nn.ConvTranspose2d(17, 3, kernel_size=3, stride=1, padding=1))\n\t #nn.Sigmoid())\n \n \n def forward(self, x, mask):\n n = x.size()[0]\n\n #x = torch.add(x, noise)\n #print(\"****\")\n #print(x.shape)\n x = self.encoder_l1(x)\n #print(x.shape)\n x = self.encoder_l2(x)\n #print(x.shape)\n x = self.encoder_l3(x)\n #print(x.shape)\n z = self.encoder_l4(x)\n #print(x.shape)\n #z = self.encoder(x)\n z = z.view(-1, 128*self.del1_size*self.del1_size)\n z = self.fc1(z)\n x_hat = self.fc2(z)\n x_hat = x_hat.view(-1, 128, self.del1_size, self.del1_size)\n \n #print(x_hat.shape)\n \n m1 = nn.MaxPool2d(4, stride = 4)\n mask_l1 = m1(mask)\n #print(mask_l1.shape)\n #print(type(x_hat), type(mask_l1))\n x_hat = torch.cat((x_hat, mask_l1), dim = 1)\n x_hat = self.decoder_l1(x_hat)\n #print(x_hat.shape)\n m2 = nn.MaxPool2d(2, stride = 2)\n mask_l2 = m2(mask)\n x_hat = torch.cat((x_hat, mask_l2), dim = 1)\n #print(mask_l2.shape)\n x_hat = self.decoder_l2(x_hat)\n x_hat = torch.cat((x_hat, mask), dim = 1)\n #print(x_hat.shape)\n x_hat = self.decoder_l3(x_hat)\n x_hat = torch.cat((x_hat, mask), dim = 1)\n #print(x_hat.shape)\n x_hat = self.decoder_l4(x_hat)\n\n return z, x_hat\n\n def encode(self, x):\n #x = x.unsqueeze(0)\n z, x_hat = self.forward(x)\n\n return z","sub_path":"gb_files/models/model_AE_128FC.py","file_name":"model_AE_128FC.py","file_ext":"py","file_size_in_byte":3523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"518090462","text":"# Released under The MIT License (MIT)\n# http://opensource.org/licenses/MIT\n# Copyright (c) 2013 SCoT Development Team\n\n\"\"\" Use scikit-learn routines as backend.\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport scipy as sp\nfrom . import backend_builtin as builtin\nfrom . import config, datatools\nfrom .varbase import VARBase\n\n\ndef wrapper_fastica(data):\n \"\"\" Call FastICA implementation from scikit-learn.\n \"\"\"\n from sklearn.decomposition import FastICA\n ica = FastICA()\n ica.fit(datatools.cat_trials(data))\n u = ica.components_.T\n m = ica.mixing_.T\n return m, u\n\n\ndef wrapper_pca(x, reducedim):\n \"\"\" Call PCA implementation from scikit-learn.\n \"\"\"\n from sklearn.decomposition import PCA\n pca = PCA(n_components=reducedim)\n pca.fit(datatools.cat_trials(x))\n d = pca.components_\n c = pca.components_.T\n y = datatools.dot_special(x,c)\n return c, d, y\n\n\nclass VAR(VARBase):\n \"\"\" Scikit-learn based implementation of VARBase.\n\n This class fits VAR models using various implementations of generalized linear model fitting available in scikit-learn.\n \n Parameters \n ----------\n model_order : int\n Autoregressive model order\n fitobj : class, optional\n Instance of a linear model implementation.\n \"\"\"\n def __init__(self, model_order, fitobj=None):\n VARBase.__init__(self, model_order)\n if fitobj is None:\n from sklearn.linear_model import LinearRegression\n fitobj = LinearRegression()\n self.fitting_model = fitobj\n\n def fit(self, data):\n \"\"\" Fit VAR model to data.\n \n Parameters\n ----------\n data : array-like, shape = [n_samples, n_channels, n_trials] or [n_samples, n_channels]\n Continuous or segmented data set.\n \n Returns\n -------\n self : :class:`VAR`\n The :class:`VAR` object.\n \"\"\"\n data = sp.atleast_3d(data)\n (x, y) = self._construct_eqns(data)\n self.fitting_model.fit(x, y)\n\n self.coef = self.fitting_model.coef_\n\n self.residuals = data - self.predict(data)\n self.rescov = sp.cov(datatools.cat_trials(self.residuals[self.p:, :, :]), rowvar=False)\n\n return self\n\n\nbackend = builtin.backend.copy()\nbackend.update({\n 'ica': wrapper_fastica,\n 'pca': wrapper_pca,\n 'var': VAR\n})\n\n\ndef activate():\n \"\"\" Set backend attribute in the config module.\n \"\"\"\n config.backend = backend\n\n\nactivate()\n","sub_path":"scot/backend_sklearn.py","file_name":"backend_sklearn.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"59846409","text":"r\"\"\"\nMetadata template objects (:mod: `qiita_db.metadata_template)\n=============================================================\n\n..currentmodule:: qiita_db.metadata_template\n\nThis module provides the MetadataTemplate base class and the subclasses\nSampleTemplate and PrepTemplate.\n\nClasses\n-------\n\n..autosummary::\n :toctree: generated/\n\n BaseSample\n Sample\n PrepSample\n MetadataTemplate\n SampleTemplate\n PrepTemplate\n\nMethods\n-------\n\n..autosummary::\n :toctree: generated/\n\n sample_template_adder\n\"\"\"\n\n# -----------------------------------------------------------------------------\n# Copyright (c) 2014--, The Qiita Development Team.\n#\n# Distributed under the terms of the BSD 3-clause License.\n#\n# The full license is in the file LICENSE, distributed with this software.\n# -----------------------------------------------------------------------------\n\nfrom __future__ import division\nfrom future.builtins import zip\nfrom copy import deepcopy\n\nimport pandas as pd\nimport numpy as np\n\nfrom qiita_core.exceptions import IncompetentQiitaDeveloperError\nfrom .exceptions import (QiitaDBDuplicateError, QiitaDBColumnError,\n QiitaDBUnknownIDError, QiitaDBNotImplementedError,\n QiitaDBDuplicateHeaderError)\nfrom .base import QiitaObject\nfrom .sql_connection import SQLConnectionHandler\nfrom .util import exists_table, get_table_cols\n\n\ndef _get_datatypes(metadata_map):\n r\"\"\"Returns the datatype of each metadata_map column\n\n Parameters\n ----------\n metadata_map : DataFrame\n The MetadataTemplate contents\n\n Returns\n -------\n list of str\n The SQL datatypes for each column, in column order\n \"\"\"\n datatypes = []\n for dtype in metadata_map.dtypes:\n if dtype in [np.int8, np.int16, np.int32, np.int64]:\n datatypes.append('integer')\n elif dtype in [np.float16, np.float32, np.float64]:\n datatypes.append('float8')\n else:\n datatypes.append('varchar')\n return datatypes\n\n\ndef _as_python_types(metadata_map, headers):\n r\"\"\"Converts the values of metadata_map pointed by headers from numpy types\n to python types.\n\n Psycopg2 does not support the numpy types, so we should cast them to the\n closest python type\n\n Parameters\n ----------\n metadata_map : DataFrame\n The MetadataTemplate contents\n headers : list of str\n The headers of the columns of metadata_map that needs to be converted\n to a python type\n\n Returns\n -------\n list of lists\n The values of the columns in metadata_map pointed by headers casted to\n python types.\n \"\"\"\n values = []\n for h in headers:\n if isinstance(metadata_map[h][0], np.generic):\n values.append(list(map(np.asscalar, metadata_map[h])))\n else:\n values.append(list(metadata_map[h]))\n return values\n\n\nclass BaseSample(QiitaObject):\n r\"\"\"Sample object that accesses the db to get the information of a sample\n belonging to a PrepTemplate or a SampleTemplate.\n\n Parameters\n ----------\n sample_id : str\n The sample id\n md_template : MetadataTemplate\n The metadata template obj to which the sample belongs to\n\n Methods\n -------\n __eq__\n __len__\n __getitem__\n __setitem__\n __delitem__\n __iter__\n __contains__\n exists\n keys\n values\n items\n get\n\n See Also\n --------\n QiitaObject\n Sample\n PrepSample\n \"\"\"\n # Used to find the right SQL tables - should be defined on the subclasses\n _table_prefix = None\n _column_table = None\n _id_column = None\n\n def _check_template_class(self, md_template):\n r\"\"\"Checks that md_template is of the correct type\n\n Parameters\n ----------\n md_template : MetadataTemplate\n The metadata template\n\n Raises\n ------\n IncompetentQiitaDeveloperError\n If its call directly from the Base class\n If `md_template` doesn't have the correct type\n \"\"\"\n raise IncompetentQiitaDeveloperError()\n\n def __init__(self, sample_id, md_template):\n r\"\"\"Initializes the object\n\n Parameters\n ----------\n sample_id : str\n The sample id\n md_template : MetadataTemplate\n The metadata template in which the sample is present\n\n Raises\n ------\n QiitaDBUnknownIDError\n If `sample_id` does not correspond to any sample in md_template\n \"\"\"\n # Check that we are not instantiating the base class\n self._check_subclass()\n # Check that the md_template is of the correct type\n self._check_template_class(md_template)\n # Check if the sample id is present on the passed metadata template\n # This test will check that the sample id is actually present on the db\n if sample_id not in md_template:\n raise QiitaDBUnknownIDError(sample_id, self.__class__.__name__)\n # Assign private attributes\n self._id = sample_id\n self._md_template = md_template\n self._dynamic_table = \"%s%d\" % (self._table_prefix,\n self._md_template.id)\n\n def __hash__(self):\n r\"\"\"Defines the hash function so samples are hashable\"\"\"\n return hash(self._id)\n\n def __eq__(self, other):\n r\"\"\"Self and other are equal based on type and ids\"\"\"\n if not isinstance(other, type(self)):\n return False\n if other._id != self._id:\n return False\n if other._md_template != self._md_template:\n return False\n return True\n\n @classmethod\n def exists(cls, sample_id, md_template):\n r\"\"\"Checks if already exists a MetadataTemplate for the provided object\n\n Parameters\n ----------\n sample_id : str\n The sample id\n md_template : MetadataTemplate\n The metadata template to which the sample belongs to\n\n Returns\n -------\n bool\n True if already exists. False otherwise.\n \"\"\"\n cls._check_subclass()\n conn_handler = SQLConnectionHandler()\n return conn_handler.execute_fetchone(\n \"SELECT EXISTS(SELECT * FROM qiita.{0} WHERE sample_id=%s AND \"\n \"{1}=%s)\".format(cls._table, cls._id_column),\n (sample_id, md_template.id))[0]\n\n def _get_categories(self, conn_handler):\n r\"\"\"Returns all the available metadata categories for the sample\n\n Parameters\n ----------\n conn_handler : SQLConnectionHandler\n The connection handler object connected to the DB\n\n Returns\n -------\n set of str\n The set of all available metadata categories\n \"\"\"\n # Get all the required columns\n required_cols = get_table_cols(self._table, conn_handler)\n # Get all the the columns in the dynamic table\n dynamic_cols = get_table_cols(self._dynamic_table, conn_handler)\n # Get the union of the two previous lists\n cols = set(required_cols).union(dynamic_cols)\n # Remove the sample_id column and the study_id/raw_data_id columns,\n # as this columns are used internally for data storage and they don't\n # actually belong to the metadata\n cols.remove('sample_id')\n cols.remove(self._id_column)\n return cols\n\n def __len__(self):\n r\"\"\"Returns the number of metadata categories\n\n Returns\n -------\n int\n The number of metadata categories\n \"\"\"\n conn_handler = SQLConnectionHandler()\n # return the number of columns\n return len(self._get_categories(conn_handler))\n\n def __getitem__(self, key):\n r\"\"\"Returns the value of the metadata category `key`\n\n Parameters\n ----------\n key : str\n The metadata category\n\n Returns\n -------\n obj\n The value of the metadata category `key`\n\n Raises\n ------\n KeyError\n If the metadata category `key` does not exists\n\n See Also\n --------\n get\n \"\"\"\n conn_handler = SQLConnectionHandler()\n key = key.lower()\n if key in self._get_categories(conn_handler):\n # Check if we have either to query the table with required columns\n # or the dynamic table\n if key in get_table_cols(self._table, conn_handler):\n return conn_handler.execute_fetchone(\n \"SELECT {0} FROM qiita.{1} WHERE {2}=%s AND \"\n \"sample_id=%s\".format(key, self._table, self._id_column),\n (self._md_template.id, self._id))[0]\n else:\n return conn_handler.execute_fetchone(\n \"SELECT {0} FROM qiita.{1} WHERE \"\n \"sample_id=%s\".format(key, self._dynamic_table),\n (self._id, ))[0]\n else:\n # The key is not available for the sample, so raise a KeyError\n raise KeyError(\"Metadata category %s does not exists for sample %s\"\n \" in template %d\" %\n (key, self._id, self._md_template.id))\n\n def __setitem__(self, key, value):\n r\"\"\"Sets the metadata value for the category `key`\n\n Parameters\n ----------\n key : str\n The metadata category\n value : obj\n The new value for the category\n \"\"\"\n raise QiitaDBNotImplementedError()\n\n def __delitem__(self, key):\n r\"\"\"Removes the sample with sample id `key` from the database\n\n Parameters\n ----------\n key : str\n The sample id\n \"\"\"\n raise QiitaDBNotImplementedError()\n\n def __iter__(self):\n r\"\"\"Iterator over the metadata keys\n\n Returns\n -------\n Iterator\n Iterator over the sample ids\n\n See Also\n --------\n keys\n \"\"\"\n conn_handler = SQLConnectionHandler()\n return iter(self._get_categories(conn_handler))\n\n def __contains__(self, key):\n r\"\"\"Checks if the metadata category `key` is present\n\n Parameters\n ----------\n key : str\n The sample id\n\n Returns\n -------\n bool\n True if the metadata category `key` is present, false otherwise\n \"\"\"\n conn_handler = SQLConnectionHandler()\n return key.lower() in self._get_categories(conn_handler)\n\n def keys(self):\n r\"\"\"Iterator over the metadata categories\n\n Returns\n -------\n Iterator\n Iterator over the sample ids\n\n See Also\n --------\n __iter__\n \"\"\"\n return self.__iter__()\n\n def values(self):\n r\"\"\"Iterator over the metadata values, in metadata category order\n\n Returns\n -------\n Iterator\n Iterator over metadata values\n \"\"\"\n conn_handler = SQLConnectionHandler()\n values = conn_handler.execute_fetchone(\n \"SELECT * FROM qiita.{0} WHERE {1}=%s AND \"\n \"sample_id=%s\".format(self._table, self._id_column),\n (self._md_template.id, self._id))[2:]\n dynamic_values = conn_handler.execute_fetchone(\n \"SELECT * from qiita.{0} WHERE \"\n \"sample_id=%s\".format(self._dynamic_table),\n (self._id, ))[1:]\n values.extend(dynamic_values)\n return iter(values)\n\n def items(self):\n r\"\"\"Iterator over (category, value) tuples\n\n Returns\n -------\n Iterator\n Iterator over (category, value) tuples\n \"\"\"\n conn_handler = SQLConnectionHandler()\n values = dict(conn_handler.execute_fetchone(\n \"SELECT * FROM qiita.{0} WHERE {1}=%s AND \"\n \"sample_id=%s\".format(self._table, self._id_column),\n (self._md_template.id, self._id)))\n dynamic_values = dict(conn_handler.execute_fetchone(\n \"SELECT * from qiita.{0} WHERE \"\n \"sample_id=%s\".format(self._dynamic_table),\n (self._id, )))\n values.update(dynamic_values)\n del values['sample_id']\n del values[self._id_column]\n return values.items()\n\n def get(self, key):\n r\"\"\"Returns the metadata value for category `key`, or None if the\n category `key` is not present\n\n Parameters\n ----------\n key : str\n The metadata category\n\n Returns\n -------\n Obj or None\n The value object for the category `key`, or None if it is not\n present\n\n See Also\n --------\n __getitem__\n \"\"\"\n try:\n return self[key]\n except KeyError:\n return None\n\n\nclass PrepSample(BaseSample):\n r\"\"\"Class that models a sample present in a PrepTemplate.\n\n See Also\n --------\n BaseSample\n Sample\n \"\"\"\n _table = \"common_prep_info\"\n _table_prefix = \"prep_\"\n _column_table = \"raw_data_prep_columns\"\n _id_column = \"raw_data_id\"\n\n def _check_template_class(self, md_template):\n r\"\"\"Checks that md_template is of the correct type\n\n Parameters\n ----------\n md_template : PrepTemplate\n The metadata template\n\n Raises\n ------\n IncompetentQiitaDeveloperError\n If `md_template` is not a PrepTemplate object\n \"\"\"\n if not isinstance(md_template, PrepTemplate):\n raise IncompetentQiitaDeveloperError()\n\n\nclass Sample(BaseSample):\n r\"\"\"Class that models a sample present in a SampleTemplate.\n\n See Also\n --------\n BaseSample\n PrepSample\n \"\"\"\n _table = \"required_sample_info\"\n _table_prefix = \"sample_\"\n _column_table = \"study_sample_columns\"\n _id_column = \"study_id\"\n\n def _check_template_class(self, md_template):\n r\"\"\"Checks that md_template is of the correct type\n\n Parameters\n ----------\n md_template : SampleTemplate\n The metadata template\n\n Raises\n ------\n IncompetentQiitaDeveloperError\n If `md_template` is not a SampleTemplate object\n \"\"\"\n if not isinstance(md_template, SampleTemplate):\n raise IncompetentQiitaDeveloperError()\n\n\nclass MetadataTemplate(QiitaObject):\n r\"\"\"Metadata map object that accesses the db to get the sample/prep\n template information\n\n Attributes\n ----------\n id\n\n Methods\n -------\n create\n exists\n __len__\n __getitem__\n __setitem__\n __delitem__\n __iter__\n __contains__\n keys\n values\n items\n get\n to_file\n\n See Also\n --------\n QiitaObject\n SampleTemplate\n PrepTemplate\n \"\"\"\n\n # Used to find the right SQL tables - should be defined on the subclasses\n _table_prefix = None\n _column_table = None\n _id_column = None\n _strict = True\n _sample_cls = None\n\n def _check_id(self, id_, conn_handler=None):\n r\"\"\"Checks that the MetadataTemplate id_ exists on the database\"\"\"\n self._check_subclass()\n conn_handler = (conn_handler if conn_handler is not None\n else SQLConnectionHandler())\n return conn_handler.execute_fetchone(\n \"SELECT EXISTS(SELECT * FROM qiita.{0} WHERE \"\n \"{1}=%s)\".format(self._table, self._id_column),\n (id_, ))[0]\n\n @classmethod\n def _table_name(cls, obj):\n r\"\"\"Returns the dynamic table name\n\n Parameters\n ----------\n obj : Study or RawData\n The obj to which the metadata template belongs to.\n\n Returns\n -------\n str\n The table name\n\n Raises\n ------\n IncompetentQiitaDeveloperError\n If called from the base class directly\n \"\"\"\n if not cls._table_prefix:\n raise IncompetentQiitaDeveloperError(\n \"_table_prefix should be defined in the subclasses\")\n return \"%s%d\" % (cls._table_prefix, obj.id)\n\n @classmethod\n def create(cls, md_template, obj):\n r\"\"\"Creates the metadata template in the database\n\n Parameters\n ----------\n md_template : DataFrame\n The metadata template file contents indexed by samples Ids\n obj : Study or RawData\n The obj to which the metadata template belongs to. Study in case\n of SampleTemplate and RawData in case of PrepTemplate\n \"\"\"\n cls._check_subclass()\n\n # Check that we don't have a MetadataTemplate for obj\n if cls.exists(obj):\n raise QiitaDBDuplicateError(cls.__name__, 'id: %d' % obj.id)\n\n # We are going to modify the md_template. We create a copy so\n # we don't modify the user one\n md_template = deepcopy(md_template)\n # In the database, all the column headers are lowercase\n md_template.columns = [c.lower() for c in md_template.columns]\n\n # Check that we don't have duplicate columns\n if len(set(md_template.columns)) != len(md_template.columns):\n raise QiitaDBDuplicateHeaderError()\n\n conn_handler = SQLConnectionHandler()\n # Check that md_template have the required columns\n db_cols = get_table_cols(cls._table, conn_handler)\n # Remove the sample_id and study_id columns\n db_cols.remove('sample_id')\n db_cols.remove(cls._id_column)\n headers = list(md_template.keys())\n sample_ids = list(md_template.index)\n num_samples = len(sample_ids)\n remaining = set(db_cols).difference(headers)\n if remaining:\n # If strict, raise an error, else default to None\n if cls._strict:\n raise QiitaDBColumnError(\"Missing columns: %s\" % remaining)\n else:\n for col in remaining:\n md_template[col] = pd.Series([None] * num_samples,\n index=sample_ids)\n # Insert values on required columns\n values = _as_python_types(md_template, db_cols)\n values.insert(0, sample_ids)\n values.insert(0, [obj.id] * num_samples)\n values = [v for v in zip(*values)]\n conn_handler.executemany(\n \"INSERT INTO qiita.{0} ({1}, sample_id, {2}) \"\n \"VALUES (%s, %s, {3})\".format(cls._table, cls._id_column,\n ', '.join(db_cols),\n ', '.join(['%s'] * len(db_cols))),\n values)\n\n # Insert rows on *_columns table\n headers = list(set(headers).difference(db_cols))\n datatypes = _get_datatypes(md_template.ix[:, headers])\n # psycopg2 requires a list of tuples, in which each tuple is a set\n # of values to use in the string formatting of the query. We have all\n # the values in different lists (but in the same order) so use zip\n # to create the list of tuples that psycopg2 requires.\n values = [v for v in zip([obj.id] * len(headers), headers, datatypes)]\n conn_handler.executemany(\n \"INSERT INTO qiita.{0} ({1}, column_name, column_type) \"\n \"VALUES (%s, %s, %s)\".format(cls._column_table, cls._id_column),\n values)\n\n # Create table with custom columns\n table_name = cls._table_name(obj)\n column_datatype = [\"%s %s\" % (col, dtype)\n for col, dtype in zip(headers, datatypes)]\n conn_handler.execute(\n \"CREATE TABLE qiita.{0} (sample_id varchar, {1})\".format(\n table_name, ', '.join(column_datatype)))\n\n # Insert values on custom table\n values = _as_python_types(md_template, headers)\n values.insert(0, sample_ids)\n values = [v for v in zip(*values)]\n conn_handler.executemany(\n \"INSERT INTO qiita.{0} (sample_id, {1}) \"\n \"VALUES (%s, {2})\".format(table_name, \", \".join(headers),\n ', '.join([\"%s\"] * len(headers))),\n values)\n\n return cls(obj.id)\n\n @classmethod\n def exists(cls, obj):\n r\"\"\"Checks if already exists a MetadataTemplate for the provided object\n\n Parameters\n ----------\n obj : QiitaObject\n The object to test if a MetadataTemplate exists for\n\n Returns\n -------\n bool\n True if already exists. False otherwise.\n \"\"\"\n cls._check_subclass()\n return exists_table(cls._table_name(obj), SQLConnectionHandler())\n\n def _get_sample_ids(self, conn_handler):\n r\"\"\"Returns all the available samples for the metadata template\n\n Parameters\n ----------\n conn_handler : SQLConnectionHandler\n The connection handler object connected to the DB\n\n Returns\n -------\n set of str\n The set of all available sample ids\n \"\"\"\n sample_ids = conn_handler.execute_fetchall(\n \"SELECT sample_id FROM qiita.{0} WHERE \"\n \"{1}=%s\".format(self._table, self._id_column),\n (self._id, ))\n return set(sample_id[0] for sample_id in sample_ids)\n\n def __len__(self):\n r\"\"\"Returns the number of samples in the metadata template\n\n Returns\n -------\n int\n The number of samples in the metadata template\n \"\"\"\n conn_handler = SQLConnectionHandler()\n return len(self._get_sample_ids(conn_handler))\n\n def __getitem__(self, key):\n r\"\"\"Returns the metadata values for sample id `key`\n\n Parameters\n ----------\n key : str\n The sample id\n\n Returns\n -------\n Sample\n The sample object for the sample id `key`\n\n Raises\n ------\n KeyError\n If the sample id `key` is not present in the metadata template\n\n See Also\n --------\n get\n \"\"\"\n if key in self:\n return self._sample_cls(key, self)\n else:\n raise KeyError(\"Sample id %s does not exists in template %d\"\n % (key, self._id))\n\n def __setitem__(self, key, value):\n r\"\"\"Sets the metadata values for sample id `key`\n\n Parameters\n ----------\n key : str\n The sample id\n value : Sample\n The sample obj holding the new sample values\n \"\"\"\n raise QiitaDBNotImplementedError()\n\n def __delitem__(self, key):\n r\"\"\"Removes the sample with sample id `key` from the database\n\n Parameters\n ----------\n key : str\n The sample id\n \"\"\"\n raise QiitaDBNotImplementedError()\n\n def __iter__(self):\n r\"\"\"Iterator over the sample ids\n\n Returns\n -------\n Iterator\n Iterator over the sample ids\n\n See Also\n --------\n keys\n \"\"\"\n conn_handler = SQLConnectionHandler()\n return iter(self._get_sample_ids(conn_handler))\n\n def __contains__(self, key):\n r\"\"\"Checks if the sample id `key` is present in the metadata template\n\n Parameters\n ----------\n key : str\n The sample id\n\n Returns\n -------\n bool\n True if the sample id `key` is in the metadata template, false\n otherwise\n \"\"\"\n conn_handler = SQLConnectionHandler()\n return key in self._get_sample_ids(conn_handler)\n\n def keys(self):\n r\"\"\"Iterator over the sorted sample ids\n\n Returns\n -------\n Iterator\n Iterator over the sample ids\n\n See Also\n --------\n __iter__\n \"\"\"\n return self.__iter__()\n\n def values(self):\n r\"\"\"Iterator over the metadata values\n\n Returns\n -------\n Iterator\n Iterator over Sample obj\n \"\"\"\n conn_handler = SQLConnectionHandler()\n return iter(self._sample_cls(sample_id, self)\n for sample_id in self._get_sample_ids(conn_handler))\n\n def items(self):\n r\"\"\"Iterator over (sample_id, values) tuples, in sample id order\n\n Returns\n -------\n Iterator\n Iterator over (sample_ids, values) tuples\n \"\"\"\n conn_handler = SQLConnectionHandler()\n return iter((sample_id, self._sample_cls(sample_id, self))\n for sample_id in self._get_sample_ids(conn_handler))\n\n def get(self, key):\n r\"\"\"Returns the metadata values for sample id `key`, or None if the\n sample id `key` is not present in the metadata map\n\n Parameters\n ----------\n key : str\n The sample id\n\n Returns\n -------\n Sample or None\n The sample object for the sample id `key`, or None if it is not\n present\n\n See Also\n --------\n __getitem__\n \"\"\"\n try:\n return self[key]\n except KeyError:\n return None\n\n def _transform_to_dict(self, values):\n r\"\"\"Transforms `values` to a dict keyed by sample id\n\n Parameters\n ----------\n values : object\n The object returned from a execute_fetchall call\n\n Returns\n -------\n dict\n \"\"\"\n result = {}\n for row in values:\n # Transform the row to a dictionary\n values_dict = dict(row)\n # Get the sample id of this row\n sid = values_dict['sample_id']\n del values_dict['sample_id']\n # Remove _id_column from this row (if present)\n if self._id_column in values_dict:\n del values_dict[self._id_column]\n result[sid] = values_dict\n\n return result\n\n def to_file(self, fp):\n r\"\"\"Writes the MetadataTemplate to the file `fp` in tab-delimited\n format\n\n Parameters\n ----------\n fp : str\n Path to the output file\n \"\"\"\n conn_handler = SQLConnectionHandler()\n metadata_map = self._transform_to_dict(conn_handler.execute_fetchall(\n \"SELECT * FROM qiita.{0} WHERE {1}=%s\".format(self._table,\n self._id_column),\n (self.id,)))\n dyn_vals = self._transform_to_dict(conn_handler.execute_fetchall(\n \"SELECT * FROM qiita.{0}\".format(self._table_name(self))))\n\n for k in metadata_map:\n metadata_map[k].update(dyn_vals[k])\n\n headers = sorted(list(metadata_map.values())[0].keys())\n with open(fp, 'w') as f:\n # First write the headers\n f.write(\"#SampleID\\t%s\\n\" % '\\t'.join(headers))\n # Write the values for each sample id\n for sid, d in sorted(metadata_map.items()):\n values = [str(d[h]) for h in headers]\n values.insert(0, sid)\n f.write(\"%s\\n\" % '\\t'.join(values))\n\n\nclass SampleTemplate(MetadataTemplate):\n r\"\"\"Represent the SampleTemplate of a study. Provides access to the\n tables in the DB that holds the sample metadata information.\n\n See Also\n --------\n MetadataTemplate\n PrepTemplate\n \"\"\"\n _table = \"required_sample_info\"\n _table_prefix = \"sample_\"\n _column_table = \"study_sample_columns\"\n _id_column = \"study_id\"\n _sample_cls = Sample\n\n @staticmethod\n def metadata_headers():\n \"\"\"Returns metadata headers available\n\n Returns\n -------\n list\n Alphabetical list of all metadata headers available\n \"\"\"\n conn_handler = SQLConnectionHandler()\n return [x[0] for x in\n conn_handler.execute_fetchall(\n \"SELECT DISTINCT column_name FROM qiita.study_sample_columns \"\n \"UNION SELECT column_name FROM information_schema.columns \"\n \"WHERE table_name = 'required_sample_info' \"\n \"ORDER BY column_name\")]\n\n\nclass PrepTemplate(MetadataTemplate):\n r\"\"\"Represent the PrepTemplate of a raw dat. Provides access to the\n tables in the DB that holds the sample preparation information.\n\n See Also\n --------\n MetadataTemplate\n SampleTemplate\n \"\"\"\n _table = \"common_prep_info\"\n _table_prefix = \"prep_\"\n _column_table = \"raw_data_prep_columns\"\n _id_column = \"raw_data_id\"\n _strict = False\n _sample_cls = PrepSample\n","sub_path":"qiita_db/metadata_template.py","file_name":"metadata_template.py","file_ext":"py","file_size_in_byte":28495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"615833619","text":"from xcp2k.inputsection import InputSection\nfrom xcp2k.classes._localize4 import _localize4\nfrom xcp2k.classes._ri_info4 import _ri_info4\n\n\nclass _ri5(InputSection):\n def __init__(self):\n InputSection.__init__(self)\n self.Section_parameters = None\n self.Eps_filter = None\n self.Eps_filter_2c = None\n self.Eps_storage_scaling = None\n self.Eps_filter_mo = None\n self.Omega = None\n self.Cutoff_radius = None\n self.Ri_metric = None\n self.Num2c_matrix_functions = None\n self.Eps_eigval = None\n self.Check_2c_matrix = None\n self.Calc_cond_num = None\n self.Sqrt_order = None\n self.Eps_lanczos = None\n self.Eps_pgf_orb = None\n self.Max_iter_lanczos = None\n self.Ri_flavor = None\n self.Min_block_size = None\n self.Min_block_size_mo = None\n self.Memory_cut = None\n self.LOCALIZE = _localize4()\n self.RI_INFO = _ri_info4()\n self._name = \"RI\"\n self._keywords = {'Eps_filter': 'EPS_FILTER', 'Eps_filter_2c': 'EPS_FILTER_2C', 'Eps_storage_scaling': 'EPS_STORAGE_SCALING', 'Eps_filter_mo': 'EPS_FILTER_MO', 'Omega': 'OMEGA', 'Cutoff_radius': 'CUTOFF_RADIUS', 'Ri_metric': 'RI_METRIC', 'Num2c_matrix_functions': '2C_MATRIX_FUNCTIONS', 'Eps_eigval': 'EPS_EIGVAL', 'Check_2c_matrix': 'CHECK_2C_MATRIX', 'Calc_cond_num': 'CALC_COND_NUM', 'Sqrt_order': 'SQRT_ORDER', 'Eps_lanczos': 'EPS_LANCZOS', 'Eps_pgf_orb': 'EPS_PGF_ORB', 'Max_iter_lanczos': 'MAX_ITER_LANCZOS', 'Ri_flavor': 'RI_FLAVOR', 'Min_block_size': 'MIN_BLOCK_SIZE', 'Min_block_size_mo': 'MIN_BLOCK_SIZE_MO', 'Memory_cut': 'MEMORY_CUT'}\n self._subsections = {'LOCALIZE': 'LOCALIZE', 'RI_INFO': 'RI_INFO'}\n self._aliases = {'Calc_condition_number': 'Calc_cond_num'}\n self._attributes = ['Section_parameters']\n\n\n @property\n def Calc_condition_number(self):\n \"\"\"\n See documentation for Calc_cond_num\n \"\"\"\n return self.Calc_cond_num\n\n @Calc_condition_number.setter\n def Calc_condition_number(self, value):\n self.Calc_cond_num = value\n","sub_path":"xcp2k/classes/_ri5.py","file_name":"_ri5.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"452884699","text":"\"\"\"\nGlobal settings.\n\n.. role:: raw-html-m2r(raw)\n :format: html\n\n.. note:: **Please check out the** `git repository `_.\n\n A full list of examples can be found in directories:\n\n - `examples/basic `_ ,\n - `examples/advanced `_ ,\n - `examples/volumetric `_,\n - `examples/simulations `_.\n - `examples/other `_\n - `examples/other/dolfin `_.\n\n:raw-html-m2r:`
`\n\n.. image:: https://user-images.githubusercontent.com/32848391/51558920-ec436e00-1e80-11e9-9d96-aa9b7c72d58b.png\n\n:raw-html-m2r:`
`\n:raw-html-m2r:`
`\n\n\"\"\"\n__all__ = ['datadir', 'embedWindow']\n\n####################################################################################\n# recompute vertex and cell normals\ncomputeNormals = None\n\n# default style is TrackBallCamera\ninteractorStyle = None\n\n# allow to interact with scene during interactor.Start() execution\nallowInteraction = True\n\n# usetex, matplotlib latex compiler\nusetex = False\n\n# Qt embedding\nusingQt = False\n\n# OpenVR\nuseOpenVR = False\n\n# on some vtk versions/platforms points are redered as ugly squares\nrenderPointsAsSpheres = True\n\nrenderLinesAsTubes = False\n\n# remove hidden lines when in wireframe mode\nhiddenLineRemoval = False\n\n#\nvisibleGridEdges = False\n\n# notebook support with K3D\nnotebookBackend = None\nnotebook_plotter = None\n\n# path to Voro++ library\n# http://math.lbl.gov/voro++\nvoro_path = '/usr/local/bin'\n\n# axes titles\nxtitle = 'x'\nytitle = 'y'\nztitle = 'z'\n\n# scale magnification of the screenshot\nscreeshotScale = 1\nscreenshotTransparentBackground = False\n\n\n####################################################################################\nimport os\n_cdir = os.path.dirname(__file__)\nif _cdir == \"\":\n _cdir = \".\"\ntextures_path = _cdir + \"/textures/\"\ntextures = []\n\ndatadir = _cdir + \"/data/\"\nfonts_path = _cdir + \"/fonts/\"\nfonts = []\n\ndef embedWindow(backend='k3d', verbose=True):\n global notebook_plotter, notebookBackend\n\n if not backend:\n notebookBackend = None\n notebook_plotter = None\n return\n\n notebookBackend = backend\n if backend=='k3d':\n\n try:\n get_ipython()\n except:\n notebookBackend = None\n return\n\n try:\n import k3d\n #if verbose:\n # print('INFO: embedWindow(verbose=True), importing k3d module')\n except:\n notebookBackend = None\n if verbose:\n print('embedWindow(verbose=True): could not load k3d module, try:')\n print('> pip install k3d # and/or')\n print('> conda install nodejs')\n\n elif backend=='panel':\n try:\n get_ipython()\n if verbose:\n print('INFO: embedWindow(verbose=True), first import of panel module, this takes time...')\n import panel\n panel.extension('vtk')\n except:\n if verbose:\n print('embedWindow(verbose=True): could not load panel try:')\n print('> pip install panel # and/or')\n print('> conda install nodejs')\n else:\n print(\"Unknown backend\", backend)\n raise RuntimeError()\n\n\n#####################\ndef _init():\n global plotter_instance, plotter_instances, collectable_actors\n global textures, fonts\n global notebookBackend, notebook_plotter\n\n plotter_instance = None\n plotter_instances = []\n collectable_actors = []\n\n for f in os.listdir(textures_path):\n textures.append(f.split(\".\")[0])\n textures.remove(\"earth\")\n textures = list(sorted(textures))\n\n for f in os.listdir(fonts_path):\n fonts.append(f.split(\".\")[0])\n fonts.remove(\"licenses\")\n fonts = list(sorted(fonts))\n\n import warnings\n warnings.simplefilter(action=\"ignore\", category=FutureWarning)\n\n embedWindow()\n\n\n\n","sub_path":"vtkplotter/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"501329467","text":"from django.contrib.auth import get_user_model\nfrom django.test import TestCase\n\nfrom ..models import GameTTT\nfrom common.models import DataCell\n\n\nclass TicTacToeModelTests(TestCase):\n\n def setUp(self):\n self.p1 = get_user_model().objects.create_user('p1')\n self.p2 = get_user_model().objects.create_user('p2')\n\n def test_new_game(self):\n game = GameTTT.new_game(p1=self.p1, p2=self.p2)\n self.assertEqual(game.pk, game.play_id)\n\n def test_play_returns_true(self):\n game = GameTTT.new_game(p1=self.p1, p2=self.p2)\n b = game.play(0, 0)\n self.assertTrue(b)\n\n def test_play_plays_as_player(self):\n game = GameTTT.new_game(p1=self.p1, p2=self.p2)\n\n game.play(0, 0)\n cell1 = DataCell.objects.get(id_game=game.pk, row=0, col=0)\n self.assertEqual(cell1.data, 1)\n self.assertEqual(game.player, 2)\n\n game.play(0, 1)\n cell2 = DataCell.objects.get(id_game=game.pk, row=0, col=1)\n self.assertEqual(cell2.data, 2)\n self.assertEqual(game.player, 1)\n\n def test_check_win(self):\n game = GameTTT.new_game(p1=self.p1, p2=self.p2)\n game.play(0, 0)\n game.play(0, 1)\n game.play(1, 1)\n game.play(1, 2)\n game.play(2, 2)\n self.assertTrue(game.game_over)\n self.assertEqual(game.winner, 1)\n","sub_path":"tic_tac_toe/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"141810683","text":"\"\"\"\n Creating srv records\n\n\"\"\"\nimport twisted\nfrom dockerdns.resolver import DockerResolver\nfrom dockerdns.mappings import DockerMapping\nfrom test import mock_lookup_container, SRV_FMT\nfrom nose import SkipTest\nfrom nose.tools import raises\nfrom nose.twistedtools import deferred as nosedeferred\nfrom test.test_resolver import check_deferred\n\n\nclass TestSrv(object):\n mapping = DockerMapping(db=None)\n mapping.lookup_container = mock_lookup_container\n\n def check_equals(self, a, b, msg=None):\n assert a == b, msg\n\n def setup(self):\n self.resolver = DockerResolver(self.mapping)\n\n def test_nat_all(self):\n host, port = \"foo.docker\", 8080\n ret = self.mapping.get_nat(host, port)\n assert (8080, \"tcp\", 18080, \"0.0.0.0\") in ret, \"ret: %r\" % ret\n\n def test_nat_ports(self):\n expected = [(8080, 18080),\n (9999, 19999), (8787, 8787)]\n\n for pin, pout in expected:\n ret = self.mapping.get_nat(\"foo\", pin)\n _, _, port, _ = next(ret)\n\n yield self.check_equals, port, pout, \"unexpected value in %r\" % ret\n\n @raises(twisted.names.error.DomainError)\n @nosedeferred()\n def harn_lookupService_ko(self, n):\n \"\"\"Harness to run lookup in a deferred\n \"\"\"\n return self.resolver.lookupService(n)\n\n def test_lookupService_ko(self):\n expect_fail = 'nondocker.domain noproto.docker noport.container.docker nonint._tcp.container.docker'.split(\n )\n for n in expect_fail:\n yield self.harn_lookupService_ko, n\n\n def test_lookupService_ok(self):\n ret = self.resolver.lookupService(\"_8080._tcp.jboss631.docker\")\n ret = check_deferred(ret, True)\n print(\"resolved: %r\" % [ret])\n\n def test_mapping(self):\n container = self.mapping.lookup_container(\"foo\")\n\n for local, remote in container['NetworkSettings']['Ports'].items():\n port, proto = local.split(\"/\")\n if not remote:\n continue\n try:\n remote = remote[0]\n except IndexError:\n continue\n\n print(SRV_FMT.format(\n svc=port,\n proto=proto,\n container=container['Name'][1:],\n cclass=\"IN\",\n priority=100,\n weight=100,\n port=remote['HostPort'],\n target=remote['HostIp'] if remote[\n 'HostIp'] != '0.0.0.0' else \"localhost\"\n )\n )\n\n def test_setup(self):\n assert self.resolver\n assert self.resolver.mapping\n assert self.resolver.mapping.db is None\n\n @SkipTest\n def test_service_image(self):\n host = \"impandas.docker\"\n raise NotImplementedError(\"implement skydns-like\")\n","sub_path":"test/test_srv.py","file_name":"test_srv.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"548664039","text":"import csv\nimport pandas as pd\nimport subprocess\nimport os\nimport glob\nimport subprocess\nfrom subprocess import Popen,PIPE\nimport time\n\nN = 1000000\nnum_files = 10\n\nnum_line_per_file = int(N/num_files)\nsplit_files_lists = []\n\nprocs_list = []\nstart = 1\nend = num_line_per_file\n\nfor i in range(num_files):\n\tsplit_input_file = \"input_data_\" + str(i) + \".csv\"\n\tsplit_files_lists.append(split_input_file)\n\tcmd = ['python','generate_input_data.py', split_input_file, str(start), str(end)]\n\tstart = end + 1\n\tend = end + num_line_per_file\n\tprocs_list.append(Popen(cmd, stdout=PIPE, stderr=PIPE))\n\nfor proc in procs_list:\n proc.wait()\n\ncmd_run = \"cat \"\nfor split_input_file in split_files_lists:\n\tcmd_run += split_input_file + \" \"\ncmd_run += \"> \"\ncmd_run += \"input_data.csv\"\n\nos.system(cmd_run)\nprint(\"Completed\")","sub_path":"Similarity_search_input_data_generator.py","file_name":"Similarity_search_input_data_generator.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"209142783","text":"import inspect\nimport importlib\nfrom string import Template\n\nclass Provider(dict):\n def __init__(self, fetchers={}):\n self.fetchers = {}\n self.scoops = {}\n self.options = {}\n self.help = {}\n self.template = {}\n\n return super().__init__({})\n\n def __getitem__(self, item):\n\n try:\n result = super().__getitem__(item)\n except KeyError:\n # restrict python's eval() function -- No builtins, only \"item\" is accessible\n # api = eval('[' + item.replace(']', '],') + ']',\n # {'__builtins__': None},\n # {'item': item})[0][0]\n fetcher = self.fetchers[item].split('.')\n provider = importlib.import_module('.'.join(fetcher[0:2]))\n\n super().__setitem__(item, eval('provider.' +\n Template(fetcher[2]).substitute(self.template)))\n # restrict python's eval() functon -- No builtins, only \"self\" is accessible\n result = self.get(item)\n # result = eval(\"self\" + item, {'__builtins__': None}, {'self': self})\n return result\n\n\ndef cliapi_decor(prov, api_alias=None, scoops={}, options={}, help={}):\n def decorate_it(func):\n if api_alias is None:\n alias = func.__name__\n else:\n alias = api_alias\n # prov.scoops=alias\n prov.scoops.update(scoops)\n prov.options.update(options)\n prov.help.update(help)\n argspec = inspect.getargspec(func)\n if argspec.defaults is None:\n default_count = 0\n else:\n default_count = len(argspec.defaults)\n last_arg = len(argspec.args) - default_count\n argspec_string = '('\n for i, arg in enumerate(argspec.args):\n if i < last_arg:\n # substitute CLI options...\n arg = prov.options.get(arg, arg)\n argspec_string += '\\'' + arg + '\\', '\n else:\n default = argspec.defaults[i - last_arg]\n # substitute CLI options...\n # op_default = prov.options.get(arg, default)\n op_default = prov.options.get(arg, default)\n if op_default.startswith('$'):\n prov.template[op_default[1:]] = default\n argspec_string += arg + '=\\'' + op_default + '\\', '\n\n prov.fetchers.update({alias :\n func.__module__ + '.' +\n func.__name__ +\n argspec_string + ')'\n })\n\n def wrap_it(*args, **kwargs):\n if len(args) == 0:\n a = ()\n else:\n a = args\n if len(kwargs) == 0:\n b = {}\n else:\n b = kwargs\n return func(*a, **b)\n return wrap_it\n\n return decorate_it\n","sub_path":"cliapi_lib.py","file_name":"cliapi_lib.py","file_ext":"py","file_size_in_byte":2944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"224351213","text":"\"\"\"\nEmbedding layers useful for recommender models.\n\"\"\"\n\nfrom torch.nn import Embedding\n\n\nclass ScaledEmbedding(Embedding):\n \"\"\"\n Embedding layer that initializes its values\n to using a normal variable scaled by the inverse\n of the embedding dimension.\n \"\"\"\n\n def reset_parameters(self):\n \"\"\"\n Initialize parameters.\n \"\"\"\n\n self.weight.data.normal_(0, 1.0 / self.embedding_dim)\n if self.padding_idx is not None:\n self.weight.data[self.padding_idx].fill_(0)\n\n\nclass ZeroEmbedding(Embedding):\n \"\"\"\n Embedding layer that initializes its values\n to zero.\n Used for biases.\n \"\"\"\n\n def reset_parameters(self):\n \"\"\"\n Initialize parameters.\n \"\"\"\n\n self.weight.data.zero_()\n if self.padding_idx is not None:\n self.weight.data[self.padding_idx].fill_(0)\n\n\nclass TestEmbedding(Embedding):\n \"\"\"\n Specific Embedding for Test\n\n Parameters\n ----------\n embedding_weights: ndarray\n Embedding's weights for the\n \"\"\"\n def __init__(self,\n num_embeddings,\n embedding_dim,\n padding_idx=None,\n max_norm=None,\n norm_type=2,\n scale_grad_by_freq=False,\n sparse=False,\n embedding_weights=None):\n self._embedding_weights = embedding_weights\n super(TestEmbedding, self).__init__(num_embeddings,\n embedding_dim,\n padding_idx,\n max_norm,\n norm_type,\n scale_grad_by_freq,\n sparse)\n\n def reset_parameters(self):\n \"\"\"\n Initialize parameters.\n \"\"\"\n for i in range(self._embedding_weights.shape[0]):\n for j in range(self._embedding_weights.shape[1]):\n self.weight.data[i, j] = self._embedding_weights[i, j]\n","sub_path":"divmachines/models/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"307249613","text":"# -*- encoding: utf-8 -*-\n# Copyright (C) 2017 TSDV TTEC. All rights reserved.\n\n\nclass PhotoWrap(object):\n NONE = 0\n IN_LINE_WITH_TEXT = 1\n SQUARE = 2\n TIGHT = 3\n THROUGH = 4\n TOP_AND_BOTTOM = 5\n BEHIND_TEXT = 6\n IN_FRONT_OF_TEXT = 7\n\n\ndef convert_photo_wrap(wrap_str):\n wrap_enum = PhotoWrap.NONE\n if wrap_str == 'NONE':\n wrap_enum = PhotoWrap.NONE\n elif wrap_str == 'IN_LINE_WITH_TEXT':\n wrap_enum = PhotoWrap.IN_LINE_WITH_TEXT\n elif wrap_str == 'SQUARE':\n wrap_enum = PhotoWrap.SQUARE\n elif wrap_str == 'TIGHT':\n wrap_enum = PhotoWrap.TIGHT\n elif wrap_str == 'THROUGH':\n wrap_enum = PhotoWrap.THROUGH\n elif wrap_str == 'TOP_AND_BOTTOM':\n wrap_enum = PhotoWrap.TOP_AND_BOTTOM\n elif wrap_str == 'BEHIND_TEXT':\n wrap_enum = PhotoWrap.BEHIND_TEXT\n elif wrap_str == 'IN_FRONT_OF_TEXT':\n wrap_enum = PhotoWrap.IN_FRONT_OF_TEXT\n return wrap_enum\n\n\nclass PageDirection(object):\n \"\"\"\n Related to WritingDirection of OCREngine, the value are the same\n with reference enum\n \"\"\"\n HORIZONTAL = 0\n VERTICAL = 1\n\n\ndef convert_page_direction(page_dir_str):\n page_dir_enum = PageDirection.HORIZONTAL\n if page_dir_str is None or len(page_dir_str) == 0:\n return None\n if page_dir_str == 'HORIZONTAL':\n page_dir_enum = PageDirection.HORIZONTAL\n elif page_dir_str == 'VERTICAL':\n page_dir_enum = PageDirection.VERTICAL\n return page_dir_enum\n\n\nclass LineDirection(object):\n \"\"\"\n Related to TextlineOrder of OCREngine, the value are the same\n with reference enum\n \"\"\"\n LEFT_TO_RIGHT = 0\n RIGHT_TO_LEFT = 1\n TOP_TO_BOTTOM = 2\n\n\ndef convert_line_direction(line_dir_str):\n line_dir_enum = LineDirection.TOP_TO_BOTTOM\n if line_dir_str is None or len(line_dir_str) == 0:\n return None\n if line_dir_str == 'LEFT_TO_RIGHT':\n line_dir_enum = LineDirection.LEFT_TO_RIGHT\n elif line_dir_str == 'RIGHT_TO_LEFT':\n line_dir_enum = LineDirection.RIGHT_TO_LEFT\n elif line_dir_str == 'TOP_TO_BOTTOM':\n line_dir_enum = LineDirection.TOP_TO_BOTTOM\n return line_dir_enum\n\n\nclass CommonDirection(object):\n \"\"\"\n Common direction for using in multiple purpose\n \"\"\"\n ALL = 0\n VERTICAL = 1\n HORIZONTAL = 2\n","sub_path":"Run_PHocr_test/PHOcr_C2404_D3_linux_release/lib/phocroffice/phocr_elements/office_enum.py","file_name":"office_enum.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"34505176","text":"#!/usr/bin/env python\n# created by hwajong 2012.07.23\n\nimport sys\nimport os\nimport time\nimport glob\nimport rutil\nimport rdiff\nfrom subprocess import *\nfrom termcolor import cprint, colored\n\ndef print_usage():\n\tusage = '@@ Usage : %s target-server [remote-dir=`pwd`]' % os.path.basename(sys.argv[0])\n\tcprint(usage, 'yellow', attrs=['bold'])\n\ndef rdiff_dir(host, ip, t_dir):\n\n\tlocal_dir = os.getenv('PWD')\n\tfiles = glob.glob(local_dir + '/*')\n\tfor file in files:\n\t\tif os.path.isdir(file) or not os.path.isfile(file):\n\t\t\tcontinue\n\t\tif file.find('.backup.') != -1 or file.find('.bak') != -1:\n\t\t\t#cprint(\"@ skip - %s\" % (file), 'green')\n\t\t\tcontinue\n\n\t\t#cprint(\"@ %s\" % (file), 'yellow')\n\t\tt_file = os.path.basename(file)\n\t\trdiff.rdiff(host, ip, t_dir, t_file)\n\n\n\n# MAIN --------------------------------\ndef main():\n\targc = len(sys.argv)\n\tif argc < 2 or argc > 3:\n\t\tprint_usage()\n\t\texit(0)\n\n\tt_server = sys.argv[1]\n\n\tremote_dir = ''\n\tif argc == 3:\n\t\tremote_dir = sys.argv[2]\n\telse:\n\t\tremote_dir = os.getenv('PWD')\n\n\tt_infos = rutil.get_t_server_ip(t_server)\n\n\tfor host in sorted(t_infos.keys()):\n\t\tip = t_infos[host]\n\t\tcprint(\"--- rdiff_dir(%s, %s, %s) ---\" % (host, ip, remote_dir), 'green', attrs=['bold'])\n\t\trdiff_dir(host, ip, remote_dir)\n\n\nif __name__ == '__main__':\n\tmain()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"python_script/rdiff_dir.py","file_name":"rdiff_dir.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"595906319","text":"# Copyright 2020 - 2021 MONAI Consortium\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# http://www.apache.org/licenses/LICENSE-2.0\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\nimport logging\nimport os\n\nfrom lib import GenericISegGraphCut, GenericISegGraphcutColdstart, GenericISegSimpleCRF, MyInfer, MyStrategy, MyTrain\nfrom monai.networks.layers import Norm\nfrom monai.networks.nets import UNet\n\nfrom monailabel.interfaces import MONAILabelApp\nfrom monailabel.utils.activelearning import Random\n\nlogger = logging.getLogger(__name__)\n\n\nclass MyApp(MONAILabelApp):\n def __init__(self, app_dir, studies):\n self.network = UNet(\n dimensions=3,\n in_channels=1,\n out_channels=2,\n channels=(16, 32, 64, 128, 256),\n strides=(2, 2, 2, 2),\n num_res_units=2,\n norm=Norm.BATCH,\n )\n\n self.model_dir = os.path.join(app_dir, \"model\")\n self.pretrained_model = os.path.join(self.model_dir, \"pretrained.pt\")\n self.final_model = os.path.join(self.model_dir, \"model.pt\")\n\n self.download(\n [\n (\n self.pretrained_model,\n \"https://api.ngc.nvidia.com/v2/models/nvidia/med/\"\n \"clara_pt_spleen_ct_segmentation/versions/1/files/models/model.pt\",\n ),\n ]\n )\n\n super().__init__(\n app_dir=app_dir,\n studies=studies,\n name=\"Segmentation - Generic\",\n description=\"Active Learning solution to label generic organ\",\n version=2,\n )\n\n def init_infers(self):\n infers = {\n \"segmentation\": MyInfer([self.pretrained_model, self.final_model], self.network),\n \"Coldstart->ISeg+GraphCut\": GenericISegGraphcutColdstart(),\n \"ISeg+GraphCut\": GenericISegGraphCut(),\n \"ISeg+SimpleCRF\": GenericISegSimpleCRF(),\n }\n\n # Simple way to Add deepgrow 2D+3D models for infer tasks\n infers.update(self.deepgrow_infer_tasks(self.model_dir))\n return infers\n\n def init_trainers(self):\n return {\n \"segmentation\": MyTrain(\n self.model_dir, self.network, load_path=self.pretrained_model, publish_path=self.final_model\n )\n }\n\n def init_strategies(self):\n return {\n \"random\": Random(),\n \"first\": MyStrategy(),\n }\n","sub_path":"sample-apps/generic_segmentation/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"322916543","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win-amd64\\egg\\ResultDashboard\\Dashboard\\pyPVConnectionAnalysis.py\n# Compiled at: 2020-03-15 13:05:48\n# Size of source mod 2**32: 11254 bytes\n\"\"\"\nauthor : kapil duwadi\nversion: 0.0.1\n\"\"\"\nimport os, shutil, math\nfrom datetime import timedelta\nfrom datetime import datetime as dt\nfrom ResultDashboard.Dashboard.DateTimeProcessingContainer import *\nfrom ResultDashboard.Dashboard.DSSRiskAnalyzer.pyRisk import *\nfrom ResultDashboard.Dashboard.ReadersContainer import *\nimport toml\n\nclass PVConnection:\n\n def __init__(self, SettingsFile, PVDict, TimeDict, Accept):\n self.Settings = SettingsFile\n self.PVDict = PVDict\n self.TimeDict = TimeDict\n self.Accept = Accept\n self.CreateNewDSSFile()\n\n def ProcessResult(self):\n ExportPath = os.path.join(self.ProjectPath, self.Settings['Active Project'], 'Exports', 'category')\n self.AssetLevelMetrics = ['NVRI', 'LVRI', 'TVRI', 'CRI', 'TE', 'LE', 'TLOF', 'TOG']\n self.SystemMetrics = ['SARDI_voltage', 'SARDI_line', 'SARDI_transformer', 'SARDI_aggregated', 'SE_line',\n 'SE_transformer', 'SE', 'SALOF_transformer', 'SOG']\n BaseData = ReadFromFile(os.path.join(ExportPath, 'Base', 'SystemLevelMetrics.csv'))\n BaseDataDict = dict(zip(list(BaseData['Metrics']), list(BaseData['Values'])))\n NewData = ReadFromFile(os.path.join(ExportPath, 'Temporary', 'SystemLevelMetrics.csv'))\n NewDataDict = dict(zip(list(NewData['Metrics']), list(NewData['Values'])))\n RiskMetricDiff = (NewDataDict['SARDI_aggregated'] - BaseDataDict['SARDI_aggregated']) / 14.4\n OvergenerationDiff = (NewDataDict['SOG'] - BaseDataDict['SOG']) / 1152\n EnergyLossDiff = NewDataDict['SE'] - BaseDataDict['SE']\n return (\n RiskMetricDiff, OvergenerationDiff, EnergyLossDiff)\n\n def ProcessForDifferenceinParameters(self):\n ExportPath = os.path.join(self.ProjectPath, self.Settings['Active Project'], 'Exports', 'category')\n voltageBase = ReadFromFile(os.path.join(ExportPath, 'Base', 'voltagemagAssetTimeSeries.csv'))\n lineBase = ReadFromFile(os.path.join(ExportPath, 'Base', 'lineloadingAssetTimeSeries.csv'))\n transformerBase = ReadFromFile(os.path.join(ExportPath, 'Base', 'transformerloadingAssetTimeSeries.csv'))\n voltageTemporary = ReadFromFile(os.path.join(ExportPath, 'Temporary', 'voltagemagAssetTimeSeries.csv'))\n lineTemporary = ReadFromFile(os.path.join(ExportPath, 'Temporary', 'lineloadingAssetTimeSeries.csv'))\n transformerTemporary = ReadFromFile(os.path.join(ExportPath, 'Temporary', 'transformerloadingAssetTimeSeries.csv'))\n voltageDiffDict, voltageDict = {}, {}\n for columnname in list(voltageBase.columns):\n Difference = [x[1] - x[0] for x in zip(list(voltageBase[columnname]), list(voltageTemporary[columnname]))]\n voltageDiffDict[columnname] = max(Difference)\n voltageDict[columnname] = voltageBase[columnname].tolist()[Difference.index(max(Difference))]\n\n lineDiffDict, lineDict = {}, {}\n for columnname in list(lineBase.columns):\n Difference = [x[1] - x[0] for x in zip(list(lineBase[columnname]), list(lineTemporary[columnname]))]\n lineDiffDict[columnname] = max(Difference)\n lineDict[columnname] = lineBase[columnname].tolist()[Difference.index(max(Difference))]\n\n transformerDiffDict, transformerDict = {}, {}\n for columnname in list(transformerBase.columns):\n Difference = [x[1] - x[0] for x in zip(list(transformerBase[columnname]), list(transformerTemporary[columnname]))]\n transformerDiffDict[columnname] = max(Difference)\n transformerDict[columnname] = transformerBase[columnname].tolist()[Difference.index(max(Difference))]\n\n return (\n voltageDiffDict, lineDiffDict, transformerDiffDict, voltageDict, lineDict, transformerDict)\n\n def CreateNewDSSFile(self):\n self.WorkingPath = os.path.join(self.Settings['Project Path'], self.Settings['Active Project'], 'PVConnection')\n self.ProjectPath = os.path.join(self.Settings['Project Path'], self.Settings['Active Project'], 'PVConnection', 'Projects')\n if os.path.exists(self.ProjectPath):\n shutil.rmtree(self.ProjectPath)\n if not os.path.exists(os.path.join(self.WorkingPath, 'Temporary')):\n os.mkdir(os.path.join(self.WorkingPath, 'Temporary'))\n for file in os.listdir(os.path.join(self.WorkingPath, 'Base')):\n shutil.copy(os.path.join(self.WorkingPath, 'Base', file), os.path.join(self.WorkingPath, 'Temporary'))\n\n self.AddPVSystem(os.path.join(self.WorkingPath, 'Temporary'), 'load.dss', 'PVsystem.dss', self.PVDict)\n self.RunPowerFlow()\n\n def RunPowerFlow(self):\n Hour, Minute, Second = self.TimeDict['Time'].split(':')\n Hour, Minute, Second = int(float(Hour)), int(float(Minute)), int(float(Second))\n Day = dt.strptime(self.TimeDict['Day'].split(' ')[0], '%Y-%m-%d')\n startdate = dt(Day.year, Day.month, Day.day, Hour, Minute, Second)\n if self.TimeDict['Mode'] == 'Snapshot':\n enddate = startdate + timedelta(minutes=(self.Settings['Time Step (min)']))\n aggregate_time = self.Settings['Time Step (min)']\n if self.TimeDict['Mode'] == 'Daily':\n enddate = startdate + timedelta(hours=24)\n aggregate_time = self.Settings['Time Step (min)']\n Month = Day.month + 1 if Day.month < 12 else 1\n if self.TimeDict['Mode'] == 'Monthly':\n enddate = dt(Day.year, Month, Day.day, Hour, Minute, Second)\n aggregate_time = 1440\n if self.TimeDict['Mode'] == 'Yearly':\n startdate = dt(Day.year, 1, 1, 0, 0, 0)\n enddate = dt(Day.year, 12, 31, 23, 59, 59)\n aggregate_time = 1440\n os.makedirs(os.path.join(self.ProjectPath, self.Settings['Active Project']))\n shutil.copytree(os.path.join(self.WorkingPath, 'ExtraData'), os.path.join(self.ProjectPath, self.Settings['Active Project'], 'ExtraData'))\n os.mkdir(os.path.join(self.ProjectPath, self.Settings['Active Project'], 'Exports'))\n os.mkdir(os.path.join(self.ProjectPath, self.Settings['Active Project'], 'DSSScenarios'))\n shutil.copytree(os.path.join(self.WorkingPath, 'Base'), os.path.join(self.ProjectPath, self.Settings['Active Project'], 'DSSScenarios', 'Base'))\n shutil.copytree(os.path.join(self.WorkingPath, 'Temporary'), os.path.join(self.ProjectPath, self.Settings['Active Project'], 'DSSScenarios', 'Temporary'))\n os.makedirs(os.path.join(self.ProjectPath, self.Settings['Active Project'], 'AnalysisScenarios', 'Category'))\n BaseSettingsDict = ReadFromFile(os.path.join(self.WorkingPath, 'settings.toml'))\n BaseSettingsDict['Project path'] = self.ProjectPath\n BaseSettingsDict['Active_Scenario'] = 'category'\n BaseSettingsDict['start_time'] = dt.strftime(startdate, '%Y/%m/%d %H:%M:%S')\n BaseSettingsDict['stop_time'] = dt.strftime(enddate, '%Y/%m/%d %H:%M:%S')\n BaseSettingsDict['Risk_metric_aggregate_minutes'] = aggregate_time\n TomlStrings = toml.dumps(BaseSettingsDict)\n TextFile = open(os.path.join(self.ProjectPath, self.Settings['Active Project'], 'AnalysisScenarios', 'Category', 'settings.toml'), 'w')\n TextFile.write(TomlStrings)\n TextFile.close()\n RunRiskAnalysis(os.path.join(self.ProjectPath, self.Settings['Active Project'], 'AnalysisScenarios', 'Category', 'settings.toml'))\n\n def AddPVSystem(self, RootPath, LoadDSS, PVDSS, PVdict):\n Phases = 1 if PVdict['Phases'] != 'RYB' else 3\n Phase2NumDict = {'R':1, 'Y':2, 'B':3}\n LineToAdd = ['new',\n 'pvsystem.{}'.format(PVdict['LoadName']),\n 'irradiance={}'.format(PVdict['Irradiance']),\n 'kva={}'.format(float(PVdict['Capacity'] * PVdict['InverterOverSizeFactor'])),\n 'pmpp={}'.format(float(PVdict['Capacity'])),\n 'kvar={}'.format(PVdict['KVAR']),\n '%cutin={}'.format(PVdict['CutIn']),\n '%cutout={}'.format(PVdict['CutOut']),\n 'yearly={}'.format(PVdict['Profile'])]\n with open(os.path.join(RootPath, LoadDSS)) as (fp):\n readline = fp.readline()\n while readline:\n linecontent = str(readline.strip())\n if PVdict['LoadName'].lower() in linecontent.lower():\n linecontentlist = linecontent.split(' ')\n for element in linecontentlist:\n if 'bus1=' in element:\n Bus1string = element\n if 'kv=' in element:\n kvstring = element\n if 'phases=' in element:\n phasestring = element\n\n break\n readline = fp.readline()\n\n fp.close()\n if Phases >= float(phasestring.split('=')[1]):\n LineToAdd.append(Bus1string)\n LineToAdd.append(phasestring)\n LineToAdd.append(kvstring)\n if Phases < float(phasestring.split('=')[1]):\n LineToAdd.append(Bus1string.split('.')[0] + '.' + Phase2NumDict[PVdict['Phases']] + '.0')\n LineToAdd.append('phase={}'.format(Phases))\n LineToAdd.append('kv={}'.format(float(kvstring.split('=')[1]) / math.sqrt(3)))\n LineString = ' '.join(LineToAdd)\n newfile = open(os.path.join(RootPath, PVDSS), 'w')\n newfile.write(LineString)\n newfile.close()\n\n\nif __name__ == '__main__':\n SettingsFile = ReadFromFile('C:\\\\Users\\\\KDUWADI\\\\Desktop\\\\NREL_Projects\\\\CIFF-TANGEDCO\\\\TANGEDCO\\\\SoftwareTools\\\\VisualizingInDashboard\\\\Projects\\\\settings.toml')\n PVDict = {'LoadName':'gwclt12', 'Irradiance':0.98, 'Capacity':5, 'InverterOverSizeFactor':0.9, 'KVAR':0, 'CutIn':0.05, 'CutOut':0.05, 'Profile':'solarmult', 'Phases':'RYB'}\n TimeDict = {'Mode':'Daily', 'Time':'5:00:00', 'Day':'2018-1-1 0:0:0'}\n a = PVConnection(SettingsFile, PVDict, TimeDict)\n b, c, d = a.ProcessForDifferenceinParameters()\n print(b)\n print(c)\n print(d)","sub_path":"pycfiles/EMeRGE-1.4a0-py3.7/pyPVConnectionAnalysis.cpython-37.py","file_name":"pyPVConnectionAnalysis.cpython-37.py","file_ext":"py","file_size_in_byte":10296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"350508051","text":"import os\n\npath=input('path of the folder: ')\nos.chdir(path)\nfo=open(\"All_Contents.txt\",\"a\")\nexception=['System Volume Information','$RECYCLE.BIN'] \ndef print_directory(path):\n root_dir=os.listdir(path)\n for content in root_dir:\n fo.write(str(content)+\"\\n\")\n if content in exception:\n continue\n if os.path.isdir(path+\"\\\\\"+content):\n fo.write(\"\\n\")\n print_directory(path+\"\\\\\"+content)\n fo.write(\"\\n\")\n\nprint_directory(path) \nfo.close() \n \n \n","sub_path":"all_directory_in_folder.py","file_name":"all_directory_in_folder.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"156596791","text":"# Copyright 2020- Robot Framework Foundation\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.\nimport json\nimport os\nimport re\nimport shutil\nimport string\nimport sys\nimport time\nfrom concurrent.futures._base import Future\nfrom datetime import timedelta\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Set, Union\n\nfrom assertionengine import AssertionOperator\nfrom overrides import overrides\nfrom robot.libraries.BuiltIn import EXECUTION_CONTEXTS, BuiltIn # type: ignore\nfrom robot.result.model import TestCase as TestCaseResult # type: ignore\nfrom robot.running.model import TestCase as TestCaseRunning # type: ignore\nfrom robot.utils import secs_to_timestr, timestr_to_secs # type: ignore\nfrom robotlibcore import DynamicCore # type: ignore\n\nfrom .base import ContextCache, LibraryComponent\nfrom .generated.playwright_pb2 import Request\nfrom .keywords import (\n Control,\n Cookie,\n Devices,\n Evaluation,\n Getters,\n Interaction,\n Network,\n PlaywrightState,\n Promises,\n RunOnFailureKeywords,\n Waiter,\n WebAppState,\n)\nfrom .keywords.crawling import Crawling\nfrom .playwright import Playwright\nfrom .utils import AutoClosingLevel, is_falsy, is_same_keyword, keyword, logger\n\n# Importing this directly from .utils break the stub type checks\nfrom .utils.data_types import DelayedKeyword, SupportedBrowsers\nfrom .version import __version__ as VERSION\n\n\nclass Browser(DynamicCore):\n \"\"\"Browser library is a browser automation library for Robot Framework.\n\n This is the keyword documentation for Browser library. For information\n about installation, support, and more please visit the\n [https://github.com/MarketSquare/robotframework-playwright|project pages].\n For more information about Robot Framework itself, see [https://robotframework.org|robotframework.org].\n\n Browser library uses\n [https://github.com/microsoft/playwright|Playwright Node module]\n to automate [https://www.chromium.org/Home|Chromium],\n [https://www.mozilla.org/en-US/firefox/new/|Firefox]\n and [https://webkit.org/|WebKit] with a single library.\n\n\n == Table of contents ==\n\n %TOC%\n\n = Browser, Context and Page =\n\n Browser library works with three different layers that build on each other:\n *Browser*, *Context* and *Page*.\n\n\n == Browsers ==\n\n A *browser* can be started with one of the three\n different engines Chromium, Firefox or Webkit.\n\n === Supported Browsers ===\n\n | Browser | Browser with this engine |\n | ``chromium`` | Google Chrome, Microsoft Edge (since 2020), Opera |\n | ``firefox`` | Mozilla Firefox |\n | ``webkit`` | Apple Safari, Mail, AppStore on MacOS and iOS |\n\n Since [https://github.com/microsoft/playwright|Playwright] comes with a pack of builtin\n binaries for all browsers, no additional drivers e.g. geckodriver are needed.\n\n All these browsers that cover more than 85% of the world wide used browsers,\n can be tested on Windows, Linux and MacOS.\n Theres is not need for dedicated machines anymore.\n\n A browser process is started ``headless`` (without a GUI) by default.\n Run `New Browser` with specified arguments if a browser with a GUI is requested\n or if a proxy has to be configured.\n A browser process can contain several contexts.\n\n\n == Contexts ==\n\n A *context* corresponds to set of independent incognito pages in a browser\n that share cookies, sessions or profile settings. Pages in two separate\n contexts do not share cookies, sessions or profile settings.\n Compared to Selenium, these do *not* require their own browser process.\n To get a clean environment a test can just open a new context.\n Due to this new independent browser sessions can be opened with\n Robot Framework Browser about 10 times faster than with Selenium by\n just opening a `New Context` within the opened browser.\n\n The context layer is useful e.g. for testing different users sessions on the\n same webpage without opening a whole new browser context.\n Contexts can also have detailed configurations, such as geo-location, language settings,\n the viewport size or color scheme.\n Contexts do also support http credentials to be set, so that basic authentication\n can also be tested. To be able to download files within the test,\n the ``acceptDownloads`` argument must be set to ``True`` in `New Context` keyword.\n A context can contain different pages.\n\n\n == Pages ==\n\n A *page* does contain the content of the loaded web site and has a browsing history.\n Pages and browser tabs are the same.\n\n Typical usage could be:\n | *** Test Cases ***\n | Starting a browser with a page\n | New Browser chromium headless=false\n | New Context viewport={'width': 1920, 'height': 1080}\n | New Page https://marketsquare.github.io/robotframework-browser/Browser.html\n | Get Title == Browser\n\n The `Open Browser` keyword opens a new browser, a new context and a new page.\n This keyword is useful for quick experiments or debugging sessions.\n\n When a `New Page` is called without an open browser, `New Browser`\n and `New Context` are executed with default values first.\n\n Each Browser, Context and Page has a unique ID with which they can be addressed.\n A full catalog of what is open can be received by `Get Browser Catalog` as dictionary.\n\n = Finding elements =\n\n All keywords in the library that need to interact with an element\n on a web page take an argument typically named ``selector`` that specifies\n how to find the element.\n\n Selector strategies that are supported by default are listed in the table\n below.\n\n | = Strategy = | = Match based on = | = Example = |\n | ``css`` | CSS selector. | ``css=.class > \\\\#login_btn`` |\n | ``xpath`` | XPath expression. | ``xpath=//input[@id=\"login_btn\"]`` |\n | ``text`` | Browser text engine. | ``text=Login`` |\n | ``id`` | Element ID Attribute. | ``id=login_btn`` |\n\n CSS Selectors can also be recorded with `Record selector` keyword.\n\n == Explicit Selector Strategy ==\n\n The explicit selector strategy is specified with a prefix using syntax\n ``strategy=value``. Spaces around the separator are ignored, so\n ``css=foo``, ``css= foo`` and ``css = foo`` are all equivalent.\n\n\n == Implicit Selector Strategy ==\n\n *The default selector strategy is `css`.*\n\n If selector does not contain one of the know explicit selector strategies, it is\n assumed to contain css selector.\n\n Selectors that are starting with ``//`` or ``..`` are considered as xpath selectors.\n\n Selectors that are in quotes are considered as text selectors.\n\n Examples:\n\n | # CSS selectors are default.\n | `Click` span > button.some_class # This is equivalent\n | `Click` css=span > button.some_class # to this.\n |\n | # // or .. leads to xpath selector strategy\n | `Click` //span/button[@class=\"some_class\"]\n | `Click` xpath=//span/button[@class=\"some_class\"]\n |\n | # \"text\" in quotes leads to exact text selector strategy\n | `Click` \"Login\"\n | `Click` text=\"Login\"\n\n\n == CSS ==\n\n As written before, the default selector strategy is `css`. See\n [https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | css selector]\n for more information.\n\n Any malformed selector not starting with ``//`` or ``..`` nor starting and ending\n with a quote is assumed to be a css selector.\n\n Note that ``#`` is a comment character in [https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#ignored-data | Robot Framework syntax] and needs to be\n escaped like ``\\\\#`` to work as a [https://developer.mozilla.org/en-US/docs/Web/CSS/ID_selectors | css ID selector].\n\n Examples:\n | `Click` span > button.some_class\n | `Get Text` \\\\#username_field == George\n\n\n == XPath ==\n\n XPath engine is equivalent to [https://developer.mozilla.org/en/docs/Web/API/Document/evaluate|Document.evaluate].\n Example: ``xpath=//html/body//span[text()=\"Hello World\"]``.\n\n Malformed selector starting with ``//`` or ``..`` is assumed to be an xpath selector.\n For example, ``//html/body`` is converted to ``xpath=//html/body``. More\n examples are displayed in `Examples`.\n\n Note that xpath does not pierce [https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM|shadow_roots].\n\n\n == Text ==\n\n Text engine finds an element that contains a text node with the passed text.\n For example, ``Click text=Login`` clicks on a login button, and\n ``Wait For Elements State text=\"lazy loaded text\"`` waits for the \"lazy loaded text\"\n to appear in the page.\n\n Text engine finds fields based on their labels in text inserting keywords.\n\n Malformed selector starting and ending with a quote (either ``\"`` or ``'``) is assumed\n to be a text selector. For example, ``Click \"Login\"`` is converted to ``Click text=\"Login\"``.\n Be aware that these leads to exact matches only!\n More examples are displayed in `Examples`.\n\n\n === Insensitive match ===\n\n By default, the match is case-insensitive, ignores leading/trailing whitespace and\n searches for a substring. This means ``text= Login`` matches\n ````.\n\n === Exact match ===\n\n Text body can be escaped with single or double quotes for precise matching,\n insisting on exact match, including specified whitespace and case.\n This means ``text=\"Login \"`` will only match ```` with exactly\n one space after \"Login\". Quoted text follows the usual escaping rules, e.g.\n use ``\\\\\"`` to escape double quote in a double-quoted string: ``text=\"foo\\\\\"bar\"``.\n\n === RegEx ===\n\n Text body can also be a JavaScript-like regex wrapped in / symbols.\n This means ``text=/^hello .*!$/i`` or ``text=/^Hello .*!$/`` will match ``Hello Peter Parker!``\n with any name after ``Hello``, ending with ``!``.\n The first one flagged with ``i`` for case-insensitive.\n See [https://regex101.com/|https://regex101.com] for more information about RegEx.\n\n === Button and Submit Values ===\n\n Input elements of the type button and submit are rendered with their value as text,\n and text engine finds them. For example, ``text=Login`` matches\n ````.\n\n == Cascaded selector syntax ==\n\n Browser library supports the same selector strategies as the underlying\n Playwright node module: xpath, css, id and text. The strategy can either\n be explicitly specified with a prefix or the strategy can be implicit.\n\n A major advantage of Browser is, that multiple selector engines can be used\n within one selector. It is possible to mix XPath, CSS and Text selectors while\n selecting a single element.\n\n Selectors are strings that consists of one or more clauses separated by\n ``>>`` token, e.g. ``clause1 >> clause2 >> clause3``. When multiple clauses\n are present, next one is queried relative to the previous one's result.\n Browser library supports concatination of different selectors seperated by ``>>``.\n\n For example:\n | `Highlight Elements` \"Hello\" >> ../.. >> .select_button\n | `Highlight Elements` text=Hello >> xpath=../.. >> css=.select_button\n\n Each clause contains a selector engine name and selector body, e.g.\n ``engine=body``. Here ``engine`` is one of the supported engines (e.g. css or\n a custom one). Selector ``body`` follows the format of the particular engine,\n e.g. for css engine it should be a [https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | css selector].\n Body format is assumed to ignore leading and trailing white spaces,\n so that extra whitespace can be added for readability. If selector\n engine needs to include ``>>`` in the body, it should be escaped\n inside a string to not be confused with clause separator,\n e.g. ``text=\"some >> text\"``.\n\n Selector engine name can be prefixed with ``*`` to capture element that\n matches the particular clause instead of the last one. For example,\n ``css=article >> text=Hello`` captures the element with the text ``Hello``,\n and ``*css=article >> text=Hello`` (note the *) captures the article element\n that contains some element with the text Hello.\n\n For convenience, selectors in the wrong format are heuristically converted\n to the right format. See `Implicit Selector Strategy`\n\n == Examples ==\n | # queries 'div' css selector\n | Get Element css=div\n |\n | # queries '//html/body/div' xpath selector\n | Get Element //html/body/div\n |\n | # queries '\"foo\"' text selector\n | Get Element text=foo\n |\n | # queries 'span' css selector inside the result of '//html/body/div' xpath selector\n | Get Element xpath=//html/body/div >> css=span\n |\n | # converted to 'css=div'\n | Get Element div\n |\n | # converted to 'xpath=//html/body/div'\n | Get Element //html/body/div\n |\n | # converted to 'text=\"foo\"'\n | Get Element \"foo\"\n |\n | # queries the div element of every 2nd span element inside an element with the id foo\n | Get Element \\\\#foo >> css=span:nth-child(2n+1) >> div\n | Get Element id=foo >> css=span:nth-child(2n+1) >> div\n\n Be aware that using ``#`` as a starting character in Robot Framework would be interpreted as comment.\n Due to that fact a ``#id`` must be escaped as ``\\\\#id``.\n\n == Frames ==\n\n By default, selector chains do not cross frame boundaries. It means that a\n simple CSS selector is not able to select and element located inside an iframe\n or a frameset. For this usecase, there is a special selector ``>>>`` which can\n be used to combine a selector for the frame and a selector for an element\n inside a frame.\n\n Given this simple pseudo html snippet:\n | \n\n Here's a keyword call that clicks the button inside the frame.\n\n | Click id=iframe >>> id=btn\n\n The selectors on the left and right side of ``>>>`` can be any valid selectors.\n The selector clause directly before the frame opener ``>>>`` must select the frame element.\n\n == WebComponents and Shadow DOM ==\n\n Playwright and so also Browser are able to do automatic piercing of Shadow DOMs\n and therefore are the best automation technology when working with WebComponents.\n\n Also other technologies claim that they can handle\n [https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM|Shadow DOM and Web Components].\n However, non of them do pierce shadow roots automatically,\n which may be inconvenient when working with Shadow DOM and Web Components.\n\n For that reason, css engine pierces shadow roots. More specifically, every\n [https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_combinator|Descendant combinator]\n pierces an arbitrary number of open shadow roots, including the implicit descendant combinator\n at the start of the selector.\n\n That means, it is not nessesary to select each shadow host, open its shadow root and\n select the next shadow host until you reach the element that should be controlled.\n\n === CSS:light ===\n\n ``css:light`` engine is equivalent to [https://developer.mozilla.org/en/docs/Web/API/Document/querySelector | Document.querySelector]\n and behaves according to the CSS spec.\n However, it does not pierce shadow roots.\n\n ``css`` engine first searches for elements in the light dom in the iteration order,\n and then recursively inside open shadow roots in the iteration order. It does not\n search inside closed shadow roots or iframes.\n\n Examples:\n\n |
\n |
In the light dom
\n |
In the light dom, but goes into the shadow slot
\n | \n |
\n | \n | In the shadow dom\n | \n |
  • Deep in the shadow
  • \n |
    \n |
    \n |
    \n | \n |
    \n |
    \n\n Note that ```` is not an html element, but rather a shadow root\n created with ``element.attachShadow({mode: 'open'})``.\n\n - Both ``\"css=article div\"`` and ``\"css:light=article div\"`` match the first ``
    In the light dom
    ``.\n - Both ``\"css=article > div\"`` and ``\"css:light=article > div\"`` match two ``div`` elements that are direct children of the ``article``.\n - ``\"css=article .in-the-shadow\"`` matches the ``
    ``, piercing the shadow root, while ``\"css:light=article .in-the-shadow\"`` does not match anything.\n - ``\"css:light=article div > span\"`` does not match anything, because both light-dom ``div`` elements do not contain a ``span``.\n - ``\"css=article div > span\"`` matches the ````, piercing the shadow root.\n - ``\"css=article > .in-the-shadow\"`` does not match anything, because ``
    `` is not a direct child of ``article``\n - ``\"css:light=article > .in-the-shadow\"`` does not match anything.\n - ``\"css=article li#target\"`` matches the ``
  • Deep in the shadow
  • ``, piercing two shadow roots.\n\n === text:light ===\n\n ``text`` engine open pierces shadow roots similarly to ``css``, while ``text:light`` does not.\n Text engine first searches for elements in the light dom in the iteration order, and then\n recursively inside open shadow roots in the iteration order. It does not search inside\n closed shadow roots or iframes.\n\n === id, data-testid, data-test-id, data-test and their :light counterparts ===\n\n Attribute engines are selecting based on the corresponding attribute value.\n For example: ``data-test-id=foo`` is equivalent to ``css=[data-test-id=\"foo\"]``,\n and ``id:light=foo`` is equivalent to ``css:light=[id=\"foo\"]``.\n\n == Element reference syntax ==\n\n It is possible to get a reference to an element by using `Get Element` keyword. This\n reference can be used as a *first* part of a selector by using a special selector\n syntax `element=` like this:\n\n | ${ref}= Get Element .some_class\n | Click element=${ref} >> .some_child\n\n The `.some_child` selector in the example is relative to the element referenced by ${ref}.\n\n = Assertions =\n\n Keywords that accept arguments ``assertion_operator`` <`AssertionOperator`> and ``assertion_expected``\n can optionally assert that a specified condition holds. Keywords will return the value even when the\n assertion is performed by the keyword.\n\n Assert will retry and fail only after a specified timeout.\n See `Importing` and ``retry_assertions_for`` (default is 1 second) for configuring this timeout.\n\n\n %ASSERTION_TABLE%\n\n By default keywords will provide an error message if an assertion fails.\n Default error message can be overwritten with a ``message`` argument.\n The ``message`` argument accepts `{value}`, `{value_type}`, `{expected}` and\n `{expected_type}` [https://docs.python.org/3/library/stdtypes.html#str.format|format]\n options.\n The `{value}` is value returned by the keyword and the `{expected}`\n is expected value defined by the user, usually value in the\n ``assertion_expected`` argument. The `{value_type}` and\n `{expected_type}` are the type definitions from `{value}` and `{expected}`\n arguments. In similar fashion as Python\n [https://docs.python.org/3/library/functions.html#type|type] returns type definition.\n Assertions will retry until ``timeout`` has expired if they do not pass.\n\n The assertion ``assertion_expected`` value is not converted by the library and\n is used as is. Therefore when assertion is made, the ``assertion_expected``\n argument value and value returned the keyword must have same type. If types\n are not same, assertion will fail. Example `Get Text` always returns a string\n and has to be compared with a string, even the returned value might look like\n a number.\n\n Other Keywords have other specific types they return.\n `Get Element Count` always returns an integer.\n `Get Bounding Box` and `Get Viewport Size` can be filtered.\n They return a dictionary without filter and a number when filtered.\n These Keywords do automatic conversion for the expected value if a number is returned.\n\n * < less or greater > With Strings*\n Compairisons of strings with ``greater than`` or ``less than`` compares each character,\n starting from 0 reagarding where it stands in the code page.\n Example: ``A < Z``, ``Z < a``, ``ac < dc`\n It does never compare the length of elements. Neither lists nor strings.\n The comparison stops at the first character that is different.\n Examples: ``'abcde' < 'abd'``, ``'100.000' < '2'``\n In Python 3 and therefore also in Browser it is not possible to compare numbers\n with strings with a greater or less operator.\n On keywords that return numbers, the given expected value is automatically\n converted to a number before comparison.\n\n\n The getters `Get Page State` and `Get Browser Catalog` return a dictionary. Values of the dictionary can directly asserted.\n Pay attention of possible types because they are evaluated in Python. For example:\n\n | Get Page State validate 2020 >= value['year'] # Compairsion of numbers\n | Get Page State validate \"IMPORTANT MESSAGE!\" == value['message'] # Compairsion of strings\n\n == The 'then' or 'evaluate' closure ==\n\n Keywords that accept arguments ``assertion_operator`` and ``assertion_expected``\n can optionally also use ``then`` or ``evaluate`` closure to modify the returned value with\n BuiltIn Evaluate. Actual value can be accessed with ``value``.\n\n For example ``Get Title then 'TITLE: '+value``.\n See\n [https://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Evaluating%20expressions|\n Builtin Evaluating expressions]\n for more info on the syntax.\n\n == Examples ==\n\n | # *Keyword* *Selector* *Key* *Assertion Operator* *Assertion Expected*\n | Get Title equal Page Title\n | Get Title ^= Page\n | Get Style //*[@id=\"div-element\"] width > 100\n | Get Title matches \\\\\\\\w+\\\\\\\\s\\\\\\\\w+\n | Get Title validate value == \"Login Page\"\n | Get Title evaluate value if value == \"some value\" else \"something else\"\n\n = Automatic page and context closing =\n\n %AUTO_CLOSING_LEVEL%\n\n = Implicit waiting =\n\n Browser library and Playwright have many mechanisms to help in waiting for elements.\n Playwright will auto-wait before performing actions on elements.\n Please see [https://playwright.dev/docs/actionability/ | Auto-waiting on Playwright documentation]\n for more information.\n\n On top of Playwright auto-waiting Browser assertions will wait and retry\n for specified time before failing any `Assertions`.\n Time is specified in Browser library initialization with ``retry_assertions_for``.\n\n Browser library also includes explicit waiting keywords such as `Wait for Elements State`\n if more control for waiting is needed.\n\n = Experimental: Re-using same node process =\n\n Browser library integrated nodejs and python. NodeJS side can be also executed as a standalone process.\n Browser libraries running on the same machine can talk to that instead of starting new node processes.\n This can speed execution when running tests parallel.\n To start node side run on the directory when Browser package is\n ``PLAYWRIGHT_BROWSERS_PATH=0 node Browser/wrapper/index.js PORT``.\n ``PORT`` is port you want to use for the node process.\n To execute tests then with pabot for example do ``ROBOT_FRAMEWORK_BROWSER_NODE_PORT=PORT pabot ..``.\n\n = Extending Browser library with a JavaScript module =\n\n Browser library can be extended with JavaScript. Module must be in CommonJS format that Node.js uses.\n You can translate your ES6 module to Node.js CommonJS style with Babel. Many other languages\n can be also translated to modules that can be used from Node.js. For example TypeScript, PureScript and\n ClojureScript just to mention few.\n\n | async function myGoToKeyword(page, args, logger, playwright) {\n | logger(args.toString())\n | playwright.coolNewFeature()\n | return await page.goto(args[0]);\n | }\n\n ``page``: [https://playwright.dev/docs/api/class-page|the playwright Page object].\n\n ``args``: list of strings from Robot Framework keyword call.\n\n !! A BIT UNSTABLE AND SUBJECT TO API CHANGES !!\n ``logger``: callback function that takes strings as arguments and writes them to robot log. Can be called multiple times.\n\n ``playwright``: playwright module (* from 'playwright'). Useful for integrating with Playwright features that Browser library doesn't support with it's own keywords. [https://playwright.dev/docs/api/class-playwright| API docs]\n\n == Example module.js ==\n\n | async function myGoToKeyword(page, args) {\n | await page.goto(args[0]);\n | return await page.title();\n | }\n | exports.__esModule = true;\n | exports.myGoToKeyword = myGoToKeyword;\n\n == Example Robot Framework side ==\n\n | *** Settings ***\n | Library Browser jsextension=${CURDIR}/module.js\n |\n | *** Test Cases ***\n | Hello\n | New Page\n | ${title}= myGoToKeyword https://playwright.dev\n | Should be equal ${title} Playwright\n\n Also selector syntax can be extended withm custom selector with a js module\n\n == Example module keyword for custom selector registerin ==\n\n | async function registerMySelector(page, args, log, playwright) {\n | playwright.selectors.register(\"myselector\", () => ({\n | // Returns the first element matching given selector in the root's subtree.\n | query(root, selector) {\n | return root.querySelector(`a[data-title=\"${selector}\"]`);\n | },\n |\n | // Returns all elements matching given selector in the root's subtree.\n | queryAll(root, selector) {\n | return Array.from(root.querySelectorAll(`a[data-title=\"${selector}\"]`));\n | }\n | }));\n | return 1;\n | }\n | exports.__esModule = true;\n | exports.registerMySelector = registerMySelector;\n \"\"\"\n\n ROBOT_LIBRARY_VERSION = VERSION\n ROBOT_LISTENER_API_VERSION = 3\n ROBOT_LIBRARY_LISTENER: \"Browser\"\n ROBOT_LIBRARY_SCOPE = \"GLOBAL\"\n _context_cache = ContextCache()\n _suite_cleanup_done = False\n run_on_failure_keyword: Optional[DelayedKeyword] = None\n\n def __init__(\n self,\n timeout: timedelta = timedelta(seconds=10),\n enable_playwright_debug: bool = False,\n auto_closing_level: AutoClosingLevel = AutoClosingLevel.TEST,\n retry_assertions_for: timedelta = timedelta(seconds=1),\n run_on_failure: str = \"Take Screenshot fail-screenshot-{index}\",\n external_browser_executable: Optional[Dict[SupportedBrowsers, str]] = None,\n jsextension: Optional[str] = None,\n enable_presenter_mode: bool = False,\n playwright_process_port: Optional[int] = None,\n ):\n \"\"\"Browser library can be taken into use with optional arguments:\n\n - ``timeout`` \n Timeout for keywords that operate on elements. The keywords will wait\n for this time for the element to appear into the page. Defaults to \"10s\" => 10 seconds.\n - ``enable_playwright_debug`` \n Enable low level debug information from the playwright tool. Mainly\n Useful for the library developers and for debugging purposes.\n - ``auto_closing_level`` < ``TEST`` | ``SUITE`` | ``MANUAL`` >\n Configure context and page automatic closing. Default is ``TEST``,\n for more details, see `AutoClosingLevel`\n - ``retry_assertions_for`` \n Timeout for retrying assertions on keywords before failing the keywords.\n This timeout starts counting from the first failure.\n Global ``timeout`` will still be in effect.\n This allows stopping execution faster to assertion failure when element is found fast.\n - ``run_on_failure`` \n Sets the keyword to execute in case of a failing Browser keyword.\n It can be the name of any keyword. If the keyword has arguments those must be separated with\n two spaces for example ``My keyword \\\\ arg1 \\\\ arg2``.\n If no extra action should be done after a failure, set it to ``None`` or any other robot falsy value.\n - ``external_browser_executable`` >\n Dict mapping name of browser to path of executable of a browser.\n Will make opening new browsers of the given type use the set executablePath.\n Currently only configuring of `chromium` to a separate executable (chrome,\n chromium and Edge executables all work with recent versions) works.\n - ``jsextension`` \n Path to Javascript module exposed as extra keywords. Module must be in CommonJS.\n - ``enable_presenter_mode`` \n Automatic highlights to interacted components, slowMo and a small pause at the end.\n \"\"\"\n self.timeout = self.convert_timeout(timeout)\n self.retry_assertions_for = self.convert_timeout(retry_assertions_for)\n self.ROBOT_LIBRARY_LISTENER = self\n self._execution_stack: List[dict] = []\n self._running_on_failure_keyword = False\n self._pause_on_failure: Set[\"Browser\"] = set()\n self.run_on_failure_keyword = self._parse_run_on_failure_keyword(run_on_failure)\n self.external_browser_executable: Dict[SupportedBrowsers, str] = (\n external_browser_executable or {}\n )\n self._unresolved_promises: Set[Future] = set()\n self._playwright_state = PlaywrightState(self)\n libraries = [\n self._playwright_state,\n Control(self),\n Cookie(self),\n Crawling(self),\n Devices(self),\n Evaluation(self),\n Interaction(self),\n Getters(self),\n Network(self),\n RunOnFailureKeywords(self),\n Promises(self),\n Waiter(self),\n WebAppState(self),\n ]\n self.playwright = Playwright(\n self, enable_playwright_debug, playwright_process_port\n )\n self._auto_closing_level = auto_closing_level\n self.current_arguments = ()\n if jsextension is not None:\n libraries.append(self._initialize_jsextension(jsextension))\n self.presenter_mode = enable_presenter_mode\n DynamicCore.__init__(self, libraries)\n\n @staticmethod\n def _parse_run_on_failure_keyword(\n keyword_with_args: str,\n ) -> Optional[DelayedKeyword]:\n if is_falsy(keyword_with_args):\n return None\n parts = keyword_with_args.split(\" \")\n if len(parts) < 1:\n return None\n return {\"name\": parts[0], \"args\": tuple(parts[1:])}\n\n def _initialize_jsextension(self, jsextension: str) -> LibraryComponent:\n component = LibraryComponent(self)\n with self.playwright.grpc_channel() as stub:\n response = stub.InitializeExtension(\n Request().FilePath(path=os.path.abspath(jsextension))\n )\n for name in response.keywords:\n setattr(component, name, self._jskeyword_call(name))\n return component\n\n def _jskeyword_call(self, name: str):\n @keyword\n def func(*args):\n with self.playwright.grpc_channel() as stub:\n responses = stub.CallExtensionKeyword(\n Request().KeywordCall(name=name, arguments=args)\n )\n for response in responses:\n logger.info(response.log)\n if response.json == \"\":\n return\n return json.loads(response.json)\n\n return func\n\n @property\n def outputdir(self) -> str:\n if EXECUTION_CONTEXTS.current:\n return BuiltIn().get_variable_value(\"${OUTPUTDIR}\")\n else:\n return \".\"\n\n @property\n def browser_output(self) -> Path:\n return Path(self.outputdir, \"browser\")\n\n def _start_suite(self, suite, result):\n if not self._suite_cleanup_done and self.browser_output.is_dir():\n self._suite_cleanup_done = True\n logger.debug(f\"Removing: {self.browser_output}\")\n shutil.rmtree(str(self.browser_output), ignore_errors=True)\n if self._auto_closing_level != AutoClosingLevel.MANUAL:\n try:\n self._execution_stack.append(self.get_browser_catalog())\n except ConnectionError as e:\n logger.debug(f\"Browser._start_suite connection problem: {e}\")\n\n def _start_test(self, test, result):\n if self._auto_closing_level == AutoClosingLevel.TEST:\n try:\n self._execution_stack.append(self.get_browser_catalog())\n except ConnectionError as e:\n logger.debug(f\"Browser._start_test connection problem: {e}\")\n\n def _end_test(self, test: TestCaseRunning, result: TestCaseResult):\n if len(self._unresolved_promises) > 0:\n logger.warn(f\"Waiting unresolved promises at the end of test '{test.name}'\")\n self.wait_for_all_promises()\n if self._auto_closing_level == AutoClosingLevel.TEST:\n if self.presenter_mode:\n logger.debug(\"Presenter mode: Wait for 5 seconds before pruning pages\")\n time.sleep(5.0)\n if len(self._execution_stack) == 0:\n logger.debug(\"Browser._end_test empty execution stack\")\n return\n try:\n catalog_before_test = self._execution_stack.pop()\n self._prune_execution_stack(catalog_before_test)\n except AssertionError as e:\n logger.debug(f\"Test Case: {test.name}, End Test: {e}\")\n except ConnectionError as e:\n logger.debug(f\"Browser._end_test connection problem: {e}\")\n\n def _end_suite(self, suite, result):\n if self._auto_closing_level != AutoClosingLevel.MANUAL:\n if len(self._execution_stack) == 0:\n logger.debug(\"Browser._end_suite empty execution stack\")\n return\n try:\n catalog_before_suite = self._execution_stack.pop()\n self._prune_execution_stack(catalog_before_suite)\n except AssertionError as e:\n logger.debug(f\"Test Suite: {suite.name}, End Suite: {e}\")\n except ConnectionError as e:\n logger.debug(f\"Browser._end_suite connection problem: {e}\")\n\n def _prune_execution_stack(self, catalog_before: dict) -> None:\n catalog_after = self.get_browser_catalog()\n ctx_before_ids = [c[\"id\"] for b in catalog_before for c in b[\"contexts\"]]\n ctx_after_ids = [c[\"id\"] for b in catalog_after for c in b[\"contexts\"]]\n new_ctx_ids = [c for c in ctx_after_ids if c not in ctx_before_ids]\n for ctx_id in new_ctx_ids:\n self._playwright_state.switch_context(ctx_id)\n self._playwright_state.close_context()\n pages_before = [\n (p[\"id\"], c[\"id\"])\n for b in catalog_before\n for c in b[\"contexts\"]\n for p in c[\"pages\"]\n ]\n pages_after = [\n (p[\"id\"], c[\"id\"])\n for b in catalog_after\n for c in b[\"contexts\"]\n for p in c[\"pages\"]\n if c[\"id\"] not in new_ctx_ids\n ]\n new_page_ids = [p for p in pages_after if p not in pages_before]\n for page_id, ctx_id in new_page_ids:\n self._playwright_state.close_page(page_id, ctx_id)\n\n def run_keyword(self, name, args, kwargs=None):\n try:\n return DynamicCore.run_keyword(self, name, args, kwargs)\n except AssertionError as e:\n self.keyword_error()\n if self._pause_on_failure:\n sys.__stdout__.write(f\"\\n[ FAIL ] {e}\")\n sys.__stdout__.write(\n \"\\n[Paused on failure] Press Enter to continue..\\n\"\n )\n sys.__stdout__.flush()\n input()\n raise e\n\n def start_keyword(self, name, attrs):\n \"\"\"Take screenshot of tests that have failed due to timeout.\n\n This method is part of the Listener API implemented by the library.\n\n This can be done with BuiltIn keyword `Run Keyword If Timeout\n Occurred`, but the problem there is that you have to remember to\n put it into your Suite/Test Teardown. Since taking screenshot is\n the most obvious thing to do on failure, let's do it automatically.\n\n This cannot be implemented as a `end_test` listener method, since at\n that time, the teardown has already been executed and browser may have\n been closed already. This implementation will take the screenshot\n before the teardown begins to execute.\n \"\"\"\n self.current_arguments = tuple(attrs[\"args\"])\n if attrs[\"type\"] == \"Teardown\":\n timeout_pattern = \"Test timeout .* exceeded.\"\n test = EXECUTION_CONTEXTS.current.test\n if (\n test is not None\n and test.status == \"FAIL\"\n and re.match(timeout_pattern, test.message)\n ):\n self.screenshot_on_failure(test.name)\n\n def keyword_error(self):\n \"\"\"Runs keyword on failure.\n\n Only works during testing since this uses robot's outputdir for output.\n \"\"\"\n if self._running_on_failure_keyword or not self.run_on_failure_keyword:\n return\n try:\n self._running_on_failure_keyword = True\n if is_same_keyword(self.run_on_failure_keyword[\"name\"], \"Take Screenshot\"):\n args = self.run_on_failure_keyword[\"args\"]\n path = args[0] if args else self._failure_screenshot_path()\n self.take_screenshot(path)\n else:\n BuiltIn().run_keyword(\n self.run_on_failure_keyword[\"name\"],\n *self.run_on_failure_keyword[\"args\"],\n )\n except Exception as err:\n logger.warn(\n f\"Keyword '{self.run_on_failure_keyword['name']}' could not be run on failure:\\n{err}\"\n )\n finally:\n self._running_on_failure_keyword = False\n\n def _failure_screenshot_path(self):\n valid_chars = \"-_.() %s%s\" % (string.ascii_letters, string.digits)\n test_name = BuiltIn().get_variable_value(\"${TEST NAME}\", \"GENERIC\")\n return os.path.join(\n self.outputdir,\n \"\".join(c for c in test_name if c in valid_chars).replace(\" \", \"_\")\n + \"_FAILURE_SCREENSHOT_{index}\",\n )\n\n def get_timeout(self, timeout: Union[timedelta, None]) -> float:\n if timeout is None:\n return self.timeout\n return self.convert_timeout(timeout)\n\n def convert_timeout(\n self, timeout: Union[timedelta, float], to_ms: bool = True\n ) -> float:\n convert = 1000 if to_ms else 1\n if isinstance(timeout, timedelta):\n return timeout.total_seconds() * convert\n return timestr_to_secs(timeout) * convert\n\n def millisecs_to_timestr(self, timeout: float) -> str:\n return secs_to_timestr(timeout / 1000)\n\n @overrides\n def get_keyword_documentation(self, name):\n doc = DynamicCore.get_keyword_documentation(self, name)\n if name == \"__intro__\":\n doc = doc.replace(\"%ASSERTION_TABLE%\", AssertionOperator.__doc__)\n doc = doc.replace(\"%AUTO_CLOSING_LEVEL%\", AutoClosingLevel.__doc__)\n return doc\n","sub_path":"Browser/browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":41373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"568416695","text":"#! /usr/bin/python3\nimport socket\nfrom app import UDP_PORT, ADDRESSES\n\nUDP_IP = ADDRESSES[0]\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nsock.bind((UDP_IP, UDP_PORT))\n\nwhile True:\n data, address = sock.recvfrom(1024)\n print(f\"received message:{data}\")\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"437116048","text":"from tapes import Tape\nfrom bfinterpreter import Interpreter\n\n\ndef get_single_char():\n var = input(\"Input, one letter at a time:\")\n return var\n\n\ninput_tape = Tape(0, None)\nimaginary_tape = Tape(None, None)\nmiddle_tape = (None, None)\noutput_tape = Tape(None, None)\n\n\nvar = get_single_char()\nwhile len(var) > 0:\n input_tape.set(var)\n print(\"input tape: \" + str(input_tape))\n print(\"Sub lists: \" + str(input_tape.sub_lists()))\n var = get_single_char()\n\n","sub_path":"symbolist/TMNN/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"199031592","text":"def main():\n import sys\n input = sys.stdin.readline\n\n N, K = map(int, input().split())\n s = []\n while True:\n n = N % K\n N //= K\n if N == 0 and n == 0:\n break\n s.append(n)\n print(len(s))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"legacy/abc156/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"549949281","text":"#!/usr/bin/python\r\n# York Robotics Kit Python API\r\n#\r\n# Version 0.21\r\n# Utility functions for use with York Robotics Kit\r\n# James Hilder, York Robotics Laboratory, Dec 2020\r\n\r\n\"\"\"\r\n.. module:: utils\r\n :synopsis: Assorted utility functions\r\n\r\n.. moduleauthor:: James Hilder \r\n\r\n\r\n\"\"\"\r\n\r\nimport subprocess, os, timeit, time, datetime, logging\r\nimport yrk.settings as s\r\n\r\ndef i2c_lock():\r\n start_time = time.time()\r\n while(os.path.isfile(s.I2C_LOCK_FILENAME) and (start_time + s.I2C_TIMEOUT > time.time()) ):\r\n time.sleep(0.001)\r\n if(start_time + s.I2C_TIMEOUT > time.time()):\r\n try:\r\n os.mknod(s.I2C_LOCK_FILENAME)\r\n except FileExistsError:\r\n logging.debug(\"Cannot write i2c lock file, retrying\")\r\n i2c_lock()\r\n else:\r\n logging.error(\"I2C Lock timed-out, deleting lock file\")\r\n i2c_unlock()\r\n i2c_lock()\r\n\r\ndef i2c_unlock():\r\n try:\r\n os.remove(s.I2C_LOCK_FILENAME)\r\n except FileNotFoundError:\r\n logging.warning(\"Attempt to remove non-existant I2C lock\")\r\n\r\ndef get_program_filelist():\r\n filelist = [f[:-10] for f in os.listdir(s.PROGRAM_FILEPATH) if (os.path.isfile(os.path.join(s.PROGRAM_FILEPATH, f)) and f.endswith('_apihat.py'))]\r\n logging.debug(filelist)\r\n return filelist\r\n\r\ndef write_prog_state_info(message):\r\n f= open(s.program_info_filename,\"w+\")\r\n f.write(message)\r\n f.close()\r\n\r\ndef request_program(index):\r\n filename = get_program_filelist()[int(index)] + \"_apihat\"\r\n f= open(s.program_request_filename,\"w+\")\r\n f.write(filename)\r\n f.close()\r\n logging.info(\"Wrote %s to %s\" % (filename,s.program_request_filename))\r\n\r\ndef get_audio_filelist():\r\n filelist = [f for f in os.listdir(s.AUDIO_FILEPATH) if (os.path.isfile(os.path.join(s.AUDIO_FILEPATH, f)))]\r\n logging.debug(filelist)\r\n return filelist\r\n\r\ndef decode_time(epoch_seconds):\r\n return datetime.datetime.fromtimestamp(epoch_seconds).strftime('%Y-%m-%d %H:%M:%S.%f')\r\n\r\ndef dynamic_values_to_csv():\r\n update_cpu_load()\r\n mem = get_mem_usage()\r\n return \"%2.1f,%2.1f,%2.1f,%2.1f,%2.1f,%d,%2.1f,%2.1f,%2.1f,%d,%d,%2.2f,%2.2f,%d,%d,%d,%d,%d,%d,%d,%d\" % (cpu_percent_load_array[0][4]*100,cpu_percent_load_array[1][4]*100,cpu_percent_load_array[2][4]*100,cpu_percent_load_array[3][4]*100,cpu_percent_load_array[4][4]*100,get_arm_clockspeed(),get_pcb_temp(),get_cpu_temp(),get_gpu_temp(),mem[0],mem[1],mem[2],get_battery_voltage(),sensors.read_adc(0),sensors.read_adc(1),sensors.read_adc(2),sensors.read_adc(3),arduino.read_encoder(1),arduino.read_encoder(3),arduino.read_encoder(2),arduino.read_encoder(4))\r\n\r\ndef dynamic_values_to_csv_header():\r\n return \"total-cpu-load,cpu-0-load,cpu-1-load,cpu-2-load,cpu-3-load,clock-speed,pcb-temp,cpu-temp,gpu-temp,memory-used,memory-total,memory-used-pct,battery-voltage,analog-1,analog-2,analog-3,analog-4,enc-1-relative,enc-1-cumulative,enc-2-relative,enc-2-cumulative\"\r\n\r\ndef get_battery_voltage():\r\n return 0\r\n #return sensors.read_voltage()\r\n\r\ndef get_pcb_temp():\r\n return 0\r\n #return sensors.read_pcb_temp()\r\n\r\ndef get_ip():\r\n cmd = \"hostname -I | cut -d\\' \\' -f1\"\r\n IP = subprocess.check_output(cmd, shell = True ).strip()\r\n return IP.decode()\r\n\r\ndef get_hostname():\r\n cmd = \"hostname\"\r\n return subprocess.check_output(cmd, shell = True ).strip().decode()\r\n\r\ndef get_cpu_load_using_top():\r\n cmd = \"top -bn1 | grep load | awk '{printf \\\"%.2f\\\", $(NF-2)}'\"\r\n CPU = subprocess.check_output(cmd, shell = True )\r\n return CPU\r\n\r\ntotal_cpu_time = 0\r\ncpu_load_array = [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]]\r\ncpu_percent_load_array = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]\r\n\r\ndef get_cpu_load():\r\n update_cpu_load()\r\n return round(cpu_percent_load_array[0][4] * 1000) / 10\r\n\r\ndef update_cpu_load():\r\n global total_cpu_time, cpu_load_array, cpu_percent_load_array\r\n cmd = \"head -n 5 /proc/stat\"\r\n load = subprocess.check_output(cmd, shell = True ).splitlines()\r\n current_cpu_load = []\r\n for index,line in enumerate(load):\r\n tokens = line.split(b\" \")\r\n offset = 0\r\n if index == 0: offset = 1 #/proc/stat adds double space for overall cpu\r\n user = int(tokens[1+offset])\r\n nice = int(tokens[2+offset])\r\n system = int(tokens[3+offset])\r\n idle = int(tokens[4+offset])\r\n active = user+nice+system\r\n total = active+idle\r\n cpu_line = [user,nice,system,idle,active,total]\r\n current_cpu_load.append(cpu_line)\r\n if current_cpu_load[0][5] > total_cpu_time:\r\n total_cpu_time = current_cpu_load[0][5]\r\n cpu_percent_load_array = []\r\n amend_array = True\r\n for index,line in enumerate(current_cpu_load):\r\n #print(line)\r\n user_dif = line[0] - cpu_load_array[index][0]\r\n nice_dif = line[1] - cpu_load_array[index][1]\r\n system_dif = line[2] - cpu_load_array[index][2]\r\n idle_dif = line[3] - cpu_load_array[index][3]\r\n active_dif = line[4] - cpu_load_array[index][4]\r\n total_dif = line[5] - cpu_load_array[index][5]\r\n if(total_dif > 0):\r\n user_pct = user_dif / total_dif\r\n nice_pct = nice_dif / total_dif\r\n system_pct = system_dif / total_dif\r\n idle_pct = idle_dif / total_dif\r\n active_pct = active_dif / total_dif\r\n pct_line = [user_pct, nice_pct, system_pct, idle_pct, active_pct]\r\n cpu_percent_load_array.append(pct_line)\r\n else: amend_array = False\r\n if amend_array: cpu_load_array = current_cpu_load\r\n return cpu_percent_load_array\r\n\r\ndef get_arm_clockspeed():\r\n cmd = \"/opt/vc/bin/vcgencmd measure_clock arm\"\r\n CSpeed = subprocess.check_output(cmd, shell = True )\r\n cspeed_str = (int(int(CSpeed.split(b\"=\")[1])/1000000))\r\n return cspeed_str\r\n\r\ndef get_gpu_temp():\r\n cmd = \"/opt/vc/bin/vcgencmd measure_temp\"\r\n GPUTemp = subprocess.check_output(cmd, shell = True )\r\n return (float(GPUTemp.split(b\"=\")[1].split(b\"'\")[0]))\r\n\r\ndef get_cpu_temp():\r\n cmd = \"cat /sys/class/thermal/thermal_zone0/temp\"\r\n CPUTemp = subprocess.check_output(cmd, shell = True )\r\n return (round(int(CPUTemp) / 1000,1))\r\n\r\ndef get_mem_usage():\r\n cmd = \"free -m | awk 'NR==2{printf \\\"%s\\\\n%s\\\\n%.2f\\\", $3,$2,$3*100/$2 }'\"\r\n MemUsage = subprocess.check_output(cmd, shell = True ).splitlines()\r\n mem_used = int(MemUsage[0])\r\n mem_total = int(MemUsage[1])\r\n mem_used_pct = float(MemUsage[2])\r\n return [mem_used,mem_total,mem_used_pct]\r\n\r\ndef time_functions():\r\n print(\"Timing how long 100 calls of each function take:\")\r\n print (\"IP: %s\" % get_ip())\r\n print(timeit.timeit(stmt=get_ip, number=100) / .100)\r\n print (\"LOAD: %f \" % get_cpu_load())\r\n print(timeit.timeit(stmt=get_cpu_load, number=100) / .10)\r\n #print (\"TOP LOAD:%s %%\" % get_cpu_load_using_top())\r\n #print(timeit.timeit(stmt=get_cpu_load_using_top, number=10) / .010)\r\n print (\"CLOCK: %d MHz\" % get_arm_clockspeed())\r\n print(timeit.timeit(stmt=get_arm_clockspeed, number=100) / .100)\r\n print (\"GPU: %f C\" % get_gpu_temp())\r\n print(timeit.timeit(stmt=get_gpu_temp, number=100) / .100)\r\n print (\"CPU: %f C\" % get_cpu_temp())\r\n print(timeit.timeit(stmt=get_cpu_temp, number=100) / .100)\r\n print (\"MEMORY: %s \" % get_mem_usage())\r\n print(timeit.timeit(stmt=get_mem_usage, number=100) / .100)\r\n print (\"COMBINED:%s \" % dynamic_values_to_csv())\r\n print(timeit.timeit(stmt=dynamic_values_to_csv, number = 20) / .02)\r\n\r\n\r\n#Command line test [will run when display.py is run directly]\r\nif __name__ == \"__main__\":\r\n time_functions()\r\n while True:\r\n print (dynamic_values_to_csv())\r\n time.sleep(0.5)\r\n os._exit(1)\r\n","sub_path":"yrk/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"233785372","text":"from nba_data.data.player import Player\nfrom nba_data.data.position import Position\n\n\nclass PlayerDetails:\n def __init__(self, player, birth_date, height, weight, jersey_number, position):\n self.player = player\n self.birth_date = birth_date\n self.height = height\n self.weight = weight\n self.jersey_number = jersey_number\n self.position = position\n\n @staticmethod\n def create(nba_id, name, team_id, birth_date, height, weight, jersey_number, position_name):\n return PlayerDetails(player=Player.create(id=nba_id, name=name, team_id=team_id),\n birth_date=birth_date,\n height=height,\n weight=weight,\n jersey_number=jersey_number,\n position=Position.get_position_from_name(position_name))","sub_path":"nba_data/data/player_details.py","file_name":"player_details.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"329289794","text":"\r\n\r\n# not tested completely\r\n\r\nimport numpy as np\r\nfrom rich.console import Console\r\nfrom rich.table import Column, Table\r\n\r\n\r\nclass Board:\r\n def __init__(self,steal = False):\r\n self.board = np.array([[ 4 ,4 ,4 ,4 , 4 , 4] , [ 4 ,4 ,4 ,4 , 4 , 4 ] ])\r\n # score[0] of player 1 score[1] of player 2\r\n self.score_1 = 0\r\n self.score_2 = 0\r\n self.game_still_going = True\r\n self.with_stealing = steal\r\n\r\n self.player_dic = {1 : 1 , 2 : 0}\r\n # 1 means ok 0 means game ended no moves 2 means play again 3 means invalid move\r\n def play(self,player,index):\r\n # index from 0 to 5\r\n\r\n #player2 = 2 and player1 = 1\r\n if not self.game_still_going:\r\n #print('game ended')\r\n return 0\r\n play_again = False\r\n curr_row = self.player_dic[player]\r\n curr_col = index\r\n value_in_cell = self.board[curr_row, curr_col]\r\n if value_in_cell == 0:\r\n return 3\r\n\r\n\r\n self.board[curr_row, curr_col] = 0\r\n v = value_in_cell\r\n while value_in_cell > 0:\r\n if curr_row == 1 and curr_col == 5:\r\n if player == 1:\r\n self.score_1 += 1\r\n value_in_cell -= 1\r\n if value_in_cell == 0:\r\n if self.check_game():\r\n return 0\r\n else:\r\n return 2\r\n\r\n curr_row = 0\r\n curr_col = 5\r\n self.board[curr_row, curr_col] += 1\r\n value_in_cell -= 1\r\n if player == 2:\r\n curr_row = 0\r\n curr_col = 5\r\n\r\n if self.with_stealing and self.board[curr_row, curr_col] == 0 and value_in_cell == 1:\r\n #print('stealing')\r\n self.score_2 += value_in_cell + self.board[1, curr_col]\r\n self.board[1, curr_col] = 0\r\n value_in_cell -= 1\r\n else:\r\n self.board[curr_row, curr_col] += 1\r\n value_in_cell -= 1\r\n continue\r\n if curr_row == 0 and curr_col == 0:\r\n if player == 1:\r\n curr_row = 1\r\n curr_col = 0\r\n if self.with_stealing and self.board[curr_row, curr_col] == 0 and value_in_cell == 1:\r\n #print('stealing')\r\n self.score_1 += value_in_cell + self.board[0, curr_col]\r\n self.board[0, curr_col] = 0\r\n value_in_cell -= 1\r\n else:\r\n self.board[curr_row, curr_col] += 1\r\n value_in_cell -= 1\r\n\r\n if player == 2:\r\n self.score_2 += 1\r\n value_in_cell -= 1\r\n if value_in_cell == 0:\r\n if self.check_game():\r\n return 0\r\n else:\r\n return 2\r\n curr_row = 1\r\n curr_col = 0\r\n self.board[curr_row, curr_col] += 1\r\n value_in_cell -= 1\r\n\r\n continue\r\n if curr_row == 1:\r\n curr_col += 1\r\n\r\n if self.with_stealing and self.board[curr_row, curr_col] == 0 and value_in_cell == 1 and player == 1:\r\n #print('stealing')\r\n self.score_1 += value_in_cell + self.board[0, curr_col]\r\n self.board[0, curr_col] = 0\r\n value_in_cell -= 1\r\n else:\r\n self.board[curr_row,curr_col] += 1\r\n value_in_cell -= 1\r\n continue\r\n if curr_row == 0:\r\n curr_col -= 1\r\n if self.with_stealing and self.board[curr_row, curr_col] == 0 and value_in_cell == 1 and player == 2:\r\n #print('stealing')\r\n self.score_2 += value_in_cell + self.board[1, curr_col]\r\n self.board[1, curr_col] = 0\r\n value_in_cell -= 1\r\n else:\r\n self.board[curr_row,curr_col] += 1\r\n value_in_cell -= 1\r\n continue\r\n\r\n if self.check_game():\r\n return 0\r\n else:\r\n return 1\r\n\r\n def check_game(self):\r\n if np.sum(self.board[0,:]) == 0:\r\n for i in range(6):\r\n self.score_1 += self.board[1,i]\r\n self.game_still_going = False\r\n self.board[1, :] = 0\r\n #print('game ended')\r\n return True\r\n\r\n if np.sum(self.board[1,:]) == 0:\r\n for i in range(6):\r\n self.score_2 += self.board[0,i]\r\n self.game_still_going = False\r\n self.board[0,:] = 0\r\n #print('game ended')\r\n return True\r\n return False\r\n\r\n def draw(self):\r\n table = Table(show_header=True)\r\n table.add_column(\"score 2\")\r\n table.add_column(\"cell 1\")\r\n table.add_column(\"cell 2\")\r\n table.add_column(\"cell 3\")\r\n table.add_column(\"cell 4\")\r\n table.add_column(\"cell 5\")\r\n table.add_column(\"cell 6\")\r\n table.add_column(\"score 1\")\r\n table.add_column(\"players\")\r\n\r\n table.add_row(str(self.score_2) , str(self.board[0,0]) , str(self.board[0,1]) , str(self.board[0,2]) ,str(self.board[0,3]) , str(self.board[0,4]) , str(self.board[0,5]) ,'--' , 'player 2' )\r\n\r\n table.add_row('--', str(self.board[1, 0]), str(self.board[1, 1]), str(self.board[1, 2]),\r\n str(self.board[1, 3]), str(self.board[1, 4]), str(self.board[1, 5]), str(self.score_1) ,'player 1')\r\n\r\n console.print(table)\r\n","sub_path":"board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":5895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"25592816","text":"import requests, time\n\nCAPTCHA_GURU_KEY = 'Your Key'\n\ndef captcha_guru(site_key):\n query = 'https://api.captcha.guru/in.php?key=' + CAPTCHA_GURU_KEY + '&method=userrecaptcha&googlekey=' + site_key + '&pageurl=https://www.inipec.gov.it/cerca-pec/-/pecs/companies'\n try:\n resp = requests.get(query, timeout=300)\n except Exception as e:\n print('Error type:', type(e))\n print('CAPTCHA GURU service error to request:', e)\n return False, 'CAPTCHA GURU service error: ' + str(e)\n\n print(\"CAPTCHA GURU submit request response:\", resp.text);\n if resp.text[0:2] != 'OK':\n print('CAPTCHA GURU service error.\\nError code: \"' + resp.text + '\"')\n return False, resp.text\n captcha_id = resp.text[3:] # OK|2122988149\n fetch_url = \"https://api.captcha.guru/res.php?key=\" + CAPTCHA_GURU_KEY + \"&action=get&id=\" + captcha_id\n # wait till captcha is ready\n for i in range(1, 36): # 36*10 = 360 seconds = 6 min\n time.sleep(3) # wait 10 sec.\n resp = requests.get(fetch_url)\n # print ('Passed', i*10 , 'seconds. AZcap result response: ', resp.text)\n if resp.text[0:2] == 'OK':\n return True, resp.text[3:]\n\n return False, resp.text","sub_path":"captcha_guru.py","file_name":"captcha_guru.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"567612374","text":"import argparse\n\narg_lists = []\nparser = argparse.ArgumentParser()\n\ndef str2bool(v):\n return v.lower() in ('true', '1')\n\ndef add_argument_group(name):\n arg = parser.add_argument_group(name)\n arg_lists.append(arg)\n return arg\n\n# UI\nui_arg = add_argument_group('UI')\nui_arg.add_argument('--operation_mode', type=str, default='Train', choices = ['Train', 'Test'],\n help='The mode which you want to operate. (Train or Test)')\nui_arg.add_argument('--train_mode', type=str, default='Localize', choices = ['Localize'],\n help='The list of the training [Localize/Align/Classify]')\nui_arg.add_argument('--test_mode', type=str, default='Localize', choices = ['Localize'],\n help='The list of the test [Localize/Align/Classify]')\n\n# Load Data\ndata_loader_arg = add_argument_group('data_loader')\ndata_loader_arg.add_argument('--localize_base_path', type=str,\n default='G:\\\\Dataset\\\\NOAA_Right_Whale_Recognition\\\\imgs',\n help='TODO')\ndata_loader_arg.add_argument('--localize_label_path', type=str,\n default='D:\\\\Source\\\\Git\\\\Kaggle_RightWhaleRecognition_DeepSense\\\\data\\\\slot.json',\n help='TODO')\n\n# Train Common\ntrain_common_arg = add_argument_group('train_common')\n\n\n# Localize\nlocalize_hyper_param_arg = add_argument_group('localize_hyper_param')\nlocalize_hyper_param_arg.add_argument('--localize_ensemble_size', type=int, default=6,\n help='TODO')\nlocalize_hyper_param_arg.add_argument('--localize_base_lr', type=float, default=1e-5,\n help='TODO')\nlocalize_hyper_param_arg.add_argument('--localize_minibatch_size', type=int, default=32,\n help='TODO')\nlocalize_hyper_param_arg.add_argument('--localize_image_resize_w', type=int, default=256,\n help='TODO')\nlocalize_hyper_param_arg.add_argument('--localize_image_resize_h', type=int, default=256,\n help='TODO')\nlocalize_hyper_param_arg.add_argument('--localize_validation_image_ratio', type=float, default=0.02,\n help='TODO')\n\nlog_arg = add_argument_group('logging')\nlog_arg.add_argument('--localizer_log', type=str, default = './localizer_log',\n help = 'TODO')\nlog_arg.add_argument('--localizer_checkpoint', type=str, default = '/localizer_checkpoint',\n help = 'TODO')\nlog_arg.add_argument('--localizer_result', type=str, default = '/localizer_result',\n help = 'TODO')\nlog_arg.add_argument('--checkpoint_repository', type=str, default = './checkpoint_repository',\n help = 'TODO')\n# etc\netc_arg = add_argument_group('etc')\netc_arg.add_argument('--log_gpu_info', type=str2bool, default=False,\n help='The boolean value about logging gpu info')\n\ndef get_config():\n config, unparsed = parser.parse_known_args()\n return config, unparsed\n\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"144023733","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# Copyright 2005-2011 TUBITAK/UEKAE\n# Licensed under the GNU General Public License, version 2.\n# See the file http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt\n\nfrom pisi.actionsapi import pisitools\nfrom pisi.actionsapi import get\n\nWorkDir = get.ARCH()\n\ndef install():\n pisitools.dodir(\"/opt\")\n pisitools.insinto(\"/opt\", \"eclipse\")\n\n # Make eclipse icon visible on start menu\n pisitools.insinto(\"/usr/share/pixmaps\", \"%s/opt/eclipse/plugins/org.eclipse.platform_3.6.2.v201101050951/eclipse48.png\" % get.installDIR(), \"eclipse.png\")\n","sub_path":"pardus/tags/2011/programming/environment/eclipse/eclipse/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"226552408","text":"import cv2\nimport os\nimport logging as log\nimport datetime as dt\nfrom time import sleep\nimport time\nimport click\nimport platform\nimport sys\nimport tempfile\nfrom pid.decorator import pidfile\n\n\nclass FaceLock(object):\n\n def __init__(self):\n pass\n\n def lock_screen(self) -> None:\n \"\"\"\n run screen lock command on different platforms\n :return: None\n \"\"\"\n os_type = platform.system()\n if os_type == 'Windows':\n import ctypes\n ctypes.windll.user32.LockWorkStation()\n\n elif os_type == 'Linux':\n os.popen('gnome-screensaver-command --lock > /dev/null &')\n\n elif os_type == 'Darwin':\n os.popen('/System/Library/CoreServices/Menu\\ Extras/user.menu/Contents/Resources/CGSession -suspend')\n else:\n raise Exception('Unsupported OS platform: %s' % os_type)\n\n def run(self, delay_seconds, sleep_seconds, display, always):\n face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\")\n log.basicConfig(level=log.INFO)\n\n video_capture = cv2.VideoCapture(0)\n anterior = 0\n counter = 0\n trigger = int(delay_seconds/sleep_seconds)\n\n while True:\n t1 = time.time()\n if not video_capture.isOpened():\n print('Unable to load camera.')\n sleep(3)\n pass\n\n ret, frame = video_capture.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n faces = face_cascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(50, 50)\n )\n\n if len(faces) < 1:\n counter += 1\n log.info(\"[%s] no face detected, counter=%d\" % (dt.datetime.now(), counter))\n\n if counter > trigger:\n self.lock_screen()\n\n if not always:\n video_capture.release()\n cv2.destroyAllWindows()\n sys.exit()\n\n if anterior != len(faces):\n anterior = len(faces)\n log.info(\"[%s] faces: %d\" % (dt.datetime.now(), len(faces)))\n counter = 0\n\n if display:\n # Draw a rectangle around the faces\n for (x, y, w, h) in faces:\n cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)\n # Display the resulting frame\n frame = cv2.resize(frame, (300, 200))\n cv2.imshow('Face Detection', frame)\n cv2.waitKey(200)\n\n t2 = time.time()\n sleep_time = max(0, sleep_seconds-(t2-t1))\n time.sleep(sleep_time) # Sleep for x second, discounting the running time of the program\n\n\n@pidfile(piddir=os.path.join(tempfile.gettempdir(), sys.argv[0]+'.pid'))\n@click.command()\n@click.option('-t', '--trigger-seconds', default=20,\n help='activate command after this many seconds without detecting a face')\n@click.option('--sleep-seconds', help='sleep every this many seconds', default=0.5)\n@click.option('--display', help='display a webcam window', is_flag=True, default=False)\n@click.option('--always', help='do not exist after screen is locked', is_flag=True, default=False)\ndef main(trigger_seconds, sleep_seconds, display, always):\n \"\"\"\n program entry\n\n :param trigger_seconds:\n :param sleep_seconds:\n :param display:\n :param always:\n :return:\n \"\"\"\n facelock = FaceLock()\n facelock.run(trigger_seconds, sleep_seconds, display, always)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"facelock.py","file_name":"facelock.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"528143633","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /tmp/pip-build-ed191__6/Pygments/pygments/lexers/modeling.py\n# Compiled at: 2020-01-10 16:25:35\n# Size of source mod 2**32: 13409 bytes\n\"\"\"\n pygments.lexers.modeling\n ~~~~~~~~~~~~~~~~~~~~~~~~\n\n Lexers for modeling languages.\n\n :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.\n :license: BSD, see LICENSE for details.\n\"\"\"\nimport re\nfrom pygments.lexer import RegexLexer, include, bygroups, using, default\nfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, Number, Punctuation, Whitespace\nfrom pygments.lexers.html import HtmlLexer\nfrom pygments.lexers import _stan_builtins\n__all__ = [\n 'ModelicaLexer', 'BugsLexer', 'JagsLexer', 'StanLexer']\n\nclass ModelicaLexer(RegexLexer):\n __doc__ = '\\n For `Modelica `_ source code.\\n\\n .. versionadded:: 1.1\\n '\n name = 'Modelica'\n aliases = ['modelica']\n filenames = ['*.mo']\n mimetypes = ['text/x-modelica']\n flags = re.DOTALL | re.MULTILINE\n _name = \"(?:'(?:[^\\\\\\\\']|\\\\\\\\.)+'|[a-zA-Z_]\\\\w*)\"\n tokens = {'whitespace':[\n (\n '[\\\\s\\ufeff]+', Text),\n (\n '//[^\\\\n]*\\\\n?', Comment.Single),\n (\n '/\\\\*.*?\\\\*/', Comment.Multiline)], \n 'root':[\n include('whitespace'),\n (\n '\"', String.Double, 'string'),\n (\n '[()\\\\[\\\\]{},;]+', Punctuation),\n (\n '\\\\.?[*^/+-]|\\\\.|<>|[<>:=]=?', Operator),\n (\n '\\\\d+(\\\\.?\\\\d*[eE][-+]?\\\\d+|\\\\.\\\\d*)', Number.Float),\n (\n '\\\\d+', Number.Integer),\n (\n '(abs|acos|actualStream|array|asin|assert|AssertionLevel|atan|atan2|backSample|Boolean|cardinality|cat|ceil|change|Clock|Connections|cos|cosh|cross|delay|diagonal|div|edge|exp|ExternalObject|fill|floor|getInstanceName|hold|homotopy|identity|inStream|integer|Integer|interval|inverse|isPresent|linspace|log|log10|matrix|max|min|mod|ndims|noClock|noEvent|ones|outerProduct|pre|previous|product|Real|reinit|rem|rooted|sample|scalar|semiLinear|shiftSample|sign|sin|sinh|size|skew|smooth|spatialDistribution|sqrt|StateSelect|String|subSample|sum|superSample|symmetric|tan|tanh|terminal|terminate|time|transpose|vector|zeros)\\\\b',\n Name.Builtin),\n (\n '(algorithm|annotation|break|connect|constant|constrainedby|der|discrete|each|else|elseif|elsewhen|encapsulated|enumeration|equation|exit|expandable|extends|external|firstTick|final|flow|for|if|import|impure|in|initial|inner|input|interval|loop|nondiscrete|outer|output|parameter|partial|protected|public|pure|redeclare|replaceable|return|stream|then|when|while)\\\\b',\n Keyword.Reserved),\n (\n '(and|not|or)\\\\b', Operator.Word),\n (\n '(block|class|connector|end|function|model|operator|package|record|type)\\\\b',\n Keyword.Reserved, 'class'),\n (\n '(false|true)\\\\b', Keyword.Constant),\n (\n 'within\\\\b', Keyword.Reserved, 'package-prefix'),\n (\n _name, Name)], \n 'class':[\n include('whitespace'),\n (\n '(function|record)\\\\b', Keyword.Reserved),\n (\n '(if|for|when|while)\\\\b', Keyword.Reserved, '#pop'),\n (\n _name, Name.Class, '#pop'),\n default('#pop')], \n 'package-prefix':[\n include('whitespace'),\n (\n _name, Name.Namespace, '#pop'),\n default('#pop')], \n 'string':[\n (\n '\"', String.Double, '#pop'),\n (\n '\\\\\\\\[\\\\\\'\"?\\\\\\\\abfnrtv]', String.Escape),\n (\n '(?i)<\\\\s*html\\\\s*>([^\\\\\\\\\"]|\\\\\\\\.)+?(<\\\\s*/\\\\s*html\\\\s*>|(?=\"))',\n using(HtmlLexer)),\n (\n '<|\\\\\\\\?[^\"\\\\\\\\<]+', String.Double)]}\n\n\nclass BugsLexer(RegexLexer):\n __doc__ = '\\n Pygments Lexer for `OpenBugs `_ and WinBugs\\n models.\\n\\n .. versionadded:: 1.6\\n '\n name = 'BUGS'\n aliases = ['bugs', 'winbugs', 'openbugs']\n filenames = ['*.bug']\n _FUNCTIONS = ('abs', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctanh',\n 'cloglog', 'cos', 'cosh', 'cumulative', 'cut', 'density', 'deviance',\n 'equals', 'expr', 'gammap', 'ilogit', 'icloglog', 'integral', 'log',\n 'logfact', 'loggam', 'logit', 'max', 'min', 'phi', 'post.p.value',\n 'pow', 'prior.p.value', 'probit', 'replicate.post', 'replicate.prior',\n 'round', 'sin', 'sinh', 'solution', 'sqrt', 'step', 'tan', 'tanh',\n 'trunc', 'inprod', 'interp.lin', 'inverse', 'logdet', 'mean', 'eigen.vals',\n 'ode', 'prod', 'p.valueM', 'rank', 'ranked', 'replicate.postM',\n 'sd', 'sort', 'sum', 'D', 'I', 'F', 'T', 'C')\n _DISTRIBUTIONS = ('dbern', 'dbin', 'dcat', 'dnegbin', 'dpois', 'dhyper', 'dbeta',\n 'dchisqr', 'ddexp', 'dexp', 'dflat', 'dgamma', 'dgev', 'df',\n 'dggamma', 'dgpar', 'dloglik', 'dlnorm', 'dlogis', 'dnorm',\n 'dpar', 'dt', 'dunif', 'dweib', 'dmulti', 'ddirch', 'dmnorm',\n 'dmt', 'dwish')\n tokens = {'whitespace':[\n (\n '\\\\s+', Text)], \n 'comments':[\n (\n '#.*$', Comment.Single)], \n 'root':[\n include('comments'),\n include('whitespace'),\n (\n '(model)(\\\\s+)(\\\\{)',\n bygroups(Keyword.Namespace, Text, Punctuation)),\n (\n '(for|in)(?![\\\\w.])', Keyword.Reserved),\n (\n '(%s)(?=\\\\s*\\\\()' % '|'.join(_FUNCTIONS + _DISTRIBUTIONS),\n Name.Builtin),\n (\n '[A-Za-z][\\\\w.]*', Name),\n (\n '[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?', Number),\n (\n '\\\\[|\\\\]|\\\\(|\\\\)|:|,|;', Punctuation),\n (\n '<-|~', Operator),\n (\n '\\\\+|-|\\\\*|/', Operator),\n (\n '[{}]', Punctuation)]}\n\n def analyse_text(text):\n if re.search('^\\\\s*model\\\\s*{', text, re.M):\n return 0.7\n else:\n return 0.0\n\n\nclass JagsLexer(RegexLexer):\n __doc__ = '\\n Pygments Lexer for JAGS.\\n\\n .. versionadded:: 1.6\\n '\n name = 'JAGS'\n aliases = ['jags']\n filenames = ['*.jag', '*.bug']\n _FUNCTIONS = ('abs', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctanh',\n 'cos', 'cosh', 'cloglog', 'equals', 'exp', 'icloglog', 'ifelse',\n 'ilogit', 'log', 'logfact', 'loggam', 'logit', 'phi', 'pow', 'probit',\n 'round', 'sin', 'sinh', 'sqrt', 'step', 'tan', 'tanh', 'trunc',\n 'inprod', 'interp.lin', 'logdet', 'max', 'mean', 'min', 'prod',\n 'sum', 'sd', 'inverse', 'rank', 'sort', 't', 'acos', 'acosh', 'asin',\n 'asinh', 'atan', 'T', 'I')\n _DISTRIBUTIONS = tuple('[dpq]%s' % x for x in ('bern', 'beta', 'dchiqsqr', 'ddexp',\n 'dexp', 'df', 'gamma', 'gen.gamma',\n 'logis', 'lnorm', 'negbin', 'nchisqr',\n 'norm', 'par', 'pois', 'weib'))\n _OTHER_DISTRIBUTIONS = ('dt', 'dunif', 'dbetabin', 'dbern', 'dbin', 'dcat', 'dhyper',\n 'ddirch', 'dmnorm', 'dwish', 'dmt', 'dmulti', 'dbinom',\n 'dchisq', 'dnbinom', 'dweibull', 'ddirich')\n tokens = {'whitespace':[\n (\n '\\\\s+', Text)], \n 'names':[\n (\n '[a-zA-Z][\\\\w.]*\\\\b', Name)], \n 'comments':[\n (\n '(?s)/\\\\*.*?\\\\*/', Comment.Multiline),\n (\n '#.*$', Comment.Single)], \n 'root':[\n include('comments'),\n include('whitespace'),\n (\n '(model|data)(\\\\s+)(\\\\{)',\n bygroups(Keyword.Namespace, Text, Punctuation)),\n (\n 'var(?![\\\\w.])', Keyword.Declaration),\n (\n '(for|in)(?![\\\\w.])', Keyword.Reserved),\n (\n '(%s)(?=\\\\s*\\\\()' % '|'.join(_FUNCTIONS + _DISTRIBUTIONS + _OTHER_DISTRIBUTIONS),\n Name.Builtin),\n include('names'),\n (\n '[-+]?[0-9]*\\\\.?[0-9]+([eE][-+]?[0-9]+)?', Number),\n (\n '\\\\[|\\\\]|\\\\(|\\\\)|:|,|;', Punctuation),\n (\n '<-|~', Operator),\n (\n '\\\\+|-|\\\\*|\\\\/|\\\\|\\\\|[&]{2}|[<>=]=?|\\\\^|%.*?%', Operator),\n (\n '[{}]', Punctuation)]}\n\n def analyse_text(text):\n if re.search('^\\\\s*model\\\\s*\\\\{', text, re.M):\n if re.search('^\\\\s*data\\\\s*\\\\{', text, re.M):\n return 0.9\n else:\n if re.search('^\\\\s*var', text, re.M):\n return 0.9\n return 0.3\n else:\n return 0\n\n\nclass StanLexer(RegexLexer):\n __doc__ = \"Pygments Lexer for Stan models.\\n\\n The Stan modeling language is specified in the *Stan Modeling Language\\n User's Guide and Reference Manual, v2.17.0*,\\n `pdf `__.\\n\\n .. versionadded:: 1.6\\n \"\n name = 'Stan'\n aliases = ['stan']\n filenames = ['*.stan']\n tokens = {'whitespace':[\n (\n '\\\\s+', Text)], \n 'comments':[\n (\n '(?s)/\\\\*.*?\\\\*/', Comment.Multiline),\n (\n '(//|#).*$', Comment.Single)], \n 'root':[\n (\n '\"[^\"]*\"', String),\n include('comments'),\n include('whitespace'),\n (\n '(%s)(\\\\s*)(\\\\{)' % '|'.join(('functions', 'data', 'transformed\\\\s+?data', 'parameters',\n 'transformed\\\\s+parameters', 'model', 'generated\\\\s+quantities')),\n bygroups(Keyword.Namespace, Text, Punctuation)),\n (\n 'target\\\\s*\\\\+=', Keyword),\n (\n '(%s)\\\\b' % '|'.join(_stan_builtins.KEYWORDS), Keyword),\n (\n 'T(?=\\\\s*\\\\[)', Keyword),\n (\n '(%s)\\\\b' % '|'.join(_stan_builtins.TYPES), Keyword.Type),\n (\n '(<)(\\\\s*)(upper|lower)(\\\\s*)(=)',\n bygroups(Operator, Whitespace, Keyword, Whitespace, Punctuation)),\n (\n '(,)(\\\\s*)(upper)(\\\\s*)(=)',\n bygroups(Punctuation, Whitespace, Keyword, Whitespace, Punctuation)),\n (\n '[;,\\\\[\\\\]()]', Punctuation),\n (\n '(%s)(?=\\\\s*\\\\()' % '|'.join(_stan_builtins.FUNCTIONS), Name.Builtin),\n (\n '(~)(\\\\s*)(%s)(?=\\\\s*\\\\()' % '|'.join(_stan_builtins.DISTRIBUTIONS),\n bygroups(Operator, Whitespace, Name.Builtin)),\n (\n '[A-Za-z]\\\\w*__\\\\b', Name.Builtin.Pseudo),\n (\n '(%s)\\\\b' % '|'.join(_stan_builtins.RESERVED), Keyword.Reserved),\n (\n '[A-Za-z]\\\\w*(?=\\\\s*\\\\()]', Name.Function),\n (\n '[A-Za-z]\\\\w*\\\\b', Name),\n (\n '[0-9]+(\\\\.[0-9]*)?([eE][+-]?[0-9]+)?', Number.Float),\n (\n '\\\\.[0-9]+([eE][+-]?[0-9]+)?', Number.Float),\n (\n '[0-9]+', Number.Integer),\n (\n '<-|(?:\\\\+|-|\\\\.?/|\\\\.?\\\\*|=)?=|~', Operator),\n (\n \"\\\\+|-|\\\\.?\\\\*|\\\\.?/|\\\\\\\\|'|\\\\^|!=?|<=?|>=?|\\\\|\\\\||&&|%|\\\\?|:\", Operator),\n (\n '[{}]', Punctuation),\n (\n '\\\\|', Punctuation)]}\n\n def analyse_text(text):\n if re.search('^\\\\s*parameters\\\\s*\\\\{', text, re.M):\n return 1.0\n else:\n return 0.0","sub_path":"pycfiles/libopenstorage_openstorage-0.42.24.1-py3-none-any/modeling.cpython-36.py","file_name":"modeling.cpython-36.py","file_ext":"py","file_size_in_byte":11046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"217358535","text":"# Copyright 2016 Cisco Systems, Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n\nfrom networking_cisco.apps.saf.common import config\nfrom networking_cisco.apps.saf.common import dfa_logger as logging\nfrom networking_cisco.apps.saf.common import dfa_sys_lib as utils\nfrom networking_cisco.apps.saf.server import dfa_events_handler as deh\n\nfrom networking_cisco._i18n import _LE\n\nLOG = logging.getLogger(__name__)\n\n\nclass DfaNeutronHelper(object):\n\n \"\"\"Helper Routines for Neutron. \"\"\"\n\n def __init__(self):\n \"\"\"Initialization. \"\"\"\n self.neutron_help = deh.EventsHandler('neutron', None, 20, 25)\n cfg = config.CiscoDFAConfig('neutron').cfg\n self.root_helper = cfg.sys.root_helper\n\n @property\n def neutronclient(self):\n \"\"\"Returns client object. \"\"\"\n return self.neutron_help.nclient\n\n def create_network(self, name, tenant_id, subnet, gw=None):\n \"\"\"Create the openstack network, including the subnet. \"\"\"\n\n try:\n body = {'network': {'name': name, 'tenant_id': tenant_id,\n 'admin_state_up': True}}\n netw = self.neutronclient.create_network(body=body)\n net_dict = netw.get('network')\n net_id = net_dict.get('id')\n except Exception as exc:\n LOG.error(_LE(\"Failed to create network %(name)s, Exc %(exc)s\"),\n {'name': name, 'exc': str(exc)})\n return None, None\n\n try:\n if gw is None:\n body = {'subnet': {'cidr': subnet,\n 'ip_version': 4,\n 'network_id': net_id,\n 'tenant_id': tenant_id,\n 'enable_dhcp': False}}\n else:\n body = {'subnet': {'cidr': subnet,\n 'ip_version': 4,\n 'network_id': net_id,\n 'tenant_id': tenant_id,\n 'enable_dhcp': False,\n 'gateway_ip': gw}}\n subnet_ret = self.neutronclient.create_subnet(body=body)\n subnet_dict = subnet_ret.get('subnet')\n subnet_id = subnet_dict.get('id')\n except Exception as exc:\n LOG.error(_LE(\"Failed to create subnet %(sub)s, exc %(exc)s\"),\n {'sub': subnet, 'exc': str(exc)})\n try:\n self.neutronclient.delete_network(net_id)\n except Exception as exc:\n LOG.error(_LE(\"Failed to delete network %(net)s, exc %(exc)s\"),\n {'net': net_id, 'exc': str(exc)})\n return None, None\n return net_id, subnet_id\n\n def delete_network(self, name, tenant_id, subnet_id, net_id):\n \"\"\"Delete the openstack subnet and network. \"\"\"\n try:\n self.neutronclient.delete_subnet(subnet_id)\n except Exception as exc:\n LOG.error(_LE(\"Failed to delete subnet %(sub)s exc %(exc)s\"),\n {'sub': subnet_id, 'exc': str(exc)})\n return\n try:\n self.neutronclient.delete_network(net_id)\n except Exception as exc:\n LOG.error(_LE(\"Failed to delete network %(name)s exc %(exc)s\"),\n {'name': name, 'exc': str(exc)})\n\n # Pass\n def delete_network_all_subnets(self, net_id):\n \"\"\"Delete the openstack network including all its subnets. \"\"\"\n try:\n body = {'network_id': net_id}\n subnet_list = self.neutronclient.list_subnets(body=body)\n subnet_list = subnet_list.get('subnets')\n for subnet in subnet_list:\n if subnet.get('network_id') == net_id:\n subnet_id = subnet.get('id')\n self.neutronclient.delete_subnet(subnet_id)\n except Exception as exc:\n LOG.error(_LE(\"Failed to delete subnet for net %(net)s \"\n \"Exc %(exc)s\"), {'net': net_id, 'exc': str(exc)})\n return False\n try:\n self.neutronclient.delete_network(net_id)\n except Exception as exc:\n LOG.error(_LE(\"Failed to delete network %(net)s Exc %(exc)s\"),\n {'net': net_id, 'exc': str(exc)})\n return False\n return True\n\n def is_subnet_present(self, subnet_addr):\n \"\"\"Returns if a subnet is present. \"\"\"\n try:\n subnet_list = self.neutronclient.list_subnets(body={})\n subnet_dat = subnet_list.get('subnets')\n for sub in subnet_dat:\n if sub.get('cidr') == subnet_addr:\n return True\n return False\n except Exception as exc:\n LOG.error(_LE(\"Failed to list subnet %(sub)s, Exc %(exc)s\"),\n {'sub': subnet_addr, 'exc': str(exc)})\n return False\n\n def get_all_subnets_cidr(self, no_mask=False):\n \"\"\"Returns all the subnets. \"\"\"\n body = {}\n subnet_cidrs = []\n try:\n subnet_list = self.neutronclient.list_subnets(body=body)\n subnet_dat = subnet_list.get('subnets')\n for sub in subnet_dat:\n if no_mask:\n subnet_cidrs.append(sub.get('cidr').split('/')[0])\n else:\n subnet_cidrs.append(sub.get('cidr'))\n except Exception as exc:\n LOG.error(_LE(\"Failed to list subnet Exc %s\"), str(exc))\n return subnet_cidrs\n\n def get_subnets_for_net(self, net):\n \"\"\"Returns the subnets in a network. \"\"\"\n try:\n subnet_list = self.neutronclient.list_subnets(network_id=net)\n subnet_dat = subnet_list.get('subnets')\n return subnet_dat\n except Exception as exc:\n LOG.error(_LE(\"Failed to list subnet net %(net)s, Exc: %(exc)s\"),\n {'net': net, 'exc': str(exc)})\n return None\n\n def get_subnet_cidr(self, subnet_id):\n \"\"\"retrieve the CIDR associated with a subnet, given its ID. \"\"\"\n try:\n subnet_list = self.neutronclient.list_subnets(id=subnet_id)\n subnet_dat = subnet_list.get('subnets')[0]\n return subnet_dat.get('cidr')\n except Exception as exc:\n LOG.error(_LE(\"Failed to list subnet for ID %(subnet)s, \"\n \"exc %(exc)s\"), {'subnet': subnet_id, 'exc': exc})\n return None\n\n def delete_network_subname(self, sub_name):\n \"\"\"Delete the network by part of its name, use with caution. \"\"\"\n try:\n body = {}\n net_list = self.neutronclient.list_networks(body=body)\n for net in net_list:\n if net.get('name').find(sub_name) != -1:\n self.delete_network_all_subnets(net.get('net_id'))\n except Exception as exc:\n LOG.error(_LE(\"Failed to get network by subname %(name)s, \"\n \"Exc %(exc)s\"),\n {'name': sub_name, 'exc': str(exc)})\n\n def get_network_by_name(self, nwk_name):\n \"\"\"Search for a openstack network by name. \"\"\"\n ret_net_lst = []\n try:\n body = {}\n net_list = self.neutronclient.list_networks(body=body)\n net_list = net_list.get('networks')\n for net in net_list:\n if net.get('name') == nwk_name:\n ret_net_lst.append(net)\n except Exception as exc:\n LOG.error(_LE(\"Failed to get network by name %(name)s, \"\n \"Exc %(exc)s\"),\n {'name': nwk_name, 'exc': str(exc)})\n return ret_net_lst\n\n def get_network_by_tenant(self, tenant_id):\n \"\"\"Returns the network of a given tenant. \"\"\"\n ret_net_lst = []\n try:\n net_list = self.neutronclient.list_networks(body={})\n for net in net_list.get('networks'):\n if net.get('tenant_id') == tenant_id:\n ret_net_lst.append(net)\n except Exception as exc:\n LOG.error(_LE(\"Failed to get network by tenant %(tenant)s, \"\n \"Exc %(exc)s\"),\n {'tenant': tenant_id, 'exc': str(exc)})\n return ret_net_lst\n\n # Tested\n def get_rtr_by_name(self, rtr_name):\n \"\"\"Search a router by its name. \"\"\"\n upd_rtr_list = []\n try:\n rtr_list = self.neutronclient.list_routers()\n for rtr in rtr_list.get('routers'):\n if rtr_name == rtr['name']:\n upd_rtr_list.append(rtr)\n except Exception as exc:\n LOG.error(_LE(\"Failed to get router by name %(name)s, \"\n \"Exc %(exc)s\"),\n {'name': rtr_name, 'exc': str(exc)})\n return upd_rtr_list\n\n def create_router(self, name, tenant_id, subnet_lst):\n \"\"\"Create a openstack router and add the interfaces. \"\"\"\n try:\n body = {'router': {'name': name, 'tenant_id': tenant_id,\n 'admin_state_up': True}}\n router = self.neutronclient.create_router(body=body)\n rout_dict = router.get('router')\n rout_id = rout_dict.get('id')\n except Exception as exc:\n LOG.error(_LE(\"Failed to create router with name %(name)s\"\n \" Exc %(exc)s\"), {'name': name, 'exc': str(exc)})\n return None\n\n ret = self.add_intf_router(rout_id, tenant_id, subnet_lst)\n if not ret:\n try:\n ret = self.neutronclient.delete_router(rout_id)\n except Exception as exc:\n LOG.error(_LE(\"Failed to delete router %(name)s, Exc %(exc)s\"),\n {'name': name, 'exc': str(exc)})\n return None\n return rout_id\n\n def add_intf_router(self, rout_id, tenant_id, subnet_lst):\n \"\"\"Add the interfaces to a router. \"\"\"\n try:\n for subnet_id in subnet_lst:\n body = {'subnet_id': subnet_id}\n intf = self.neutronclient.add_interface_router(rout_id,\n body=body)\n intf.get('port_id')\n except Exception as exc:\n LOG.error(_LE(\"Failed to create router intf ID %(id)s,\"\n \" Exc %(exc)s\"), {'id': rout_id, 'exc': str(exc)})\n return False\n return True\n\n # Passed\n def delete_router(self, name, tenant_id, rout_id, subnet_lst):\n \"\"\"Delete the openstack router.\n\n Delete the router and remove the interfaces attached to it.\n \"\"\"\n ret = self.delete_intf_router(name, tenant_id, rout_id, subnet_lst)\n if not ret:\n return False\n\n try:\n ret = self.neutronclient.delete_router(rout_id)\n except Exception as exc:\n LOG.error(_LE(\"Failed to delete router %(name)s ret %(ret)s \"\n \"Exc %(exc)s\"),\n {'name': name, 'ret': str(ret), 'exc': str(exc)})\n return False\n return True\n\n def delete_intf_router(self, name, tenant_id, rout_id, subnet_lst):\n \"\"\"Delete the openstack router and remove the interfaces attached. \"\"\"\n try:\n for subnet_id in subnet_lst:\n body = {'subnet_id': subnet_id}\n intf = self.neutronclient.remove_interface_router(rout_id,\n body=body)\n intf.get('id')\n except Exception as exc:\n LOG.error(_LE(\"Failed to delete router interface %(name)s, \"\n \" Exc %(exc)s\"), {'name': name, 'exc': str(exc)})\n return False\n return True\n\n def delete_router_by_name(self, rtr_name, tenant_id):\n \"\"\"Delete the openstack router and its interfaces given its name.\n\n The interfaces should be already removed prior to calling this\n function.\n \"\"\"\n try:\n routers = self.neutronclient.list_routers()\n rtr_list = routers.get('routers')\n for rtr in rtr_list:\n if rtr_name == rtr['name']:\n self.neutronclient.delete_router(rtr['id'])\n except Exception as exc:\n LOG.error(_LE(\"Failed to get and delete router by name %(name)s, \"\n \"Exc %(exc)s\"),\n {'name': rtr_name, 'exc': str(exc)})\n return False\n return True\n\n def get_router_intf(self, router_id):\n \"\"\"Retrieve the router interfaces. Incomplete, TODO(padkrish). \"\"\"\n try:\n body = {}\n self.neutronclient.show_router(router_id, body=body)\n except Exception as exc:\n LOG.error(_LE(\"Failed to show router interface %(id)s \"\n \"Exc %(exc)s\"), {'id': router_id, 'exc': str(exc)})\n return\n # Complete fixme(padkrish)\n\n def get_router_port_subnet(self, subnet_id):\n try:\n body = 'network:router_interface'\n port_data = self.neutronclient.list_ports(device_owner=body)\n port_list = port_data.get('ports')\n for port in port_list:\n sub = port.get('fixed_ips')[0].get('subnet_id')\n if sub == subnet_id:\n return port\n return None\n except Exception as exc:\n LOG.error(_LE(\"Failed to get router port subnet %(net)s, \"\n \"Exc: %(exc)s\"), {'net': subnet_id, 'exc': str(exc)})\n return None\n\n def get_rtr_name(self, router_id):\n \"\"\"Retrieve the router name. Incomplete. \"\"\"\n try:\n body = {}\n router = self.neutronclient.show_router(router_id, body=body)\n return router.get('router').get('name')\n except Exception as exc:\n LOG.error(_LE(\"Failed to show router interface %(id)s \"\n \"Exc %(exc)s\"), {'id': router_id, 'exc': str(exc)})\n\n def find_rtr_namespace(self, rout_id):\n \"\"\"Find the namespace associated with the router. \"\"\"\n if rout_id is None:\n return None\n args = ['ip', 'netns', 'list']\n try:\n ns_list = utils.execute(args, root_helper=self.root_helper)\n except Exception as exc:\n LOG.error(_LE(\"Unable to find the namespace list Exception %s\"),\n exc)\n return None\n for ns in ns_list.split():\n if 'router' in ns and rout_id in ns:\n return ns\n\n def program_rtr(self, args, rout_id, namespace=None):\n \"\"\"Execute the command against the namespace. \"\"\"\n if namespace is None:\n namespace = self.find_rtr_namespace(rout_id)\n if namespace is None:\n LOG.error(_LE(\"Unable to find namespace for router %s\"), rout_id)\n return False\n final_args = ['ip', 'netns', 'exec', namespace] + args\n try:\n utils.execute(final_args, root_helper=self.root_helper)\n except Exception as e:\n LOG.error(_LE(\"Unable to execute %(cmd)s. \"\n \"Exception: %(exception)s\"),\n {'cmd': final_args, 'exception': e})\n return False\n return True\n\n def program_rtr_return(self, args, rout_id, namespace=None):\n \"\"\"Execute the command against the namespace and return the result. \"\"\"\n if namespace is None:\n namespace = self.find_rtr_namespace(rout_id)\n if namespace is None:\n LOG.error(_LE(\"Unable to find namespace for router %s\"), rout_id)\n return False\n final_args = ['ip', 'netns', 'exec', namespace] + args\n try:\n return utils.execute(final_args, root_helper=self.root_helper)\n except Exception as e:\n LOG.error(_LE(\"Unable to execute %(cmd)s. \"\n \"Exception: %(exception)s\"),\n {'cmd': final_args, 'exception': e})\n return None\n\n def program_rtr_default_gw(self, tenant_id, rout_id, gw):\n \"\"\"Program the default gateway of a router. \"\"\"\n args = ['route', 'add', 'default', 'gw', gw]\n ret = self.program_rtr(args, rout_id)\n if not ret:\n LOG.error(_LE(\"Program router returned error for %s\"), rout_id)\n return False\n return True\n\n def get_subnet_nwk_excl(self, tenant_id, excl_list, excl_part=False):\n \"\"\"Retrieve the subnets of a network.\n\n Get the subnets inside a network after applying the exclusion\n list.\n \"\"\"\n net_list = self.get_network_by_tenant(tenant_id)\n ret_subnet_list = []\n for net in net_list:\n if excl_part:\n name = net.get('name')\n part = name.partition('::')[2]\n if part:\n continue\n subnet_lst = self.get_subnets_for_net(net.get('id'))\n for subnet_elem in subnet_lst:\n subnet = subnet_elem.get('cidr').split('/')[0]\n subnet_and_mask = subnet_elem.get('cidr')\n if subnet not in excl_list:\n ret_subnet_list.append(subnet_and_mask)\n return ret_subnet_list\n\n def program_rtr_all_nwk_next_hop(self, tenant_id, rout_id, next_hop,\n excl_list):\n \"\"\"Program the next hop for all networks of a tenant. \"\"\"\n namespace = self.find_rtr_namespace(rout_id)\n if namespace is None:\n LOG.error(_LE(\"Unable to find namespace for router %s\"), rout_id)\n return False\n\n net_list = self.get_network_by_tenant(tenant_id)\n for net in net_list:\n subnet_lst = self.get_subnets_for_net(net.get('id'))\n for subnet_elem in subnet_lst:\n subnet = subnet_elem.get('cidr').split('/')[0]\n subnet_and_mask = subnet_elem.get('cidr')\n if subnet not in excl_list:\n args = ['route', 'add', '-net', subnet_and_mask, 'gw',\n next_hop]\n ret = self.program_rtr(args, rout_id, namespace=namespace)\n if not ret:\n LOG.error(_LE(\"Program router returned error for %s\"),\n rout_id)\n return False\n return True\n\n def program_rtr_nwk_next_hop(self, rout_id, next_hop, cidr):\n \"\"\"Program the next hop for all networks of a tenant. \"\"\"\n namespace = self.find_rtr_namespace(rout_id)\n if namespace is None:\n LOG.error(_LE(\"Unable to find namespace for router %s\"), rout_id)\n return False\n\n args = ['route', 'add', '-net', cidr, 'gw', next_hop]\n ret = self.program_rtr(args, rout_id, namespace=namespace)\n if not ret:\n LOG.error(_LE(\"Program router returned error for %s\"), rout_id)\n return False\n return True\n\n def remove_rtr_nwk_next_hop(self, rout_id, next_hop, subnet_lst,\n excl_list):\n \"\"\"Remove the next hop for all networks of a tenant. \"\"\"\n namespace = self.find_rtr_namespace(rout_id)\n if namespace is None:\n LOG.error(_LE(\"Unable to find namespace for router %s\"), rout_id)\n return False\n\n args = ['ip', 'route']\n ret = self.program_rtr_return(args, rout_id, namespace=namespace)\n if ret is None:\n LOG.error(_LE(\"Get routes return None %s\"), rout_id)\n return False\n routes = ret.split('\\n')\n concat_lst = subnet_lst + excl_list\n for rout in routes:\n if len(rout) == 0:\n continue\n nwk = rout.split()[0]\n if nwk == 'default':\n continue\n nwk_no_mask = nwk.split('/')[0]\n if nwk_no_mask not in concat_lst and nwk not in concat_lst:\n args = ['route', 'del', '-net', nwk, 'gw', next_hop]\n ret = self.program_rtr(args, rout_id, namespace=namespace)\n if not ret:\n LOG.error(_LE(\"Program router returned error for %s\"),\n rout_id)\n return False\n return True\n\n def get_fw(self, fw_id):\n \"\"\"Return the Firewall given its ID. \"\"\"\n fw = None\n try:\n fw = self.neutronclient.show_firewall(fw_id)\n except Exception as exc:\n LOG.error(_LE(\"Failed to get firewall list for id %(id)s, \"\n \"Exc %(exc)s\"), {'id': fw_id, 'exc': str(exc)})\n return fw\n\n # Tested\n def get_fw_rule(self, rule_id):\n \"\"\"Return the firewall rule, given its ID. \"\"\"\n rule = None\n try:\n rule = self.neutronclient.show_firewall_rule(rule_id)\n except Exception as exc:\n LOG.error(_LE(\"Failed to get firewall rule for id %(id)s \"\n \"Exc %(exc)s\"), {'id': rule_id, 'exc': str(exc)})\n return rule\n\n # Tested\n def get_fw_policy(self, policy_id):\n \"\"\"Return the firewall policy, given its ID. \"\"\"\n policy = None\n try:\n policy = self.neutronclient.show_firewall_policy(policy_id)\n except Exception as exc:\n LOG.error(_LE(\"Failed to get firewall plcy for id %(id)s \"\n \"Exc %(exc)s\"),\n {'id': policy_id, 'exc': str(exc)})\n return policy\n","sub_path":"networking_cisco/apps/saf/server/dfa_openstack_helper.py","file_name":"dfa_openstack_helper.py","file_ext":"py","file_size_in_byte":22095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"647780359","text":"from nmtg.data.dataset import Dataset\nfrom nmtg.data.text_lookup_dataset import TextLookupDataset\n\n\nclass ParallelDataset(Dataset):\n def __init__(self, src_data: TextLookupDataset, tgt_data: TextLookupDataset = None):\n self.src_data = src_data # technically a duplicate, but it's fine\n self.tgt_data = tgt_data\n\n def __getitem__(self, index):\n source = self.src_data[index]\n res = {'id': index, 'src_indices': source, 'src_size': len(source)}\n\n if self.tgt_data is not None:\n target = self.tgt_data[index]\n target_input = target[:-1]\n target_output = target[1:]\n res['tgt_input'] = target_input\n res['tgt_output'] = target_output\n res['tgt_size'] = len(target_output)\n\n return res\n\n def __len__(self):\n return len(self.src_data)\n\n def collate_samples(self, samples):\n src_batch = self.src_data.collate_samples([x['src_indices'] for x in samples])\n res = {'src_indices': src_batch['indices'],\n 'src_size': src_batch['size'],\n 'src_lengths': src_batch['lengths']}\n\n if self.tgt_data is not None:\n target_input = self.tgt_data.collate_samples([x['tgt_input'] for x in samples])\n target_output = self.tgt_data.collate_samples([x['tgt_output'] for x in samples])\n res['tgt_input'] = target_input['indices']\n res['tgt_output'] = target_output['indices']\n res['tgt_size'] = target_output['size']\n res['tgt_lengths'] = target_output['lengths']\n\n return res\n","sub_path":"nmtg/data/parallel_dataset.py","file_name":"parallel_dataset.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"196984457","text":"#Librerias\nimport pandas as pd\nimport numpy as np\nimport time\nfrom scipy import stats\nimport multiprocessing\nfrom datetime import datetime\nfrom datetime import timedelta\nimport matplotlib.pyplot as plt\n\n# TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n# TO DO: get user input for month (all, january, february, ... , june)\n# TO DO: get user input for day of week (all, monday, tuesday, ... sunday)\nDias_Semana= {'Lunes': 'Monday','Martes':'Tuesday','Miercoles':'Wednesday','Jueves':'Thursday','Viernes':'Friday','Sabado':'Saturday','Domingo':'Sunday'}\nCiudades =['Chicago','New York', 'Washington']\nmensajes =['Vamos a ver los de datos de '+Ciudades[0],'Vamos a ver los de datos de '+Ciudades[1], 'Vamos a ver los de datos de '+Ciudades[2], 'No tenemos datos para su ciudad ¿Por qué no intenta con: Chicago New York o Washington?']\nciudad=\"\"\nResultado=\"\"\nweek = ['Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado', 'Domingo']\nsearch_city = input('Estadisticas de Bikeshare por ciudad Princial, mes y dia selec su ciudad ')\nciudad = search_city.lower()\nwhile search_city.lower() == \"chicago\" or \"new york\" or \"washington\":\n if search_city.lower() == \"chicago\":\n Resultado = (mensajes[0])\n elif search_city.lower() == \"new york\":\n Resultado = (mensajes[1])\n elif search_city.lower() == \"washington\":\n Resultado = (mensajes[2])\n else:\n Resultado =(mensajes[3])\n print(ciudad)\n print(Resultado)\n search_city = input('Select nombre ') \n break\n if search_city == \"chicago\":\n Resultado = (mensajes[0])\n elif search_city == \"new york\":\n Resultado = (mensajes[1])\n elif search_city == \"washington\":\n Resultado = (mensajes[2])\n break\n\nprint(Resultado)\n \nciudad = search_city.lower()\nInput_Fecha = input('Mes: de Ene - Jun ')\nmonth = Input_Fecha.lower()\n\nDatos_Ciudades = { 'chicago': 'chicago.csv','new york': 'new_york_city.csv','washington': 'washington.csv' }\ndf = pd.read_csv(Datos_Ciudades[ciudad])\ndf['Start Time'] = pd.to_datetime(df['Start Time'])\ndf['dia_semana'] = df['Start Time'].dt.day_name()\ndf['month'] = df['Start Time'].dt.month\nif month != 'all':\n months = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio']\n month = months.index(month) + 1\n df = df[df['month'] == month]\nDias_Semana= {'Lunes': 'Monday','Martes':'Tuesday','Miercoles':'Wednesday','Jueves':'Thursday','Viernes':'Friday','Sabado':'Saturday','Domingo':'Sunday'}\nInput_day = input('Ingrese el día de la semana ')\nday_es=Input_day.capitalize()\n\nif Dias_Semana[day_es] != 'all':\n df = df[df['dia_semana'] == Dias_Semana[day_es]]\n\n# TO DO: display the most common month\n# TO DO: display the most common day of week\n# TO DO: display the most common start hour\n#Para responder pegunta, se filtra carla la informacion de nuevo, y no se filtra\n\nEstadistica_Meses = input('¿Ver los datos de las estadisticas de los meses?')\nif Estadistica_Meses == 'si':\n Datos_Ciudades = { 'chicago': 'chicago.csv','new york': 'new_york_city.csv','washington': 'washington.csv' }\n df = pd.read_csv(Datos_Ciudades[ciudad]) \n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['month'] = df['Start Time'].dt.month\n df['day'] = df['Start Time'].dt.dayofweek\n df['hour'] = df['Start Time'].dt.hour\n month= df['month'].mode()[0]\n pop_mont = months[month - 1]\n popday= df['Start Time'].dt.dayofweek.mode()[0]\n pop_day = week[popday]\n pophour =df['hour'] = df['Start Time'].dt.hour.mode()[0]\n pop_hour= str(pophour)\n print('El mes que mas se repite en '+ciudad+' es '+pop_mont)\n print('El dia que mas se repite en '+ciudad+' es '+pop_day)\n print('La hora que mas se repite en '+ciudad+' es '+pop_hour+':00')\n\nelse:\n\n# TO DO: display most commonly used start station\n# TO DO: display most commonly used end station\n# TO DO: display most frequent combination of start station and end station trip\n\n Estadistica_Estaciones = input('Estadisticas de las estaciones?')\n if Estadistica_Estaciones == 'si':\n month = Input_Fecha.lower()\n Datos_Ciudades = { 'chicago': 'chicago.csv','new york': 'new_york_city.csv','washington': 'washington.csv' }\n df = pd.read_csv(Datos_Ciudades[ciudad])\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['dia_semana'] = df['Start Time'].dt.day_name()\n df['month'] = df['Start Time'].dt.month\n if month != 'all':\n months = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio']\n month = months.index(month) + 1\n df = df[df['month'] == month]\n Dias_Semana= {'Lunes': 'Monday','Martes':'Tuesday','Miercoles':'Wednesday','Jueves':'Thursday','Viernes':'Friday','Sabado':'Saturday','Domingo':'Sunday'}\n if Dias_Semana[day_es] != 'all':\n df = df[df['dia_semana'] == Dias_Semana[day_es]]\n Start_Station=df['Start Station'].mode()[0]\n End_Station=df['End Station'].mode()[0]\n df['Comb_Station'] ='De '+df['Start Station']+' a '+df['End Station']\n Comb_Station = df['Comb_Station'].mode()[0]\n print('Estacion mas residencial: '+Start_Station)\n print('Estacion masturistica: '+End_Station)\n print('Viaje mas comun es: '+Comb_Station)\n\n# TO DO: display total travel time\n# TO DO: display mean travel time\n\n else:\n Estadistica_viajes = input('Estadisticas de los viajes?')\n if Estadistica_viajes == 'si':\n month = Input_Fecha.lower()\n Datos_Ciudades = { 'chicago': 'chicago.csv','new york': 'new_york_city.csv','washington': 'washington.csv' }\n df = pd.read_csv(Datos_Ciudades[ciudad])\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['End Time'] = pd.to_datetime(df['End Time'])\n df['dia_semana'] = df['Start Time'].dt.day_name()\n df['month'] = df['Start Time'].dt.month\n if month != 'all':\n months = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio']\n month = months.index(month) + 1\n df = df[df['month'] == month]\n day_es=Input_day.capitalize()\n if Dias_Semana[day_es] != 'all':\n df = df[df['dia_semana'] == Dias_Semana[day_es]] \n df['duracion'] = df['End Time'] - df['Start Time']\n Viaje_total=df['duracion'].sum()\n Promedio_viaje=df['duracion'].mean()\n print('Promedio de duración de viajes es: '+str(Promedio_viaje))\n print('Duración de los viajes es: '+str(Viaje_total))\n\n# TO DO: Display counts of user types\n# TO DO: Display counts of gender\n else:\n Estadistica_generos = input('Estadisticas de los usuarios?')\n if Estadistica_generos == 'si':\n month = Input_Fecha.lower()\n Datos_Ciudades = { 'chicago': 'chicago.csv','new york': 'new_york_city.csv','washington': 'washington.csv' }\n df = pd.read_csv(Datos_Ciudades[ciudad])\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['dia_semana'] = df['Start Time'].dt.day_name()\n df['month'] = df['Start Time'].dt.month\n if month != 'all':\n month = Input_Fecha.lower()\n months = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio']\n month = months.index(month) + 1\n df = df[df['month'] == month]\n \n \n if Dias_Semana[day_es] != 'all':\n day_es=Input_day.capitalize()\n df = df[df['dia_semana'] == Dias_Semana[day_es]] \n Suma_Tipos = df['User Type'].value_counts()\n Suma_Generos = df['Gender'].value_counts()\n print('Por tipo de usuarios: ') \n print(Suma_Tipos)\n print('Por tipo de generos: ') \n print(Suma_Generos)\n\n# TO DO: Display earliest, most recent, and most common year of birth\n\n else:\n Estadistica_nacimientos = input('Estadisticas de las fechas de nacimiento?')\n if Estadistica_nacimientos == 'si':\n Datos_Ciudades = { 'chicago': 'chicago.csv','new york': 'new_york_city.csv','washington': 'washington.csv' }\n df = pd.read_csv(Datos_Ciudades[ciudad])\n month = Input_Fecha.lower()\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['dia_semana'] = df['Start Time'].dt.day_name()\n df['month'] = df['Start Time'].dt.month\n if month != 'all':\n month = Input_Fecha.lower()\n months = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio']\n month = months.index(month) + 1\n df = df[df['month'] == month]\n if Dias_Semana[day_es] != 'all':\n day_es=Input_day.capitalize()\n primer_nacimiento = df['Birth Year'].min()\n ultimo_nacimiento= df['Birth Year'].max()\n moda_nacimientos=df['Birth Year'].mode()[0]\n print('Año nacimiento mas mayor: '+str(primer_nacimiento)[0:4])\n print('Año nacimiento mas joven: '+str(ultimo_nacimiento)[0:4])\n print('Moda año nacimiento: '+str(moda_nacimientos)[0:4])\n print(\"Gracias por su consulta\")\n else:\n print(\"Gracias por su consulta\")\n#Display contents of the CSV file to the display as requested by the user. \ndef muestra_data(df):\n inicio_loc = 0\n fin_loc = 5\n data_cruda = input(\"¿Quiere ver la base de info?: \").lower()\n if data_cruda == 'si':\n while fin_loc <= df.shape[0] - 1:\n print(df.iloc[inicio_loc:fin_loc,:])\n inicio_loc += 5\n fin_loc += 5\n mensaje_final = input(\"¿Quiere consultar de nuevo?: \").lower()\n if mensaje_final == 'no':\n \n break\n \n \nmuestra_data(df)\nprint(\"Gracias por su consulta\")\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":9663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"27451502","text":"# blurring and reduicng noice ( a little )\n\n# from file opencv7.py\nimport numpy as np\nimport cv2 as cv\n\ncap = cv.VideoCapture(0)\n\nwhile True:\n\n _, frame = cap.read()\n frame = cv.resize(frame, (0, 0), fx = 0.4, fy = 0.4)\n hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)\n\n min = np.array([30, 50, 50])\n max = np.array([90, 200, 200])\n\n mask = cv.inRange(hsv, min, max)\n result = cv.bitwise_and(frame, frame, mask = mask)\n\n #types of blur\n # 1 kernel and 2D filer\n #kernel = np.ones((15,15), np.float32)/(15*15)\n #smooth = cv.filter2D(result, -1, kernel)\n\n # guassian blur\n #blur = cv.GaussianBlur(result, (15,15), 0)\n\n # median blur ( works best )\n median = cv.medianBlur(result, 15)\n\n # bilateral blur ( not so useful )\n #bilateral = cv.bilateralFilter(result, 15, 75, 75)\n\n\n #cv.imshow(\"frame\" ,frame)\n #cv.imshow(\"mask\" ,mask)\n cv.imshow(\"result\" ,result)\n\n # showing all the blurring\n #cv.imshow(\"smooth\" ,smooth)\n #cv.imshow(\"blur\" ,blur)\n cv.imshow(\"median\" ,median)\n #cv.imshow(\"bilateral\" ,bilateral)\n\n\n\n\n\n\n\n if cv.waitKey(1) & 0xFF == ord('q'):\n break\n\n\n\ncap.release()\ncv.destroyAllWindows()\n","sub_path":"opencv/opencv8.py","file_name":"opencv8.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"510312592","text":"from __future__ import division\nimport hoomd\nimport hoomd.md\nimport numpy as np\n\n\nhoomd.context.initialize(\"\");\n\npositions = [[5*x, 0,0] for x in range(-10,10)]\nnum_particles = 20\ntypes = ['R','A','B','C','D','E']\nbond_types = []\nbox_width = 200\n\n# Place the type R central particles\n# 2d box, 10x10\nbox = hoomd.data.boxdim(L=box_width,dimensions=2) # dimensions=2 forces Lz=1\nsnapshot = hoomd.data.make_snapshot(N=num_particles,\n box=box,\n particle_types=types,\n bond_types=bond_types);\n\n\nsnapshot.particles.position[:] = positions\nsnapshot.particles.typeid[:] = [0 for x in range(-10,10)]\n\nsnapshot.particles.moment_inertia[:] = [[0,0,10] for x in range(-10,10)]\n\n# set gaussian random velocity for all proteins\nsnapshot.particles.velocity[:] = np.random.normal(0.0,\n np.sqrt(0.8 / 1.0), [snapshot.particles.N, 3]);\n\n# initialize hoomd with this snapshot\nhoomd.init.read_snapshot(snapshot)\n\nrigid = hoomd.md.constrain.rigid();\n\ntheta = np.arccos(1.5/9)\nscale = 1 # wanted to be able to scale proteins up in size but couldn't get COM coods right\nstart_x = -2\nstart_y = -3\nprotein_edge_particles = []\nedge_particle_types = []\n# particles along first edge\nfor i in range(1 + 9*scale):\n x = np.cos(theta)*i + (start_x*scale)\n y = np.sin(theta)*i + (start_y*scale)\n protein_edge_particles.append([x,y,0])\n if i <=3:\n edge_particle_types.append('A')\n else:\n edge_particle_types.append('B')\n# particles along opposite edge\nfor i in range(1 + 9*scale):\n x = -np.cos(theta)*i + (start_x + 4)*scale\n y = np.sin(theta)*i + (start_y)*scale\n protein_edge_particles.append([x,y,0])\n if i <= 3:\n edge_particle_types.append('D')\n else:\n edge_particle_types.append('C')\n# particles along top edge\nfor i in range(1,1*scale):\n x = (start_x + 1.5)*scale + i\n y = (start_y + 9)*scale\n protein_edge_particles.append([x,y,0])\n edge_particle_types.append('E')\n# particles along bottom edge\nfor i in range(1,4*scale):\n x = (start_x)*scale + i\n y = (start_y)*scale\n protein_edge_particles.append([x,y,0])\n edge_particle_types.append('E')\n \n\n\n\n# trapezoid particles, adjusted so R is approximately COM (just eyeballing)\nrigid.set_param('R',\n types=edge_particle_types,\n positions=protein_edge_particles);\nrigid.create_bodies()\n\n\nnl = hoomd.md.nlist.cell();\n# use gaussian interaction because it is mathematicaaly simple\ngauss = hoomd.md.pair.gauss(r_cut=2, nlist=nl)\n# same type particles repel\ngauss.pair_coeff.set('A', 'A',epsilon=500, sigma=0.5);\ngauss.pair_coeff.set('B', 'B',epsilon=500, sigma=0.5);\ngauss.pair_coeff.set('C', 'C',epsilon=500, sigma=0.5);\ngauss.pair_coeff.set('D', 'D',epsilon=500, sigma=0.5);\n# these need to attract so proteins as0le\ngauss.pair_coeff.set('A', 'D',epsilon=-500, sigma=0.5);\ngauss.pair_coeff.set('B', 'C',epsilon=-500, sigma=0.5);\n# everything else repels\ngauss.pair_coeff.set('A', 'B',epsilon=500, sigma=0.5);\ngauss.pair_coeff.set('A', 'C',epsilon=500, sigma=0.5);\ngauss.pair_coeff.set('B', 'D',epsilon=500, sigma=0.5);\ngauss.pair_coeff.set('C', 'D',epsilon=500, sigma=0.5);\n\n# R does nothing\ngauss.pair_coeff.set('R', 'R',epsilon=0, sigma=2.0);\ngauss.pair_coeff.set('R', 'A',epsilon=0, sigma=2.0);\ngauss.pair_coeff.set('R', 'B',epsilon=0, sigma=2.0);\ngauss.pair_coeff.set('R', 'C',epsilon=0, sigma=2.0);\ngauss.pair_coeff.set('R', 'D',epsilon=0, sigma=2.0);\n\ngauss.pair_coeff.set('E', 'E',epsilon=500, sigma=2.0);\ngauss.pair_coeff.set('E', 'R',epsilon=500, sigma=2.0);\ngauss.pair_coeff.set('E', 'A',epsilon=500, sigma=2.0);\ngauss.pair_coeff.set('E', 'B',epsilon=500, sigma=2.0);\ngauss.pair_coeff.set('E', 'C',epsilon=500, sigma=2.0);\ngauss.pair_coeff.set('E', 'D',epsilon=500, sigma=2.0);\n\n\nrigidTest = hoomd.group.rigid_center();\nhoomd.md.integrate.mode_standard(dt=0.001);\nhoomd.md.integrate.nve(group=rigidTest);\n\n\nhoomd.dump.gsd(\"trajectory.gsd\", period=20, group=hoomd.group.all(), overwrite=True);\n\nhoomd.run(5e4);\n\n","sub_path":"scriptRod.py","file_name":"scriptRod.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"152094875","text":"import unittest\n\nimport brain\n\n\nclass XorTest(unittest.TestCase):\n\n def test(self):\n net = brain.NeuralNetwork()\n net.train([\n ([0, 0], [0]),\n ([0, 1], [1]),\n ([1, 0], [1]),\n ([1, 1], [0])\n ])\n output = net.run([1, 0])\n self.assertTrue(output[0] > 0.9)\n","sub_path":"tests/test_xor.py","file_name":"test_xor.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"118547092","text":"import torch\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport datetime\nfrom skimage.measure import compare_ssim, compare_psnr\nfrom utils import mkdir_if_not_exist\n\n############ Parameters ###############\nN = 7\nsigma = 50\ncuda_flag = True\n\nSAVE_PNG = False\nsavedir = './results/'\ndataset_dir = './testsets/ASU/'\npsnrsave = 'ASU-SD_%d.txt' % sigma\nmodel_path = './mynetwork/denoising_%d.pkl' % sigma\n\n\ndef evaluate(dataset_dir, out_img_dir, cuda_flag=True, savetxt='psnr.txt'):\n\n denoisenet = torch.load(model_path)\n if isinstance(denoisenet, torch.nn.DataParallel):\n denoisenet = denoisenet.module\n\n if cuda_flag:\n denoisenet.cuda().eval()\n else:\n denoisenet.eval()\n\n if SAVE_PNG:\n mkdir_if_not_exist(out_img_dir)\n mkdir_if_not_exist(out_img_dir + 'ASU/')\n mkdir_if_not_exist(out_img_dir + 'ASU/%d/' % sigma)\n\n test_img_list = os.listdir(dataset_dir)\n\n str_format = 'im%d.png'\n total_count = 1338 + 7*6\n count = 0\n\n pre = datetime.datetime.now()\n psnr_val = 0\n ssim_val = 0\n\n for file in test_img_list:\n seq_noisy = dataset_dir + file + '/Gauss_%d/noisy/' % sigma\n num = len(os.listdir(seq_noisy))\n psnr = 0\n ssim = 0\n\n noisy_frames = []\n\n if SAVE_PNG:\n mkdir_if_not_exist(out_img_dir + 'ASU/%d/%s/' % (sigma, file))\n\n for j in range(1, num+1):\n noisy_path = seq_noisy + 'im%d.png' % j\n noisy_frames.append(plt.imread(noisy_path))\n\n noisy_frames = np.array(noisy_frames)\n noisy_frames_padded = np.lib.pad(noisy_frames, pad_width=((N // 2, N // 2), (0, 0), (0, 0), (0, 0)), mode='constant')\n noisy_frames_padded = np.transpose(noisy_frames_padded, (0, 3, 1, 2))\n\n for i in range(num):\n reference_path = dataset_dir + file + '/ori/' + str_format % (i+1)\n reference_frame = plt.imread(reference_path)\n\n input_frames = noisy_frames_padded[i:i+N]\n input_frames = torch.from_numpy(input_frames).cuda()\n\n input_frames = input_frames.view(1, input_frames.size(0), input_frames.size(1), input_frames.size(2), input_frames.size(3))\n x_list = denoisenet(input_frames)\n predicted_img = x_list[-1][0, :, :, :]\n\n Img = predicted_img.permute(1, 2, 0).data.cpu().numpy().astype(np.float32)\n\n count += 1\n\n ######## compare PSNR and SSIM ########\n psnr += compare_psnr(Img, reference_frame, data_range=1.)\n ssim += compare_ssim(Img, reference_frame, data_range=1., multichannel=True)\n\n ######## save output images ########\n if SAVE_PNG:\n plt.imsave(out_img_dir + 'ASU/%d/%s/im%d.png' % (sigma, file, i+1), np.clip(Img, 0.0, 1.0))\n\n cur = datetime.datetime.now()\n processing_time = (cur - pre).seconds / count\n\n\n print('%.2fs per frame.\\t%.2fs left.' % (processing_time, processing_time * (total_count - count)))\n\n print('video %s, psnr %.4f, ssim %.4f.\\n' % (file, psnr/num, ssim/num))\n psnr_val += psnr / num\n ssim_val += ssim / num\n # save loss.txt\n txtfile = open(savetxt, 'a')\n txtfile.write('video %s, psnr %.4f, ssim %.4f.\\n' % (file, psnr/num, ssim/num))\n txtfile.close()\n\n ave_psnr_val = psnr_val / len(test_img_list)\n ave_ssim_val = ssim_val / len(test_img_list)\n print('PSNR_val: %.4fdB, SSIM_val: %.4f\\n' % (ave_psnr_val, ave_ssim_val))\n txtfile = open(savetxt, 'a')\n txtfile.write('Average psnr %.4f, ssim %.4f\\n\\n' % (ave_psnr_val, ave_ssim_val))\n txtfile.close()\n\n\nwith torch.no_grad():\n evaluate(dataset_dir, savedir, cuda_flag=cuda_flag, savetxt=psnrsave)\nFalse","sub_path":"evaluate_ASU.py","file_name":"evaluate_ASU.py","file_ext":"py","file_size_in_byte":3740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"428384016","text":"\"\"\"\nSiEPIC Photonics Package \n\nAuthor: Mustafa Hammood\n Mustafa@ece.ubc.ca\n\nExample: Application of SiEPIC_PP: Model the experimental response of a Bragg grating\n\"\"\"\n\n#%% import package and installed dependent packages\nimport sys, os, math, cmath\nimport numpy as np\nfrom numpy.lib.scimath import sqrt as csqrt\n# go up two directories\n#dir_path = os.path.dirname(os.path.abspath(__file__))\n#sys.path.append(os.path.dirname(os.path.dirname(dir_path)))\n\nimport SiEPIC_Photonics_Package as SiEPIC_PP\nfrom SiEPIC_Photonics_Package.setup import *\n\n#%% download .mat files from GitHub repo and parse it to a variable (data)\n# response to be calibrated\nfile_name_in = 'Bragg'\nfile_extension = '.mat'\nurl = 'https://www.dropbox.com/s/hw7dgstrfvseq9q/PCM_PCMBraggDW30_1723.mat?dl=1'\nPORT = 1\ninput_response= SiEPIC_PP.core.download_response(url,PORT)\n\n# Grating design parameters\n\nwavelength_start = 1500e-9\nwavelength_stop = 1600e-9\nresolution = 0.001\n\n# Grating waveguide compact model\n# these are polynomial fit constants from a waveguide width of 500 nm\nn1_g = 4.077182700600432\nn2_g = -0.982556173493906\nn3_g = -0.046366956781710\n\n\n# grating parameters\nperiod = 320e-9 # period of perturbation\nN = 300 # number of periods\n\n# Cavity Parameters\nalpha = 150/4.34\n\n#%% apply SiEPIC_PP calibration correction function\n[power_corrected, power_calib_fit] = SiEPIC_PP.core.calibrate_envelope( input_response, input_response)\n\n#%% plot responses and save pdf\n# raw responses of reference calibration data and input data\nwavelength = input_response[0]*1e9\npower_calib = input_response[1]\nmatplotlib.pyplot.figure(0)\nfig1 = matplotlib.pyplot.plot(wavelength,power_calib, label='Input data', color='red')\nmatplotlib.pyplot.legend(loc=0)\nmatplotlib.pyplot.ylabel('Power (dBm)', color = 'black')\nmatplotlib.pyplot.xlabel('Wavelength (nm)', color = 'black')\nmatplotlib.pyplot.setp(fig1, 'linewidth', 2.0)\nmatplotlib.pyplot.xlim(round(min(wavelength)),round(max(wavelength)))\nmatplotlib.pyplot.title(\"Experimental data (raw)\")\nmatplotlib.pyplot.savefig(file_name_in+'.pdf')\nmatplotlib.rcParams.update({'font.size': 14, 'font.family' : 'Times New Roman', 'font.weight': 'bold'})\n\n# Calibrated responses of the input data\nmatplotlib.pyplot.figure(1)\nfig1 = matplotlib.pyplot.plot(wavelength,power_corrected, label='Calibrated input data', color='red')\nmatplotlib.pyplot.legend(loc=0)\nmatplotlib.pyplot.ylabel('Response (dB)', color = 'black')\nmatplotlib.pyplot.xlabel('Wavelength (nm)', color = 'black')\nmatplotlib.pyplot.setp(fig1, 'linewidth', 2.0)\nmatplotlib.pyplot.xlim(round(min(wavelength)),round(max(wavelength)))\nmatplotlib.pyplot.title(\"Experimental data (calibrated)\")\nmatplotlib.pyplot.savefig(file_name_in+'_calibrated.pdf')\nmatplotlib.rcParams.update({'font.size': 14, 'font.family' : 'Times New Roman', 'font.weight': 'bold'})\n\n#%% extract the bandwidth (3 dB) and central wavelength of the response.\n[bandwidth, central_wavelength] = SiEPIC_PP.core.bandwidth( input_response, 3)\n#print(\"3dB Bandwidth = \"+str(bandwidth))\n#print(\"Central wavelength= \"+str(central_wavelength))\n\n#%% find the coupling coefficient/strength (kappa) of the grating from experimental response\nng = 4.2\nkappa = math.pi*ng*bandwidth/(central_wavelength**2)\n\n#%% Apply coupled-mode thoery\n\nj = cmath.sqrt(-1)\n\nlambda_0 = np.linspace(wavelength_start, wavelength_stop, round((wavelength_stop-wavelength_start)*1e9/resolution))\nneff = (n1_g + n2_g*(lambda_0*1e6) + n3_g*(lambda_0*1e6)**2)\nbeta = 2*math.pi*neff/lambda_0\n\n\nLg_L = N*period\ndeltaB = 2*math.pi*neff/lambda_0-math.pi/period\nomega = csqrt(kappa**2-deltaB**2)\n\n\nt = []; r = []\nfor i in range(len(lambda_0)):\n G_L = [\n [np.cosh(omega[i]*Lg_L)-j*deltaB[i]/omega[i]*np.sinh(omega[i]*Lg_L),\n -j*kappa*np.sinh(omega[i]*Lg_L)/omega[i]],\n [j*kappa*np.sinh(omega[i]*Lg_L)/omega[i],\n np.cosh(omega[i]*Lg_L)+j*deltaB[i]/omega[i]*np.sinh(omega[i]*Lg_L)]]\n\n \n # matrix multiplication G_L*Y*G_R\n H = G_L\n \n t.append(H[0][0]-H[1][0]*H[0][1]/H[1][1])\n r.append(-H[1][0]/H[1][1])\n \n# to log scale\nT = np.log10(np.absolute(t)**2)\nR = np.log10(np.absolute(r)**2)\n\n#%% plot spectrum\nmatplotlib.pyplot.figure(2)\nfig1 = matplotlib.pyplot.plot(lambda_0*1e9,T, label='Transmission', color='blue')\nfig2 = matplotlib.pyplot.plot(lambda_0*1e9,R, label='Reflection', color='red')\nmatplotlib.pyplot.legend(loc=0)\nmatplotlib.pyplot.ylabel('Response (dB)', color = 'black')\nmatplotlib.pyplot.xlabel('Wavelength (nm)', color = 'black')\nmatplotlib.pyplot.setp(fig1, 'linewidth', 2.0)\nmatplotlib.pyplot.setp(fig2, 'linewidth', 2.0)\nmatplotlib.pyplot.xlim(round(min(lambda_0*1e9)),round(max(lambda_0*1e9)))\nmatplotlib.pyplot.title(\"Calculated response of the structure using CMT (log scale)\")\nmatplotlib.pyplot.savefig('bragg_cmt_log'+'.pdf')\nmatplotlib.rcParams.update({'font.size': 14, 'font.family' : 'Times New Roman', 'font.weight': 'bold'})\n\nmatplotlib.pyplot.figure(3)\nfig1 = matplotlib.pyplot.plot(lambda_0*1e9,np.absolute(t), label='Transmission', color='blue')\nfig2 = matplotlib.pyplot.plot(lambda_0*1e9,np.absolute(r), label='Reflection', color='red')\nmatplotlib.pyplot.legend(loc=0)\nmatplotlib.pyplot.ylabel('Response', color = 'black')\nmatplotlib.pyplot.xlabel('Wavelength (nm)', color = 'black')\nmatplotlib.pyplot.setp(fig1, 'linewidth', 2.0)\nmatplotlib.pyplot.setp(fig2, 'linewidth', 2.0)\nmatplotlib.pyplot.xlim(round(min(lambda_0*1e9)),round(max(lambda_0*1e9)))\nmatplotlib.pyplot.title(\"Calculated response of the structure using CMT (linear scale)\")\nmatplotlib.pyplot.savefig('bragg_cmt_linear'+'.pdf')\nmatplotlib.rcParams.update({'font.size': 14, 'font.family' : 'Times New Roman', 'font.weight': 'bold'})\n","sub_path":"Examples/Applications/Bragg_experimental/Bragg_experimental.py","file_name":"Bragg_experimental.py","file_ext":"py","file_size_in_byte":5703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"302673385","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 5 14:49:25 2020\n\n@author: evaneastin\n\"\"\"\n\n# PHYS 128AL FINAL LAB: Muon Flux Experiment\n# aiming to quantify flux of cosmic ray particles, angled N-S, form zenith angles 0-90\n# want to show discrepancy between flat and round earth distributions\n\nimport numpy as np\n# approximate rectangular detector dimensions, use for flux, found using vernier caliper\nw = 10.2 * 10**(-2) # m\nl = 10.7 * 10**(-2) # m\nA = l * w # area estimate of rect. detector in m^2\nderr = .001/np.sqrt(12) # uncertianty in vernier caliper\nAerr = A * np.sqrt((derr/w)**2 + (derr/l)**2) # uncertainty in detector area\nalpha = 9.08 # uncertainty in zenith angle **important one**\nbeta = 10.8 # uncertainty in azimuthal angle, half of total sep angle\n\n# defined constants for the fitting curve\nR = 6371.371 * 10**3 # Earth's radius in m\n# calculated using latitude (34.41406135) and elevation (~26 m) from https://www.maps.ie/coordinates.html\n# https://rechneronline.de/earth-radius/ combined above values to get radius\nd_low = 10 * 10**3 # lowest expected height above ground of muon production in m\nd_high = 15 * 10**3 # greatest expected height above ground of muon production in m\n\ndef D_round(R, d, x): # closed column density expression for curved atmosphere\n return np.sqrt((R ** 2 / d ** 2) * np.cos(x) **2 + (2 * R / d) + 1) - (R * np.cos(x) / d)\n\ndef MuonEFlux(Dfunc, I_0, n): # muon energy integrated flux\n return I_0 * (Dfunc) ** (-(n - 1))\n\ndef cosfit(x, I_0, n): # fit function from zenith angle dependence of cosmic muons\n return I_0 * np.cos(x)**(n - 1)\n\ndef MuonFlux(counts, area, time): # observed muon flux from experiment\n return counts / (area * time)\n\ndef FluxErr(count, counterr, area, aerr): # equal to the flux uncertainty divided by calculated flux\n return np.sqrt((counterr/count)**2 + (aerr/area)**2)\n\ndef regression(fitfunc, y): # returns residual sum of squares\n return sum((fitfunc - y)**2)\n\ndef residuals(fitfunc, y): # returns residuals\n return np.array(fitfunc - y)\n\nimport matplotlib.pyplot as plt\nfrom scipy import optimize, stats\n\ntheta = np.radians(90 - np.array([10, 25, 40, 55, 70, 85])) # zenith angle\nN = np.array([482, 652, 61, 85, 107, 172]) # observed counts\nNerr = np.array([np.sqrt(N)]) # count uncertainty\nobserv_time = np.array([70000, 70000, 4000, 4000, 4000, 4000]) # observation time in seconds\nflux= MuonFlux(N, A, observ_time) # calculated flux without subtracting accidental rate\nnewflux = ((N / observ_time) - 0.00001536765222) / A # final calculated flux removing rate of accidentals\nobserverr = FluxErr(N, Nerr, A, Aerr)\nnewerr = newflux * observerr # total flux uncertainty\n\nx = np.linspace(0, np.pi / 2, 2000)\n\nxnew = D_round(R, d_low, theta)\n\na = np.radians(alpha)/2\nthetaerr = np.array([a, a, a, a, a, a]) # angle uncertianty calculated from alpha\n\n# plotting of full results\n\n# plot 1: overall distributions with log10 y scale\nplt.errorbar(theta, newflux, yerr=newerr.flatten(), xerr=thetaerr, fmt='.', label='Observed Data')\n\npopt, pcov = optimize.curve_fit(MuonEFlux, xnew, newflux, p0=[4, 3], bounds=(0, 5))\nn_fit = popt\nfiterr = np.sqrt(np.diag(pcov))\nxplot = np.linspace(0, np.pi / 2, 2000)\nyplot1 = MuonEFlux(D_round(R, d_high, xplot), n_fit[0], n_fit[1])\nplt.plot(xplot, yplot1, '-', color='green', label='Fitted Round Earth Distribution')\n\npopt2, pcov2 = optimize.curve_fit(cosfit, theta, newflux, p0=[4, 3], bounds=(0, 5))\nfiterr2 = np.sqrt(np.diag(pcov2))\nprint(popt2, fiterr2)\n\nplt.plot(xplot, cosfit(xplot, *popt2), color='black', label='Fitted Flat Earth Distribution')\nplt.plot(xplot, 4 * np.cos(xplot)**2, color='red', label=r'$\\cos^{2}(\\theta_{z})$')\nplt.ylabel(r'Muon Flux [counts $m^{-2} s^{-1}$]')\nplt.xlabel(r'Angle $\\theta_{z}$ from zenith [radians]')\nplt.yscale('log')\nplt.ylim(10**(-2), 5)\nplt.xlim(0, np.pi / 2)\nplt.xticks(np.arange(0, np.pi / 2 + np.pi / 10, np.pi / 10), labels=[0, r'$\\frac{\\pi}{10}$', r'$\\frac{\\pi}{5}$', r'$\\frac{3\\pi}{10}$', r'$\\frac{2\\pi}{5}$', r'$\\frac{\\pi}{2}$'])\nplt.title('Muon Flux Distribution as a Function of Zenith Angle')\nplt.grid()\nplt.legend()\nplt.show()\n\n# plot 2: detailed plot around 90 deg, should show discrepancy between flat and round earth distributions\nplt.plot(xplot, yplot1, '-', color='green', label='Fitted Round Earth Distribution')\nplt.plot(xplot, cosfit(xplot, *popt2), color='black', label='Fitted Flat Earth Distribution')\nplt.plot(xplot, 4 * np.cos(xplot)**2, color='r', label=r'$\\cos^{2}(\\theta_{z})$')\nplt.ylabel(r'Muon Flux [counts $m^{-2} s^{-1}$]')\nplt.xlabel(r'Angle $\\theta_{z}$ from zenith [radians]')\nplt.xlim(11 * np.pi / 24, np.pi / 2)\nplt.xticks(np.arange(11 * np.pi / 24, np.pi / 2, np.pi / 24), labels=[r'$\\frac{11\\pi}{24}$', r'$\\frac{\\pi}{2}$'])\nplt.ylim(0, 0.1)\nplt.grid()\nplt.legend()\nplt.title(r'Muon Flux Distribution around $\\theta_{z} = \\frac{\\pi}{2}$')\nplt.show()\n\nrss = regression(MuonEFlux(D_round(R, d_high, theta), n_fit[0], n_fit[1]), flux) # residual sum of squares\nresid = residuals(MuonEFlux(D_round(R, d_high, theta), n_fit[0], n_fit[1]), flux) # residuals\n\n\nchisquare1 = stats.chisquare(flux, MuonEFlux(D_round(R, d_high, theta), n_fit[0], n_fit[1]), 2) # chi-squared test for round earth distribution\nchisquare2 = stats.chisquare(flux, cosfit(theta, *popt2), 2) # chi-squared test for flat earth distribution\n\nprint(MuonEFlux(D_round(R, d_high, np.pi/2), n_fit[0], n_fit[1]))\n\n# making some new changes in order to see if push/pull requests work??\n# making another change to make sure we can push this to github\n","sub_path":"MuonFluxEXP.py","file_name":"MuonFluxEXP.py","file_ext":"py","file_size_in_byte":5545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"597472996","text":"## A module search for optimal phenology based on carbon optimization\n# Author: Xiangtao Xu\n\nimport numpy as np\nimport sys\nimport pdb\nfrom myForest import Leaves, Canopy\nfrom myUtils import weighted_percentile\n\n\n##############################################################################\n##############################################################################\n# PhenOpt class\n# This call includes methods to calculate the optimal phenology given\n# functional traits and average climate\n\nclass PhenOpt(object):\n\n # first some class-level constants for phenology \n SHED_WINDOW = 14\n # number of days for leaves to shed after the shedding criterion is met\n MATURE_WINDOW = 21\n # number of days for new leaves to mature\n\n WATER_STRESS = 0\n # level of water stress [0 -> 2]\n\n TMP_DIFF = 5.\n # leaf temperature difference between sun-lit and shaded leaves\n\n UMOL2G = 1e-6 * 12\n # convert from umol CO2 to gC\n\n TIMESTEP = 1 # default running at one day resolution\n\n LEAF_TURNOVER = 1e-4\n # baseline leaf turnover rate [day-1]\n\n SIM_YEAR = 50\n # default running for 50 years\n\n SIM_CC2LMA = 1.5/2.\n # default construction cost\n # Xu et al. 2016\n\n C_RESORPTION = 0.2\n # carbon resorption efficiency is 20% from Vergutz et al. 2012\n\n # reference climate to calculate PC\n REF_TMP = 25. # degC\n REF_VPD = 1000. # Pa\n REF_PAR = 1200. # umol/m2/sec\n REF_SZA = 30. # solar zenith angle, 30deg\n\n #--------------------------\n # class method\n @classmethod\n def convert_vpd(cls,vpd,org_tmp,new_tmp):\n '''\n convert vpd at org_tmp to vpd at new_tmp assuming the vapor\n pressure does not change\n '''\n\n # first calculate the vp at org_tmp\n # some constants to calculate vpd\n c0 = .6105851e+03\n c1 = .4440316e+02\n c2 = .1430341e+01\n c3 = .2641412e-01\n c4 = .2995057e-03\n c5 = .2031998e-05\n c6 = .6936113e-08\n c7 = .2564861e-11\n c8 =-.3704404e-13\n\n\n x = org_tmp\n vp = ( c0 + x\n * ( c1 + x\n * ( c2 + x\n * ( c3 + x\n * ( c4 + x\n * ( c5 + x\n * ( c6 + x\n * ( c7 + x * c8\n )))))))) - vpd\n x = new_tmp\n return ( c0 + x\n * ( c1 + x\n * ( c2 + x\n * ( c3 + x\n * ( c4 + x\n * ( c5 + x\n * ( c6 + x\n * ( c7 + x * c8\n )))))))) - vp\n\n @classmethod\n def get_tmp_diff(cls,par,tmp_air):\n '''\n Get the leaf-air temperature difference based on Rey-Sanchez et al. 2016 Climate\n Research\n\n The paper offered different equations for wet season (low Tair) and dry season (high\n Tair). Here we just take the maximum difference from the two equations because the wet\n season equation tends to underestimate the difference at higher temperature\n '''\n\n # tmp_air in degC\n # par in umol/m2/sec\n tmp_diff = np.maximum(0.,(np.maximum(\n np.exp(1.354) * (par ** 0.026) * (tmp_air ** 0.554), # wet season\n np.exp(-0.074) * (par ** 0.005) * (tmp_air ** 1.015) # dry season\n ) - tmp_air\n ))\n return tmp_diff\n\n\n\n #--------------------------\n # Initialization of the class\n def __init__(self,\n spCode : 'Species Code' ,\n spLMA : 'LMA of each species' ,\n spVcmax25 : 'Vcmax25 of each species' ,\n spG1 : 'Stomatal slope of each species' ,\n spB : 'Species ageing rate' ,\n siteLat : 'site latitude' ,\n siteLon : 'site longitude' ,\n laiProfile : 'laiProfile for each species' = [0.5,0.5,1.,1.],\n spTLP : 'Species Turgor Loss Point' = None\n ):\n\n # first check input quality\n input_lens = [len(spCode),len(spLMA),len(spVcmax25),len(spG1),len(spB)]\n if spTLP is not None:\n input_lens.append(len(spTLP))\n\n assert len(np.unique(input_lens)) == 1,\\\n 'Input species traits do not have the same length!'\n\n # store the input into instance variables\n self.spCode = np.array(spCode)\n self.spLMA = np.array(spLMA)\n self.spVcmax25 = np.array(spVcmax25)\n self.spG1 = np.array(spG1)\n self.spB = np.array(spB)\n if spTLP is None:\n self.spTLP = None \n else:\n self.spTLP = np.array(spTLP)\n\n self.spNum = len(self.spCode)\n self.laiProfile = np.array(laiProfile)\n self.layerNum = (len(self.laiProfile) - 1) # don't include the last layer\n\n # predict maturation window using LMA according to Miyazawa et al. 1998\n # Fig. 5\n self.maturation = (self.spLMA / 3. + 15).astype(int)\n\n self.siteLat = siteLat\n self.siteLon = siteLon\n \n\n # initiate look-up table for phenology optimization\n\n # 1. local optimization\n self.Gmax_local = np.zeros((365,self.layerNum,self.spNum))\n # maximum leaf lifetime average daily carbon gain rate by only\n # considering local optimization\n\n self.LL_local = np.zeros((365,self.layerNum,self.spNum))\n # optimal leaf longevity by only consiering local optimization\n\n self.Td_local = np.zeros((365,self.layerNum,self.spNum))\n\n # 2. Consider dormant period\n #self.Gmax_dormant = np.zeros((365,self.layerNum,self.spNum))\n # maximum leaf lifetime average daily carbon gain rate by\n # considering local optimization and possibility of dormancy\n\n #self.LL_dormant = np.zeros((365,self.layerNum,self.spNum))\n # optimal leaf longevity by considering local optimization and\n # possibility of dormancy\n\n #self.T_dormant = np.zeros((365,self.layerNum,self.spNum))\n # optimal dormancy time by considering local optimization and\n # possibility of dormancy\n\n\n # 3. Consider cascading effect\n self.Gmax_all = np.zeros((365,self.layerNum,self.spNum))\n # maximum leaf lifetime average daily carbon gain rate by\n # considering local optimization, possibility of dormancy and cascading\n # effect\n\n self.LL_all = np.zeros((365,self.layerNum,self.spNum))\n # optimal leaf longevity by considering local optimization and\n # possibility of dormancy\n \n self.Td_all = np.zeros((365,self.layerNum,self.spNum))\n\n\n\n # initiate results for phenology simulations\n self.sim_lai_avg = np.zeros((365,self.layerNum,self.spNum))\n # average seasonal cycle of simulated LAI\n\n self.sim_lai_y = np.zeros((365,self.layerNum,self.spNum))\n # average seasonal cycle of simulated LAI for young leaves (<= 2month)\n self.sim_lai_m = np.zeros((365,self.layerNum,self.spNum))\n # average seasonal cycle of simulated LAI for mature leaves (> 2 month <= 6 month)\n self.sim_lai_o = np.zeros((365,self.layerNum,self.spNum))\n # average seasonal cycle of simulated LAI for old leaves (> 6 month)\n\n\n self.sim_litter_avg = np.zeros((365,self.layerNum,self.spNum))\n # average seasonal cycle of simulated leaf litter in units of LAI\n\n self.sim_age_avg = np.zeros((365,self.layerNum,self.spNum))\n # average seasonal cycle of average leaf age\n \n self.sim_gain_avg = np.zeros((365,self.layerNum,self.spNum))\n # average seasonal cycle of simulated realized daily carbon gain rate\n\n self.sim_gpp_avg = np.zeros((365,self.layerNum,self.spNum))\n # average seasonal cycle of simulated realized GPP\n\n self.sim_pc_avg = np.zeros((365,self.layerNum,self.spNum))\n # average seasonal cycle of simulated photosynthetic capacity at reference climate\n\n self.sim_LL_stats = np.zeros((6,self.layerNum,self.spNum))\n # Statistics of the realized leaf longeivty\n # Mean, 5%,25%,50%,75%,95% percentiles\n\n\n # for now we do not consider the interactions between LAI and leaf\n # light environment\n\n # \n #--------------------------\n\n #--------------------------\n # instance method\n # calculate optimal carbon look-up table based on average climate seasonality\n # and simulate phenology\n #-------------------------\n def optimize_clim_avg(self,\n PAR : 'photosynthetically active radiation [umol/m2/s]',\n Rshort : 'total incoming short wave radiation [umol/m2/s]',\n vpd : 'vapor pressure deficit [Pa]',\n tmp : 'air temperature [degC]',\n pres : 'air pressure [Pa]',\n freezeRisk : 'freeze risk for each day' = None,\n soil_psi : 'soil water potential [MPa] (optional)' = None,\n TMP_OPTION : 'option to calcualte leaf temperature' = 1,\n is_local : 'whether the diurnal cycle is in local ime' = True,\n sza_option : 'whether allow sza to change seasonally' = 0,\n is_debug : 'whether go into debugging mode using pdb' = False,\n trait_adapt: 'where include vertical trait plasticity/adaption' = False,\n N : 'number of leaf cycles to track in optimization' = 5,\n ):\n '''\n Calculate the optimized phenology look-up table\n '''\n\n # first check input data quality\n if not isinstance(PAR,np.ndarray):\n PAR = np.array(PAR)\n if not isinstance(Rshort,np.ndarray):\n Rshort = np.array(Rshort)\n if not isinstance(vpd,np.ndarray):\n vpd = np.array(vpd)\n if not isinstance(tmp,np.ndarray):\n tmp = np.array(tmp)\n if not isinstance(pres,np.ndarray):\n pres = np.array(pres)\n if (soil_psi is not None) and (not isinstance(soil_psi,np.ndarray)):\n soil_psi = np.array(soil_psi)\n\n assert len(PAR.shape) == 2 and PAR.shape[0] == 365,\\\n 'PAR should have two dimensions with the first as seasonal and the second as diurnal'\n assert len(Rshort.shape) == 2 and Rshort.shape[0] == 365,\\\n 'Rshort should have two dimensions with the first as seasonal and the second as diurnal'\n assert len(vpd.shape) == 2 and vpd.shape[0] == 365,\\\n 'vpd should have two dimensions with the first as seasonal and the second as diurnal'\n assert len(tmp.shape) == 2 and tmp.shape[0] == 365,\\\n 'tmp should have two dimensions with the first as seasonal and the second as diurnal'\n assert len(pres.shape) == 2 and pres.shape[0] == 365,\\\n 'pres should have two dimensions with the first as seasonal and the second as diurnal'\n if soil_psi is not None:\n assert len(soil_psi.shape) == 1 and soil_psi.shape[0] == 365,\\\n 'soil_psi should have one dimension represents seasonality'\n\n\n\n # Need to create a canopy class to calculate leaf-level climate\n dielNum = PAR.shape[1]\n myCanopy = Canopy(self.laiProfile)\n\n leafPar_sun = np.zeros(PAR.shape + (self.layerNum,))\n leafPar_shade = np.zeros(PAR.shape + (self.layerNum,))\n leafPar_fsun = np.zeros(PAR.shape + (self.layerNum,))\n\n for cur_doy in np.arange(365):\n for iDiel in np.arange(dielNum):\n # get cur climate\n curPar = PAR[cur_doy,iDiel]\n curRshort = Rshort[cur_doy,iDiel]\n\n # deal with time zone\n # need to convert to UTC from local time if necessary\n if is_local:\n ihour = (iDiel + 0.5) / dielNum * 24.\n else:\n ihour = np.mod(\n (iDiel + 0.5) / dielNum * 24.\n + np.round(self.siteLon / 15.) ,24)\n\n hourAng = (ihour - 12.) * np.pi / 12.\n declineAng = (-23.44 / 180. * np.pi *\n np.cos(2.*np.pi/365.*(cur_doy+10.)))\n # hour angle\n\n if sza_option == 0:\n curSZA = np.arccos( np.sin(self.siteLat/180. * np.pi) \n * np.sin(declineAng)\n + np.cos(self.siteLat/180. * np.pi)\n * np.cos(declineAng)\n * np.cos(hourAng)\n ) / np.pi * 180.\n elif sza_option == 1:\n declineAng = (-23.44 / 180. * np.pi *\n np.cos(2.*np.pi/365.*(113+10.))) # spring equinox\n curSZA = np.arccos( np.sin(self.siteLat/180. * np.pi) \n * np.sin(declineAng)\n + np.cos(self.siteLat/180. * np.pi)\n * np.cos(declineAng)\n * np.cos(hourAng)\n ) / np.pi * 180.\n else:\n print('wrong option for sza_option!')\n return -1\n\n\n myCanopy.radiative_transfer(curPar,curSZA,Rshort=curRshort)\n #print(ihour,hourAng,curSZA)\n #print(curRshort,curPar)\n #print(myCanopy.layerParSun)\n #print(myCanopy.layerParShade)\n for ilayer in np.arange(self.layerNum):\n leafPar_sun[cur_doy,iDiel,ilayer] = \\\n np.maximum(0.,myCanopy.layerParSun[ilayer])\n leafPar_shade[cur_doy,iDiel,ilayer] = \\\n np.maximum(0.,myCanopy.layerParShade[ilayer])\n leafPar_fsun[cur_doy,iDiel,ilayer] = \\\n np.maximum(0.,myCanopy.layerFSun[ilayer])\n\n # calculate temperature difference based on \n leafTmpDiff_sun = np.zeros_like(leafPar_sun)\n leafTmpDiff_shade = np.zeros_like(leafPar_shade)\n if TMP_OPTION == 0:\n # constant tmp_diff\n leafTmpDiff_sun[:] = self.TMP_DIFF\n leafTmpDiff_shade[:] = 0.\n elif TMP_OPTION == 1:\n # use Rey-Sanches from BCI\n for ilayer in np.arange(self.layerNum):\n leafTmpDiff_sun[:,:,ilayer] = self.get_tmp_diff(leafPar_sun[:,:,ilayer],tmp)\n leafTmpDiff_shade[:,:,ilayer] = self.get_tmp_diff(leafPar_shade[:,:,ilayer],tmp)\n # print the average, 5%, 95% of temperature difference\n# print('Sun-lit leaves')\n# print('Mean tmp_diff:\\n',np.amax(np.nanmean(leafTmpDiff_sun,axis=0),axis=0))\n# print('5pct tmp_diff:\\n',np.amax(np.nanpercentile(leafTmpDiff_sun,5.,axis=0),axis=0))\n# print('95pcttmp_diff:\\n',np.amax(np.nanpercentile(leafTmpDiff_sun,95.,axis=0),axis=0))\n# print('Mean leafPar_sun:\\n',np.nanmean(leafPar_sun,axis=0))\n# print('seasonal leafPar_sun:\\n',np.nanmean(leafPar_sun,axis=1)[:,0])\n#\n# print('Shaded leaves')\n# print('Mean tmp_diff:\\n',np.amax(np.nanmean(leafTmpDiff_shade,axis=0),axis=0))\n# print('5pct tmp_diff:\\n',np.amax(np.nanpercentile(leafTmpDiff_shade,5.,axis=0),axis=0))\n# print('95pct tmp_diff:\\n',np.amax(np.nanpercentile(leafTmpDiff_shade,95.,axis=0),axis=0))\n# print('Mean leafPar_shade:\\n',np.nanmean(leafPar_shade,axis=0))\n\n\n # we also need to get the light profile at reference level to calculate PC\n myCanopy.radiative_transfer(self.REF_PAR,self.REF_SZA)\n\n # loop over each canopy layer and each species to fill in the look up\n # table\n for ilayer in np.arange(self.layerNum):\n # loop over the species to calculate Gmax and LL\n for isp,spName in enumerate(self.spCode):\n\n if trait_adapt:\n # include within-canopy trait adaptation\n\n # Assume LMA and Vcmax follow the same extinction rule\n # Following Lloyd et al. 2010\n # In this case, spB would not change\n\n k_ext = np.exp(0.00963 * self.spVcmax25[isp] - 2.43)\n k_lma_ext = k_ext - 0.035 \n # LMA extinction rate, estimated from the BCI data\n # The idea is that LMA goes down slower than Vcmax within canopy\n # so that at lower canopy, Vcmax/LMA is smaller than Vcmax/LMA at canopy\n\n if ilayer == 0:\n top_lai = 0.\n else:\n top_lai = np.sum(self.laiProfile[0:ilayer])\n \n layer_Vcmax25 = self.spVcmax25[isp] * np.exp(-k_ext * top_lai)\n layer_LMA = self.spLMA[isp] * np.exp(-k_lma_ext * top_lai)\n layer_maturation = (layer_LMA / 3. + 15).astype(int)\n layer_spB = (10. ** (Leaves.bB[0] + Leaves.bB[1] * \n np.log10(layer_Vcmax25 / layer_LMA))).astype(int)\n\n else:\n # no within-canopy trait adaptation\n layer_Vcmax25 = self.spVcmax25[isp]\n layer_LMA = self.spLMA[isp]\n layer_maturation = self.maturation[isp]\n layer_spB = self.spB[isp]\n\n print(ilayer,spName,layer_spB)\n # first ditermine the time when Vcmax becomes 0, or absolutely non-profitable\n # we will search the optimum within that length\n search_day_max = layer_maturation + layer_spB\n cur_Vcmax_array = np.zeros((search_day_max,))\n\n\n # used to calculate realized lai for the species\n cur_lai_frac_array = np.ones((search_day_max,))\n cur_lai_frac_array[0:layer_maturation] = \\\n np.arange(layer_maturation).astype(float) / layer_maturation\n\n\n cur_Vcmax_array[0:layer_maturation] = layer_Vcmax25 * \\\n (np.arange(0,layer_maturation) + 1) / float(layer_maturation)\n cur_Vcmax_array[layer_maturation:search_day_max] = np.maximum(0.\n , layer_Vcmax25\n * (1. - (np.arange(layer_maturation,search_day_max)\n - float(layer_maturation)) / layer_spB))\n\n\n # structure to record the carbon gain rates for all combinations of doy and age\n daily_gain_matrix = np.zeros((search_day_max,365))\n daily_pc_matrix = np.zeros((search_day_max,365))\n daily_gpp_matrix = np.zeros((search_day_max,365))\n\n # create a leaf class\n init_LMA_array = np.ones((search_day_max,)) * layer_LMA\n init_matureVcmax25_array = np.ones((search_day_max,)) * layer_Vcmax25\n init_spCode_array = np.repeat(spName,search_day_max)\n sp_leaf = Leaves(search_day_max,LMA=init_LMA_array,\n matureVcmax25=init_matureVcmax25_array,\n spCode=init_spCode_array,\n age=np.arange(1,search_day_max+1))\n\n # reset stomatal conductance slope for each species\n sp_leaf.g1 = self.spG1[isp]\n\n # calculate the temperature threshold for the species\n\n\n for cur_doy in np.arange(365):\n # update Vcmax and Jmax\n\n # water stress\n if self.WATER_STRESS == 0:\n # no water stress\n water_stress_factor = 1.\n else:\n # include water stress\n cur_soil_psi = soil_psi[cur_doy] \n if self.spTLP is None:\n # No TLP provided use soil psi\n water_stress_factor = (\n np.maximum(1e-6,np.minimum(1.,\n (cur_soil_psi - (-1.5)) / 1.5 )) * self.WATER_STRESS / 100\n + 1. * (100. - self.WATER_STRESS) / 100.\n\n )\n else:\n water_stress_factor = (\n np.maximum(1e-6,np.minimum(1.0,\n 1. / (1. + (cur_soil_psi / self.spTLP[isp]) ** 4.0)))\n * self.WATER_STRESS / 100.\n + 1. * (100 - self.WATER_STRESS) / 100.\n )\n \n\n # update Vcmax (ageing + water stress)\n sp_leaf.Vcmax25 = cur_Vcmax_array * water_stress_factor\n sp_leaf.Jmax25 = (Leaves.Jmax25B[0] + Leaves.Jmax25B[1] *\n cur_Vcmax_array) * water_stress_factor\n\n sp_leaf.dailyGain[:] = 0.\n\n daily_gpp = np.zeros_like(sp_leaf.dailyGain)\n\n\n\n for iDiel in np.arange(dielNum):\n # first sun-lit leaves\n\n # input need to be array\n leaf_vpd = PhenOpt.convert_vpd(\n vpd[cur_doy,iDiel],\n tmp[cur_doy,iDiel],\n tmp[cur_doy,iDiel]+leafTmpDiff_sun[cur_doy,iDiel,ilayer])\n sp_leaf.update_climate([tmp[cur_doy,iDiel]\n +leafTmpDiff_sun[cur_doy,iDiel,ilayer]],\n [leafPar_sun[cur_doy,iDiel,ilayer]],\n [leaf_vpd]) \n\n # perform photosynthesis\n An = sp_leaf.photosynthesize()\n # add net An to daily Cgain\n sp_leaf.dailyGain += An * leafPar_fsun[cur_doy,iDiel,ilayer]\n\n daily_gpp += ((sp_leaf.An + sp_leaf.Rd) *\n leafPar_fsun[cur_doy,iDiel,ilayer])\n\n # shaded leaves\n # input need to be array\n leaf_vpd = PhenOpt.convert_vpd(\n vpd[cur_doy,iDiel],\n tmp[cur_doy,iDiel],\n tmp[cur_doy,iDiel]+leafTmpDiff_shade[cur_doy,iDiel,ilayer])\n\n sp_leaf.update_climate([tmp[cur_doy,iDiel]\n +leafTmpDiff_shade[cur_doy,iDiel,ilayer]],\n [leafPar_shade[cur_doy,iDiel,ilayer]],\n [leaf_vpd]) \n\n # perform photosynthesis\n An = sp_leaf.photosynthesize()\n\n # add net An to daily Cgain\n sp_leaf.dailyGain += An * (1. -\n leafPar_fsun[cur_doy,iDiel,ilayer])\n daily_gpp += ((sp_leaf.An + sp_leaf.Rd) *\n (1. - leafPar_fsun[cur_doy,iDiel,ilayer]))\n\n\n\n\n\n daily_gain_matrix[:,cur_doy] += sp_leaf.dailyGain\\\n * (self.UMOL2G * 86400. / dielNum)\n daily_gpp_matrix[:,cur_doy] += (daily_gpp *\n self.UMOL2G * 86400. / dielNum)\n\n # PC\n if TMP_OPTION == 0:\n pc_tmp_diff_sun = self.TMP_DIFF\n pc_tmp_diff_shade = 0.\n elif TMP_OPTION == 1 :\n pc_tmp_diff_sun = self.get_tmp_diff(\n np.maximum(0.,myCanopy.layerParSun[ilayer]),self.REF_TMP) \n pc_tmp_diff_shade = self.get_tmp_diff(\n np.maximum(0.,myCanopy.layerParShade[ilayer]),self.REF_TMP) \n\n # first sun-lit leaves\n leaf_vpd = PhenOpt.convert_vpd(\n self.REF_VPD,\n self.REF_TMP,\n self.REF_TMP+pc_tmp_diff_sun)\n sp_leaf.update_climate([self.REF_TMP + pc_tmp_diff_sun],\n [myCanopy.layerParSun[ilayer]],\n [leaf_vpd]) \n\n # perform photosynthesis\n sp_leaf.photosynthesize()\n # add net An to daily Cgain\n daily_pc_matrix[:,cur_doy] += ((sp_leaf.An + sp_leaf.Rd) * myCanopy.layerFSun[ilayer])\n\n # then shaded leaves\n leaf_vpd = PhenOpt.convert_vpd(\n self.REF_VPD,\n self.REF_TMP,\n self.REF_TMP+pc_tmp_diff_shade)\n sp_leaf.update_climate([self.REF_TMP + pc_tmp_diff_shade],\n [myCanopy.layerParShade[ilayer]],\n [leaf_vpd]) \n\n # perform photosynthesis\n sp_leaf.photosynthesize()\n # add net An to daily Cgain\n daily_pc_matrix[:,cur_doy] += ((sp_leaf.An + sp_leaf.Rd) * (1.-myCanopy.layerFSun[ilayer]))\n # umol/m2/sec\n\n\n\n ####################################################################\n for cur_doy in np.arange(365):\n # TRACK freezing damage for trees with high Vcmax/LMA\n # currently the threshold is set arbitrarily as 0.3\n # umol/m2/g\n # use -2.3 degC as a temperature threshold\n if (freezeRisk is not None and \n self.spVcmax25[isp]/self.spLMA[isp] > 0.3 and\n freezeRisk[cur_doy] > 0.):\n\n\n for leaf_age in np.arange(search_day_max):\n idx_first = np.arange(leaf_age,search_day_max)\n idx_second = np.mod(cur_doy+np.arange(len(idx_first)),365)\n\n # reduce future carbon gain\n daily_gain_matrix[idx_first,idx_second] *= (1. -\n freezeRisk[cur_doy])\n # reduce resorption\n daily_gain_matrix[leaf_age,cur_doy] -= (\n freezeRisk[cur_doy] * layer_LMA * \n self.C_RESORPTION * self.SIM_CC2LMA)\n \n\n # go to next doy\n continue\n\n\n # include WATER STRESS\n # Basically, when water stress level < 0.5 (leaf water potential < TLP)\n # Leaves cannot expand, thus any daily_gain_matrix starting from these days\n # shall have zero values\n # water stress\n# if self.WATER_STRESS == 0:\n# # no water stress\n# water_stress_factor = 1.\n# else:\n# # include water stress\n# cur_soil_psi = soil_psi[cur_doy] \n# if self.spTLP is None:\n# # No TLP provided use soil psi\n# water_stress_factor = (\n# np.maximum(1e-6,np.minimum(1.,\n# (cur_soil_psi - (-1.5)) / 1.5 )) * self.WATER_STRESS / 100\n# + 1. * (100. - self.WATER_STRESS) / 100.\n#\n# )\n# else:\n# water_stress_factor = (\n# np.maximum(1e-6,np.minimum(1.0,\n# 1. / (1. + (cur_soil_psi / self.spTLP[isp]) ** 4.0)))\n# * self.WATER_STRESS / 100.\n# + 1. * (100 - self.WATER_STRESS) / 100.\n# )\n#\n# if water_stress_factor < 0.5:\n# # all the leaves within half of leaf_maturation time would fall and lead to\n# # zero daily gain\n# for leaf_age in np.arange(layer_maturation//2):\n# idx_first = np.arange(leaf_age,search_day_max)\n# idx_second = np.mod(cur_doy+np.arange(len(idx_first)),365)\n#\n# # reduce future carbon gain to zero\n# daily_gain_matrix[idx_first,idx_second] *= (0.)\n \n\n # finally set all the nan values to zero\n #daily_gain_matrix[np.isnan(daily_gain_matrix[:])] = 0.\n\n\n # calculate PC for all leaf ages\n \n # Another potential way for the optimization\n # First, for the optimization to work, we need to make sure the\n # total time considered is infinitely large or at least the\n # same. So we can choose 2 * (search_day_max + 365) - 1 as Tt. In this case any\n # leaf cycles should spend at least two cohorts of leaves to\n # cover the period\n\n # Second, now we redefine the problem as finding split date(s)\n # so that the total carbon gain over the study period is\n # maximized. This is equivalent to maximize the life-time\n # average carbon gain rate\n\n # Third, We construct a matrix as Gt(365,Tt,N) to record total\n # carbon gain. Gt means the maximum carbon gain for leaf\n # cohorts that start on doy, extends for Tt and have N life\n # cycles. First dimension is the starting doy, second dimension\n # is the length of the study period, third dimension is how many cohorts to\n # consider. This is an auxiliary data structure to help\n # determin the best way to split Tt. For instance, if we want\n # to know what's the best LL for the first leaf life cycle\n # within the study period, we only need to find LL that\n # maximizes Gt(doy,LL,0) + np.amax(Gt(doy+LL,:,N))\n\n # Fourth, fill up Gt\n # first, get a structure of daily_gain_matrix[Tt,365] and\n # For N = 0\n # Gt(doy,Tt,N) = np.amax(np.sum(daily_gain_matrix[Tt-Td,doy+Td]))\n # loop through Tt/2.\n #\n # For N = 1\n # Gt(doy,Tt,N) = \n # loop over potential T_life_cycle of first cohort (search_day_max+365 -\n # 1 choices), find Tlc that maximzes Gt(doy,Tlc,N-1) + Gt(doy+Tlc,Tt-Tlc,N-1)\n # Then Gt(doy,Tt,N) = Gt(doy,Tlc,N-1) + Gt(doy+Tlc,Tt-Tlc,N-1)\n # For N > 1, repeat the last step\n\n T_total = int(np.ceil((search_day_max + 365) / 365)*365)\n N_final = np.amax([N,int(np.ceil(\n T_total/(search_day_max/3.)))+1])\n print('N_final = {:d}'.format(N_final))\n # total time for the optimization\n Gtmax_matrix = np.zeros((T_total,365,N_final)) * np.nan\n # maximum total carbon gain - construction cost over the period\n # T_total, starting from doy, split into N+1 different cohorts\n\n Td_matrix = np.zeros((T_total,365,N_final))\n # record the best choices for dormancy\n\n LL_matrix = np.zeros((T_total,365,N_final))\n # record the best choices for leaf longevity\n\n \n # first of all we need to generate total_gain_matrix as a function of LL and\n # doy from daily_gain_matrix\n # loop # 365\n\n total_gain_matrix = np.zeros_like(daily_gain_matrix)\n\n for init_doy in np.arange(365):\n idx_first = np.arange(search_day_max)\n idx_second = np.mod(init_doy+np.arange(search_day_max),365)\n total_gain_matrix[:,init_doy] = (\n np.cumsum(daily_gain_matrix[idx_first,idx_second]) - \n (self.SIM_CC2LMA * layer_LMA\n * (1. - self.C_RESORPTION)))\n\n\n # dynamic programming\n\n # Now we need to fill the case when N == 0\n\n # array of potential dormant period\n Td_array = np.arange(365)\n\n # loop # 365 * (search_day_max+365)\n for init_doy in np.arange(365):\n # find the comulative daily gain\n for T_idx in np.arange(T_total):\n # given the total time and dormant period\n # calculate the corresponding leaf longevity\n LL_idx = T_idx - Td_array\n\n # given the dormant period, calculate the corresponding\n # flushing doy\n doy_idx = np.mod(init_doy + Td_array,365).astype(int)\n\n data_mask = (LL_idx >= 0) & (LL_idx < search_day_max)\n\n if (np.sum(data_mask) > 0):\n # at least some possiblity\n cur_total_gain = total_gain_matrix[LL_idx[data_mask],\n doy_idx[data_mask]]\n\n best_idx = np.argmax(cur_total_gain)\n\n Gtmax_matrix[T_idx,init_doy,0] = cur_total_gain[best_idx] \n Td_matrix[T_idx,init_doy,0] = (\n Td_array[data_mask][best_idx])\n LL_matrix[T_idx,init_doy,0] = (\n LL_idx[data_mask][best_idx])\n\n # then circulate over number of cohort (noc)\n # (N-1) * 365 * (search_day_max + 365)\n T_total_array = np.arange(T_total)\n # different choices of first cohort\n for noc in np.arange(1,N_final):\n\n print(noc)\n # we need to loop over init doy\n for init_doy in np.arange(365):\n # loop over length of first cohort\n\n # only search for profitable T for the first cohort\n T_idx_array = T_total_array[\n Gtmax_matrix[:,init_doy,0] > 0.]\n for T_idx in T_idx_array:\n # find the doy for the next cohort\n next_doy = np.mod(init_doy+T_idx+1,365)\n next_T_idx = T_total_array - (T_idx+1) - 1\n # plus 1 when convert from index to days\n\n data_mask = (next_T_idx >= 0)\n\n if np.sum(data_mask) == 0:\n continue\n\n tmp_idx = next_T_idx[data_mask]\n update_idx = T_total_array[data_mask]\n\n # find the total Gt for different combinations\n Gt_sum = ( Gtmax_matrix[T_idx,init_doy,0]\n + Gtmax_matrix[tmp_idx,next_doy,noc-1])\n\n # check whether we need to update Gtmax_matrix\n # two scenarios\n # (1) Gtmax_matrix is nan while Gt_sum is not\n # (2) Gtmax_matrix < Gt_sum\n update_mask = (\n (np.isnan(Gtmax_matrix[update_idx,init_doy,noc]) &\n ~(np.isnan(Gt_sum))) |\n ( Gtmax_matrix[update_idx,init_doy,noc]\n = 0)\n#\n# #LL_array[LL_array==0] = 365\n#\n# \n# LL_array += iyr * 365 # consider year to cross\n# #LL_array -= 1 # convert to index\n#\n# LL_mask = np.array( Td_mask & (LL_array >= 0)\n# & (LL_array < search_day_max)\n# , dtype=bool)\n#\n#\n# if np.sum(LL_mask) == 0:\n# # no available data\n# #print('LL_mask has nothing')\n# continue\n#\n# update_mask = np.array(\n# G_fixed[iyr\n# ,shed_doy_array[LL_mask]\n# ,flush_doy] <\n# average_gain_matrix[Td,\n# LL_array[LL_mask],\n# flush_doy],dtype=bool)\n#\n# if np.sum(update_mask) == 0:\n# # no need to update\n# #print('No need to update')\n# continue\n#\n# # find index\n# idx_1 = shed_doy_array[LL_mask][update_mask]\n# idx_2 = LL_array[LL_mask][update_mask]\n#\n# G_fixed[iyr,idx_1,flush_doy] = \\\n# average_gain_matrix[Td,idx_2,flush_doy]\n#\n# Td_fixed[iyr,idx_1,flush_doy] = Td\n#\n# \n# del average_gain_matrix\n# del leaf_age_matrix \n# #pdb.set_trace()\n#\n# # now we have auxiliary variables to find the optimal G\n# # let's start!\n#\n# G_all = np.zeros((365,))\n# LL_all = np.zeros((365,))\n# Td_all = np.zeros((365,))\n\n\n\n\n# for flush_doy in np.arange(365):\n#\n# print(flush_doy)\n# # get the mask\n# positive_mask = (G_fixed[:,:,flush_doy] > 0.).ravel()\n#\n#\n# idx_array = np.arange(len(positive_mask))\n# idx_dict = {}\n# for ico in np.arange(N):\n# idx_dict['{:d}'.format(ico)] = []\n#\n# idx_mask = np.zeros((len(positive_mask),N),dtype=int)\n# idx_mask[positive_mask,0] = 1\n# idx_dict['0'] = idx_array[idx_mask[:,0] == 1]\n# # this is used to store indexes to search\n#\n#\n# cur_G = np.zeros((N,)) # total gain rate\n# cur_T = np.zeros((N,)) # total time\n# cur_Tf = np.zeros((N,),dtype=int) # flush doy\n# cur_Tf[0] = flush_doy\n# update_flag = np.ones((N,)) # record whether each cohort has been updated\n# loop_idx = np.zeros((N,),dtype=int)\n#\n# Gmax = 0.\n#\n# while (loop_idx[0] < len(idx_dict['0'])):\n# for ico in np.arange(0,N-1):\n# # update the current cohort only when update_flag\n# # is 1\n# if update_flag[ico] == 1:\n# # get the flushing date of current cohort\n# cur_iyr, cur_shed = np.unravel_index(\n# idx_dict['{:d}'.format(ico)][loop_idx[ico]],\n# G_fixed.shape[0:2])\n#\n# \n# # find cur_G max\n# cur_G[ico] = G_fixed[cur_iyr,cur_shed,cur_Tf[ico]] \n# cur_T[ico] = np.mod(cur_shed - cur_Tf[ico],365)\\\n# + cur_iyr * 365 + 1\n#\n# # find properties of next cohort\n## if ico < N-1:\n# cur_Tf[ico+1] = np.mod(cur_shed + 1,365)\n# # find the index to search\n# idx_mask[:,ico+1] = 0\n# idx_mask[(G_fixed[:,:,cur_Tf[ico+1]]\n# > 0.).ravel()\n# ,ico+1] = 1\n# idx_dict['{:d}'.format(ico+1)] = \\\n# idx_array[idx_mask[:,ico+1] == 1]\n#\n# update_flag[ico] = 0\n#\n# # calculate the final G for the last cohort\n# if len(idx_dict['{:d}'.format(N-1)]) > 0:\n# iyr_array, shed_array = np.unravel_index(\n# idx_dict['{:d}'.format(N-1)],\n# G_fixed.shape[0:2])\n#\n# last_G = G_fixed[iyr_array,shed_array,cur_Tf[N-1]]\n# last_T = np.mod(shed_array - cur_Tf[N-1], 365)\\\n# + iyr_array * 365 + 1\n# final_G = ( np.sum(cur_G[0:N-1] * cur_T[0:N-1])\n# + last_G * last_T) / (np.sum(cur_T[0:N-1]) + last_T)\n#\n# # find the maximum in final_G\n# best_final_G = np.amax(final_G)\n# best_final_idx = np.argmax(final_G)\n# cur_T[N-1] = last_T[best_final_idx]\n# cur_G[N-1] = last_G[best_final_idx]\n#\n# if best_final_G > Gmax:\n# # find a better Gmax\n# # record it\n# Gmax = best_final_G\n# best_iyr, best_shed = np.unravel_index(\n# idx_dict['0'][loop_idx[0]],\n# G_fixed.shape[0:2])\n# best_T = cur_T.copy()\n# best_G = cur_G.copy()\n#\n# # increment second to the last loop_idx\n# loop_idx[N-2] += 1\n# update_flag[N-2] = 1\n#\n# # update other loop_idx\n# for ico in np.arange(N-2,0,-1):\n# # find whether reached the last one\n# if (loop_idx[ico] == np.sum(idx_mask[:,ico] == 1)) and ico > 0:\n# # modify the ico cohort\n# loop_idx[ico-1] += 1\n# loop_idx[ico] = 0\n# update_flag[ico-1] = 1\n# update_flag[ico] = 1\n# \n#\n# Td_all[flush_doy] = Td_fixed[best_iyr,best_shed,flush_doy]\n# LL_all[flush_doy] = best_T[0] - Td_all[flush_doy] \n# G_all[flush_doy] = best_G[0]\n# \n #pdb.set_trace()\n \n\n\n # find the maximum average_gain_matrix for each starting day\n # and update local optimization results\n #print('LL_local')\n #print(self.LL_local[:,ilayer,isp])\n\n\n #find optimal dormancy without cascading effect\n\n # find the maximum average_gain_matrix after considering leaf shedding\n # average_gain_matrix with wait\n # the maximum is to wait for 364 days\n# wait_average_gain_matrix = np.zeros((365,365))\n# for wait_day in np.arange(365):\n# new_flush_day = np.mod(np.arange(365)+wait_day,365)\n# wait_average_gain_matrix[wait_day,:] = \\\n# (self.Gmax_local[new_flush_day,ilayer,isp] *\n# self.LL_local[new_flush_day,ilayer,isp] /\n# (self.LL_local[new_flush_day,ilayer,isp] + wait_day))\n#\n# self.Gmax_dormant[:,ilayer,isp] = np.amax(wait_average_gain_matrix,axis=0)\n# self.T_dormant[:,ilayer,isp] = np.argmax(wait_average_gain_matrix,axis=0)\n# self.LL_dormant[:,ilayer,isp] = \\\n# self.LL_local[np.mod(np.arange(365)+self.T_dormant[:,ilayer,isp]\n# ,365).astype(int),ilayer,isp]\n\n # consider cascading effect\n # It is currently not clear how to fully include cascading\n # effect.\n # For now, only include two scenarios\n # (1) next cohort needs dormancy\n # (2) next cohort G < current daily g\n # Then find Gmax_all and LL_all\n\n# for flush_day in np.arange(365):\n# # for each flush_day check the T_dormant and Gmax for next\n# # cohort\n# cur_LL = np.int(self.LL_local[flush_day,ilayer,isp])\n# cur_Gtotal = self.Gmax_local[flush_day,ilayer,isp] * cur_LL\n# next_flush_day = np.int(np.mod(flush_day + cur_LL,365))\n#\n# while ((daily_gain_matrix[cur_LL-1,next_flush_day] >\n# self.Gmax_local[next_flush_day,ilayer,isp]) or\n# (self.T_dormant[next_flush_day,ilayer,isp] > 0 and\n# daily_gain_matrix[cur_LL-1,next_flush_day] > 0)\n# ):\n# \n# cur_Gtotal += daily_gain_matrix[cur_LL-1,next_flush_day]\n# cur_LL += 1\n# next_flush_day = np.int(np.mod(next_flush_day + 1,365))\n# #\n# # record the Gmax_all and LL_all\n# self.Gmax_all[flush_day,ilayer,isp] = cur_Gtotal / cur_LL\n# self.LL_all[flush_day,ilayer,isp] = cur_LL\n\n\n print('LL_all')\n print(self.LL_all[:,ilayer,isp])\n print('Td_all')\n print(self.Td_all[:,ilayer,isp])\n\n ## we will calculate the average gain_matrix for two consecutive\n ## days) of current cohort with modification of LL (-365,365)\n #print('T_dormant:')\n #print(self.T_dormant[:,ilayer,isp])\n #print('LL_dormant:')\n #print(self.LL_dormant[:,ilayer,isp])\n #multi_average_gain_matrix=np.zeros((365*2,365))\n ## first dimension, trials of waiting time of first cohort\n ## fourth dimension, each flushing day\n\n #print('zero day Gtotal',average_gain_matrix[0,100]*1.)\n\n #for flush_day in np.arange(365):\n # cur_LL = int(self.LL_local[flush_day,ilayer,isp])\n\n # # loop over different modifications\n # for iLL in np.arange(365*2):\n # LL_mod = int(iLL - 365)\n # if ((cur_LL + LL_mod <= 1) or \n # (cur_LL + LL_mod >= self.spB[isp])):\n # # impossible modifications\n # multi_average_gain_matrix[iLL,flush_day] = -9999.\n # continue\n\n # cur_Gtotal = average_gain_matrix[\n # cur_LL+LL_mod-1,flush_day] * (cur_LL+LL_mod)\n\n # next_flush_day = np.mod(flush_day + cur_LL + LL_mod,365)\n\n # next_T_dormant = self.T_dormant[next_flush_day,ilayer,isp]\n # next_LL = self.LL_dormant[next_flush_day,ilayer,isp]\n # next_Gtotal = self.Gmax_dormant[next_flush_day,ilayer,isp]\\\n # * (next_T_dormant+next_LL)\n\n # multi_average_gain_matrix[iLL,flush_day] = \\\n # (cur_Gtotal+next_Gtotal) / \\\n # (cur_LL+LL_mod\n # +next_T_dormant+next_LL)\n\n #print('argmax:multi_average_gain')\n #print(np.argmax(multi_average_gain_matrix,axis=0))\n ## find the best LL_mod\n #LL_mod_opt = np.argmax(\n # multi_average_gain_matrix,axis=0) - 365\n\n ## calculate Gmax_all and LL_all\n #self.LL_all[:,ilayer,isp] = self.LL_local[:,ilayer,isp] + LL_mod_opt\n #print(self.LL_all[:,ilayer,isp])\n #print(LL_mod_opt)\n #for flush_day in np.arange(365):\n # cur_LL = int(self.LL_all[flush_day,ilayer,isp])\n # self.Gmax_all[flush_day,ilayer,isp] = \\\n # average_gain_matrix[cur_LL-1,flush_day]\n\n\n\n # ----------------------\n # Simulate seasonality\n # ----------------------\n\n # since we have the carbon gain stats, we can now simulate the phenology\n # calculate the last 20 year average seasonality of LAI and litter\n\n flush_array = np.zeros((np.maximum(search_day_max,366),))\n LL_array = np.zeros((np.maximum(search_day_max,366),),dtype=np.int)\n # array that record flushing events\n # flush_array need to be at least one year long\n lai_age_array = np.zeros((search_day_max,))\n age_remain_array = np.zeros((search_day_max,))\n\n # loop over years\n cur_year = 0.\n cur_doy = -1\n \n # record the realized LL\n # we have 365 values at most for each year\n real_LL = np.zeros((int(365 * self.SIM_YEAR),),np.float)\n # should weight by lai\n real_LL_weight = np.zeros((int(365 * self.SIM_YEAR),),np.float) \n cohort_num = 0\n \n while cur_year < self.SIM_YEAR:\n # start from the day with highest Gmax_all\n if cur_year == 0 and cur_doy == -1:\n # initilization\n init_doy = np.argmax(self.Gmax_all[:,ilayer,isp])\n\n # starting from days with highest Gmax_all\n cur_doy = int(np.mod(init_doy+self.Td_all[init_doy,ilayer,isp],365))\n\n flush_array[0] = 1.\n LL_array[0] = np.int(self.LL_all[init_doy,ilayer,isp])\n \n #finally set init_doy the same as cur_doy to mark the\n #start of simulaiton\n init_doy = cur_doy\n # apply shedding due to phenology\n if self.SHED_WINDOW <= 1:\n shed_lai = np.sum(lai_age_array[age_remain_array == 0.])\n lai_age_array[age_remain_array == 0] = 0.\n else:\n # shed leaves within the next SHED_WINDOW days\n # start to shed leaves when leaf has reached to LL -\n # SHED_WINDOW and finished when LL + SHED_WINDOW\n\n shed_lai = 0.\n for shed_day in np.arange(-self.SHED_WINDOW,self.SHED_WINDOW):\n # every day shed 1/2*SHED_WINDOW fraction of total shed_lai\n shed_lai += (\n np.sum(lai_age_array[age_remain_array == (-shed_day)])\n / (self.SHED_WINDOW-shed_day))\n\n lai_age_array[age_remain_array == (-shed_day)] = (\n lai_age_array[age_remain_array == (-shed_day)]\n * (1. - 1. / (self.SHED_WINDOW - shed_day))\n )\n\n\n # update age_remain_array after shedding\n age_remain_array[lai_age_array == 0.] = 0.\n\n # apply shedding due to turnover of active leaves [age_reimain_array > 0.]\n shed_lai += np.sum(lai_age_array[age_remain_array > 0.]) * self.LEAF_TURNOVER\n lai_age_array[age_remain_array > 0.] *= (1. - self.LEAF_TURNOVER)\n\n # determine the flush time of the next cohort\n wait_time = np.int(self.Td_all[cur_doy,ilayer,isp])\n flush_array[wait_time] += shed_lai\n LL_array[wait_time] = np.int(self.LL_all[cur_doy,ilayer,isp])\n \n # apply flushing according to flush events array\n\n # if water stress is two strong, put it off for one day\n # cur_daily_psi = daily_psi[cur_doy] \n # water_stress_factor = (np.maximum(1e-6,np.minimum(1.0,\n # 1. / (1. + (cur_daily_psi / spTLP[isp]) ** 4.0)))\n # * WATER_STRESS_SCALE + \n # 1. * (10 - WATER_STRESS_SCALE)\n # ) / 10.\n # if water_stress_factor < 0.5:\n ## pdb.set_trace()\n # flush_array[1] += flush_array[0]\n # flush_array[0] = 0.\n\n lai_age_array[0] += flush_array[0]\n\n if flush_array[0] > 0.:\n age_remain_array[0] = LL_array[0]\n \n # record the realized leaf longevity\n if self.SIM_YEAR - cur_year < 20:\n real_LL[cohort_num] = LL_array[0]\n real_LL_weight[cohort_num] = flush_array[0]\n if cohort_num < (real_LL.shape[0] - 1):\n cohort_num += 1\n\n # record stats\n # for the last 20 years\n # has to be .le. here because cur_year start from 0\n if self.SIM_YEAR - cur_year <= 20:\n\n # lai\n self.sim_lai_avg[cur_doy,ilayer,isp] += \\\n np.sum(lai_age_array * cur_lai_frac_array)\n\n # young leaves\n self.sim_lai_y[cur_doy,ilayer,isp] += \\\n np.sum((lai_age_array * cur_lai_frac_array)[0:60//self.TIMESTEP])\n # mature leaves\n self.sim_lai_m[cur_doy,ilayer,isp] += \\\n np.sum((lai_age_array * cur_lai_frac_array)[60//self.TIMESTEP:180//self.TIMESTEP])\n # old leaves\n self.sim_lai_o[cur_doy,ilayer,isp] += \\\n np.sum((lai_age_array * cur_lai_frac_array)[180//self.TIMESTEP::])\n\n # age\n self.sim_age_avg[cur_doy,ilayer,isp] += (\n np.sum(np.arange(1,search_day_max+1) * lai_age_array) /\n np.sum(lai_age_array))\n # litter\n self.sim_litter_avg[cur_doy,ilayer,isp] += shed_lai\n\n #daily gain\n self.sim_gain_avg[cur_doy,ilayer,isp] += np.nansum(\n daily_gain_matrix[:,cur_doy] *\n lai_age_array)\n\n #daily gpp\n self.sim_gpp_avg[cur_doy,ilayer,isp] += np.nansum(\n daily_gpp_matrix[:,cur_doy] *\n lai_age_array)\n\n # pc\n self.sim_pc_avg[cur_doy,ilayer,isp] += np.nansum(\n daily_pc_matrix[:,cur_doy] * lai_age_array) / self.REF_PAR # convert to umol CO2 / umol Photon\n\n # This day has passed...\n next_doy = np.mod(cur_doy+1,365)\n # Update all age-related arrays\n flush_array[0] = 0.\n flush_array = np.roll(flush_array,-1)\n LL_array[0] = 0\n LL_array = np.roll(LL_array,-1)\n \n age_remain_array[lai_age_array > 0.] -= 1.\n lai_age_array = np.roll(lai_age_array,1)\n age_remain_array = np.roll(age_remain_array,1)\n\n\n cur_doy = next_doy\n if cur_doy == init_doy:\n # pdb.set_trace() \n cur_year += 1\n # print('Year {}'.format(cur_year))\n\n # record sim_LL_stats\n final_real_LL = real_LL[(real_LL > 0.) & (~np.isnan(real_LL)) ]\n final_real_LL_weight = real_LL_weight[(real_LL > 0.) & (~np.isnan(real_LL))]\n self.sim_LL_stats[0,ilayer,isp] = np.average(final_real_LL,\n weights=final_real_LL_weight)\n pct_array = np.array([5.,25.,50.,75.,95.]) / 100.\n self.sim_LL_stats[1:6,ilayer,isp] = weighted_percentile(\n final_real_LL,\n pct_array,sample_weight=final_real_LL_weight)\n\n # time average\n self.sim_lai_avg /= np.minimum(self.SIM_YEAR,20)\n self.sim_lai_y /= np.minimum(self.SIM_YEAR,20)\n self.sim_lai_m /= np.minimum(self.SIM_YEAR,20)\n self.sim_lai_o /= np.minimum(self.SIM_YEAR,20)\n self.sim_age_avg /= np.minimum(self.SIM_YEAR,20)\n self.sim_litter_avg /= np.minimum(self.SIM_YEAR,20)\n self.sim_gain_avg /= np.minimum(self.SIM_YEAR,20)\n self.sim_gpp_avg /= np.minimum(self.SIM_YEAR,20)\n self.sim_pc_avg /= np.minimum(self.SIM_YEAR,20)\n \n\n # return leaf-level meteorology after radiative transfer\n return (leafPar_sun,leafPar_shade,leafPar_fsun,\n leafTmpDiff_sun,leafTmpDiff_shade,)\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","sub_path":"PhenoOpt/src/loc_utils/PhenOpt.py","file_name":"PhenOpt.py","file_ext":"py","file_size_in_byte":64200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"540232678","text":"import sys\n\nfrom client import Client\nimport itsyouonline\n\n# itsyou.online client\niyo_client = itsyouonline.Client()\n\n# goramldir client\nclient = Client()\n\ndef main(app_id, app_secret):\n '''\n Login to itsyou.online server\n If succeed, next request will use `Authorization` header\n acquired from this login process\n '''\n iyo_client.oauth.LoginViaClientCredentials(app_id, app_secret)\n\n '''\n create JWT token with specified 'scopes'.\n You need to change 'user:memberof:goraml' to match with your\n organization scopes\n '''\n jwt_token = iyo_client.oauth.CreateJWTToken([\"user:memberof:goraml\"])\n\n # Set our goramldir client to use JWT token from itsyou.online\n client.set_auth_header(\"token \" + jwt_token)\n\n # try to make simple GET call to goramldir server\n resp = client.users_byUsername_get(\"john\")\n print(resp.json())\n\nif __name__ == \"__main__\":\n '''\n usage : python3 main.py application_id application_secret\n '''\n main(sys.argv[1], sys.argv[2])\n","sub_path":"docs/tutorial/python/client/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"580929858","text":"from django.db import models\n\nfrom django.contrib.auth.models import User\nfrom games.models import Game\n\nclass Pick(models.Model):\n\tPICK_CHOICES = (\n\t\t('HOME', 'Home'),\n\t\t('AWAY', 'Away')\n\t)\n\n\tuser = models.ForeignKey(User)\n\tgame = models.ForeignKey(Game)\n\tpick = models.CharField(max_length = 4, choices = PICK_CHOICES)\n\tthree_point = models.BooleanField()\n\t\n\tdef __unicode__(self):\n\t\tpoints = \"\"\n\n\t\tif self.three_point:\n\t\t\tpoints = \" - 3pt\"\n\n\t\treturn \"%s%s%s%s%s%s%s%s%s%s%s%s%s\" % \\\n\t\t\t(self.user.username, \" - \", self.pick, points, \" - \", \\\n\t\t\tself.game.away_team, \" (\", str(self.game.away_spread), \") at \", \\\n\t\t\tself.game.home_team, \" (\", str(self.game.home_spread), \")\")\n\t\n\tdef dump(self, logger):\n\t\tlogger.log(self.user.username)\n\t\tlogger.log(self.game.gamenumber)\n\t\tlogger.log(self.pick)\n\t\tlogger.log(self.three_point)\n\n\tclass Meta:\n\t\tapp_label = 'picks'\n\nclass PickResult(models.Model):\n\tRESULT_CHOICES = (\n\t\t('HIT', 'Hit'),\n\t\t('MISS', 'Miss'),\n\t\t('PUSH', 'Push')\n\t)\n\n\tpick = models.ForeignKey(Pick)\n\tresult = models.CharField(max_length = 4, choices = RESULT_CHOICES)\n\n\tdef __unicode__(self):\n\t\tpoints = \"\"\n\n\t\tif self.pick.three_point:\n\t\t\tpoints = \" - 3pt\"\n\n\t\treturn \"%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\" % \\\n\t\t\t(self.pick.user.username, \" - \", self.pick.pick, points, \" - \", self.result, \" - \", \\\n\t\t\tself.pick.game.away_team, \" (\", str(self.pick.game.away_spread), \") at \", \\\n\t\t\tself.pick.game.home_team, \" (\", str(self.pick.game.home_spread), \")\")\n\t\n\tdef dump(self, logger):\n\t\tlogger.log(self.pick.user.username)\n\t\tlogger.log(self.pick.game.gamenumber)\n\t\tlogger.log(self.pick.pick)\n\t\tlogger.log(self.result)\n\n\tclass Meta:\n\t\tapp_label = 'picks'\n","sub_path":"picks/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"464599339","text":"from django.contrib import admin\nfrom .models import BFQuestionnaire, BFTest\n\n# Register your models here.\nclass BFQuestionnaireAdmin(admin.ModelAdmin):\n fieldsets = [\n ('Question Statement', {'fields':['question']}),\n ('Answer Statement',{'fields':['front_ans','back_ans']})\n ]\nadmin.site.register(BFTest)\nadmin.site.register(BFQuestionnaire,BFQuestionnaireAdmin)\n","sub_path":"recruit/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"380990001","text":"# Author: S1NH.com\n\n'''\nimport时载入base64数据库,调用get_base64_from_ID(商标ID)输出商标base64(jpeg)\nmemory的问题,可能需要重构\n'''\nimport config\n\nDATABASE_IMG_BASE64 = config.DATABASE_IMG_BASE64\n\ntrademark_base64 = []\ntrademark_id = []\n\nprint('Reading Image Database...')\n\nwith open(DATABASE_IMG_BASE64, 'r') as f:\n for line in f.readlines():\n _id, _, _base64 = line.split(\"\\\"\")[1:4]\n trademark_base64.append(_base64)\n trademark_id.append(_id)\n\n\ndef get_base64_from_ID(_id):\n db_index = trademark_id.index(_id)\n b64 = trademark_base64[db_index]\n return b64\n","sub_path":"base64_database.py","file_name":"base64_database.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"102067227","text":"import re\n\nimport pandas as pd\nimport requests\n\n\ndef searchImage(ID, key):\n \"\"\"\n\n :param ID: The searching ID specified by yourself\n :param key: Google API Key, In this example, it is ID[0]-City, ID[1]-Country provided by the .csv file.\n \"\"\"\n\n print(ID[2])\n for i in [2, 3]:\n ID[i] = re.sub('/', '', ID[i])\n # use \\\\ to avoid dangling metacharacter\n ID[i] = re.sub('\\\\?', '', ID[i])\n ID[i] = re.sub(' ', '', ID[i])\n ID[i] = re.sub('\\r', '', ID[i])\n ID[i] = re.sub('\\n', '', ID[i])\n image_backgroud_url = 'https://maps.googleapis.com/maps/api/staticmap?¢er=' + ID[2] + ',' + ID[\n 3] + '&zoom=10&format=png&maptype=roadmap&style=feature:road|visibility:off&style=element:labels%7Cvisibility:off&size=640x640&scale=2&key=' + key\n image_road_url = 'https://maps.googleapis.com/maps/api/staticmap?¢er=' + ID[2] + ',' + ID[\n 3] + '&zoom=10&format=png&maptype=roadmap&style=visibility:off&style=feature:road|visibility:on&style=element:labels%7Cvisibility:off&size=640x640&scale=2&key=' + key\n image_roadmap_url = 'https://maps.googleapis.com/maps/api/staticmap?¢er=' + ID[2] + ',' + ID[\n 3] + '&zoom=10&format=png&maptype=roadmap&style=element:labels%7Cvisibility:off&size=640x640&scale=2&key=' + key\n image_satellite_url = 'https://maps.googleapis.com/maps/api/staticmap?¢er=' + ID[2] + ',' + ID[\n 3] + '&zoom=10&format=png&maptype=satellite&style=element:labels%7Cvisibility:off&size=640x640&scale=2&key=' + key\n satellite = requests.get(image_satellite_url)\n backgroud = requests.get(image_backgroud_url)\n road = requests.get(image_road_url)\n roadmap = requests.get(image_roadmap_url)\n with open(\"./ImageSet/Background/\" + str(ID[0]) + \".background_\" + str(ID[2]) + \".png\", \"wb\") as f:\n f.write(backgroud.content)\n with open(\"./ImageSet/Road/\" + str(ID[0]) + \".road_\" + str(ID[2]) + \".png\", \"wb\") as f:\n f.write(road.content)\n with open(\"./ImageSet/RoadMap/\" + str(ID[0]) + \".roadmap_\" + str(ID[2]) + \".png\", \"wb\") as f:\n f.write(roadmap.content)\n with open(\"./ImageSet/Satellite/\" + str(ID[0]) + \".satellite_\" + str(ID[2]) + \".png\", \"wb\") as f:\n f.write(satellite.content)\n\n\ndef searchInRange(dataFile, idxS, idxE):\n for i in range(idxS, idxE):\n searchImage(dataFile[i])\n\n\n# My Multi-threading\nimport threading\n\n\ndef threadAccelerate(datapath, operation, numThread):\n if operation == 'searchGoogle':\n data = pd.read_csv(datapath).values\n ThreadStart = True\n if ThreadStart:\n thread_size = numThread\n thread_length = len(data) // thread_size\n count = 0\n threadList = []\n print(thread_length)\n for i in range(thread_size + 1):\n newThread = threading.Thread(target=searchInRange,\n args=(data, count, min(count + thread_length, len(data)),))\n count += thread_length\n newThread.start()\n threadList.append(newThread)\n for i in range(thread_size):\n threadList[i].join()\n print(\"Done\")\n\n\n# 60 is ok for 16G memory and 4700K.\nthreadAccelerate('./Data/OldData/PopulationLatitudeLongitudeNoKorea.csv', 'searchGoogle', 60)\n","sub_path":"1.城市数据预测/Search.py","file_name":"Search.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"400746887","text":"# Ignore the warnings\nimport warnings\nwarnings.filterwarnings('always')\nwarnings.filterwarnings('ignore')\n\n# data visualisation and manipulation\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport seaborn as sns\n#configure\n# sets matplotlib to inline and displays graphs below the corressponding cell.\n'''\n#thêm\nimport matplotlib.pyplot as plt\n\n#configure\n# sets matplotlib to inline and displays graphs below the corressponding cell.\n\n \n#thêm\nfrom IPython import get_ipython\nipy = get_ipython()\nif ipy is not None:\n ipy.run_line_magic('matplotlib', 'inline')\n#\n'''\n#matplotlib inline\nstyle.use('fivethirtyeight')\nsns.set(style='whitegrid',color_codes=True)\n\n#nltk\nimport nltk\n\n#preprocessing\nfrom nltk.corpus import stopwords #stopwords\nfrom nltk import word_tokenize,sent_tokenize # tokenizing\nfrom nltk.stem import PorterStemmer,LancasterStemmer # using the Porter Stemmer and Lancaster Stemmer and others\nfrom nltk.stem.snowball import SnowballStemmer\nfrom nltk.stem import WordNetLemmatizer # lammatizer from WordNet\n\n# for part-of-speech tagging\nfrom nltk import pos_tag\n\n# for named entity recognition (NER)\nfrom nltk import ne_chunk\n\n# vectorizers for creating the document-term-matrix (DTM)\nfrom sklearn.feature_extraction.text import TfidfVectorizer,CountVectorizer\n\n# BeautifulSoup libraray\nfrom bs4 import BeautifulSoup \n\nimport re # regex\n\n#model_selection\nfrom sklearn.model_selection import train_test_split,cross_validate\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import GridSearchCV\n\n#evaluation\nfrom sklearn.metrics import accuracy_score,roc_auc_score \nfrom sklearn.metrics import classification_report\nfrom mlxtend.plotting import plot_confusion_matrix\n\n#preprocessing scikit\nfrom sklearn.preprocessing import MinMaxScaler,StandardScaler,Imputer,LabelEncoder\n\n#classifiaction.\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import LinearSVC,SVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier,GradientBoostingClassifier,AdaBoostClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.naive_bayes import GaussianNB,MultinomialNB\n \n#stop-words\nstop_words=set(nltk.corpus.stopwords.words('english'))\n\n#keras\nimport keras\nfrom keras.preprocessing.text import one_hot,Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.models import Sequential\nfrom keras.layers import Dense , Flatten ,Embedding,Input,CuDNNLSTM,LSTM\nfrom keras.models import Model\nfrom keras.preprocessing.text import text_to_word_sequence\n\n#gensim w2v\n#word2vec\nfrom gensim.models import Word2Vec\n#rev_frame=pd.read_csv(r'../input/Reviews.csv')\nrev_frame=pd.read_csv('D:/LUANVAN_Cao_hoc/DE_TAI_THAM_KHAO/Reviews.csv')\ndf=rev_frame.copy()\ndf.head()\n\ndf=df[['Text','Score']]\n#them print(df.head)\nprint(df.head)\ndf['review']=df['Text']\ndf['rating']=df['Score']\ndf.drop(['Text','Score'],axis=1,inplace=True)\n\nprint(df.shape)\ndf.head()\n\n# check for null values\nprint(df['rating'].isnull().sum())\nprint(df['review'].isnull().sum()) # no null values.\n\n# remove duplicates/ for every duplicate we will keep only one row of that type. \ndf.drop_duplicates(subset=['rating','review'],keep='first',inplace=True) \n\n# now check the shape. note that shape is reduced which shows that we did has duplicate rows.\nprint(df.head)\nprint(df.shape)\ndf.head()\n\n# printing some reviews to see insights.\nfor review in df['review'][:5]:\n print(review+'\\n'+'\\n')\n\ndef mark_sentiment(rating):\n\tif(rating<=3):\n\t\treturn 0\n\telse:\n\t\treturn 1\ndf['sentiment']=df['rating'].apply(mark_sentiment)\ndf.drop(['rating'],axis=1,inplace=True)\ndf.head()\nprint(df.head)\n# function to clean and pre-process the text.\ndef clean_reviews(review): \n \n # 1. Removing html tags\n review_text = BeautifulSoup(review,\"lxml\").get_text()\n\n # 2. Retaining only alphabets.\n review_text = re.sub(\"[^a-zA-Z]\",\" \",review_text)\n\n # 3. Converting to lower case and splitting\n word_tokens= review_text.lower().split()\n\n # 4. Remove stopwords\n le=WordNetLemmatizer()\n stop_words= set(stopwords.words(\"english\")) \n word_tokens= [le.lemmatize(w) for w in word_tokens if not w in stop_words]\n \n cleaned_review=\" \".join(word_tokens)\n\n return cleaned_review\nprint(df.loc[df.sentiment==0])\npos_df=df.loc[df.sentiment==1,:][:50000]\nneg_df=df.loc[df.sentiment==0,:][:50000]\n\npos_df.head()\nneg_df.head()\nprint(pos_df.head)\n#combining\ndf=pd.concat([pos_df,neg_df],ignore_index=True)\n\nprint(df.shape)\ndf.head()\nprint(df.head)\n# shuffling rows\ndf = df.sample(frac=1).reset_index(drop=True)\nprint(df.head)\nprint(df.shape) # perfectly fine.\ndf.head()\n\n# import gensim\n# load Google's pre-trained Word2Vec model.\n# pre_w2v_model = gensim.models.KeyedVectors.load_word2vec_format(r'drive/Colab Notebooks/amazon food reviews/GoogleNews-vectors-negative300.bin', binary=True) \n\ntokenizer = nltk.data.load('tokenizers/punkt/english.pickle')\nsentences=[]\nsum=0\nfor review in df['review']:\n sents=tokenizer.tokenize(review.strip())\n\n sum+=len(sents)\n for sent in sents:\n cleaned_sent=clean_reviews(sent)\n sentences.append(cleaned_sent.split()) # can use word_tokenize also.\nprint(sum)\nprint(len(sentences)) # total no of sentences\n\n# trying to print few sentences\nfor te in sentences[:5]:\n print(te,\"\\n\")\n\n\n\n\nimport gensim\nw2v_model=gensim.models.Word2Vec(sentences=sentences,size=300,window=10,min_count=1)\n\n'''\nParameters: -\nsentences : The sentences we have obtained.\n\nsize : The dimesnions of the vector used to represent each word.\n\nwindow : The number f words around any word to see the context.\n\nmin_count : The minimum number of times a word should appear for its embedding to be formed or learnt.\n'''\n\nw2v_model.train(sentences,epochs=10,total_examples=len(sentences))\n\n# embedding of a particular word.\nw2v_model.wv.get_vector('like')\n\n# total numberof extracted words.\nvocab=w2v_model.wv.vocab\nprint(\"The total number of words are : \",len(vocab))\n\n# words most similar to a given word.\nw2v_model.wv.most_similar('like')\n\n# similaraity b/w two words\nw2v_model.wv.similarity('good','like')\n\nprint(\"The no of words :\",len(vocab))\n# print(vocab)\n\n# print(vocab)\nvocab=list(vocab.keys())\n\nword_vec_dict={}\nfor word in vocab:\n word_vec_dict[word]=w2v_model.wv.get_vector(word)\nprint(\"The no of key-value pairs : \",len(word_vec_dict)) # should come equal to vocab size\n\n# # just check\n# for word in vocab[:5]:\n# print(word_vec_dict[word])\n\n# cleaning reviews.\ndf['clean_review']=df['review'].apply(clean_reviews)\n\n# number of unique words = 56379.\n\n# now since we will have to pad we need to find the maximum lenght of any document.\n\nmaxi=-1\nfor i,rev in enumerate(df['clean_review']):\n tokens=rev.split()\n if(len(tokens)>maxi):\n maxi=len(tokens)\nprint(maxi)\n\ntok = Tokenizer()\ntok.fit_on_texts(df['clean_review'])\nvocab_size = len(tok.word_index) + 1\nencd_rev = tok.texts_to_sequences(df['clean_review'])\n\nmax_rev_len=1565 # max lenght of a review\nvocab_size = len(tok.word_index) + 1 # total no of words\nembed_dim=300 # embedding dimension as choosen in word2vec constructor\n\n# now padding to have a amximum length of 1565\npad_rev= pad_sequences(encd_rev, maxlen=max_rev_len, padding='post')\npad_rev.shape # note that we had 100K reviews and we have padded each review to have a lenght of 1565 words.\n\n# now creating the embedding matrix\nembed_matrix=np.zeros(shape=(vocab_size,embed_dim))\nfor word,i in tok.word_index.items():\n embed_vector=word_vec_dict.get(word)\n if embed_vector is not None: # word is in the vocabulary learned by the w2v model\n embed_matrix[i]=embed_vector\n # if word is not found then embed_vector corressponding to that vector will stay zero.\n \n # checking.\nprint(embed_matrix[14])\n\n# prepare train and val sets first\nY=keras.utils.to_categorical(df['sentiment']) # one hot target as required by NN.\nx_train,x_test,y_train,y_test=train_test_split(pad_rev,Y,test_size=0.20,random_state=42)\n\nfrom keras.initializers import Constant\nfrom keras.layers import ReLU\nfrom keras.layers import Dropout\nmodel=Sequential()\nmodel.add(Embedding(input_dim=vocab_size,output_dim=embed_dim,input_length=max_rev_len,embeddings_initializer=Constant(embed_matrix)))\n# model.add(CuDNNLSTM(64,return_sequences=False)) # loss stucks at about \nmodel.add(Flatten())\nmodel.add(Dense(16,activation='relu'))\nmodel.add(Dropout(0.50))\n# model.add(Dense(16,activation='relu'))\n# model.add(Dropout(0.20))\nmodel.add(Dense(2,activation='sigmoid')) # sigmod for bin. classification.\n\nmodel.summary()\n'''\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding_1 (Embedding) (None, 1565, 300) 16914000 \n_________________________________________________________________\nflatten_1 (Flatten) (None, 469500) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 16) 7512016 \n_________________________________________________________________\ndropout_1 (Dropout) (None, 16) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 2) 34 \n=================================================================\nTotal params: 24,426,050\nTrainable params: 24,426,050\nNon-trainable params: 0\n_________________________________________________________________\n'''\n'''\n# compile the model\nmodel.compile(optimizer=keras.optimizers.RMSprop(lr=1e-3),loss='binary_crossentropy',metrics=['accuracy'])\n# specify batch size and epocj=hs for training.\nepochs=5\nbatch_size=64\n\n# fitting the model.\nmodel.fit(x_train,y_train,epochs=epochs,batch_size=batch_size,validation_data=(x_test,y_test))\n\n#The final accuracy after 5 epochs is about 84% which is pretty decent.\n'''\n\n'''\nFURTHER IDEAS : -\n1) ProductId and UserId can be used to track the general ratings of a given product and also to track the review patter of a particular user as if he is strict in reviwing or not.\n\n2) Helpfulness feature may tell about the product. This is because gretare the no of people talking about reviews, the mre stronger or critical it is expected to be.\n\n3) Summary column can also give a hint.\n\n4) One can also try the pre-trained embeddings like Glove word vectors etc...\n\n5) Lastly tuning the n/w hyperparameters is always an option;).\n'''","sub_path":"BiLSTM/ref.py","file_name":"ref.py","file_ext":"py","file_size_in_byte":10554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"332502293","text":"#!/usr/bin/env python\n\nclass Database(object):\n\tNONR = 0\n\tSTATEMENT = 1\n\tAFFECTED = 2\n\tINSERT_ID = 3\n\n\tconnections = {}\n\n\tdatabase_info = None\n\n\tingore_targets = []\n\n\tactive_key = 'default'\n\tlogs = {}\n\n\t@staticmethod\n\tdef start_log(logging_key, key='default'):\n\t\tif not Database.logs.get(key):\n\t\t\tDatabase.logs[key] = DatabaseLog(key)\n\t\tif Database.connections.get(key):\n\t\t\tfor connection in Database.connections.get(key):\n\t\t\t\tconnection.set_logger(Database.logs[key])\n\t\tDatabase.logs[key].start(logging_key)\n\t\treturn Database.logs[key]\n\n\t@staticmethod\n\tdef get_log(logging_key, key='default'):\n\t\tif not Database.logs.get(key):\n\t\t\treturn None\n\t\tlog = Database.logs[key]\n\t\tqueries = log.get(logging_key)\n\t\tlog.end(logging_key)\n\t\treturn queries\n\n\t@staticmethod\n\tdef get_connection(target='default', key=None):\n\t\tif not key:\n\t\t\tkey = Database.active_key\n\t\tif Database.ingore_targets[key][target] or not Database.database_info[key][target]:\n\t\t\ttarget = 'default'\n\t\tif not Database.connections[key][target]:\n\t\t\tDatabase.connections[key][target] = Database.open_connection(key, target)\n\t\treturn Database.connections[key][target]\n\n\t@staticmethod\n\tdef is_active_connection():\n\t\treturn Database.active_key and Database.connections.get(Database.active_key)\n\n\t@staticmethod\n\tdef set_active_connection(key='default'):\n\t\tif not Database.database_info:\n\t\t\tDatabase.parse_connection_info()\n\t\tif Database.database_info.get(key):\n\t\t\told_key = Database.active_key\n\t\t\tDatabase.active_key = key\n\t\t\treturn old_key\n\n\t@staticmethod\n\tdef parse_connection_info():\n\t\tfrom random import randint\n\t\tglobal databases\n\t\tdatabase_info = databases if isinstance(databases, dict) else {}\n\t\tfor index, info in database_info.iteritem():\n\t\t\tfor target, value in info.iteritem():\n\t\t\t\tif not value.get('driver'):\n\t\t\t\t\tchoice = randint(0, database_info[index][target] - 1)\n\t\t\t\t\tdatabase_info[index][target] = database_info[index][target][choice]\n\n\t\t\t\tif not database_info[index][target].get('prefix'):\n\t\t\t\t\tdatabase_info[index][target]['prefix'] = dict(default='')\n\t\t\t\telif not isinstance(database_info[index][target]['prefix'], dict):\n\t\t\t\t\tdatabase_info[index][target]['prefix'] = dict(default=database_info[index][target]['prefix'])\n\n\t\tDatabase.database_info.update(database_info)\n\n\t@staticmethod\n\tdef add_connection_info(key, target, info):\n\t\tif not Database.database_info[key][target]:\n\t\t\tDatabase.database_info[key][target] = info\n\n\t@staticmethod\n\tdef get_connection_info(key='default'):\n\n\t\treturn Database.database_info.get(key)\n\n\t@staticmethod\n\tdef rename_connection(old_key, new_key):\n\t\tif not self.database_info:\n\t\t\tDatabase.parse_connection_info()\n\n\t\tif Database.database_info.get(old_key) and not Database.database_info.get(new_key):\n\t\t\tDatabase[new_key] = Database.database_info[old_key]\n\t\t\tdel Database[old_key]\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\t@staticmethod\n\tdef remove_connection(key):\n\t\tif Database.database_info.get(key):\n\t\t\tDatabase.close_connection(None, key)\n\t\t\tdel Database.database_info[key]\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\t@staticmethod\n\tdef open_connection(key, target):\n\t\tif not Database.database_info:\n\t\t\tDatabase.parse_connection_info()\n\n\t\tif key not in Database.database_info:\n\t\t\traise DatabaseConnectionNotDefinedException('The specified database connection is not defined: ' + key)\n\n\t\tdriver = Database.database_info[key][target].get('driver')\n\t\tif not driver:\n\t\t\traise DatabaseDriverNotSpecifiedException('Driver not specified for this database connection: ' + key)\n\n\t\tnew_connection = import_driver(key)(Database.database_info[key][target])\n\t\tnew_connection.set_target(target)\n\t\tnew_connection.set_key(key)\n\t\tlogger = Database.logs.get(key)\n\t\tif logger:\n\t\t\tnew_connection.set_logger(logger)\n\t\treturn new_connection\n\n\t@staticmethod\n\tdef close_connection(target=None, key=None):\n\t\tkey = key if key else Database.active_key\n\t\tif target:\n\t\t\tif Database.connections[key][target]:\n\t\t\t\tDatabase.connections[key][target].close()\n\t\t\t\tdel Database.connections[key][target]\n\t\telse:\n\t\t\tconnections = Database.connections.get(key)\n\t\t\tif connections:\n\t\t\t\tfor target, connection in connections.iteritems():\n\t\t\t\t\tDatabase[key][target].close()\n\t\t\t\t\tdel Database[key][target]\n\n\tdef ignore_target(key, target):\n\t\tDatabase.ignore_targets[key][target] = True","sub_path":"solo/db/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":4249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"490624391","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport cv2\n#主函數\nif __name__ == \"__main__\":\n #黑色畫板 400 x 400\n s = 400\n I = np.zeros((s,s),np.uint8)\n #隨機生成 橫縱坐標均在 100 至 300 的座標點\n n=80#隨機生成 n 個座標點,每一行存儲一個座標\n points = np.random.randint(100,300,(n,2),np.int32)\n #把上述點集處的灰度值設置為 255,單個白色圖元點不容易觀察,用一個小圓標注一下\n for i in range(n):\n cv2.circle(I,(points[i,0],points[i,1]),2,255,2)\n #求點集 points 的凸包\n convexhull = cv2.convexHull(points,clockwise=False)\n # ----- 列印凸包的資訊 ----\n print (type(convexhull))\n print (convexhull.shape)\n #連接凸包的各個點\n k = convexhull.shape[0]\n for i in range(k-1):\n cv2.line(I,(convexhull[i,0,0],convexhull[i,0,1]),(convexhull[i+1,0,0],convexhull[i+1,0,1]),255,2)\n #首尾相接\n cv2.line(I,(convexhull[k-1,0,0],convexhull[k-1,0,1]),(convexhull[0,0,0],convexhull[0,0,1]),255,2)\n #顯示圖片\n cv2.imshow(\"I\",I)\n cv2.imwrite(\"I.jpg\",I)\n cv2.waitKey(0)\n cv2.destroyAllWindows() \n","sub_path":"0521/p07_幾何形狀的檢測和擬合/01_convexHull.py","file_name":"01_convexHull.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"229273275","text":"from collections import defaultdict, Counter\nimport statistics\nfrom _collections import deque\nimport math\nimport itertools\nimport pickle\nimport os\n\ndef itercons(iterable, n):\n \"\"\" Iterates over overlapping list of 'n' consecutive elements (python equivalent of each_cons).\n \"\"\"\n current = deque()\n for a in iterable:\n current.append(a)\n if len(current) == n:\n yield list(current)\n current.popleft()\n\ndef iterslices(iterable, n, smaller_last=True):\n \"\"\" Iterates over non-overlapping list of 'n' consecutive elements (python equivalent of each_slices).\n The last element might be smaller.\n \"\"\"\n current = []\n for a in iterable:\n current.append(a)\n if len(current) == n:\n yield current\n current = []\n if current and smaller_last:\n yield current\n\n\ndef covariance(array1, array2):\n m1 = statistics.mean(array1) \n m2 = statistics.mean(array2) \n n = len(array1)\n return sum([(e1 - m1) * (e2 - m2) for e1, e2 in zip(array1, array2)]) / (n - 1)\n \n \ndef coorelation(array1, array2):\n m1 = statistics.mean(array1) \n m2 = statistics.mean(array2) \n s1 = statistics.stdev(array1) \n s2 = statistics.stdev(array2) \n assert len(array1) == len(array2)\n n = len(array1)\n return sum([(e1 - m1) * (e2 - m2) for e1, e2 in zip(array1, array2)]) / (n - 1) / (s1*s2)\n\n\ndef cosine_similarity(a1, a2):\n sumxx, sumxy, sumyy = 0, 0, 0\n for x, y in zip(a1, a2):\n sumxx += x*x\n sumyy += y*y\n sumxy += x*y\n if sumxx*sumyy == 0:\n return 0\n return sumxy/math.sqrt(sumxx*sumyy)\n\n\ndef similarity(tab1, tab2):\n counter1 = Counter()\n counter2 = Counter()\n total1, total2 = 0, 0\n for n in range(1, 5):\n for cons in itercons(tab1, n):\n cons_str = \"\".join(str(c) for c in cons)\n counter1[cons_str] += 1\n total1 += 1\n for cons in itercons(tab2, n):\n cons_str = \"\".join(str(c) for c in cons)\n counter2[cons_str] += 1\n total2 += 1\n \n all_elms = list(set(counter1.keys()) | set(counter2.keys()))\n a1 = [counter1.get(e, 0)/total1 for e in all_elms]\n a2 = [counter2.get(e, 0)/total2 for e in all_elms]\n return (cosine_similarity(a1, a2))\n\ndef flatten_once(list_of_list):\n return list(itertools.chain(*list_of_list))\n\n\ndef count_ngrams(data, max_ngams=5):\n counters = [Counter() for _ in range (max_ngams + 1)]\n for n in range(1, max_ngams+1):\n total = 0\n if len(data) < n:\n break\n incr = 1 / (len(data) - n + 1) # 1/ number of ngrams of len n\n for cons in itercons(data, n):\n cons_str = bytes(cons)\n counters[n][cons_str] += incr\n return counters\n\n\ndef count_ngrams_flattened(data, max_ngams=5):\n result = {}\n for dct in count_ngrams(data, max_ngams=5):\n result.update(dct)\n return result\n\n\ndef load_pickle(filename):\n with open(filename, \"rb\") as fin:\n return (pickle.load(fin))\n \ndef save_pickle(filename, data):\n with open(filename, \"wb\") as fout:\n return (pickle.dump(data, fout))\n\n\nclass LangStats():\n def __init__(self, stats):\n self.stats = stats\n\n @classmethod\n def load_or_compute(cls, picklefile, files, max_ngams=5):\n if os.path.exists(picklefile):\n stats = load_pickle(picklefile)\n else:\n data = []\n for f in files:\n with open(f, \"rb\") as fin:\n data.append(fin.read())\n stats = count_ngrams_flattened(b\"\".join(data), max_ngams)\n save_pickle(picklefile, stats)\n return LangStats(stats)\n \n \n def get_probas(self, ngrams):\n return [self.stats.get(g, 0) for g in ngrams]\n \n def similarity(self, phrase, max_ngams=5):\n stats = count_ngrams_flattened(phrase, max_ngams)\n keys, values = zip(*stats.items())\n lang_probas = self.get_probas(keys)\n return cosine_similarity(lang_probas, values)\n \n def similarity_probas(self, phrase, max_ngams=5):\n stats = count_ngrams_flattened(phrase, max_ngams)\n print (phrase, stats)\n keys, values = zip(*stats.items())\n lang_probas = self.get_probas(keys)\n return [lang_probas, values]\n \n ","sub_path":"vig64/stegalib.py","file_name":"stegalib.py","file_ext":"py","file_size_in_byte":4344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"65520230","text":"import re\nimport json\nimport logging\nfrom channels import Group\nfrom channels.sessions import channel_session\nfrom .models import ScanList, TalkGroup\n\nlog = logging.getLogger(__name__)\n\n@channel_session\ndef ws_connect(message):\n try:\n prefix, tg_type, label = message['path'].strip('/').split('/')\n if prefix != 'ws-calls':\n log.debug('invalid ws path=%s', message['path'])\n return\n except ValueError:\n log.debug('invalid ws path=%s', message['path'])\n return\n\n log.debug('connect %s=%s client=%s:%s', \n tg_type, label, message['client'][0], message['client'][1])\n \n label_list = label.split('+')\n for new_label in label_list: \n channel_name = 'livecall-{}-{}'.format(tg_type, new_label)\n log.debug(\"Connected to channel {}\".format(channel_name))\n message.reply_channel.send({\"accept\": True})\n Group(channel_name, channel_layer=message.channel_layer).add(message.reply_channel)\n\n message.channel_session['scan'] = label\n\n@channel_session\ndef ws_receive(message):\n try:\n label = message.channel_session['scan']\n \n scan = ScanList.objects.get(name=label)\n except KeyError:\n log.debug('no scanlist in channel_session')\n return\n except ScanList.DoesNotExist:\n log.debug('recieved message, but scablist does not exist label=%s', label)\n return\n\n # conform to the expected message format.\n try:\n data = json.loads(message['text'])\n except ValueError:\n log.debug(\"ws message isn't json text=%s\", text)\n return\n \n@channel_session\ndef ws_disconnect(message):\n try:\n label = message.channel_session['scan']\n scan = ScanList.objects.get(name=label)\n Group('livecall-'+label, channel_layer=message.channel_layer).discard(message.reply_channel)\n except (KeyError, ScanList.DoesNotExist):\n pass\n","sub_path":"radio/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"39004119","text":"#Challenge can be found at https://www.hackerrank.com/challenges/computing-the-correlation/problem.\n\n\nimport math\n\ndef read():\n m = []\n ph = []\n ch = []\n N = int(input())\n for _ in range(N):\n l = list(map(int, input().split('\\t')))\n m.append(l[0])\n ph.append(l[1])\n ch.append(l[2]) \n return m, ph, ch, N\n\ndef squared_sum_by_element(l):\n sq_sum = 0\n for val in l:\n sq_sum = sq_sum + val ** 2\n return sq_sum\n\ndef squared_sum(l):\n return sum(l) ** 2\n\ndef product_sum(l1, l2):\n return sum([i * j for i, j in zip(l1, l2)])\n\n\ndef pearson_corr(l1, l2, N):\n numerator = N * product_sum(l1, l2) - sum(l1) * sum(l2)\n denominator = math.sqrt(N * squared_sum_by_element(l1) - squared_sum(l1)) * math.sqrt(N * squared_sum_by_element(l2) - squared_sum(l2))\n return numerator / denominator\n\ndef compute():\n m, ph, ch, N = read()\n\n m_ph = pearson_corr(m, ph, N)\n ph_ch = pearson_corr(ph, ch, N)\n m_ch = pearson_corr(ch, m, N)\n \n\n print(str(round(m_ph, 2)) + '\\n' + str(round(ph_ch, 2)) \n + '\\n' + str(round(m_ch, 2)))\n\ncompute()\n","sub_path":"Pearson Correlation Coefficient/pearson-coeff.py","file_name":"pearson-coeff.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"97795971","text":"import boto3\nimport sys\nimport os.path\nimport shutil\nfrom datetime import datetime\nimport CommonLibrary\n\nproject = 'DATA_LAKE_PRE_CALCULATE'\ntoday_date = str(datetime.date(datetime.now()))\nexecutable_path = os.path.abspath(os.path.join(os.path.realpath(os.path.dirname(sys.argv[0])), os.pardir)) + '/data_process/upload_data'\nbucket = 'qa.zefyr.datasource'\n\nfor folder in os.listdir(executable_path):\n if folder == 'ZS_120':\n s3_folder = '120_product_list'\n if folder == 'ZS_121':\n s3_folder = '121_brand_list'\n if folder == 'ZS_122':\n s3_folder = '122_retail_price'\n if folder == 'ZS_123':\n s3_folder = '123_product_low_high'\n if folder == 'ZS_125':\n s3_folder = '125_Brand_location'\n if folder == 'ZS_130':\n s3_folder = '130_brand_talk'\n if folder == 'ZS_131':\n s3_folder = '131_stock'\n if folder == 'ZS_132':\n s3_folder = '/132_cannabis_plc'\n if folder == 'ZS_133':\n s3_folder = '133_Dispensaries'\n if folder == 'ZS_135':\n s3_folder = '135_mj_doc_number'\n\n for subfolder in os.listdir((os.path.join(executable_path, folder))):\n uploadfilepath = (os.path.join(executable_path, folder, subfolder))\n uploadfilename = (os.path.join(project, s3_folder, today_date, subfolder))\n s3 = boto3.client('s3')\n s3.upload_file(uploadfilepath, bucket, uploadfilename)\n\n shutil.rmtree(executable_path + '/' + folder)\n\nCommonLibrary.StatesFlagUpdate(sys.argv[0])","sub_path":"data_process/aws_file_upload.py","file_name":"aws_file_upload.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"220639786","text":"import markup\nimport webbrowser\nimport os\nimport info.urlfile\n\nitems = ( \"Item one\", \"Item two\", \"Item three\", \"Item four\" )\nparas = ( \"This was a fantastic list.\", \"And now for something completely different.\" )\nimages = ( \"thumb1.jpg\", \"thumb2.jpg\", \"more.jpg\", \"more2.jpg\" )\n\npage = markup.page( )\npage.init( title=\"Project 42\", \n# css=( 'one.css', 'two.css' ), # eventually create CSS file with another script\n header=\"Something at the top\", \n footer=\"The bitter end.\" )\n\npage.ul()\npage.li( items ) # get list of headlines from func\npage.ul.close( )\n\npage.p( paras )\npage.img( src=images, width=100, height=80, alt=\"Thumbnails\" )\n\n# create temporary web file\ni_file = open(\"cache/index.html\", \"w+\")\ni_file.write(str(page))\ni_file.close()\nnew = 2\nurl = \"file:///home/aethio/project_42/cache/index.html\"\nwebbrowser.open(url, new=new)\n#os.remove(\"/home/aethio/project_42/cache/index.html\")\n\n#def gen_html(): # when printing, print url id associated (1,2,3,4 print page\n# info.urlfile = reload(info.urlfile)\n# for name, items in info.urlfile.__dict__.iteritems(): # for d\n# if isinstance(items, dict) and not name.startswith('_'):\n","sub_path":"scripts/.obsolete/gen_html.py","file_name":"gen_html.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"606730974","text":"from flask import Flask,request\nfrom flask_restful import Resource,Api\nfrom flask_jwt import JWT, jwt_required\nfrom security import authenticate,identity\n\napp = Flask(__name__)\napp.security_key = 'Jagadish'\napi = Api(app)\n\nJWT = JWT(app,authenticate,identity) #/auth\nitems = []\n\nclass Item(Resource):\n @jwt_required()\n def get(self,name):\n item = next(filter(lambda x:x['name']==name,items))\n return {'item': item},200 if item is not None else 404\n\n def post(self,name):\n if next(filter(lambda x:x['name']==name,items),None):\n return{'message':\"An item with name '{}' already exists\".format(name)},400\n\n data = request.get_json()\n item = {'name':name,'price':data['price'],'type':'wood'}\n items.append(item)\n return item,201\n\nclass ItemList(Resource):\n def get(self):\n return {'item':items}\n\napi.add_resource(Item,'/item/')\napi.add_resource(ItemList,'/items')\n\napp.run(port=4999,debug = True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"402613843","text":"def load_input(filename):\n with open(filename, 'r') as input_file:\n data = [str(line.strip()) for line in input_file]\n\n return data\n\ndef solve_a(data):\n twos = 0\n threes = 0\n\n for line in data:\n _set = set(line)\n\n two_match = False\n three_match = False\n\n for char in _set:\n count = line.count(char)\n\n if count == 2 and not two_match:\n twos += 1\n two_match = True\n elif count == 3 and not three_match:\n threes += 1\n three_match = True\n\n return twos * threes\n\ndef solve_b(data):\n for line_01 in data:\n for line_02 in data:\n if sum([1 if char[0] != char[1] else 0 for char in zip(list(line_01), list(line_02))]) == 1:\n\n return ''.join([line_01[index] if line_01[index] == line_02[index] else '' for index in range(len(line_01))])\n\nif __name__ == '__main__':\n data = load_input('challenges/day_02/input.txt')\n\n assert solve_a(['abcdef', 'bababc', 'abbcde', 'abcccd', 'aabcdd', 'abcdee', 'ababab']) == 12\n assert solve_b(['abcde', 'fghij', 'klmno', 'pqrst', 'fguij', 'axcye', 'wvxyz']) == 'fgij'\n\n answer_a = solve_a(data)\n answer_b = solve_b(data)\n\n print(f'Part A answer: {answer_a} Part B answer: {answer_b}')\n\n","sub_path":"Challenges/day_02/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"557834370","text":"import os\nimport random\nimport time\nfrom datetime import datetime, timezone, timedelta\n\n\nCMD = '''git filter-branch -f --env-filter \\\\\n \\'if [ $GIT_COMMIT = {hash} ]\n then{export}\n fi\\''''\n\nDATE = '''export GIT_AUTHOR_DATE=\"{date}\"\n export GIT_COMMITTER_DATE=\"{date}\"'''\n\nNAME = '''export GIT_AUTHOR_NAME=\"{name}\"\n export GIT_COMMITTER_NAME=\"{name}\"'''\n\nEMAIL = '''export GIT_AUTHOR_EMAIL=\"{email}\"\n export GIT_COMMITTER_EMAIL=\"{email}\"'''\n\n\ndef strTimeProp(start, end, prop, frmt):\n stime = time.mktime(time.strptime(start, frmt))\n etime = time.mktime(time.strptime(end, frmt))\n ptime = stime + prop * (etime - stime)\n return int(ptime)\n\n\ndef formatDateList(mylist, frmtA='%Y-%m-%d %H:%M:%S', frmtB=\"%a %b %d %H:%M %Y %z\"):\n return [datetime.strptime(x, '%Y-%m-%d %H:%M:%S').astimezone(timezone(timedelta(hours=+8))).strftime(\"%a %b %d %H:%M %Y %z\") for x in mylist]\n\n\ndef randomDateList(start, end, n, frmt='%Y-%m-%d %H:%M:%S'):\n return [time.strftime(frmt, time.localtime(strTimeProp(start, end, random.random(), frmt))) for _ in range(n)]\n\n\ndef getRandomDateList(start, end, lenth):\n mylist = randomDateList(start, end, lenth)\n mylist = sorted(mylist, reverse=True)\n return formatDateList(mylist)\n\n\ndef main(default, git_hash, is_execute):\n if git_hash == []:\n os.system(\n 'git log --pretty=format:\"%H\" > gitlogEc971d5b54aa973826103e303a96a3c19d0d914c')\n git_hash = open('gitlogEc971d5b54aa973826103e303a96a3c19d0d914c', 'r')\\\n .read()\\\n .split('\\n')\n\n dates = getRandomDateList(default['start'], default['end'], len(git_hash)) if 'start' in default and 'end' in default else []\n\n for i, h in enumerate(git_hash):\n export = '\\n\\t{DATE}\\n\\t{NAME}\\n\\t{EMAIL}'.format(\n DATE=('' if dates == [] else DATE.format(date=dates[i])),\n NAME=(NAME.format(name=default['name']) if 'name' in default else ''),\n EMAIL=(EMAIL.format(email=default['email']) if 'email' in default else ''),\n )\n\n if export != '':\n if is_execute:\n os.system(CMD.format(\n hash=h,\n export=export,\n ))\n else:\n print(CMD.format(\n hash=h,\n export=export,\n ))\n os.system('rm gitlogEc971d5b54aa973826103e303a96a3c19d0d914c')\n\n\nif __name__ == '__main__':\n default = {\n # 'name': 'Yatimisi2018',\n # 'email': 'yatimisi2018@gmail.com',\n # 'start': '2010-02-02 00:00:00',\n # 'end': '2019-05-15 00:00:00',\n }\n\n git_hash = []\n\n main(default, git_hash, False)\n","sub_path":"newFile/transform-git-commit.py","file_name":"transform-git-commit.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"378914780","text":"import Communication.Packets.Outgoing.ServerPacketHeader as Outgoin\r\nimport HabboHotel.Game as Game\r\nfrom Communication.DataStream.Response import Response\r\n\r\nclass NavigatorMetaDataComposer:\r\n def __init__(self):\r\n self.response = Response(Outgoin.NavigatorMetaDataComposer)\r\n self.response.WriteInt(len(Game.NavigatorManager.GetParentTabs()))\r\n\r\n for tab in Game.NavigatorManager.GetParentTabs():\r\n self.response.WriteString(tab.tab_name)\r\n self.response.WriteInt(0)","sub_path":"GuardianServer/Communication/Packets/Outgoing/Navigator/NavigatorMetaDataComposer.py","file_name":"NavigatorMetaDataComposer.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"619375244","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\nimport django.core.validators\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Category',\n fields=[\n ('Name', models.CharField(max_length=30, unique=True, serialize=False, primary_key=True)),\n ],\n ),\n migrations.CreateModel(\n name='Service',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('NameService', models.CharField(max_length=50)),\n ('DescriptionService', models.TextField(max_length=500)),\n ('Calification', models.PositiveIntegerField(validators=[django.core.validators.MaxValueValidator(10)])),\n ('Phone', models.IntegerField()),\n ('Image', models.ImageField(upload_to=b'static/ImageService')),\n ('Category', models.ForeignKey(to='Service.Category')),\n ],\n ),\n migrations.CreateModel(\n name='UserAQL',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('FirstName', models.CharField(max_length=50)),\n ('LastName', models.CharField(max_length=50)),\n ('DNI', models.IntegerField()),\n ('Email', models.EmailField(max_length=300)),\n ('Phone', models.IntegerField(max_length=10)),\n ('User', models.OneToOneField(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.AddField(\n model_name='service',\n name='User',\n field=models.ForeignKey(to='Service.UserAQL'),\n ),\n ]\n","sub_path":"aquienllamo9.0/Service/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"175092161","text":"# Напишіть клас Person, який містить наступну інформацію: прізвище, ім’я, по-батькові та дата народження людини. В\n# класі створіть метод, який по заданій даті народження виводитиме повну кількість років людини. Напишіть клас\n# Candidate, який наслідуватиме Person і доповнюватиме його наступною інформацією про кандидата у депутати: номер\n# округу, кількість виборців в окрузі, кількість виборців, що проголосувала за кандидата, партійна приналежність. Для\n# заданої партії знайдіть кандидата, за якого віддали голоси найбільший процент виборців та знайдіть найстаршого\n# кандидата серед усіх, хто подолав 50%.\n\nfrom datetime import datetime\n\n\nclass Person:\n def __init__(self, first_name, middle_name, last_name, birth_date):\n self.first_name = str(first_name)\n self.middle_name = str(middle_name)\n self.last_name = str(last_name)\n self.birth_date = datetime.strptime(birth_date, \"%d-%m-%Y\")\n\n def get_age(self):\n return int((datetime.now() - self.birth_date).days / 365.25)\n\n def __str__(self):\n return \" \".join([self.first_name, self.middle_name, self.last_name])\n\n\nclass Candidate(Person):\n def __init__(self, first_name, middle_name, last_name, birth_date, district, electorate, votes, party):\n super().__init__(first_name, middle_name, last_name, birth_date)\n self.district = int(district)\n self.electorate = int(electorate)\n self.votes = int(votes)\n if self.votes > self.electorate:\n self.votes = self.electorate\n\n self.party = str(party)\n\n\ndef get_the_best(candidates):\n \"\"\"\n Повертає найкращого кандидата. По відсотку голосів.\n :param candidates:\n :return:\n \"\"\"\n result = candidates[0]\n percent = result.votes / result.electorate\n for i in candidates:\n current = i.votes / i.electorate\n if current > percent:\n percent = current\n result = i\n return result\n\n\ndef get_oldest(candidates):\n \"\"\"\n Повертає найстаршого кандидата\n :param candidates:\n :return:\n \"\"\"\n result = candidates[0]\n max = result.get_age()\n for i in candidates:\n current = i.get_age()\n if current > max:\n max = current\n result = i\n return result\n\n\ndef get_more_than(candidates, percent=0.5):\n \"\"\"\n Повертає кандидатів у яких процен голосів більше ніж деяке число(0.5 == 50%)\n :param candidates:\n :param percent:\n :return:\n \"\"\"\n result = []\n for i in candidates:\n if i.votes / i.electorate >= percent:\n result.append(i)\n return result\n\n\nif __name__ == '__main__':\n putin = Candidate(\"Vladimir\", \"Vladimirovich\", \"Putin\", \"06-04-1964\", 1, 1000, 1200, \"Edinaya Rosiya\")\n poroshenko = Candidate(\"Poroshenko\", \"Ivan\", \"Ivanovuch\", \"07-05-1910\", 10, 1000, 1100, \"Roshen\")\n tamara = Candidate(\"Tamara\", \"Prosto\", \"Tamara\", \"21-09-1997\", 1, 12, 4, \"Tamara\")\n #Додаш сама.\n\n all = [putin, poroshenko, tamara]\n print(\"за якого віддали голоси найбільший процент виборців:\" + str(get_the_best(all)))\n print(\"знайдіть найстаршого кандидата серед усіх, хто подолав 50%.\", str(get_oldest(get_more_than(all))))","sub_path":"_6.py","file_name":"_6.py","file_ext":"py","file_size_in_byte":3877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"393678645","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 8 11:02:59 2015\n\nThis Modules contains input/output functions for reading/writing files.\n\n@author: Landon\n\"\"\"\n\nimport sys\n\n## INPUT MENUS##\n\ndef recur_find(path, f_type): #finds all files of type(f_type) in directory tree.\n import fnmatch\n import os\n matches = []\n for root, dirnames, filenames in os.walk(path):\n for filename in fnmatch.filter(filenames, '*.' + f_type):\n matches.append(os.path.join(root, filename))\n return(matches)\n \ndef file_finder(path, f_type):\n import glob\n return(glob.glob(path + '/*.' + f_type))\n \n## OUTPUT MENUS##\n \ndef make_dir(obtain):\n import os\n if not os.path.exists(os.path.dirname(obtain)):\n os.makedirs(os.path.dirname(obtain))\n \ndef excel_write(path, data_out):\n import pandas as pd\n writer = pd.ExcelWriter(path + 'data_dump.xlsx')\n print(\"Writing to Excel file...\", path + 'data_dump.xlsx')\n data_out.to_excel(writer)\n writer.save()\n \ndef output_parent(path):\n import os\n path = os.path.dirname(path)\n return(path)\n \ndef write_table(table, title, path, file_name):\n import os\n table_txt = table.get_string()\n with open(os.path.join(path, file_name), 'a') as file:\n file.write('\\n' + title + '\\n')\n file.write(table_txt)\n file.close()","sub_path":"DB_DIR/menu_items.py","file_name":"menu_items.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"556190788","text":"# coding:utf8\nimport torch\nfrom torch import nn\nfrom .basic_module import BasicModule\n\nclass LSTMNet(BasicModule):\n def __init__(self, in_dim, hidden_dim, n_layer, n_class, device):\n super(LSTMNet, self).__init__()\n self.n_class = n_class\n self.n_layer = n_layer\n self.hidden_dim = hidden_dim\n self.lstm = nn.LSTM(in_dim, hidden_dim, n_layer, batch_first=True, bidirectional=True)\n #self.lstm = nn.LSTM(in_dim, hidden_dim, n_layer, batch_first=True)\n self.out = nn.Linear(hidden_dim*2, self.n_class)\n #self.out = nn.Linear(hidden_dim, self.n_class)\n self.device = device\n\n def forward(self, x):\n# import ipdb\n# ipdb.set_trace()\n h0 = torch.zeros(self.n_layer*2, x.size(0), self.hidden_dim).to(self.device)\n c0 = torch.zeros(self.n_layer*2, x.size(0), self.hidden_dim).to(self.device)\n \n lstm_out, _ = self.lstm(x,(h0,c0))\n #lstm_out, _ = self.lstm(x)\n out = self.out(lstm_out)\n\t# pay attention to the dim of tensor,or there are some error of criterion \n out = out.view(-1, self.n_class)\n #return out\n return out,lstm_out\n\n\n","sub_path":"models/lstmnet.py","file_name":"lstmnet.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"87576257","text":"'''\n@author: wei,xiang\nmodified by c_yazli\n'''\n\nimport fs_wrapper\nimport settings.common as SC\nfrom case_utility import *\nfrom logging_wrapper import log_test_case, save_fail_log, print_report_line\nfrom test_case_base import TestCaseBase\nfrom qrd_shared.case import *\nfrom qrd_shared.launcher.Launcher import Launcher\nfrom _ctypes_test import func\n\nclass test_suit_cmcc_devci_message_case13(TestCaseBase):\n '''\n\n @see: L{TestCaseBase }\n '''\n \n \n def test_case_main(self, case_results):\n global case_flag , TAG\n case_flag = False\n TAG = \"Dev-ci cases: Messager \"\n log_test_case(self.case_config_map[fs_wrapper.CASE_NAME_ATTR], self.name +' : case Start')\n log_test_framework(TAG, self.name + \" -Start\")\n send_num = SC.PUBLIC_CHINAMOBIE_TESTING_NUMBER\n #Preconditions: Requires photo to be most recent picture taken and for the video to be directly across from it\n \"\"\"\n cases contnets you need to add\n \n \"\"\"\n #send picture\n send_key(KEY_HOME)\n launcher = Launcher()\n launcher.launch_from_launcher('gallery')\n gallery.go_home()\n #click_menuitem_by_text(text, isVerticalList, isScrollable, searchFlag, waitForView, clickType)\n send_key(KEY_MENU)\n click_textview_by_text(\"Select album\")\n sleep(1)\n click_button_by_id(\"selection_menu\")\n sleep(1)\n click_textview_by_text(\"Select all\")\n sleep(1)\n if search_view_by_id(\"action_delete\"):\n click_button_by_id(\"action_delete\")\n sleep(1)\n if search_text(\"OK\"):\n click_textview_by_text(\"OK\")\n send_key(KEY_BACK)\n send_key(KEY_BACK)\n \n start_activity(\"org.codeaurora.snapcam\", \"com.android.camera.CameraLauncher\")\n sleep(1)\n if search_text(\"Remember photo locations\"):\n click_textview_by_text(\"Yes\")\n sleep(1)\n click_imageview_by_id(\"camera_switcher\")\n sleep(1)\n click_imageview_by_desc('Switch to photo')\n sleep(1)\n click_imageview_by_desc('Shutter')\n sleep(5)\n click_imageview_by_id(\"camera_switcher\")\n sleep(1)\n click_imageview_by_desc(\"Switch to video\")\n sleep(5)\n click_imageview_by_desc('Shutter')\n sleep(2)\n click_imageview_by_id('shutter_button')\n sleep(1)\n #modified by c_yazli\n send_key(KEY_HOME)\n sleep(2)\n \n \n launcher.launch_from_launcher('gallery')\n sleep(1)\n click(540,925)\n take_screenshot()\n sleep(1)\n send_key(KEY_MENU)\n click_textview_by_text(\"Select item\")\n click(555,825)\n if search_view_by_desc(\"Share with Messaging\"):\n click_imageview_by_id(\"default_activity_button\")\n sleep(1)\n else:\n #search_view_by_desc(\"Messaging\"):\n click_imageview_by_desc(\"Share with\")\n sleep(1)\n click_textview_by_text(\"Messaging\")\n \n if search_text(\"Message size\"):\n click_button_by_text(\"OK\")\n log_test_case(\"test_suit_cmcc_devci_message_case13\", \"Enter messaging successfully\")\n else:\n log_test_case(\"test_suit_cmcc_devci_message_case13\", \"Can't Enter messaging \")\n take_screenshot()\n \n \n launcher.launch_from_launcher('gallery')\n #click(540,925)\n take_screenshot()\n sleep(1)\n send_key(KEY_MENU)\n click_textview_by_text(\"Select item\")\n click(544,1180)\n click_imageview_by_id(\"default_activity_button\")\n sleep(5)\n click_textview_by_id(\"recipients_editor\")\n ime.IME_input_number(1, send_num, \"c\")\n log_test_framework(self.name, \"Sending MMS with picture\")\n \n \n func2 = lambda:search_text('MMS', isScrollable=1, searchFlag=TEXT_CONTAINS) \n if not wait_for_fun(func2, True, 10):\n set_cannot_continue()\n log_test_framework(\"cmcc_devci_message_case11:\", \"send button not found\")\n else:\n click_imageview_by_id('send_button_mms')\n \n func3 = lambda:search_text(mms.get_value(\"sent\"), searchFlag=TEXT_CONTAINS)\n if not wait_for_fun(func3, True, 60):\n log_test_framework(\"cmcc_devci_message_case13:\", \"Sent mms failed\")\n else:\n log_test_framework(\"cmcc_devci_message_case13:\", \"Sent mms successful\")\n case_flag = True\n mms.go_home()\n \n \n if case_flag:\n qsst_log_case_status(STATUS_SUCCESS, \"\" , SEVERITY_HIGH)\n else:\n qsst_log_case_status(STATUS_FAILED, \"\", SEVERITY_HIGH)\n \n case_results.append((self.case_config_map[fs_wrapper.CASE_NAME_ATTR], case_flag))\n \n \n def test_case_end(self):\n '''\n record the case result\n\n '''\n log_test_case(self.case_config_map[fs_wrapper.CASE_NAME_ATTR], TAG + ' : end')\n if can_continue() and case_flag == True:\n # shutdown()\n log_test_case(self.case_config_map[fs_wrapper.CASE_NAME_ATTR], TAG + ': case pass')\n print_report_line(self.case_config_map[fs_wrapper.CASE_NAME_ATTR] + TAG + ' : \\tpass')\n else:\n log_test_case(self.case_config_map[fs_wrapper.CASE_NAME_ATTR], TAG + ' : case fail')\n print_report_line(self.case_config_map[fs_wrapper.CASE_NAME_ATTR] + TAG + ' : \\tfail')\n save_fail_log()\n ","sub_path":"Source/QSST/Config/data/M/test_env/test_suit_cmcc_devci_message/test_suit_cmcc_devci_message_case13.py","file_name":"test_suit_cmcc_devci_message_case13.py","file_ext":"py","file_size_in_byte":5523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"544278080","text":"from django.shortcuts import render,redirect\nfrom .models import Car\nfrom .forms import CarsForm\nfrom django.contrib import messages\n\ndef car_list(request):\n\tcars = Car.objects.all()\n\tcontext = {\n\t\t\"cars\": cars,\n\t}\n\treturn render(request, 'car_list.html', context)\n\n\ndef car_detail(request, car_id):\n\tcar = Car.objects.get(id=car_id)\n\tcontext = {\n\t\t\"car\": car,\n\t}\n\treturn render(request, 'car_detail.html', context)\n\n\ndef car_create(request):\n\tform = CarsForm()\n\tif request.method == \"POST\":\n\t\tform = CarsForm(request.POST, request.FILES)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\tmessages.success(request, \"Car Created Successfully.\")\n\t\t\treturn redirect(\"car-list\")\n\tcontext = {\n \"form\":form\n }\n\treturn render(request, 'car_create.html', context)\n\n\ndef car_update(request, car_id):\n\tobj = Car.objects.get(id=car_id)\n\tform = CarsForm(instance=obj)\n\tif request.method == \"POST\":\n\t\tform = CarsForm(request.POST, request.FILES, instance=obj)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\tmessages.success(request, \"Car Updated Successfully.\")\n\t\t\treturn redirect(\"car-list\")\n\tcontext = {\n \"obj\":obj,\n \"form\":form\n }\n\treturn render(request, 'car_update.html', context)\n\n\ndef car_delete(request, car_id):\n\tCar.objects.get(id=car_id).delete()\n\tmessages.error(request, \"Car Deleted Successfully.\")\n\treturn redirect(\"car-list\")\n","sub_path":"cars/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"635082138","text":"'''\nCreated on Apr 25, 2013\n\n@author: osune\n'''\nfrom PyQt4 import QtCore, QtGui, Qt\n\nfrom .ui_moodlescraper import Ui_MainWindow\nfrom ..UiLogic.config import ConfigWrapper\nfrom ..UiLogic.loginlogic import LoginWrapper\nfrom ..UiLogic.treeitems import FileItem, FolderItem\nfrom ...MoodleScraperBase import virtfilesys as vfs\n\nimport time\nimport logging\n\n\n\n\n\n\nclass MissingConfigError(Exception):\n pass\n\nclass MainWindow(QtGui.QMainWindow):\n '''\n MoodleScraper main window\n '''\n\n\n def __init__(self, *args):\n '''\n Constructor\n '''\n QtGui.QMainWindow.__init__(self, *args)\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n self.setupLogic()\n self.createConnects()\n self.loadConfigs()\n\n if not self.config.logFile is None:\n logging.basicConfig(filename=self.config.logFile, level=self.config.logLvl)\n else:\n logging.basicConfig(level=self.config.logLvl)\n\n self.courses = []\n self.foundfiles = []\n self.selectedFiles = []\n self.syncinprogress = False\n self.logininprogress = False\n\n\n def setupLogic(self):\n self.config = ConfigWrapper()\n\n\n\n\n def createConnects(self):\n self.ui.actionQuit.setMenuRole(QtGui.QAction.QuitRole)\n self.ui.actionQuit.triggered.connect(self.close)\n self.ui.actionConfiguration.triggered.connect(self.switchToConfig)\n self.ui.btnBxConfig.accepted.connect(self.saveConfigs)\n self.ui.btnBxConfig.rejected.connect(self.switchToSync)\n self.ui.pBtnSynchronize.clicked.connect(self.sync)\n self.ui.pBtnLogin.clicked.connect(self.login)\n\n\n\n @QtCore.pyqtSlot()\n def login(self):\n\n if self.logininprogress: return\n self.logininprogress = True\n try:\n QtGui.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))\n if self.ui.lEdUsername.text() == '' or self.ui.lEdPassword.text() == '':\n return\n try:\n if self.config.url is None or self.config.targetFolder is None:\n raise MissingConfigError\n except Exception as ex:\n em = QtGui.QMessageBox.critical(self,\n self.tr(\"Missing configuration\"),\n self.tr('Non optional configuration is missing.')\n )\n if (em == QtGui.QMessageBox.Ok):\n self.switchToConfig()\n else:\n progressDialog = QtGui.QProgressDialog(self.tr('Login in progress.\\nRetrieving course data.'), None, 0, 0, self)\n progressDialog.setWindowModality(QtCore.Qt.WindowModal)\n progressDialog.setMinimumDuration(1)\n\n\n loginobj = LoginWrapper(self.ui.lEdUsername.text(),\n self.ui.lEdPassword.text(),\n self.config.url,\n self.config.targetFolder)\n\n\n\n\n loginobj.coursefound.connect(self.addCourseToTree)\n loginobj.filefound.connect(self.addFileToTree)\n loginobj.finished.connect(progressDialog.cancel)\n\n\n\n\n\n\n\n\n self.ui.treeWidget.clear()\n\n logging.debug('Starting login thread')\n\n loginThread = QtCore.QThread()\n loginobj.moveToThread(loginThread)\n loginobj.finished.connect(loginThread.quit)\n loginThread.started.connect(loginobj.dologin)\n# progressDialog.canceled.connect(loginThread.quit)\n loginThread.start()\n\n progressDialog.show()\n progressDialog.exec_()\n# loginThread.quit()\n loginThread.wait()\n\n\n\n\n\n except Exception as ex:\n print(ex)\n finally:\n QtGui.QApplication.restoreOverrideCursor()\n self.logininprogress = False\n\n\n @QtCore.pyqtSlot(vfs.Folder)\n def addCourseToTree(self, arg1):\n self.ui.treeWidget.addTopLevelItem(FolderItem(arg1))\n\n @QtCore.pyqtSlot(vfs.File)\n def addFileToTree(self, arg1):\n root = self.ui.treeWidget.invisibleRootItem()\n course_count = root.childCount()\n for i in range(course_count):\n item = root.child(i)\n if item.course == arg1.parent:\n file = FileItem(arg1)\n item.addChild(file)\n if not arg1.fileExists():\n file.mark_as_unsynced()\n break\n\n\n @QtCore.pyqtSlot()\n def sync(self):\n self.syncinprogress = True\n try:\n progress = QtGui.QProgressDialog(self.tr('Syncing Files'), self.tr('Abort'),\n 0, 100)\n progress.setWindowModality(QtCore.Qt.WindowModal)\n progress.setMinimumDuration(1)\n\n x = 1\n while(True):\n progress.setValue(x)\n x += 1\n if progress.wasCanceled():\n break\n time.sleep(1)\n progress.setValue(100)\n finally:\n self.syncinprogress = False\n\n\n @QtCore.pyqtSlot()\n def saveConfigs(self):\n self.config.saveConfig(self.ui.lEdUrl.text(),\n self.ui.lEdTargetFolder.text(),\n self.ui.sBxLogLevel.value(),\n self.ui.lEdLogFolder.text())\n self.switchToSync()\n\n def loadConfigs(self):\n self.ui.lEdUrl.setText(self.config.url)\n self.ui.lEdTargetFolder.setText(self.config.targetFolder)\n self.ui.sBxLogLevel.setValue(self.config.logLvl)\n self.ui.lEdLogFolder.setText(self.config.logFile)\n\n @QtCore.pyqtSlot()\n def switchToConfig(self):\n self.switchPage(1)\n\n @QtCore.pyqtSlot()\n def switchToSync(self):\n self.switchPage(0)\n\n def closeEvent(self, event):\n self.saveConfigs()\n event.accept()\n\n def switchPage(self, index):\n self.ui.stWMain.setCurrentIndex(index)\n","sub_path":"src/MoodleScraperLib/MoodleScraperGui/Ui/MainWindow.py","file_name":"MainWindow.py","file_ext":"py","file_size_in_byte":6161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"544986050","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# --------------------------------------------------------\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Chao CHEN (chaochancs@gmail.com)\n# Created On: 2017-06-13\n# --------------------------------------------------------\nimport sys\nsys.path.insert(0, '../')\nimport dataset.dataset as dataset\nfrom module.symbols import Net, Net_cls, save_weights\nfrom utils import AverageMeter, data_loader\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport torch\n\ndef test(model, test_loader, epoch, margin, threshlod, is_cuda=True, log_interval=1000):\n model.eval()\n test_loss = AverageMeter()\n accuracy = 0\n num_p = 0\n total_num = 0\n batch_num = len(test_loader)\n for batch_idx, (data_a, data_p, data_n,target) in enumerate(test_loader):\n if is_cuda:\n data_a = data_a.cuda()\n data_p = data_p.cuda()\n data_n = data_n.cuda()\n target = target.cuda()\n\n data_a = Variable(data_a, volatile=True)\n data_p = Variable(data_p, volatile=True)\n data_n = Variable(data_n, volatile=True)\n target = Variable(target)\n\n out_a = model(data_a)\n out_p = model(data_p)\n out_n = model(data_n)\n\n loss = F.triplet_margin_loss(out_a,out_p,out_n, margin)\n\n dist1 = F.pairwise_distance(out_a,out_p)\n dist2 = F.pairwise_distance(out_a,out_n)\n #print('dist1', dist1)\n #print('dist2',dist2)\n #print('threshlod', threshlod)\n\n num = ((dist1 < threshlod).sum() + (dist2 > threshlod).sum()).data[0]\n num_p += num\n num_p = 1.0 * num_p\n total_num += data_a.size()[0] * 2\n #print('num--num_p -- total', num, num_p , total_num)\n test_loss.update(loss.data[0])\n if (batch_idx + 1) % log_interval == 0:\n accuracy_tmp = num_p / total_num \n print('Test- Epoch {:04d}\\tbatch:{:06d}/{:06d}\\tAccuracy:{:.04f}\\tloss:{:06f}'\\\n .format(epoch, batch_idx+1, batch_num, accuracy_tmp, test_loss.avg))\n test_loss.reset()\n\n accuracy = num_p / total_num\n return accuracy\n\ndef best_test(model, _loader, model_path=None, is_cuda=True):\n if not model_path is None:\n model.load_full_weights(model_path)\n print('loaded model file: {:s}'.format(model_path))\n if is_cuda:\n model = model.cuda()\n model.eval()\n total_num = 0\n batch_num = len(_loader)\n for batch_idx, (data_a, data_p, data_n,target) in enumerate(_loader):\n if is_cuda:\n data_a = data_a.cuda()\n data_p = data_p.cuda()\n data_n = data_n.cuda()\n target = target.cuda()\n\n data_a = Variable(data_a, volatile=True)\n data_p = Variable(data_p, volatile=True)\n data_n = Variable(data_n, volatile=True)\n target = Variable(target)\n\n out_a = model(data_a)\n out_p = model(data_p)\n out_n = model(data_n)\n current_d_a_p = F.pairwise_distance(out_a,out_p)\n current_d_a_n = F.pairwise_distance(out_a,out_n)\n if batch_idx == 0:\n d_a_p = current_d_a_p\n d_a_n = current_d_a_n\n else:\n d_a_p = torch.cat((d_a_p, current_d_a_p), 0)\n d_a_n = torch.cat((d_a_n, current_d_a_n), 0)\n total_num += 2*data_a.size()[0]\n\n mean_d_a_p = d_a_p.mean().data[0]\n mean_d_a_n = d_a_n.mean().data[0]\n start = min(mean_d_a_n, mean_d_a_p)\n end = max(mean_d_a_n, mean_d_a_p)\n best_thre = 0\n best_num = 0\n thre_step = 0.1\n\n for val in torch.arange(start, end+thre_step, thre_step):\n num = (((d_a_p <= val).float()).sum() + (d_a_n > val).float().sum()).data[0]\n #print(num, val)\n if num > best_num:\n best_num = num\n best_thre = val\n return best_thre, best_num/total_num, mean_d_a_p, mean_d_a_n\n \n \n\n \n\n\ndef evaluation(model_path, test_list):\n model = Net()\n model = model.cuda()\n model.load_full_weights(model_path)\n model.eval()\n \n image_root = '/path/to/ReId_data/image/'\n if False:\n train_list = 'data/debug.txt'\n test_list = '../data/test_debug.txt'\n else:\n train_list = 'data/train_all_5set.txt'\n test_list = '../data/test_all_5set.txt'\n test_loader = data_loader(image_root, test_list, shuffle=True, batch_size=32)\n margin = 1\n accuracy = test(model, test_loader, 0, margin, threshlod=10, log_interval=10)\n\n\nif __name__ == '__main__':\n import os\n os.environ['CUDA_VISIBLE_DEVICES'] = '1'\n model = Net() \n margin = 1.0\n model_path = 'path/to/model/file'\n test_list = '../data/open_val.txt'\n image_root = 'data/root'\n test_loader = data_loader(image_root, test_list, shuffle=True, batch_size=128)\n thre, acc, _, _ = best_test(model, test_loader, model_path, is_cuda=True)\n print('best_threshold : {:.03f}, best_accuracy:{:.03f}'.format(thre, acc))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"tools/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"410570085","text":"import logging\n\nfrom dvc.exceptions import DvcException, InvalidArgumentError\nfrom dvc.repo import locked\nfrom dvc.repo.scm_context import scm_context\n\nfrom .utils import exp_commits, push_refspec, resolve_exp_ref\n\nlogger = logging.getLogger(__name__)\n\n\n@locked\n@scm_context\ndef push(\n repo,\n git_remote,\n exp_name: str,\n *args,\n force=False,\n push_cache=False,\n **kwargs,\n):\n exp_ref = resolve_exp_ref(repo.scm, exp_name)\n if not exp_ref:\n raise InvalidArgumentError(\n f\"'{exp_name}' is not a valid experiment name\"\n )\n\n def on_diverged(refname: str, rev: str) -> bool:\n if repo.scm.get_ref(refname) == rev:\n return True\n raise DvcException(\n f\"Local experiment '{exp_name}' has diverged from remote \"\n \"experiment with the same name. To override the remote experiment \"\n \"re-run with '--force'.\"\n )\n\n refname = str(exp_ref)\n logger.debug(\"git push experiment '%s' -> '%s'\", exp_ref, git_remote)\n\n from dvc.scm import TqdmGit\n\n with TqdmGit(desc=\"Pushing git refs\") as pbar:\n push_refspec(\n repo.scm,\n git_remote,\n refname,\n refname,\n force=force,\n on_diverged=on_diverged,\n progress=pbar.update_git,\n )\n\n if push_cache:\n _push_cache(repo, exp_ref, **kwargs)\n\n\ndef _push_cache(repo, exp_ref, dvc_remote=None, jobs=None, run_cache=False):\n revs = list(exp_commits(repo.scm, [exp_ref]))\n logger.debug(\"dvc push experiment '%s'\", exp_ref)\n repo.push(jobs=jobs, remote=dvc_remote, run_cache=run_cache, revs=revs)\n","sub_path":"dvc/repo/experiments/push.py","file_name":"push.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"390956860","text":"import sys\nimport unittest, pytest\n\nimport sympy as sp\nimport matplotlib.pyplot as plt\n\n\nif sys.platform == 'win32':\n pytestmark = pytest.mark.skip(\"Skipping test on Windows\")\n has_dla = False\n\n # Create stub class for test\n class dla(object):\n UserExpression = object\nelse:\n import dolfin as dl\n from pyapprox_dev.fenics_models.advection_diffusion import *\n from pyapprox_dev.fenics_models.advection_diffusion_wrappers import *\n from pyapprox_dev.fenics_models.fenics_utilities import *\n\nskiptest = unittest.skipIf(\n not has_dla, reason=\"fenics_adjoint package missing\")\n\n\nclass ExactSolutionPy(dla.UserExpression):\n def __init__(self, **kwargs):\n self.kappa = kappa\n self.t = 0\n if '2019' in dl.__version__:\n # does not work for fenics 2017 only 2019\n super().__init__(**kwargs)\n # in 2017 base class __init__ does not need to be called.\n\n def eval(self, values, x):\n values[0] = np.sin(2*np.pi*x[0])*np.sin(2*np.pi*x[1])*cos(\n 2*np.pi*self.t)\n if abs(x[0]) < 1e-12:\n # print(x,values,self.t)\n assert values[0] == 0\n\n\nclass ForcingPy(dla.UserExpression):\n def __init__(self, kappa, **kwargs):\n self.kappa = kappa\n self.t = 0\n if '2019' in dl.__version__:\n # does not work for fenics 2017 only 2019\n super().__init__(**kwargs)\n # in 2017 base class __init__ does not need to be called.\n\n def eval(self, values, x):\n values[0] = \\\n -2*np.pi*sin(\n 2*np.pi*self.t)*sin(2*np.pi*x[0])*sin(2*np.pi*x[1])\\\n + self.kappa*8*np.pi**2*sin(\n 2*np.pi*x[0])*sin(2*np.pi*x[1])*cos(2*np.pi*self.t)\n\n\ndef get_repeated_random_samples_with_varying_config_values(\n num_vars, config_vars, generate_random_sample, num_samples):\n num_config_vars = config_vars.shape[0]\n samples = np.empty((num_vars+num_config_vars, 0))\n random_samples = generate_random_sample(num_vars, num_samples)\n random_samples = np.vstack(\n (random_samples, np.empty((config_vars.shape[0], num_samples))))\n for ii in range(num_samples):\n samples_ii = random_samples[:, ii:ii+1]\n samples_ii = np.tile(samples_ii, (1, config_vars.shape[1]))\n samples_ii[-num_config_vars:, :] = config_vars\n samples = np.hstack((samples, samples_ii))\n return samples\n\n\ndef get_exact_solution_sympy(steady_state):\n from sympy.abc import t\n x, y = sp.symbols('x[0] x[1]')\n a, b, c = 2*dl.pi, 2*dl.pi, 2*dl.pi\n # using sp.pi instead of pi can cause JIT compiler to fail. Not sure why\n u = sp.sin(a*x)*sp.sin(b*y)\n if not steady_state:\n u *= sp.cos(c*t)\n return u, x, y, t\n\n\ndef get_exact_solution(mesh, degree, steady_state=False):\n exact_sol_sympy = get_exact_solution_sympy(steady_state)[0]\n exact_sol = dla.Expression(\n sp.printing.ccode(exact_sol_sympy), cell=mesh.ufl_cell(),\n domain=mesh, t=0, degree=degree)\n #print (sp.printing.ccode(exact_sol_sympy))\n return exact_sol\n\n\ndef get_forcing(kappa, mesh, degree, steady_state=False, advection=False):\n \"\"\"\n\n u(x,y,t)=sin(2*pi*x)*sin(2*pi*y)*cos(2*pi*t)\n\n is a solution to du/dt=k d^2u/dx^2+f on [0,1]^2\n\n f = -2*pi*sin(2*pi*t)*sin(2*pi*x[0])*sin(2*pi*x[1])\n + kappa*8*pi**2*sin(2*pi*x[0])*sin(2*pi*x[1])*cos(2*pi*t)\n \"\"\"\n u, x, y, t = get_exact_solution_sympy(steady_state)\n\n dxu2 = sum(u.diff(xi, 2) for xi in (x, y))\n dtu = u.diff(t, 1)\n if advection:\n bdxu = sum(u.diff(xi, 1)\n for xi in (x, y)) # for beta = Constant([1,1])\n # bdxu = sum(u.diff(xi, 1) for xi in (x,)) # for beta = Constant([1,0])\n forcing_sympy = dtu-kappa*dxu2+bdxu\n assert dtu == kappa*dxu2-bdxu+forcing_sympy\n else:\n forcing_sympy = (dtu-kappa*dxu2)\n assert dtu == kappa*dxu2+forcing_sympy\n #print (sp.printing.ccode(forcing_sympy))\n forcing = dla.Expression(\n sp.printing.ccode(forcing_sympy), cell=mesh.ufl_cell(), domain=mesh,\n degree=degree, t=0)\n\n return forcing\n\n\ndef get_gradu_dot_n(kappa, alpha, mesh, degree, phys_var, n):\n u, x, y, t = get_exact_solution_sympy(False)\n xi = [x, y][phys_var]\n gradu = u.diff(xi, 1)\n expr_sympy = kappa*gradu*n+alpha*u\n expr = dla.Expression(\n sp.printing.ccode(expr_sympy), cell=mesh.ufl_cell(), domain=mesh,\n degree=degree, t=0)\n # print(expr_sympy)\n return expr\n\n\ndef get_quadratic_exact_solution(alpha, beta, mesh, degree):\n exact_sol = dla.Expression('1 + x[0]*x[0] + alpha*x[1]*x[1] + beta*t',\n alpha=alpha, beta=beta, cell=mesh.ufl_cell(),\n domain=mesh, t=0, degree=degree)\n return exact_sol\n\n\ndef get_quadratic_solution_forcing(alpha, beta, mesh, degree):\n f = dla.Expression('beta - 2 - 2*alpha', beta=beta,\n alpha=alpha, degree=degree)\n return f\n\n\nclass TestTransientDiffusion(unittest.TestCase):\n def test_quadratic_solution(self):\n dt = 0.01\n t = 0\n final_time = 2\n nx, ny = 2, 2\n degree = 2\n alpha, beta = 3, 1.2\n kappa = dla.Constant(1)\n mesh = dla.RectangleMesh(dl.Point(0, 0), dl.Point(1, 1), nx, ny)\n function_space = dl.FunctionSpace(mesh, \"Lagrange\", degree)\n\n boundary_conditions = get_dirichlet_boundary_conditions_from_expression(\n get_quadratic_exact_solution(alpha, beta, mesh, degree), 0, 1, 0, 1)\n sol = run_model(\n function_space, kappa,\n get_quadratic_solution_forcing(alpha, beta, mesh, degree),\n get_quadratic_exact_solution(alpha, beta, mesh, degree),\n dt, final_time, boundary_conditions=boundary_conditions) # ,\n # exact_sol=get_quadratic_exact_solution(alpha,beta,mesh,degree))\n\n exact_sol = get_quadratic_exact_solution(alpha, beta, mesh, degree)\n exact_sol.t = final_time\n error = dl.errornorm(exact_sol, sol, mesh=mesh)\n print('Error', error)\n assert error <= 3e-14\n\n def test_cosine_solution_dirichlet_boundary_conditions(self):\n dt = 0.05\n t = 0\n final_time = 1\n nx, ny = 31, 31\n degree = 2\n kappa = dla.Constant(3)\n\n mesh = dla.RectangleMesh(dl.Point(0, 0), dl.Point(1, 1), nx, ny)\n function_space = dl.FunctionSpace(mesh, \"Lagrange\", degree)\n boundary_conditions = get_dirichlet_boundary_conditions_from_expression(\n get_exact_solution(mesh, degree), 0, 1, 0, 1)\n sol = run_model(\n function_space, kappa, get_forcing(kappa, mesh, degree),\n get_exact_solution(mesh, degree),\n dt, final_time, boundary_conditions=boundary_conditions,\n second_order_timestepping=True, exact_sol=None)\n\n exact_sol = get_exact_solution(mesh, degree)\n exact_sol.t = final_time\n error = dl.errornorm(exact_sol, sol, mesh=mesh)\n print('Error', error)\n assert error <= 1e-4\n\n def test_cosine_solution_robin_boundary_conditions(self):\n dt = 0.05\n t = 0\n final_time = 1\n nx, ny = 31, 31\n degree = 2\n kappa = dla.Constant(3)\n\n mesh = dla.RectangleMesh(dl.Point(0, 0), dl.Point(1, 1), nx, ny)\n function_space = dl.FunctionSpace(mesh, \"Lagrange\", degree)\n # bc : kappa * grad u.dot(n)+alpha*u=beta\n alpha = 1\n from functools import partial\n expression = partial(get_gradu_dot_n, kappa, alpha, mesh, degree)\n boundary_conditions = get_robin_boundary_conditions_from_expression(\n expression, dla.Constant(alpha))\n\n sol = run_model(\n function_space, kappa, get_forcing(kappa, mesh, degree),\n get_exact_solution(mesh, degree),\n dt, final_time, boundary_conditions=boundary_conditions,\n second_order_timestepping=True, exact_sol=None)\n\n exact_sol = get_exact_solution(mesh, degree)\n exact_sol.t = final_time\n error = dl.errornorm(exact_sol, sol, mesh=mesh)\n print('Error', error)\n assert error <= 1e-4\n\n def test_superposition_dirichlet_boundary_conditions(self):\n dt = 0.05\n t = 0\n final_time = 1\n nx, ny = 31, 31\n degree = 2\n kappa = dla.Constant(3)\n xl, xr, yb, yt = 0.25, 1.25, 0.25, 1.25\n\n sols = []\n mesh = dla.RectangleMesh(dl.Point(xl, yb), dl.Point(xr, yt), nx, ny)\n function_space = dl.FunctionSpace(mesh, \"Lagrange\", degree)\n for ii in range(4):\n boundary_conditions =\\\n get_dirichlet_boundary_conditions_from_expression(\n get_exact_solution(mesh, degree), xl, xr, yb, yt)\n for jj in range(4):\n if jj != ii:\n boundary_conditions[jj][2] = dla.Constant(0.)\n\n sol = run_model(\n function_space, kappa, dla.Constant(0.0),\n dla.Constant(0.0),\n dt, final_time, boundary_conditions=boundary_conditions,\n second_order_timestepping=True, exact_sol=None)\n sols.append(sol)\n\n sol = run_model(\n function_space, kappa, get_forcing(kappa, mesh, degree),\n get_exact_solution(mesh, degree),\n dt, final_time, boundary_conditions=None,\n second_order_timestepping=True, exact_sol=None)\n sols.append(sol)\n\n superposition_sol = sols[0]\n for ii in range(1, len(sols)):\n superposition_sol += sols[ii]\n superposition_sol = dla.project(superposition_sol, function_space)\n\n boundary_conditions = get_dirichlet_boundary_conditions_from_expression(\n get_exact_solution(mesh, degree), xl, xr, yb, yt)\n sol = run_model(\n function_space, kappa, get_forcing(kappa, mesh, degree),\n get_exact_solution(mesh, degree),\n dt, final_time, boundary_conditions=boundary_conditions,\n second_order_timestepping=True, exact_sol=None)\n\n exact_sol = get_exact_solution(mesh, degree, True)\n error = dl.errornorm(exact_sol, sol, mesh=mesh)\n print('Error', error)\n assert error <= 1e-4\n\n error = dl.errornorm(superposition_sol, sol, mesh=mesh)\n print('error', error)\n assert error < 1e-14\n\n\nclass TestSteadyStateDiffusion(unittest.TestCase):\n def test_superposition_dirichlet_boundary_conditions(self):\n nx, ny = 31, 31\n degree = 2\n kappa = dla.Constant(3)\n xl, xr, yb, yt = 0.25, 1.25, 0.25, 1.25\n\n sols = []\n mesh = dla.RectangleMesh(dl.Point(xl, yb), dl.Point(xr, yt), nx, ny)\n function_space = dl.FunctionSpace(mesh, \"Lagrange\", degree)\n for ii in range(4):\n boundary_conditions =\\\n get_dirichlet_boundary_conditions_from_expression(\n get_exact_solution(mesh, degree, True), xl, xr, yb, yt)\n for jj in range(4):\n if jj != ii:\n boundary_conditions[jj] = [\n 'dirichlet', boundary_conditions[jj][1], 0]\n sol = run_steady_state_model(\n function_space, kappa, dla.Constant(0.0),\n boundary_conditions=boundary_conditions)\n sols.append(sol)\n\n sol = run_steady_state_model(\n function_space, kappa, get_forcing(kappa, mesh, degree, True),\n boundary_conditions=None)\n sols.append(sol)\n\n superposition_sol = sols[0]\n for ii in range(1, len(sols)):\n superposition_sol += sols[ii]\n # pp=dl.plot(superposition_sol)\n #plt.colorbar(pp); plt.show()\n superposition_sol = dla.project(superposition_sol, function_space)\n\n boundary_conditions = get_dirichlet_boundary_conditions_from_expression(\n get_exact_solution(mesh, degree, True), xl, xr, yb, yt)\n sol = run_steady_state_model(\n function_space, kappa, get_forcing(kappa, mesh, degree, True),\n boundary_conditions=boundary_conditions)\n # plt.figure()\n # pp=dl.plot(sol-superposition_sol)\n #plt.colorbar(pp); plt.show()\n\n exact_sol = get_exact_solution(mesh, degree, True)\n error = dl.errornorm(exact_sol, sol, mesh=mesh)\n print('Error', error)\n assert error <= 1e-4\n\n error = dl.errornorm(superposition_sol, sol, mesh=mesh)\n print('error', error)\n assert error < 1e-14\n\n def test_superposition_mixed_boundary_conditions(self):\n nx, ny = 31, 31\n degree = 2\n kappa = dla.Constant(3)\n xl, xr, yb, yt = 0.0, 1.0, 0.0, 1.0\n\n \"\"\"\n based upon the test in Fenics example ft_poisson_extended\n \"\"\"\n x, y = sp.symbols('x[0], x[1]') # needed by UFL\n u = 1 + x**2 + 2*y**2 # exact solution\n u_e = u # exact solution\n u_00 = u.subs(x, 0) # restrict to x = 0\n u_01 = u.subs(x, 1) # restrict to x = 1\n u_10 = u.subs(y, 0) # restrict to y = 0\n u_11 = u.subs(y, 1) # restrict to y = 1\n f = -sp.diff(u, x, 2) - sp.diff(u, y, 2) # -Laplace(u)\n f = sp.simplify(f) # simplify f\n g_10 = sp.diff(u, y).subs(y, 0) # compute g = -du/dn\n g_11 = -sp.diff(u, y).subs(y, 1) # compute g = -du/dn\n\n # Collect variables\n variables = [u_e, u_00, u_01, u_10, u_11, f, g_10, g_11]\n\n # Turn into C/C++ code strings\n variables = [sp.printing.ccode(var) for var in variables]\n\n # Turn into FEniCS Expressions\n variables = [dla.Expression(var, degree=2) for var in variables]\n\n # Extract variables\n u_e, u_00, u_01, u_10, u_11, f, g_10, g_11 = variables\n\n # Extract variables\n u_e, u_00, u_01, u_10, u_11, f, g_10, g_11 = variables\n\n # Define boundary conditions\n bndry_objs = get_2d_rectangular_mesh_boundaries(xl, xr, yb, yt)\n boundary_conditions = [\n ['dirichlet', bndry_objs[0], u_00], # x = 0\n ['dirichlet', bndry_objs[1], u_01], # x = 1\n # ['dirichlet',bndry_objs[2],u_10], # y = 0\n # ['dirichlet',bndry_objs[3],u_11]] # y = 1\n ['robin', bndry_objs[2], g_10, 0.], # y = 0\n ['neumann', bndry_objs[3], g_11]] # y = 1\n\n # Compute solution\n kappa = dla.Constant(1)\n\n mesh = dla.RectangleMesh(dl.Point(xl, yb), dl.Point(xr, yt), nx, ny)\n function_space = dl.FunctionSpace(mesh, \"Lagrange\", degree)\n sol = run_steady_state_model(\n function_space, kappa, f,\n boundary_conditions=boundary_conditions)\n # pp=dl.plot(sol)\n #plt.colorbar(pp); plt.show()\n\n error = dl.errornorm(u_e, sol, mesh=mesh)\n print('error', error)\n assert error < 2e-12\n\n sols = []\n for ii in range(4):\n bndry_objs = get_2d_rectangular_mesh_boundaries(xl, xr, yb, yt)\n boundary_conditions_ii = [\n ['dirichlet', bndry_objs[0], u_00], # x = 0\n ['dirichlet', bndry_objs[1], u_01], # x = 1\n # ['dirichlet',bndry_objs[2],u_10], # y = 0\n # ['dirichlet',bndry_objs[3],u_11]] # y = 1\n ['robin', bndry_objs[2], 0., g_10], # y = 0\n ['neumann', bndry_objs[3], g_11]] # y = 1\n\n for jj in range(4):\n if jj != ii:\n # boundary_conditions_ii[jj]=['dirichlet',bndry_objs[jj],0]\n boundary_conditions_ii[jj][2] = 0\n\n sol_ii = run_steady_state_model(\n function_space, kappa, dla.Constant(0.0),\n boundary_conditions=boundary_conditions_ii)\n sols.append(sol_ii)\n # plt.figure(ii+1)\n # pp=dl.plot(sol_ii)\n # plt.colorbar(pp);\n\n bndry_objs = get_2d_rectangular_mesh_boundaries(xl, xr, yb, yt)\n boundary_conditions_ii = [\n ['dirichlet', bndry_objs[0], 0], # x = 0\n ['dirichlet', bndry_objs[1], 0], # x = 1\n # ['dirichlet',bndry_objs[2],0], # y = 0\n # ['dirichlet',bndry_objs[3],0]] # y = 1\n ['robin', bndry_objs[2], 0., 0], # y = 0\n ['neumann', bndry_objs[3], 0]] # y = 1\n\n sol_ii = run_steady_state_model(\n function_space, kappa, f,\n boundary_conditions=boundary_conditions_ii)\n sols.append(sol_ii)\n # plt.figure(ii+1)\n # pp=dl.plot(sol_ii)\n # plt.show()\n\n superposition_sol = sols[0]\n for ii in range(1, len(sols)):\n superposition_sol += sols[ii]\n # pp=dl.plot(superposition_sol)\n #plt.colorbar(pp); plt.show()\n superposition_sol = dla.project(superposition_sol, function_space)\n\n error = dl.errornorm(superposition_sol, sol, mesh=mesh)\n print('error', error)\n assert error < 5e-12\n\n\nclass TestTransientAdvectionDiffusionEquation(unittest.TestCase):\n def test_maunfactured_solution_dirichlet_boundaries(self):\n # Define time stepping\n final_time = 0.7\n exact_sol_sympy = get_exact_solution_sympy(steady_state=False)[0]\n exact_sol = dla.Expression(\n sp.printing.ccode(exact_sol_sympy), t=0, degree=6)\n exact_sol.t = final_time\n\n # Create mesh\n def run(nx, degree):\n dt = final_time/nx\n mesh = dla.RectangleMesh(dl.Point(0, 0), dl.Point(1, 1), nx, nx)\n # Define function spaces\n function_space = dl.FunctionSpace(mesh, \"CG\", degree)\n # Define initial condition\n initial_condition = dla.Constant(0.0)\n\n # Define velocity field\n beta = dla.Expression(\n ('1.0', '1.0'), cell=mesh.ufl_cell(), domain=mesh,\n degree=degree)\n # Define diffusivity field\n kappa = dla.Constant(1.0)\n\n # Define forcing\n forcing = get_forcing(\n kappa, mesh, degree, steady_state=False, advection=True)\n\n # boundary_conditions = \\\n # get_dirichlet_boundary_conditions_from_expression(\n # get_exact_solution(mesh,degree),0,1,0,1)\n boundary_conditions = None\n sol = run_model(\n function_space, kappa, forcing, initial_condition, dt,\n final_time, boundary_conditions, velocity=beta,\n second_order_timestepping=True)\n return sol\n\n # use refined reference solution instead of exact solution\n # exact_sol=run(128,2)\n\n etypes, degrees, rates, errors = compute_convergence_rates(\n run, exact_sol, max_degree=1, num_levels=4)\n degree = 1\n print(rates[degree]['L2 norm'])\n assert np.allclose(\n rates[degree]['L2 norm'][-1:], (degree+1)*np.ones(1), atol=1e-2)\n # for error_type in etypes:\n # print('\\n' + error_type)\n # for degree in degrees:\n # print('P%d: %s' %(degree, str(rates[degree][error_type])[1:-1]))\n\n def test_maunfactured_solution_dirichlet_boundaries_using_object(self):\n # Define time stepping\n final_time = 0.7\n exact_sol_sympy = get_exact_solution_sympy(steady_state=False)[0]\n exact_sol = dla.Expression(\n sp.printing.ccode(exact_sol_sympy), t=0, degree=6)\n exact_sol.t = final_time\n\n class NewModel(AdvectionDiffusionModel):\n def initialize_random_expressions(self, random_sample):\n init_condition = self.get_initial_condition(None)\n boundary_conditions, function_space = \\\n self.get_boundary_conditions_and_function_space(None)\n beta = self.get_velocity(None)\n forcing = self.get_forcing(None)\n kappa = self.get_diffusivity(None)\n return init_condition, boundary_conditions, function_space, \\\n beta, forcing, kappa\n\n def get_velocity(self, random_sample):\n assert random_sample is None\n beta = dla.Expression(\n ('1.0', '1.0'), cell=self.mesh.ufl_cell(), domain=self.mesh,\n degree=self.degree)\n return beta\n\n def get_diffusivity(self, random_sample):\n assert random_sample is None\n return dla.Constant(1.0)\n\n def get_forcing(self, random_sample):\n assert random_sample is None\n kappa = self.get_diffusivity(None)\n return get_forcing(\n kappa, self.mesh, self.degree, steady_state=False,\n advection=True)\n\n def run(n, degree):\n nx = np.log2(n)-2\n model = NewModel(final_time, degree, qoi_functional_misc)\n samples = np.array([[nx, nx, nx]]).T\n sol = model.solve(samples)\n return sol\n etypes, degrees, rates, errors = compute_convergence_rates(\n run, exact_sol, max_degree=1, num_levels=4)\n degree = 1\n print(rates[degree]['L2 norm'])\n assert np.allclose(\n rates[degree]['L2 norm'][-1:], (degree+1)*np.ones(1), atol=1e-2)\n\n @skiptest\n def test_advection_diffusion_base_class(self):\n \"\"\"\n Just check the benchmark runs\n \"\"\"\n nvars, corr_len = 2, 0.1\n benchmark = setup_advection_diffusion_benchmark(\n nvars=nvars, corr_len=corr_len, max_eval_concurrency=1)\n model = benchmark.fun\n #random_samples = np.zeros((nvars,1))\n random_samples = -np.sqrt(3)*np.ones((nvars, 1))\n config_samples = 3*np.ones((3, 1))\n samples = np.vstack([random_samples, config_samples])\n bmodel = model.base_model\n qoi = bmodel(samples)\n assert np.all(np.isfinite(qoi))\n sol = bmodel.solve(samples)\n\n @skiptest\n def test_advection_diffusion_base_class_adjoint(self):\n nvars, corr_len = 2, 0.1\n benchmark = setup_advection_diffusion_benchmark(\n nvars=nvars, corr_len=corr_len, max_eval_concurrency=1)\n model = benchmark.fun\n #random_samples = np.zeros((nvars,1))\n random_samples = -np.sqrt(3)*np.ones((nvars, 1))\n config_samples = 3*np.ones((3, 1))\n samples = np.vstack([random_samples, config_samples])\n bmodel = model.base_model\n qoi = bmodel(samples)\n assert np.all(np.isfinite(qoi))\n sol = bmodel.solve(samples)\n\n grad = qoi_functional_grad_misc(sol, bmodel)\n\n kappa = bmodel.kappa\n J = dl_qoi_functional_misc(sol)\n control = dla.Control(kappa)\n Jhat = dla.ReducedFunctional(J, control)\n h = dla.Function(kappa.function_space())\n h.vector()[:] = np.random.normal(\n 0, 1, kappa.function_space().dim())\n conv_rate = dla.taylor_test(Jhat, kappa, h)\n assert np.allclose(conv_rate, 2.0, atol=1e-3)\n\n # Check that gradient with respect to kappa is calculated correctly\n # this requires passing in entire kappa vector and not just variables\n # used to compute the KLE.\n from pyapprox.optimization import check_gradients\n from pyapprox.models.wrappers import SingleFidelityWrapper\n from functools import partial\n\n init_condition, boundary_conditions, function_space, beta, \\\n forcing, kappa = bmodel.initialize_random_expressions(\n random_samples[:, 0])\n\n def fun(np_kappa):\n dt = 0.1\n fn_kappa = dla.Function(function_space)\n fn_kappa.vector()[:] = np_kappa[:, 0]\n bmodel.kappa = fn_kappa\n sol = run_model(\n function_space, fn_kappa, forcing,\n init_condition, dt, bmodel.final_time,\n boundary_conditions, velocity=beta,\n second_order_timestepping=bmodel.second_order_timestepping,\n intermediate_times=bmodel.options.get(\n 'intermediate_times', None))\n vals = np.atleast_1d(bmodel.qoi_functional(sol))\n if vals.ndim == 1:\n vals = vals[:, np.newaxis]\n grad = bmodel.qoi_functional_grad(\n sol, bmodel)\n return vals, grad\n\n kappa = bmodel.get_diffusivity(random_samples[:, 0])\n x0 = dla.project(\n kappa, function_space).vector()[:].copy()[:, None]\n check_gradients(fun, True, x0)\n\n # Test that gradient with respect to kle coefficients is correct\n\n from pyapprox.karhunen_loeve_expansion import \\\n compute_kle_gradient_from_mesh_gradient\n vals, jac = bmodel(samples, jac=True)\n\n # Extract mean field and KLE basis from expression\n # TODO add ability to compute gradient of kle to\n # nobile_diffusivity_fenics_class\n kle = bmodel.get_diffusivity(np.zeros(random_samples.shape[0]))\n mean_field_fn = dla.Function(function_space)\n mean_field_fn = dla.interpolate(kle, function_space)\n mean_field = mean_field_fn.vector()[:].copy()-np.exp(1)\n\n mesh_coords = function_space.tabulate_dof_coordinates()[:, 0]\n I = np.argsort(mesh_coords)\n basis_matrix = np.empty((mean_field.shape[0], random_samples.shape[0]))\n exact_basis_matrix = np.array([\n mesh_coords*0+1,\n np.sin((2)/2*np.pi*mesh_coords/bmodel.options['corr_len'])]).T\n for ii in range(random_samples.shape[0]):\n zz = np.zeros(random_samples.shape[0])\n zz[ii] = 1.0\n kle = bmodel.get_diffusivity(zz)\n field_fn = dla.Function(function_space)\n field_fn = dla.interpolate(kle, function_space)\n # 1e-15 used to avoid taking log of zero\n basis_matrix[:, ii] = np.log(\n field_fn.vector()[:].copy()-mean_field+1e-15)-1\n\n assert np.allclose(\n mean_field + np.exp(1+basis_matrix.dot(random_samples[:, 0])),\n x0[:, 0])\n\n # nobile diffusivity uses different definitions of KLE\n # k = np.exp(1+basis_matrix.dot(coef))+mean_field\n # than that assumed in compute_kle_gradient_from_mesh_gradient\n # k = np.exp(basis_matrix.dot(coef)+mean_field)\n # So to\n # keep current interface set mean field to zero and then correct\n # returned gradient\n grad = compute_kle_gradient_from_mesh_gradient(\n jac, basis_matrix, mean_field*0, True, random_samples[:, 0])\n grad *= np.exp(1)\n\n from pyapprox.optimization import approx_jacobian\n fun = SingleFidelityWrapper(bmodel, config_samples[:, 0])\n fd_grad = approx_jacobian(fun, random_samples)\n\n # print(grad, fd_grad)\n assert np.allclose(grad, fd_grad)\n\n def test_advection_diffusion_source_inversion_model(self):\n \"\"\"\n Just check the benchmark runs\n \"\"\"\n benchmark = setup_advection_diffusion_source_inversion_benchmark(\n measurement_times=np.array([0.05, 0.15]), source_strength=0.5, source_width=0.1)\n model = benchmark.fun\n #random_samples = np.zeros((nvars,1))\n random_samples = np.array([[0.25, 0.75]]).T\n config_samples = 3*np.ones((3, 1))\n samples = np.vstack([random_samples, config_samples])\n sol = model.base_model.solve(samples)\n\n # plt.figure(figsize=(2*8,6))\n # ax=plt.subplot(121)\n # p0=dl.plot(sol[0])\n # plt.colorbar(p0,ax=ax)\n # ax=plt.subplot(122)\n # p1=dl.plot(sol[1])\n # plt.colorbar(p1,ax=ax)\n # plt.show()\n\n qoi = model.base_model(samples)\n print(qoi)\n assert np.all(np.isfinite(qoi))\n\n# TODO implement a test that has time varying dirichlet conditions and another with time varing alpha in robin conditions. Then write code to preassemble a when these two things are not time varying.\n\n\nif __name__ == \"__main__\":\n transient_diffusion_test_suite =\\\n unittest.TestLoader().loadTestsFromTestCase(TestTransientDiffusion)\n unittest.TextTestRunner(verbosity=2).run(transient_diffusion_test_suite)\n steady_state_diffusion_test_suite =\\\n unittest.TestLoader().loadTestsFromTestCase(TestSteadyStateDiffusion)\n unittest.TextTestRunner(verbosity=2).run(steady_state_diffusion_test_suite)\n transient_advection_diffusion_equation_test_suite =\\\n unittest.TestLoader().loadTestsFromTestCase(\n TestTransientAdvectionDiffusionEquation)\n unittest.TextTestRunner(verbosity=2).run(\n transient_advection_diffusion_equation_test_suite)\n","sub_path":"pyapprox_dev/pyapprox_dev/fenics_models/tests/test_advection_diffusion.py","file_name":"test_advection_diffusion.py","file_ext":"py","file_size_in_byte":28819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"72624597","text":"from argparse import ArgumentParser\nfrom logic.files import getAllFiles\nfrom logic.files import writeAllFiles\n\n\n#args\nparser = ArgumentParser()\nparser.add_argument(\"-p\", \"--path\", help = \"Specify the path to be analyzed.\", required = True)\nparser.add_argument(\"-o\", \"--output\", help = \"Specify the output file name.\", default = \"files_inventory.csv\")\n\nargs = parser.parse_args()\n\n#Get all files\nfiles = getAllFiles(args.path)\n\n#check csv extension\nif(not args.output.endswith('.csv')):\n\targs.output = args.output + '.csv'\n\n#write files\nwriteAllFiles(args.output, files)","sub_path":"folderInventoryCLI.py","file_name":"folderInventoryCLI.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"314817434","text":"\"\"\"\nThis module will do all the process of filling the database and calling the\nOpen food facts API.\nThis module is callable with the command 'manage.py databse'\n\"\"\"\n\nfrom django.core.management.base import BaseCommand\nfrom django.db.utils import DataError, IntegrityError\nfrom app.models import Product, Category\nfrom progress.bar import FillingSquaresBar\nfrom app.config import config as c\nimport requests\n\n\nclass Command(BaseCommand):\n\n def launch_process(self):\n \"\"\"Launch the all process\"\"\"\n\n print(\"regen database process launched...\")\n self.clear_db()\n\n def clear_db(self):\n \"\"\"Delete all datas in DB\"\"\"\n\n print(\"dropping actual database...\")\n product_obj = Product.objects.all()\n product_obj.delete()\n\n cat_obj = Category.objects.all()\n cat_obj.delete()\n print(\"database cleared !\")\n\n self.request_off_api()\n\n def request_off_api(self):\n \"\"\"Download all products from OFF API and insert them in a list\"\"\"\n\n categories = c.CATEGORIES\n payload = c.PAYLOAD\n url = c.URL\n products = []\n\n with FillingSquaresBar(\n \"Downloading products from OFF...\",\n max=len(categories), suffix=\"%(percent)d%%\") as bar:\n\n for category in categories:\n payload[\"tag_0\"] = category\n\n try:\n data = requests.get(url, params=payload)\n results = data.json()\n products.append(results['products'])\n bar.next()\n\n except ValueError as err:\n print(\"Error: {}\".format(err))\n\n bar.finish()\n print(\"downloading completed !\")\n\n self.delete_uncomplete_products(products)\n\n def delete_uncomplete_products(self, products):\n \"\"\"Delete all product who are missing an usfull element\"\"\"\n\n complete_products = []\n with FillingSquaresBar(\n \"Removing corrupted products...\",\n max=len(products), suffix=\"%(percent)d%%\") as bar:\n\n for list in products:\n for p in list:\n if (\n p.get(\"product_name_fr\")\n and p.get(\"brands\")\n and p.get(\"nutriscore_grade\")\n and p.get(\"url\")\n and p.get('image_front_url')\n and p.get(\"nutriscore_grade\") is not None\n ):\n complete_products.append(p)\n\n bar.next()\n bar.finish()\n self.get_categories(complete_products)\n\n def get_categories(self, products):\n \"\"\"\n Will extract each diffrents categories from the products and\n insert them in a list\n \"\"\"\n\n categories = []\n with FillingSquaresBar(\n \"Insering products in database...\",\n max=len(products), suffix=\"%(percent)d%%\") as bar:\n\n for product in products:\n prod_cats = []\n min_cats = product[\"categories\"].lower().split(\n \", \" and \",\")\n for min_cat in min_cats:\n category = min_cat.strip()\n if category.startswith(\"en\") or category.startswith(\"fr\"):\n pass\n else:\n prod_cats.append(category)\n if category not in categories:\n categories.append(category)\n product[\"categories\"] = prod_cats\n\n self.insert_categories(prod_cats, product)\n\n bar.next()\n bar.finish()\n\n print(\"Process achieved with succsess !\")\n\n def insert_categories(self, categories, product):\n \"\"\"Will insert all the categories in DB\"\"\"\n\n for category in categories:\n cat = Category.objects.get_or_create(\n name=category)\n\n self.insert_product_in_db(product, cat[0])\n\n def insert_product_in_db(self, product, cat):\n \"\"\"Will insert all the product in DB\"\"\"\n\n try:\n product_name_fr = product['product_name_fr']\n brands = product['brands']\n nutriscore_grade = product['nutriscore_grade']\n stores = product['stores']\n url = product['url']\n image = product['image_front_url']\n\n try:\n\n prod = Product.objects.get_or_create(\n product_name_fr=product_name_fr,\n brands=brands,\n nutriscore_grade=nutriscore_grade,\n stores=stores,\n url=url,\n image=image,\n )[0]\n\n prod.categories.add(cat)\n\n except KeyError:\n pass\n\n except DataError:\n pass\n\n except IntegrityError:\n pass\n\n except KeyError:\n pass\n\n def handle(self, *args, **options):\n \"\"\"Alow to use the Django command 'manage.py database'\"\"\"\n\n self.launch_process()\n","sub_path":"app/management/commands/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":5122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"409946005","text":"# 예시 사례를 dp테이블로 N=6정도 까지 확인해보면 피보나치 규칙임을 알 수 있다.\r\n\r\nN=int(input())\r\ndef sol(N):\r\n if N==1 or N==2:\r\n return N\r\n L=[0]*(N+1)\r\n \r\n L[1]=1\r\n L[2]=2\r\n \r\n\r\n for i in range(3,N+1):\r\n L[i]=(L[i-1]+L[i-2])%15746\r\n return L[N]\r\n \r\nprint(sol(N))","sub_path":"01타일.py","file_name":"01타일.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"261157827","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, exceptions, SUPERUSER_ID\nfrom odoo.tools.translate import _\nimport base64\nimport csv\nimport cStringIO\nfrom odoo.exceptions import Warning\nimport tempfile\nimport binascii\nimport xlrd\n\nclass ImportBOM(models.TransientModel):\n _name = 'import.bom'\n\n file = fields.Binary('File ', required=True)\n import_option = fields.Selection([('csv', 'CSV File'), ('xls', 'XLS File')], string='Select', default='csv')\n\n @api.multi\n def import_bom(self, field):\n product_obj = self.env['product.product']\n product_tmpl_obj = self.env['product.template']\n bom_obj = self.env['mrp.bom']\n mrp_bom_line = self.env['mrp.bom.line']\n uom_obj = self.env['product.uom']\n routing_obj = self.env['mrp.routing']\n bom = self.env['mrp.bom']\n\n product_id = product_tmpl_obj.search([('default_code', '=', field[1])], limit=1)\n if not product_id:\n product_id = product_tmpl_obj.create({'name': field[0],'default_code': field[1]})\n\n bom_id = bom_obj.search([('product_tmpl_id', '=', product_id.id),('code','=',field[9].strip())],limit=1)\n routing_id = routing_obj.search([('name', '=', field[8])], limit=1)\n\n product_uom = uom_obj.search([('name', '=', field[3].strip())])\n material_uom = uom_obj.search([('name', '=', field[7].strip())])\n if not product_uom:\n raise Warning(_('This \"%s\" uom is not in system, Please create it.') % field[3].strip())\n\n material_id = product_obj.search([('default_code', '=', field[4])], limit=1)\n flag = False\n if not material_id:\n material_id = product_obj.create({'name': field[5],'default_code': field[4]})\n\n latest_bom = bom_obj.search([('code','=',field[9].strip())],limit=1)\n # if latest_bom:\n # bom_id = latest_bom\n\n if bom_id and bom_id.code == field[9].strip():\n if field[10] == 'True':\n is_premix = True\n else:\n is_premix = False\n\n bom_id.update({\n 'code': field[9].strip(),\n 'product_qty': float(field[2].strip()),\n 'is_premix': is_premix,\n })\n for bom_line in bom_id.bom_line_ids:\n if bom_line.product_id != material_id:\n flag = True\n if bom_line.product_id == material_id:\n bom_line.product_qty = float(field[6].strip())\n return\n if flag:\n mrp_bom_line.create({\n 'bom_id': bom_id.id,\n 'product_id': material_id.id,\n 'product_qty': float(field[6].strip()),\n 'product_uom_id': material_uom.id,\n })\n\n else:\n if field[10] == 'True':\n is_premix = True\n else:\n is_premix = False\n\n variant_id = self.env['product.product'].search([('product_tmpl_id', '=', product_id.id)], limit=1)\n vals = {\n 'product_tmpl_id': product_id.id,\n 'product_id': variant_id.id,\n 'product_qty': float(field[2].strip()),\n 'routing_id': routing_id.id,\n 'product_uom_id': product_uom.id,\n 'is_premix': is_premix,\n 'code': field[9].strip(),\n }\n if field[5] != '':\n vals.update({'bom_line_ids': [(0, 0, {\n 'product_id': material_id.id or False,\n 'product_qty': float(field[6].strip()) or 0.0,\n 'product_uom_id': material_uom.id or False,\n })]})\n bom_obj.create(vals)\n\n \n\n @api.multi\n def import_bom_data(self):\n if self.import_option == 'xls':\n fp = tempfile.NamedTemporaryFile(suffix=\".xlsx\")\n fp.write(binascii.a2b_base64(self.file))\n fp.seek(0)\n try:\n workbook = xlrd.open_workbook(fp.name)\n except Exception:\n raise exceptions.Warning(_(\"Not a valid file!\"))\n\n sheet = workbook.sheet_by_index(0)\n for row_no in range(sheet.nrows):\n if row_no <= 0:\n fields = map(lambda row: row.value.encode('utf-8'), sheet.row(row_no))\n else:\n line = (map(lambda row: isinstance(row.value, unicode) and row.value.encode('utf-8') or str(row.value), sheet.row(row_no)))\n self.import_bom(line)\n\n if self.import_option == 'csv':\n data = base64.b64decode(self.file)\n file_input = cStringIO.StringIO(data)\n file_input.seek(0)\n reader = csv.reader(file_input, delimiter=',',\n lineterminator='\\r\\n')\n reader_info = []\n try:\n reader_info.extend(reader)\n except Exception:\n raise exceptions.Warning(_(\"Not a valid file!\"))\n\n for i in range(1, len(reader_info)):\n try:\n field = map(str, reader_info[i])\n except ValueError:\n raise exceptions.Warning(_(\"Dont Use Charecter only use numbers\"))\n\n self.import_bom(field)\n","sub_path":"import_bom_and_stock/wizard/import_bom.py","file_name":"import_bom.py","file_ext":"py","file_size_in_byte":5429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"296125754","text":"import cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimg = cv2.imread('road.jpg')\n## convert to rgb\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\nheight = img.shape[0]\nwidth = img.shape[1]\n\nregion_of_interest_vertices = [\n (0, height),\n (width/2, height/2),\n (width, height)\n]\n\n\ndef region_of_interest(img, vertices):\n mask = np.zeros_like(img)\n channel_count = img.shape[2]\n match_mask_color = (255,) * channel_count\n cv2.fillPoly(mask, vertices, match_mask_color)\n masked_image = cv2.bitwise_and(img, mask)\n return masked_image\n\ncropped_image = region_of_interest(img,\n np.array([region_of_interest_vertices], np.int32),)\n\nplt.imshow(cropped_image)\nplt.show()\n","sub_path":"lane-detection/detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"496761054","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/11/5/20:47\n# @Author : Hester Xu\n# Email : xuruizhu@yeah.net\n# @File : Lesson5_homework_20181105.py\n# @Software : PyCharm\n'''\n1. 寻找10到12岁的小女孩加入球队(包含10,12),询问用户的性别(男:m),(女:f)和年龄,\n然后显示一条消息指出这个人是否可以加入球队,询问10��后,输出满足条件的总人数。\n'''\ncount = 0\nfor i in range(3):\n gender = input(\"请输入用户的性别(男:m,女:f):\")\n age = eval(input(\"请输入用户的年龄:\"))\n if gender in 'f':\n if 10 <= age <= 12:\n print(\"这个用户可以加入球队\")\n count+=1\n else:\n print(\"这个用户不可以加入球队\")\n else:\n print(\"这个用户不可以加入球队\")\nprint(\"满足条件的总人数是{}人\".format(count))\n\n# 2. 利用for循环,完成a=[1,7,4,89,34,2]的冒泡排序: 冒泡排序:小的排前面,大的排后面。\na=[1,7,4,89,34,666,99,8,2,2]\nfor i in range(1, len(a)):\n for j in range(len(a)-i):\n if a[j] > a[j + 1]:\n a[j], a[j + 1] = a[j + 1], a[j]\nprint(a)\n\n'''\n3. 有一组用户的登录信息存储在字典 login_info 里面,\n字典格式如下:login_info={\"admin\":\"root\",\"user_1\":\"123456\"}\nkey表示用户名,value表示密码,请编写函数满足如下条件:\n1)设计1个登陆的程序, 不同的用户名和对成密码存在个字典里面, 输入正确的用户名和密码去登陆,\n2)首先输入用户名,如果用户名不存在或者为空,则一直提示输入正确的用户名\n3)当用户名正确的时候,提示去输入密码,如果密码跟用户名不对应,则提示密码错误请重新输入。\n4)如果密码输入错误超过三次,中断程序运行。\n5)当输入密码错误时,提示还有几次机会\n6)用户名和密码都输入正确的时候,提示登陆成功!\n'''\nlogin_info={\"admin\":\"root\",\"user_1\":\"123456\"}\nusername = input(\"请输入用户名:\")\nwhile username not in login_info.keys() or False:\n username = input(\"请输入正确的用户名:\")\n\npwd = input(\"请输入密码:\")\ndef fac(pwd):\n i = 3\n while i <= 3:\n if pwd in login_info[username]:\n print(\"登录成功\")\n break\n elif i == 0:\n break\n print(\"密码错误,还有{}次机会\".format(i))\n pwd = input(\"请重新输入密码:\")\n i -= 1\nif pwd in login_info[username]:\n print(\"登录成功\")\nelse:\n fac(pwd)\n","sub_path":"Lemon/Python_Base/Lesson5_20181105/Lesson5_homework_20181105.py","file_name":"Lesson5_homework_20181105.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"489649220","text":"\"\"\"\r\nProgrammer: Chris Blanks\r\nLast Edited: 11/3/2018\r\nProject: Automated Self-Serving System\r\nPurpose: This script defines the MainApp class that runs everything.\r\n\"\"\"\r\n\r\n#Standard library imports\r\nimport tkinter as tk\r\nimport os\r\nimport datetime\r\n\r\n#My scripts\r\nfrom CustomerWindow import CustomerWindow\r\nfrom EmployeeWindow import EmployeeWindow\r\nimport DrinkProfile as dp_class\r\nfrom LoginWindow import LoginWindow\r\nfrom KeyboardWindow import KeyboardWindow\r\n\r\n\r\ndef runMainApplication():\r\n \"\"\"Basic run of application.\"\"\"\r\n root = tk.Tk()\r\n main_app = MainApp(master= root)\r\n root.mainloop()\r\n\r\n\r\nclass MainApp:\r\n\r\n #class member variables\r\n isEmployeeMode= False\r\n isValidLogin = False\r\n drink_profile_directory = \"/Users/Cabla/Documents/PYTHON_MODULES/SENIOR_DESIGN_CODE/drink_profiles\"\r\n config_file_path = \"/Users/Cabla/Documents/PYTHON_MODULES/SENIOR_DESIGN_CODE/system_info/config.txt\"\r\n drink_names = []\r\n \r\n def __init__(self,master):\r\n self.master = master\r\n self.writeToLog(\"Running main application\")\r\n self.drink_objects = self.getDrinks()\r\n self.createMainWindow()\r\n self.selectWindow()\r\n \r\n self.retrieveConfigurationInformation()\r\n self.cleanOldDrinksFromConfig()\r\n\r\n\r\n def selectWindow(self):\r\n \"\"\"Determines what window is open.\"\"\"\r\n #input mode until GPIO pin is setup to trigger employee mode\r\n selection = int(input(\"Press 1 to enter employee mode.\"))\r\n\r\n if selection == 1:\r\n self.isEmployeeMode = True\r\n #self.launchKeyboardWindow()\r\n self.launchLoginWindow() \r\n else:\r\n self.isEmployeeMode = False\r\n self.master.withdraw()\r\n self.createCustomerWindow()\r\n\r\n\r\n def createMainWindow(self):\r\n \"\"\"Displays main window elements. \"\"\"\r\n self.master.geometry(\"200x200\")\r\n self.main_title = tk.Label(self.master,text=\"Root Window\")\r\n self.main_title.grid()\r\n\r\n self.customer_window_btn = tk.Button(self.master,text=\"customer window\"\r\n ,command= lambda window=\"customer\": self.relaunchWindow(window))\r\n self.customer_window_btn.grid()\r\n self.employee_window_btn = tk.Button(self.master,text=\"employee window\"\r\n ,command= lambda window=\"employee\": self.relaunchWindow(window))\r\n self.employee_window_btn.grid()\r\n\r\n \r\n def relaunchWindow(self,window):\r\n \"\"\" Relaunches the selected window.\"\"\"\r\n if window == \"customer\":\r\n self.isEmployeeMode = False\r\n self.master.withdraw()\r\n self.createCustomerWindow()\r\n elif window == \"employee\":\r\n self.isEmployeeMode = True\r\n self.master.withdraw()\r\n #self.launchKeyboardWindow()\r\n self.launchLoginWindow()\r\n else:\r\n print(\"What the heck?\")\r\n\r\n \r\n def createCustomerWindow(self):\r\n \"\"\"Creates separate customer window.\"\"\"\r\n self.customer_top_lvl = tk.Toplevel(self.master)\r\n self.customer_window = CustomerWindow(self)\r\n\r\n \r\n def createEmployeeWindow(self,isAdminMode):\r\n \"\"\"Creates separate employee window \"\"\"\r\n self.employee_top_lvl = tk.Toplevel(self.master)\r\n self.employee_window = EmployeeWindow(self,isAdminMode)\r\n\r\n \r\n def launchLoginWindow(self):\r\n \"\"\"Launches login window when employee mode is selected.\"\"\"\r\n self.login_top_lvl = tk.Toplevel(self.master)\r\n self.login_window = LoginWindow(self)\r\n\r\n \r\n def launchKeyboardWindow(self):\r\n \"\"\"Launches a top level window that contains a keyboard that can deliver\r\n input to processes that need it.\"\"\"\r\n self.keyboard_top_lvl = tk.Toplevel(self.master)\r\n self.keyboard_window = KeyboardWindow(self)\r\n\r\n \r\n def getDrinks(self):\r\n \"\"\"Retrieves a list of active Drink objects.\"\"\"\r\n temp = []\r\n os.chdir(self.drink_profile_directory)\r\n drink_profile_names = os.listdir(os.getcwd())\r\n for name in drink_profile_names:\r\n path_builder = self.drink_profile_directory +\"/\"+ name\r\n os.chdir(path_builder)\r\n drink = dp_class.DrinkProfile(path_builder +\"/\"+ os.listdir(os.getcwd())[1])\r\n if drink.isActive == \"1\":\r\n drink.name = (drink.name).replace(\" \",\"_\")\r\n drink.addDrinkToConfig()\r\n temp.append(drink)\r\n #go back to SENIOR_DESIGN_CODE directory\r\n os.chdir(\"..\")\r\n os.chdir(\"..\")\r\n return temp\r\n\r\n\r\n def retrieveConfigurationInformation(self):\r\n \"\"\"Retrieves configuration info (e.g. drink names) from config file \"\"\"\r\n f = open(self.config_file_path,'r+')\r\n lines = f.read().splitlines()\r\n #print(\"'{}' contents:\\n\".format((f.name).split(\"/\")[-1]),'\\n'.join(lines))\r\n\r\n line_number = 1\r\n for line in lines:\r\n if line_number == 1:\r\n if line.split()[1] == '0':\r\n print(\"Config file is not locked.\\n\\n\")\r\n else:\r\n self.isLocked = True\r\n print(\"Config file is locked.\\n\\n\")\r\n if line_number == 2:\r\n drinks = line.split(\" \")\r\n for i in range(len(drinks)-1):\r\n self.drink_names.append(drinks[i+1])\r\n line_number+=1 \r\n f.close()\r\n\r\n\r\n def updateConfigurationFile(self,item_to_update,updated_value= None):\r\n \"\"\" \"\"\"\r\n f = open(self.config_file_path,\"r+\")\r\n lines = f.read().splitlines()\r\n f.seek(0)\r\n\r\n line_headers = [\"locked \",\"active_drink_list \",\"system_status \"]\r\n line_to_edit = 0\r\n \r\n if item_to_update == \"data_lock\":\r\n line_to_edit = 1\r\n if item_to_update == \"drink_list\":\r\n line_to_edit = 2\r\n if item_to_update == \"system_status\":\r\n line_to_edit = 3\r\n\r\n line_number = 1\r\n for line in lines:\r\n if line_number == line_to_edit and updated_value != None:\r\n line = line_headers[line_to_edit - 1] + updated_value\r\n f.write(line+\"\\n\")\r\n else:\r\n f.write(line+\"\\n\")\r\n if line_number == 3:\r\n break\r\n line_number+=1\r\n\r\n f.close()\r\n\r\n\r\n def cleanOldDrinksFromConfig(self):\r\n \"\"\"Updates the active drinks in the config file.\"\"\"\r\n cleaned_list_of_names = \"\"\r\n loaded_drink_object_names = []\r\n for drink in self.drink_objects:\r\n loaded_drink_object_names.append((drink.name).replace(\"_\",\" \"))\r\n for config_name in self.drink_names:\r\n if config_name.replace(\"_\",\" \") in loaded_drink_object_names:\r\n cleaned_list_of_names = cleaned_list_of_names + config_name + \" \"\r\n self.updateConfigurationFile(\"drink_list\",cleaned_list_of_names)\r\n self.writeToLog(\"Cleaned Config file.\")\r\n \r\n \r\n def writeToLog(self, message):\r\n \"\"\"Writes messages into the log.txt file.\"\"\"\r\n self.todays_log = \"system_info/log_files/log_on_\"+str(datetime.date.today())+\".txt\"\r\n log = open(self.todays_log,\"a\")\r\n full_msg = str(datetime.datetime.now()) +\" : \" + message\r\n log.write(full_msg + \"\\n\")\r\n log.close()\r\n\r\n \r\n def addUserToLogin(self,user_type,username,password):\r\n \"\"\"Creates a new user in the user_login file. Ex: self.addUserToLogin(\"R\",\"Lei\",\"Zhang\")\"\"\"\r\n file = open(\"system_info/user_login.txt\",\"r+\")\r\n lines = file.read().splitlines()\r\n file.seek(0)\r\n print(lines)\r\n line_num = 1\r\n if user_type == \"A\":\r\n for line in lines:\r\n if \"ADMIN USER\" in line:\r\n line = line +\"\\n\"+ username +\" \"+ password\r\n if \"END\" in line:\r\n file.write(line)\r\n print(\"END:\" + line)\r\n break\r\n file.write(line+\"\\n\")\r\n print(\"Add lines: \"+line)\r\n else:\r\n for line in lines:\r\n if \"REGULAR USER\" in line:\r\n line = line +\"\\n\"+ username +\" \"+ password\r\n if \"END\" in line:\r\n file.write(line)\r\n print(line)\r\n break\r\n file.write(line+\"\\n\")\r\n print(line)\r\n file.seek(0)\r\n print(file.readlines())\r\n file.flush()\r\n file.close()\r\n\r\n msg = \"Added \"+username+ \"account to login.\"\r\n self.writeToLog(msg) \r\n\r\n def deleteUserFromLogin(self, username, password):\r\n \"\"\"Deletes a user in the user_login file (besides the original admin account).\"\"\"\r\n file = open(\"system_info/user_login.txt\",\"r+\")\r\n lines = file.read().splitlines()\r\n file.seek(0)\r\n print(lines)\r\n login_combo = username +\" \" + password\r\n for line in lines:\r\n if \"END\" in line:\r\n file.write(\"END\")\r\n break\r\n if not login_combo in line:\r\n file.write(line+\"\\n\")\r\n print(\"delete lines: \"+line)\r\n else:\r\n pass\r\n file.truncate()\r\n file.flush()\r\n file.close()\r\n\r\n msg = \"Removed \"+username+ \"account from login.\"\r\n self.writeToLog(msg) \r\n\r\n \r\nif __name__ == \"__main__\":\r\n runMainApplication()\r\n","sub_path":"Senior_Design_Code_Copy/MainApp.py","file_name":"MainApp.py","file_ext":"py","file_size_in_byte":9588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"245118149","text":"import unittest\nimport tempfile\nimport os\n#from worldengine.step import Step\nfrom worldengine.world import World\nfrom worldengine.hdf5_serialization import save_world_to_hdf5, load_world_to_hdf5\n\ntry: # are we python3?\n set\nexcept NameError: # apparently not.\n from sets import Set as set\n\n\nclass TestSerialization(unittest.TestCase):\n\n def setUp(self):\n self.maxDiff = None\n\n def test_protobuf_serialize_unserialize(self):\n w = World(\"Dummy\", 16, 16, seed=1)\n serialized = w.protobuf_serialize()\n unserialized = World.protobuf_unserialize(serialized)\n self.assertEqual(set(w.layers.keys()), set(unserialized.layers.keys()))\n for l in w.layers.keys():\n self.assertEqual(w.layers[l].all(), unserialized.layers[l].all())\n self.assertEqual(w.ocean_level, unserialized.ocean_level)\n self.assertEqual(w.seed, unserialized.seed)\n self.assertEqual(w.number_of_plates, unserialized.number_of_plates)\n self.assertEqual(sorted(dir(w)), sorted(dir(unserialized)))\n self.assertEqual(w, unserialized)\n\n def test_hdf5_serialize_unserialize(self):\n filename = None\n try:\n w = World(\"Dummy\", 16, 16,1)\n f = tempfile.NamedTemporaryFile(delete=False)\n f.close()\n filename = f.name\n serialized = save_world_to_hdf5(w, filename)\n unserialized = load_world_to_hdf5(filename)\n self.assertEqual(set(w.layers.keys()), set(unserialized.layers.keys()))\n self.assertEqual(w.layers['humidity'].quantiles, unserialized.layers['humidity'].quantiles)\n for l in w.layers.keys():\n self.assertEqual(w.layers[l].all(), unserialized.layers[l].all())\n self.assertEqual(w.ocean_level, unserialized.ocean_level)\n self.assertEqual(w.seed, unserialized.seed)\n self.assertEqual(w.number_of_plates, unserialized.number_of_plates)\n self.assertEqual(sorted(dir(w)), sorted(dir(unserialized)))\n finally:\n if filename:\n os.remove(filename)\n\n \nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/serialization_test.py","file_name":"serialization_test.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"488255672","text":"# Copyright 2013 GRNET S.A. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or\n# without modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain the above\n# copyright notice, this list of conditions and the following\n# disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials\n# provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS\n# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# The views and conclusions contained in the software and\n# documentation are those of the authors and should not be\n# interpreted as representing official policies, either expressed\n# or implied, of GRNET S.A.\n\n\"\"\"\nThis is the burnin class that tests the Servers' functionality\n\n\"\"\"\n\nimport sys\nimport stat\nimport base64\nimport random\nimport socket\n\nfrom vncauthproxy.d3des import generate_response as d3des_generate_response\n\nfrom synnefo_tools.burnin.common import BurninTests, Proper\nfrom synnefo_tools.burnin.cyclades_common import CycladesTests\n\n\n# Too many public methods. pylint: disable-msg=R0904\n# Too many instance attributes. pylint: disable-msg=R0902\n# This class gets replicated into actual TestCases dynamically\nclass GeneratedServerTestSuite(CycladesTests):\n \"\"\"Test Spawning Serverfunctionality\"\"\"\n use_image = Proper(value=None)\n personality = Proper(value=None)\n avail_flavors = Proper(value=None)\n use_flavor = Proper(value=None)\n server = Proper(value=None)\n ipv4 = Proper(value=None)\n ipv6 = Proper(value=None)\n username = Proper(value=None)\n password = Proper(value=None)\n\n def test_001_submit_create_server(self):\n \"\"\"Submit a create server request\"\"\"\n if self._image_is(self.use_image, \"linux\"):\n # Enforce personality test\n self.info(\"Creating personality content to be used\")\n self.personality = [{\n 'path': \"/root/test_inj_file\",\n 'owner': \"root\",\n 'group': \"root\",\n 'mode': stat.S_IRUSR | stat.S_IWUSR,\n 'contents': base64.b64encode(\"This is a personality file\")\n }]\n self.use_flavor = random.choice(self.avail_flavors)\n\n self.server = self._create_server(\n self.use_image, self.use_flavor,\n personality=self.personality, network=True)\n self.username = self._get_connection_username(self.server)\n self.password = self.server['adminPass']\n\n def test_002_server_build_list(self):\n \"\"\"Test server is in BUILD state, in server list\"\"\"\n servers = self._get_list_of_servers(detail=True)\n servers = [s for s in servers if s['id'] == self.server['id']]\n\n self.assertEqual(len(servers), 1)\n server = servers[0]\n self.assertEqual(server['name'], self.server['name'])\n self.assertEqual(server['flavor']['id'], self.use_flavor['id'])\n self.assertEqual(server['image']['id'], self.use_image['id'])\n self.assertEqual(server['status'], \"BUILD\")\n\n def test_003_server_build_details(self):\n \"\"\"Test server is in BUILD state, in details\"\"\"\n server = self._get_server_details(self.server)\n self.assertEqual(server['name'], self.server['name'])\n self.assertEqual(server['flavor']['id'], self.use_flavor['id'])\n self.assertEqual(server['image']['id'], self.use_image['id'])\n self.assertEqual(server['status'], \"BUILD\")\n\n def test_004_set_server_metadata(self):\n \"\"\"Test setting some of the server's metadata\"\"\"\n image = self.clients.cyclades.get_image_details(self.use_image['id'])\n os_value = image['metadata']['os']\n self.clients.cyclades.update_server_metadata(\n self.server['id'], OS=os_value)\n\n servermeta = \\\n self.clients.cyclades.get_server_metadata(self.server['id'])\n imagemeta = \\\n self.clients.cyclades.get_image_metadata(self.use_image['id'])\n self.assertEqual(servermeta['OS'], imagemeta['os'])\n\n def test_005_server_becomes_active(self):\n \"\"\"Test server becomes ACTIVE\"\"\"\n self._insist_on_server_transition(self.server, [\"BUILD\"], \"ACTIVE\")\n\n def test_006_get_server_oob_console(self):\n \"\"\"Test getting OOB server console over VNC\n\n Implementation of RFB protocol follows\n http://www.realvnc.com/docs/rfbproto.pdf.\n\n \"\"\"\n console = self.clients.cyclades.get_server_console(self.server['id'])\n self.assertEquals(console['type'], \"vnc\")\n sock = self._insist_on_tcp_connection(\n socket.AF_INET, console['host'], console['port'])\n\n # Step 1. ProtocolVersion message (par. 6.1.1)\n version = sock.recv(1024)\n self.assertEquals(version, 'RFB 003.008\\n')\n sock.send(version)\n\n # Step 2. Security (par 6.1.2): Only VNC Authentication supported\n sec = sock.recv(1024)\n self.assertEquals(list(sec), ['\\x01', '\\x02'])\n\n # Step 3. Request VNC Authentication (par 6.1.2)\n sock.send('\\x02')\n\n # Step 4. Receive Challenge (par 6.2.2)\n challenge = sock.recv(1024)\n self.assertEquals(len(challenge), 16)\n\n # Step 5. DES-Encrypt challenge, use password as key (par 6.2.2)\n response = d3des_generate_response(\n (console[\"password\"] + '\\0' * 8)[:8], challenge)\n sock.send(response)\n\n # Step 6. SecurityResult (par 6.1.3)\n result = sock.recv(4)\n self.assertEquals(list(result), ['\\x00', '\\x00', '\\x00', '\\x00'])\n sock.close()\n\n def test_007_server_has_ipv4(self):\n \"\"\"Test active server has a valid IPv4 address\"\"\"\n server = self.clients.cyclades.get_server_details(self.server['id'])\n # Update the server attribute\n self.server = server\n\n self.ipv4 = self._get_ips(server, version=4)\n\n def test_008_server_has_ipv6(self):\n \"\"\"Test active server has a valid IPv6 address\"\"\"\n self._skip_if(not self.use_ipv6, \"--no-ipv6 flag enabled\")\n\n self.ipv6 = self._get_ips(self.server, version=6)\n\n def test_009_server_ping_ipv4(self):\n \"\"\"Test server responds to ping on IPv4 address\"\"\"\n for ipv4 in self.ipv4:\n self._insist_on_ping(ipv4, version=4)\n\n def test_010_server_ping_ipv6(self):\n \"\"\"Test server responds to ping on IPv6 address\"\"\"\n self._skip_if(not self.use_ipv6, \"--no-ipv6 flag enabled\")\n self._insist_on_ping(self.ipv6[0], version=6)\n\n def test_011_attach_second_network(self):\n \"\"\"Attach a second public IP to our server\"\"\"\n floating_ip = self._create_floating_ip()\n self._create_port(floating_ip['floating_network_id'],\n device_id=self.server['id'],\n floating_ip=floating_ip)\n\n # Update server attributes\n server = self.clients.cyclades.get_server_details(self.server['id'])\n self.server = server\n self.ipv4 = self._get_ips(server, version=4)\n self.assertEqual(len(self.ipv4), 2)\n\n # Test new IPv4\n self.test_009_server_ping_ipv4()\n\n def test_012_submit_shutdown(self):\n \"\"\"Test submit request to shutdown server\"\"\"\n self.clients.cyclades.shutdown_server(self.server['id'])\n\n def test_013_server_becomes_stopped(self):\n \"\"\"Test server becomes STOPPED\"\"\"\n self._insist_on_server_transition(self.server, [\"ACTIVE\"], \"STOPPED\")\n\n def test_014_submit_start(self):\n \"\"\"Test submit start server request\"\"\"\n self.clients.cyclades.start_server(self.server['id'])\n\n def test_015_server_becomes_active(self):\n \"\"\"Test server becomes ACTIVE again\"\"\"\n self._insist_on_server_transition(self.server, [\"STOPPED\"], \"ACTIVE\")\n\n def test_016_server_ping_ipv4(self):\n \"\"\"Test server OS is actually up and running again\"\"\"\n self.test_009_server_ping_ipv4()\n\n def test_017_ssh_to_server_ipv4(self):\n \"\"\"Test SSH to server public IPv4 works, verify hostname\"\"\"\n self._skip_if(not self._image_is(self.use_image, \"linux\"),\n \"only valid for Linux servers\")\n hostname1 = self._insist_get_hostname_over_ssh(\n self.ipv4[0], self.username, self.password)\n hostname2 = self._insist_get_hostname_over_ssh(\n self.ipv4[1], self.username, self.password)\n # The hostname must be of the form 'prefix-id'\n self.assertTrue(hostname1.endswith(\"-%d\" % self.server['id']))\n self.assertEqual(hostname1, hostname2)\n\n def test_018_ssh_to_server_ipv6(self):\n \"\"\"Test SSH to server public IPv6 works, verify hostname\"\"\"\n self._skip_if(not self._image_is(self.use_image, \"linux\"),\n \"only valid for Linux servers\")\n self._skip_if(not self.use_ipv6, \"--no-ipv6 flag enabled\")\n hostname = self._insist_get_hostname_over_ssh(\n self.ipv6[0], self.username, self.password)\n # The hostname must be of the form 'prefix-id'\n self.assertTrue(hostname.endswith(\"-%d\" % self.server['id']))\n\n def test_019_rdp_to_server_ipv4(self):\n \"\"\"Test RDP connection to server public IPv4 works\"\"\"\n self._skip_if(not self._image_is(self.use_image, \"windows\"),\n \"only valid for Windows servers\")\n sock = self._insist_on_tcp_connection(\n socket.AF_INET, self.ipv4[0], 3389)\n # No actual RDP processing done. We assume the RDP server is there\n # if the connection to the RDP port is successful.\n # pylint: disable-msg=W0511\n # FIXME: Use rdesktop, analyze exit code? see manpage\n sock.close()\n\n def test_020_rdp_to_server_ipv6(self):\n \"\"\"Test RDP connection to server public IPv6 works\"\"\"\n self._skip_if(not self._image_is(self.use_image, \"windows\"),\n \"only valid for Windows servers\")\n self._skip_if(not self.use_ipv6, \"--no-ipv6 flag enabled\")\n sock = self._insist_on_tcp_connection(\n socket.AF_INET, self.ipv6[0], 3389)\n # No actual RDP processing done. We assume the RDP server is there\n # if the connection to the RDP port is successful.\n # pylint: disable-msg=W0511\n # FIXME: Use rdesktop, analyze exit code? see manpage\n sock.close()\n\n def test_021_personality(self):\n \"\"\"Test file injection for personality enforcement\"\"\"\n self._skip_if(not self._image_is(self.use_image, \"linux\"),\n \"only implemented for linux servers\")\n assert self.personality is not None, \"No personality used\"\n\n for inj_file in self.personality:\n self._check_file_through_ssh(\n self.ipv4[0], inj_file['owner'], self.password,\n inj_file['path'], inj_file['contents'])\n\n def test_022_destroy_floating_ips(self):\n \"\"\"Destroy the floating IPs\"\"\"\n self._disconnect_from_network(self.server)\n\n def test_023_submit_delete_request(self):\n \"\"\"Test submit request to delete server\"\"\"\n self._delete_servers([self.server])\n\n\n# --------------------------------------------------------------------\n# The actuall test class. We use this class to dynamically create\n# tests from the GeneratedServerTestSuite class. Each of these classes\n# will run the same tests using different images and or flavors.\n# The creation and running of our GeneratedServerTestSuite class will\n# happen as a testsuite itself (everything here is a test!).\nclass ServerTestSuite(BurninTests):\n \"\"\"Generate and run the GeneratedServerTestSuite\n\n We will generate as many testsuites as the number of images given.\n Each of these testsuites will use the given flavors at will (random).\n\n \"\"\"\n avail_images = Proper(value=None)\n avail_flavors = Proper(value=None)\n gen_classes = Proper(value=None)\n\n def test_001_images_to_use(self):\n \"\"\"Find images to be used by GeneratedServerTestSuite\"\"\"\n if self.images is None:\n self.info(\"No --images given. Will use the default %s\",\n \"^Debian Base$\")\n filters = [\"name:^Debian Base$\"]\n else:\n filters = self.images\n\n self.avail_images = self._find_images(filters)\n self.info(\"Found %s images. Let's create an equal number of tests\",\n len(self.avail_images))\n\n def test_002_flavors_to_use(self):\n \"\"\"Find flavors to be used by GeneratedServerTestSuite\"\"\"\n flavors = self._get_list_of_flavors(detail=True)\n\n if self.flavors is None:\n self.info(\"No --flavors given. Will use all of them\")\n self.avail_flavors = flavors\n else:\n self.avail_flavors = self._find_flavors(\n self.flavors, flavors=flavors)\n self.info(\"Found %s flavors to choose from\", len(self.avail_flavors))\n\n def test_003_create_testsuites(self):\n \"\"\"Generate the GeneratedServerTestSuite tests\"\"\"\n gen_classes = []\n for img in self.avail_images:\n name = (str(\"GeneratedServerTestSuite_(%s)\" %\n img['name']).replace(\" \", \"_\"))\n self.info(\"Constructing class %s\", name)\n class_dict = {\n 'use_image': Proper(value=img),\n 'avail_flavors': Proper(value=self.avail_flavors)\n }\n cls = type(name, (GeneratedServerTestSuite,), class_dict)\n # Make sure the class can be pickled, by listing it among\n # the attributes of __main__. A PicklingError is raised otherwise.\n thismodule = sys.modules[__name__]\n setattr(thismodule, name, cls)\n # Append the generated class\n gen_classes.append(cls)\n\n self.gen_classes = gen_classes\n\n def test_004_run_testsuites(self):\n \"\"\"Run the generated tests\"\"\"\n self._run_tests(self.gen_classes)\n","sub_path":"snf-tools/synnefo_tools/burnin/server_tests.py","file_name":"server_tests.py","file_ext":"py","file_size_in_byte":14696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"640785909","text":"from django.shortcuts import render, redirect\nfrom .models import Post, Comment\nfrom account.models import Account\n\n# Create your views here.: 어떤 데이터가 어떻게 처리될 지 알려주는 함수! model과 templates를 연결.\ndef home(request):\n post_list = Post.objects.all() \n return render(request, 'home.html', {'post_list':post_list})\n\n #쿼리셋과 메소드의 형식: \"모델.쿼리셋(Object).메소드\"\n #all():포스트로 만든 모든 쿼리셋 객체들을 불러오라는 소리\n #.count: 개수 반환\n # .first(): 첫번째 객체 반환\n # .last(): 마지막 객체 반환\n #쿼리셋:포스트 안에 있는 객체를 담아준다.모델로부터 객체의 목록을 전달받을 수 있음.=.object\n #쿼리셋을 이용해서 받은 데이터를 정렬, 표시하는 방법을 메소드라고 함.\n\ndef detail(request, post_id):\n post = Post.objects.get(id=post_id)\n comments = post.comment_set.all().order_by('-pub_date')\n return render(request,\"detail.html\", {'post':post, 'comments': comments})\n\ndef write(request):\n if request.method==\"POST\":\n title = request.POST['title']\n content = request.POST['content']\n image = request.FILES.get('file', '')\n account = Account.objects.get(user=request.user)\n\n post = Post(account=account, title=title, content=content)\n\n if image:\n post.image = image\n \n post.save()\n return redirect('home')\n else:\n return render(request, 'write.html')\n\ndef delete(request, post_id):\n post = Post.objects.get(id=post_id)\n # 각 글의 고유한 아이디를()에 넣어야함, id=는 변수, post_id=상수값. \n post.delete()\n return redirect('home')\n\n#어려운 부분: 갱신하기\ndef edit(request,post_id):\n if request.method==\"POST\":\n post=Post.objects.get(id=post_id)\n post.title=request.POST['title']\n post.content=request.POST['content']\n post.save()\n return redirect('') \n\n else:\n post=Post.objects.get(id=post_id)\n return render (request, 'edit.html',{\"post\": post})\n\ndef comment_create(request, post_id):\n if request.method==\"POST\":\n post=Post.objects.get(id=post_id)\n comment=Comment(post=post)\n # 파랑포스트는 models에 있는 변수 post, 흰 포스트는 객체의 값 특정된 것(엄마=엄마이름)\n comment.content=request.POST['content']\n comment.save()\n \n return redirect('detail',post_id)\n\n","sub_path":"write/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"223290151","text":"# python tool for returning a formated date string\n\nimport os, sys\n\ndef process(ar):\n ar = ar.strip('\\n')\n ar = ar.strip('\\t')\n ar = ar.strip(' ')\n return ar\n\ndef get_date(formatter = '.'):\n cmd='date +%d' + formatter + '%m' + formatter + '%Y > tmp'\n x = os.system(cmd)\n assert(x == 0)\n f_temp = open('tmp', 'r')\n buffer = f_temp.read()\n f_temp.close()\n buffer = process(buffer)\n print(buffer, end = '', flush = True)\n\nif (__name__ == '__main__'):\n get_date()","sub_path":"macros/curr_date.py","file_name":"curr_date.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"499898749","text":"import pandas as pd\nimport numpy as np\nfrom collections import OrderedDict\n\n# get min/max values for all columns\n\ndef get_min_max(df):\n \"\"\"\n returns dictionary with min and max values for each numeric column,\n :param df: (pandas dataframe): any pandas data frame\n :return: dictionary: dictionary with columns as keys and list of\n [min,max] as values.\n \"\"\"\n\n min_df = df.min() # this drops some columns for some reason\n max_df = df.max()\n min_max_dict = OrderedDict()\n\n for col in min_df.index:\n # return as np.array so can use dtype on it to check for non-numeric\n tmp = np.array([min_df[col],max_df[col]])\n min_max_dict[col] = tmp\n\n return min_max_dict\n\ndef get_cols_string_or_not(df,string=True, include_cols=None ):\n \"\"\"\n :param df: (dataframe) dataframe with columns to extract\n :param string: (boolean) if True return list of columns with strings,\n if False, return list of numeric columns\n :param include_cols: restrict search to this list if included\n :return: (list) list of columns with only numeric or only non-numeric values\n \"\"\"\n if include_cols:\n # get new pd frame with included columns\n df_of_col = df.loc[:, include_cols]\n all_numeric = df_of_col.select_dtypes(include=np.number).columns.values.tolist()\n else:\n include_cols = df.columns.values.tolist()\n all_numeric = df.select_dtypes(include=np.number).columns.values.tolist()\n if string:\n tmp = [col for col in include_cols if col not in all_numeric]\n return tmp\n else:\n return all_numeric\n\ndef get_corr_from_predictions(preds,y,metrics='mse',\n corr = ['spearman','kendall'],\n round = False):\n \"\"\"\n given predictions and labels, returns rank order correlations\n :param preds: (numpy array): predictions from mse or one hot softmax\n :param y: y (numpy array): labels\n :param metrics: (string): metric used in loss function, 'mse' or 'accuracy'\n 'accuracy' assumes one hot encoding, 'mse' assumes regression\n :param corr: (string): list of corr methods to use\n :param round: (boolean) if set round the regression values\n :return: dictionary: = dictionary with keys for methods, values are\n coefficients\n \"\"\"\n corr_values = {}\n if metrics == 'accuracy':\n y_out = np.argmax(y, axis=1)\n x_out = np.argmax(preds, axis=1)\n elif metrics == 'mse':\n y_out = np.reshape(y, (y.shape[0],))\n x_out = np.reshape(preds, (preds.shape[0],))\n if round: # option for rounding output of regression to whole values\n x_out = np.round(x_out)\n else:\n print('get_corr_from_predictions(): option for metrics = ',metrics,\n ' not supported, ' + 'returning zeros')\n for item in corr:\n corr_values[item] = 0.0\n return corr_values\n\n df = pd.DataFrame(data = {'x_out': x_out,'y_out': y_out})\n # df = pd.DataFrame(data=y_out, columns=['y_out'])\n # df['x_out'] = pd.Series(x_out, index=df.index)\n for item in corr:\n corr_values[item] = df.loc[:, ['x_out', 'y_out']].corr(method=item).iloc[0][1]\n return corr_values\n\ndef accuracy_from_round(preds,y):\n \"\"\"\n given predictions and labels from mse regression, return rounded output\n predictions\n :param preds: (numpy array): predictions from mse\n :param y: (numpy array): labels\n :return: accuracy in percent\n \"\"\"\n y_out = np.reshape(y, (y.shape[0],))\n x_out = np.reshape(preds, (preds.shape[0],))\n x_out = np.round(x_out)\n correct = np.sum((x_out-y_out)==0)\n return correct/y_out.shape[0]\n\ndef get_unique_counts(df,column_name):\n \"\"\"\n Returns a series object containing counts of all unique valuess in column_name\n :param df: (pandas dataframe)\n :param column_name: (string) column name to search\n :return: (series object) contains counts of all unique values and appends\n an index 'max' to show the max count of all indices\n \"\"\"\n count_unique = df[column_name].value_counts()\n count_unique['max'] = count_unique.max()\n\n return count_unique\n\n\n","sub_path":"NeuralNetworks/LSTM/pandas_utils.py","file_name":"pandas_utils.py","file_ext":"py","file_size_in_byte":4196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"508671475","text":"#Timer class is an abstration of the python threading library\nimport threading\nfrom time import *\n\nclass Timer:\n\tdef __init__(self, Interval, Function, Args = []):\n\t\tif (Interval == 0):\n\t\t\traise Exception(\"You cannot run a function every 0 seconds, make the interval > 0.\")\n\t\t\n\t\tself.mArgs \t= Args\n\t\tself.mInterval \t= Interval\n\t\tself.mFunction \t= Function\n\t\tself.mThread \t= threading.Timer(Interval, self.Delay)\n\t\tself.mRun \t= False\t\n\n\tdef Delay(self):\n\t\tself.mRun = True\n\n\tdef Fctn(self):\t\t\n\t\tif (self.mCount > 0):\n\t\t\tif (len(self.mArgs)):\n\t\t\t\tself.mFunction(self.mArgs)\n\t\t\telse:\n\t\t\t\tself.mFunction()\n\t\telse:\n\t\t\treturn True\n\t\tself.mCount -= 1\n\t\treturn False\t\n\n\tdef __call__(self, Count = 0):\n\t\tself.mCount = Count\n\t\t#\n\t\tself.mThread = threading.Timer(self.mInterval, self.Delay)\n\t\tself.mThread.start()\n\t\twhile (True):\n\t\t\tself.mRun = False\n\t\t\t\n\t\t\twhile(self.mRun == False):\n\t\t\t\tsleep(0.001)\n\t\t\n\t\t\tself.mThread.cancel()\t\t\n\t\t\tself.mThread = threading.Timer(self.mInterval, self.Delay)\n\t\t\tself.mThread.start()\t\t\t\t\n\t\t\tif(self.Fctn()):\n\t\t\t\treturn\n\t\t\t\n\n\"\"\"\ndef Test():\n\tprint(\"testme\")\n\nBob = Timer(1, Test)\nBob(5)\n\"\"\"\n\n","sub_path":"Sagan/Timer.py","file_name":"Timer.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"382444139","text":"# -*- coding: utf-8 -*-\n#\n# Copyright 2017-2018 Swiss Data Science Center (SDSC)\n# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and\n# Eidgenössische Technische Hochschule Zürich (ETHZ).\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\"\"\"A Sphinx theme for Renku documentation.\"\"\"\n\nimport os\n\nfrom setuptools import setup\n\nreadme = open('README.rst').read()\nhistory = open('CHANGES.rst').read()\n\ntests_require = [\n 'check-manifest>=0.25',\n 'isort>=4.2.2',\n 'pydocstyle>=1.0.0',\n]\n\nextras_require = {\n 'docs': [\n 'Sphinx>=1.6.3',\n ],\n 'tests': tests_require,\n}\n\nextras_require['all'] = extras_require['docs'] + extras_require['tests']\n\ninstall_requires = [\n 'Sphinx>=1.6.3',\n]\n\n# Get the version string. Cannot be done with import!\ng = {}\nwith open(os.path.join('renku_sphinx_theme', 'version.py'), 'rt') as fp:\n exec(fp.read(), g)\n version = g['__version__']\n\nsetup(\n name='renku-sphinx-theme',\n version=version,\n description=__doc__,\n long_description=readme + '\\n\\n' + history,\n keywords='Renku Sphinx theme',\n license='Apache License 2.0',\n author='Swiss Data Science Center (SDSC)',\n author_email='contact@datascience.ch',\n url='https://github.com/SwissDataScienceCenter/renku-sphinx-theme',\n platforms='any',\n packages=['renku_sphinx_theme'],\n include_package_data=True,\n extras_require=extras_require,\n install_requires=install_requires,\n tests_require=tests_require,\n entry_points={\n 'sphinx.html_themes': [\n 'renku = renku_sphinx_theme',\n ],\n },\n classifiers=[\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: OS Independent',\n 'Topic :: Documentation',\n 'Topic :: Software Development :: Documentation',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"567069184","text":"from ops.framework import (\n EventSource,\n EventBase,\n Object,\n ObjectEvents,\n)\n\nfrom pathlib import Path\n\nimport subprocess\n\nimport os\n\nclass ConfigureSlurmEvent(EventBase):\n \"\"\"Event used to signal that slurm config should be written to disk.\n \"\"\"\n\nclass SlurmSnapInstalledEvent(EventBase):\n \"\"\"Event used to signal that the slurm snap has been installed.\n \"\"\"\n\nclass ConfigureSlurmEvents(ObjectEvents):\n configure_slurm = EventSource(ConfigureSlurmEvent)\n slurm_snap_installed = EventSource(SlurmSnapInstalledEvent)\n\n\nclass SlurmSnapOps(Object):\n \"\"\"Class containing events used to signal slurm snap configuration.\n\n Events emitted:\n - configure_slurm\n \"\"\"\n on = ConfigureSlurmEvents()\n\n def install_slurm_snap(self):\n #cmd = [\"snap\", \"install\"]\n #resource = resource_get(\"slurm\")\n\n #if resource is not False:\n # cmd.append(resource)\n # cmd.append(\"--dangerous\")\n # cmd.append(\"--classic\")\n #else:\n # cmd.append(\"slurm\")\n\n #subprocess.call(cmd)\n #change this dude\n subprocess.call([\"snap\", \"install\", \"slurm\"])\n subprocess.call([\"snap\", \"connect\", \"slurm:network-control\"])\n subprocess.call([\"snap\", \"connect\", \"slurm:system-observe\"])\n subprocess.call([\"snap\", \"connect\", \"slurm:hardware-observe\"])\n\n def render_slurm_config(self, source, target, context):\n \"\"\"Render the context into the source template and write\n it to the target location.\n \"\"\"\n\n source = Path(source)\n target = Path(target)\n\n if context and type(context) == dict:\n ctxt = context\n else:\n raise TypeError(\n f\"Incorect type {type(context)} for context - Please debug.\"\n )\n\n if not source.exists():\n raise Exception(\n f\"Source config {source} does not exist - Please debug.\"\n )\n\n if target.exists():\n target.unlink()\n\n with open(str(target), 'w') as f:\n f.write(open(str(source), 'r').read().format(**ctxt))\n\n\n def set_slurm_snap_mode(self, snap_mode):\n subprocess.call([\"snap\", \"set\", \"slurm\", snap_mode])\n\n pass\n\ndef resource_get(resource_name):\n '''Used to fetch the resource path of the given name.\n This wrapper obtains a resource path and adds an additional\n check to return False if the resource is zero length.\n '''\n res_path = subprocess.run(\n [\n 'resource-get',\n resource_name\n ]\n )\n if res_path and os.stat(res_path).st_size != 0:\n return res_path\n return False\n\n","sub_path":"src/slurm_snap_ops.py","file_name":"slurm_snap_ops.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"6168163","text":"\"\"\"Definition of the Kaltura Video content type\n\"\"\"\n\nfrom zope.interface import implements\n\nfrom AccessControl import ClassSecurityInfo\n\n\nfrom Products.Archetypes import atapi\nfrom Products.ATContentTypes.content import base\nfrom Products.ATContentTypes.content import schemata\nfrom Products.ATContentTypes.interface.file import IATFile\nfrom Products.ATContentTypes.interface.file import IFileContent\nfrom plone.app.blob.content import ATBlob\nfrom plone.app.blob.interfaces import IATBlobFile\n\nfrom zope.i18nmessageid import MessageFactory\n_ = MessageFactory('kaltura_video')\n\nfrom rfa.kaltura.interfaces import IKalturaVideo\nfrom rfa.kaltura.config import PROJECTNAME\n\nfrom rfa.kaltura.content import base as KalturaBase\nfrom rfa.kaltura.kutils import kconnect\n\nfrom KalturaClient.Plugins.Core import KalturaMediaEntry as API_KalturaMediaEntry\n\nKalturaVideoSchema = ATBlob.schema.copy() + KalturaBase.KalturaBaseSchema.copy() + \\\n atapi.Schema((\n atapi.StringField('title',\n searchable=1,\n required=True,\n languageIndependent=1,\n accessor=\"Title\",\n widget=atapi.StringWidget(label=\"Title\",\n label_msgid=\"label_kvideofile_title\",\n description=\"The title of this video.\",\n description_msgid=\"desc_kvideofile_title\",\n i18n_domain=\"kaltura_video\"),\n \n ),\n \n atapi.StringField('description',\n searchable=0,\n required=True,\n accessor=\"Description\",\n widget=atapi.StringWidget(label=\"Description\",\n label_msgid=\"label_kvideofile_desc\",\n description=\"Enter a description\",\n description_msgid=\"desc_kvideofile_title\",\n i18n_domain=\"kaltura_video\"),\n ),\n \n atapi.ImageField('thumbnail',\n searchable=0,\n required=False,\n mode='r',\n widget=atapi.ImageWidget(label=\"Thumbnail\",\n description=\"Thumbnail of video\",\n visible = {'edit': 'invisible', 'view': 'visible'},\n i18n_domain=\"kaltura_video\")\n ),\n \n atapi.StringField('playbackUrl',\n searchable=0,\n accessor=\"getPlaybackUrl\",\n mode=\"r\",\n widget=atapi.ComputedWidget(label=\"Url\",\n description=\"Url set by Kaltura after upload (read only)\",\n visible = { 'edit' :'visible', 'view' : 'visible' },\n i18n_domain=\"kaltura_video\")\n ),\n \n ),\n )\n\nKalturaVideoSchema += KalturaBase.KalturaMetadataSchema.copy()\n\n# Set storage on fields copied from ATContentTypeSchema, making sure\n# they work well with the python bridge properties.\n\nKalturaVideoSchema['title'].storage = atapi.AnnotationStorage()\nKalturaVideoSchema['description'].storage = atapi.AnnotationStorage()\n\nschemata.finalizeATCTSchema(KalturaVideoSchema, moveDiscussion=False)\n\n###TODO: Offer option NOT to store video as a blob in the ZODB\nclass KalturaVideo(ATBlob, KalturaBase.KalturaContentMixin):\n \"\"\"Kaltura Video Content Type - stores the video file on your Kaltura account\"\"\"\n #ISA KalturaMediaEntry\n implements(IKalturaVideo, IATBlobFile, IATFile, IFileContent)\n\n # CMF FTI setup\n global_allow = True\n default_view = 'kvideo_main'\n #immediate_view = 'generic_preview'\n \n # CompositePack setup\n layout = 'kvideo_main'\n layouts = ('kvideo_main',\n )\n\n meta_type = \"KalturaVideo\"\n schema = KalturaVideoSchema\n\n title = atapi.ATFieldProperty('title')\n description = atapi.ATFieldProperty('description')\n \n security = ClassSecurityInfo()\n\n def __init__(self, oid, **kwargs):\n super(KalturaVideo, self).__init__(oid, **kwargs)\n self.KalturaObject = None\n\n # -*- Your ATSchema to Python Property Bridges Here ... -*-\n \n security.declarePublic(\"getPlaybackUrl\")\n def getPlaybackUrl(self):\n if self.KalturaObject is not None:\n return self.KalturaObject.getDataUrl()\n else:\n return None\n \n playbackUrl = property(getPlaybackUrl) \n \n security.declarePrivate('getDefaultPlayerId')\n def getDefaultPlayerId(self):\n return \"20100652\"\n\n ### These may get duplicated in base.py - we'll see ###\n \n def updateCategories(self, categories):\n categoryString = ','.join([c for c in self.getCategories if c])\n self._updateRemote(CategoriesIds=categoryString)\n \n def updateTags(self, tags): \n tagsString = ','.join([t for t in self.getTags() if t])\n self._updateRemote(Tags=tagsString) \n \n ### end possible base class methods ###\n \n security.declarePrivate('_updateRemote')\n def _updateRemote(self, **kwargs):\n \"\"\"will set the specified attribute on the matching object in Kaltura\n Try not to modify self.KalturaObject directly -use this method instead\n to keep things in sync with the remote server.\n \n For example, to update the name of the kaltura video:\n self._updateRemote(name='NewName')\n \"\"\" \n (client, session) = kconnect()\n newVideo = API_KalturaMediaEntry()\n for (attr, value) in kwargs.iteritems():\n setter = getattr(newVideo, 'set'+attr)\n setter(value)\n result = client.media.update(self.getEntryId(), newVideo)\n self.setKalturaObject(result) \n \natapi.registerType(KalturaVideo, PROJECTNAME)\n\n\n\n\n","sub_path":"rfa/kaltura/content/kalturavideo.py","file_name":"kalturavideo.py","file_ext":"py","file_size_in_byte":6421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"460510086","text":"class Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n # hash用于建立数值到下表的映射\n hash = {}\n # 循环nums数值,并添加映射\n for i in range(len(nums)):\n if target - nums[i] in hash:\n return [hash[target - nums[i]], i]\n hash[nums[i]] = i\n # 无解的情况\n return [-1, -1]\n\n\n# 如果是返回这两个数 而不是index\n# 哈希表\ndef twoSum(numbers, target):\n hash_set = set()\n \n for i in range(len(numbers)):\n if target-numbers[i] in hash_set:\n return (numbers[i], target-numbers[i])\n hash_set.add(numbers[i])\n\n return None\n\n# 双指针\nclass Solution:\n def twoSum(self, numbers, target):\n numbers.sort()\n\n L, R = 0, len(numbers)-1\n while L < R:\n if numbers[L]+numbers[R] == target:\n return (numbers[L], numbers[R])\n if numbers[L]+numbers[R] < target:\n L += 1\n else:\n R -= 1\n return None","sub_path":"two_pointers/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"52133883","text":"import os\nimport cv2\nimport time\n\n\n# modules for opencv https://github.com/opencv/opencv/tree/master/data/haarcascades\n\ndef getphoto(filename, cameranumber):\n cap = cv2.VideoCapture(cameranumber)\n for i in range(5):\n cap.read()\n \n ret, frame = cap.read()\n face_cascade = cv2.CascadeClassifier(os.getcwd()+'/haarcascade_frontalface_default.xml')\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray,scaleFactor= 1.1, minNeighbors= 5, minSize=(10, 10))\n faces_detected = format(len(faces))\n cv2.imwrite(filename, frame) \n cap.release() \n \n return(faces_detected)\n\n\n\nfilename = os.getcwd()+'/photos/'+time.ctime().replace(':','_')+'.png'\nprint(filename)\n\nfacescount = getphoto(filename, 0)\nprint('Faces find : ' + facescount)\n","sub_path":"find_face.py","file_name":"find_face.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"97868853","text":"# _*_ coding: UTF-8 _*_\n# @Time : 2020/12/25 0:16\n# @Author : LiuXiaoQiang\n# @Site : https://github.com/qq183727918\n# @File : payment.py\n# @Software : PyCharm\nimport requests\nfrom influence.judgingThatTheTokenIsInvalid.judgingThatTheTokenIsInvalid import InviTation\nfrom params.sem_params import ParamsTest\nfrom file_pre.read_token import ReadToken\n\n\nclass PayMent:\n\n def paymentest(self, purchaseSn):\n self.urla = ParamsTest().selenium_url_pre()\n token = ReadToken().retoken()\n url = f\"{self.urla}scp-procurement-service/controller-procurementPaymentOpsService/front/getList\"\n\n querystring = {\n \"status\": \"\",\n \"paymentMethod\": \"\",\n \"attribute\": \"\",\n \"purchaseSn\": purchaseSn,\n \"PurchaseStatus\": \"\",\n \"PurchaseType\": \"\",\n \"groupId\": \"\",\n \"tax\": \"\",\n \"consignee\": \"\",\n \"refundStatus\": \"\",\n \"receiptStatus\": \"\",\n \"supplierId\": \"\",\n \"badPaypal\": \"\",\n \"type\": 0,\n \"currentPage\": 1,\n \"pageSize\": 10\n }\n\n headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Authorization\": f'Bearer {token}'\n }\n\n response = requests.get(url, headers=headers, params=querystring)\n\n re = response.json()\n\n TheTokenValue = InviTation().token_code(re['code'])\n\n if TheTokenValue == 200:\n\n # pprint.pprint(re)\n\n data = re[\"data\"]\n lists = []\n for k in data:\n dict = {\n # \"paymenttype\": \"预付款单\",\n \"paymentAmount\": \"\",\n \"attributeName\": \"\"\n }\n # 付款单金额\n paymentAmount = k[\"paymentAmount\"]\n # 付款单属性(无票可付、票到付款)\n attributeName = k[\"attributeName\"]\n dict[\"paymentAmount\"] = paymentAmount\n dict[\"attributeName\"] = attributeName\n lists.append(dict)\n\n print(lists)\n\n return lists\n elif TheTokenValue == 401:\n self.paymentest(purchaseSn)\n elif TheTokenValue == '请找相关开发人员解决':\n print('请找相关开发人员解决')\n else:\n print('请检查代码逻辑,谢谢')\n\n\nif __name__ == '__main__':\n purchaseSn = 'NCG2020122400034'\n pm = PayMent()\n pm.paymentest(purchaseSn)\n","sub_path":"debug/procur/payment.py","file_name":"payment.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"468780870","text":"import csv\nfrom django.core.management import BaseCommand\nfrom sightings.models import show\nclass Command(BaseCommand):\n help = 'Import Data'\n\n def add_arguments(self, parser):\n parser.add_argument('path', type=str)\n\n def handle(self, *args, **kwargs):\n import datetime\n path = kwargs['path']\n with open(path) as f:\n reader = csv.reader(f)\n next(reader)\n for item in reader:\n for i in (15,16,17,18,19,21,22,23,24,25,26,27,28):\n if item[i] == 'false':\n item[i] = False\n else:\n item[i] = True\n\n longitude = item[0]\n latitude = item[1]\n unique_squirrel_id = item[2]\n shift = item[4]\n date = datetime.datetime.strptime(item[5],\"%m%d%Y\").strftime(\"%Y-%m-%d\")\n age = item[7]\n primary_fur_color = item[8]\n location = item[12]\n specific_location = item[14]\n running = item[15]\n chasing = item[16]\n climbing = item[17]\n eating = item[18]\n foraging = item[19]\n other_activities = item[20]\n kuks = item[21]\n quaas = item[22]\n moans = item[23]\n tail_flags = item[24]\n tail_twitches = item[25]\n approaches = item[26]\n indifferent = item[27]\n run_from = item[28]\n\n new_show = show(Longitude = longitude, Latitude = latitude,Unique_squirrel_id = unique_squirrel_id, Shift = shift, Date = date, Age = age,\n Primary_fur_color = primary_fur_color, Location = location, Specific_location = specific_location,\n Running = running, Chasing = chasing, Climbing = climbing, Eating = eating, Foraging = foraging,\n Other_activities = other_activities, Kuks = kuks, Quaas=quaas, Moans=moans, Tail_flags = tail_flags, \n Tail_twitches = tail_twitches, Approaches = approaches, Indifferent = indifferent, Runs_from = run_from)\n\n new_show.save()\n","sub_path":"sightings/management/commands/import_squirrel_data.py","file_name":"import_squirrel_data.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"77482093","text":"# Core packages\nimport functools\n\n# Third party packages\nimport flask\nimport modules.authentication as authentication\n\n\ndef login_required(func):\n \"\"\"\n Decorator that checks if a user is logged in, and redirects\n to login page if not.\n \"\"\"\n @functools.wraps(func)\n @private_cache_headers\n def is_user_logged_in(*args, **kwargs):\n if not authentication.is_authenticated(flask.session):\n return flask.redirect('login?next=' + flask.request.path)\n\n return func(*args, **kwargs)\n return is_user_logged_in\n\n\ndef _cache_headers_decorator(route_function, cache_headers):\n \"\"\"\n Return a decorator function to add a set of Cache-Control headers\n to the response\n \"\"\"\n\n @functools.wraps(route_function)\n def decorated_function(*args, **kwargs):\n response = flask.make_response(\n route_function(*args, **kwargs)\n )\n\n if response.status_code == 200:\n # Only add caching headers to successful responses\n response.headers['Cache-Control'] = ', '.join(cache_headers)\n\n return response\n\n return decorated_function\n\n\ndef public_cache_headers(route_function):\n \"\"\"\n Add standard caching headers to a public route:\n\n - Cache pages for 30 seconds\n (allows Squid to take significant load of the app)\n - Serve stale pages while revalidating the cache for 5 minutes\n (allows Squid to response instantly while doing cache refreshes)\n - Show stale pages if the app is erroring for 1 day\n (gives us a 1 day buffer to fix errors before they are publicly visible)\n \"\"\"\n\n cache_headers = [\n 'max-age=30',\n 'stale-while-revalidate=300',\n 'stale-if-error=86400',\n ]\n\n return _cache_headers_decorator(route_function, cache_headers)\n\n\ndef private_cache_headers(route_function):\n \"\"\"\n Add standard caching headers to a private route:\n\n - Most importantly, add \"private\"\n (to prevent responses going where they shouldn't)\n \"\"\"\n\n cache_headers = [\n 'private', # Important\n ]\n\n return _cache_headers_decorator(route_function, cache_headers)\n","sub_path":"decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"169647923","text":"#!/usr/bin/python3\n\"\"\"Matrix divided by number\nArgs:\n matrix: a matrix, two dimemsion lists\n div: a number\n\"\"\"\n\n\ndef matrix_divided(matrix, div):\n \"\"\"Function makes matrix divided by a number\n Return:\n returns a matrix after division\n \"\"\"\n\n if div == 0:\n raise ZeroDivisionError('division by zero')\n if type(div) is not int and type(div) is not float:\n raise TypeError('div must be a number')\n b = [a for sub in matrix for a in sub]\n for i in b:\n if type(i) is not int and type(i) is not float:\n raise TypeError(\"matrix must be a matrix (list of lists) of integers/floats\")\n c = [len(sub) == len(matrix[0]) for sub in matrix]\n if not all(c):\n raise TypeError('Each row of the matrix must have the same size')\n A = []\n for i in range(len(matrix)):\n row = []\n for j in range(len(matrix[0])):\n row.append(round(matrix[i][j]/div, 2))\n A.append(row)\n return A\n","sub_path":"0x07-python-test_driven_development/2-matrix_divided.py","file_name":"2-matrix_divided.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"489367392","text":"import pandas as pd\nfrom scipy.spatial.distance import cdist\nfrom sklearn.preprocessing import StandardScaler\nfrom app import app\n\ndef create_similarity(song, dataframe):\n distance_vector = cdist(XA=song,XB=dataframe,metric='euclidean')\n similarities = 1 / (1 + distance_vector) \n similarity_index = pd.DataFrame(similarities, columns=dataframe.index)\n return similarity_index\n\ndef get_recommendation(client, from_year, to_year, listed_artists, popular_artists, not_explicit, features_list):\n keys_to_remove = [\"duration_ms\",\"key\",\"mode\",\"time_signature\",\"loudness\",\"id\",\"uri\",\"track_href\",\"analysis_url\",\"type\"]\n for features in features_list:\n for key in keys_to_remove:\n features.pop(key)\n\n tracks_list = pd.DataFrame.from_dict(client.select_all_tracks(listed_artists, popular_artists, not_explicit, from_year, to_year),\n orient=\"columns\")\n tracks_list.columns=[\"name\", \"artist\", \"album\", \"year\", \"uri\", \"img\", \"acousticness\", \"danceability\", \"energy\", \"instrumentalness\", \"liveness\", \"speechiness\", \"valence\", \"tempo\"]\n scaler = StandardScaler()\n tracks_list[[\"acousticness\", \"danceability\", \"energy\", \"instrumentalness\", \"liveness\", \"speechiness\", \"valence\", \"tempo\"]] = scaler.fit_transform(tracks_list[[\"acousticness\", \"danceability\", \"energy\", \"instrumentalness\", \"liveness\", \"speechiness\", \"valence\", \"tempo\"]])\n tracks_list.set_index([\"name\", \"artist\", \"album\", \"year\", \"uri\", \"img\"], inplace=True)\n\n name_list, artist_list, album_list, year_list, img_list, uri_list, match_list = ([] for i in range(7))\n\n for features in features_list:\n song = pd.DataFrame(columns=['acousticness','danceability','energy','instrumentalness','liveness','speechiness','valence','tempo'])\n song = song.append(features, ignore_index=True)\n song = scaler.transform(song)\n\n results = create_similarity(song,tracks_list).T[0].sort_values(ascending=False).reset_index()\n name_list.append(results.loc[results[0]<0.95, 'name'].reset_index(drop=True)[0])\n artist_list.append(results.loc[results[0]<0.95, 'artist'].reset_index(drop=True)[0])\n album_list.append(results.loc[results[0]<0.95, 'album'].reset_index(drop=True)[0])\n year_list.append(results.loc[results[0]<0.95, 'year'].reset_index(drop=True)[0])\n img_list.append(results.loc[results[0]<0.95, 'img'].reset_index(drop=True)[0])\n uri_list.append(results.loc[results[0]<0.95, 'uri'].reset_index(drop=True)[0])\n match_list.append(round(results.loc[results[0]<0.95, 0].reset_index(drop=True)[0]*100))\n return name_list, artist_list, album_list, year_list, img_list, uri_list, match_list","sub_path":"app/recommender.py","file_name":"recommender.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"131213890","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 5 11:28:01 2018\n\n@author: tqc268\n\"\"\"\n\n\nimport sys\nimport pandas as pd\nimport os\nimport copy\n\nsys.path.append(r'../../../pydaisy')\n\nfrom Daisy import *\nif __name__ =='__main__':\n xl = pd.read_excel(r'Treat4+5_S1_S3.xlsx', None)\n for sheet in xl.items():\n df=sheet[1]\n template = DaisyModel(r'Foulum94-10_v8.dai')\n i=0\n unique_name = sheet[0]\n newfile= copy.deepcopy(template) \n block = newfile.Input['defaction'][1]\n \n for i in range(0,len(df)):\n block.Children.append(DaisyEntry('wait_mm_dd', [str(df['date'][i].month), str(df['date'][i].day)]))\n \n if df['action'][i]=='sow':\n for crop in df['what'][i].split(','):\n sow = DaisyEntry('sow', ['\"' + crop.strip() +'\"'])\n block.Children.append(sow) \n elif df['action'][i]=='harvest' or df['action'][i]=='cut' :\n for crop in df['what'][i].split(','):\n harvest = DaisyEntry(df['action'][i], ['\"' + crop.strip() +'\"'])\n harvest.Children.append(DaisyEntry('stub', ['7 [cm]']))\n block.Children.append(harvest) \n elif df['action'][i]=='fertilize':\n fert = DaisyEntry('fertilize',[])\n fert.Children.append(DaisyEntry('\"' + df['what'][i]+'\"',[]))\n fert.Children.append(DaisyEntry('equivalent_weight',[ str(df['amount'][i]) , '[kg N/ha]']))\n fert.Children.append(DaisyEntry('from', ['-5', '[cm]']))\n fert.Children.append(DaisyEntry('to', ['-15', '[cm]']))\n block.Children.append(fert)\n elif df['action'][i]== 'irrigate':\n irri= DaisyEntry('irrigate_overhead', [str(df['amount'][i]), '[mm/h]'])\n block.Children.append(irri)\n else:\n block.Children.append(DaisyEntry(df['action'][i],[]))\n \n filename = os.path.join(unique_name, 'setup.dai')\n newfile.save_as(filename)\n \n run_sub_folders(r'.','setup.dai')\n\n","sub_path":"KG_kalib/RunDaisy8/RunMultiDaisy.py","file_name":"RunMultiDaisy.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"156531338","text":"# Copyright 2017 Google Inc.\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\"\"\"Database backed histogram.\"\"\"\n\nimport itertools\nimport operator\nimport typing\nimport sqlite3\nimport injector\nimport numpy\nfrom simulation.base import Base\nfrom simulation.static import WEEK\n\n\nclass Histogram(Base):\n \"\"\"Histogram stored in a DB.\"\"\"\n __run = 0\n\n @injector.inject\n @injector.noninjectable('name')\n def __init__(self, conn: sqlite3.Connection, name: str):\n super(Histogram, self).__init__()\n self.__cache_size = self.get_config_int('cache_size', section='stats')\n self.__cursor = conn.cursor()\n self.__name = name\n self.__sum = 0\n self.__count = 0\n self.__write_cache = []\n\n @classmethod\n def new_run(cls):\n \"\"\"Increment the run counter.\"\"\"\n cls.__run += 1\n\n @classmethod\n def runs(cls):\n \"\"\"Indicates the number of runs.\"\"\"\n return cls.__run\n\n def append(self, timestamp: int, cid: str, value: float) -> None:\n \"\"\"Inserts into the histogram, just in cache for now.\"\"\"\n self.__sum += value\n self.__count += 1\n self.__write_cache.append((timestamp, cid, float(value)))\n if len(self.__write_cache) >= self.__cache_size:\n self.flush()\n\n def flush(self) -> None:\n \"\"\"Dump the cache to the database.\"\"\"\n if self.__write_cache:\n self.__cursor.executemany(\n '''INSERT INTO histogram\n (run, histogram, timestamp, computer, value)\n VALUES(%d, '%s', ?, ?, ?);''' % (self.runs(), self.__name),\n self.__write_cache)\n self.__write_cache = []\n\n def get_all_hourly_histograms(self) -> typing.List[numpy.ndarray]:\n \"\"\"Gets all the subhistograms per hour.\"\"\"\n self.flush()\n self.__cursor.execute(\n '''SELECT hour, value\n FROM histogram\n WHERE histogram = ?\n ORDER BY hour ASC;''',\n (self.__name,))\n dct = {i: numpy.ascontiguousarray([i[1] for i in g])\n for i, g in itertools.groupby(\n self.__cursor.fetchall(), operator.itemgetter(0))}\n return [dct.get(i, numpy.asarray([])) for i in range(168)]\n\n def get_all_histogram(self, cid: str = None) -> numpy.ndarray:\n \"\"\"Gets all the data from the histogram.\"\"\"\n self.flush()\n if cid is None:\n self.__cursor.execute(\n '''SELECT value\n FROM histogram\n WHERE histogram = ?;''',\n (self.__name,))\n else:\n self.__cursor.execute(\n '''SELECT value\n FROM histogram\n WHERE histogram = ?\n AND computer = ?;''',\n (self.__name, cid))\n return numpy.ascontiguousarray(\n [i['value'] for i in self.__cursor.fetchall()])\n\n def get_all_hourly_summaries(self) -> typing.List[typing.Dict[str, float]]:\n \"\"\"Gets all the summaries per hour.\"\"\"\n ret = []\n for hist in self.get_all_hourly_histograms():\n dct = {}\n for summary in ('mean', 'median'):\n try:\n dct[summary] = getattr(numpy, summary)(hist)\n except (IndexError, RuntimeWarning):\n dct[summary] = 0.0\n ret.append(dct)\n return ret\n\n def get_all_hourly_count(self) -> typing.List[int]:\n \"\"\"Gets all the count per hour.\"\"\"\n self.flush()\n self.__cursor.execute(\n '''SELECT hour, COUNT(*) AS count\n FROM histogram\n WHERE histogram = ?\n GROUP BY hour\n ORDER BY hour ASC;''',\n (self.__name,))\n dct = dict(self.__cursor.fetchall())\n return [dct.get(i, 0) for i in range(168)]\n\n def sum_histogram(self, cid: str = None) -> int:\n \"\"\"Sums up all the elements of this histogram.\"\"\"\n if cid is None:\n return self.__sum\n self.flush()\n self.__cursor.execute(\n '''SELECT SUM(value) AS sum\n FROM histogram\n WHERE histogram = ?\n AND computer = ?;''',\n (self.__name, cid))\n return int(self.__cursor.fetchone()['sum'])\n\n def count_histogram(self, cid: str = None) -> int:\n \"\"\"Counts the number of elements in this histogram.\"\"\"\n if cid is None:\n return self.__count\n self.flush()\n self.__cursor.execute(\n '''SELECT COUNT(*) AS count\n FROM histogram\n WHERE histogram = ?\n AND computer = ?;''',\n (self.__name, cid))\n return int(self.__cursor.fetchone()['count'])\n\n\ndef create_histogram_tables(conn: sqlite3.Connection) -> None:\n \"\"\"Creates the tables on the database.\"\"\"\n cursor = conn.cursor()\n cursor.execute('DROP TRIGGER IF EXISTS t_hour;')\n cursor.execute('DROP INDEX IF EXISTS i_histogram_hour;')\n cursor.execute('DROP TABLE IF EXISTS histogram;')\n cursor.execute('''\n CREATE TABLE histogram (\n id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n run INTEGER NOT NULL,\n hour INTEGER,\n histogram TEXT NOT NULL,\n computer TEXT NOT NULL,\n timestamp REAL NOT NULL,\n value REAL NOT NULL\n );''')\n cursor.execute(\n 'CREATE INDEX i_histogram ON histogram(histogram);')\n cursor.execute(\n 'CREATE INDEX i_computer ON histogram(computer);')\n cursor.execute(\n 'CREATE INDEX i_hour ON histogram(hour);')\n cursor.execute(\n 'CREATE INDEX i_run ON histogram(run);')\n cursor.execute('''\n CREATE TRIGGER t_hour AFTER INSERT ON histogram\n FOR EACH ROW BEGIN\n UPDATE histogram SET hour =\n (CAST(new.timestamp AS INTEGER) %% %d) / 3600\n WHERE id = NEW.id;\n END;''' % WEEK(1))\n","sub_path":"simulation/histogram.py","file_name":"histogram.py","file_ext":"py","file_size_in_byte":6539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"291459751","text":"#%%\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nfrom pathlib import Path\nimport shutil\nimport collections\n\nimport gym\nfrom gym import wrappers\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# from env import VecEnv\nfrom models import PolicyNetwork, CriticNetwork\n# import util\n\nimport agent\nimport market\n\nfrom gym.envs.registration import register\nfrom gym import envs\n\nall_envs = envs.registry.all()\nenv_ids = [env_spec.id for env_spec in all_envs ]\n\n# %%\nCONFIG = dict()\nCONFIG['envid'] = 'market-v0'\nCONFIG['entry_point'] = 'market:marketenv'\n\n# %%\n\n# delete if it's registered\nif CONFIG['envid'] in gym.envs.registry.env_specs:\n del gym.envs.registry.env_specs[CONFIG['envid']]\n\nif CONFIG['envid'] not in env_ids:\n register(\n\n id = CONFIG['envid'],\n entry_point = CONFIG['entry_point']\n\n )\n\n\n#%%\n\nclass envlogger:\n\n GAMMA = 0.99\n GAE_LAMBDA = 0.95\n CLIPRANGE = 0.2\n OPT_ITER = 20\n BATCH_SIZE = 2048\n\n def __init__(self,env_id,max_timesteps,action_space=2,\n trajectory_size=256\n ):\n\n self.env = gym.make(env_id)\n self.max_timesteps = max_timesteps\n self.trajectory = {\"s\":[],\"a\":[],\"t\":[],\"r\":[],'state':[]}\n\n self.policy = PolicyNetwork(action_space=action_space)\n self.old_policy = PolicyNetwork(action_space=action_space)\n self.critic = CriticNetwork()\n\n self.iter_traj = 0 \n self.trajectory_size = trajectory_size\n\n self.policy(np.atleast_2d(self.generate_initial_states()))\n self.old_policy(np.atleast_2d(self.generate_initial_states()))\n\n\n def generate_initial_states(self):\n\n bid_s = np.arange(0,20) * 1e-5\n ask_s = np.arange(0,20) * 1e-5\n trades = np.zeros(100)\n\n return(\n np.append(\n np.append(bid_s,ask_s)\n , trades\n )\n )\n\n def reset(self):\n\n self.env.reset()\n self.reset_trajectory()\n\n\n def reset_env(self):\n self.env.reset()\n\n\n def step(self,action):\n\n self.iter_traj += 1\n\n observation, reward, done, info = self.env.step(action)\n self.trajectory['s'].append(\n np.append(observation['bid_s'],observation['ask_s'])\n )\n\n self.trajectory['a'].append(action)\n self.trajectory['r'].append(reward)\n self.trajectory['t'].append(info['trade'])\n\n if len(self.trajectory['t']) > 100 :\n self.trajectory['state'].append( np.append(\n np.append(observation['bid_s'],observation['ask_s']),\n np.array(self.trajectory['t'][-100:],dtype=np.float32)\n ))\n return(self.trajectory['state'][-1],info['trade'])\n else:\n self.trajectory['state'].append( np.append(\n np.append(observation['bid_s'],observation['ask_s']),\n np.append(np.zeros(100-len(self.trajectory['t'])),\n np.array(self.trajectory['t'],dtype=np.float32)\n )\n ))\n return(self.trajectory['state'][-1],info['trade'])\n\n def get_trajectory(self):\n\n trajectory = self.trajectory\n\n trajectory['s'] = np.array(trajectory['s'],dtype=np.float32)\n trajectory['a'] = np.array(trajectory['a'],dtype=np.float32)\n trajectory['t'] = np.array(trajectory['t'],dtype=np.float32)\n trajectory['r'] = np.array(trajectory['r'],dtype=np.float32)\n trajectory['state'] = np.array(trajectory['state'],dtype=np.float32)\n\n return trajectory\n\n def reset_trajectory(self):\n\n self.trajectory = {'s':[],'a':[],'r':[],'t':[],'state':[]}\n self.iter_traj = 0\n\n def run(self,n_updates,logdir=None):\n\n # self.summary_writer = tf.summary.create_file_writer(str(logdir))\n history = {\"epoch\":[],\"score\":[]}\n\n trajectories = dict()\n\n for epoch in range(n_updates):\n\n inventory = 0 \n self.reset_trajectory()\n state = self.generate_initial_states()\n\n for _ in range(self.trajectory_size+100):\n\n action = self.policy.sample_action(state)\n next_state,trade = self.step(np.append(action,inventory))\n inventory += trade\n state = next_state\n\n trajectory = self.get_trajectory()\n trajectory = self.compute_advantage(trajectory,state)\n\n vloss = self.update_critic(\n trajectory['state'][100:],\n trajectory['R'][100:]\n )\n\n self.update_policy(\n trajectory['state'][100:],\n trajectory['a'][100:,:1],\n trajectory['advantage'][100:]\n )\n\n score = np.array(trajectory['r']).sum()\n\n history['epoch'].append(epoch)\n history['score'].append(score)\n\n if epoch % 5 == 0 :\n print(str(epoch),':')\n pd.DataFrame(history).plot(x='epoch',y='score')\n\n return(pd.DataFrame(history))\n\n\n def compute_advantage(self,trajectory:dict,state_last_plus_one:np.ndarray):\n\n '''\n generalized advantage estimation (gae,2016)\n '''\n\n trajectory['v_pred'] = self.critic(trajectory['state']).numpy(\n ).reshape(-1)\n trajectory['v_pred_next'] = np.append(\n trajectory['v_pred'][1:], \n self.critic(np.atleast_2d(state_last_plus_one)).numpy()\n )\n \n\n normed_rewards = trajectory['r']\n deltas = normed_rewards+self.GAMMA * trajectory['v_pred_next'] \\\n - trajectory['v_pred']\n\n advantages = np.zeros_like(deltas,dtype=np.float32)\n\n lastgae = 0 \n for i in reversed(range(len(deltas))):\n\n lastgae = deltas[i] + self.GAMMA * self.GAE_LAMBDA * lastgae\n advantages[i] = lastgae\n\n trajectory['advantage'] = advantages\n trajectory['R'] = advantages + trajectory['v_pred']\n\n return trajectory\n\n def update_policy(self,states,actions,advantages):\n\n self.old_policy.set_weights(self.policy.get_weights())\n indices = np.random.choice(\n range(states.shape[0]),(self.OPT_ITER,self.BATCH_SIZE)\n )\n\n for i in range(self.OPT_ITER):\n idx = indices[i]\n old_means, old_stdevs = self.old_policy(states[idx])\n old_logprob = self.compute_logprob(\n old_means,old_stdevs,actions[idx]\n )\n\n with tf.GradientTape() as tape :\n\n new_means, new_stdevs = self.policy(states[idx])\n new_logprob = self.compute_logprob(\n new_means,new_stdevs,actions[idx]\n )\n ratio = tf.exp(new_logprob-old_logprob)\n ratio_clipped = tf.clip_by_value(\n ratio,1-self.CLIPRANGE,1+self.CLIPRANGE\n )\n loss_unclipped = ratio*advantages[idx]\n loss_clipped = ratio_clipped*advantages[idx]\n loss = tf.minimum(loss_unclipped,loss_clipped)\n loss = -1* tf.reduce_mean(loss)\n\n grads = tape.gradient(loss,self.policy.trainable_variables)\n grads, _ = tf.clip_by_global_norm(grads,0.5)\n self.policy.optimizer.apply_gradients(\n zip(grads,self.policy.trainable_variables)\n )\n\n\n def update_critic(self,states,v_targs):\n\n losses = []\n indices = np.random.choice(\n range(states.shape[0]),(self.OPT_ITER,self.BATCH_SIZE)\n )\n \n\n for i in range(self.OPT_ITER):\n\n idx = indices[i]\n old_vpred = self.critic(states[idx])\n\n with tf.GradientTape() as tape:\n\n vpred = self.critic(states[idx])\n vpred_clipped = old_vpred + tf.clip_by_value(\n vpred - old_vpred, -self.CLIPRANGE,self.CLIPRANGE\n )\n loss = tf.maximum(\n tf.square(v_targs[idx]-vpred),\n tf.square(v_targs[idx]-vpred_clipped)\n )\n loss = tf.reduce_mean(loss)\n\n grads = tape.gradient(loss,self.critic.trainable_variables)\n grads,_ = tf.clip_by_global_norm(grads,0.5)\n self.critic.optimizer.apply_gradients(\n zip(grads,self.critic.trainable_variables)\n )\n losses.append(loss)\n\n return np.array(losses).mean()\n\n\n @tf.function\n def compute_logprob(self,means,stdevs,actions):\n\n logprob = -0.5 * np.log(2*np.pi)\n logprob += -tf.math.log(stdevs)\n logprob += -0.5 * tf.square((actions-means)/stdevs)\n logprob = tf.reduce_sum(logprob,axis=1,keepdims=True)\n\n return(logprob)\n\n\n\n\n# %%\n\nmkt = envlogger(CONFIG['envid'],1000)\nmkt.reset()\ninventory = 0 \noutput = mkt.run(n_updates=100)\n\n\n# %%\n\n\n","sub_path":"traial.py","file_name":"traial.py","file_ext":"py","file_size_in_byte":8878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"466356377","text":"import json\nimport os\nfrom pathlib import Path\nfrom typing import Tuple, Dict, List, Any, Union\n\nimport torch\nfrom pycocotools.coco import COCO\nfrom pycocotools.cocoeval import COCOeval\nfrom torch.utils.data import DataLoader\n\nimport rock.datasets.nyu_depth_v2\nimport rock.ssd.encoder\nimport rock.ssd.prior_boxes\nimport rock.datasets.transforms\nimport rock.model.network\nimport rock.utils.load\nimport rock.utils.hide_print\n\n\ndef evaluate_model(model_path: str,\n test_path: str = 'data/train_test/nyuv2_test',\n device: torch.device = torch.device(\"cuda\"),\n aux: bool = True,\n aux_tasks: Tuple[str, ...] = ('scene', 'depth', 'normals'),\n coco_json_save_path: str = 'data/eval/',\n show_all_cats: bool = False,\n verbose: bool = True) -> None:\n \"\"\" Loads a model and evaluates it\n \"\"\"\n if verbose:\n print(\"Evaluating model: {}\".format(model_path))\n\n pboxes = rock.ssd.prior_boxes.pboxes_rock()\n encoder = rock.ssd.encoder.Encoder(pboxes)\n test_trans = rock.datasets.transforms.Transformer(pboxes, (480, 640), train=False)\n test_data = rock.datasets.nyu_depth_v2.NYUv2Detection(test_path, transform=test_trans, auxiliary=aux)\n\n model = rock.model.network.rock_network(aux_tasks) if aux else rock.model.network.baseline_ssd()\n model = model.to(device)\n rock.utils.load.load_from_checkpoint(model_path, model, verbose=verbose)\n\n gt_path = os.path.join(coco_json_save_path, 'gt_box.json')\n dt_path = os.path.join(coco_json_save_path, 'pred_box.json')\n\n if verbose:\n ap1, ap2 = evaluate(model, test_data, encoder, device, gt_path=gt_path, dt_path=dt_path,\n show_all_cats=show_all_cats)\n else:\n with rock.utils.hide_print.HiddenPrints():\n ap1, ap2 = evaluate(model, test_data, encoder, device, gt_path=gt_path, dt_path=dt_path,\n show_all_cats=show_all_cats)\n\n print('val mAP[0.50:0.95] = {:.4f}'.format(ap1))\n print('val mAP[0.50] = {:.4f}'.format(ap2))\n\n\ndef evaluate(model: torch.nn.Module,\n dataset: rock.datasets.nyu_depth_v2.NYUv2Detection,\n encoder: rock.ssd.encoder.Encoder,\n device: torch.device = torch.device(\"cuda\"),\n gt_path: str = 'data/eval/gt_box.json',\n dt_path: str = 'data/eval/pred_box.json',\n max_output: int = 100,\n show_all_cats: bool = False) -> Tuple[float, float]:\n \"\"\" Evaluates the network's output using COCOeval (adapted for the NYUv2 dataset)\n\n |\n Prints out the mAP and related metrics for the given model on the given dataset\n\n Args:\n model: network\n dataset: dataset on which to run eval\n encoder: encoder use to encode / decode the network's output\n device: device on which to run eval (default: cuda)\n gt_path: save path for ground truths bounding boxes json file\n dt_path: save path for predicted bounding boxes json file\n max_output: maximum number of bounding boxes to consider per image (default: 100)\n show_all_cats: whether to show AP for all categories or just an average (default: False)\n\n Returns:\n Average Precision (AP) @[ IoU=0.50:0.95] and AP @[ IoU=0.50]\n \"\"\"\n # Put model in eval mode\n model.eval()\n\n _create_coco_files(model, dataset, encoder, device, gt_path, dt_path, max_output)\n\n cocoGt = COCO(gt_path)\n cocoDt = cocoGt.loadRes(dt_path)\n\n E = COCOeval(cocoGt, cocoDt, iouType='bbox')\n\n if not show_all_cats:\n E.evaluate()\n E.accumulate()\n E.summarize()\n print(\"Current AP: {:.5f}\".format(E.stats[0]))\n\n # Put model back in training mode\n model.train()\n\n return E.stats[0], E.stats[1]\n\n else:\n # Evaluation by category\n catIds = E.params.catIds\n cats = dataset.categories\n\n for elem in catIds:\n E.params.catIds = elem\n\n print(\"catId: \" + str(elem))\n print(\"catName: \" + cats[elem])\n E.evaluate()\n E.accumulate()\n E.summarize()\n print()\n\n print(\"All catIds: \" + str(catIds))\n E.params.catIds = catIds\n E.evaluate()\n E.accumulate()\n E.summarize()\n print(\"Current AP: {:.5f}\".format(E.stats[0]))\n\n # Put model back in training mode\n model.train()\n\n return E.stats[0], E.stats[1] # Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ]\n\n\ndef _create_coco_files(model: torch.nn.Module,\n dataset: rock.datasets.nyu_depth_v2.NYUv2Detection,\n encoder: rock.ssd.encoder.Encoder,\n device: torch.device,\n gt_path: str,\n dt_path: str,\n max_output: int) -> None:\n # Create paths if they don't exist\n if not Path(gt_path).exists():\n Path(os.path.dirname(gt_path)).mkdir(parents=True, exist_ok=True)\n\n if not Path(dt_path).exists():\n Path(os.path.dirname(dt_path)).mkdir(parents=True, exist_ok=True)\n\n img_width, img_height = 640, 480\n\n gt_dict = _init_gt_dict(dataset)\n dt_dict = []\n\n model.to(device)\n\n dataloader = DataLoader(dataset, batch_size=8, shuffle=False, num_workers=2)\n for nbatch, sample in enumerate(dataloader, start=1):\n print(\"Parsing batch: {}/{}\".format(nbatch, len(dataloader)), end='\\r')\n with torch.no_grad():\n inp = sample['img'].to(device)\n img_id = sample['img_id']\n\n ploc, plabel, *aux_out = model(inp)\n\n for id in img_id.tolist():\n\n gt_dict['images'].append({\"id\": id, \"width\": img_width, \"height\": img_height, \"file_name\": None})\n\n boxes, labels = dataset.get_eval(id)\n for i, (box, label) in enumerate(zip(boxes, labels)):\n annot = {}\n annot['id'] = id * 100 + i\n annot['image_id'] = id\n annot['category_id'] = label\n annot['bbox'] = [int(elem) for elem in list(box)]\n annot['area'] = int(box[2]) * int(box[3])\n annot['iscrowd'] = 0\n annot['segmentation'] = None\n gt_dict['annotations'].append(annot)\n\n dec = encoder.decode_batch(ploc, plabel, max_output_num=max_output)\n\n for id, preds in zip(img_id.tolist(), dec):\n pred_boxes, labels, confs = preds\n\n # If nothing predicted, don't add anything\n if pred_boxes.shape[0] == 0:\n continue\n\n # Get box sizes in pixel and convert to l,t,w,h for COCOeval\n boxes = pred_boxes.cpu() * torch.tensor([img_width, img_height, img_width, img_height])\n l, t, w, h = boxes[:, 0], boxes[:, 1], boxes[:, 2] - boxes[:, 0], boxes[:, 3] - boxes[:, 1]\n boxes[:, 0] = l\n boxes[:, 1] = t\n boxes[:, 2] = w\n boxes[:, 3] = h\n boxes = torch.round(boxes * 10) / 10\n\n for box, label, conf in zip(boxes.tolist(), labels.tolist(), confs.tolist()):\n annot = {}\n annot['image_id'] = id\n annot['category_id'] = label\n annot['bbox'] = box\n annot['score'] = conf\n dt_dict.append(annot)\n\n with open(gt_path, 'w') as outfile:\n json.dump(gt_dict, outfile)\n\n with open(dt_path, 'w') as outfile:\n json.dump(dt_dict, outfile)\n\n\n# noinspection PyDictCreation\ndef _init_gt_dict(dataset: rock.datasets.nyu_depth_v2.NYUv2Detection) -> Dict[str, Union[List[Any], Dict[str, str]]]:\n d = {}\n d['info'] = {\"description\": \"Subset of NYUv2 Dataset\",\n \"url\": \"\",\n \"version\": \"\",\n \"year\": 2020,\n \"contributor\": \"\",\n \"date_created\": \"\"}\n d['licenses'] = []\n d['images'] = []\n d['annotations'] = []\n d['categories'] = []\n\n # Remove background as a category\n for i, name in enumerate(dataset.categories[1:], start=1):\n d['categories'].append({\"supercategory\": \"home\", \"id\": int(i), \"name\": name})\n\n return d\n","sub_path":"rock/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":8365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"473389422","text":"from django.conf.urls import url\nimport idea.views\n\nurlpatterns = [\n url(r'^$', idea.views.list),\n url(r'^add/$', idea.views.add_idea, name='add_idea'),\n url(r'^add/(?P\\d+)/$', idea.views.add_idea, name='add_idea'),\n url(r'^edit/(?P\\d+)/$', idea.views.edit_idea, name='edit_idea'),\n url(r'^list/$', idea.views.list, name='idea_list'),\n url(r'^list/(?P\\w+)/$', idea.views.list, name='idea_list'),\n url(r'^detail/(?P\\d+)/$', idea.views.detail, name='idea_detail'),\n url(r'^detail/likes/(?P\\d+)/$', idea.views.show_likes, name='show_likes'),\n url(r'^detail/(?P\\d+)/remove_tag/(?P[a-zA-Z0-9/\\-_]+)/$',\n idea.views.remove_tag, name='remove_tag'),\n url(r'^vote/up/$', idea.views.up_vote, name='upvote_idea'),\n url(r'^challenge/(?P\\d+)/$',\n idea.views.challenge_detail, name='challenge_detail'),\n url(r'^room/(?P.+)/$',\n idea.views.room_detail, name='room_detail'),\n url(r'^room/$',\n idea.views.room_detail, name='room_detail'),\n url(r'challenge/list/$', idea.views.banner_list, name='banner_list'),\n]\n","sub_path":"idea/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"154468052","text":"\"\"\"\nAuthor : Byunghyun Ban\nDate : 2020.07.17.\nThis code uses DCGAN sample codes from Tensorflow.org\nwhich has Apache 2.0 License.\n\"\"\"\n# pip install -q imageio\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nfrom matplotlib import pyplot as plt\nfrom tensorflow import keras\nimport tensorflow as tf\nfrom PIL import Image\nimport numpy as np\n\n\n# 데이터를 떠먹여 줄 클래스를 제작합니다.\nclass DataReader():\n def __init__(self):\n (self.origin_train_X, _), (_, _) = keras.datasets.cifar10.load_data()\n self.train_X = self.preprocess(self.origin_train_X)\n self.train_dataset = tf.data.Dataset.from_tensor_slices(self.train_X).shuffle(50000).batch(256)\n\n def preprocess(self, images):\n images = images / 127.5 - 1\n return images\n\n def show_processed_images(self):\n plt.figure(figsize=(10, 10))\n for i in range(25):\n plt.subplot(5, 5, i + 1)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n plt.imshow(self.train_X[i])\n plt.show()\n","sub_path":"[3편] 인간의 시각 처리를 흉내 낸 인공지능 - CNN/[9장] 이미지 학습 기법 활용하기/3_9_2_AI는 창의력을 발휘할 수 있을까 - GAN/03 - CIFAR10/data_reader.py","file_name":"data_reader.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"482164821","text":"\nimport requests\n\n\nclass FacialKeypointsDetectionService(object):\n\n def __init__(self, url, api_key, **kwargs):\n self.url = url\n self.api_key = api_key\n\n def process(self, image):\n pass\n\n def processRequest(self, json, data, headers, params):\n\n result = None\n\n while True:\n\n response = requests.request( 'post', self.url, json = json, data = data, headers = headers, params = params )\n\n if response.status_code == 200 or response.status_code == 201:\n\n if 'content-length' in response.headers and int(response.headers['content-length']) == 0: \n result = None \n elif 'content-type' in response.headers and isinstance(response.headers['content-type'], str): \n if 'application/json' in response.headers['content-type'].lower(): \n result = response.json() if response.content else None \n\n else:\n print( \"Error code: %d\" % ( response.status_code ) )\n print( \"Message: %s\" % ( response.json()['error']['message'] ) )\n\n break\n \n return result\n\n","sub_path":"FinalProject/FacialKeypointsDetectionService.py","file_name":"FacialKeypointsDetectionService.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"160362913","text":"from fuze.containers.enumerator import Enum\n\n\nclass LoggerLevels(Enum):\n DEBUG = 0\n INFO = 1\n WARN = 2\n ERROR = 3\n CRITICAL = 3\n\n\nclass Environments(Enum):\n __ALIASES__ = {\n \"dev\": \"development\",\n \"develop\": \"development\",\n \"local\": \"development\",\n \"stage\": \"staging\",\n \"test\": \"testing\",\n \"prod\": \"production\"\n }\n\n DEVELOPMENT = 0\n STAGING = 1\n TESTING = 2\n PRODUCTION = 3\n\n\nclass BasicTypes(Enum):\n NONE = 0\n INTEGER = 1\n FLOAT = 2\n BOOL = 3\n STRING = 4\n DATE = 5\n DATETIME = 6\n BYTES = 7\n DICT = 8\n LIST = 9\n OBJECT = 10\n\n\n @classmethod\n def reflect(cls, o):\n import datetime\n\n if o is None:\n return BasicTypes.NONE\n\n tbl = getattr(BasicTypes, \"_bases\", None)\n if tbl is None:\n tbl = {\n None: BasicTypes.NONE,\n str: BasicTypes.STRING,\n int: BasicTypes.INTEGER,\n float: BasicTypes.FLOAT,\n bool: BasicTypes.BOOL,\n datetime.date: BasicTypes.DATE,\n datetime.datetime: BasicTypes.DATETIME,\n bytes: BasicTypes.BYTES,\n bytearray: BasicTypes.BYTES,\n dict: BasicTypes.DICT,\n list: BasicTypes.LIST,\n tuple: BasicTypes.LIST,\n object: BasicTypes.OBJECT\n }\n setattr(BasicTypes, \"_bases\", tbl)\n\n if o in tbl:\n return tbl[o]\n\n if isinstance(o, str):\n return BasicTypes.STRING\n\n if isinstance(o, int):\n return BasicTypes.INTEGER\n\n if isinstance(o, bool):\n return BasicTypes.BOOL\n\n if isinstance(o, datetime.date):\n return BasicTypes.DATE\n\n if isinstance(o, datetime.datetime):\n return BasicTypes.DATETIME\n\n if isinstance(o, float):\n return BasicTypes.FLOAT\n\n if isinstance(o, dict):\n return BasicTypes.DICT\n\n if isinstance(o, (list, tuple)):\n return BasicTypes.LIST\n\n if isinstance(o, (bytes, bytearray)):\n return BasicTypes.BYTES\n\n return BasicTypes.OBJECT\n\n @classmethod\n def to_str(cls, o, type=None):\n import simplejson as __json__\n\n if type is None:\n if o is None:\n return \"\"\n\n type = BasicTypes.reflect(o)\n\n if type == BasicTypes.NONE:\n return \"\"\n\n if type == BasicTypes.STRING or BasicTypes.INTEGER or BasicTypes.FLOAT:\n return str(o)\n\n if type == BasicTypes.BOOL:\n return \"true\" if o else \"false\"\n\n if type == BasicTypes.DATE:\n return o.strftime(\"%Y-%m-%d\")\n\n if type == BasicTypes.DATETIME:\n return o.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n if type == BasicTypes.OBJECT:\n if hasattr(o, \"__dict__\"):\n o = o.__dict__\n type = BasicTypes.DICT\n\n if type == BasicTypes.DICT or type == BasicTypes.LIST:\n return __json__.dumps(o, check_circular=False, sort_keys=True)\n\n return str(o)\n\n @classmethod\n def cast(cls, type, value, **kwds):\n import simplejson as __json__\n from fuze import date\n\n assert isinstance(type, BasicTypes), \"The type parameter is not a valid BasicType enum.\"\n\n o = value\n\n if type == BasicTypes.NONE:\n return None\n\n if not isinstance(o, str):\n o = BasicTypes.to_str(o)\n\n if BasicTypes.STRING:\n return o\n\n silent = True if \"default\" in kwds else False\n default = kwds.get(\"default\")\n\n if type == BasicTypes.INTEGER:\n try:\n return int(o)\n except Exception as ex:\n if silent:\n return default\n raise\n\n if type == BasicTypes.FLOAT:\n try:\n return float(o)\n except Exception as ex:\n if silent:\n return default\n raise\n\n if type == BasicTypes.BOOL:\n try:\n return True if o.strip().lower() in [\"true\", \"t\", \"1\", \"yes\", \"y\"] else False\n except Exception as ex:\n if silent:\n return default\n raise\n\n if type == BasicTypes.DATE or type == BasicTypes.DATETIME:\n try:\n return date.parse(o)\n except Exception as ex:\n if silent:\n return default\n raise\n\n # if type == BasicTypes.BYTES:\n # raise NotImplementedError()\n\n if type == BasicTypes.DICT or type == BasicTypes.LIST:\n try:\n return __json__.loads(o)\n except Exception as ex:\n if silent:\n return default\n raise\n\n raise NotImplementedError()\n\n# class FileTypes(Enum):\n# Image = 1\n# Document = 2\n# Audio = 3\n# Video = 4\n# Archive = 5\n# Application = 6\n\n# class ActionTypes(Enum):\n# Create = 1\n# Update = 2\n# Delete = 3\n# View = 4\n# Login = 5\n# Logout = 6\n","sub_path":"fuze/constants/enums/generic.py","file_name":"generic.py","file_ext":"py","file_size_in_byte":5219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"315542625","text":"from lxml import etree\nfrom selenium import webdriver\nfrom time import sleep\nimport pandas as pd\nimport numpy as np\nimport re\nimport csv\n\ncsvfile = open('data_jd.csv', 'w', encoding='utf-8', newline='')\nwr = csv.writer(csvfile)\nwr.writerow(['title', 'sells', 'price'])\n\nbrow = webdriver.Chrome()\n# https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq=%E6%89%8B%E6%9C%BA&psort=3&page=1&s=61&page=1\nbrow.get('https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq=%E6%89%8B%E6%9C%BA&psort=3&click=0')\nfor page in range(1, 3): # 爬取100页\n print('it is page:',page)\n js = 'document.documentElement.scrollTop = document.documentElement.scrollHeight * %f' % 0.9\n brow.execute_script(js)\n sleep(2)\n js = 'document.documentElement.scrollTop = document.documentElement.scrollHeight * %f' % 0.9\n brow.execute_script(js)\n sleep(2)\n html_source = brow.page_source # 抽取网页源码\n dom = etree.HTML(html_source) # 解析为DOM型\n title_list = dom.xpath('//*[@id=\"J_goodsList\"]/ul/li/div/div[4]/a/em/text()[1]')\n # //*[@id=\"J_goodsList\"]/ul/li[13]/div/div[4]/a/em/text()[1]\n # //*[@id=\"J_goodsList\"]/ul/li[1]/div/div[4]/a/em/text()[1]\n \n # //*[@id=\"J_goodsList\"]/ul/li[10]/div/div[4]/a/em/text()[1]\n # //*[@id=\"J_goodsList\"]/ul/li[60]/div/div[4]/a/em/text()[1]\n sells_list = dom.xpath('//*[@id=\"J_goodsList\"]/ul/li/div/div[5]/strong/a/text()')\n # //*[@id=\"J_goodsList\"]/ul/li[26]/div/div[5]/strong\n # //*[@id=\"J_goodsList\"]/ul/li[{}]/div/div[5]/text()\n price_list = dom.xpath('//*[@id=\"J_goodsList\"]/ul/li/div/div[3]/strong/i/text()')\n # //*[@id=\"J_goodsList\"]/ul/li/div/div[3]/strong/i\n # //*[@id=\"J_goodsList\"]/ul/li[2]/div/div[3]/strong/i\n # price_per_list = dom.xpath('//*[@id=\"content\"]/div[1]/ul/li/div[1]/div[6]/div[2]/span/text()')\n print('title_list len :',len(title_list))\n print('sells_list len :',len(sells_list))\n print('price_list len :',len(price_list))\n for i in range(min(min(len(title_list),len(sells_list)),len(price_list))):\n if(title_list[i] and sells_list[i] and price_list[i]): # 判断不为空\n # space = re.findall('(\\d+.?\\d+)平米',info_list[i])\n # price_per = re.findall('(\\d+)元/平米',price_per_list[i])\n # year = re.findall('(\\d+)年建',info_list[i])\n # if not year:\n # print('there is no year with info:',info_list[i])\n # else:\n wr.writerow([title_list[i], sells_list[i], price_list[i]])\n # next_page = brow.find_element_by_link_title('使用方向键右键也可翻到下一页哦!')\n next_page = brow.find_element_by_class_name('pn-next')\n # 下一页>\n # next_page = brow.find_element_by_link_text('下一页')\n next_page.click()\n # print('++++++++++++++',next_page)\n sleep(3)\nbrow.quit()\ncsvfile.close()","sub_path":"京东/jd.py","file_name":"jd.py","file_ext":"py","file_size_in_byte":3060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"446753796","text":"import logging\n\nimport six\nfrom Crypto import Random\nfrom Crypto.Cipher import AES\nfrom Crypto.Util.py3compat import bchr, bord\nfrom botocore.exceptions import ClientError\n\nfrom spacel.security.payload import EncryptedPayload\n\nlogger = logging.getLogger('spacel.security.kms_crypt')\n\nBLOCK_SIZE = AES.block_size\nCIPHER_MODE = AES.MODE_CBC\n\n\nclass KmsCrypto(object):\n \"\"\"\n Uses KMS to encrypt/decrypt data with AES-256.\n \"\"\"\n\n def __init__(self, clients, kms_key):\n self._kms_key = kms_key\n self._clients = clients\n self._random = Random.new()\n\n def encrypt(self, app_region, plaintext, create_key=True):\n \"\"\"\n Encrypt data for an application.\n :param app_region: SpaceAppRegion.\n :param plaintext: Plaintext blob.\n :param create_key: Create key if missing (else fail).\n :return: EncryptedPayload.\n \"\"\"\n region = app_region.region\n # Get DEK:\n logger.debug('Fetching fresh data key...')\n try:\n alias_name = self._kms_key.get_key_alias(app_region)\n kms = self._clients.kms(region)\n data_key = kms.generate_data_key(KeyId=alias_name,\n KeySpec='AES_256')\n except ClientError as e:\n e_message = e.response['Error'].get('Message', '')\n if create_key and 'is not found' in e_message:\n # Key not found, create and try again:\n self._kms_key.create_key(app_region)\n return self.encrypt(app_region, plaintext)\n raise e\n\n # Encode and pad data:\n encoding = 'bytes'\n if isinstance(plaintext, six.string_types):\n encoding = 'utf-8'\n if six.PY3: # pragma: no cover\n plaintext = bytes(plaintext, encoding)\n else: # pragma: no cover\n plaintext = plaintext.encode(encoding)\n pad_length = BLOCK_SIZE - (len(plaintext) % BLOCK_SIZE)\n padded = plaintext + (pad_length * bchr(pad_length))\n logger.debug('Padded %s %s to %s.', len(plaintext), encoding,\n len(padded))\n\n logger.debug('Encrypting data with data key...')\n iv = self._random.read(BLOCK_SIZE)\n\n cipher = AES.new(data_key['Plaintext'], CIPHER_MODE, iv)\n ciphertext = cipher.encrypt(padded)\n\n encrypted_key = data_key['CiphertextBlob']\n return EncryptedPayload(iv, ciphertext, encrypted_key, region, encoding)\n\n def decrypt_payload(self, payload):\n \"\"\"\n Decrypt an encrypted payload.\n :param payload: EncryptedPayload.\n :return: Decrypted payload.\n \"\"\"\n return self.decrypt(payload.iv, payload.ciphertext, payload.key,\n payload.key_region, payload.encoding)\n\n def decrypt(self, iv, ciphertext, key, key_region, encoding):\n \"\"\"\n Decrypt.\n :param iv: Encryption IV.\n :param ciphertext: Ciphertext.\n :param key: Encrypted data key.\n :param key_region: Data key region (KMS).\n :param encoding: Encoding\n :return: Decrypted payload.\n \"\"\"\n # Decrypt DEK:\n logger.debug('Decrypting data key...')\n kms = self._clients.kms(key_region)\n decrypted_key = kms.decrypt(CiphertextBlob=key)\n\n # Decrypt data:\n cipher = AES.new(decrypted_key['Plaintext'], CIPHER_MODE, iv)\n plaintext = cipher.decrypt(ciphertext)\n\n # Remove pad:\n pad_length = bord(plaintext[-1])\n actual_pad = plaintext[-pad_length:]\n expected_pad = bchr(pad_length) * pad_length\n if actual_pad != expected_pad:\n raise ValueError('Incorrect padding')\n unpadded = plaintext[:-pad_length]\n\n if encoding == 'bytes': # pragma: no cover\n return unpadded\n if six.PY3: # pragma: no cover\n return str(unpadded, encoding)\n else: # pragma: no cover\n return unpadded.decode(encoding)\n","sub_path":"src/spacel/security/kms_crypt.py","file_name":"kms_crypt.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"73300599","text":"n, s = map(int, input().split())\nallVals = []\nfor i in range(n):\n name, val = input().split()\n allVals.append((int(val), name))\nsortedVals = sorted(allVals)\nsortedVals.reverse()\nanswer = []\ntotal = 0\nfor val, name in sortedVals:\n if(total + val <= s):\n answer.append(name)\n total += val\nif total == s:\n print(len(answer))\n print(\"\\n\".join(answer))\nelse:\n print(0)\n","sub_path":"Virtual/NAC_Practice/2021_Regionals_Practice_1/i.py","file_name":"i.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"572585311","text":"'''\r\nProblem 6:\r\nPRINT THE BELOW MENTIONED PATTERN FOR ANY \"N\" VALUE. WHERE \"N\" INDICATES NO.OF ROWS.\r\nInput Format\r\nA SINGLE INTEGER DENOTING N VALUE\r\nConstraints\r\n1<=N<=100\r\nOutput Format\r\nPATTERN AS SHOWN IN SAMPLE TEST CASE\r\nSample Input 0\r\n5\r\nSample Output 0\r\n1\r\n 2\r\n 3\r\n 4\r\n 5\r\n'''\r\n\r\nn=int(input())\r\nfor index in range(n):\r\n print(' '*index,(index+1))\r\n","sub_path":"number pattern.py","file_name":"number pattern.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"488610149","text":"# -*- coding: utf-8 -*-\n###\n# (C) Copyright (2012-2019) Hewlett Packard Enterprise Development LP\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\n# THE SOFTWARE.\n###\n\nfrom pprint import pprint\nfrom hpOneView.oneview_client import OneViewClient\nfrom config_loader import try_load_from_file\n\nconfig = {\n \"ip\": \"\",\n \"credentials\": {\n \"userName\": \"\",\n \"password\": \"\"\n }\n}\n\n# Try load config from a file (if there is a config file)\nconfig = try_load_from_file(config)\noneview_client = OneViewClient(config)\nserver_hardware_types = oneview_client.server_hardware_types\n\n# Get the first 10 records, sorting by name descending\nprint(\"\\nGet the first 10 server hardware types, sorting by name descending, filtering by name\")\nserver_hardware_types_all = server_hardware_types.get_all(0, 10, sort='name:descending')\npprint(server_hardware_types_all, depth=2)\n\n# Get all, with defaults\nprint(\"\\nGet all server hardware types\")\nserver_hardware_types_all = server_hardware_types.get_all()\npprint(server_hardware_types_all, depth=3)\n\n# Get by uri\nprint(\"\\nGet a Server Hardware Type by uri\")\nserver_hardware_type_by_uri = server_hardware_types.get_by_uri(server_hardware_types_all[0][\"uri\"])\npprint(server_hardware_type_by_uri.data, depth=2)\n\n# Get by name and update\nprint(\"\\nGet a Server Hardware Type by name\")\nserver_hardware_type = server_hardware_types.get_by_name(\"SY 480 Gen9 1\")\npprint(server_hardware_type.data, depth=2)\nupdate = {\n 'description': \"Updated Description\"\n}\nserver_hardware_type.update(update)\nprint(\"\\nServer Hardware type '{}' updated: \\n 'description': '{}'\".format(\n server_hardware_type.data['name'],\n server_hardware_type.data['description']))\n","sub_path":"examples/server_hardware_types.py","file_name":"server_hardware_types.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"604191715","text":"\"\"\"\nImplementation of Train Data Service.\n\"\"\"\n\nimport json\n\nimport cherrypy\n\n\nclass TrainDataService:\n def __init__(self, json_data):\n self.trains = json.loads(json_data)\n\n @cherrypy.expose()\n @cherrypy.tools.json_out()\n def data_for_train(self, train_id):\n with cherrypy.HTTPError.handle(KeyError, 404):\n return self.trains[train_id]\n\n @cherrypy.expose()\n @cherrypy.tools.json_in()\n @cherrypy.tools.json_out()\n def reserve(self):\n reservation = cherrypy.request.json\n train_id = reservation[\"train_id\"]\n seats = reservation[\"seats\"]\n booking_reference = reservation[\"booking_reference\"]\n\n with cherrypy.HTTPError.handle(KeyError, 400, f\"Train not found: {train_id}.\"):\n train = self.trains[train_id]\n\n for seat in seats:\n with cherrypy.HTTPError.handle(KeyError, 400, f\"Seat not found: {seat}.\"):\n existing_booking_reference = train[\"seats\"][seat][\"booking_reference\"]\n\n if (\n existing_booking_reference\n and existing_booking_reference != booking_reference\n ):\n return f\"Already booked with reference: {existing_booking_reference}.\"\n\n for seat in seats:\n train[\"seats\"][seat][\"booking_reference\"] = booking_reference\n\n return self.data_for_train(train_id)\n\n @cherrypy.expose()\n @cherrypy.tools.json_out()\n def reset(self, train_id):\n with cherrypy.HTTPError.handle(KeyError, 404):\n train = self.trains[train_id]\n\n for seat in train[\"seats\"].values():\n seat[\"booking_reference\"] = \"\"\n\n return self.data_for_train(train_id)\n","sub_path":"train_reservation/train_data_service.py","file_name":"train_data_service.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"484639287","text":"# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.\n# This product includes software developed at Datadog (https://www.datadoghq.com/).\n# Copyright 2019-Present Datadog, Inc.\nfrom __future__ import annotations\n\n\nfrom datadog_api_client.model_utils import (\n ModelComposed,\n cached_property,\n)\n\n\nclass ServiceDefinitionSchema(ModelComposed):\n def __init__(self, **kwargs):\n \"\"\"\n Service definition schema.\n\n :param contact: Contact information about the service.\n :type contact: ServiceDefinitionV1Contact, optional\n\n :param extensions: Extensions to V1 schema.\n :type extensions: {str: (bool, date, datetime, dict, float, int, list, str, none_type,)}, optional\n\n :param external_resources: A list of external links related to the services.\n :type external_resources: [ServiceDefinitionV1Resource], optional\n\n :param info: Basic information about a service.\n :type info: ServiceDefinitionV1Info\n\n :param integrations: Third party integrations that Datadog supports.\n :type integrations: ServiceDefinitionV1Integrations, optional\n\n :param org: Org related information about the service.\n :type org: ServiceDefinitionV1Org, optional\n\n :param schema_version: Schema version being used.\n :type schema_version: ServiceDefinitionV1Version\n\n :param tags: A set of custom tags.\n :type tags: [str], optional\n\n :param contacts: A list of contacts related to the services.\n :type contacts: [ServiceDefinitionV2Contact], optional\n\n :param dd_service: Unique identifier of the service. Must be unique across all services and is used to match with a service in Datadog.\n :type dd_service: str\n\n :param dd_team: Experimental feature. A Team handle that matches a Team in the Datadog Teams product.\n :type dd_team: str, optional\n\n :param docs: A list of documentation related to the services.\n :type docs: [ServiceDefinitionV2Doc], optional\n\n :param links: A list of links related to the services.\n :type links: [ServiceDefinitionV2Link], optional\n\n :param repos: A list of code repositories related to the services.\n :type repos: [ServiceDefinitionV2Repo], optional\n\n :param team: Team that owns the service.\n :type team: str, optional\n\n :param application: Identifier for a group of related services serving a product feature, which the service is a part of.\n :type application: str, optional\n\n :param description: A short description of the service.\n :type description: str, optional\n\n :param lifecycle: The current life cycle phase of the service.\n :type lifecycle: str, optional\n\n :param tier: Importance of the service.\n :type tier: str, optional\n \"\"\"\n super().__init__(kwargs)\n\n @cached_property\n def _composed_schemas(_):\n # we need this here to make our import statements work\n # we must store _composed_schemas in here so the code is only run\n # when we invoke this method. If we kept this at the class\n # level we would get an error because the class level\n # code would be run when this module is imported, and these composed\n # classes don't exist yet because their module has not finished\n # loading\n from datadog_api_client.v2.model.service_definition_v1 import ServiceDefinitionV1\n from datadog_api_client.v2.model.service_definition_v2 import ServiceDefinitionV2\n from datadog_api_client.v2.model.service_definition_v2_dot1 import ServiceDefinitionV2Dot1\n\n return {\n \"oneOf\": [\n ServiceDefinitionV1,\n ServiceDefinitionV2,\n ServiceDefinitionV2Dot1,\n ],\n }\n","sub_path":"src/datadog_api_client/v2/model/service_definition_schema.py","file_name":"service_definition_schema.py","file_ext":"py","file_size_in_byte":3872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"254526789","text":"\nimport pandas as pd\nimport numpy as np\nimport re\n\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import PorterStemmer \n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\n\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\n\ndata = pd.read_csv('/content/drive/My Drive/datascience/Machine Learning/Board Infinity/portfolio/news-data.csv')\ndata.head()\n\n# le = LabelEncoder()\n# data['category'] = le.fit_transform(data['category'])\n\nnltk.download('stopwords')\nall_stopwords = set(stopwords.words('english'))\n\ndef clean_text(text):\n \"\"\"\n text: a string \n return: modified initial string\n \"\"\"\n text = re.sub('[^a-zA-Z]', ' ', text)\n text = text.lower()\n text = text.split()\n stemmer = PorterStemmer()\n text = ' '.join([stemmer.stem(word)for word in text if word not in all_stopwords])\n return text\n\ndata['text'] = data['text'] .apply(clean_text)\n\ndata.head()\n\narticle = data['text']\nlabel = data['category']\n\ntrain_X, X_test, train_y, y_test = train_test_split(article, label, test_size = 0.2, random_state = 0)\nX_train, X_val, y_train, y_val = train_test_split(train_X, train_y, test_size = 0.15, random_state = 0)\n\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_val.shape)\nprint(y_val.shape)\nprint(X_test.shape)\nprint(y_test.shape)\n\nnum_words = 2000\noov_token = ''\npad_type = 'post'\ntrunc_type = 'post'\n\n# Tokenize our training data\ntokenizer = Tokenizer(num_words=num_words, oov_token=oov_token)\ntokenizer.fit_on_texts(X_train)\n\n# Get our training data word index\nword_index = tokenizer.word_index\n\n# Encode training data sentences into sequences\ntrain_sequences = tokenizer.texts_to_sequences(X_train)\n\n# Get max training sequence length\nmaxlength = max([len(x) for x in train_sequences])\n\n# Pad the training sequences\ntrain_padded = pad_sequences(train_sequences, padding=pad_type, truncating=trunc_type, maxlen=maxlength)\n\n# Output the results of our work\nprint(\"Word index:\\n\", word_index)\nprint(\"\\nTraining sequences:\\n\", train_sequences)\nprint(\"\\nPadded training sequences:\\n\", train_padded)\nprint(\"\\nPadded training shape:\", train_padded.shape)\nprint(\"Training sequences data type:\", type(train_sequences))\nprint(\"Padded Training sequences data type:\", type(train_padded))\n\n# for x, y in zip(X_train, train_padded):\n# print('{} -> {}'.format(x, y))\n\n# print(\"\\nWord index (for reference):\", word_index)\n\n# tokenizing validation data\nvalidation_sequences = tokenizer.texts_to_sequences(X_val)\nvalidation_padded = pad_sequences(validation_sequences, padding=pad_type, truncating=trunc_type, maxlen=maxlength)\n\nprint(\"Validation sequences:\\n\", validation_sequences)\nprint(\"\\nPadded validation sequences:\\n\", validation_padded)\nprint(\"\\nPadded validation shape:\",validation_padded.shape)\n\n# tokenizing test data\ntest_sequences = tokenizer.texts_to_sequences(X_test)\ntest_padded = pad_sequences(test_sequences, padding=pad_type, truncating=trunc_type, maxlen=maxlength)\n\nprint(\"Testing sequences:\\n\", test_sequences)\nprint(\"\\nPadded testing sequences:\\n\", test_padded)\nprint(\"\\nPadded testing shape:\",test_padded.shape)\n\nprint(set(label))\n\nlabel_tokenizer = Tokenizer()\nlabel_tokenizer.fit_on_texts(y_train)\n\ntraining_label_seq = np.array(label_tokenizer.texts_to_sequences(y_train))\nvalidation_label_seq = np.array(label_tokenizer.texts_to_sequences(y_val))\ntesting_label_seq = np.array(label_tokenizer.texts_to_sequences(y_test))\n\nprint(training_label_seq[0])\nprint(training_label_seq[1])\nprint(training_label_seq[2])\nprint(training_label_seq.shape)\nprint()\nprint(validation_label_seq[0])\nprint(validation_label_seq[1])\nprint(validation_label_seq[2])\nprint(validation_label_seq.shape)\nprint()\nprint(testing_label_seq[0])\nprint(testing_label_seq[1])\nprint(testing_label_seq[2])\nprint(testing_label_seq.shape)\n\nmodel = tf.keras.models.Sequential()\nmodel.add(tf.keras.layers.Dense(10, activation='relu'))\nmodel.add(tf.keras.layers.Dense(10, activation='relu'))\nmodel.add(tf.keras.layers.Dense(5, activation='softmax'))\nmodel.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy' , metrics = ['accuracy'])\n\nnum_epochs = 10\ntrain_pred = model.fit(X_train, y_train, epochs=num_epochs, validation_data=(X_val, y_val), verbose=2)\n\n","sub_path":"Model Selection/6. deep_learning_models.py","file_name":"6. deep_learning_models.py","file_ext":"py","file_size_in_byte":4365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"259902774","text":"#! /usr/bin/env python\nimport requests\nimport json\nfrom templates import current_id\n\ndef curate(file_name,file_title,template_id,host,user,pswd,cert=None,content=None):\n if content is None:\n with open(file_name, 'r') as f: \n content = f.read()\n data=dict()\n data['content']=[content]\n data['schema']=[template_id]\n data['title']=[file_title]\n \n url = host + \"/rest/curate\"\n r = requests.post(url, data=data, auth=(user, pswd), verify=cert)\n if int(r.status_code)==201:\n return \"created\" #int(r.status_code)\n else:\n return r.json()\n\ndef curate_as(file_name,file_title,host,user,pswd,cert=None,filename=None,template_title=None,content=None):\n template_id = current_id(host,user,pswd,cert=cert,filename=filename,title=template_title)\n return curate(file_name,file_title,template_id,host,user,pswd,cert=cert,content=content)\n","sub_path":"libs/mdcs/curate.py","file_name":"curate.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"139072109","text":"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\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\"\"\"Utility functions for detection inference.\"\"\"\nfrom __future__ import division\n\nimport tensorflow as tf\nimport numpy as np\nimport json\n\n#sys.path.append('/home/wangli/code/projects/UVA/video-recognition-ae/yolo/darkflow/darkflow/')\nfrom ..cython_utils.cy_yolo2_findboxes import box_constructor\n\nfrom object_detection.core import standard_fields\n\nimport pdb\ndef build_input(meta, tfrecord_paths):\n \"\"\"Builds the graph's input.\n\n Args:\n tfrecord_paths: List of paths to the input TFRecords\n\n Returns:\n serialized_example_tensor: The next serialized example. String scalar Tensor\n image_tensor: The decoded image of the example. Uint8 tensor,\n shape=[1, None, None,3]\n \"\"\"\n filename_queue = tf.train.string_input_producer(\n tfrecord_paths, shuffle=False, num_epochs=1)\n\n tf_record_reader = tf.TFRecordReader()\n _, serialized_example_tensor = tf_record_reader.read(filename_queue)\n features = tf.parse_single_example(\n serialized_example_tensor,\n features={\n standard_fields.TfExampleFields.image_encoded:\n tf.FixedLenFeature([], tf.string),\n })\n encoded_image = features[standard_fields.TfExampleFields.image_encoded]\n image_tensor = tf.image.decode_image(encoded_image, channels=3)\n image_tensor_float = tf.image.convert_image_dtype(image_tensor, tf.float32)\n image_tensor_float.set_shape([None, None, 3])\n h, w, c = meta['inp_size']\n image_tensor_float = tf.image.resize_images(image_tensor_float, [h,w])\n image_tensor_float = tf.expand_dims(image_tensor_float, 0)\n\n return serialized_example_tensor, image_tensor_float\n\n\ndef build_meta( meta_file):\n \"\"\"\n return a meta\n \"\"\"\n with open(meta_file, 'r') as fp:\n meta = json.load(fp)\n return meta\n\ndef build_inference_graph(image_tensor, inference_graph_path):\n \"\"\"Loads the inference graph and connects it to the input image.\n\n Args:\n image_tensor: The input image. uint8 tensor, shape=[1, None, None, 3]\n inference_graph_path: Path to the inference graph with embedded weights\n\n Returns:\n detected_boxes_tensor: Detected boxes. Float tensor,\n shape=[num_detections, 4]\n detected_scores_tensor: Detected scores. Float tensor,\n shape=[num_detections]\n detected_labels_tensor: Detected labels. Int64 tensor,\n shape=[num_detections]\n \"\"\"\n with tf.gfile.Open(inference_graph_path, 'rb') as graph_def_file:\n graph_content = graph_def_file.read()\n graph_def = tf.GraphDef()\n graph_def.MergeFromString(graph_content)\n\n tf.import_graph_def(\n graph_def, name='', input_map={'input': image_tensor})\n\n g = tf.get_default_graph()\n\n detected_boxes_tensor = tf.squeeze(\n g.get_tensor_by_name('output:0'), 0)\n\n return detected_boxes_tensor\n\ndef process_box(meta, b, h, w, threshold):\n max_indx = np.argmax(b.probs)\n max_prob = b.probs[max_indx]\n label = meta['labels'][max_indx]\n #pdb.set_trace()\n if max_prob > threshold:\n left = int ((b.x - b.w/2.) * w)\n right = int ((b.x + b.w/2.) * w)\n top = int ((b.y - b.h/2.) * h)\n bot = int ((b.y + b.h/2.) * h)\n if left < 0 : left = 0\n if right > w - 1: right = w - 1\n if top < 0 : top = 0\n if bot > h - 1: bot = h - 1\n mess = '{}'.format(label)\n #return (left, right, top, bot, mess, max_indx, max_prob)\n return (top, left, bot, right, mess, max_indx, max_prob)\n return None\n\ndef yolo2googleout( meta, category_index, yolo_out, threshold=0.3):\n \"\"\"convert out to desired format\n :param feed_dict:\n :param img_shape:\n :return: out\n :return: detection_out\n \"\"\"\n out = yolo_out.copy()\n boxes = box_constructor(meta, out)\n h, w, c = meta['inp_size']\n out = [process_box(meta, b, h, w, threshold) for b in boxes]\n out = [out1 for out1 in out if out1] #remove empty boxes\n # out format: [[left, right, top, bot, mess, max_indx, confidence], ...]\n #pdb.set_trace()\n try:\n detection_out = np.array([norm_boxes(meta, out1[:4]) for out1 in out])\n #pdb.set_trace()\n except ValueError:\n #pdb.set_trace()\n detection_out = []\n scores = np.array([out1[-1] for out1 in out])\n messes = [out1[-3] for out1 in out]\n ## the id of objects in coco is different between google detection and yolo detection\n ## change the id of yolo to google expression through category_index\n classes = []\n for mess in messes:\n c = [category['id'] for key, category in category_index.items() if category['name'] == mess]\n if c:\n classes.append(c[0])\n else:\n classes.append(0)\n\n classes = np.array(classes)\n classes = classes.reshape(-1,)\n #classes = np.array([out1[-2] for out1 in out])\n return detection_out, scores, classes #messes\n\ndef to_tlbr(tlwh):\n \"\"\"Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,\n `(top left, bottom right)`.\n \"\"\"\n ret = np.array(tlwh)\n ret[2:] += ret[:2]\n return ret\n\ndef norm_boxes(meta, boxes):\n \"\"\"Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,\n `(top left, bottom right)`.\n \"\"\"\n h, w, c = meta['inp_size']\n ret = np.array(boxes).astype(float)\n ret[0] = ret[0]/h\n ret[2] = ret[2]/h\n ret[1] = ret[1]/w\n ret[3] = ret[3]/w\n #pdb.set_trace()\n return ret\n\ndef infer_detections_and_add_to_example(\n meta, category_index, serialized_example_tensor, detected_boxes_tensor, discard_image_pixels):\n \"\"\"Runs the supplied tensors and adds the inferred detections to the example.\n\n Args:\n serialized_example_tensor: Serialized TF example. Scalar string tensor\n detected_boxes_tensor: Detected boxes. Float tensor,\n shape=[num_detections, 4]\n detected_scores_tensor: Detected scores. Float tensor,\n shape=[num_detections]\n detected_labels_tensor: Detected labels. Int64 tensor,\n shape=[num_detections]\n discard_image_pixels: If true, discards the image from the result\n Returns:\n The de-serialized TF example augmented with the inferred detections.\n \"\"\"\n tf_example = tf.train.Example()\n (serialized_example, detected_items) = tf.get_default_session().run([\n serialized_example_tensor, detected_boxes_tensor\n ])\n #pdb.set_trace()\n detected_boxes, detected_scores, detected_classes = yolo2googleout(meta, category_index, detected_items)\n #pdb.set_trace()\n\n tf_example.ParseFromString(serialized_example)\n feature = tf_example.features.feature\n if(detected_boxes != []):\n try:\n detected_boxes = detected_boxes.T\n feature[standard_fields.TfExampleFields.\n detection_score].float_list.value[:] = detected_scores\n feature[standard_fields.TfExampleFields.\n detection_bbox_ymin].float_list.value[:] = detected_boxes[0]\n feature[standard_fields.TfExampleFields.\n detection_bbox_xmin].float_list.value[:] = detected_boxes[1]\n feature[standard_fields.TfExampleFields.\n detection_bbox_ymax].float_list.value[:] = detected_boxes[2]\n feature[standard_fields.TfExampleFields.\n detection_bbox_xmax].float_list.value[:] = detected_boxes[3]\n feature[standard_fields.TfExampleFields.\n detection_class_label].int64_list.value[:] = detected_classes\n except TypeError:\n tf.logging.info(\" a TypeError\")\n #pdb.set_trace()\n\n #print(detected_classes)\n #print(detected_scores)\n #print(detected_boxes.T)\n\n if discard_image_pixels:\n del feature[standard_fields.TfExampleFields.image_encoded]\n\n return tf_example\n\n","sub_path":"research/object_detection/inference/yolo_detection_inference.py","file_name":"yolo_detection_inference.py","file_ext":"py","file_size_in_byte":8304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"348342899","text":"from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('connectors.connector_questionnaire',\n url(r'^upload/', 'connector_questionnaire.upload'),\n url(r'^auth/grant/', 'auth.grant'),\n url(r'^auth/token/', 'auth.token'),\n url(r'^auth/refresh_token/', 'auth.refresh_token'),\n# url(r'^auth/revoke/', 'auth.revoke'),\n# url(r'^auth/sync/', 'auth.sync'),\n)\n","sub_path":"sensible_data_service/connectors/connector_questionnaire/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"229776424","text":"# Accept number from user return its power\r\n#input : 2 4 \r\n#ouput : 16\r\ndef DisplayPower(no1 , no2):\r\n \r\n iCnt = 1 \r\n iMult = 1\r\n #for i in range(no2): # no1 = 2 , no2 = 4\r\n #iMult = iMult * no1\r\n #return iMult\r\n \r\n while(iCnt <= no2):\r\n iMult = iMult * no1\r\n iCnt = iCnt +1\r\n return iMult\r\n \r\n \r\ndef main():\r\n \r\n print(\"Enter the number\")\r\n value1 = int(input())\r\n \r\n print(\"Enter the number\")\r\n value2 = int(input())\r\n print(\"**************************\") \r\n \r\n bret = DisplayPower(value1,value2)\r\n print(\"Power is : \",bret)\r\n \r\n print(\"**************************\") \r\n\r\nif __name__==\"__main__\":\r\n main()","sub_path":"PowerofNo.py","file_name":"PowerofNo.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"449624827","text":"import cv2\nimport sys\nfrom ctypes import *\n\nlibface = CDLL('./libfacedetection.so')\n\nresult_buffer = create_string_buffer(0x20000)\nresults = 0\n\nimage = cv2.imread(sys.argv[1])\nif image is None:\n print('Can not load the image file {}.'.format(sys.argv[1]))\n sys.exit()\n\n'''\n# 为解决图像偏右问题,根据libfacedetection的要求,将图像按宽度裁剪为64的倍数\nw, h = image.shape[1], image.shape[0]\nratio = int(w / 64) * 64 / w\nimg = image[0:int(h * ratio), 0:int(w * ratio)]\nimg = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n'''\n\nimg = image\n\n# 指定函数输出结果为指针类型\npResults = cast(results, POINTER(c_int))\n\n# libface._Z14facedetect_cnnPhS_iii.argtypes = [c_char, c_char, c_int, c_int, c_int]\nlibface._Z14facedetect_cnnPhS_iii.restype = POINTER(c_int)\n\n#\n# libfacedetection编译后,so中导出函数名称会有变化,通过 dm -D 命令找到facedetect_cnn的函数入口\n# $ nm -D libfacedetection.so | grep facedetect_cnn\n# 0000b11c T _Z14facedetect_cnnPhS_iii\n#\n# facedetectcnn.h 中的函数原型定义\n# int * facedetect_cnn(unsigned char * result_buffer, //buffer memory for storing face detection results, !!its size must be 0x20000 Bytes!!\n# unsigned char * rgb_image_data, int width, int height, int step); //input image, it must be BGR (three channels) insteed of RGB image!\n#\n# 结果缓存 result_buffer 、图像数据 rgb_image_data 必须用传址方式送入函数,采用ctypes的byref函数取得引用地址\n# image为numpy.narray类型,byref会引发无法自动转换类型错误,需手动指定类型强制转换:byref(image.ctypes.data_as(ctypes.POINTER(ctypes.c_char)).contents)\n#\npResults = libface._Z14facedetect_cnnPhS_iii(byref(result_buffer), byref(img.ctypes.data_as(POINTER(c_char)).contents), img.shape[1], img.shape[0], img.shape[1]*3)\n\n# pResults为c_int指针,用pResults.contents.value取得其值\nprint('{} faces detected.'.format(pResults.contents.value if pResults else 0))\n\n# result_buffer数据格式为:\n# 第0-3字节,为识别到的人脸数量\n# 第4字节以后,均为识别结果,每个结果占用空间为142*2字节\n# 每个结果空间内,内容分别为:x, y, w, h, confidence, angle,每项信息占2字节\nstart_pos = 4\noffset = 142*2\nfor x in range(pResults.contents.value):\n # 每一个组结果的起始位置为:初始位置+偏移量*第几个结果\n pos = start_pos + offset * x\n x,y,w,h,c,a = [i for i in memoryview(result_buffer[pos:pos+12]).cast('H')]\n\n print('face_rect=[{}, {}, {}, {}], confidence={}, angle={}'.format(x, y, w, h, c, a))\n image=cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\ncv2.imshow(\"Image\", image)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n","sub_path":"libfacedetection/libface_image.py","file_name":"libface_image.py","file_ext":"py","file_size_in_byte":2738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"541299152","text":"'''\nVery simple boolean program that checks to see if an integer's value is\nequal to the sum of its character values when written in words, where a\nsingle character's value is determined through a mapped sequence.\n\nIterating through the values 0 to 999 inclusive, True solutions are:\n\n- 251 (two hundred and fifty one) is equivalent to its value using the\n\tdefault map\n- 259 (two hundred and fifty nine) is equivalent to its value using the\n\tdefault map\n- 261 (two hundred and sixty one) is equivalent to its value using the\n\tmap which starts at zero (zero_map)\n- 279 (two hundred and seventy nine) is equivalent to its value using\n\tthe map which starts at zero (zero_map)\n- there are no results when using double_map, fib_map, or bin_map\n\nThe lack of results for double_map was somewhat interesting, but was\nexpected for fib_map and bin_map. This is because these sequences grow\nvery quickly. I don't know how to formally prove this (which would be\ncool), but it can be argued that the values in these sequences will\ngrow faster than the numbers' values, and so there are no more\nsolutions to be found unless there exists a number > 999 which has an\nincredibly large name.\n'''\n\nfrom num2words import num2words as as_words\n\ndefault_map = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,\n\t\t\t\t\t'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,\n\t\t\t\t\t's':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}\n\nzero_map = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,\n\t\t\t\t'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,\n\t\t\t\t's':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25}\n\ndouble_map = {'a':1,'b':2,'c':6,'d':8,'e':10,'f':12,'g':14,'h':16,\n\t\t\t\t'i':18,'j':20,'k':22,'l':24,'m':26,'n':28,'o':30,\n\t\t\t\t'p':32,'q':34,'r':36,'s':38,'t':40,'u':42,'v':44,\n\t\t\t\t'w':46,'x':48,'y':50,'z':52}\n\nfib_map = {'a':1,'b':1,'c':2,'d':3,'e':5,'f':8,'g':13,'h':21,\n\t\t\t'i':34,'j':55,'k':89,'l':144,'m':233,'n':377,'o':610,\n\t\t\t'p':987,'q':1597,'r':2584,'s':4181,'t':6765,'u':10946,\n\t\t\t'v':17711,'w':28657,'x':46368,'y':75025,'z':121393}\n\nbin_map = {'a':1,'b':2,'c':4,'d':8,'e':16,'f':32,'g':64,'h':128,'i':256,\n\t\t\t'j':512,'k':1024,'l':2048,'m':4096,'n':8192,'o':16384,'p':32768,\n\t\t\t'q':65536,'r':131072,'s':262144,'t':524288,'u':1048576,'v':2097152,\n\t\t\t'w':4194304,'x':8388608,'y':16777216,'z':33554432}\n\ndef choose_map(seq):\n\tif seq == '':\n\t\treturn default_map\n\telif seq == 'zero':\n\t\treturn zero_map\n\telif seq == 'double':\n\t\treturn double_map\n\telif seq == 'fib':\n\t\treturn fib_map\n\telif seq == 'bin':\n\t\treturn bin_map\n\telse:\n\t\traise ValueError(seq,'is not defined.')\n\ndef number_is_value(num,seq=''):\n\twords = as_words(num)\n\tmap_type = choose_map(seq)\n\tval = 0\n\tfor letter in words:\n\t\tif letter in map_type:\n\t\t\tval+= map_type[letter]\n\treturn num==val\n\ndef main():\n\n\t# basic tests\n\tprint(251,'->',number_is_value(251)) # True\n\tprint(261,'->',number_is_value(261)) # False\n\tprint(251,'zero ->',number_is_value(251,'zero')) # False\n\tprint(261,'zero ->',number_is_value(261,'zero')) # True\n\n\t# searching for values that work\n\tfor num in range(0,300):\n\t\tif number_is_value(num):\n\t\t\tprint(num,'is equal to the value using default map.')\n\t\tif number_is_value(num,'zero'):\n\t\t\tprint(num,'is equal to the value using zero map.')\n\n\nmain()","sub_path":"number_is_value.py","file_name":"number_is_value.py","file_ext":"py","file_size_in_byte":3253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"383579174","text":"import asyncio\n\nimport telethon as tg\n\nfrom .. import command, module\n\nfishing_chat = 259643624 ##-1001463155229\n\n\nclass FishingUtils(module.Module):\n name = \"Fishing\"\n disabled = False\n running = False\n\n @command.desc(\"Start Fishing!\")\n async def cmd_startfish(self, ctx: command.Context):\n if self.running == True:\n await ctx.respond(\"!!You are already fishing!!\")\n else:\n self.running = True\n await ctx.respond(\"`-> Fishing Started!`\")\n \n while self.running:\n await self.bot.client.send_message(fishing_chat, \"/fish@CalsiBot\")\n await asyncio.sleep(3)\n\n @command.desc(\"Stop Fishing!\")\n async def cmd_stopfish(self, ctx: command.Context):\n if self.running == True:\n self.running = False\n await ctx.respond(\"`-> Fishing stopped!`\")\n else:\n await ctx.respond(\"`You are not fishing currently`\\ndo it by 'startfish'\")\n\n async def on_message(self, event: tg.events.NewMessage.Event) -> None:\n if event.is_group and str(event.chat_id) == str(fishing_chat):\n await self.bot.client.send_read_acknowledge(event.chat, event.message, clear_mentions=True)\n","sub_path":"fishing.py","file_name":"fishing.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"155294458","text":"import urllib, json, requests\nimport datetime\nimport imaplib\nimport email as rand\nfrom bs4 import BeautifulSoup\n\nclass Messager:\n def __init__(self, url, email, password):\n self.url = url\n self.email = email\n self.password = password\n \n def error_handler(self, req):\n if req.status_code != 200:\n print(req.status_code)\n req.raise_for_status()\n \n def get_messages(self):\n output = requests.get(self.url)\n self.error_handler(output)\n messages = output.json()\n if len(messages) != 0:\n for mes in messages:\n mes[\"message_date\"] = datetime.datetime.strptime(mes[\"message_date\"][:-6], \\\n \"%a, %m %b %Y %H:%M:%S\")\n messages.sort(key = lambda x: x[\"message_date\"])\n return messages\n else:\n print(\"No messages found\")\n return None\n \n def create_message(self, payload):\n req = requests.post(self.url, json = payload)\n self.error_handler(req)\n \n def delete_message(self, _id):\n req = requests.delete(self.url + \"/{}\".format(_id))\n self.error_handler(req)\n \n def clear_all_messages(self):\n req = requests.delete(self.url)\n self.error_handler(req)\n print(\"All messages have been deleted\")\n \n def mark_seen(self, _id):\n body = {\"seen\": True}\n req = requests.put(self.url + \"/{}\".format(_id), json = body)\n self.error_handler(req)\n \n def check_unread(self, server = \"imap.gmail.com\"):\n con = imaplib.IMAP4_SSL(server)\n con.login(self.email, self.password)\n con.select(\"Inbox\")\n typ, data = con.search(None, \"(UNSEEN)\")\n msgs = []\n for num in data[0].split():\n typ, data = con.fetch(num, \"(RFC822)\")\n msg = rand.message_from_bytes(data[0][1])\n output = {}\n output[\"author\"] = \" \".join(msg[\"From\"].split()[:-1])\n output[\"message_date\"] = msg[\"Date\"]\n soup = BeautifulSoup(msg.get_payload()[1].as_string())\n output[\"body\"] = soup.find(\"body\").find(\"div\").get_text()\n typ, data = con.store(num, \"-FLAGS\", \"//Seen\")\n msgs.append(output)\n if len(msgs) == 0:\n print(\"No unread messages found\")\n return None\n else:\n return msgs\n \n def push_new_messages(self):\n msgs = self.check_unread()\n if msgs:\n print(\"{} unread message(s)\".format(len(msgs)))\n for m in msgs:\n self.create_message(m)\n else:\n return None\n \n def get_queued_message(self):\n msgs = self.get_messages()\n for i in msgs:\n if i[\"seen\"] == False:\n break\n if i[\"seen\"] == True:\n print(\"No messages to present\")\n return None\n else:\n self.mark_seen(i[\"_id\"])\n return i\n \n def delete_old_messages(self, thres = 5):\n cut = datetime.timedelta(hours = 1, days = thres)\n count = 0\n for msg in self.get_messages():\n diff = datetime.datetime.now() - msg[\"message_date\"]\n if diff > cut:\n print(\"Message Deleted w/ Body: {}\".format(msg[\"body\"]))\n self.delete_message(msg[\"_id\"])\n count += 1\n return count\n","sub_path":"node_implementation/python_files/Messager.py","file_name":"Messager.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"221009062","text":"import dynamicobjectkeeper\r\nimport work\r\nimport author\r\nimport fileoperation\r\n\r\ndef fillAuthorList(line, showInformation = False):\r\n\r\n splittedByDieses = line.split(\"#####\")\r\n\r\n if (len(splittedByDieses) != 3):\r\n return\r\n\r\n workName = splittedByDieses[0]\r\n authorName = splittedByDieses[1]\r\n date = splittedByDieses[2]\r\n\r\n attachWorkToAuthor(workName, date, authorName)\r\n\r\n if(showInformation == True):\r\n print(\"Eser Adı: \" + workName + \" - Yazar Adı: \" + authorName + \" - Tarih: \" + date)\r\n\r\n return\r\n\r\ndef newWork(file):\r\n\r\n workName = input(\"Eser Adi: \")\r\n authorName = input(\"Yazar Adi: \")\r\n date = input(\"Tarih: \")\r\n\r\n attachWorkToAuthor(workName, date, authorName)\r\n\r\n line = \"\\n\" + workName + \"#####\" + authorName + \"#####\" + date\r\n\r\n fileoperation.writeToFile(file, line)\r\n\r\n return\r\n\r\ndef attachWorkToAuthor(workName, date, authorName):\r\n\r\n authorInstance = dynamicobjectkeeper.getAuthor(authorName)\r\n\r\n if authorInstance == None:\r\n authorInstance = author.Author(authorName)\r\n dynamicobjectkeeper.pushAuthor(authorInstance)\r\n\r\n workInstance = work.Work(workName, date)\r\n authorInstance.attachWork(workInstance)\r\n\r\n return\r\n\r\ndef searchByWorkName(workName):\r\n\r\n for author in dynamicobjectkeeper.authorList:\r\n for work in author.workArray:\r\n if(work.name == workName):\r\n print(\"Eser Adı: \" + work.name + \" - Yazar Adı: \" + author.name + \" - Tarih: \" + work.date)\r\n\r\n return\r\n\r\ndef searchByAuthorName(authorName):\r\n\r\n for author in dynamicobjectkeeper.authorList:\r\n if(author.name == authorName):\r\n for work in author.workArray:\r\n print(\"Eser Adı: \" + work.name + \" - Yazar Adı: \" + author.name + \" - Tarih: \" + work.date)\r\n\r\n return\r\n\r\ndef searchByDate(date):\r\n\r\n for author in dynamicobjectkeeper.authorList:\r\n for work in author.workArray:\r\n if(work.date == date):\r\n print(\"Eser Adı: \" + work.name + \" - Yazar Adı: \" + author.name + \" - Tarih: \" + work.date)\r\n\r\n return\r\n\r\ndef emptyAuthors():\r\n dynamicobjectkeeper.authorList = []\r\n return\r\n\r\ndef writeToConsole(message):\r\n print(message)\r\n return","sub_path":"commandexecutor.py","file_name":"commandexecutor.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"118267981","text":"#FE2\r\n# Shawn Wright\r\n# 2/26/19\r\n# \r\n\r\ndef main ():\r\n \r\n\r\n \r\n\r\n print( \"MENU\")\r\n print( 1, \" Report \")\r\n\r\n\r\n print( 2, \" Average Values : \")\r\n\r\n print( 3, \" Exit Program : \")\r\n \r\n menuChoice = int(input(\"Please select the menu option : \"))\r\n\r\n if (menuChoice == 1):\r\n \r\n with open(\" tdsc01titles.txt\",\"w\") as outfile:\r\n h1= \" Item ID \"\r\n h2 = \" Buyer \"\r\n h3= \" Item Name \"\r\n h4= \" Price \"\r\n\r\n outfile.write( h1.ljust(9) + h2.ljust(20) + h3.ljust(16) + h4 +\"\\n\" ) \r\n\r\n with open(\" tdsc01.txt\",\"w\") as infile:\r\n count = 0\r\n for line in infile:\r\n filer = line[0:7]\r\n itemID = line[7:10]\r\n itemID2 = line[10:13]\r\n buyer = line[13:33]\r\n buyer = buyer.rstrip(\" \")\r\n itemName = line[33:48]\r\n filer2 = line[48:75]\r\n price = line[75:78]\r\n price = line[78:80]\r\n \r\n outfile.write( itemID + \"-\" + itemID2.ljust(5) + buyer.ljust(20) + itemName.ljust(16) + \"$\" + price +\"\\n\" )\r\n \r\n \r\n \r\n\r\n elif (menuChoice == 2):\r\n print(\"II\")\r\n with open(\"Formatted Report.txt\",\"r\") as infile:\r\n total = 0\r\n count = 0\r\n for line in infile:\r\n value = int(line)\r\n count = count + 1\r\n total = total + value\r\n ave = total / count\r\n print(ave)\r\n \r\n \r\n \r\n elif (menuChoice == 3):\r\n print(\"III\")\r\n\r\n quit()\r\n\r\n else:\r\n print(\"Error: Restart program and enter a number between 1 and 3.\" )\r\n \r\n\r\nmain() \r\n","sub_path":"Strings/Assignments/TDSC01 Report.py","file_name":"TDSC01 Report.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"647716841","text":"import os\nimport getpass\n\n\n\nos.system(\"tput setaf 3\")\nprint(\"\"\"\n\\n\\tARTH2020.2.20 Group 4\n\\n\\tTEAM MEMBERS\n\\t1.Pritee Dharme\n\\t2.Suyog Shinde\n\\t3.Shrikant Luharia\n\\t4.Suraj Kumar\n\"\"\")\n\n\nos.system(\"tput setaf 5\")\nprint(\"\\n\\t\\t\\tWelcome to my Automation menu!!\")\nos.system(\"tput setaf 7\")\nprint(\"\\n\\t\\t\\t---------------------------\")\n\npasswd = getpass.getpass(\"Enter your password : \")\n\nif passwd != \"root\":\n print(\"\\n\\tInvalid Password...\")\n exit()\n\ndef task():\n print(\"\"\"\n\\n\n Press 1 : To launch the Hadoop menu\n Press 2 : To launch the AWS menu\n Press 3 : To launch the Partition menu\n Press 4 : To launch the docker menu\n press 5 : To Launch the webserver\n Press 6 : Exit..\n\"\"\")\n\n kite = int(input(\"\\n\\tEnter the option :\"))\n\n\n if kite == 1:\n def hadoop():\n print(\"\"\"\n \\n\n Welcome to hadoop menu\n ----------------------\n \n Press 1 to get into master menu\n Press 2 to get into slave menu\n Press 3 to get into client menu\n Press 4 Exit..\n \"\"\")\n opt = int(input(\"\\n\\tEnter the option :\"))\n\n if opt == 1:\n print(\"\"\"\n \\tPress 1 : To configure the master\n \\tPress 2 : To start the master\n \\tPress 3 : To stop master\n \\tPress 4 : To check the proceses running \n \\tPress 5 : To check report \n \\tPress 6 : Exit \n \"\"\")\n\n hopt = int(input(\"\\n\\tInput the option:\"))\n if hopt == 1:\n direc = input(\"\\n\\tEnter the directory name for master:\")\n os.system(\"mkdir {}\".format(direc))\n ipp = input(\"\\n\\tEnter the Master ip:\")\n os.system('cd /etc/hadoop')\n cc = '''\n\n \n\n \n\n\nfs.default.name\nhdfs://{}:9001\n\n'''.format(ipp)\n text_file = open(\"/etc/hadoop/core-site.xml\", 'w')\n n = text_file.write(cc)\n text_file.close()\n dd =\"\"\"\n\n \n\n \ns\n\ndfs.name.dir\n/{}\n\n\n \"\"\".format(direc)\n hdf_file = open(\"/etc/hadoop/hdfs-site.xml\", 'w')\n m = hdf_file.write(dd)\n hdf_file.close()\n os.system(\"hadoop namenode -format -Y\")\n print(\"Successfully configured the name node\")\n elif hopt == 2:\n os.system(\"cd /etc/hadoop\")\n os.system(\"hadoop-daemon.sh start namenode\")\n print(\"Successfully started the name node\")\n elif hopt == 3:\n os.system(\"cd /etc/hadoop\")\n os.system(\"hadoop-daemon.sh stop namenode\")\n print(\"Successfully stoped the name node\")\n\n elif hopt == 4:\n os.system(\"jps\")\n elif hopt == 5:\n os.system(\"hadoop dfsadmin --report\")\n elif hopt == 6:\n os.system(\"exit\")\n else:\n print(\"invalid option...\")\n hadoop()\n elif opt == 2:\n print(\"\"\"\n \\tPress 1 : To configure the datanode \n \\tPress 2 : To start the slave\n \\tPress 3 : To stop slave\n \\tPress 4 : To check the proceses running\n \\tPress 5 : To check report \n \\tPress 6 : Exit \n \"\"\")\n hopt = int(input(\"\\n\\tInput the option.. \"))\n if hopt == 1:\n direc = input(\"\\n\\tEnter the directory name for slave:\")\n os.system(\"mkdir {}\".format(direc))\n ipp = input(\"\\n\\tEnter the Master ip:\")\n os.system('cd /etc/hadoop')\n cc = '''\n\n \n\n \n\n\nfs.default.name\nhdfs://{}:9001\n\n'''.format(ipp)\n text_file = open(\"/etc/hadoop/core-site.xml\", 'w')\n n = text_file.write(cc)\n text_file.close()\n dd = \"\"\"\n\n \n\n \n\n\ndfs.data.dir\n/{}\n\n\n \"\"\".format(direc)\n hdf_file = open(\"/etc/hadoop/hdfs-site.xml\", 'w')\n m = hdf_file.write(dd)\n hdf_file.close()\n print(\"Successfully configured the data node\")\n\n elif hopt == 2:\n os.system(\"cd /etc/hadoop\")\n os.system(\"hadoop-daemon.sh start datanode\")\n print(\"Successfully started the data node\")\n\n elif hopt == 3:\n os.system(\"cd /etc/hadoop\")\n os.system(\"hadoop-daemon.sh stop datanode\")\n print(\"Successfully stoped the data node\")\n\n elif hopt == 4:\n os.system(\"jps\")\n elif hopt == 5:\n os.system(\"hadoop dfsadmin -report\")\n elif hopt == 6:\n os.system(\"exit\")\n else:\n print(\"\\n\\tinvalid option...\")\n hadoop()\n\n elif opt == 3:\n print(\"\"\"\n \\tPress 1 : To configure the client\n \\tPress 2 : To upload a file\n \\tPress 3 : To remove a file\n \\tPress 4 : To read a file\n \\tPress 5 : To list the files\n \\tPress 6 : To upload a file with default block size\n \\tPress 7 : Exit..\")\n \"\"\")\n cip = int(input(\"\\n\\tInput the option:\"))\n if cip == 1:\n mip = input(\"\\n\\tEnter the master ip\")\n cc = '''\n\n \n\n \n\n\nfs.default.name\nhdfs://{}:9001\n\n'''.format(mip)\n text_file = open(\"/etc/hadoop/core-site.xml\", 'w')\n n = text_file.write(cc)\n text_file.close()\n print(\"Successfully configured the Client\")\n\n elif cip == 2:\n filep = input(\"\\n\\tEnter the full file path\")\n os.system(\"hadoop fs -put {} /\".format(filep))\n print(\"File Uploded successfully\")\n\n elif cip == 3:\n filep = input(\"\\n\\tEnter the full file name you want to remove :\")\n os.system(\"hadoop fs -rm /{}\".format(filep))\n print(\"File removed successfully\")\n\n elif cip == 4:\n filep = input(\"\\n\\tEnter the full file name you want to read :\")\n os.system(\"hadoop fs -cat /{}\".format(filep))\n elif cip == 5:\n os.system(\"hadoop fs ls /\")\n elif cip == 6:\n bs = int(input(\"Enter the Block size\"))\n filep = input(\"Enter the full file path\")\n os.system(\"hadoop fs -Ddfs.block.size={}M -put {} /\".format(bs,filep))\n elif cip == 7:\n os.system(\"exit\")\n else:\n print(\"\\n\\tInvalid option...\")\n elif opt == 4:\n os.system(\"exit\")\n\n else:\n print(\"\\n\\tinvalid option\")\n hadoop()\n task()\n hadoop()\n elif kite == 2:\n def aws():\n print(\"\"\"\\n\n \\tPress 1 : To launch the EC-2 menu\n \\tPress 2 : To launch the S3 menu\n \\tPress 3 : To launch the IAM menu\n \\tPress 4 : To launch the CLOUDFRONT menu\n \\tPress 5 : To configure the AWS CLI\n \\tPress 6 : Exit..\n \"\"\")\n\n menu = int(input(\"\\n\\tEnter the option.. \"))\n if menu == 1:\n print(\"\"\"\n \\n\n \\tPress 1 : To launch the instances menu \n \\tPress 2 : To launch the volume menu\n \\tPress 3 : To launch the Security group menu \n \\tPress 4 : To launch the Key pair menu \n \\tPress 5 : To launch the snapshot menu\n \\tPress 6 : Exit..\n \"\"\")\n ola = int(input(\"\\n\\tEnter the option :\"))\n if ola == 1:\n print(\"\"\"\n \\t Welcome to the instances menu \n \\t 1.To describe instances press 1\n \\t 2.To Describe the instances type press 2\n \\t 3.To Run a new instance press 4\n \\t 4.To start a instance press 5\n \\t 5.To stop the instance press 6\n \\t 6.To reboot a instance press 6\n \\t 7.To terminate a instance press 7\n \\t 8. exit press 8\")\n \n \"\"\")\n im = int(input(\"\\n\\tInput the option:\"))\n if im == 1:\n os.system(\"aws ec2 describe-instances\")\n elif im == 2:\n os.system(\"aws ec2 describe-instances-types\")\n elif im == 3:\n imageid = input(\"\\n\\tEnter the image id :\")\n inty = input(\"\\n\\tenter the instance type :\")\n subnetid = input(\"\\n\\tenter the subnet id :\")\n security = input(\"\\n\\tenter the security group id :\")\n keyname = input(\"\\n\\tenter the key name :\")\n os.system(\"aws ec2 run-instance --image-id {} --instance-type {} --count 1 --subnet-id {} --key-name {}\".format(imageid,inty,subnetid,security,keyname,))\n elif im == 4:\n instanceid = input(\"\\n\\tEnter thr instance id\")\n os.system(\"aws ec2 start-instances --instance-ids {}\".format(instanceid))\n elif im == 5:\n instanceid = input(\"\\n\\tEnter thr instance id\")\n os.system(\"aws ec2 stop-instances --instance-ids {}\".format(instanceid))\n elif im == 6:\n instanceid = input(\"\\n\\tEnter thr instance id\")\n os.system(\"aws ec2 reboot-instances --instance-ids {}\".format(instanceid))\n elif im == 7:\n instanceid = input(\"\\n\\tEnter thr instance id\")\n os.system(\"aws ec2 terminate-instances --instance-ids {}\".format(instanceid))\n elif im == 8:\n os.system(\"exit\")\n else:\n print(\"Choose the correct option\")\n elif ola == 2:\n print(\"\"\"\n \\t 1.To create Volume press 1\n \\t 2.To delete Volume press 2\n \\t 3.To Modify Volume press 3\n \\t 4. To Attach Volume press 4\n \\t 5.To detach Volume press 5\n \\t 6. To Exit press 6\n \"\"\")\n im = int(input(\"\\n\\tEnter the option:\"))\n if im == 1:\n vtype = input(\"\\n\\tEnter the Volume type:\")\n size = input(\"\\n\\tEnter the size of volume: \")\n az = input(\"\\n\\tEnter the avaibility zone:\")\n os.system(\"aws ec2 create-volume --volume-type {} --size {} --availability-zone {}\".format(vtype,size,az))\n print(\"Successfully created a volume\")\n elif im == 2:\n vid = input(\"\\n\\tEnter the Volume ID:\")\n os.system(\"aws ec2 delete-volume --volume-id {}\".format(vid))\n print(\"Successfully deleted a volume\")\n elif im == 3:\n vid =input(\"\\n\\tEnter the volume ID:\")\n size =int(input(\"\\n\\tEnter the size you want to change:\"))\n os.system(\"aws ec2 modify-volume --volume-id {} --size {}\".format(vid,size))\n print(\"Successfully increased the volume size\")\n elif im == 4:\n device = input(\"\\n\\tEnter the device e.g /dev/shd:\")\n iid = input(\"\\n\\tEnter the instance id:\")\n vid = input(\"\\n\\tEnter the Volume id:\")\n os.system(\"aws ec2 attach-volume --device {} --instance-id {} --volume-id {}\".format(device,iid,vid))\n print(\"Successfully decreased the volume size\")\n elif im == 5:\n device = input(\"\\n\\tEnter the device e.g /dev/shd:\")\n iid = input(\"\\n\\tEnter the instance id:\")\n vid = input(\"\\n\\tEnter the Volume id:\")\n os.system(\"aws ec2 detach-volume --device {} --instance-id {} --volume-id {}\".format(device,iid,vid))\n elif im == 6:\n os.system(\"exit\")\n else:\n print(\"\\n\\tChoose the correct option:\")\n elif ola == 3:\n print(\"\"\"\n \\t 1. To Describe security groups press 1\n \\t 2. To create a security group press 2\n \\t 3.To delete a security group press 3 \n \\t 4. Exit press 4\n \"\"\")\n se =int(input(\"\\n\\tInput the option:\"))\n if se == 1:\n gn = input(\"\\n\\tEnter the groups names:\")\n os.system(\"aws ec2 describe-security-groups --group-names {}\".format( gn))\n elif se == 2:\n gn = input(\"\\n\\tEnter the group name:\")\n des = input(\"\\n\\tEnter the description\")\n os.system(\"aws ec2 create-security-group --group-name {} --description' {}' \".format(gn,des))\n elif se ==3:\n gn = input(\"\\n\\tEnter the group name:\")\n os.system(\"aws ec2 delete-security-group --group-name {}\".format(gn))\n elif se == 4:\n os.system(\"exit\")\n else:\n print(\"choose the correct option:\")\n elif ola == 4:\n print(\"\"\"\n \\t 1.To describe key pairs press 1\n \\t 2.To create a new key pair press 1\n \\t 3.To Delete a key pair press 3\n \\t 4. To Exit press 4 \n \"\"\")\n keyy = int(input(\"\\n\\tInput the option:\"))\n if keyy == 1:\n kn = input(\"\\n\\tEnter the key pair name:\")\n os.system(\"aws ec2 descibe-key-pairs --key-name {}\".format(kn))\n elif keyy == 2:\n kn = input(\"\\n\\tEnter the key name:\")\n qe =input(\"\\n\\tEnter the query:\")\n os.system(\"aws ec2 create-key-pairs --key-name {} --query '{}' --output text > {}.pem\".format(kn,qe,kn))\n elif keyy == 3:\n kn = input(\"\\n\\tEnter the key pair name:\")\n os.system(\"aws ec2 delete-key-pairs --key-name {}\".format(kn))\n elif keyy == 4:\n os.system(\"exit\")\n elif ola ==5:\n print(\"\"\"\n \\t 1.To describe snapshots press 1\n \\t 2.To create snapshots press 2\n \\t 3.To delete snapshots press 3\n \\t 4.To Exit\n \"\"\")\n snap = int(input(\"\\n\\tinput the option:\"))\n if snap == 1:\n sid = input(\"\\n\\tEnter yours snapshot id:\")\n os.system(\"aws ec2 describe-snapshots --snapshot-ids {}\".format(sid))\n elif snap == 2:\n vid =input(\"\\n\\tEnter the volume id:\")\n des = input(\"\\n\\tEnter the description for snapshot:\")\n os.system(\"aws ec2 create-snapshot --volume-id {} --description '{}'\".format(vid,des))\n elif snap == 3:\n sid = input(\"\\n\\tEnter yours snapshot id:\")\n os.system(\"aws ec2 delete-snapshot --snapshot-id {}\".format(sid))\n elif snap == 4:\n os.system(\"exit\")\n else:\n print(\"\\n\\tchoose the correct option:\")\n elif ola == 6:\n os.system(\"exit\")\n else:\n print(\"Choose the correct option:\")\n aws()\n#S3 menu starts\n elif menu ==2:\n def option():\n op = int(input('''\n \\n\n ..............#WELCOME IN MAIN MENU#................\n \n \\n\n Press 1 : To Create a S3 Bucket..\n press 2 : To List all S3 Bucket..\n Press 3 : To Create Bucket policies..\n Press 4 : To Delete the Bucket..\n Press 5 : To Delete Bucket Policies..\n press 6 : exit..\n \\n\n what can I help you..: '''))\n\n if op == 1:\n name1 = input(\"\\n\\tEnter your Bucket that you want..>> \")\n name2 = input(\"\\n\\tEnter your AWS Region ..>> \")\n os.system(\n \"aws s3api create-bucket --bucket {} --region {} --create-bucket-configuration LocationConstraint={}\".format(\n name1, name2, name2))\n print(\"\\n....>>>Your Bucket is Successfully Created<<<....\")\n option()\n elif op == 2:\n os.system('aws s3api list-buckets --query \"Bucket[].Name\"')\n print(\"\\n....>>> Your All Buckets <<<....\")\n option()\n elif op == 3:\n print(\"\\n\\t Press 1 : To create bucket public..\\n\\t Press 2 : To make Image Public \\n\")\n pr = int(input(\"Enter your choice..>> \"))\n if pr == 1:\n name1 = input(\"\\n\\t Enter the name of Bucket..>> \")\n os.system(\"aws s3api put-bucket-ac1 --public-read --bucket {}\".format(name1))\n print(\"\\n....>>>Your Bucket is Now Public<<<....\")\n elif pr == 2:\n name1 = input(\"\\n\\t Enter the name of bucket..>> \")\n name2 = input(\"\\n\\t Enter your image name..>> \")\n os.system(\n \"aws s3api put-object-ac1 --bucket {} --key {}.jpg --grant-read uri=http://acs.amazonaws.com/groups/global/AllUsers\".format(\n name1, name2))\n print(\"\\n....>>>Your Image is now Public<<<....\")\n\n option()\n\n elif op == 4:\n name1 = input(\"\\n\\t Enter the name of bucket..>> \")\n name2 = input(\"\\n\\t Enter the Region name..>> \")\n os.system(\"aws s3api delete-bucket --bucket {} --region {}\".format(name1, name2))\n print(\"\\n....>>> Your Bucket is Successfully Deleted <<<....\")\n option()\n elif op == 5:\n name1 = input(\"\\n\\t Enter the name of Bucket..>> \")\n os.system(\"aws s3api delete-bucket-policy --bucket {}\".format(name1))\n print(\"\\n....>>>Your Bucket Policies Successfully Deleted<<<....\")\n option()\n elif op == 6:\n os.system(\"exit\")\n os.system(\"tput setaf 3\")\n print(\"\\n\\n\\t#########..THANK YOU..See you soon..#########\")\n os.system(\"tput setaf 7\")\n print(\"\\n\")\n\n else:\n print(\"Incorrect Choice,select correct option..\")\n anykey = input(\"\\n\\t Press Enter to go main menu\")\n option()\n option()\n aws()\n elif menu ==3:\n def option():\n op = int(input('''\n \\n\n ..............#WELCOME IN MAIN MENU#................\n \n \\n\n Press 1 : To Create a IAM Group..\n press 2 : To Create a IAM User..\n Press 3 : To Add IAM User in IAM Group..\n Press 4 : To Attach IAM managed policy to IAM User..\n Press 5 : To Set Password to IAM User..\n Press 6 : To Create Access and Public Key..\n press 7 : exit..\n \\n\n what can I help you..: '''))\n\n if op == 1:\n name1 = input(\"\\n\\tEnter Group name that you want..>> \")\n os.system(\"aws iam create-group --group-name {}\".format(name1))\n print(\"\\n\\t....>>>Your IAM Group is Successfully Created<<<....\")\n option()\n elif op == 2:\n name2 = input(\"\\n\\tEnter User name that you want..>>\")\n os.system(\"aws iam create-user --user-name {}\".format(name2))\n print(\"\\n\\t....>>> Your IAM User is Successfully Created <<<....\")\n option()\n elif op == 3:\n name2 = input(\"\\n\\t Enter the name of IAM User..>> \")\n name1 = input(\"\\n\\t Enter the name of IAM Group..>>\")\n os.system(\"aws iam add-user-to-group --user-name {} --group-name {}\".format(name2, name1))\n os.system(\"aws iam get-group --group-name {}\".format(name1))\n print(\"\\n\\t....>>>Your IAM User is Added in IAM Group Successfully <<<...\")\n option()\n\n elif op == 4:\n name2 = input(\"\\n\\t Enter the name of IAM User..>> \")\n os.system(\"aws iam attach-user-policy --user-name {} --policy=arn:aws:iam::aws:policy/PowerUserAccess\")\n os.system(\"aws iam list-attached-user-policies --user-name {}\".format(name2))\n print(\"\\n\\t....>>> Your IAM Policy is Successfully Attached <<<....\")\n option()\n\n elif op == 5:\n name2 = input(\"\\n\\t Enter the name of IAM User..>> \")\n name3 = input(\"\\n\\t Enter the Password that you want to give..>> \")\n os.system(\n \"aws iam create-login-profile --user-name {} --password {} --password-reset-required\".format(name2, name3))\n print(\"\\n\\t....>>>Your Password is Successfully Set <<<....\")\n option()\n elif op == 6:\n name2 = input(\"\\n\\t Enter the name of IAM User..>> \")\n os.system(\"aws iam create-access-key --user-name {}\".format(name2))\n print(\"\\n\\t ....>>> Your Key is Generated Successfully <<<....\")\n option()\n elif op == 7:\n os.system(\"exit\")\n os.system(\"tput setaf 3\")\n print(\"\\n\\n\\t#########..THANK YOU..#########\")\n os.system(\"tput setaf 7\")\n print(\"\\n\")\n\n else:\n print(\"Incorrect Choice,select correct option..\")\n anykey = input(\"\\n\\t Press Enter to go main menu\")\n option()\n \n option()\n aws()\n elif menu == 4:\n print(\"\"\"\n \\n\\t\n To lauch the cloud front menu press 1\n \n \"\"\")\n op = int(input(\"\\n\\tEnter the option:\"))\n\n if op == 1:\n print(\"\"\"\n \\t 1.To create distribution press 1\n \\t 2.To delete distribution press 2\n \\t 3.To list the distribution press 3\n \\t 4. to Exit press 4\n \"\"\")\n opt =int(input(\"\\n\\tInput the option:\"))\n if opt == 1:\n odn = input(\"\\n\\tEnter the origin domain name:\")\n dro = input(\"\\n\\tEnter the default root object:\")\n os.system(\"aws cloudfront create-distribution --origin-domain-name {} --default-root-object {}\".format(odn,dro))\n elif opt == 2:\n cid = input(\"\\n\\tEnter the distribution id:\")\n etag = input(\"\\n\\tEnter the distribution etag:\")\n os.system(\"aws cloudfront delete-distribution --id {} --if-match {}\".format(cid,etag))\n elif opt == 3:\n os.system(\"aws cloudfront list-distributions: \")\n elif opt == 4:\n os.system(\"exit\")\n else:\n print(\"Choose the correct option: \")\n else:\n print(\"Invalid option...\")\n elif menu == 5:\n os.system('\\ncurl \"https://awscli.amazonaws.com/awscli-exe-linux-x86_64-2.0.30.zip\" -o \"awscliv2.zip\"')\n os.system(\" unzip awscliv2.zip \")\n os.system(\" sudo ./aws/install \")\n os.system(\"\\n sudo ./aws/install -i /usr/local/aws-cli -b /usr/local/bin\")\n os.system(\"\\n aws --version\")\n os.system(\"\\n aws configure\")\n print(\"\\n\\t.....you configure successfully.....\")\n\n elif menu == 6:\n os.system(\"exit\")\n else:\n print(\"Invalid option...\")\n aws()\n #task()\n aws()\n task()\n elif kite == 3:\n def par():\n print(\"\"\"\\n\n \\tPress 1.To Enter the static partition menu\n \\tPress 2.To Enter the LVM partition menu\n \\tPress 3.Exit\n \"\"\")\n part = int(input(\"\\n\\tEnter the option.. \"))\n if part ==1:\n def option():\n op = int(input('''\n \\n\n \n \\tPress 1 : To Create a Static Partition..\n \\tPress 2 : Format and mount partition..\n \\tPress 3 : To increase size of Partition..\n \\tPress 4 : To decrease size of partition..\n \\tPress 5 : To delete the static partiton..\n \\tpress 6 : exit..\n \\n\n what can I help you..: '''))\n\n if op == 1:\n os.system(\"\\n yum install parted\")\n name1 = input(\"\\n\\tEnter your harddisk that you want..>> \")\n part1 = input(\"\\n\\tEnter start point of partition..>> \")\n part2 = input(\"\\n\\tEnter end point of partition..>> \")\n os.system(\"parted {} mkpart primary ext4 {}G {}G;\".format(name1, part1, part2))\n os.system(\"lsblk\")\n option()\n elif op == 2:\n name3 = input(\"\\n\\t Enter the name of partition..>> \")\n os.system(\"mkfs.ext4 {}\".format(name3))\n name4 = input(\"\\n\\t Enter the folder name that you want..>>\")\n os.system(\"mkdir \\{}\".format(name4))\n os.system(\"mount {} {}\".format(name3,name4))\n os.system(\"lsblk\")\n\n elif op == 3:\n name1 = input(\"\\n\\t Enter the name of harddisk..>> \")\n num1 = input(\"\\n\\t Enter the number of partition..>> \")\n size1 = input(\"\\n\\t Enter the incresing end point size..>> \")\n os.system(\"parted {} resizepart {} {}G\".format(name1, num1, size1))\n os.system(\"lsblk\")\n option()\n elif op == 4:\n name1 = input(\"\\n\\t Enter the name of harddisk..>> \")\n num1 = input(\"\\n\\t Enter the number of partition..>> \")\n size2 = input(\"\\n\\t Enter the decreasing end point size..>> \")\n os.system(\"parted {} resizepart {} {}G\".format(name1, num1, size2))\n os.system(\"lsblk\")\n option()\n elif op == 5:\n name1 = input(\"\\n\\t Enter the name of harddisk..>> \")\n num1 = input(\"\\n\\t Enter the number of partition..>> \")\n os.system(\"parted {} rm {}\".format(name1, num1))\n os.system(\"lsblk\")\n option()\n elif op == 6:\n os.system(\"exit\")\n os.system(\"tput setaf 3\")\n print(\"\\n\\n\\t#########..THANK YOU..See you soon..#########\")\n os.system(\"tput setaf 7\")\n print(\"\\n\")\n\n else:\n print(\"Incorrect Choice,select correct option..\")\n anykey = input(\"\\n\\t Press Enter to go main menu\")\n option()\n par()\n elif part == 2:\n def printme():\n ch = int(input(''' \n \\n\n \n \\tPress 1 : To see Hard disk information..\n \\tPress 2 : To create a Physical Volume (PV)..\n \\tPress 3 : To create a Volume Group (VG)..\n \\tPress 4 : To create a Logical Volume (LV)..\n \\tPress 5 : To format the Logical Volume (LV)..\n \\tPress 6 : To create a Folder and Mount Logical Volume..\n \\tPress 7 : To increase the LVM partition..\n \\tPress 8 : To decrease the LVM partition..\n \\tPress 9 : Exit..\n \\n\n What can I help you : '''))\n print(\"\\t\\n.........................###...........................\\n\")\n\n if ch == 1:\n os.system(\"\\n fdisk -l\")\n os.system(\"tput setaf 3\")\n anykey = input(\"\\n\\t Press Enter to go main menu...>>\")\n os.system(\"tput setaf 7\")\n printme()\n\n elif ch == 2:\n os.system(\"\\n fdisk -l\")\n Disk1 = input(\"\\n\\n\\tEnter name of 1 st harddisk that you want >> \")\n os.system(\"pvcreate {}\".format(Disk1))\n os.system(\"pvdisplay {}\".format(Disk1))\n Disk2 = input(\"\\n\\t Enter name of 2 nd harddisk that you want >> \")\n os.system(\"pvcreate {}\".format(Disk2))\n os.system(\"pvdisplay {}\".format(Disk2))\n os.system(\"tput setaf 3\")\n print(\"\\n\\n\\t>>>>>>>>>Your two physical volume(PV) created successfully<<<<<<<<<<\")\n anykey = input(\"\\n\\t Press Enter to go main menu...>>\")\n os.system(\"tput setaf 7\")\n printme()\n\n elif ch == 3:\n os.system(\"\\n fdisk -l\")\n Disk1 = input(\"\\n\\n\\tEnter name of 1 st harddisk that you want >> \")\n Disk2 = input(\"\\n\\tEnter name of 2 nd harddisk that you want >> \")\n name1 = input(\"\\n\\tGive name to your Volume Group(VG) >> \")\n os.system(\"pvdisplay {}\".format(Disk1))\n os.system(\"pvdisplay {}\".format(Disk2))\n os.system(\"vgcreate {} {} {}\".format(name1, Disk1, Disk2))\n os.system(\"vgdisplay {}\".format(name1))\n os.system(\"tput setaf 3\")\n print(\"\\n\\n\\t>>>>>>>>>>Your Volume Group(VG) {} created successfully<<<<<<<<< \".format(name1))\n anykey = input(\"\\n\\t Press Enter to go main menu...>>\")\n os.system(\"tput setaf 7\")\n printme()\n\n elif ch == 4:\n os.system(\"\\n fdisk -l\")\n # Disk1= input(\"\\n\\n\\t Enter name of 1 st harddisk that you want >> \")\n # Disk2= input(\"\\n\\t Enter name of 2 nd harddisk that you want >> \")\n size1 = input(\"\\n\\t Enter size for your Logical Volume >> \")\n name1 = input(\"\\n\\t Enter your Volume Group(VG) name >> \")\n name2 = input(\"\\n\\t Give name to your Logical Volume(LV) >> \")\n # os.system(\"pvcreate {}\".format(Disk1))\n # os.system(\"pvcreate {}\".format(Disk2))\n # os.system(\"vgcreate {} {} {}\".format (name1,Disk1,Disk2))\n os.system(\"vgdisplay {}\".format(name1))\n os.system(\"lvcreate --size {}G --name {} {} \".format(size1, name2, name1))\n os.system(\"lvdisplay {}/{}\".format(name1, name2))\n os.system(\"tput setaf 3\")\n print(\"\\n\\n\\t>>>>>>>>>Your Logical Volume(LV) {} created successfully<<<<<<<<<\".format(name2))\n anykey = input(\"\\n\\t Press Enter to go main menu...>>\")\n os.system(\"tput setaf 7\")\n printme()\n\n elif ch == 5:\n name2 = input(\"\\n\\n\\tEnter the name of Volume Group >> \")\n name3 = input(\"\\n\\n\\tEnter the name of Logical Volume >> \")\n os.system(\"mkfs.ext4 /dev/{}/{}\".format(name2, name3))\n os.system(\"tput setaf 3\")\n print(\"\\n\\n\\t>>>>>>>>>Your Logical Volume Formated<<<<<<<<\")\n anykey = input(\"\\n\\t Press Enter to go main menu...>>\")\n os.system(\"tput setaf 7\")\n printme()\n\n elif ch == 6:\n folder1 = input(\"\\n\\n\\t Enter folder name that you want >> \")\n os.system(\"mkdir {}\".format(folder1))\n name2 = input(\"\\n\\tEnter the name of Volume Group >> \")\n name3 = input(\"\\n\\tEnter the name of Logical Volume >> \")\n os.system(\"mount /dev/{}/{} {}\".format(name2, name3, folder1))\n os.system(\"df -hT\")\n os.system(\"tput setaf 3\")\n print(\"\\n\\n\\t>>>>>>>>Your Logical Volume mounted<<<<<<<<\")\n anykey = input(\"\\n\\t Press Enter to go main menu...>> \")\n os.system(\"tput setaf 7\")\n printme()\n\n elif ch == 7:\n pr1 = input(\"\\n\\n\\tEnter the name of VG Partition..: \")\n pr2 = input(\"\\n\\n\\tEnter the name of LV Partition..:\")\n pr3 = input(\"\\n\\n\\tEnter the increase size..: \")\n os.system(\"lvextend --size +{}G /dev/{}/{}\".format(pr3,pr1,pr2))\n os.system(\"resize2fs /dev/{}/{}\".format(pr1,pr2))\n anykey = input(\"\\n\\t Press Enter to go main menu...>> \")\n printme()\n\n elif ch == 8:\n pr1 = input(\"\\n\\n\\tEnter the name of VG Partition..: \")\n pr2 = input(\"\\n\\n\\tEnter the name of LV Partition..:\")\n pr3 = input(\"\\n\\n\\tEnter the decrease size..: \")\n os.system(\"lvreduce -r -L {}G /dev/{}/{}\".format(pr3, pr1, pr2))\n anykey = input(\"\\n\\t Press Enter to go main menu...>> \")\n printme()\n\n elif ch == 9:\n os.system(\"exit\")\n os.system(\"tput setaf 3\")\n print(\"\\n\\n\\t#########..THANK YOU..See you soon..#########\")\n os.system(\"tput setaf 7\")\n print(\"\\n\")\n\n else:\n print(\"Incorrect Choice,select correct option..\")\n anykey = input(\"\\n\\t Press Enter to go main menu\")\n printme()\n printme()\n par()\n elif part == 3:\n os.system(\"exit\")\n par()\n task()\n\n elif kite == 4:\n def dock():\n print(\"\\n Let's start docker\")\n print(\"\"\"\n \\tPress 1 : To install docker \n \\tPress 2 : To start docker \n \\tPress 3 : To check status of docker \n \\tPress 4 : To install images of Docker \n \\tPress 5 : To check images of docker \n \\tPress 6 : To run container top of docker \n \\tPress 7 : To run python top of container \n \\tPress 8 : Exit.. \n \"\"\")\n i = int(input(\"Enter your choice..: \"))\n if i == 1:\n os.system(\"dnf config-manager --add-repo=https://download.docker.com/linux/centos/docker-ce.repo\")\n os.system(\"dnf install docker-ce --nobest -y\")\n dock()\n elif i == 2:\n os.system(\"systemctl start docker\")\n dock()\n elif i == 3:\n os.system(\"systemctl status docker\")\n dock()\n elif i == 4:\n x = input(\"Enter image name..>> \")\n os.system(\"docker pull {}\".format(x))\n dock()\n elif i == 5:\n os.system(\"docker images\")\n dock()\n elif i == 6:\n y = input(\"enter image name..>> \")\n z = input(\"Give OS name that you want..>> \")\n os.system(\"docker run -it --name {} {}\".format(z, y))\n dock()\n elif i == 7:\n y = input(\"enter image name..>> \")\n z = input(\"Give OS name that you want..>> \")\n os.system(\"docker run -it --name {} {}\".format(z, y))\n os.system(\"yum install python3\")\n os.system(\"python 3\")\n dock()\n elif i == 8:\n os.system(\"exit\")\n else:\n print(\"Invalid option...\")\n dock()\n task()\n elif kite == 5:\n os.system(\"yum install httpd\")\n os.system(\"systemctl start httpd\")\n os.system(\"systemctl status httpd\")\n task()\n\n elif kite == 6:\n os.system(\"exit\")\n print(\"\\n ........ THANK YOU .......\")\n\n else:\n print(\"Invalid option...\")\n task()\n\ntask()\n","sub_path":"MainMenu.py","file_name":"MainMenu.py","file_ext":"py","file_size_in_byte":40455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"465453621","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import Case\nfrom itertools import chain\nfrom operator import attrgetter\n\n\ndef index(request):\n cases = Case.objects.filter(public=True)\n return render(request, 'investigations/index.html', {'cases': cases})\n\n\ndef investigation_case(request, slug):\n case = get_object_or_404(Case, slug=slug)\n related_cases = case.related_cases.filter(public=True)\n team_members = case.present_team_members.all()\n guests = case.present_guests.all()\n\n parties_present = sorted(chain(team_members, guests), key=attrgetter('last_name'))\n\n return render(request, 'investigations/case.html', {\n 'case': case,\n 'related_cases': related_cases,\n 'parties_present': parties_present\n })\n","sub_path":"spor/investigations/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"88098612","text":"# Author: Duncan Law-Green (dlg@kyubi.co.uk)\n# Copyright 2017 Kyubi Systems\n# Licensed under the Apache License, Version 2.0 (see LICENSE)\n# ------------------------------------------------------------\n# \n# FILESET\n#\n# Support libraries. Build set of NAME geochemical data files from\n# input directory covering specific timespan.\n\nimport arrow\nimport glob\nimport os\nfrom collections import defaultdict\n\nfrom .name import Name\nfrom .util import shortname\n\n\nclass Fileset:\n \"\"\"\n Read directory of NAME files, \n extract subset corresponding to given time period\n \"\"\"\n def __init__(self, directory):\n \"\"\"\n Initialise Fileset object.\n\n directory -- input directory path\n \"\"\"\n self.directory = directory\n self.dates = {}\n self.weeks = defaultdict(list)\n self.months = defaultdict(list)\n self.years = defaultdict(list)\n\n if not os.path.isdir(directory):\n raise ValueError(\"Input argument is not a directory\")\n\n self.files = glob.glob(directory + '/*_group*.txt')\n\n # group input filenames by week, month, year\n # generate dict of lists\n for f in self.files:\n \n g = shortname(f)\n d = arrow.get(g, 'YYYYMMDD')\n \n self.dates[g] = d\n\n self.weeks[self.getWeek(d)].append(f)\n self.months[self.getMonth(d)].append(f)\n self.years[self.getYear(d)].append(f)\n\n def getAll(self):\n \"\"\"\n Return all NAME files found in directory\n \"\"\"\n return self.files\n\n def between(self, start, stop):\n \"\"\"\n Return NAME files between two dates\n\n start -- start date, YYYYMMDD format\n stop -- stop date, YYYYMMDD format\n \"\"\"\n a = arrow.get(start, 'YYYYMMDD')\n b = arrow.get(stop, 'YYYYMMDD')\n result = []\n for f in self.files:\n g = shortname(f)\n d = arrow.get(g, 'YYYYMMDD')\n if (d >= a) and (d <= b):\n result.append(f)\n return result\n\n def getDay(self, day):\n \"\"\"\n Return NAME files for given day\n\n day --- date, YYYYMMDD format\n \"\"\"\n a = arrow.get(day, 'YYYYMMDD')\n result = []\n for f in self.files:\n g = shortname(f)\n d = arrow.get(g, 'YYYYMMDD')\n if (d == a):\n result.append(f)\n return result\n\n def getWeek(self, a):\n \"\"\"\n Return week number for given Arrow object\n a -- Arrow timestamp object\n \"\"\"\n return a.isocalendar()[1]\n\n def getMonth(self, a):\n \"\"\"\n Return month number for given Arrow object\n a -- Arrow timestamp object\n \"\"\"\n return a.format('M')\n\n def getYear(self, a):\n \"\"\"\n Return year for given Arrow object\n a -- Arrow timestamp object\n \"\"\"\n return a.format('YYYY')\n","sub_path":"pynameplot/namereader/fileset.py","file_name":"fileset.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"336222173","text":"from enum import Enum\nfrom typing import Any, Callable, Dict, List, Union\nfrom ml_gym.gym.evaluators.evaluator import AbstractEvaluator\nfrom ml_gym.gym.post_processing import PredictPostProcessingIF\nfrom ml_gym.persistency.logging import ExperimentStatusLogger\nimport torch\nfrom ml_gym.batching.batch import DatasetBatch, EvaluationBatchResult, InferenceResultBatch\nfrom ml_gym.data_handling.dataset_loader import DatasetLoader\nfrom ml_gym.gym.inference_component import InferenceComponent\nfrom ml_gym.metrics.metrics import Metric\nfrom ml_gym.models.nn.net import NNModel\nfrom ml_gym.loss_functions.loss_functions import Loss\nfrom ml_gym.gym.predict_postprocessing_component import PredictPostprocessingComponent\nfrom ml_gym.error_handling.exception import BatchStateError, EvaluationError, MetricCalculationError, LossCalculationError\nfrom accelerate import Accelerator\n\n\nclass AccelerateEvaluator(AbstractEvaluator):\n def __init__(self, eval_component: \"AccelerateEvalComponent\"):\n self.eval_component = eval_component\n\n def evaluate(self, model: NNModel, accelerator: Accelerator, epoch_result_callback_fun: Callable = None,\n batch_processed_callback_fun: Callable = None) -> List[EvaluationBatchResult]:\n model.eval()\n\n # returns a EvaluationBatchResult for each split\n evaluation_batch_results = self.eval_component.evaluate(model=model, accelerator=accelerator,\n epoch_result_callback_fun=epoch_result_callback_fun,\n batch_processed_callback_fun=batch_processed_callback_fun)\n return evaluation_batch_results\n\n\nclass AccelerateEvalComponent:\n \"\"\"This thing always comes with batteries included, i.e., datasets, loss functions etc. are all already stored in here.\"\"\"\n\n def __init__(self, inference_component: InferenceComponent, post_processors: Dict[str, PredictPostprocessingComponent], metrics: List[Metric],\n loss_funs: Dict[str, Loss], dataset_loaders: Dict[str, DatasetLoader],\n cpu_target_subscription_keys: List[str] = None, cpu_prediction_subscription_keys: List[Union[str, List]] = None,\n metrics_computation_config: List[Dict] = None, loss_computation_config: List[Dict] = None):\n self.loss_funs = loss_funs\n self.inference_component = inference_component\n # maps split names to postprocessors\n self.post_processors = post_processors\n self.metrics = metrics\n self.dataset_loaders = dataset_loaders\n self.cpu_target_subscription_keys = cpu_target_subscription_keys\n self.cpu_prediction_subscription_keys = cpu_prediction_subscription_keys\n # determines which metrics are applied to which splits (metric_key to split list)\n self.metrics_computation_config = None if metrics_computation_config is None else {\n m[\"metric_tag\"]: m[\"applicable_splits\"] for m in metrics_computation_config}\n # determines which losses are applied to which splits (loss_key to split list)\n self.loss_computation_config = None if loss_computation_config is None else {\n m[\"loss_tag\"]: m[\"applicable_splits\"] for m in loss_computation_config}\n self.experiment_status_logger: ExperimentStatusLogger = None\n\n def evaluate(self, model: NNModel, accelerator: Accelerator, epoch_result_callback_fun: Callable = None,\n batch_processed_callback_fun: Callable = None) -> List[EvaluationBatchResult]:\n return [self.evaluate_dataset_split(model, split_name, loader, accelerator, epoch_result_callback_fun, batch_processed_callback_fun) for split_name, loader in self.dataset_loaders.items()]\n\n def evaluate_dataset_split(self, model: NNModel, split_name: str,\n dataset_loader: DatasetLoader, accelerator: Accelerator, epoch_result_callback_fun: Callable = None,\n batch_processed_callback_fun: Callable = None) -> EvaluationBatchResult:\n post_processors = self.post_processors[split_name] + self.post_processors[\"default\"]\n\n # calc losses\n if self.loss_computation_config is not None:\n loss_tags = [loss_tag for loss_tag, applicable_splits in self.loss_computation_config.items()\n if split_name in applicable_splits]\n split_loss_funs = {tag: loss_fun for tag, loss_fun in self.loss_funs.items() if tag in loss_tags}\n else:\n split_loss_funs = self.loss_funs\n\n batch_losses = []\n inference_result_batches_cpu = []\n num_batches = len(dataset_loader)\n processed_batches = 0\n for batch in dataset_loader:\n inference_result_batch = self.forward_batch(dataset_batch=batch, model=model, postprocessors=post_processors)\n\n irb_filtered_dict = {\"predictions\": inference_result_batch.predictions, \"targets\": inference_result_batch.targets,\n \"tags\": inference_result_batch.tags}\n irb_filtered_dict_gathered = accelerator.gather_for_metrics(irb_filtered_dict)\n\n irb_filtered_gathered = InferenceResultBatch(predictions=irb_filtered_dict_gathered[\"predictions\"],\n targets=irb_filtered_dict_gathered[\"targets\"],\n tags=irb_filtered_dict_gathered[\"tags\"])\n\n batch_loss = self._calculate_loss_scores(irb_filtered_gathered, split_loss_funs)\n batch_losses.append(batch_loss)\n\n irb_filtered = irb_filtered_gathered.split_results(predictions_keys=self.cpu_prediction_subscription_keys,\n target_keys=self.cpu_target_subscription_keys,\n device=torch.device(\"cpu\"))\n\n inference_result_batches_cpu.append(irb_filtered)\n processed_batches += 1\n splits = list(self.dataset_loaders.keys())\n if accelerator.is_main_process:\n batch_processed_callback_fun(status=\"evaluation\",\n num_batches=num_batches,\n current_batch=processed_batches,\n splits=splits,\n current_split=split_name)\n\n # calc metrics\n try:\n prediction_batch = InferenceResultBatch.combine(inference_result_batches_cpu)\n except BatchStateError as e:\n raise EvaluationError(f\"Error combining inference result batch on split {split_name}.\") from e\n\n # select metrics for split\n if self.metrics_computation_config is not None:\n metric_tags = [metric_tag for metric_tag, applicable_splits in self.metrics_computation_config.items()\n if split_name in applicable_splits]\n split_metrics = [metric for metric in self.metrics if metric.tag in metric_tags]\n else:\n split_metrics = self.metrics\n metric_scores = self._calculate_metric_scores(prediction_batch, split_metrics)\n\n # aggregate losses\n loss_keys = batch_losses[0].keys()\n loss_scores = {key: [torch.mean(torch.Tensor([l[key] for l in batch_losses])).item()] for key in loss_keys}\n\n evaluation_result = EvaluationBatchResult(losses=loss_scores,\n metrics=metric_scores,\n dataset_name=dataset_loader.dataset_name,\n split_name=split_name)\n if epoch_result_callback_fun is not None and accelerator.is_main_process:\n epoch_result_callback_fun(evaluation_result=evaluation_result)\n return evaluation_result\n\n def _get_metric_fun(self, identifier: str, target_subscription: Enum, prediction_subscription: Enum,\n metric_fun: Callable, params: Dict[str, Any]) -> Metric:\n return Metric(identifier, target_subscription, prediction_subscription, metric_fun, params)\n\n def forward_batch(self, dataset_batch: DatasetBatch, model: NNModel,\n postprocessors: List[PredictPostProcessingIF]) -> InferenceResultBatch:\n inference_result_batch = self.inference_component.predict(model, dataset_batch, postprocessors)\n return inference_result_batch\n\n def _calculate_metric_scores(self, inference_batch: InferenceResultBatch, split_metrics: List[Metric]) -> Dict[str, List[float]]:\n metric_scores = {}\n for metric in split_metrics:\n try:\n metric_scores[metric.tag] = [metric(inference_batch)]\n except Exception as e:\n raise MetricCalculationError(f\"Error during calculation of metric {metric.tag}\") from e\n return metric_scores\n\n def _calculate_loss_scores(self, forward_batch: InferenceResultBatch, split_loss_funs: Dict[str, Loss]) -> Dict[str, List[float]]:\n loss_scores = {}\n for loss_key, loss_fun in split_loss_funs.items():\n try:\n loss_scores[loss_key] = self._get_batch_loss(loss_fun, forward_batch)\n except Exception as e:\n raise LossCalculationError(\"Error during calculation of loss {loss_key}\") from e\n\n return loss_scores\n\n def _get_batch_loss(self, loss_fun: Loss, forward_batch: InferenceResultBatch) -> List[torch.Tensor]:\n loss = loss_fun(forward_batch)\n loss = [loss.sum()]\n return loss\n","sub_path":"src/ml_gym/gym/evaluators/accelerate_evaluator.py","file_name":"accelerate_evaluator.py","file_ext":"py","file_size_in_byte":9655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"803983","text":"# deal data and plot dispersion curves\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass Dispersion(object):\n\tdef phonon_sort(self,k_point,filename1,filename2):\n\t\tself.k_point = k_point # k_point = 50#k_point数\n\t\tself.filename1 = filename1\n\t\tself.filename2 = filename2\n\t\tself.cm2THz = 33.36 # 单位转换1THz=33.36cm-1,如果频率已经是THz,修改为1\n\t\tself.number_round = 6 # 保留6位有效数字\n\t\twith open(self.filename1) as sort_before, open(self.filename2, 'w') as p_sort_after:\n\t\t\tsort = sort_before.read().strip().split()\n\t\t\t# print(sort)\n\t\t\tsort = map(eval,sort)\n\t\t\tsort = list(sort)\n\t\t\tprint('总元素数:',len(sort))\n\t\t\trow_number = int(len(sort)/self.k_point) # 原本每一行数字的数量,原子数*3,\n\t\t\tprint('\\n每一行元素数:',row_number,'个数据,其中前三个是基矢\\n')#可能多了一列,在第四列全是0.删掉\n\t\t\tatom_number = int((row_number-3)/3)\n\t\t\tprint('原子个数:',atom_number)\n\t\t\t# 由于输出的格式不正确,这里是修改格式\n\t\t\tfor i in range(self.k_point):\n\t\t\t\t# print(i)\n\t\t\t\tfor j in range(i*row_number,(i+1)*row_number):\n\t\t\t\t\t# print(sort[j])\n\t\t\t\t\t# print(j)\n\t\t\t\t\tsortly = round(sort[j],6)\n\t\t\t\t\tif self.cm2THz == 33.36:\n\t\t\t\t\t\tsortly = str(sortly/self.cm2THz)#注意数据单位修改\n\t\t\t\t\telse:\n\t\t\t\t\t\tsortly = sortly\n\t\t\t\t\tp_sort_after.write(sortly)\n\t\t\t\t\t# p_sort_after.write(str(sortly))\n\t\t\t\t\tp_sort_after.write(3*'\\t')\n\t\t\t\tp_sort_after.write('\\n')\n\n\t\t\treturn \n\n\tdef plot_curves(self, figname, dpi=300,lw=1.0, figsize_x=8, figsize_y=16, \n rxmin=0, rxmax=0.5, rymin=0, rymax=2):\n\t\tself.figname = figname\n\t\tself.figdpi = dpi \n\t\tself.linewidth = lw\n\t\tself.figsx = figsize_x\n\t\tself.figsy = figsize_y\n\t\tself.r_xmin = rxmin # range of x\n\t\tself.r_xmax = rxmax\n\t\tself.r_ymin = rymin # range of y\n\t\tself.r_ymax = rymax\n\n\t\tdata = np.loadtxt(self.filename2)\n\t\tprint(data.shape)\n\t\tif self.cm2THz == 33.36:\n\t\t\tprint('注:\\n“如果数据没有转换单位到THz,需要在此程序转换”')\n\t\t\t# 由于之前在转换单位的时候把基矢也转换了,所以在此把基矢*33.36\n\t\t\tvector = data[:,0]*33.36\n\t\t\t# print(vector)\n\t\telse:\n\t\t\tvector = data[:, 0]\n\t\tfrequency = data[:, 4:]#由于多出第一列位移,2 3 4 列是波矢,所以从第5列开始是频率\n\t\t# print(frequency)\n\t\t\n\t\tplt.rc('font', family='Times New Roman', size=16)\n\t\tplt.figure(figsize=(self.figsx, self.figsy))\n\t\tplt.plot(vector,frequency,'blue',linewidth=1)\n\t\t# 格式\n\t\t# plt.title('Dipersion', size=26)\n\t\tplt.xlabel('Wave vector',size=22)\n\t\tplt.ylabel('Frequency (THz)',size=22)\t\t\n\t\tplt.xticks(size=22)\n\t\tplt.yticks(size=22)\n\t\t# 范围\n\t\tplt.xlim(self.r_xmin, self.r_xmax)\n\t\tplt.ylim(self.r_ymin, self.r_ymax)\n\t\t# 保存\n\t\tplt.savefig(self.figname, dpi=self.figdpi)\n\t\tplt.show()\n\t\tplt.close()\n\t\treturn \n\n\n\nk_point = 50\n# 图片大小,默认为(8,6),dpi=300\nfigsize_x = 8\nfigsize_y = 16\ndpi = 300\n# 线宽默认为1.0\nlw = 1.0\n# 画图范围,默认x:(0,0.5),y:(0,2)\nrange_xmin = 0\nrange_xmax = 0.5\nrange_ymin = 0\nrange_ymax = 2\n# 原始需要分类的dipersion文件\ndisper_before = 'phonon_sorted.dat'\n# 要保存的文件\ndisper_after = 'p_sorted_20'\n\n# 保存的图片\ndisperfig = 'phonon_disp.tiff'\n\ndispersion = Dispersion()\ndispersion.phonon_sort(k_point, disper_before, disper_after)\ndispersion.plot_curves(disperfig, dpi, lw,\n figsize_x, figsize_y,\n range_xmin, range_xmax,\n range_ymin, range_ymax)\n","sub_path":"Dispersion_sort/DispersionCurves.py","file_name":"DispersionCurves.py","file_ext":"py","file_size_in_byte":3468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"588932461","text":"import torch\nimport numpy as np\n\n\nEPISILON = 1e-6\n\n\n# we can track dynamic infomation\n# naively, we can also directly insert all information into LSTM\ndef TrackingDynamicInfos(prevROIFeature, prevROI, currROIFeature, currROI, kernel=5):\n\t'''\n\tcalculate the dynamic movement info and feed into our TrackingLocGRU\n\tinput length are all tracking module capacity\n\tinput features should be the same shape for convenience\n\n\twe use the matchTrans principle here.\n\t\n\tinputs\n\t@prevROIFeature: info : tracking objects' features in previous frame\n\t\t\t\t\t\ttype : torch float tensor\n\t\t\t\t\t\tshape : (numObjects, C, H, W) h=w=32\n\t@prevROI: info : previous frames tracking objects' rois\n\t\t\t\t\t\ttype : torch tensor int\n\t\t\t\t\t\tshape : (numObjects, 4) which dim 2 contains (x1, y1, x2, y2) \n\t@currROIFeature: info : tracking objects' features in current frame\n\t\t\t\t\t\ttype : torch float tensor\n\t\t\t\t\t\tshape : (numObjects, C, H, W)\n\t@currROI: info : current frames tracking objects' rois\n\t\t\t\t\t\ttype : torch tensor int\n\t\t\t\t\t\tshape : (numObjects, 4) which dim 2 contains (x1, y1, x2, y2)\n\treturn\n\t@trackingDynamicInfos: type : torch float tensor\n\t\t\t\t\t\t\tshape : (numObjects, 3*, H, W), dim 1 contains (deltaX, deltaY) wrt previous frame\n\n\t'''\n\tnumObjects, C, H, W = prevROIFeature.size()\n\tassert prevROIFeature.size() == currROIFeature.size(), [prevROIFeature.size(), currROIFeature.size()]\n\t# assert H == 16 and W == 32, W\n\tassert len(prevROI.size()) == 2 and prevROI.size(1) == 4, prevROI.size()\n\tassert len(currROI.size()) == 2 and currROI.size(1) == 4, currROI.size()\n\ttrackingDynamicInfos = prevROIFeature.new(numObjects, 3*kernel*kernel, H, W).zero_()\n\n\ttrackingLocInfo = prevROIFeature.new(numObjects, 2, 2, H, W).zero_()\n\n\tfor i in torch.arange(numObjects):\n\t\t# if tracking object exist in last frame\n\t\t# we calculate info \n\t\tprevROIXLoc = torch.arange(W).float()\n\t\tprevROIXLoc = prevROIXLoc*(prevROI[i, 2] - prevROI[i, 0])/(W-1) + prevROI[i, 0]\n\t\tassert prevROIXLoc.size(0) == W, prevROIXLoc.size(0)\n\t\tprevROIXLoc = prevROIXLoc.expand(H, -1)\n\n\t\tcurrROIXLoc = torch.arange(W).float()\n\t\tcurrROIXLoc = currROIXLoc*(currROI[i, 2] - currROI[i, 0])/(W-1) + currROI[i, 0]\n\t\tassert currROIXLoc.size(0) == W, currROIXLoc.size(0)\n\t\tcurrROIXLoc = currROIXLoc.expand(H, -1) \n\n\t\tprevROIYLoc = torch.arange(H).float()\n\t\tprevROIYLoc = prevROIYLoc*(prevROI[i, 3] - prevROI[i, 1])/(H-1) + prevROI[i, 1]\n\t\tassert prevROIYLoc.size(0) == H, prevROIYLoc.size(0)\n\t\tprevROIYLoc = prevROIYLoc.expand(W, -1)\n\t\tprevROIYLoc = prevROIYLoc.transpose(1, 0).contiguous()\n\n\t\tcurrROIYLoc = torch.arange(H).float()\n\t\tcurrROIYLoc = currROIYLoc*(currROI[i, 3] - currROI[i, 1])/(H-1) + currROI[i, 1]\n\t\tassert currROIYLoc.size(0) == H, currROIYLoc.size(0)\n\t\tcurrROIYLoc = currROIYLoc.expand(W, -1)\n\t\tcurrROIYLoc = currROIYLoc.transpose(1, 0).contiguous()\n\n\n\t\ttrackingLocInfo[i, 0, 0] = prevROIXLoc\n\t\ttrackingLocInfo[i, 0, 1] = prevROIYLoc \n\t\ttrackingLocInfo[i, 1, 0] = currROIXLoc\n\t\ttrackingLocInfo[i, 1, 1] = currROIYLoc\n\tk_min = int(-(kernel-1)/2)\n\tk_max = int((kernel+1)/2)\n\tfor i in torch.arange(k_min, k_max):\n\t\tfor j in torch.arange(k_min, k_max):\n\t\t\tcompare_prev_features = prevROIFeature.new(prevROIFeature.size()).zero_()\n\t\t\tcompare_prev_loc = trackingLocInfo.new(numObjects, 2, H, W).zero_()\n\t\t\tcompare_prev_features[:, :, max(0, -i):min(H-i, H), max(0,-j):min(W-j, W)] = \\\n\t\t\t\t\t\tprevROIFeature[:, :, max(0,i):min(H+i, H), max(0,j):min(W+j,W)]\n\t\t\t# assert compare_prev_loc[:, 0].size() == trackingLocInfo[:, 0, 0].size() and trackingLocInfo[:, 0, 0].size() == prevROI[:, 2].size(),\\\n\t\t\t# \t[compare_prev_loc.size(), trackingLocInfo.size(), prevROI.size()]\n\t\t\tcompare_prev_loc[:, 0] = trackingLocInfo[:, 0, 0] +(i.float()*(prevROI[:, 2] - prevROI[:, 0])/(W-1)).view(-1, 1, 1)\n\t\t\tcompare_prev_loc[:, 1] = trackingLocInfo[:, 0, 1] +(j.float()*(prevROI[:, 3] - prevROI[:, 1])/(H-1)).view(-1, 1, 1)\n\n\t\t\t# print([ (3*((i-k_min)*kernel + (j-k_min))).item(), (3*((i-k_min)*kernel + (j-k_min))+2).item()])\n\t\t\t# print(trackingDynamicInfos[:, 3*((i-k_min)*kernel + (j-k_min)):3*((i-k_min)*kernel + (j-k_min))+2].size())\n\t\t\ttrackingDynamicInfos[:, 3*((i-k_min)*kernel + (j-k_min)):3*((i-k_min)*kernel + (j-k_min))+2] = \\\n\t\t\t\ttrackingLocInfo[:, 1]-compare_prev_loc\n\t\t\ttemp = compare_prev_features*currROIFeature\n\t\t\ttrackingDynamicInfos[:, 3*((i-k_min)*kernel + (j-k_min))+2] = torch.sum(temp, dim=1)\n\t\t\tdel compare_prev_features\n\t\t\tdel compare_prev_loc\n\t\t\tdel temp\n\t\t\t# torch.cuda.empty_cache()\n\n\treturn trackingDynamicInfos\n\n\ndef clip_tracking_boxes(boxes, im_info):\n\t'''\n\tim_info : [h,w]\n\t'''\n\tboxes[:,0::4].clamp_(0, im_info[1]-1)\n\tboxes[:,1::4].clamp_(0, im_info[0]-1)\n\tboxes[:,2::4].clamp_(0, im_info[1]-1)\n\tboxes[:,3::4].clamp_(0, im_info[0]-1)\n\treturn boxes\n\ndef tracking_boxes_validation_check(boxes):\n\tcount=0\n\tvalid_indexes =-boxes.new(boxes.size(0)).fill_(1).long()\n\tfor i in torch.arange(boxes.size(0)):\n\t\tif boxes[i, 2]<=boxes[i, 0] or boxes[i, 3]<=boxes[i, 1]:\n\t\t\tboxes[i] = 0\n\t\telse:\n\t\t\tvalid_indexes[count] = i\n\t\t\tcount+=1\n\tvalid_indexes = valid_indexes[:count]\n\treturn boxes, valid_indexes\n","sub_path":"lib/model/faster_rcnn/tracking_utils.py","file_name":"tracking_utils.py","file_ext":"py","file_size_in_byte":5148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"102760356","text":"from selenium import webdriver\nimport time\nfrom selenium.webdriver.common.keys import Keys\n\nprofile = webdriver.FirefoxProfile();\n#MIME type for zip file \"aaplication/zip\"\nprofile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/zip')\ndriver =webdriver.Firefox(profile);\n# driver = webdriver.Firefox()\ndriver.get('https://pixelarity.com/login')\nUNAME = driver.find_element_by_id('email')\nUNAME.send_keys('xxmrmau5@gmail.com')\nUNAME.send_keys(Keys.TAB)\n\nPASS = driver.find_element_by_id('password')\nPASS.send_keys('')\ndriver.find_element_by_class_name('fit').click()\n\ntime.sleep(5)\n#eventually make this a wait\n\ndriver.find_element_by_link_text('Browse').click()\n\ntime.sleep(5)\nid=[]\nindex = 0\n\nprint('getting ids')\nwhile True:\n divs = driver.find_elements_by_class_name('item')\n try: \n id.append(divs[index].get_attribute('id'))\n except IndexError:\n print('done')\n break # no more elements, exit the loop\n\n # # do smth\n # # ...\n index += 1\nogurl = 'https://pixelarity.com/'\nhtml ='/download/html'\npsd='/download/psd'\nurl = []\npsdurl =[]\nfor i in range(len(id)):\n print(id[i])\n url.append(ogurl + id[i] + html)\n psdurl.append(ogurl +id[i] +html) \n\nimport csv\nfrom itertools import izip\n\nwith open('some.csv', 'wb') as f:\n writer = csv.writer(f)\n writer.writerows(izip(url, psdurl))\n","sub_path":"downloadtemps.py","file_name":"downloadtemps.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"451912157","text":"x = int(input(\"輸入X座標\"))\ny = int(input(\"輸入Y座標\"))\nif (x == 0 and y == 0):\n print(\"該點位於原點\")\nelif(x == 0 and y >0):\n position =y*y\n print(\"該點位於上半平面Y軸上,離原點距離根號\",position)\nelif (x == 0 and y < 0):\n position = y*y\n print(\"該點位於下半平面Y軸上,離原點距離根號\",position)\nelif (x < 0 and y == 0):\n position =x*x\n print(\"該點位於左半平面X軸上,離原點距離根號\",position)\nelif (x>0 and y ==0):\n position = x*x\n print(\"該點位於右半平面X軸上,離原點距離根號\",position)\nelif (x>0 and y > 0 ):\n position = x*x+y*y\n print(\"該點位於第一象限,離原點距離根號\",position)\nelif(x < 0 and y > 0):\n position = x*x+y*y\n print(\"該點位於第二象限,離原點距離根號\",position)\nelif (x < 0 and y < 0):\n position = x*x+y*y\n print(\"該點位於第三象限,離原點距離根號\",position)\nelse:\n position = x*x+y*y\n print(\"該點位於第四象限,離原點距離根號\",position)\n","sub_path":"第一次midterm/練習4.py","file_name":"練習4.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"111123304","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 13 10:49:00 2020\n\n@author: rcj\n\"\"\"\nimport os\nfrom ReadMMIAfits_OCRE import Read_MMIA_Observation\nimport torch\nimport numpy as np\n\ndef npToTensor(npList):\n return torch.from_numpy(np.flip(npList,axis=0).copy())\n\ndef ASIM_DataLoader(dataDir, loadStatusUpdate,minval, maxval, p, sliceSize):\n if ('P1D' and 'P2D' and 'P3D') not in locals():\n ErroneousFiles = []\n workingFiles = []\n fileList = []\n for root, dirs, files in os.walk(dataDir):\n fileList.append([os.path.join(root, x) for x in files]) #Get all file paths\n \n fileListFlatten = [item for items in fileList for item in items] # Flatten the list to 1D list\n fileListFlatten = np.random.choice(fileListFlatten, int(len(fileListFlatten)*p), replace=False)\n fileListFlatten = [str(x) for x in fileListFlatten]\n # Define empty data vecors for each photometer\n P1D = []\n P2D = []\n P3D = []\n Time = []\n #Obs_ID = []\n #FrameTime = []\n for count, file in enumerate(fileListFlatten):\n if count % loadStatusUpdate == 0: # Print loading progress.\n print('Files loaded: ',count, '/', len(fileListFlatten))\n try: # Try to load the data\n # RCJ Note: ASIM level 1 raw data is not \"nice\" to read. Instead of using Pytorch build in\n # load() function, we will use OC's load function and simply only save what we need.\n Observation_ID,Dat,Dat0,FrameTimeC,FrameTimeP,TimeError,Nframe,P1Exist,P2Exist,P3Exist,CHU1Meta_exists,CHU2Meta_exists,CHU1Exist,CHU2Exist, \\\n DPU_Count,DPU_PreReset,Priority,Frame_Number,Priority,Frame_Number,PHOT1_Trig,PHOT2_Trig,PHOT3_Trig,CHU1_TrigR,CHU1_TrigC,CHU1_Trig, \\\n CHU2_TrigR,CHU2_TrigC,CHU2_Trig,MXT,T,TT,BT,PHOT1_Data,PHOT2_Data,PHOT3_Data,PhotSizeTot,PhotSize,mR,MR,mC,MC,CHU1Meta,CHU2Meta, \\\n CHU1,CHU2,LON,LAT,ALT,PosX,PosY,PosZ,PosVX,PosVY,PosVZ,PosYaw,PosPitch,PosRoll,CHU1_row_peak_value,CHU1_row_integral_value, \\\n CHU1_column_peak_value,CHU1_column_integral_value,CHU2_row_peak_value,CHU2_row_integral_value,CHU2_column_peak_value, \\\n CHU2_column_integral_value,PHOT1_peak_value,PHOT1_integral_value,PHOT2_peak_value,PHOT2_integral_value,PHOT3_peak_value, \\\n PHOT3_integral_value,PHOT1_temp,PHOT2_temp,PHOT3_temp,CHU1_temp,CHU2_temp,CHU1_20v_45v,CHU2_20v_45v = \\\n Read_MMIA_Observation(file,False,1) \n workingFiles.append(fileListFlatten[count])\n \n if(P1Exist): #If the datafile contains photometer data, store it\n # Obs_ID.append(Observation_ID[0])\n currentSlice = 0\n previousSlice = 0\n while currentSlice < len(PHOT1_Data) - sliceSize:\n currentSlice += sliceSize\n P1D.append(npToTensor(PHOT1_Data[previousSlice:currentSlice]))\n P2D.append(npToTensor(PHOT2_Data[previousSlice:currentSlice]))\n P3D.append(npToTensor(PHOT3_Data[previousSlice:currentSlice]))\n Time.append(npToTensor(T[previousSlice:currentSlice]))\n previousSlice = currentSlice\n # FrameTime.append(FrameTimeP)\n # Some files appear to be erroneous, skip these. Create list with names for further investigation\n # RCJ Personal note: Ask OC what is going on with erroneous files.\n except: \n #print('Erroneous dataset:', fileListFlatten[count])\n ErroneousFiles.append(fileListFlatten[count])\n else:\n print('Files already loaded, skipping reloading')\n \n class Dataset(torch.utils.data.Dataset):\n 'Characterizes a dataset for PyTorch'\n def __init__(self, P1D, P2D, P3D, Time):\n 'Initialization'\n #self.Obs_ID = npToTensor(Obs_ID)\n self.P1D = P1D\n self.P2D = P2D\n self.P3D = P3D\n self.Time = Time\n #self.FrameTime = FrameTime\n \n \n def __len__(self):\n 'Denotes the total number of samples'\n return len(self.P1D)\n \n def __getitem__(self, idx):\n 'Generates one sample of data'\n # Select sample\n #ID = self.Obs_ID[idx]\n P1 = self.P1D[idx]\n P2 = self.P2D[idx]\n P3 = self.P3D[idx]\n Time = self.Time[idx]\n #FrameTime = self.FrameTime[idx]\n #sample = {'P1D': P1, 'P2D': P2, 'P3D': P3, 'Time': Time}\n return P1, P2, P3, Time\n \n class NormalizedDataset(torch.utils.data.Dataset):\n def __init__(self, dataset, minval, maxval):\n super().__init__()\n self.dataset = dataset\n self.minval = minval\n self.maxval = maxval\n \n def __len__(self):\n return len(self.dataset)\n \n def __getitem__(self, idx):\n return torch.clamp((self.dataset[idx] - self.minval) / (self.maxval - self.minval), 0.000001, 0.99999)\n\n CollectedData = Dataset(NormalizedDataset(P1D,minval,maxval), NormalizedDataset(P2D,minval,maxval), NormalizedDataset(P3D,minval,maxval), Time)\n return CollectedData\n","sub_path":"Scripts/TrainingTheModel/ASIM_DataLoader_Slicing_Func.py","file_name":"ASIM_DataLoader_Slicing_Func.py","file_ext":"py","file_size_in_byte":5373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"523765151","text":"# -*- coding:utf-8 -*-\n\"\"\"\n@author: Gordon Han\n@contact: Gordon-Han@hotmail.com\n\"\"\"\nimport re\nimport json\n\nimport lxml.html\n\nimport config\n\n\ndef scraping_callback(html):\n scraping(html)\n return get_follow_pages(html)\n\n\ndef scraping(html):\n p = re.compile('
    .*?(\\d+).*?(.*?).*?(.*?)

    .*?'\n + '(.*?)

    .*?(.*?).*?(.*?)', re.S)\n with open('MaoYan.txt', 'a', encoding='utf-8') as f:\n for result in p.findall(html):\n r = {\n \"index\": result[0],\n \"img\": result[1],\n \"title\": result[2],\n \"star\": result[3].strip()[3:],\n \"time\": result[4].strip()[5:],\n \"score\": result[5] + result[6]\n }\n f.write(json.dumps(r, ensure_ascii=False) + '\\n')\n\n\ndef get_follow_pages(html):\n tree = lxml.html.fromstring(html)\n links = tree.xpath('//ul[@class=\"list-pager\"]/li[last()]/a')\n for link in links:\n yield link.get('href')\n\n\ndef match(link, link_regex):\n return re.match(link_regex, link)\n\n\ndef get_links(html):\n web_page = re.compile(']+href=[\"\\'](.*?)[\"\\']', re.IGNORECASE)\n return web_page.findall(html)\n","sub_path":"ch03/maoyan_top100_movie/scraping_callback.py","file_name":"scraping_callback.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"113381349","text":"def decrypt(word):\n keys = {}\n for letter in word:\n keys[letter] = keys.get(letter, 0) + 1\n key = sorted(keys.items(), key=lambda x: x[1], reverse=True)[0]\n return chr(ord(key[0]) - ord(\" \"))\n\n\ndef encryption(word, key, decode=False):\n ls = []\n for i in word:\n if decode:\n ls.append(chr((ord(i) - ord(key)) % 65536))\n else:\n ls.append(chr(ord(i) + ord(key) % 65536))\n return \"\".join(ls)\n\n\nif __name__ == '__main__':\n\n text = \"I Love UNIX\"\n key = \"I\"\n\n encrypted_text = encryption(text, key)\n decrypted_text = encryption(encrypted_text, key, decode=True)\n\n print(f\"{text} -> «{encrypted_text}» -> {decrypted_text}\")\n\n print(f\"Подобранный ключ: {decrypt(encrypted_text)}\")\n","sub_path":"cesar.py","file_name":"cesar.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"62412727","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('classroom/group//course//assignments/',views.Student_Assignment_Names.as_view(),name=\"Assignment_names\"),\n path('classroom/group/course/create_assignment/',views.Create_Assignment,name=\"Assignment_names\"),\n path('classroom/group_course//assignments/',views.Teacher_Assignment_Names.as_view(),name=\"Assignment_names\"),\n path('classroom/group/course/submit_assignment/',views.submit_assignment,name=\"submit_assignment\"),\n path('assignment//',views.Assignment_Details.as_view(),name=\"assignment_details\"),\n path('assignment//assignment_submitted_students',views.assignment_submitted_students.as_view(),name=\"assignment_submitted_students\"),\n \n ]","sub_path":"root/backend/lms/assignment/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"579677348","text":"'''\nAuthor: David L. Bernick\nEdited by: Jairo Navarro\n\nThe MIT License (MIT)\n\nCopyright (c) 2015 David L. Bernick, Jairo Navarro\n'''\n\nimport sys\nclass FastAreader :\n '''\n Class to provide reading of a file containing one or more FASTA\n formatted sequences:\n object instantiation:\n FastAreader():\n \n object attributes:\n fname: the initial file name\n \n methods:\n readFasta() : returns header and sequence as strings.\n Author: David Bernick\n Date: April 19, 2013\n '''\n \n def __init__ (self, fname=''):\n '''contructor: saves attribute fname '''\n \n self.fname = fname\n \n def doOpen (self):\n if self.fname is '':\n return sys.stdin\n else:\n return open(self.fname)\n \n def readFasta (self):\n '''\n using filename given in init, returns each included FastA record\n as 2 strings - header and sequence. If filename was not provided,\n stdin is used. Whitespace is removed, and sequence is upcased.\n The initial '>' is removed from the header.\n '''\n header = ''\n sequence = ''\n \n with self.doOpen() as fileH:\n # initialize return containers\n header = ''\n sequence = ''\n \n # skip to first fasta header\n line = fileH.readline()\n while not line.startswith('>') :\n line = fileH.readline()\n header = line[1:].rstrip()\n \n # header is saved, get the rest of the sequence\n # up until the next header is found\n # then yield the results and wait for the next call.\n # next call will resume at the yield point\n # which is where we have the next header\n for line in fileH:\n if line.startswith ('>'):\n yield header,sequence\n header = line[1:].rstrip()\n sequence = ''\n else :\n sequence += ''.join(line.rstrip().split()).upper()\n # final header and sequence will be seen with an end of file\n # with clause will terminate, so we do the final yield of the data\n yield header,sequence\n\n","sub_path":"fastaReader.py","file_name":"fastaReader.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"158899036","text":"#! /usr/bin/env python\nimport re\nimport sys\n\n\n\nif(2 > len(sys.argv)):\n print(\"Too few parameters. Usage:\\nlogreg.py \")\n\nprint(\"Will now process %s\\n\" % sys.argv[1])\n\ninfile = open(sys.argv[1], 'r')\ndata = infile.read()\ninfile.close()\n\naddDatesRE = re.compile('\\\"stamp\\\"\\s*:\\s*\\{\\s*\\\"\\$numberLong\\\"\\s*:\\s*\\\"\\s*(?P\\d*)\\s*\\\"\\s*\\}')\ndata = addDatesRE.sub('\"stamp\" : {\"$date\" : \\g}', data)\n\nrepLIntsRE = re.compile('\\{\\s*\\\"\\$numberLong\\\"\\s*:\\s*\\\"\\s*(?P\\d*)\\s*\\\"\\s*\\}')\ndata = repLIntsRE.sub('\\g', data)\n\noutfile = open(sys.argv[1], 'w')\noutfile.write(\"%s\" % data)\noutfile.close()\n","sub_path":"src/logreg.py","file_name":"logreg.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"277160433","text":"import random\nimport time\nfrom fractions import gcd\nimport numpy as np\n\ndef primeq(x):\n\tif x in (2,3,5,7,11,13,17,19,23,29,31,37,41,43,47): return(True)\n\tif x < 2: return(False)\n\tif gcd(x,614889782588491410) != 1: return(False)\n\td = x - 1\n\ts = 0\n\twhile d % 2 == 0:\n\t\td /= 2\n\t\ts += 1\n\tk = 10;\n\tfor i in range(k):\n\t\ta = random.randint(2,x-2)\n\t\tm = pow(a,d,x)\n\t\tif (m == 1) | (m == x-1): continue\n\t\tfor j in range(s-1):\n\t\t\tm = pow(m,2,x)\n\t\t\tif m == x-1: break\n\t\t\tif m == 1: return(False)\n\t\tif m == x-1: continue\n\t\telse: return(False)\n\treturn(True)\n\ndef primesfrom2to(n):\n # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188\n \"\"\" Input n>=6, Returns a array of primes, 2 <= p < n \"\"\"\n sieve = np.ones(n/3 + (n%6==2), dtype=np.bool)\n sieve[0] = False\n for i in xrange(int(n**0.5)/3+1):\n if sieve[i]:\n k=3*i+1|1\n sieve[ ((k*k)/3) ::2*k] = False\n sieve[(k*k+4*k-2*k*(i&1))/3::2*k] = False\n return np.r_[2,3,((3*np.nonzero(sieve)[0]+1)|1)]\n\nprint(primesfrom2to(100))\n\nt = time.clock()\ni = 0\ncomposites = []\nwhile True:\n\tx = random.randint(2**127,2**128)\n\ti += 1\n\tif primeq(x): break\n\t#else: composites.append(x) \ntimetaken = time.clock()-t\nprint('Took '+str(timetaken)+' seconds to test '+str(i)+' numbers. '+str(i/timetaken)+' numbers per second')\nprint(x)\n","sub_path":"mr.py","file_name":"mr.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"319233302","text":"import pyrax\n\npyrax.set_setting('identity_type', 'rackspace')\n\npyrax.set_credentials('{username}', '{apiKey}')\n\ndomain = pyrax.cloud_dns.find(name=\"example.com\")\n\nrecord = domain.get_record('{recordId}')\n\nrecord.update(data=\"192.168.1.2\")\n\n# Super awesome 'get local IP' mython string. I got it from\n# http://stackoverflow.com/a/1267524\nprint([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])\n","sub_path":"rax-dynamicDNS.py","file_name":"rax-dynamicDNS.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"596462537","text":"from flask import Flask, jsonify, request\nimport os\nimport logging\nimport logstash\nimport sys\nimport logging.handlers\n\n#if 'LOG_HOST' not in os.environ:\n# raise(Exception(\"LOG_HOST NOT DEFINED\"))\n\n#host = os.environ['LOG_HOST']\n\ntest_logger = logging.getLogger('python-http-logger')\ntest_logger.setLevel(logging.INFO)\ntest_logger.addHandler(logging.handlers.HTTPHandler('{{MYDESTNAME}}', '/', method='POST'))\n\napp = Flask(__name__)\n\ndef log_request(req):\n extra = {\n 'ip': request.environ.get('X-Forwarded-For', request.remote_addr),\n 'url': req.full_path,\n }\n test_logger.info('honeypot: ', extra=extra)\n\n# data_to_log.update(req.headers)\n\n@app.route('/', defaults={'path': ''})\n@app.route('/')\ndef honey(path):\n log_request(request)\n return jsonify({'result': 'ok'})\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\",port=8080)\n","sub_path":"serverless/honeypot.py","file_name":"honeypot.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"88455602","text":"#####################################################################\r\n# -*- coding: iso-8859-1 -*- #\r\n# #\r\n# Frets on Fire #\r\n# Copyright (C) 2006 Sami Kyöstilä #\r\n# 2008 myfingershurt #\r\n# 2008 Glorandwarf #\r\n# 2008 evilynux #\r\n# #\r\n# This program is free software; you can redistribute it and/or #\r\n# modify it under the terms of the GNU General Public License #\r\n# as published by the Free Software Foundation; either version 2 #\r\n# of the License, or (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, write to the Free Software #\r\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, #\r\n# MA 02110-1301, USA. #\r\n#####################################################################\r\n\r\nfrom builtins import str\nfrom builtins import range\nfrom builtins import object\nfrom Font import Font\r\nfrom Texture import Texture\r\nfrom Svg import ImgDrawing, SvgContext\r\nfrom Texture import Texture\r\nfrom Audio import Sound\r\nfrom Language import _\r\nimport random\r\nimport Language\r\nimport Config\r\nimport Version\r\n#myfingershurt: needed for multi-OS file fetching\r\nimport os\r\nimport sys\r\nimport Player\r\nimport Log\r\n\r\n# these constants define a few customized letters in the default font\r\n#MFH - with the new simplified Font.py, no more custom glpyhs... let's do a simple replacement here for now...\r\nSTAR1 = ' '\r\nSTAR2 = '*'\r\nLEFT = '<'\r\nRIGHT = '>'\r\nSTAR3 = STAR1\r\nSTAR4 = STAR2\r\n\r\n#-STAR1 = unicode('\\x10')\r\n#-STAR2 = unicode('\\x11')\r\n#-LEFT = unicode('\\x12')\r\n#-RIGHT = unicode('\\x13')\r\n#-STAR3 = unicode('\\x14') #Worldrave - Added new Star3\r\n#-STAR4 = unicode('\\x15') #Worldrave - Added new Star4\r\n\r\nclass Data(object):\r\n \"\"\"A collection of globally used data resources such as fonts and sound effects.\"\"\"\r\n def __init__(self, resource, svg):\r\n\r\n self.logClassInits = Config.get(\"game\", \"log_class_inits\")\r\n if self.logClassInits == 1:\r\n Log.debug(\"Data class init (Data.py)...\")\r\n\r\n self.resource = resource\r\n self.svg = svg\r\n\r\n self.sfxVolume = Config.get(\"audio\", \"SFX_volume\")\r\n self.crowdVolume = Config.get(\"audio\", \"crowd_volume\")\r\n\r\n #Get theme\r\n themename = Config.get(\"coffee\", \"themename\")\r\n self.themeLabel = themename\r\n self.themeCoOp = False\r\n\r\n self.players = None\r\n self.players = Player.loadPlayers()\r\n\r\n #myfingershurt: check for existance of theme path\r\n themepath = os.path.join(Version.dataPath(), \"themes\")\r\n self.themepath = themepath\r\n self.path = Version.dataPath()\r\n\r\n if not os.path.exists(os.path.join(themepath,themename,\"notes.png\")):\r\n #myfingershurt: here need to ensure an existing theme is selected\r\n themes = []\r\n defaultTheme = None #myfingershurt\r\n allthemes = os.listdir(themepath)\r\n for name in allthemes:\r\n if os.path.exists(os.path.join(themepath,name,\"notes.png\")):\r\n themes.append(name)\r\n if name == \"MegaLight\": #myfingershurt\r\n defaultTheme = name #myfingershurt\r\n i = len(themes)\r\n if defaultTheme != \"MegaLight\": #myfingershurt\r\n defaultTheme = themes[0] #myfingershurt\r\n #not a valid theme if notes.png isn't there! Force default theme:\r\n Config.set(\"coffee\", \"themename\",defaultTheme)\r\n #re-init Data with new default\r\n themename = defaultTheme\r\n self.themeLabel = themename\r\n\r\n\r\n if not os.path.exists(os.path.join(Version.dataPath(), \"themes\", themename, \"vocals\")):\r\n self.vocalPath = \"vocals\"\r\n else:\r\n self.vocalPath = os.path.join(\"themes\",themename,\"vocals\")\r\n\r\n if self.fileExists(os.path.join(\"themes\",themename,\"spfill.png\")):\r\n self.theme = 0\r\n elif self.fileExists(os.path.join(\"themes\",themename,\"overdrive fill.png\")):\r\n self.theme = 2\r\n self.themeCoOp = True\r\n else:\r\n self.theme = 1\r\n if self.fileExists(os.path.join(\"themes\",themename,\"coop_rockmeter.png\")):\r\n self.themeCoOp = True\r\n\r\n self.fontScreenBottom = 0.75 #from our current viewport's constant 3:4 aspect ratio (which is always stretched to fill the video resolution)\r\n\r\n\r\n #myfingershurt: multi-OS compatibility file access fixes using os.path.join()\r\n # load font customization images\r\n\r\n #Worldrave - Use new defined Star3 and star4. Using star1 and star2 as a fallback.\r\n\r\n #MFH - no more custom glyphs, these are wasting memory.\r\n #MFH - but we do need these star1-4 images anyway. Leaving them loaded here in the Data object.\r\n self.loadImgDrawing(self, \"star1\", os.path.join(\"themes\",themename,\"star1.png\"), textureSize = (128, 128))\r\n self.loadImgDrawing(self, \"star2\", os.path.join(\"themes\",themename,\"star2.png\"), textureSize = (128, 128))\r\n\r\n #MFH - let's not rely on errors here if we don't have to...\r\n if self.fileExists(os.path.join(\"themes\",themename,\"star3.png\")):\r\n self.loadImgDrawing(self, \"star3\", os.path.join(\"themes\",themename,\"star3.png\"), textureSize = (128, 128))\r\n else:\r\n self.star3 = self.star1\r\n if self.fileExists(os.path.join(\"themes\",themename,\"star4.png\")):\r\n self.loadImgDrawing(self, \"star4\", os.path.join(\"themes\",themename,\"star4.png\"), textureSize = (128, 128))\r\n else:\r\n self.star4 = self.star2\r\n\r\n\r\n if self.fileExists(os.path.join(\"themes\",themename,\"starperfect.png\")):\r\n self.loadImgDrawing(self, \"starPerfect\", os.path.join(\"themes\",themename,\"starperfect.png\"), textureSize = (128, 128))\r\n self.perfectStars = True\r\n self.maskStars = False\r\n else:\r\n self.starPerfect = self.star2\r\n self.fcStars = False\r\n self.starFC = self.star2\r\n self.maskStars = True\r\n self.perfectStars = False\r\n\r\n #self.perfectStars = False\r\n if self.perfectStars:\r\n if self.fileExists(os.path.join(\"themes\",themename,\"starfc.png\")):\r\n self.loadImgDrawing(self, \"starFC\", os.path.join(\"themes\",themename,\"starfc.png\"), textureSize = (128, 128))\r\n self.fcStars = True\r\n else:\r\n #self.starFC = None\r\n self.starFC = self.starPerfect\r\n self.fcStars = False\r\n\r\n #self.loadImgDrawing(self, \"left\", \"left.png\", textureSize = (128, 128))\r\n #self.loadImgDrawing(self, \"right\", \"right.png\", textureSize = (128, 128))\r\n\r\n # load misc images\r\n self.loadImgDrawing(self, \"loadingImage\", os.path.join(\"themes\",themename,\"loadingbg.png\"), textureSize = (256,256))\r\n try:\r\n self.loadImgDrawing(self, \"submenuSelect\", os.path.join(\"themes\",themename,\"submenuselect.png\"))\r\n subSelectImgW = self.submenuSelect.width1()\r\n self.submenuSelectFound = True\r\n self.subSelectWFactor = 640.000/subSelectImgW\r\n self.subSelectImgH = self.submenuSelect.height1()\r\n except IOError:\r\n self.submenuSelectFound = False\r\n self.loadImgDrawing(self, \"submenuSelect\", os.path.join(\"themes\",themename,\"menu\",\"selected.png\"))\r\n self.subSelectWFactor = 0\r\n\r\n # load all the data in parallel\r\n asciiOnly = not bool(Language.language) or Language.language == \"Custom\"\r\n reversed = _(\"__lefttoright__\") == \"__righttoleft__\" and True or False\r\n scale = 1\r\n scale2 = .5\r\n # evilynux - Load bigger fonts so they're nicer when scaled, scaling readjusted\r\n fontSize = [44, 108, 34, 32, 30]\r\n\r\n if asciiOnly:\r\n font = resource.fileName(\"default.ttf\")\r\n bigFont = resource.fileName(\"title.ttf\")\r\n else:\r\n Log.debug(\"Main font International.ttf used!\")\r\n font = \\\r\n bigFont = resource.fileName(\"international.ttf\")\r\n\r\n # load fonts\r\n font1 = lambda: Font(font, fontSize[0], scale = scale*.5, reversed = reversed, systemFont = not asciiOnly)\r\n font2 = lambda: Font(bigFont, fontSize[1], scale = 1, reversed = reversed, systemFont = not asciiOnly)\r\n if self.theme == 1: # evilynux - No outline for GH3\r\n font3 = lambda: Font(pauseFont, fontSize[2], scale = scale2, reversed = reversed, systemFont = not asciiOnly, outline = False)\r\n else:\r\n font3 = lambda: Font(pauseFont, fontSize[2], scale = scale2, reversed = reversed, systemFont = not asciiOnly)\r\n font4 = lambda: Font(scoreFont, fontSize[3], scale = scale2, reversed = reversed, systemFont = not asciiOnly, outline = False)\r\n font5 = lambda: Font(streakFont, fontSize[3], scale = scale2, reversed = reversed, systemFont = not asciiOnly, outline = False)\r\n if self.theme == 1:\r\n font6 = lambda: Font(loadingFont, fontSize[3], scale = scale2*1.4, reversed = reversed, systemFont = not asciiOnly, outline = False, shadow = True) #Worldrave - Added shadow to Loading Phrases in GH-Based Theme's\r\n else:\r\n font6 = lambda: Font(loadingFont, fontSize[3], scale = scale2, reversed = reversed, systemFont = not asciiOnly, outline = False)\r\n if self.theme == 2:\r\n font7 = lambda: Font(songFont, fontSize[4], scale = scale2, reversed = reversed, systemFont = not asciiOnly, outline = False)#kk69: loads font specific for song name in Guitar Scene =)\r\n else:\r\n font7 = lambda: Font(songFont, fontSize[0], scale = scale2, reversed = reversed, systemFont = not asciiOnly, outline = False)#kk69: loads font specific for song name in Guitar Scene =)\r\n font8 = lambda: Font(songListFont, fontSize[3], scale = scale2, reversed = reversed, systemFont = not asciiOnly, outline = False) #MFH\r\n font9 = lambda: Font(shadowfont, fontSize[3], scale = scale2, reversed = reversed, systemFont = not asciiOnly, outline = False, shadow = True) #blazingamer\r\n font10 = lambda: Font(streakFont2, fontSize[2], scale = scale2*1.08, reversed = reversed, systemFont = not asciiOnly, outline = False, shadow = True) #blazingamer - Worldrave modified size to accuracy.\r\n\r\n\r\n resource.load(self, \"font\", font1, onLoad = self.customizeFont, synch = True)\r\n resource.load(self, \"bigFont\", font2, onLoad = self.customizeFont, synch = True)\r\n\r\n\r\n #MFH - seems like these should be up here...\r\n menuFont = resource.fileName(os.path.join(\"themes\",themename,\"menu.ttf\"))\r\n pauseFont = resource.fileName(os.path.join(\"themes\",themename,\"pause.ttf\"))\r\n scoreFont = resource.fileName(os.path.join(\"themes\",themename,\"score.ttf\"))\r\n\r\n if self.fileExists(os.path.join(\"themes\",themename,\"Streak.ttf\")):\r\n streakFont = resource.fileName(os.path.join(\"themes\",themename,\"streak.ttf\"))\r\n else:\r\n streakFont = resource.fileName(os.path.join(\"themes\",themename,\"score.ttf\"))\r\n if self.fileExists(os.path.join(\"themes\",themename,\"Song.ttf\")):\r\n songFont = resource.fileName(os.path.join(\"themes\",themename,\"song.ttf\"))\r\n else:\r\n songFont = resource.fileName(os.path.join(\"themes\",themename,\"menu.ttf\"))#kk69: use menu font when song font is not present\r\n\r\n if self.fileExists(os.path.join(\"themes\",themename,\"loading.ttf\")):\r\n loadingFont = resource.fileName(os.path.join(\"themes\",themename,\"loading.ttf\"))\r\n else:\r\n loadingFont = resource.fileName(\"default.ttf\")\r\n\r\n if self.fileExists(os.path.join(\"themes\",themename,\"songlist.ttf\")):\r\n songListFont = resource.fileName(os.path.join(\"themes\",themename,\"songlist.ttf\"))\r\n else:\r\n songListFont = menuFont\r\n if self.fileExists(os.path.join(\"themes\",themename,\"songlist.ttf\")):\r\n shadowfont = resource.fileName(os.path.join(\"themes\",themename,\"songlist.ttf\"))\r\n else:\r\n shadowfont = menuFont\r\n\r\n #blazingamer\r\n if self.fileExists(os.path.join(\"themes\",themename,\"streakphrase.ttf\")):\r\n streakFont2 = resource.fileName(os.path.join(\"themes\",themename,\"streakphrase.ttf\"))\r\n else:\r\n streakFont2 = menuFont\r\n\r\n #blazingamer:Reorganized\r\n if self.theme == 0:\r\n font1 = lambda: Font(menuFont, fontSize[2], scale = scale*.5, reversed = reversed, systemFont = not asciiOnly)\r\n font2 = lambda: Font(menuFont, fontSize[2], scale = scale*.5, reversed = reversed, systemFont = not asciiOnly, outline = False)\r\n resource.load(self, \"lfont\", font2, onLoad = self.customizeFont, synch = True)\r\n resource.load(self, \"font\", font1, onLoad = self.customizeFont, synch = True)\r\n elif self.theme == 1:\r\n font1 = lambda: Font(menuFont, fontSize[3], scale = scale*.5, reversed = reversed, systemFont = not asciiOnly, outline = False) #Worldrave - Removed outline from options text on GH-Based theme's. No other drawbacks noticed.\r\n font2 = lambda: Font(menuFont, fontSize[3], scale = scale*.5, reversed = reversed, systemFont = not asciiOnly, outline = False)\r\n resource.load(self, \"lfont\", font2, onLoad = self.customizeFont, synch = True)\r\n resource.load(self, \"font\", font1, onLoad = self.customizeFont, synch = True)\r\n elif self.theme == 2:\r\n font1 = lambda: Font(menuFont, fontSize[4], scale = scale*.5, reversed = reversed, systemFont = not asciiOnly, outline = False)\r\n resource.load(self, \"font\", font1, onLoad = self.customizeFont, synch = True)\r\n\r\n\r\n resource.load(self, \"pauseFont\", font3, onLoad = self.customizeFont, synch = True)\r\n resource.load(self, \"scoreFont\", font4, onLoad = self.customizeFont, synch = True)\r\n resource.load(self, \"streakFont\", font5, onLoad = self.customizeFont, synch = True)\r\n resource.load(self, \"songFont\", font7, onLoad = self.customizeFont, synch = True)\r\n resource.load(self, \"streakFont2\", font10, onLoad = self.customizeFont, synch = True)#blazingamer\r\n\r\n resource.load(self, \"songListFont\", font8, onLoad = self.customizeFont, synch = True)\r\n resource.load(self, \"shadowfont\", font9, onLoad = self.customizeFont, synch = True)\r\n resource.load(self, \"loadingFont\", font6, onLoad = self.customizeFont, synch = True)\r\n\r\n self.fontDict = {\"font\": self.font, \"bigFont\": self.bigFont, \"pauseFont\": self.pauseFont, \"scoreFont\": self.scoreFont, \\\r\n \"streakFont\": self.streakFont, \"songFont\": self.songFont, \"streakFont2\": self.streakFont2, \\\r\n \"songListFont\": self.songListFont, \"shadowfont\": self.shadowfont, \"loadingFont\": self.loadingFont}\r\n\r\n\r\n if self.fileExists(os.path.join(\"themes\",themename,\"sounds\",\"starding.ogg\")):\r\n self.loadSoundEffect(self, \"starDingSound\", os.path.join(\"themes\",themename,\"sounds\",\"starding.ogg\"))\r\n self.starDingSoundFound = True\r\n else:\r\n Log.debug(\"Star ding sound not found, loading another sound.\")\r\n self.loadSoundEffect(self, \"starDingSound\", os.path.join(\"sounds\",\"clapsound.ogg\"))\r\n self.starDingSoundFound = False\r\n\r\n if self.fileExists(os.path.join(\"themes\",themename,\"sounds\",\"starlost.ogg\")):\r\n self.loadSoundEffect(self, \"starLostSound\", os.path.join(\"themes\",themename,\"sounds\",\"starlost.ogg\"))\r\n self.starLostSoundFound = True\r\n else:\r\n if self.fileExists(os.path.join(\"sounds\",\"starlost.ogg\")):\r\n self.loadSoundEffect(self, \"starLostSound\", os.path.join(\"sounds\",\"starlost.ogg\"))\r\n self.starLostSoundFound = True\r\n else:\r\n Log.debug(\"Star lost sound not found, loading another sound.\")\r\n self.loadSoundEffect(self, \"starLostSound\", os.path.join(\"sounds\",\"clapsound.ogg\"))\r\n self.starLostSoundFound = False\r\n\r\n if self.fileExists(os.path.join(\"sounds\",\"bassdrum.ogg\")):\r\n self.loadSoundEffect(self, \"bassDrumSound\", os.path.join(\"sounds\",\"bassdrum.ogg\"))\r\n self.bassDrumSoundFound = True\r\n else:\r\n Log.debug(\"Bass drum sound not found, loading another sound.\")\r\n self.loadSoundEffect(self, \"bassDrumSound\", os.path.join(\"sounds\",\"clapsound.ogg\"))\r\n self.bassDrumSoundFound = False\r\n\r\n#Faaa Drum sound\r\n if self.fileExists(os.path.join(\"sounds\",\"tom01.ogg\")):\r\n self.loadSoundEffect(self, \"T1DrumSound\", os.path.join(\"sounds\",\"tom01.ogg\"))\r\n self.T1DrumSoundFound = True\r\n else:\r\n Log.debug(\"Drum sound tom01 not found, loading another sound.\")\r\n self.loadSoundEffect(self, \"T1DrumSound\", os.path.join(\"sounds\",\"clapsound.ogg\"))\r\n self.T1DrumSoundFound = False\r\n if self.fileExists(os.path.join(\"sounds\",\"tom02.ogg\")):\r\n self.loadSoundEffect(self, \"T2DrumSound\", os.path.join(\"sounds\",\"tom02.ogg\"))\r\n self.T2DrumSoundFound = True\r\n else:\r\n Log.debug(\"Drum sound tom02 not found, loading another sound.\")\r\n self.loadSoundEffect(self, \"T2DrumSound\", os.path.join(\"sounds\",\"clapsound.ogg\"))\r\n self.T2DrumSoundFound = False\r\n if self.fileExists(os.path.join(\"sounds\",\"tom03.ogg\")):\r\n self.loadSoundEffect(self, \"T3DrumSound\", os.path.join(\"sounds\",\"tom03.ogg\"))\r\n self.T3DrumSoundFound = True\r\n else:\r\n Log.debug(\"Drum sound tom03 not found, loading another sound.\")\r\n self.loadSoundEffect(self, \"T3DrumSound\", os.path.join(\"sounds\",\"clapsound.ogg\"))\r\n self.T3DrumSoundFound = False\r\n if self.fileExists(os.path.join(\"sounds\",\"crash.ogg\")):\r\n self.loadSoundEffect(self, \"CDrumSound\", os.path.join(\"sounds\",\"crash.ogg\"))\r\n self.CDrumSoundFound = True\r\n else:\r\n Log.debug(\"Drum sound crash not found, loading another sound.\")\r\n self.loadSoundEffect(self, \"CDrumSound\", os.path.join(\"sounds\",\"clapsound.ogg\"))\r\n self.CDrumSoundFound = False\r\n\r\n # load sounds\r\n resource.load(self, \"screwUpsounds\", self.loadScrewUpsounds)\r\n resource.load(self, \"screwUpsoundsBass\", self.loadScrewUpsoundsBass)\r\n resource.load(self, \"screwUpsoundsDrums\", self.loadScrewUpsoundsDrums) #myfingershurt: drum screw up sounds\r\n\r\n resource.load(self, \"acceptSounds\", self.loadAcceptSounds) #myfingershurt\r\n resource.load(self, \"cancelSounds\", self.loadBackSounds) #myfingershurt\r\n\r\n resource.load(self, \"symcsounds\", self.loadScrewUpsounds)\r\n self.loadSoundEffect(self, \"selectSound1\", os.path.join(\"themes\",themename,\"sounds\",\"select1.ogg\"))\r\n self.loadSoundEffect(self, \"selectSound2\", os.path.join(\"themes\",themename,\"sounds\",\"select2.ogg\"))\r\n self.loadSoundEffect(self, \"selectSound3\", os.path.join(\"themes\",themename,\"sounds\",\"select3.ogg\"))\r\n self.loadSoundEffect(self, \"startSound\", os.path.join(\"themes\",themename,\"sounds\",\"start.ogg\"))\r\n self.loadSoundEffect(self, \"starSound\", os.path.join(\"themes\",themename,\"sounds\",\"starpower.ogg\"))\r\n\r\n if self.fileExists(os.path.join(\"themes\",themename,\"sounds\",\"failsound.ogg\")):\r\n self.loadSoundEffect(self, \"failSound\", os.path.join(\"themes\",themename,\"sounds\",\"failsound.ogg\"))\r\n else: #MFH: Fallback on general failsound.ogg\r\n self.loadSoundEffect(self, \"failSound\", os.path.join(\"sounds\",\"failsound.ogg\"))\r\n Log.warn(themename + \"\\sounds\\ failsound.ogg not found -- using general failsound.ogg instead.\")\r\n\r\n #myfingershurt: integrating Capo's starpower clap sounds\r\n self.loadSoundEffect(self, \"clapSound\", os.path.join(\"sounds\",\"clapsound.ogg\"))\r\n\r\n if self.fileExists(os.path.join(\"themes\",themename,\"sounds\",\"starpowerready.ogg\")):\r\n self.loadSoundEffect(self, \"starReadySound\", os.path.join(\"themes\",themename,\"sounds\",\"starpowerready.ogg\"))\r\n else: #MFH: Fallback on starpower.ogg\r\n self.loadSoundEffect(self, \"starReadySound\", os.path.join(\"themes\",themename,\"sounds\",\"starpower.ogg\"))\r\n Log.warn(themename + \"\\sounds\\starpowerready.ogg not found -- using starpower.ogg instead.\")\r\n\r\n #MFH - fallback on sounds\\crowdcheers.ogg, and then starpower.ogg. Note if the fallback crowdcheers was used or not.\r\n if self.fileExists(os.path.join(\"themes\",themename,\"sounds\",\"crowdcheers.ogg\")):\r\n self.loadSoundEffect(self, \"crowdSound\", os.path.join(\"themes\",themename,\"sounds\",\"crowdcheers.ogg\"), crowd = True)\r\n self.cheerSoundFound = 2\r\n elif self.fileExists(os.path.join(\"sounds\",\"crowdcheers.ogg\")):\r\n self.loadSoundEffect(self, \"crowdSound\", os.path.join(\"sounds\",\"crowdcheers.ogg\"), crowd = True)\r\n self.cheerSoundFound = 1\r\n Log.warn(themename + \"\\sounds\\crowdcheers.ogg not found -- using data\\sounds\\crowdcheers.ogg instead.\")\r\n else: #MFH: Fallback on starpower.ogg\r\n self.loadSoundEffect(self, \"crowdSound\", os.path.join(\"themes\",themename,\"sounds\",\"starpower.ogg\"))\r\n self.cheerSoundFound = 0\r\n Log.warn(themename + \"\\sounds\\crowdcheers.ogg not found -- using starpower.ogg instead.\")\r\n\r\n if self.fileExists(os.path.join(\"themes\",themename,\"sounds\",\"staractivate.ogg\")):\r\n self.loadSoundEffect(self, \"starActivateSound\", os.path.join(\"themes\",themename,\"sounds\",\"staractivate.ogg\"))\r\n else: #MFH: Fallback on starpower.ogg\r\n self.loadSoundEffect(self, \"starActivateSound\", os.path.join(\"themes\",themename,\"sounds\",\"starpower.ogg\"))\r\n Log.warn(themename + \"\\sounds\\staractivate.ogg not found -- using starpower.ogg instead.\")\r\n\r\n if self.fileExists(os.path.join(\"themes\",themename,\"sounds\",\"battleused.ogg\")):\r\n self.loadSoundEffect(self, \"battleUsedSound\", os.path.join(\"themes\",themename,\"sounds\",\"battleused.ogg\"))\r\n elif self.fileExists(os.path.join(\"themes\",themename,\"sounds\",\"staractivate.ogg\")):\r\n self.loadSoundEffect(self, \"battleUsedSound\", os.path.join(\"themes\",themename,\"sounds\",\"staractivate.ogg\"))\r\n Log.warn(themename + \"\\sounds\\battleused.ogg not found -- using staractive.ogg instead.\")\r\n else: #Fallback on starpower.ogg\r\n self.loadSoundEffect(self, \"battleUsedSound\", os.path.join(\"themes\",themename,\"sounds\",\"starpower.ogg\"))\r\n Log.warn(themename + \"\\sounds\\battleused.ogg not found -- using starpower.ogg instead.\")\r\n\r\n\r\n if self.fileExists(os.path.join(\"themes\",themename,\"sounds\",\"stardeactivate.ogg\")):\r\n self.loadSoundEffect(self, \"starDeActivateSound\", os.path.join(\"themes\",themename,\"sounds\",\"stardeactivate.ogg\"))\r\n self.starDeActivateSoundFound = True\r\n else: #MFH: Fallback on starpower.ogg - required to load, but will not be played.\r\n self.loadSoundEffect(self, \"starDeActivateSound\", os.path.join(\"themes\",themename,\"sounds\",\"starpower.ogg\"))\r\n self.starDeActivateSoundFound = False\r\n Log.warn(themename + \"\\sounds\\stardeactivate.ogg not found -- sound disabled.\")\r\n\r\n if self.fileExists(os.path.join(\"themes\",themename,\"sounds\",\"rescue.ogg\")):\r\n self.loadSoundEffect(self, \"rescueSound\", os.path.join(\"themes\",themename,\"sounds\",\"rescue.ogg\"))\r\n elif self.fileExists(os.path.join(\"themes\",themename,\"sounds\",\"staractivate.ogg\")):\r\n self.loadSoundEffect(self, \"rescueSound\", os.path.join(\"themes\",themename,\"sounds\",\"staractivate.ogg\"))\r\n Log.warn(themename + \"\\sounds\\rescue.ogg not found -- using staractivate.ogg instead.\")\r\n else:\r\n self.loadSoundEffect(self, \"rescueSound\", os.path.join(\"themes\",themename,\"sounds\",\"starpower.ogg\"))\r\n Log.warn(themename + \"\\sounds\\rescue.ogg not found -- using starpower.ogg instead.\")\r\n\r\n if self.fileExists(os.path.join(\"themes\",themename,\"sounds\",\"coopfail.ogg\")):\r\n self.loadSoundEffect(self, \"coOpFailSound\",os.path.join(\"themes\",themename,\"sounds\",\"coopfail.ogg\"))\r\n elif self.fileExists(os.path.join(\"themes\",themename,\"sounds\",\"stardeactivate.ogg\")):\r\n self.loadSoundEffect(self, \"coOpFailSound\",os.path.join(\"themes\",themename,\"sounds\",\"stardeactivate.ogg\"))\r\n Log.warn(themename + \"\\sounds\\coopfail.ogg not found -- using stardeactivate.ogg instead\")\r\n elif self.fileExists(os.path.join(\"themes\",themename,\"sounds\",\"out.ogg\")): #MFH - not all themes have out.ogg!\r\n self.loadSoundEffect(self, \"coOpFailSound\",os.path.join(\"themes\",themename,\"sounds\",\"out.ogg\"))\r\n Log.warn(themename + \"\\sounds\\coopfail.ogg not found -- using out.ogg instead\")\r\n else:\r\n self.loadSoundEffect(self, \"coOpFailSound\",os.path.join(\"themes\",themename,\"sounds\",\"back1.ogg\"))\r\n Log.warn(themename + \"\\sounds\\coopfail.ogg not found -- using back1.ogg instead\")\r\n\r\n\r\n\r\n #myfingershurt: adding You Rock sound effect\r\n if self.fileExists(os.path.join(\"themes\",themename,\"sounds\",\"rocksound.ogg\")):\r\n self.loadSoundEffect(self, \"rockSound\", os.path.join(\"themes\",themename,\"sounds\",\"rocksound.ogg\"))\r\n else:\r\n self.loadSoundEffect(self, \"rockSound\", os.path.join(\"sounds\",\"rocksound.ogg\"))\r\n\r\n #if self.theme == 0 or self.theme == 1:#GH2 or GH3\r\n # #self.loadSoundEffect(self, \"acceptSound\", os.path.join(\"themes\",themename,\"sounds\",\"in.ogg\"))\r\n # self.loadSoundEffect(self, \"cancelSounds\", os.path.join(\"themes\",themename,\"sounds\",\"out.ogg\"))\r\n #elif self.theme == 2:\r\n # #self.loadSoundEffect(self, \"acceptSound\", os.path.join(\"themes\",themename,\"sounds\",\"action.ogg\"))\r\n # self.loadSoundEffect(self, \"cancelSounds\", os.path.join(\"themes\",themename,\"sounds\",\"out.ogg\"))\r\n\r\n\r\n def SetAllScrewUpSoundFxObjectVolumes(self, volume): #MFH - single function to go through all screwup sound objects and set object volume to the given volume\r\n for s in self.screwUpsounds:\r\n s.setVolume(volume)\r\n for s in self.screwUpsoundsBass:\r\n s.setVolume(volume)\r\n for s in self.screwUpsoundsDrums:\r\n s.setVolume(volume)\r\n\r\n def SetAllSoundFxObjectVolumes(self, volume = None): #MFH - single function to go through all sound objects (and iterate through all sound lists) and set object volume to the given volume\r\n #MFH TODO - set every sound object's volume here...\r\n if volume is None:\r\n self.sfxVolume = Config.get(\"audio\", \"SFX_volume\")\r\n self.crowdVolume = Config.get(\"audio\", \"crowd_volume\")\r\n volume = self.sfxVolume\r\n self.starDingSound.setVolume(volume)\r\n self.bassDrumSound.setVolume(volume)\r\n self.T1DrumSound.setVolume(volume)\r\n self.T2DrumSound.setVolume(volume)\r\n self.T3DrumSound.setVolume(volume)\r\n self.CDrumSound.setVolume(volume)\r\n for s in self.acceptSounds:\r\n s.setVolume(volume)\r\n for s in self.cancelSounds:\r\n s.setVolume(volume)\r\n #self.cancelSounds.setVolume(volume)\r\n self.rockSound.setVolume(volume)\r\n self.starDeActivateSound.setVolume(volume)\r\n self.starActivateSound.setVolume(volume)\r\n self.battleUsedSound.setVolume(volume)\r\n self.rescueSound.setVolume(volume)\r\n self.coOpFailSound.setVolume(volume)\r\n self.crowdSound.setVolume(self.crowdVolume)\r\n self.starReadySound.setVolume(volume)\r\n self.clapSound.setVolume(volume)\r\n self.failSound.setVolume(volume)\r\n self.starSound.setVolume(volume)\r\n self.startSound.setVolume(volume)\r\n self.selectSound1.setVolume(volume)\r\n self.selectSound2.setVolume(volume)\r\n self.selectSound3.setVolume(volume)\r\n\r\n\r\n def loadSoundEffect(self, target, name, fileName, crowd = False):\r\n volume = self.sfxVolume\r\n if crowd:\r\n volume = self.crowdVolume\r\n fileName = self.resource.fileName(fileName)\r\n self.resource.load(target, name, lambda: Sound(fileName), onLoad = lambda s: s.setVolume(volume))\r\n\r\n\r\n def determineNumSounds(self, soundPath, soundPrefix, soundExtension = \".ogg\"): #MFH - auto random sound enumeration\r\n soundNum = 1\r\n while self.fileExists(os.path.join(soundPath,\"%s%d%s\" % (soundPrefix, soundNum, soundExtension) ) ):\r\n soundNum += 1\r\n return soundNum-1\r\n\r\n def getSoundObjectList(self, soundPath, soundPrefix, numSounds, soundExtension = \".ogg\"): #MFH\r\n Log.debug( str(numSounds) + \" \" + soundPrefix + \" sounds found in \" + soundPath + \": \" + soundPrefix + \"1\" + soundExtension + \" - \" + soundPrefix + str(numSounds) + soundExtension )\r\n return [Sound(self.resource.fileName(os.path.join(soundPath,\"%s%d%s\" % (soundPrefix, i, soundExtension) ))) for i in range(1, numSounds+1)]\r\n\r\n def loadBackSounds(self): #MFH - adding optional support for random choice between two back sounds\r\n soundPathTheme = os.path.join(\"themes\",self.themeLabel,\"sounds\")\r\n soundPathData = \"sounds\"\r\n soundPath = soundPathTheme\r\n soundPrefix = \"back\"\r\n numSounds = self.determineNumSounds(soundPath, soundPrefix)\r\n if numSounds > 0:\r\n return self.getSoundObjectList(soundPath, soundPrefix, numSounds)\r\n else:\r\n return [Sound(self.resource.fileName(os.path.join(\"themes\",self.themeLabel,\"sounds\",\"out.ogg\")))]\r\n\r\n def loadAcceptSounds(self):\r\n soundPathTheme = os.path.join(\"themes\",self.themeLabel,\"sounds\")\r\n soundPathData = \"sounds\"\r\n soundPath = soundPathTheme\r\n soundPrefix = \"accept\"\r\n numSounds = self.determineNumSounds(soundPath, soundPrefix)\r\n if numSounds > 0:\r\n return self.getSoundObjectList(soundPath, soundPrefix, numSounds)\r\n else:\r\n if self.theme == 0 or self.theme == 1:#GH2 or GH3\r\n return [Sound(self.resource.fileName(os.path.join(\"themes\",self.themeLabel,\"sounds\",\"in.ogg\")))]\r\n elif self.theme == 2:\r\n return [Sound(self.resource.fileName(os.path.join(\"themes\",self.themeLabel,\"sounds\",\"action.ogg\")))]\r\n\r\n def loadScrewUpsounds(self):\r\n soundPathTheme = os.path.join(\"themes\",self.themeLabel,\"sounds\")\r\n soundPathData = \"sounds\"\r\n soundPath = soundPathTheme\r\n soundPrefix = \"guitscw\"\r\n numSounds = self.determineNumSounds(soundPath, soundPrefix)\r\n if numSounds == 0:\r\n soundPath = soundPathData\r\n numSounds = self.determineNumSounds(soundPath, soundPrefix)\r\n return self.getSoundObjectList(soundPath, soundPrefix, numSounds)\r\n\r\n def loadScrewUpsoundsBass(self):\r\n soundPathTheme = os.path.join(\"themes\",self.themeLabel,\"sounds\")\r\n soundPathData = \"sounds\"\r\n soundPath = soundPathTheme\r\n soundPrefix = \"bassscw\"\r\n numSounds = self.determineNumSounds(soundPath, soundPrefix)\r\n if numSounds == 0:\r\n soundPath = soundPathData\r\n numSounds = self.determineNumSounds(soundPath, soundPrefix)\r\n return self.getSoundObjectList(soundPath, soundPrefix, numSounds)\r\n\r\n def loadScrewUpsoundsDrums(self):\r\n soundPathTheme = os.path.join(\"themes\",self.themeLabel,\"sounds\")\r\n soundPathData = \"sounds\"\r\n soundPath = soundPathTheme\r\n soundPrefix = \"drumscw\"\r\n numSounds = self.determineNumSounds(soundPath, soundPrefix)\r\n if numSounds == 0:\r\n soundPath = soundPathData\r\n numSounds = self.determineNumSounds(soundPath, soundPrefix)\r\n return self.getSoundObjectList(soundPath, soundPrefix, numSounds)\r\n\r\n def loadSyncsounds(self):\r\n return [Sound(self.resource.fileName(\"sync%d.ogg\" % i)) for i in range(1, 2)]\r\n\r\n def loadImgDrawing(self, target, name, fileName, textureSize = None):\r\n \"\"\"\r\n Load an SVG drawing synchronously.\r\n\r\n @param target: An object that will own the drawing\r\n @param name: The name of the attribute the drawing will be assigned to\r\n @param fileName: The name of the file in the data directory\r\n @param textureSize Either None or (x, y), in which case the file will\r\n be rendered to an x by y texture\r\n @return: L{ImgDrawing} instance\r\n \"\"\"\r\n fileName = self.resource.fileName(fileName)\r\n if os.path.exists(fileName):\r\n drawing = self.resource.load(target, name, lambda: ImgDrawing(self.svg, fileName), synch = True)\r\n if textureSize:\r\n drawing.convertToTexture(textureSize[0], textureSize[1])\r\n else:\r\n raise IOError(fileName)\r\n return drawing\r\n\r\n #glorandwarf: changed name to getPath\r\n def getPath(self, fileName):\r\n return self.resource.fileName(fileName)\r\n\r\n #myfingershurt: still need this fileexists function:\r\n def fileExists(self, fileName):\r\n fileName = self.resource.fileName(fileName)\r\n return os.path.exists(fileName)\r\n\r\n\r\n #MFH - no more custom font glyphs\r\n def customizeFont(self, font):\r\n pass\r\n#- # change some predefined characters to custom images\r\n#- font.setCustomGlyph(STAR1, self.star1.texture)\r\n#- font.setCustomGlyph(STAR2, self.star2.texture)\r\n#- font.setCustomGlyph(STAR3, self.star3.texture)\r\n#- font.setCustomGlyph(STAR4, self.star4.texture)\r\n#- font.setCustomGlyph(LEFT, self.left.texture)\r\n#- font.setCustomGlyph(RIGHT, self.right.texture)\r\n#- # evilynux - Load cache to speedup rendering\r\n#- if Config.get(\"performance\", \"preload_glyph_cache\"):\r\n#- font.loadCache()\r\n\r\n#MFH - acceptSound and selectSound will now be merged into either 10 random sounds or just the acceptSound as a fallback:\r\n def getAcceptSound(self):\r\n \"\"\"@return: A randomly chosen selection sound.\"\"\"\r\n return random.choice(self.acceptSounds)\r\n\r\n acceptSound = property(getAcceptSound)\r\n\r\n def getBackSound(self):\r\n \"\"\"@return: A randomly chosen selection sound.\"\"\"\r\n return random.choice(self.cancelSounds)\r\n\r\n cancelSound = property(getBackSound)\r\n\r\n\r\n def getSelectSound(self):\r\n \"\"\"@return: A randomly chosen selection sound.\"\"\"\r\n return random.choice([self.selectSound1, self.selectSound2, self.selectSound3])\r\n\r\n selectSound = property(getSelectSound)\r\n\r\n def getScrewUpSound(self):\r\n \"\"\"@return: A randomly chosen screw-up sound.\"\"\"\r\n return random.choice(self.screwUpsounds)\r\n\r\n def getScrewUpSoundBass(self):\r\n \"\"\"@return: A randomly chosen screw-up sound.\"\"\"\r\n return random.choice(self.screwUpsoundsBass)\r\n\r\n #myfingershurt: drums screw up sounds\r\n def getScrewUpSoundDrums(self):\r\n \"\"\"@return: A randomly chosen screw-up sound.\"\"\"\r\n return random.choice(self.screwUpsoundsDrums)\r\n\r\n screwUpSound = property(getScrewUpSound)\r\n screwUpSoundBass = property(getScrewUpSoundBass)\r\n screwUpSoundDrums = property(getScrewUpSoundDrums) #myfingershurt: drum screw up sounds\r\n\r\n def essentialResourcesLoaded(self):\r\n \"\"\"return: True if essential resources such as the font have been loaded.\"\"\"\r\n return bool(self.font and self.bigFont)\r\n\r\n def resourcesLoaded(self):\r\n \"\"\"return: True if all the resources have been loaded.\"\"\"\r\n return not None in list(self.__dict__.values())\r\n","sub_path":"Data.py","file_name":"Data.py","file_ext":"py","file_size_in_byte":34517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"310553461","text":"from configparser import ConfigParser\n\nfrom .parameter_store import ParameterStore\n\n\nclass FileParameterStore(ParameterStore):\n def __init__(self, filename: str):\n self.filename = filename\n self.config = ConfigParser()\n\n def get_param(self, param: str) -> str:\n self.config.read(self.filename)\n return self.config[\"config\"][param]\n\n def set_param(\n self, param: str, value: str, overwrite: bool = False, secure: bool = False\n ) -> None:\n self.config.read(self.filename)\n if overwrite:\n self.config[\"config\"][param] = value\n else:\n self.config[\"config\"].setdefault(\"param\", value)\n with open(self.filename, \"w\") as out:\n self.config.write(out)\n","sub_path":"pyhouse/paramstore/file_parameter_store.py","file_name":"file_parameter_store.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"166907165","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 26 13:14:37 2021\n@author: Bastien Longeon\n\"\"\"\nimport pandas as pd # pandas is for reading file\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\nimport time\nimport warnings\nwarnings.filterwarnings('ignore')\nstartTime = time.time()\n\nmonth = '09'\nyear = '2021'\nif year == '2021':\n month = '03'\nextension_hdf = month + 'sec.hdf5'\n\nfor i in range(0,30): # Day in september: 0 to 30\n if i < 9: day = '0' + str(i+1)\n else : day = str(i+1)\n date = str(year) + '.'+ month +'.' + day\n\n plt.figure(dpi=300, figsize=(15, 8))\n gs = gridspec.GridSpec(5, 1)\n auroral_index_kir = pd.read_hdf('maggraphs/kir'+ year + extension_hdf, 'index', start=i*1440, stop=(i+1)*1440)\n auroral_index_abk = pd.read_hdf('maggraphs/abk'+ year + extension_hdf, 'index', start=i*1440, stop=(i+1)*1440)\n hour = np.linspace(0, 24, 1440)\n\n # for k in range(0, 1440):\n # if abs(auroral_index_kir['Auroral_Index_2_H'].iloc[k]) < 75:\n # auroral_index_kir['Auroral_Index_1_2_Z/H'].iloc[k] = np.nan\n # if abs(auroral_index_abk['Auroral_Index_2_H'].iloc[k]) < 75:\n # auroral_index_abk['Auroral_Index_1_2_Z/H'].iloc[k] = np.nan\n\n\n # Subplot 1\n a1 = plt.subplot(gs[0])\n line1 = a1.scatter(hour, auroral_index_abk['Auroral_Index_1_2_Z/H'], s=.5, color='blue')\n plt.title('Auroral indexes quotients and hourly standard deviation difference during Auroral Activity\\nAbisko vs Kiruna - ' + date, fontsize=15)\n # Subplot 2\n a2 = plt.subplot(gs[1], sharex = a1)\n (line2,) = a2.plot(hour, auroral_index_abk['Auroral_Index_2_H'], linewidth=.8)\n\n # Subplot 3\n a3 = plt.subplot(gs[2], sharex = a1)\n line3 = a3.scatter(hour, auroral_index_kir['Auroral_Index_1_2_Z/H'], s=.5, color='orange')\n # Subplot 4\n a4 = plt.subplot(gs[3], sharex = a1)\n (line4,) = a4.plot(hour, auroral_index_kir['Auroral_Index_2_H'], color='orange', linewidth=.8)\n\n # Plot setup\n plt.setp(a1.get_xticklabels(), visible=False)\n plt.setp(a2.get_xticklabels(), visible=False)\n plt.setp(a3.get_xticklabels(), visible=False)\n plt.setp(a4.get_xticklabels(), visible=False)\n a1.grid()\n a2.grid()\n a3.grid()\n a4.grid()\n a1.legend([line1], ['log10(dBAC_Z/dBAC_H)_ABK'])\n a2.legend([line2], ['dBDC_H_ABK'])\n a3.legend([line3], ['log10(dBAC_Z/dBAC_H)_KIR'])\n a4.legend([line4], ['dBDC_H_KIR'])\n a1.set_ylim([-0.7, 0.7])\n a3.set_ylim([-0.7, 0.7])\n plt.xlim([0, 24])\n plt.xticks(np.arange(0,25,4)) # Show the last tick of the x-axes to see the 24-hours mark\n\n # Standard deviation study\n a = plt.subplot(gs[4])\n std_kir = list()\n std_abk = list()\n std = list()\n for k in range(0, 1440, 60):\n std_kir.append(np.nanstd(auroral_index_kir['Auroral_Index_1_2_Z/H'].iloc[k:k+60]))\n std_abk.append(np.nanstd(auroral_index_abk['Auroral_Index_1_2_Z/H'].iloc[k:k+60]))\n # for k in range(0,24):\n # std.append(std_abk[k] - std_kir[k])\n\n color = list()\n for k in range(0,1440,60):\n if np.nanmean(auroral_index_kir['Auroral_Index_2_H'].iloc[k:k+60]) > 50:\n color.append('r')\n elif np.nanmean(auroral_index_kir['Auroral_Index_2_H'].iloc[k:k+60]) < -50:\n color.append('y')\n else:\n color.append('b')\n hours = np.linspace(.5, 23.5, 24)\n scatter = a.scatter(hours, std_kir, c = color)\n a.grid()\n plt.xlim([0, 24])\n plt.ylim([-0.15, 0.35])\n # plt.legend(['std_abk - std_kir'])\n names = ['dBDC_kir < -50', 'dBDC_kir > 50', '-50 < dBDC_kir < 50']\n plt.legend(['std_kir'])\n plt.xticks(np.arange(0,25,4))\n\n plt.subplots_adjust(hspace=0.12) # Vertical gap between subplots\n plt.show()\n\n\n### Execution time ####\nexecutionTime = (time.time() - startTime)\nprint(\"Execution time: {0:.2f}s\".format(executionTime))\n","sub_path":"standard_deviation_aurora.py","file_name":"standard_deviation_aurora.py","file_ext":"py","file_size_in_byte":3886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"394339122","text":"import torch\nimport shutil\nfrom torch import optim\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport os\nfrom DataLoader2 import InitializeDataLoader\nfrom MemFFModel import MemoryFeatureFlowNet\nfrom Config2 import parse_opt, load_config\n\ndef LoadModels(opt, model, optimizer):\n resume_path = os.path.join(opt.resume_dir, opt.file_name + '.pth')\n if os.path.isfile(resume_path):\n # Load a Saved Checkpoint\n print(\"Loading checkpoint from '{}'...\".format(resume_path))\n checkpoint_dict = torch.load(resume_path, map_location=lambda storage, loc: storage)\n epoch_start = checkpoint_dict['epoch']\n best_metric = checkpoint_dict['best_metric']\n model.load_state_dict(checkpoint_dict['model'])\n optimizer.load_state_dict(checkpoint_dict['optimizer'])\n else:\n print(\"No checkpoint found at '{}'...\".format(resume_path))\n\n return model, optimizer, best_metric, epoch_start\n\ndef SaveModels(opt, model, optimizer, mAP, wAP, best_metric, epoch):\n # Save Models & Optimizer\n print(\"Saving Models at '{}'...\".format(os.path.join(opt.expr_dir, opt.exp_id, opt.file_name + '_epoch' + str(epoch) + '.pth')))\n best_flag = mAP > best_metric\n best_metric = max(mAP, best_metric)\n SaveCheckpoint({\n 'epoch': epoch + 1,\n 'best_metric': best_metric,\n 'model': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n }, opt, os.path.join(opt.expr_dir, opt.exp_id, opt.file_name + '_epoch' + str(epoch) + '.pth'), best_flag)\n\ndef SaveCheckpoint(state, opt, filename, best_flag):\n torch.save(state, filename)\n if best_flag:\n shutil.copyfile(filename, os.path.join(opt.expr_dir, opt.exp_id, opt.file_name+'_best.pth'))\n\ndef module_hook(module, grad_input, grad_out):\n print('module hook')\n print('grad_out', grad_out)\n\ndef variable_hook(grad):\n # print('variable hook')\n # print('grad', grad.mean(0))\n global gradient\n gradient += grad.mean(0).data\n # return grad\n\ndef get_new_batch_index(opt, class_label):\n '''\n output memory_index {list}{torch.LongTensor}\n memory_class_label {torch.FloatTensor of size (batch_size-memory_size+1) x n_class}\n '''\n memory_index = []\n memory_class_label = []\n for idx in range(0, min(class_label.size(0), opt.batch_size_video)-opt.memory_size+1, opt.memory_step_size):\n index = torch.arange(idx, idx+opt.memory_size, 1).type('torch.LongTensor')\n memory_index.append(index)\n memory_class_label.append(class_label[index].sum(0).gt(0).type('torch.FloatTensor'))\n memory_class_label = torch.stack(memory_class_label)\n\n return memory_index, memory_class_label\n\ndef AdjustLearningRate(opt, optimizer, epoch, mode=1):\n if mode == 0:\n # Get Current Learning Rates from Optimizer (Different Learning Rate for Parameters)\n # Need to Implement\n opt.lr_current = opt.lr * (opt.lr_schedule_rate ** (epoch // opt.lr_schedule_epoch))\n for param_group in optimizer.param_groups:\n param_group['lr'] = opt.lr_current\n else:\n # Start from the Initial Learning Rate\n opt.lr_current = opt.lr * (opt.lr_schedule_rate ** (epoch // opt.lr_schedule_epoch))\n for param_group in optimizer.param_groups:\n param_group['lr'] = opt.lr_current\n\ndef Eval(opt):\n # Initialize DataLoader for Validation Set\n test_dataloader = InitializeDataLoader(opt, mode='validation')\n\n # Initialize Model ::: Need to Change\n\n model = MemoryFeatureFlowNet(opt).cuda()\n\n # Initialize Optimizer\n parameters = filter(lambda p: p.requires_grad, model.parameters())\n optimizer = optim.Adam(parameters, lr=opt.lr)\n\n # Load a Saved Checkpoint\n model, _, _, _= LoadModels(opt, model, optimizer)\n\n # Evaluate the Network\n EvalNetwork(opt, test_dataloader, model)\n\n\ndef EvalNetwork(opt, test_dataloader, model):\n # Initialize Variables\n iteration = 1\n\n # Initialize Batch Data\n data = iter(test_dataloader)\n\n # Validate Relation Networks\n model.eval()\n\n # Iteration\n for frames_rgb, frames_flow, video_id, _, _, _, _ in data:\n\n # Get Network Outputs\n outputs = model(Variable(frames_flow, volatile=True).cuda())\n\n # Get Maximum Inference Values for Classification\n out, idx = F.softmax(outputs).data.max(0)\n\n # Test - Classification\n log_print = ''\n log_print += '%s ' % video_id\n log_print += ' '.join(str(score) for score in out.cpu())\n log_print += '\\n'\n with open(os.path.join(opt.expr_dir, opt.exp_id, 'pred_classification.txt'), 'a') as f:\n f.write(log_print)\n f.write('\\n')\n\n # Test - Localization (Need to check with sungjoon)\n out = outputs.data\n log_print = ''\n for idx in range(25):\n log_print += '%s %d ' % (video_id, idx+1)\n log_print += ' '.join(str(score) for score in out[idx, :])\n log_print += '\\n\\n'\n with open(os.path.join(opt.expr_dir, opt.exp_id, 'pred_localization.txt'), 'a') as f:\n f.write(log_print)\n\n # Display & Save Results\n if iteration % opt.checkpoint_iter == 0:\n with open(os.path.join(opt.expr_dir, opt.exp_id, 'log_test.txt'), 'a') as f:\n log_print = '[Test] Iteration: %4d/%4d' % \\\n (iteration, len(data))\n print(log_print)\n f.write(log_print)\n f.write('\\n')\n\n # Update Variables\n iteration += 1\n\nif __name__ == \"__main__\":\n opt = parse_opt()\n opt = load_config(opt) # Implemented at Config.py. 'config_rgb.pkl' and 'charades.pth' should be placed into 'start_from' folder.\n Eval(opt)\n print('Done.')","sub_path":"Evaluation.py","file_name":"Evaluation.py","file_ext":"py","file_size_in_byte":5764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"524488600","text":"import collections\nimport heapq\nfrom typing import List\n\n\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n frequency = collections.Counter(nums)\n hq, ans = [], []\n for key in frequency:\n heapq.heappush(hq, (-frequency[key], key)) # 取负,因为默认为小顶堆\n for _ in range(k):\n ans.append(heapq.heappop(hq)[1])\n return ans\n","sub_path":"Week_02/347_top_k_frequent_elements.py","file_name":"347_top_k_frequent_elements.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"358358869","text":"# -*- coding: utf-8 -*-\n\nfrom optparse import OptionParser\n\nVERSION = \"1.0.0\"\n\n\ndef main():\n parser = OptionParser(usage=\"usage: %prog [options] arg\", version=\"%prog \" + VERSION)\n\n parser.set_defaults(verbose=True,\n wave_msg=\"Hello Starter!\")\n\n parser.add_option(\"-q\", \"--quiet\",\n action=\"store_false\", dest=\"verbose\",\n help=\"don't print status messages to stdout\")\n parser.add_option(\"-v\", \"--verbose\",\n action=\"store_true\", dest=\"verbose\",\n help=\"print status messages to stdout\")\n parser.add_option(\"-w\", \"--wave\",\n action=\"store\", dest=\"wave_msg\",\n help=\"sample option\")\n\n (options, args) = parser.parse_args()\n if len(args):\n parser.error(\"argument(s) <{0}> is(are) not valid\".format(' '.join([arg for arg in args])))\n if options.verbose:\n print(options.wave_msg)\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"311745412","text":"\nfrom django.urls import path\nfrom plan import views\n\nurlpatterns = [\n path('', views.plan_list_view, name='listPlan'),\n path('/', views.plan_detail_view, name=\"plan_detail\"),\n\n path('/edit/', views.plan_update_view, name=\"plan_update\"),\n path('/delete/', views.plan_delete_view, name=\"plan_delete\"),\n path('new/', views.plan_create_view, name=\"plan_create\"),\n \n]","sub_path":"travel/plan/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"187767907","text":"def removeEven(arr):\n count = 0\n for i in range(len(arr)):\n if arr[i] % 2 !=0:\n arr[count] = arr[i]\n count+=1\n return arr[:count]\n\ndef mergesortedlist(arr1,arr2):\n arr=[]\n i=j=0\n while i< len(arr1) and j < len(arr2):\n if arr1[i] < arr2[j]:\n arr.append(arr1[i])\n i+=1\n elif arr2[j] < arr1[i]:\n arr.append(arr2[j])\n j += 1\n else:\n arr.append(arr1[i])\n i+=1\n j+=1\n\n while i < len(arr1):\n arr.append(arr1[i])\n i+=1\n\n while j < len(arr2):\n arr.append(arr2[j])\n j+=1\n\n return arr\n\n\ndef findSum(arr,value):\n # Write - Your - Code\n for i in range(len(arr)):\n for j in range(i,len(arr)):\n if arr[j] == value - arr[i]:\n print(arr[i],arr[j],value)\n return\n\n return \"Not found\"\n\ndef findProduct(arr):\n result = []\n result.append(1)\n\n for i in range(1,len(arr)):\n result.append(arr[i-1]*result[i-1])\n print(result)\n product = 1\n for i in range(len(arr)-2,-1,-1):\n product *= arr[i+1]\n result[i] = result[i] * product\n print(result)\n\n\n# def findfirstUnique(arr):\n# for i in range(len(arr)):\n# for j in range(i+1,len(arr)):\n# if arr[i] == arr[j]:\n# break\n# print(arr[i],j)\n# if j == len(arr)-1:\n# print(arr[i])\n# return\n\n\ndef findFirstUnique(arr):\n #Inside Inner Loop Check Each index of outerLoop If it's repeated in list\n #If it's not repeated then return this as first unique Integer\n isRepeated = False\n for i in range(len(arr)):\n for j in range(i+1,len(arr),1):\n if (arr[i] == arr[j]):\n isRepeated = True\n if (isRepeated == False):\n return arr[i]\n isRepeated = False\n return - 1\n\n\ndef findsecondMax(arr):\n\n max1 = arr[0]\n max2 = arr[0]\n if len(arr)<2:\n return \"Second max cannot be found\"\n else:\n max1,max2 = max(arr[0],arr[1]), min(arr[0],arr[1])\n for i in range(2,len(arr)):\n if arr[i] > max1:\n max2 = max1\n max1 = arr[i]\n elif arr[i] > max2:\n max2 = arr[i]\n return max2\n\ndef rotateArray(arr):\n temp = arr[-1]\n for i in range(len(arr)-2,-1,-1):\n arr[i+1] = arr[i]\n arr[0] = temp\n return arr\n\ndef rearrangelist(arr):\n i=0\n j = len(arr)-1\n while i < j:\n while arr[i] < 0:\n i+=1\n while arr[j] > 0:\n j-=1\n if i < j:\n arr[i] ,arr[j] = arr[j],arr[i]\n i+=1\n j-=1\n return arr\n\ndef maxmin(arr):\n revarr = arr[:]\n revarr.reverse()\n print(revarr)\n l = [None] * len(arr)\n i = 0\n j = 0\n while j < len(arr):\n l[j] = revarr[i]\n if j < len(arr)-1:\n l[j+1] = arr[i]\n j+=2\n i+=1\n print(l)\n\n#print(removeEven([1, 3, 5, 7, 9]))\n\n#print(mergesortedlist([1,3,4,5] ,[2,6,7,8]))\n#findSum([1,21,3,14,5,60,7,6],6)\n#findProduct([1,2,3,4])\n#print(findFirstUnique([2,3,2,3,6,6,9]))\n#print(findsecondMax([9,2,3,6]))\n\n#print(rotateArray([1,2,3,4,5]))\n#print(rearrangelist([10,-1,20,4,5,-9,-6]))\nmaxmin([1,2,3,4,5,6,7])","sub_path":"Python/Practice/LinkedList_Stack_Q/Lists.py","file_name":"Lists.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"250654521","text":"from sklearn.svm import SVC\nfrom trainer import *\n\n\ndef idx_to_names(ids):\n n = []\n for i in ids:\n n.append(names[i] + '1')\n n.append(names[i] + '2')\n return n\n\ndef get_data(dataset):\n pass\n\n\nstrings = ['Cheek-raise', 'Brow-raise', 'Brow-lower', 'Wink', 'Blink', 'Neutral']\nnames = ['akc', 'amy', 'gyb', 'hcy', 'hhy', 'hjb', 'hyc', 'kh', 'mon', 'phoebs', 'ross', 'tina', 'tom', 'tony', 'xwt', 'yx', 'xww', 'zyl', 'zys', 'zzz']\ntest_idx = [0, 2, 5, 9, 7]\ntrain_idx = list(set(np.arange(len(names))) - set(test_idx))\nspec = Specification(8, 30, 15) # Change the model spec\n\n\ndir_train = './data/all-data-ofdm/train/' # Change the dir\ndir_test = './data/all-data-ofdm/test/'\ndict_name = './result_model.json'\n\n\nnames_test = idx_to_names(test_idx)\ntrainer = ModelTrainer(None, spec)\ndataset_train = trainer.get_dataset_by_comp_name(dir_train, names_test)\ndataset_test = trainer.get_dataset_by_name(dir_test, names_test)\n\ntrain_data = np.array(dataset_train.data)\ntest_data = np.array(dataset_test.data)\nX_train = train_data[0:, 1:]\ny_train = train_data[0:, 0]\nX_test = test_data[0:, 1:]\ny_test = test_data[0:, 0]\n\nclf_rbf = SVC(kernel='rbf')\nclf_rbf.fit(X_train[0:, 0:3600:1], y_train)\n\ny_predict = clf_rbf.predict(X_test[0:, 0:3600:1])\n","sub_path":"learning/test_SVM.py","file_name":"test_SVM.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"550856144","text":"import pygame\n\n\nclass Bird:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.velocity = 0\n self.fall_time = 0\n self.rotation = 0\n self.animation_time = 5\n self.img_count = 0\n self.imgs = [pygame.transform.scale2x(pygame.image.load(f'flappy_bird/src/img/bird{str(x)}.png')) for x in range(1, 4)]\n self.img = self.imgs[0]\n self.rotation_velocity = 5\n self.max_rotation = 25\n\n def jump(self):\n self.fall_time = 0\n self.velocity = -12\n\n def move(self):\n self.fall_time += 1\n\n up_force = self.velocity * self.fall_time\n down_force = 1.8 * self.fall_time ** 2\n\n fall_down = up_force + down_force\n\n if fall_down >= 18:\n fall_down = (fall_down / abs(fall_down)) * 16\n\n if fall_down < 0:\n fall_down -= 2\n\n self.y = self.y + fall_down\n\n if fall_down < 0:\n if self.rotation < self.max_rotation:\n self.rotation = self.max_rotation\n else:\n if self.rotation > -90:\n self.rotation -= self.rotation_velocity\n\n def draw(self, screen):\n self.img_count += 1\n\n if self.img_count <= self.animation_time:\n self.img = self.imgs[0]\n elif self.img_count <= 2 * self.animation_time:\n self.img = self.imgs[1]\n elif self.img_count <= 3 * self.animation_time:\n self.img = self.imgs[2]\n elif self.img_count <= 4 * self.animation_time + 1:\n self.img = self.imgs[0]\n self.img_count = 0\n\n rotated_bird = pygame.transform.rotate(self.img, self.rotation)\n new_rect = rotated_bird.get_rect(center=self.img.get_rect(topleft=(self.x, self.y)).center)\n\n screen.blit(rotated_bird, new_rect)\n","sub_path":"NEAT/tasks/flappy_bird/bird.py","file_name":"bird.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"64037728","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfig = plt.figure()\n\ndef showHistogram(subplot, title, values ):\n subplot = fig.add_subplot(subplot)\n subplot.hist(values)\n subplot.set_title(title)\n\nshowHistogram(121, \"First series\", np.array([1, 3, 2, 1, 3, 2, 75, 1, 3, 2, 2, 1, 2, 3, 2, 1 ]))\nshowHistogram(122, \"Second series\",np.array([1, 2, 3, 4, 2, 19, 9, 21, 20, 22 ]))\nplt.show()\n\n\n","sub_path":"src/1.2.py","file_name":"1.2.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"326725078","text":"from flask import Flask, render_template, request, jsonify, Response\nimport requests\nfrom app import app\nfrom config import Config\n\n\n@app.route('/weather', methods=['GET'])\ndef weather():\n return render_template(\"homepage.html\")\n\n\n@app.route('/search', methods=['POST'])\ndef search_weather():\n city = request.form.get(\"city\")\n querystring = {\"q\": city, \"cnt\": \"1\", \"mode\": \"null\", \"lon\": \"0\", \"type\": \"link, accurate\", \"lat\": \"0\",\n \"units\": \"metric\"}\n\n headers = {\n 'x-rapidapi-key': Config.WEATHER_API_KEY,\n 'x-rapidapi-host': Config.WEATHER_API_HOST\n }\n\n response = requests.request(\"GET\", Config.WEATHER_API_URL, headers=headers, params=querystring)\n if response.status_code == 200:\n data = response.json()\n weather = data['list'][0]\n return render_template(\"weather.html\", weather=weather)\n\n return Response(status=404)","sub_path":"lectures/flask/routes/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"307256821","text":"n, a, b = map(int, input().split())\n\nif b - a > n + 1:\n ans = 0\nelif a > b:\n ans = 0\nelse:\n diff = b - a\n ans = (b - a) * (n - 2) + 1\nprint(ans)","sub_path":"Python_codes/p03705/s029850357.py","file_name":"s029850357.py","file_ext":"py","file_size_in_byte":156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"626141631","text":"import datetime\nimport logging\n\nlogging.basicConfig(filename=\"messenger.log\", level=logging.INFO)\n\n\ndef sign_in(conn, neo4j_server, username) -> int:\n user_id = conn.hget(\"users:\", username)\n\n if not user_id:\n print(\"No user with such username exists. Please, register first\")\n return -1\n\n conn.sadd(\"online:\", username)\n logging.info(f\"{datetime.datetime.now()} Actor: {username} Action: log in \\n\")\n\n neo4j_server.sign_in(user_id)\n return int(user_id)\n\n\ndef sign_out(conn, neo4j_server, user_id) -> int:\n username = conn.hmget(\"user:%s\" % user_id, [\"login\"])[0];\n logging.info(f\"{datetime.datetime.now()} Actor: {username} Action: sign out \\n\")\n neo4j_server.sign_out(user_id)\n return conn.srem(\"online:\", conn.hmget(\"user:%s\" % user_id, [\"login\"])[0])\n\n\ndef create_message(conn, neo4j_server, message_text, tags: list, sender_id, consumer) -> int:\n try:\n message_id = int(conn.incr('message:id:'))\n consumer_id = int(conn.hget(\"users:\", consumer))\n except TypeError:\n print(\"No user with %s username exists, can't send a message\" % consumer)\n return -1\n\n pipeline = conn.pipeline(True)\n\n pipeline.hmset('message:%s' % message_id, {\n 'text': message_text,\n 'id': message_id,\n 'sender_id': sender_id,\n 'consumer_id': consumer_id,\n 'tags': ','.join(tags),\n 'status': \"created\"\n })\n\n pipeline.lpush(\"queue:\", message_id)\n pipeline.hmset('message:%s' % message_id, {\n 'status': 'queue'\n })\n\n pipeline.zincrby(\"sent:\", 1, \"user:%s\" % conn.hmget(\"user:%s\" % sender_id, [\"login\"])[0])\n pipeline.hincrby(\"user:%s\" % sender_id, \"queue\", 1)\n pipeline.execute()\n\n neo4j_server.create_message(sender_id, consumer_id, {\"id\": message_id, \"tags\": tags})\n return message_id\n\n\ndef register(conn, neo4j_server, username):\n if conn.hget('users:', username):\n print(f\"User {username} exists\");\n return None\n\n user_id = conn.incr('user:id:')\n\n pipeline = conn.pipeline(True)\n\n pipeline.hset('users:', username, user_id)\n\n pipeline.hmset('user:%s' % user_id, {\n 'login': username,\n 'id': user_id,\n 'queue': 0,\n 'checking': 0,\n 'blocked': 0,\n 'sent': 0,\n 'delivered': 0\n })\n pipeline.execute()\n logging.info(f\"{datetime.datetime.now()} Actor: {username} Action: register \\n\")\n neo4j_server.registration(username, user_id)\n\n return user_id\n","sub_path":"Lab3/src/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"77367414","text":"import pyvista\nfrom pyvista import examples\nfilename = examples.download_cylinder_crossflow(load=False)\nfilename.split(\"/\")[-1] # omit the path\n# Expected:\n## 'cylinder_Re35.case'\nreader = pyvista.get_reader(filename)\nmesh = reader.read()\nmesh.plot(scalars=\"velocity\", component=1, clim=[-20, 20],\n cpos='xy', cmap='RdBu', show_scalar_bar=False)\n","sub_path":"version/0.35/api/readers/_autosummary/pyvista-EnSightReader-1.py","file_name":"pyvista-EnSightReader-1.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"343195859","text":"import glob\nimport sys\nimport numpy as np\nfrom openeye import oedocking, oechem\nfrom pymol import cmd\nimport shutil\n\ndef create_receptor(output_name, pdb_file, bp_min, bp_max):\n check_oeb = output_name\n proteinStructure = oechem.OEGraphMol()\n ifs = oechem.oemolistream(pdb_file)\n ifs.SetFormat(oechem.OEFormat_PDB)\n oechem.OEReadMolecule(ifs, proteinStructure)\n\n box = oedocking.OEBox(*bp_max, *bp_min)\n\n receptor = oechem.OEGraphMol()\n s = oedocking.OEMakeReceptor(receptor, proteinStructure, box)\n oedocking.OEWriteReceptorFile(receptor, check_oeb)\n\n\ndef minN(x, y):\n if x is None and y is None:\n return None\n if x is None:\n return y\n if y is None:\n return x\n if x <= y:\n return x\n return y\n\n\ndef maxN(x, y):\n if x is None and y is None:\n return None\n if x is None:\n return y\n if y is None:\n return x\n if y >= x:\n return y\n return x\n\n\ndef get_min_max(fname, inc=10):\n data = {}\n with open(fname, 'r') as f:\n next(f)\n next(f)\n next(f)\n for line in f:\n line = line.split()\n if line[0] == 'TER':\n break\n\n pocket_id = int(line[4])\n if pocket_id in data:\n data[pocket_id].append((float(line[5]), float(line[6]), float(line[7])))\n else:\n data[pocket_id] = [(float(line[5]), float(line[6]), float(line[7]))]\n\n res = {}\n for pocket, data in data.items():\n x_min, x_max = None, None\n y_min, y_max = None, None\n z_min, z_max = None, None\n\n for coord in data:\n x_min = minN(x_min, coord[0])\n x_max = maxN(x_max, coord[0])\n y_min = minN(y_min, coord[1])\n y_max = maxN(y_max, coord[1])\n z_min = minN(z_min, coord[2])\n z_max = maxN(z_max, coord[2])\n\n x_min -= inc\n x_max += inc\n y_min -= inc\n y_max += inc\n z_min += inc\n z_max += inc\n\n res[pocket] = (x_min, x_max, y_min, y_max, z_min, z_max)\n\n return res\n\n\ndef read_fppocket_file(fname):\n pockets = []\n pocket_count = 1\n with open(fname, 'r') as f:\n for line in f:\n if \"Pocket\" in line:\n for line in f:\n if \"Volume\" in line:\n line = float(line.strip().split('\\t')[-1])\n pockets.append((pocket_count, line))\n pocket_count += 1\n break\n\n return pockets\n\ndef rename(dir):\n name = dir.split(\"/\")[-2]\n name = \"ADRP_pocket1_\" + name\n # print(name)\n return \"/\".join(dir.split(\"/\")[:-2]) + \"/\" + name + \"/\"\n# directories = glob.glob('/Users/austin/Downloads/pockets-outliers'+ \"/*/\")\n# for dir in directories:\n# shutil.move(dir, rename(dir))\ndirectories = glob.glob('/Users/austin/Downloads/pockets-outliers'+ \"/*/\")\n\nprint(directories)\n\nwith open('out.csv', 'w') as fout:\n for struct in directories:\n pockets = read_fppocket_file(glob.glob(struct + \"*.txt\")[0])\n protein_name = \"_\".join(struct.split(\"/\")[-2].split(\"_\")[22:26])\n print(protein_name)\n # exit()\n pocket_data = get_min_max(glob.glob(struct + \"*.pqr\")[0])\n pdb_file = glob.glob(struct + \"*.pdb\")[0]\n\n cmd.reinitialize()\n cmd.load(pdb_file)\n cmd.do(\"remove not polymer\")\n cmd.do(\"save {}\".format(pdb_file))\n\n mean = np.mean(list(zip(*pockets))[1])\n std = np.std(list(zip(*pockets))[1])\n print(mean, std)\n for pocket_id, volume in pockets:\n print(pocket_id, protein_name)\n if volume > (mean + std):\n # min_coords, max_coords =\n print(pocket_id)\n print(pocket_data[pocket_id])\n create_receptor(\"out/\" + protein_name + \"_pocket\" + str(pocket_id) + \"_receptor.oeb\", pdb_file,\n [pocket_data[pocket_id][0], pocket_data[pocket_id][2], pocket_data[pocket_id][4]],\n [pocket_data[pocket_id][1], pocket_data[pocket_id][3], pocket_data[pocket_id][5]])\n\n fout.write(\n \"{},{},{},{},{},{},{},{},{},{}\\n\".format(protein_name + \"_pocket\" + str(pocket_id), protein_name,\n pocket_id, glob.glob(struct + \"*.pdb\")[0],\n pocket_data[pocket_id][0], pocket_data[pocket_id][1],\n pocket_data[pocket_id][2], pocket_data[pocket_id][3],\n pocket_data[pocket_id][4], pocket_data[pocket_id][5]))\n","sub_path":"scripts/prepare_pockets.py","file_name":"prepare_pockets.py","file_ext":"py","file_size_in_byte":4745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"478643324","text":"# coding: utf-8\n\n\"\"\"\nCreated on TUE Aug 08 08:39:56 2019\n\n@author: 00049000\n\"\"\"\nimport cv2\n\ndef transform_video(viedo, fourcc, output_file, fps, size, setting):\n if setting==False:\n \"\"\"\n 讀取原檔案fps及size\n \"\"\"\n fps = viedo.get(cv2.CAP_PROP_FPS)\n size = (int(viedo.get(cv2.CAP_PROP_FRAME_WIDTH)), \n int(viedo.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n print(fps)\n print(size)\n out_put = cv2.VideoWriter(output_file, fourcc, fps, size) \n while(viedo.isOpened()):\n ret, frame = viedo.read()\n if ret==True:\n # frame = cv2.flip(frame,0) #翻轉影片畫面,參數設定: 1:水平翻轉,0:垂直翻轉,-1:水平垂直翻轉\n out_put.write(frame) #write the flipped frame\n # cv2.imshow('frame',frame) \n if cv2.waitKey(1) & 0xFF == ord('q'): #按q键退出\n break\n else:\n break\n \"\"\"\n Release everything if job is finished\n \"\"\"\n viedo.release()\n out_put.release()\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n \"\"\"\n 讀入所要轉檔的影片路徑\n \"\"\"\n viedo = cv2.VideoCapture(\"C:\\\\Users\\\\User\\\\Desktop\\\\test.wmv\")\n\n \"\"\"\n Define the codec and create VideoWriter object\n 定義文件名及格式\n \"\"\"\n fourcc = cv2.VideoWriter_fourcc(*'DIVX') #FourCC是一個4字節碼,用來確定視頻的編碼格式 e.g. DIVX , XVID , MJPG , X264 , WMV1 , WMV2\n output_file = 'C:\\\\Users\\\\User\\\\Desktop\\\\final.avi'\n\n \"\"\"\n fourcc對應副檔名:\n 有括號()表示會跳出error訊息,但還是能生成檔案\n\n DIVX, XVID, MJPG, WMV1, WMV2: avi\n MJPG, WMV1 , WMV2, (X264): wmv\n (DIVX), (XVID), (X264) :mp4\n \"\"\"\n fps = 10\n size = (1716, 996)\n \"\"\"\n fps跟size也可自己設定 e.g. 10, (640, 360)..., 但很有可能轉出影片失敗,故建議使用原影片尺寸轉換\n \"\"\"\n transform_video(viedo, fourcc, output_file, fps, size, setting=False)","sub_path":"transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"314201376","text":"import cv2\nimport numpy as np\nimport os\n\n\ndef calIOU(point1, point2):\n point1 = point1.reshape(4, 2).astype(int)\n point2 = point2.reshape(4, 2).astype(int)\n rec1 = cv2.minAreaRect(point1)\n rec2 = cv2.minAreaRect(point2)\n jiao = cv2.rotatedRectangleIntersection(rec1, rec2)\n w1, h1 = rec1[1]\n w2, h2 = rec2[1]\n mode = jiao[0]\n if mode == 0:\n return 0.0\n points = jiao[1]\n inter = cv2.contourArea(points)\n over = (w1 * h1) + (w2 * h2) - inter\n iou = inter / over\n return iou\n\n\ndef eval(gtfolder='/home/yc/Videos/aaa', prefolder='/home/yc/Videos/bbb', cats=['car', 'bigcar'], iouScore=0.5,\n Score=0.7):\n tongji = np.zeros((len(cats), 3))\n for i in os.listdir(gtfolder):\n gt_dict = {}\n for cat in cats:\n gt_dict[cat] = []\n f = open(os.path.join(gtfolder, i), 'r')\n while True:\n line = f.readline()\n if line:\n splitlines = line.strip().split(' ')\n if len(splitlines) < 9:\n continue\n gt_dict[splitlines[8]].append(np.array(splitlines[:8]).astype(float))\n tongji[cats.index(splitlines[8])][0] += 1\n else:\n break\n f.close()\n if not os.path.exists(os.path.join(prefolder, i)):\n print(i, ' no predict')\n\n pre_dict = {}\n for cat in cats:\n pre_dict[cat] = []\n f = open(os.path.join(prefolder, i), 'r')\n while True:\n line = f.readline()\n if line:\n splitlines = line.strip().split(' ')\n if len(splitlines) < 10 or float(splitlines[8]) < Score:\n continue\n pre_dict[splitlines[9]].append(np.array(splitlines[:9]).astype(float))\n tongji[cats.index(splitlines[9])][1] += 1\n else:\n break\n f.close()\n for cat in cats:\n pre_dict[cat].sort(key=lambda t: -t[8])\n for j in pre_dict[cat]:\n if len(gt_dict[cat]) > 0:\n overlaps = [calIOU(j[:8], points) for points in gt_dict[cat]]\n ovmax = np.max(overlaps)\n jmax = np.argmax(overlaps)\n if ovmax > iouScore:\n gt_dict[cat].pop(jmax)\n tongji[cats.index(cat)][2] += 1\n for cat in cats:\n print('---', cat, '---')\n print('gt_num: ', tongji[cats.index(cat)][0])\n print('pre_num: ', tongji[cats.index(cat)][1])\n print('true_num: ', tongji[cats.index(cat)][2])\n res = np.sum(tongji, axis=0)\n print('---total---')\n print('gt_num: ', res[0])\n print('pre_num: ', res[1])\n print('true_num: ', res[2])\n print('p: ', res[2] / res[1])\n print('r: ', res[2] / res[0])\n\n\neval()\n\n# python eval_hbb.py --gt_root ./gt_root --pre_root ./pre_root --label_name 1,2\n","sub_path":"TargetDetection/jb/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":2909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"59727569","text":"from Jawa import EfficiencyClass\nfrom ROOT import TFile, TCut, TTree, TMath\n\nzmumurecf = TFile(\"../tuples/MuonTracking.2015.root\");\nzmumurect = zmumurecf.Get(\"Z2MuMu/DecayTree\");\n\ntriggercut_plus = TCut(\"muplus_Hlt2SingleMuonHighPTDecision_TOS==1 && muplus_Hlt1SingleMuonHighPTDecision_TOS == 1 && muplus_L0MuonDecision_TOS ==1\")\ntriggercut_minus = TCut(\"muminus_Hlt2SingleMuonHighPTDecision_TOS==1 && muminus_Hlt1SingleMuonHighPTDecision_TOS == 1 && muminus_L0MuonDecision_TOS ==1\")\n \nhasMuTT_plus = TCut(\"muplus_MuonTT_PT > 20000 && muplus_MuonTT_DeltaR < 0.1\")\nhasMuTT_minus = TCut(\"muminus_MuonTT_PT > 20000 && muminus_MuonTT_DeltaR < 0.1\")\n\nmatched_plus = TCut(\"muplus_MuonTT_nCommonMuonIDs/muplus_MuonTT_nMuonIDs > 0.4 && (muplus_nTTIDs > 0 ? muplus_MuonTT_nCommonTTIDs/muplus_MuonTT_nTTIDs > 0.6 : muplus_MuonTT_nTTIDs > 0)\")\nmatched_minus = TCut(\"muminus_MuonTT_nCommonMuonIDs/muminus_MuonTT_nMuonIDs > 0.4 && (muminus_nTTIDs > 0 ? muminus_MuonTT_nCommonTTIDs/muminus_MuonTT_nTTIDs > 0.6 : muminus_MuonTT_nTTIDs > 0)\")\n\nloosematched_plus = TCut(\"muplus_MuonTT_nCommonMuonIDs/muplus_MuonTT_nMuonIDs > 0.4\")\nloosematched_minus = TCut(\"muminus_MuonTT_nCommonMuonIDs/muminus_MuonTT_nMuonIDs > 0.4\")\n\nmagup = TCut(\"Polarity == 1\")\nmagdown = TCut(\"Polarity == -1\")\n\nvtx_minus = TCut(\"muminus_MuonTT_VtxChi2/muminus_MuonTT_VtxNDoF < 5\")\nvtx_plus = TCut(\"muplus_MuonTT_VtxChi2/muplus_MuonTT_VtxNDoF < 5\")\n\nphicut_plus = TCut(\"muplus_MuonTT_DPhi > 0.1\")\nphicut_minus = TCut(\"muminus_MuonTT_DPhi > 0.1\")\n\nwplustrkqual = TCut(\"muplus_TRACK_PCHI2 > 0.01\")\nwminustrkqual = TCut(\"muminus_TRACK_PCHI2 > 0.01\")\n\nfiducial_rec = TCut(\"muplus_PT > 20000 && muminus_PT > 20000 && boson_M > 60000 && boson_M < 120000 && muplus_ETA > 2.0 && muplus_ETA < 4.5 && muminus_ETA > 2 && muminus_ETA < 4.5 && muplus_TRACK_PCHI2 > 0.001 && muminus_TRACK_PCHI2 > 0.001 && sqrt(muplus_PERR2)/muplus_P < 0.1 && sqrt(muminus_PERR2)/muminus_P < 0.1 && muplus_cpt_0.50 < 2000 && muminus_cpt_0.50 < 2000 && boson_ENDVERTEX_CHI2/boson_ENDVERTEX_NDOF < 5\")\nfiducial_LpMm = TCut(\"muplus_PT > 20000 && muminus_MuonTT_PT > 20000 && muminus_MuonTT_M > 70000 && muminus_MuonTT_M < 110000 && muplus_ETA > 2 && muplus_ETA < 4.5 && muplus_TRACK_PCHI2 > 0.001 && muminus_MuonTT_ETA > 2 && muminus_MuonTT_ETA < 4.5\")\nfiducial_MpLm = TCut(\"muplus_MuonTT_PT > 20000 && muminus_PT > 20000 && muplus_MuonTT_M > 70000 && muplus_MuonTT_M < 110000 && muminus_ETA > 2 && muminus_ETA < 4.5 && muminus_TRACK_PCHI2 > 0.001 && muplus_MuonTT_ETA > 2 && muplus_MuonTT_ETA < 4.5\")\n\nselcutptag = triggercut_plus + hasMuTT_minus + vtx_minus + phicut_minus\nselcutmtag = triggercut_minus + hasMuTT_plus + vtx_plus + phicut_plus\n\nselcut_PTag = fiducial_rec + selcutptag\nselcut_MTag = fiducial_rec + selcutmtag\n\nselcut_PTagLL = fiducial_LpMm + selcutptag\nselcut_MTagLL = fiducial_MpLm + selcutmtag\n\npt25plus = TCut(\"muplus_PT > 25000\")\npt30plus = TCut(\"muplus_PT > 30000\")\npt25minus = TCut(\"muminus_PT > 25000\")\npt30minus = TCut(\"muminus_PT > 30000\")\n\n'''\netabins = [2.0 , 2.25 , 2.5 , 2.75 , 3.00 , 3.25 , 3.5 , 4.0 , 4.5]\netabins2 = [2.0 , 2.25 , 2.5 , 2.75 , 2.875, 3.00 , 3.1225, 3.25 , 3.375, 3.5 , 4.0 , 4.5]\ntckbins = [3500000.0, 4600000.0, 4800000.0, 5700000.0, 5900000.0, 6000000.0, 7100000.0, 7300000.0, 7400000.0,\n 7500000.0, 7600000.0, 7700000.0, 7900000.0, 7929912.0, 8000000.0]\n\npluseffvars = [\n [\"ETA\", \"muplus_MuonTT_ETA\", 10 , 2 , 4.5 ],\n [\"ETA8\", \"muplus_MuonTT_ETA\", etabins ],\n [\"PT\", \"muplus_MuonTT_PT\", 10 , 20000 , 70000],\n [\"P\", \"muplus_MuonTT_P\", 8 , 100000 , 500000],\n [\"PHI\", \"muplus_MuonTT_PHI\", 10 , -TMath.Pi() , TMath.Pi()],\n [\"VeloClusters\", \"nVeloClusters\", 8 , 0 , 4000 , \"I\"],\n [\"ITClusters\", \"nITClusters\", 8 , 0 , 2000 , \"I\"],\n [\"PVs\", \"nPVs\", 6 , -0.5 , 5.5 , \"I\"],\n [\"TCK\", \"OdinTCK\", tckbins, \"I\"]\n ]\nminuseffvars = [\n [\"ETA\", \"muminus_MuonTT_ETA\", 10 , 2 , 4.5 ],\n [\"ETA8\", \"muminus_MuonTT_ETA\", etabins ],\n [\"PT\", \"muminus_MuonTT_PT\", 10 , 20000 , 70000],\n [\"P\", \"muminus_MuonTT_P\", 8 , 100000 , 500000],\n [\"PHI\", \"muminus_MuonTT_PHI\", 10 , -TMath.Pi() , TMath.Pi()],\n [\"VeloClusters\", \"nVeloClusters\", 8 , 0 , 4000 , \"I\"],\n [\"ITClusters\", \"nITClusters\", 8 , 0 , 2000 , \"I\"],\n [\"PVs\", \"nPVs\", 6 , -0.5 , 5.5 , \"I\"],\n [\"TCK\", \"OdinTCK\", tckbins, \"I\"]\n ]\n\neff2dvars = [\n [\"ETA\",\"PHI\"],\n [\"ETA\",\"PT\"]\n ]\n'''\nfrom effbins_config import *\n\ndef makeMuonTrackMatch2015(name, selcut, passcut):\n #selcut and pass cut plus is first is array\n MuonTrackMatch2015MagUpMuPlus = EfficiencyClass(\"Muon\"+name+\"TrackMatch2015MagUpMuPlus\")\n MuonTrackMatch2015MagDownMuPlus = EfficiencyClass(\"Muon\"+name+\"TrackMatch2015MagDownMuPlus\")\n MuonTrackMatch2015MagUpMuMinus = EfficiencyClass(\"Muon\"+name+\"TrackMatch2015MagUpMuMinus\")\n MuonTrackMatch2015MagDownMuMinus = EfficiencyClass(\"Muon\"+name+\"TrackMatch2015MagDownMuMinus\")\n \n MuonTrackMatch2015MagUpMuMinus.AddTree(zmumurect)\n MuonTrackMatch2015MagUpMuMinus.SetSelectionCut(selcut[1] + magup )\n MuonTrackMatch2015MagUpMuMinus.SetPassCut(passcut[1])\n MuonTrackMatch2015MagUpMuMinus.AddVars(minuseffvars + trkminuseffvars)\n MuonTrackMatch2015MagUpMuMinus.Add2DVars(trk2dvars)\n MuonTrackMatch2015MagUpMuMinus.SetPltRange(\"muminus_MuonTT_M\" , 60 , 60000 , 120000)\n MuonTrackMatch2015MagUpMuMinus.SetEffRange(70000 , 110000)\n MuonTrackMatch2015MagUpMuMinus.MakeEntryLists()\n MuonTrackMatch2015MagUpMuMinus.MakeHists();\n MuonTrackMatch2015MagUpMuMinus.MakeEfficiencyGraph();\n MuonTrackMatch2015MagUpMuMinus.SaveToFile();\n \n MuonTrackMatch2015MagUpMuPlus.AddTree(zmumurect)\n MuonTrackMatch2015MagUpMuPlus.SetSelectionCut(selcut[0] + magup )\n MuonTrackMatch2015MagUpMuPlus.SetPassCut(passcut[0])\n MuonTrackMatch2015MagUpMuPlus.AddVars(pluseffvars + trkpluseffvars)\n MuonTrackMatch2015MagUpMuPlus.Add2DVars(trk2dvars)\n MuonTrackMatch2015MagUpMuPlus.SetPltRange(\"muplus_MuonTT_M\" , 60 , 60000 , 120000)\n MuonTrackMatch2015MagUpMuPlus.SetEffRange(70000 , 110000)\n MuonTrackMatch2015MagUpMuPlus.MakeEntryLists()\n MuonTrackMatch2015MagUpMuPlus.MakeHists();\n MuonTrackMatch2015MagUpMuPlus.MakeEfficiencyGraph();\n MuonTrackMatch2015MagUpMuPlus.SaveToFile();\n \n MuonTrackMatch2015MagDownMuMinus.AddTree(zmumurect)\n MuonTrackMatch2015MagDownMuMinus.SetSelectionCut(selcut[1] + magdown )\n MuonTrackMatch2015MagDownMuMinus.SetPassCut(passcut[1])\n MuonTrackMatch2015MagDownMuMinus.AddVars(minuseffvars + trkminuseffvars)\n MuonTrackMatch2015MagDownMuMinus.Add2DVars(trk2dvars)\n MuonTrackMatch2015MagDownMuMinus.SetPltRange(\"muminus_MuonTT_M\" , 60 , 60000 , 120000)\n MuonTrackMatch2015MagDownMuMinus.SetEffRange(70000 , 110000)\n MuonTrackMatch2015MagDownMuMinus.MakeEntryLists()\n MuonTrackMatch2015MagDownMuMinus.MakeHists()\n MuonTrackMatch2015MagDownMuMinus.MakeEfficiencyGraph()\n MuonTrackMatch2015MagDownMuMinus.SaveToFile()\n \n MuonTrackMatch2015MagDownMuPlus.AddTree(zmumurect)\n MuonTrackMatch2015MagDownMuPlus.SetSelectionCut(selcut[0] + magdown )\n MuonTrackMatch2015MagDownMuPlus.SetPassCut(passcut[0])\n MuonTrackMatch2015MagDownMuPlus.AddVars(pluseffvars + trkpluseffvars)\n MuonTrackMatch2015MagDownMuPlus.Add2DVars(trk2dvars)\n MuonTrackMatch2015MagDownMuPlus.SetPltRange(\"muplus_MuonTT_M\" , 60 , 60000 , 120000)\n MuonTrackMatch2015MagDownMuPlus.SetEffRange(70000 , 110000)\n MuonTrackMatch2015MagDownMuPlus.MakeEntryLists()\n MuonTrackMatch2015MagDownMuPlus.MakeHists();\n MuonTrackMatch2015MagDownMuPlus.MakeEfficiencyGraph();\n MuonTrackMatch2015MagDownMuPlus.SaveToFile();\n \n MuonTrackMatch2015MagUp = EfficiencyClass(\"Muon\"+name+\"TrackMatch2015MagUp\", MuonTrackMatch2015MagUpMuPlus, MuonTrackMatch2015MagUpMuMinus )\n MuonTrackMatch2015MagUp.MakeEfficiencyGraph()\n MuonTrackMatch2015MagUp.SaveToFile()\n \n MuonTrackMatch2015MagDown = EfficiencyClass( \"Muon\"+name+\"TrackMatch2015MagDown\", MuonTrackMatch2015MagDownMuPlus, MuonTrackMatch2015MagDownMuMinus )\n MuonTrackMatch2015MagDown.MakeEfficiencyGraph()\n MuonTrackMatch2015MagDown.SaveToFile()\n \n MuonTrackMatch2015MuPlus = EfficiencyClass(\"Muon\"+name+\"TrackMatch2015MuPlus\", MuonTrackMatch2015MagUpMuPlus, MuonTrackMatch2015MagDownMuPlus )\n MuonTrackMatch2015MuPlus.MakeEfficiencyGraph()\n MuonTrackMatch2015MuPlus.SaveToFile()\n \n MuonTrackMatch2015MuMinus = EfficiencyClass( \"Muon\"+name+\"TrackMatch2015MuMinus\", MuonTrackMatch2015MagUpMuMinus, MuonTrackMatch2015MagDownMuMinus )\n MuonTrackMatch2015MuMinus.MakeEfficiencyGraph()\n MuonTrackMatch2015MuMinus.SaveToFile()\n\n MuonTrackMatch2015 = EfficiencyClass(\"Muon\"+name+\"TrackMatch2015\", MuonTrackMatch2015MagDown, MuonTrackMatch2015MagUp )\n MuonTrackMatch2015.MakeEfficiencyGraph()\n MuonTrackMatch2015.SaveToFile()\n\nmakeMuonTrackMatch2015(\"\",[selcut_MTag, selcut_PTag], [matched_plus, matched_minus])\nmakeMuonTrackMatch2015(\"W\",[selcut_MTag + wplustrkqual, selcut_PTag + wminustrkqual], [matched_plus, matched_minus])\n#makeMuonTrackMatch2015(\"WPT25\",[selcut_MTag + wplustrkqual + pt25plus, selcut_PTag + wminustrkqual + pt25minus], [matched_plus, matched_minus])\n#makeMuonTrackMatch2015(\"WPT30\",[selcut_MTag + wplustrkqual + pt30plus, selcut_PTag + wminustrkqual + pt30minus], [matched_plus, matched_minus])\n#makeMuonTracking2015(\"PT25\",selcut + pt25, passcut)\n#makeMuonTracking2015(\"PT30\",selcut + pt30, passcut)\n\n","sub_path":"validation/python/MuonTrackMatch.2015.py","file_name":"MuonTrackMatch.2015.py","file_ext":"py","file_size_in_byte":9403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"470554705","text":"\"\"\"\nYou are given 2 arrays representing integer locations of stores and houses (each location in this problem is one-dementional).\nFor each house, find the store closest to it.\nReturn an integer array result where result[i] should denote the location of the store closest to the i-th house.\nIf many stores are equidistant from a particular house, choose the store with the smallest numerical location.\nNote that there may be multiple stores and houses at the same location.\n\nExample 1:\n\nExplanation:\nThe closest store to the house at location 5 is the store at the same location.\nThe closest store to the house at location 10 is the store at the location 11.\nThe closest store to the house at location 17 is the store at the location 16.\n\nExample 2:\n\n\nExample 3:\n\n\n---\nhouses and stores may not be sorted\nsort stores O(slogs)\nthen, match each house to the stores,\nbut save to best when we find a best match during the bsearch O(nlogs)\n\"\"\"\n\n\ndef smallest_diff_bsearch(arr, target):\n start = 0\n end = len(arr) - 1\n best_diff = float(\"inf\")\n res = None\n while start <= end:\n mid = start + (end - start) // 2\n if arr[mid] < target:\n if abs(arr[mid] - target) < best_diff:\n best_diff = abs(arr[mid] - target)\n res = arr[mid]\n start = mid + 1\n elif arr[mid] == target:\n return arr[mid]\n else:\n if abs(arr[mid] - target) < best_diff:\n best_diff = abs(arr[mid] - target)\n res = arr[mid]\n end = mid - 1\n return res\n\n\ndef stores_and_houses(stores, houses):\n if not stores:\n return [None] * len(houses)\n stores.sort()\n result = []\n for h in houses:\n res = smallest_diff_bsearch(stores, h)\n result.append(res)\n return result\n\n\nimport unittest\n\n\nclass StoresAndHouses(unittest.TestCase):\n def testBasicStores(self):\n houses = [1, 2, 8, 10, 11]\n stores = [-995, 1000]\n self.assertEqual(\n stores_and_houses(stores, houses), [-995, -995, 1000, 1000, 1000]\n )\n","sub_path":"lc_discuss/old/batch_2/stores_and_houses.py","file_name":"stores_and_houses.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"84872391","text":"from src.NNClassifier import NNClassifier\nfrom matplotlib import pyplot as plt\n\nclass NNClassifiersMatrix:\n def __init__(self, hidden_neurons, learning_rates, train_vector, test_vector):\n self.NNClassifierTable = []\n for i in hidden_neurons:\n for j in learning_rates:\n self.NNClassifierTable.append(NNClassifier(train_vector, test_vector, hidden_neurons=i, learning_rates=j))\n\n def train_all_classifiers(self):\n self.error_table = []\n for nn_classifier in self.NNClassifierTable:\n temp_train_error, temp_test_error = nn_classifier.train_network_get_error()\n self.error_table.append((temp_train_error, temp_test_error))\n\n def paintAverageAccuracyGraph(self):\n for idx, error_couple in enumerate(self.error_table):\n\n plt.figure()\n x_axis_values = range(0, len(error_couple[0]))\n train_line, = plt.plot(x_axis_values, error_couple[0], 'r', label='train')\n test_line, = plt.plot(x_axis_values, error_couple[1], 'b', label='test')\n plt.legend(handles=[train_line, test_line])\n ll = self.NNClassifierTable[idx].neural_network.learning_rate\n hid_neu = self.NNClassifierTable[idx].neural_network.hidden_neurons\n plt.title('average accuracy ll: ' + str(ll) + ' hid_neu: ' + str(hid_neu))\n plt.ylabel('train error')\n plt.xlabel('epoch')\n plt.show()\n\n def paintPercentageError(self):\n for idx, classifier in enumerate(self.NNClassifierTable):\n final_percentage_train_error_matrix = classifier.get_final_train_percentage_error_matrix()\n final_percentage_test_error_matrix = classifier.get_final_test_percentage_error_matrix()\n\n final_percentage_train_error_matrix.sort()\n final_percentage_test_error_matrix.sort()\n\n plt.figure()\n x_axis_values = range(0, len(final_percentage_train_error_matrix))\n train_final_line, = plt.plot(x_axis_values, final_percentage_train_error_matrix, 'r',\n label='train_final')\n plt.legend(handles=[train_final_line])\n ll = classifier.neural_network.learning_rate\n hid_neu = classifier.neural_network.hidden_neurons\n plt.title('blad treningowy dla kazdego przykladu ll: ' + str(ll) + ' hid_neu: ' + str(hid_neu))\n plt.ylabel('procent')\n plt.xlabel('przyklad')\n plt.show()\n\n plt.figure()\n x_axis_values = range(0, len(final_percentage_test_error_matrix))\n train_final_line, = plt.plot(x_axis_values, final_percentage_test_error_matrix, 'r',\n label='train_final')\n plt.legend(handles=[train_final_line])\n ll = classifier.neural_network.learning_rate\n hid_neu = classifier.neural_network.hidden_neurons\n plt.title('blad testowy dla kazdego przykladu ll: ' + str(ll) + ' hid_neu: ' + str(hid_neu))\n plt.ylabel('procent')\n plt.xlabel('przyklad')\n plt.show()","sub_path":"src/NNClassifiersMatrix.py","file_name":"NNClassifiersMatrix.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"147966253","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.11-x86_64/egg/dockerfabric/utils/net.py\n# Compiled at: 2017-08-23 16:57:48\nfrom __future__ import unicode_literals\nfrom itertools import repeat\nimport re\nfrom fabric.utils import error\nfrom .output import stdout_result\nIP4_PATTERN = re.compile(b'\\\\s+inet addr:\\\\s*((?:\\\\d{1,3}\\\\.){3}\\\\d{1,3})')\nIP6_PATTERN = re.compile(b'\\\\s+inet6 addr:\\\\s*((?:[a-f0-9]{1,4}::?){1,7}[a-f0-9]{1,4})')\n\ndef _get_address(interface_name, pattern):\n out = stdout_result((b'ifconfig {0}').format(interface_name), (1, ), shell=False, quiet=True)\n if not out:\n error((b'Network interface {0} not found.').format(interface_name))\n match = pattern.search(out)\n if match:\n return match.group(1)\n else:\n return\n\n\ndef _expand_groups(address):\n for group in address.split(b':'):\n if group:\n yield group.zfill(4)\n else:\n zero_groups = 8 - address.count(b':') if b'::' in address else 0\n for z in repeat(b'0000', zero_groups):\n yield z\n\n\ndef get_ip4_address(interface_name):\n \"\"\"\n Extracts the IPv4 address for a particular interface from `ifconfig`.\n\n :param interface_name: Name of the network interface (e.g. ``eth0``).\n :type interface_name: unicode\n :return: IPv4 address; ``None`` if the interface is present but no address could be extracted.\n :rtype: unicode\n \"\"\"\n return _get_address(interface_name, IP4_PATTERN)\n\n\ndef get_ip6_address(interface_name, expand=False):\n \"\"\"\n Extracts the IPv6 address for a particular interface from `ifconfig`.\n\n :param interface_name: Name of the network interface (e.g. ``eth0``).\n :type interface_name: unicode\n :param expand: If set to ``True``, an abbreviated address is expanded to the full address.\n :type expand: bool\n :return: IPv6 address; ``None`` if the interface is present but no address could be extracted.\n :rtype: unicode\n \"\"\"\n address = _get_address(interface_name, IP6_PATTERN)\n if address and expand:\n return (b':').join(_expand_groups(address))\n return address","sub_path":"pycfiles/docker_fabric-0.5.0-py2.7/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"502737889","text":"from django import template\nimport re\n\nblacklist = ['bitch', 'whore']\n \nregister = template.Library()\n\n@register.filter(name='multiply')\n\ndef multiply(value, arg):\n return str(value) * arg \n\n@register.filter(name='Censor')\n\ndef Censor(value):\n w=value.split()\n for i in range(len(w)):\n if w[i] in blacklist:\n w[i] ='!!цензура!!'\n string = ' '.join([str(item) for item in w])\n return string\n","sub_path":"NewsPaper/news/templatetags/custom_filters.py","file_name":"custom_filters.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"551205568","text":"# -*- coding: utf-8 -*-\nimport cv2\nimport numpy as np\nimport pandas as pd\nfrom mahotas.features import zernike_moments\nfrom sklearn.decomposition import PCA\nfrom string import ascii_lowercase\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom classifier import LetterClassifier\n\n# Iniciando Classificador\nLC = LetterClassifier(type='svm')\n\npca = PCA(n_components=0.9)\n\ndef writeLetter(letter, frame):\n font = cv2.FONT_HERSHEY_SIMPLEX\n (text_width, text_height) = cv2.getTextSize(letter, font, 6, thickness=1)[0]\n text_offset_x = 10\n text_offset_y = frame.shape[0] - 25\n box_coords = ((text_offset_x, text_offset_y), (text_offset_x + text_width - 2, text_offset_y - text_height - 2))\n\n cv2.rectangle(frame, box_coords[0], box_coords[1], (0,0,0), cv2.FILLED)\n cv2.putText(frame, letter, (text_offset_x, text_offset_y), font, 6, (255,255,255), 3)\n return\n\ndef treatImage(frame):\n frame = cv2.resize(frame, (240, 240))\n\n # aplica filtro gaussiano e coloca imagem preto e branco\n img_grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n img_grey = cv2.GaussianBlur(img_grey, (5,5), 0)\n\n # aplica otsu para binarizar\n ret, img_grey = cv2.threshold(img_grey, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n\n #tira o contorno da imagem\n contours, heirarchy = cv2.findContours(img_grey, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n borderImg = np.zeros((240, 240, 3), np.uint8)\n cv2.drawContours(borderImg, contours, -1, (125, 125, 0), 1)\n borderGrey = cv2.cvtColor(borderImg, cv2.COLOR_BGR2GRAY)\n\n # Calculate Moments\n moment = cv2.moments(borderGrey)\n\n # Calculate Hu Moments\n huMoments = cv2.HuMoments(moment)\n\n # Calcula momento de Zernike\n zeMoments = zernike_moments(borderGrey, radius=20)\n\n # cv2.imshow(\"Imagem capturada\", img_grey)\n # cv2.waitKey(0)\n\n return huMoments + zeMoments\n\ndef videoLive():\n cap = cv2.VideoCapture(0)\n framerate = cap.get(cv2.CAP_PROP_FPS)\n framecount = 0\n\n frameData = list()\n\n while(1):\n ret, frame=cap.read()\n frame = cv2.flip(frame, 1)\n framecount += 1\n\n # Check if this is the frame closest to 5 seconds\n if framecount == (framerate * 1):\n framecount = 0\n letter = predictLetter(frame)\n writeLetter(letter.upper(), frame)\n cv2.imshow('Imagem capturada', frame)\n\n k = cv2.waitKey(5) & 0xFF\n if k == 27:\n break\n\n cap.release()\n cv2.destroyAllWindows()\n\ndef applyPCA(data):\n # print('PRE-PCA: ', len(data), len(data[0]))\n data = pca.fit_transform(data)\n # print('POS-PCA: ', len(data), len(data[0]))\n # print('Variancia: ', pca.explained_variance_)\n # print('Variancia: ', pca.explained_variance_ratio_)\n # print('Componentes: ', pca.components_)\n return data\n\ndef trainClassifier():\n dfData = list()\n nComp = 0\n\n for letter in ascii_lowercase:\n for i in range(10):\n # Abre a imagem\n imgPath = 'alphabet/{}{}.jpg'.format(letter, i)\n img = cv2.imread(imgPath)\n\n # Extrai os dados do momento\n data = treatImage(img).ravel().tolist()\n data.insert(0, letter)\n dfData.append(data)\n\n # Treina a pca a PCA\n dataWithoutLetter = list(map(lambda d: d[1:], dfData))\n data = pca.fit_transform(dataWithoutLetter).tolist()\n nComp = len(data[0])\n\n columns = ['c{}'.format(i) for i in range(nComp)]\n columns.insert(0, 'letter')\n\n for i in range(len(dfData)):\n data[i].insert(0, dfData[i][0])\n\n df = pd.DataFrame(data, columns=columns).fillna(0)\n\n print(df.info())\n print(df.head(2))\n\n # Dados pra treinamento\n x = df.drop('letter', axis=1)\n y = df['letter']\n\n # sns.set(style='ticks')\n # sns.pairplot(df, hue='letter')\n\n # Treina o classificador\n LC.train(x, y, nComp)\n\ndef predictLetter(img):\n l = list()\n data = treatImage(img).ravel().tolist()\n l.append(data)\n data = pca.transform(l).tolist()\n\n columns = ['c{}'.format(i) for i in range(LC.n)]\n df = pd.DataFrame(data, columns=columns).fillna(0)\n\n prediction = LC.predict(df)\n print(\"{}, \".format(prediction[0]))\n\n return prediction[0]\n\nif __name__ == '__main__':\n trainClassifier()\n\n for letter in ascii_lowercase:\n print('**** {}'.format(letter))\n [ predictLetter(cv2.imread('alphabet/{}{}.jpg'.format(letter, i))) for i in range(10) ]\n print()\n\n print(predictLetter([cv2.imread('alphabet/d{}.jpg'.format(i)) for i in range(6) ]))\n #videoLive()\n","sub_path":"relatorio6/atividade.py","file_name":"atividade.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"279506170","text":"\"\"\"The goal of this script is to just find a good setting.\"\"\"\nimport rlkit.misc.hyperparameter as hyp\nimport torch.nn.functional as F\nfrom rlkit.launchers.experiments.disentanglement.rig_launcher import \\\n disentangled_grill_her_twin_sac_experiment\nfrom rlkit.launchers.launcher_util import run_experiment\nfrom rlkit.torch.vae.conv_vae import imsize48_default_architecture\n\nif __name__ == \"__main__\":\n variant = dict(\n qf_kwargs=dict(\n hidden_sizes=[400, 300],\n ),\n policy_kwargs=dict(\n hidden_sizes=[400, 300],\n ),\n encoder_kwargs=dict(\n hidden_sizes=[400, 300],\n hidden_activation=F.tanh,\n ),\n twin_sac_trainer_kwargs=dict(\n reward_scale=1,\n discount=0.99,\n target_update_period=1,\n use_automatic_entropy_tuning=True,\n ),\n td3_trainer_kwargs=dict(\n tau=1e-3,\n ),\n max_path_length=100,\n algo_kwargs=dict(\n batch_size=256,\n num_epochs=50,\n num_eval_steps_per_epoch=1000,\n num_expl_steps_per_train_loop=1000,\n num_trains_per_train_loop=1000,\n min_num_steps_before_training=1000,\n # batch_size=256,\n # num_epochs=50,\n # num_eval_steps_per_epoch=100,\n # num_expl_steps_per_train_loop=100,\n # num_trains_per_train_loop=100,\n # min_num_steps_before_training=1000,\n # batch_size=4,\n # num_epochs=10,\n # num_eval_steps_per_epoch=10,\n # num_expl_steps_per_train_loop=10,\n # num_trains_per_train_loop=10,\n # min_num_steps_before_training=100,\n ),\n replay_buffer_kwargs=dict(\n fraction_goals_rollout_goals=0.2,\n fraction_goals_env_goals=0.5,\n max_size=int(1e6),\n ob_keys_to_save=[\n 'latent_observation',\n 'latent_desired_goal',\n 'latent_achieved_goal',\n 'state_achieved_goal',\n 'state_desired_goal',\n 'state_observation',\n ],\n goal_keys=['latent_desired_goal', 'state_desired_goal'],\n ),\n observation_key='latent_observation',\n desired_goal_key='latent_desired_goal',\n achieved_goal_key='latent_achieved_goal',\n vae_exploration_goal_sampling_mode='env',\n vae_evaluation_goal_sampling_mode='env',\n base_env_exploration_goal_sampling_mode='train',\n base_env_evaluation_goal_sampling_mode='test',\n disentangled_qf_kwargs=dict(\n ),\n # vectorized=True,\n vectorized=False,\n vae_wrapped_env_kwargs=dict(\n norm_order=1,\n reward_params=dict(\n # type='vectorized_latent_distance',\n type='latent_distance',\n norm_order=1,\n ),\n ),\n latent_dim=2,\n vae_path='/home/vitchyr/res/02-26-experiments-vitchyr-disentanglement-pointmass-disentanglement-rig/02-26-experiments-vitchyr-disentanglement-pointmass-disentanglement-rig_2020_02_26_19_57_00_id000--s10424/vae.pkl',\n # vae_path='/global/scratch/vitchyr/models/02-26-experiments-vitchyr-disentanglement-pointmass-disentanglement-rig_2020_02_26_19_57_00_id000--s10424/vae.pkl',\n vae_n_vae_training_kwargs=dict(\n decoder_activation='sigmoid',\n vae_kwargs=dict(\n input_channels=3,\n ),\n vae_trainer_kwargs=dict(\n lr=1e-3,\n beta=20,\n ),\n vae_train_epochs=250,\n num_image_examples=30000,\n vae_architecture=imsize48_default_architecture,\n ),\n save_video=True,\n save_video_kwargs=dict(\n save_video_period=10,\n imsize=48,\n ),\n )\n\n search_space = {\n 'env_id': [\n 'Point2DEnv-Train-Everything-Eval-Everything-Images-48-v0',\n # 'Point2DEnv-Train-Half-Axis-Eval-Everything-Images-v0',\n ],\n 'disentangled_qf_kwargs.encode_state': [True],\n # 'vectorized': [\n # True,\n # False,\n # ],\n # 'disentangled_qf_kwargs.give_each_qf_single_goal_dim': [\n # True,\n # False,\n # ],\n 'have_no_disentangled_encoder': [\n True,\n ],\n }\n sweeper = hyp.DeterministicHyperparameterSweeper(\n search_space, default_parameters=variant,\n )\n\n n_seeds = 1\n mode = 'local'\n exp_prefix = '{}'.format(\n __file__.replace('/', '-').replace('_', '-').split('.')[0]\n )\n\n # n_seeds = 5\n # mode = 'sss'\n # exp_prefix = 'disentangled-basic-test-envs-new-vae'\n\n for exp_id, variant in enumerate(sweeper.iterate_hyperparameters()):\n for _ in range(n_seeds):\n run_experiment(\n disentangled_grill_her_twin_sac_experiment,\n exp_prefix=exp_prefix,\n mode=mode,\n variant=variant,\n use_gpu=True,\n time_in_mins=int(2.5*24*60),\n )\n","sub_path":"experiments/vitchyr/disentanglement/pointmass/basic_learning_sweep.py","file_name":"basic_learning_sweep.py","file_ext":"py","file_size_in_byte":5149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"500501550","text":"from math import *\n\ndef euclid(a,b):\n #Euclidean algorithm \n #compute the greatest common denominator\n if (b == 0):\n return a\n else:\n return euclid(b, a % b)\n\ndef F(L):\n m = 0\n x = 2\n maxX= int(sqrt(L))\n collection = 0\n while not(x>maxX):\n a = 1\n while(aL):\n generated = int(L/(x*y))\n #b = 1;\n # while not(b>generated):\n # print x*b, y*b, x*y*b\n # b+= 1\n collection += generated\n #print x, y, x*y, ' generator generated ',generated,'permutation(s)'\n a+=1\n x+=1\n return collection","sub_path":"an_algorithm.py","file_name":"an_algorithm.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"608640840","text":"#---------------#\n# by https://qiita.com/poorko/items/9140c75415d748633a10\n#---------------#\n\n# coding: UTF-8\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport subprocess\nimport os\n\n# setting\nurl=input('URL:')\nname=input('OUT FILE NAME:moji_out_')\nsubprocess.call(['mkdir','output'])\nfile = './output/moji_out_'+name+'.txt'\npath = os.path.abspath(file)\n\n# scraping\nhtml=requests.get(url).content\nsoup=BeautifulSoup(html,'html.parser')\nfor script in soup(['script', 'style']):\n script.decompose()\ntext=soup.get_text()\nlines= [line.strip() for line in text.splitlines()]\ntext='\\n'.join(line for line in lines if line)\n\n# write\nwith open(path, mode='w') as f:\n f.write(text)\nprint(f'\\nFinished!!\\nPlease open {path}')\nsubprocess.call(['open',path])\n","sub_path":"moji/moji.py","file_name":"moji.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"547740586","text":"# -*- coding: utf-8 -*-\n\"\"\"\n pip_services3_components.logs.LogMessage\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n \n Log message implementation\n \n :copyright: Conceptual Vision Consulting LLC 2018-2019, see AUTHORS for more details.\n :license: MIT, see LICENSE for more details.\n\"\"\"\n\nimport datetime\n\nclass LogMessage(object):\n \"\"\"\n Data object to store captured log messages. This object is used by [[CachedLogger]].\n \"\"\"\n time = None\n source = None\n level = None\n correlation_id = None\n error = None\n message = None\n\n def __init__(self, level = None, source = None, correlation_id = None, error = None, message = None):\n \"\"\"\n Creates log message\n\n :param level: a log level.\n\n :param source: the source (context name)\n\n :param correlation_id: (optional) transaction id to trace execution through call chain.\n\n :param error: an error object associated with this message.\n\n :param message: a human-readable message to log.\n \"\"\"\n self.time = datetime.datetime.utcnow()\n self.level = level\n self.source = source\n self.correlation_id = correlation_id\n self.error = error\n self.message = message\n","sub_path":"pip_services3_components/log/LogMessage.py","file_name":"LogMessage.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"237416729","text":"\"\"\" Setup script for PyPI \"\"\"\nimport os\nfrom setuptools import setup\nfrom ConfigParser import SafeConfigParser\n\nsettings = SafeConfigParser()\nsettings.read(os.path.realpath('git_pylint_commit_hook/settings.conf'))\n\n\nsetup(\n name='git-pylint-commit-hook',\n version=settings.get('general', 'version'),\n license='Apache License, Version 2.0',\n description='Git commit hook that checks Python files with pylint',\n author='Sebastian Dahlgren',\n author_email='sebastian.dahlgren@gmail.com',\n url='http://www.sebastiandahlgren.se',\n keywords=\"git commit pre-commit hook pylint python\",\n platforms=['Any'],\n packages=['git_pylint_commit_hook'],\n scripts=['git-pylint-commit-hook'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Console',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python'\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"495671452","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom threading import Thread\nfrom flask import Flask, request, render_template, make_response\n\nimport json\nimport functools\n\nfrom objects.mainobjects import *\n\nimport os\nimport psutil\n\napp = Flask(__name__)\ndb_engine = create_engine('sqlite:///storage/master.db', connect_args={'check_same_thread':False})\nsession_maker = sessionmaker()\nsession_maker.configure(bind=db_engine)\n\nmain_session = session_maker()\n\n\ndef auth_endpoint(f):\n\tdef wrap(*args, **kwargs):\n\t\tval = f()\n\t\treturn val\n\treturn wrap\n\n#def login_required(func):\n# \"\"\"Make sure user is logged in before proceeding\"\"\"\n# @functools.wraps(func)\n# def wrapper_login_required(*args, **kwargs):\n# if g.user is None:\n# return redirect(url_for(\"login\", next=request.url))\n# return func(*args, **kwargs)\n# return wrapper_login_required\n\ndef admin_endpoint(f):\n\t@functools.wraps(f)\n\tdef wrap(*args, **kwargs):\n\t\tif (request.cookies.get('teamx_session')):\n\t\t\tuser = Session.GetUserBySession(main_session, request.cookies.get('teamx_session'))\n\t\t\tif (user):\n\t\t\t\tif (user.is_admin or user.is_superuser):\n\t\t\t\t\trequest.teamx_user = user\n\t\t\t\t\treturn f()\n\t\treturn render_template('users/login.html', title='Home', user=None)\n\treturn wrap\n\n##############################\n##### Static Site Routes #####\n##############################\n\n@app.route('/')\n@app.route('/index')\ndef index():\n\tif (request.cookies.get('teamx_session')):\n\t\tuser = Session.GetUserBySession(main_session, request.cookies.get('teamx_session'))\n\t\tif (user):\n\t\t\treturn render_template('index.html', title='Home', user=user)\n\treturn render_template('index.html', title='Home', user=None)\n\n@app.route('/about')\ndef about():\n\treturn \"About\"\n\n@app.route('/contact')\ndef contact():\n\treturn \"Contact\"\n\n@app.route('/faq')\ndef faq():\n\tif (request.cookies.get('teamx_session')):\n\t\tuser = Session.GetUserBySession(main_session, request.cookies.get('teamx_session'))\n\t\tif (user):\n\t\t\treturn render_template('faqs.html', title='FAQs', user=user)\n\treturn render_template('faqs.html', title='FAQs', user=None)\n\n\n###############################\n##### Dynamic Site Routes #####\n###############################\n@app.route('/register')\ndef user_register():\n\treturn render_template('users/register.html', title='Register to become a user', user=None)\n\n@app.route('/welcome')\ndef welcome_user():\n\tif (request.cookies.get('teamx_session')):\n\t\tuser = Session.GetUserBySession(main_session, request.cookies.get('teamx_session'))\n\t\tif (user):\n\t\t\treturn render_template('users/welcome.html', title='Welcome to Team X', user=user, servers=Server.GetTopThree(main_session))\n\treturn render_template('users/register.html', title='Register to become a user', user=None)\n\n@app.route('/servers')\ndef view_all_servers():\n\tif (request.cookies.get('teamx_session')):\n\t\tuser = Session.GetUserBySession(main_session, request.cookies.get('teamx_session'))\n\t\tif (user):\n\t\t\t\treturn render_template('servers.html', title='Servers', user=user, servers=Server.GetAll(main_session))\n\treturn render_template('servers.html', title='Servers', user=None, servers=Server.GetAll(main_session))\n\n\n@app.route('/logout')\ndef logout():\n\tresponse = make_response(render_template('users/login.html', title=\"Please log in\", user=None))\n\tresponse.set_cookie('teamx_session', '', expires=0)\n\treturn response\n\n@app.route('/login')\ndef login():\n\treturn render_template('users/login.html', title=\"Please log in\", user=None)\n\n\n###############################\n##### Admin Site Routes #####\n###############################\n@app.route('/admin')\n@admin_endpoint\ndef admin_home():\n\treturn render_template('admin/dashboard.html', title=\"Admin Dashboard\", user=request.teamx_user)\n\n@app.route('/admin/users')\n@admin_endpoint\ndef admin_users():\n\treturn render_template('admin/manage_users.html', title=\"Manage Users\", user=request.teamx_user)\n\n@app.route('/admin/servers')\n@admin_endpoint\ndef admin_servers():\n\treturn render_template('admin/manage_servers.html', title=\"Admin Dashboard\", user=request.teamx_user, servers=Server.GetAll(main_session))\n\n###############################\n##### Rest API Routes #####\n###############################\n@app.route('/api/authentication/user', methods=['POST'])\ndef api_auth_user():\n\tusername = get_value_or_blank(request, \"username\")\n\tpassword = get_value_or_blank(request, \"password\")\n\n\tif (username == \"\" or password == \"\"):\n\t\treturn \"Both fields cannot be blank\", 403\n\telse:\n\t\tsession = User.LogUserIn(main_session, username, password, request.remote_addr)\n\t\tif session == None:\n\t\t\treturn \"The provided credentials did not match our records\", 403\n\t\telse:\n\t\t\treturn session.id, 200\n\n@app.route('/api/create/user', methods=['POST'])\ndef api_create_user():\n\ttry:\n\t\tusername = get_value_or_blank(request, \"username\")\n\t\tpassword = get_value_or_blank(request, \"password\")\n\t\tdisplay_name = get_value_or_blank(request, \"display_name\")\n\t\tfirst_name = get_value_or_blank(request, \"first_name\")\n\t\temail = get_value_or_blank(request, \"email\")\n\t\tuser, session_id = User.RegisterUser(main_session, username, password, display_name, first_name, email, request.remote_addr)\n\t\treturn session_id, 200\n\texcept RecordExists as ex:\n\t\treturn \"Your \"+ex.field+\" must be unique. That one is already in use\", 500\n\n@app.route('/api/create/server', methods=['POST'])\n@admin_endpoint\ndef api_create_server():\n\ttry:\n\t\tname = get_value_or_blank(request, \"name\")\n\t\taddress = get_value_or_blank(request, \"address\")\n\t\tmc_version = get_value_or_blank(request, \"minecraft_version\")\n\t\tpath_to_technic = get_value_or_blank(request, \"path_to_technic\")\n\t\tpath_to_image = \"\"\n\t\tshortdesc = get_value_or_blank(request, \"shortdesc\")\n\t\tfulldesc = get_value_or_blank(request, \"fulldesc\")\n\t\tserver = Server.AddServer(main_session, name, path_to_image, path_to_technic, mc_version, address, shortdesc, fulldesc)\n\t\treturn server.id, 200\n\texcept RecordExists as ex:\n\t\treturn \"Your \"+ex.field+\" must be unique. That one is already in use\", 500\n\n\n#This is a solution until we have something like 10k-20k users\n#After that, pagination needs to be considered\n@app.route('/api/fetch/all_users', methods=['GET'])\n@admin_endpoint\ndef api_get_all_users():\n\ttry:\n\t\treturn User.GetAllUsers(main_session)\n\texcept:\n\t\treturn \"There was an error\", 500\n\n@app.route('/api/fetch/cpu_usage', methods=['GET'])\n@admin_endpoint\ndef api_get_cpu_usage():\n\treturn str(psutil.cpu_percent())\n\n@app.route('/api/fetch/memory_usage', methods=['GET'])\n@admin_endpoint\ndef api_get_memory_usage():\n\treturn str(psutil.virtual_memory().percent)\n\n@app.route('/api/fetch/number_open_tickets', methods=['GET'])\n@admin_endpoint\ndef api_get_open_tickets():\n\treturn str(1)\n\n###############################\n##### Utility Functions #####\n###############################\ndef get_value_or_blank(request, value, type=\"POST\"):\n\t#Returns either the value pulled from a request. Or defaults to nothing\n\tif (type == \"POST\"):\n\t\treturn \"\" if request.form.get(value) is None else request.form.get(value)\n\telse:\n\t\traise NotImplemented\n\nDatabaseBase.metadata.create_all(db_engine)\nmain_session.commit()\n\napp.run(debug=True)\n","sub_path":"teamx_2-master - Copy/site/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"254789946","text":"# Copyright 2015 CityGrid Media, LLC\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#\nfrom pyramid.view import view_config\nfrom pyramid.response import Response\nfrom datetime import datetime\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom arsenalweb.views import (\n get_authenticated_user,\n log,\n )\nfrom arsenalweb.views.api import (\n get_api_attribute,\n api_read_by_id,\n api_read_by_params,\n api_delete_by_id,\n api_delete_by_params,\n )\nfrom arsenalweb.models import (\n DBSession,\n HypervisorVmAssignment,\n )\n\n\n@view_config(route_name='api_hypervisor_vm_assignments', request_method='GET', request_param='schema=true', renderer='json')\ndef api_hypervisor_vm_assignments_schema(request):\n \"\"\"Schema document for the hypervisor_vm_assignments API.\"\"\"\n\n hva = {\n }\n\n return hva\n\n\n@view_config(route_name='api_hypervisor_vm_assignment_r', request_method='GET', renderer='json')\ndef api_hypervisor_vm_assignment_read_attrib(request):\n \"\"\"Process read requests for the /api/hypervisor_vm_assignments/{id}/{resource} route.\"\"\"\n\n return get_api_attribute(request, 'HypervisorVmAssignment')\n\n\n@view_config(route_name='api_hypervisor_vm_assignment', request_method='GET', renderer='json')\ndef api_hypervisor_vm_assignment_read_id(request):\n \"\"\"Process read requests for the /api/hypervisor_vm_assignments/{id} route.\"\"\"\n\n return api_read_by_id(request, 'HypervisorVmAssignment')\n\n\n@view_config(route_name='api_hypervisor_vm_assignments', request_method='GET', renderer='json')\ndef api_hypervisor_vm_assignment_read(request):\n \"\"\"Process read requests for the /api/hypervisor_vm_assignments route.\"\"\"\n\n return api_read_by_params(request, 'HypervisorVmAssignment')\n\n\n@view_config(route_name='api_hypervisor_vm_assignments', permission='api_write', request_method='PUT', renderer='json')\ndef api_hypervisor_vm_assignments_write(request):\n \"\"\"Process write requests for the /api/hypervisor_vm_assignments route.\"\"\"\n\n au = get_authenticated_user(request)\n\n try:\n payload = request.json_body\n\n parent_node_id = payload['parent_node_id']\n child_node_id = payload['child_node_id']\n\n log.info('Checking for hypervisor_vm_assignment child_node_id={0}'.format(child_node_id))\n\n try:\n hva = DBSession.query(HypervisorVmAssignment)\n hva = hva.filter(HypervisorVmAssignment.child_node_id==child_node_id)\n hva = hva.one()\n except NoResultFound:\n try:\n log.info('Creating new hypervisor_vm_assignment parent_node_id={0},child_node_id={1}'.format(parent_node_id, child_node_id))\n utcnow = datetime.utcnow()\n\n hva = HypervisorVmAssignment(parent_node_id=parent_node_id,\n child_node_id=child_node_id,\n updated_by=au['user_id'],\n created=utcnow,\n updated=utcnow)\n\n DBSession.add(hva)\n DBSession.flush()\n except Exception as e:\n log.error('Error creating new hypervisor_vm_assignment parent_node_id={0},child_node_id={1},exception={2}'.format(parent_node_id, child_node_id, e))\n raise\n else:\n try:\n log.info('Updating hypervisor_vm_assignment parent_node_id={0},child_node_id={1}'.format(parent_node_id, child_node_id))\n\n hva.parent_node_id = parent_node_id\n hva.child_node_id = child_node_id\n hva.updated_by=au['user_id']\n\n DBSession.flush()\n except Exception as e:\n log.error('Error updating hypervisor_vm_assignment parent_node_id={0},child_node_id={1},exception={2}'.format(parent_node_id, child_node_id, e))\n raise\n\n except Exception as e:\n log.error('Error writing to hypervisor_vm_assignment API={0},exception={1}'.format(request.url, e))\n return Response(str(e), content_type='application/json', status_int=500)\n\n\n@view_config(route_name='api_hypervisor_vm_assignment', permission='api_write', request_method='DELETE', renderer='json')\ndef api_hypervisor_vm_assignments_delete_id(request):\n \"\"\"Process delete requests for the /api/hypervisor_vm_assignments/{id} route.\"\"\"\n\n return api_delete_by_id(request, 'HypervisorVmAssignment')\n\n\n@view_config(route_name='api_hypervisor_vm_assignments', permission='api_write', request_method='DELETE', renderer='json')\ndef api_hypervisor_vm_assignments_delete(request):\n \"\"\"Process delete requests for the /api/hypervisor_vm_assignments route.\n Iterates over passed parameters.\"\"\"\n\n return api_delete_by_params(request, 'HypervisorVmAssignment')\n","sub_path":"arsenalweb/views/api/hypervisor_vm_assignments.py","file_name":"hypervisor_vm_assignments.py","file_ext":"py","file_size_in_byte":5295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"414750932","text":"from django.shortcuts import render\nfrom . import forms\nfrom . import models\nfrom django.http import HttpResponse\nfrom django.contrib.auth.models import User\n# Create your views here.\ndef signup(request):\n\tif request.method =='POST':\n\t\t\tform = forms.Register(request.POST)\n\t\t\tif form.is_valid():\n\t\t\t\t form.save()\n\t\t\t\t models.Otherdetail(\n\t\t\t\t user=User.objects.get(username=form.cleaned_data.get('username')),\n\t\t\t\t bio = form.cleaned_data.get('bio'),\n\t\t\t\t dob=form.cleaned_data.get('date_of_birth')).save()\n\t\t\t\t return HttpResponse(\"USER SAVED\")\n\t\t\telse:\n\t\t\t\treturn render(request,'us_au/signup.html',{'form':form})\n\telse:\n\t\tform=forms.Register()\n\t\treturn render(request,'us_au/signup.html',{'form':form})\t","sub_path":"pro_name/us_au/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"245190546","text":"import plotly.graph_objects as go\nimport pandas as pd\nfrom datetime import datetime\nimport os\n\n\ndef str2dt(s):\n return datetime.strptime(s, '%Y-%m-%d')\n\n\ndef make_plot(precip_csv_file, ofile):\n title = 'GSMaP Precipitation by Region'\n df = pd.read_csv(precip_csv_file)\n departments = df['Admin1Name']\n df1 = df.transpose()\n df2 = df1.drop('Admin1Name', axis=0)\n col = 0\n\n labels = []\n str_x_data = df2.index.values\n x_data = [ str2dt(s) for s in str_x_data]\n\n y_data = []\n\n for department in departments:\n labels.append(department)\n y_data.append(df2[col])\n col += 1\n\n # https://plot.ly/python/discrete-color/\n colors = [\n \"rgb(229, 134, 6)\",\n \"rgb(93, 105, 177)\",\n \"rgb(82, 188, 163)\",\n \"rgb(153, 201, 69)\",\n \"rgb(204, 97, 176)\",\n \"rgb(36, 121, 108)\",\n \"rgb(218, 165, 27)\",\n \"rgb(47, 138, 196)\",\n \"rgb(107, 17, 0)\",\n \"rgb(237, 100, 90)\",\n \"rgb(165, 170, 153)\",\n ]\n\n fig = go.Figure()\n\n for i in range(0, min(len(colors), len(labels))):\n fig.add_trace(go.Scatter(\n x=x_data,\n y=y_data[i],\n mode='lines',\n name=labels[i],\n line=dict(color=colors[i], width=3),\n connectgaps=True,\n ))\n\n fig.update_layout(\n plot_bgcolor='white',\n xaxis=dict(\n linecolor='rgb(204, 204, 204)',\n linewidth=2,\n gridcolor='rgb(204, 204, 204)',\n gridwidth=1,\n title_text='Date (UTC)',\n title_font={\"size\": 20},\n ),\n yaxis=dict(\n linecolor='rgb(204, 204, 204)',\n linewidth=2,\n gridcolor='rgb(204, 204, 204)',\n gridwidth=1,\n title_text='Precipitation (mm)',\n title_font={\"size\": 20},\n ),\n showlegend=True,\n legend = dict(\n font=dict(\n family='Arial',\n size=18,\n color='rgb(82, 82, 82)',\n ),\n )\n )\n\n annotations = []\n annotations.append(dict(xref='paper', yref='paper', x=0.0, y=1.05,\n xanchor='left', yanchor='bottom',\n text=title,\n font=dict(family='Arial',\n size=30,\n color='rgb(37,37,37)'),\n showarrow=False))\n\n fig.update_layout(annotations=annotations)\n\n fig.write_image(ofile)\n print('Saved precip chart: %s' % ofile)\n\n\ndef generate_report_markdown(ag_impacts_csv, pop_impacts_csv, md_file_name):\n # markdown table\n # https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet\n if os.path.exists(md_file_name):\n os.remove(md_file_name)\n\n ag_df = pd.read_csv(ag_impacts_csv)\n pop_df = pd.read_csv(pop_impacts_csv)\n\n ag_df.set_index('Admin2Name')\n pop_df.set_index('Admin2Name')\n df = pop_df.join(ag_df, lsuffix='_pop', rsuffix='_ag')\n\n with open(md_file_name, 'w') as mdf:\n mdf.write(\n \"\"\"\n ### Population and cropland most likely impacted by flood detection this week\\n\n > Population and cropland located in areas detected as flood this week\\n\n \"\"\")\n\n mdf.write(\"Top 10 Departments | Potential population most likely impacted | Potential crops most likely impacted [km2]\\n\")\n mdf.write(\"---|---|---\\n\")\n\n df.sort_values(\"popImpacted\", inplace=True)\n count = 0\n for row in df.iterrows():\n if count == 10:\n break\n\n mdf.write(\"%s | %f | %f\\n\" % (row[1]['Admin2Name_pop'], row[1]['popImpacted'], row[1]['agImpacted_km2']))\n # print (row[1]['Admin2Name_pop'], row[1]['popImpacted'], row[1]['agImpacted_km2'])\n count += 1\n print('Saved %s' % md_file_name)\n\n\nbase_dir = os.path.dirname(__file__)\nprecip_csv_file = os.path.join(base_dir,\n r\"./data/csv/2020-01-31_Precip_Congo_Precip_gsmapGC_20200101-20200131.csv\")\nofile = os.path.join(base_dir, r'./output/precip_plot.svg')\nmake_plot(precip_csv_file, ofile)\n\nag_impacts_csv = os.path.join(base_dir,\n r'./data/csv/2020-01-31_impacts_Congo_ag_impacts_s1_2020-01-31.csv')\npop_impacts_csv = os.path.join(base_dir,\n r'./data/csv/2020-01-31_impacts_Congo_pop_impacts_s1_2020-01-31.csv')\ngenerate_report_markdown(ag_impacts_csv, pop_impacts_csv,\n os.path.join(base_dir, r'./output/md/slide3-pop-ag-impacts.md'))\n","sub_path":"lib/reveal/congo/precip-chart.py","file_name":"precip-chart.py","file_ext":"py","file_size_in_byte":4653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"282208661","text":"from geometry_msgs.msg import Pose, Point\n\nfrom erdos.op import Op\nfrom erdos.data_stream import DataStream\nfrom erdos.message import Message\n\n\nclass RaiseObjectOperator(Op):\n \"\"\"\n Raises the Sawyer arm while gripping the object.\n \"\"\"\n stream_name = \"raise-object-stream\"\n\n def __init__(self, name):\n \"\"\"\n Initializes the destination coordinates of the arm.\n \"\"\"\n super(RaiseObjectOperator, self).__init__(name)\n self.des_EE_xyz = None\n self.orientation = None\n\n @staticmethod\n def setup_streams(input_streams, location_stream_name,\n trigger_stream_name):\n \"\"\"\n Registers a callback to retrieve the location where the arm needs to\n be moved and returns a single output stream which sends the Pose\n commands to move the robot to the required location.\n \"\"\"\n input_streams.filter_name(location_stream_name)\\\n .add_callback(RaiseObjectOperator.save_destination)\n input_streams.filter_name(trigger_stream_name)\\\n .add_callback(RaiseObjectOperator.generate_move_commands)\n return [\n DataStream(data_type=Pose, name=RaiseObjectOperator.stream_name)\n ]\n\n def save_destination(self, msg):\n \"\"\"\n Saves the destination coordinates and orientation of the arm.\n \"\"\"\n self.des_EE_xyz = msg.data.des_EE_xyz_above\n self.orientation = msg.data.des_orientation_EE\n\n def generate_move_commands(self, msg):\n \"\"\"\n Creates the Pose object from the retrieved coordinates.\n \"\"\"\n raise_object_pose = Pose(\n position=Point(\n x=self.des_EE_xyz[0],\n y=self.des_EE_xyz[1],\n z=self.des_EE_xyz[2]),\n orientation=self.orientation)\n raise_object_msg = Message(raise_object_pose, msg.timestamp)\n self.get_output_stream(RaiseObjectOperator.stream_name).\\\n send(raise_object_msg)\n\n def execute(self):\n self.spin()\n","sub_path":"examples/the-feeling-of-success/raise_object_op.py","file_name":"raise_object_op.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"195643995","text":"# from autodiff import Function, Gradient\nimport numpy as np\n\nfrom .. import Solution\nfrom ..Algorithm import Algorithm\nfrom .SingleShooting import SingleShooting\nfrom math import *\nfrom beluga.utils import *\nfrom beluga.utils import Propagator\nfrom beluga.utils.Worker import Worker\nimport logging, sys, os\n\n\ntry:\n from mpi4py import MPI\n HPCSUPPORTED = 1\nexcept ImportError:\n HPCSUPPORTED = 0\n\nclass MultipleShooting(Algorithm):\n def __new__(cls, tolerance=1e-6, max_iterations=100, max_error=100, derivative_method='fd', cache_dir = None,verbose=False,cached=True,number_arcs=-1):\n obj = super(MultipleShooting, cls).__new__(cls)\n if number_arcs == 1:\n return SingleShooting(tolerance=tolerance, max_iterations=max_iterations, max_error=max_error, derivative_method=derivative_method, cache_dir=cache_dir, verbose=verbose, cached=cached)\n return obj\n\n def __init__(self, tolerance=1e-6, max_iterations=100, max_error=100, derivative_method='fd', cache_dir = None,verbose=False,cached=True,number_arcs=-1):\n self.tolerance = tolerance\n self.max_iterations = max_iterations\n self.verbose = verbose\n self.max_error = max_error\n self.derivative_method = derivative_method\n if derivative_method == 'csd':\n self.stm_ode_func = self.__stmode_csd\n self.bc_jac_func = self.__bcjac_fd\n elif derivative_method == 'fd':\n self.stm_ode_func = self.__stmode_fd\n self.bc_jac_func = self.__bcjac_fd\n else:\n raise ValueError(\"Invalid derivative method specified. Valid options are 'csd' and 'fd'.\")\n self.cached = cached\n if cached and cache_dir is not None:\n self.set_cache_dir(cache_dir)\n self.number_arcs = number_arcs\n\n # TODO: Implement the host worker in a nicer way\n # Start Host MPI process\n # self.worker = Worker(mode='HOST')\n # self.worker.startWorker()\n # self.worker.Propagator.setSolver(solver='ode45')\n self.worker = None\n\n def set_cache_dir(self,cache_dir):\n self.cache_dir = cache_dir\n if self.cached and cache_dir is not None:\n raise NotImplementedError\n # TODO: Fix this cache function. It used an old outdated package that no longer works.\n # memory = Memory(cachedir=cache_dir, mmap_mode='r', verbose=0)\n self.solve = memory.cache(self.solve)\n\n def __bcjac_csd(self, bc_func, ya, yb, phi, parameters, aux, StepSize=1e-50):\n ya = np.array(ya, dtype=complex)\n yb = np.array(yb, dtype=complex)\n # if parameters is not None:\n p = np.array(parameters, dtype=complex)\n h = StepSize\n\n nOdes = ya[0].shape[0]\n nBCs = nOdes + nOdes*(self.number_arcs - 1)\n if parameters is not None:\n nBCs += parameters.size\n\n fx = bc_func(ya,yb,parameters,aux)\n\n M = [np.zeros((nBCs, nOdes)) for _ in range(self.number_arcs)]\n N = [np.zeros((nBCs, nOdes)) for _ in range(self.number_arcs)]\n J = [None for _ in range(self.number_arcs)]\n for arc in range(self.number_arcs):\n for i in range(nOdes):\n ya[arc][i] += h*1j\n f = bc_func(ya,yb,p,aux)\n M[arc][:,i] = np.imag(f)/h\n ya[arc][i] -= h*1j\n\n yb[arc][i] += h*1j\n f = bc_func(ya,yb,p,aux)\n N[arc][:,i] = np.imag(f)/h\n yb[arc][i] -= h*1j\n J[arc] = M[arc]+np.dot(N[arc],phi[arc])\n\n if parameters is not None:\n P = np.zeros((nBCs, p.size))\n for i in range(p.size):\n p[i] = p[i] + h*1j\n f = bc_func(ya,yb,p,aux)\n P[:,i] = np.imag(f)/h\n p[i] = p[i] - h*1j\n J.append(P)\n\n J = np.hstack(J)\n return J\n\n def __bcjac_fd(self, bc_func, ya, yb, phi, parameters, aux, StepSize=1e-6):\n # if parameters is not None:\n p = np.array(parameters)\n h = StepSize\n\n nOdes = ya[0].shape[0]\n nBCs = nOdes + nOdes*(self.number_arcs - 1)\n if parameters is not None:\n nBCs += parameters.size\n\n fx = bc_func(ya,yb,parameters,aux)\n\n M = [np.zeros((nBCs, nOdes)) for _ in range(self.number_arcs)]\n N = [np.zeros((nBCs, nOdes)) for _ in range(self.number_arcs)]\n J = [None for _ in range(self.number_arcs)]\n for arc in range(self.number_arcs):\n for i in range(nOdes):\n ya[arc][i] += h\n f = bc_func(ya,yb,p,aux)\n M[arc][:,i] = (f-fx)/h\n ya[arc][i] -= h\n\n yb[arc][i] += h\n f = bc_func(ya,yb,p,aux)\n N[arc][:,i] = (f-fx)/h\n yb[arc][i] -= h\n J[arc] = M[arc]+np.dot(N[arc],phi[arc])\n\n if parameters is not None:\n P = np.zeros((nBCs, p.size))\n for i in range(p.size):\n p[i] = p[i] + h\n f = bc_func(ya,yb,p,aux)\n P[:,i] = (f-fx)/h\n p[i] = p[i] - h\n J.append(P)\n\n J = np.hstack(J)\n return J\n\n def __stmode_fd(self, x, y, odefn, parameters, aux, nOdes = 0, StepSize=1e-6):\n \"Finite difference version of state transition matrix\"\n N = y.shape[0]\n nOdes = int(0.5*(sqrt(4*N+1)-1))\n\n phi = y[nOdes:].reshape((nOdes, nOdes)) # Convert STM terms to matrix form\n Y = np.array(y[0:nOdes]) # Just states\n F = np.zeros((nOdes, nOdes))\n\n # Compute Jacobian matrix, F using finite difference\n fx = (odefn(x, Y, parameters, aux)).real\n for i in range(nOdes):\n Y[i] += StepSize\n F[:, i] = (odefn(x, Y, parameters, aux) - fx).real/StepSize\n Y[i] -= StepSize\n\n phiDot = np.dot(F, phi)\n return np.concatenate((fx, np.reshape(phiDot, (nOdes*nOdes))))\n\n def __stmode_csd(self, x, y, odefn, parameters, aux, StepSize=1e-100):\n \"Complex step version of State Transition Matrix\"\n N = y.shape[0]\n nOdes = int(0.5 * (sqrt(4 * N + 1) - 1))\n\n phi = y[nOdes:].reshape((nOdes, nOdes)) # Convert STM terms to matrix form\n Y = np.array(y[0:nOdes], dtype=complex) # Just states\n F = np.zeros((nOdes, nOdes))\n\n # Compute Jacobian matrix, F using finite difference\n for i in range(nOdes):\n Y[i] += StepSize * 1.j\n F[:, i] = np.imag(odefn(x, Y, parameters, aux)) / StepSize\n Y[i] -= StepSize * 1.j\n\n # Phidot = F*Phi (matrix product)\n phiDot = np.dot(F, phi)\n return np.concatenate((odefn(x, y, parameters, aux), np.reshape(phiDot, (nOdes * nOdes))))\n\n # def __stmode_ad(self, x, y, odefn, parameters, aux, nOdes = 0, StepSize=1e-50):\n # \"Automatic differentiation version of State Transition Matrix\"\n # phi = y[nOdes:].reshape((nOdes, nOdes)) # Convert STM terms to matrix form\n # # Y = np.array(y[0:nOdes],dtype=complex) # Just states\n # # F = np.zeros((nOdes,nOdes))\n # # # Compute Jacobian matrix using complex step derivative\n # # for i in range(nOdes):\n # # Y[i] = Y[i] + StepSize*1.j\n # # F[:,i] = np.imag(odefn(x, Y, parameters, aux))/StepSize\n # # Y[i] = Y[i] - StepSize*1.j\n # f = Function(odefn)\n # g = Gradient(odefn)\n #\n # # Phidot = F*Phi (matrix product)\n # # phiDot = np.real(np.dot(F,phi))\n # phiDot = np.real(np.dot(g(x,y,paameters,aux),phi))\n # # return np.concatenate( (odefn(x,y, parameters, aux), np.reshape(phiDot, (nOdes*nOdes) )) )\n # return np.concatenate( f(x,y,parameters,aux), np.reshape(phiDot, (nOdes*nOdes) ))\n\n\n # @staticmethod\n # def ode_wrap(func,*args, **argd):\n # def func_wrapper(x,y0):\n # return func(x,y0,*args,**argd)\n # return func_wrapper\n\n def get_bc(self,ya,yb,p,aux):\n f1 = self.bc_func(ya[0],yb[-1],p,aux)\n for i in range(self.number_arcs-1):\n nextbc = yb[i]-ya[i+1]\n f1 = np.concatenate((f1,nextbc)).astype(np.float64)\n return f1\n\n def solve(self,bvp):\n \"\"\"Solve a two-point boundary value problem\n using the multiple shooting method\n\n Args:\n deriv_func: the ODE function\n bc_func: the boundary conditions function\n solinit: a \"Solution\" object containing the initial guess\n Returns:\n solution of TPBVP\n Raises:\n \"\"\"\n guess = bvp.solution\n\n if self.worker is not None:\n ode45 = self.worker.Propagator\n else:\n # Start local pool\n ode45 = Propagator(solver='ode45',process_count=self.number_arcs)\n ode45.startPool()\n\n # Decrease time step if the number of arcs is greater than the number of indices\n if self.number_arcs >= len(guess.x):\n x,ynew = ode45(bvp.deriv_func, np.linspace(guess.x[0],guess.x[-1],self.number_arcs+1), guess.y[:,0], guess.parameters, guess.aux, abstol=self.tolerance/10, reltol=1e-3)\n guess.y = np.transpose(ynew)\n guess.x = x\n\n solinit = guess\n x = solinit.x\n # Get initial states from the guess structure\n y0g = [solinit.y[:,int(np.floor(i/self.number_arcs*x.shape[0]))] for i in range(self.number_arcs)]\n paramGuess = solinit.parameters\n\n deriv_func = bvp.deriv_func\n self.bc_func = bvp.bc_func\n aux = bvp.solution.aux\n # Only the start and end times are required for ode45\n t0 = x[0]\n tf = x[-1]\n t = x\n\n # Extract number of ODEs in the system to be solved\n nOdes = solinit.y.shape[0]\n\n # Initial state of STM is an identity matrix\n stm0 = np.eye(nOdes).reshape(nOdes*nOdes)\n\n if solinit.parameters is None:\n nParams = 0\n else:\n nParams = solinit.parameters.size\n\n iter = 1 # Initialize iteration counter\n converged = False # Convergence flag\n\n # Ref: Solving Nonlinear Equations with Newton's Method By C. T. Kelley\n # Global Convergence and Armijo's Rule, pg. 11\n alpha = 1\n beta = 1\n r0 = None\n phiset = [np.eye(nOdes) for i in range(self.number_arcs)]\n tspanset = [np.empty(t.shape[0]) for i in range(self.number_arcs)]\n\n tspan = [t0,tf]\n\n try:\n while True:\n if iter>self.max_iterations:\n logging.warn(\"Maximum iterations exceeded!\")\n break\n\n y0set = [np.concatenate( (y0g[i], stm0) ) for i in range(self.number_arcs)]\n\n for i in range(self.number_arcs):\n left = int(np.floor(i/self.number_arcs*t.shape[0]))\n right = int(np.floor((i+1)/self.number_arcs*t.shape[0]))\n if i == self.number_arcs-1:\n right = t.shape[0] - 1\n tspanset[i] = [t[left],t[right]]\n #tspanset[i] = np.linspace(t[left],t[right],np.ceil(5000/self.number_arcs))\n\n # Propagate STM and original system together\n tset,yySTM = ode45(self.stm_ode_func, tspanset, y0set, deriv_func, paramGuess, aux, abstol=self.tolerance/10, reltol=1e-5)\n\n # Obtain just last timestep for use with correction\n yf = [yySTM[i][-1] for i in range(self.number_arcs)]\n # Extract states and STM from ode45 output\n yb = [yf[i][:nOdes] for i in range(self.number_arcs)] # States\n phiset = [np.reshape(yf[i][nOdes:],(nOdes, nOdes)) for i in range(self.number_arcs)] # STM\n\n # y1 = yySTM[0][:, :nOdes]\n # for i in range(1, self.number_arcs):\n # y1 = np.vstack((y1, (yySTM[i][1:, :nOdes])))\n #\n # for i in range(0,len(y1[:,3])):\n # print('den = ' + str((-0.5 * 1 * y1[i,3] * cos(y1[i,7]) - 1 * y1[i,5] * sin(y1[i,7]))) + ' u =' + str(y1[i,7]) + ' lamX =' + str(y1[i,3]) + ' lamA =' + str(y1[i,5]))\n\n # Evaluate the boundary conditions\n res = self.get_bc(y0g, yb, paramGuess, aux)\n\n # Compute correction vector\n r1 = np.linalg.norm(res)\n if r1 > self.max_error:\n logging.warn('Residue: '+str(r1) )\n logging.warn('Residue exceeded max_error')\n raise RuntimeError('Residue exceeded max_error')\n\n if self.verbose:\n logging.debug('Residue: '+str(r1))\n\n # Solution converged if BCs are satisfied to tolerance\n if max(abs(res)) < self.tolerance:\n if self.verbose:\n logging.info(\"Converged in \"+str(iter)+\" iterations.\")\n converged = True\n break\n # logging.debug(paramGuess)\n # Compute Jacobian of boundary conditions using numerical derviatives\n J = self.bc_jac_func(self.get_bc, y0g, yb, phiset, paramGuess, aux).astype(np.float64)\n # if r0 is not None:\n # beta = (r0-r1)/(alpha*r0)\n # if beta < 0:\n # beta = 1\n # if r1>1:\n # alpha = 1/(2*r1)\n # else:\n # alpha = 1\n alpha = 0.5\n beta = 1.0\n\n r0 = r1\n\n # No damping if error within one order of magnitude\n # of tolerance\n if r1 < 10*self.tolerance:\n alpha, beta = 1, 1\n\n dy0 = alpha*beta*np.linalg.solve(J,-res)\n\n #dy0 = -alpha*beta*np.dot(np.transpose(np.dot(np.linalg.inv(np.dot(J,np.transpose(J))),J)),res)\n\n # dy0 = np.linalg.solve(J,-res)\n # if abs(r1 - 0.110277711594) < 1e-4:\n # from beluga.utils import keyboard\n\n # Apply corrections to states and parameters (if any)\n\n if nParams > 0:\n dp = dy0[(nOdes*self.number_arcs):]\n dy0 = dy0[:(nOdes*self.number_arcs)]\n paramGuess = paramGuess + dp\n for i in range(self.number_arcs):\n y0g[i] = y0g[i] + dy0[(i*nOdes):((i+1)*nOdes)]\n else:\n y0g = y0g + dy0\n iter = iter+1\n except Exception as e:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n logging.warn(fname+'('+str(exc_tb.tb_lineno)+'): '+str(exc_type))\n\n # Now program stitches together solution from the multiple arcs instead of propagating from beginning.\n # This is important for sensitive problems because they can diverge from the actual solution if propagated in single arc.\n # Therefore, the initial guess for next step and data for plotting are much better.\n if converged:\n # x1, y1 = ode45.solve(deriv_func, [x[0],x[-1]], y0g[0], paramGuess, aux, abstol=1e-6, reltol=1e-6)\n # sol = Solution(x1,y1.T,paramGuess)\n x1 = tset[0]\n y1 = yySTM[0][:, :nOdes]\n for i in range(1, self.number_arcs):\n x1 = np.hstack((x1, tset[i][1:]))\n y1 = np.vstack((y1, (yySTM[i][1:, :nOdes])))\n sol = Solution(x1, y1.T, paramGuess)\n else:\n # Return initial guess if it failed to converge\n sol = solinit\n\n sol.converged = converged\n bvp.solution = sol\n sol.aux = aux\n\n if self.worker is None:\n ode45.closePool()\n return sol\n","sub_path":"beluga/bvpsol/algorithms/MultipleShooting.py","file_name":"MultipleShooting.py","file_ext":"py","file_size_in_byte":15856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"120887161","text":"import argparse\nimport json\nimport sys\n\n\nclass FilterCommand:\n @staticmethod\n def build_argparse(subparsers):\n filter_parser = subparsers.add_parser('filter', help='Manipulate category filters')\n filter_parser.set_defaults(func=lambda _: filter_parser.print_help())\n filter_subparsers = filter_parser.add_subparsers()\n\n filter_show_cmd: argparse.ArgumentParser = filter_subparsers.add_parser('get')\n filter_show_cmd.add_argument('--category', '-c', default='ALL', help='Category id. Default is all categories')\n filter_show_cmd.add_argument('--output', '-o', default='-', help='Output file. use - to output to the standard '\n 'output (the default)')\n filter_show_cmd.set_defaults(func=lambda ctx: FilterCommand.get(ctx))\n\n @staticmethod\n def get(ctx):\n output_path = ctx.ns.output\n cat_id = ctx.ns.category\n\n def to_dict(o):\n return o.to_dict()\n\n try:\n if output_path == '-':\n output = sys.stdout\n else:\n output = open(output_path, 'wt')\n\n cat_ids = [cat_id] if cat_id != 'ALL' else [c.category_id for c in ctx.criteria_dao.all()]\n\n result = {cat_id: ctx.carscanner_allegro.get_filters(cat_id) for cat_id in cat_ids}\n json.dump(result, output, default=to_dict, indent=2)\n finally:\n if output and output is not sys.stdout:\n output.close()\n","sub_path":"src/carscanner/cli/cmd_filter.py","file_name":"cmd_filter.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"297033469","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('listing', views.QuizListingAPI.as_view()),\n path('questions', views.QuestionListingAPI.as_view()),\n path('initiate', views.InitiateTestAPI.as_view()),\n path('save', views.SaveUserTestInformationAPI.as_view()),\n path('results', views.UserTestResultsAPI.as_view())\n\n]\n","sub_path":"api/v1/quiz/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"505003447","text":"from core.helpers import all, plural, json_encode\nfrom core.logger import Logger\nfrom core.trakt import Trakt\nfrom sync.sync_base import SyncBase\n\n\nlog = Logger('sync.push')\n\n\nclass Base(SyncBase):\n task = 'push'\n\n def watch(self, key, p_items, t_item, include_identifier=True):\n if type(p_items) is not list:\n p_items = [p_items]\n\n # Ignore if trakt movie is already watched\n if t_item and t_item.is_watched:\n return True\n\n # Ignore if none of the plex items are watched\n if all([not x.seen for x in p_items]):\n return True\n\n # TODO should we instead pick the best result, instead of just the first?\n self.store('watched', self.plex.to_trakt(key, p_items[0], include_identifier))\n\n def rate(self, key, p_items, t_item, artifact='ratings'):\n if type(p_items) is not list:\n p_items = [p_items]\n\n # Filter by rated plex items\n p_items = [x for x in p_items if x.user_rating is not None]\n\n # Ignore if none of the plex items have a rating attached\n if not p_items:\n return True\n\n # TODO should this be handled differently when there are multiple ratings?\n p_item = p_items[0]\n\n # Ignore if rating is already on trakt\n if t_item and t_item.rating_advanced == p_item.user_rating:\n return True\n\n data = self.plex.to_trakt(key, p_item)\n\n data.update({\n 'rating': p_item.user_rating\n })\n\n self.store(artifact, data)\n return True\n\n def collect(self, key, p_items, t_item, include_identifier=True):\n if type(p_items) is not list:\n p_items = [p_items]\n\n # Ignore if trakt movie is already collected\n if t_item and t_item.is_collected:\n return True\n\n self.store('collected', self.plex.to_trakt(key, p_items[0], include_identifier))\n return True\n\n @staticmethod\n def log_artifact(action, label, count, level='info'):\n message = '(%s) %s %s item%s' % (\n action, label, count,\n plural(count)\n )\n\n if level == 'info':\n return log.info(message)\n elif level == 'warn':\n return log.warn(message)\n\n raise ValueError('Unknown level specified')\n\n def send(self, action, data):\n response = Trakt.request(action, data, authenticate=True)\n\n # Log successful items\n if 'rated' in response:\n rated = response.get('rated')\n unrated = response.get('unrated')\n\n log.info(\n '(%s) Rated %s item%s and un-rated %s item%s',\n action,\n rated, plural(rated),\n unrated, plural(unrated)\n )\n elif 'message' in response:\n log.info('(%s) %s', action, response['message'])\n else:\n self.log_artifact(action, 'Inserted', response.get('inserted'))\n\n # Log skipped items, if there were any\n skipped = response.get('skipped', 0)\n\n if skipped > 0:\n self.log_artifact(action, 'Skipped', skipped, level='warn')\n\n def send_artifact(self, action, key, artifact):\n items = self.artifacts.get(artifact)\n if not items:\n return\n\n return self.send(action, {key: items})\n\n\nclass Episode(Base):\n key = 'episode'\n auto_run = False\n\n def run(self, p_episodes, t_episodes, artifacts=None):\n self.reset(artifacts)\n\n enabled_funcs = self.get_enabled_functions()\n\n for key, p_episode in p_episodes.items():\n t_episode = t_episodes.get(key)\n\n # TODO check result\n self.trigger(enabled_funcs, key=key, p_episode=p_episode, t_episode=t_episode)\n\n return True\n\n def run_watched(self, key, p_episode, t_episode):\n return self.watch(key, p_episode, t_episode, include_identifier=False)\n\n def run_ratings(self, key, p_episode, t_episode):\n return self.parent.rate(key, p_episode, t_episode, 'episode_ratings')\n\n def run_collected(self, key, p_episode, t_episode):\n return self.collect(key, p_episode, t_episode, include_identifier=False)\n\n\nclass Show(Base):\n key = 'show'\n children = [Episode]\n\n def run(self, section=None, artifacts=None):\n self.reset(artifacts)\n self.check_stopping()\n\n enabled_funcs = self.get_enabled_functions()\n if not enabled_funcs:\n log.info('There are no functions enabled, skipping push.show')\n return True\n\n p_shows = self.plex.library('show', section)\n if not p_shows:\n # No items found, no need to continue\n return True\n\n # Fetch library, and only get ratings and collection if enabled\n t_shows, t_shows_table = self.trakt.merged(\n 'shows',\n ratings='ratings' in enabled_funcs,\n collected='collected' in enabled_funcs\n )\n\n if t_shows_table is None:\n log.warn('Unable to construct merged library from trakt')\n return False\n\n self.start(len(p_shows))\n\n for x, (key, p_show) in enumerate(p_shows.items()):\n self.check_stopping()\n self.progress(x + 1)\n\n t_show = t_shows_table.get(key)\n\n log.debug('Processing \"%s\" [%s]', p_show[0].title if p_show else None, key)\n\n # TODO check result\n self.trigger(enabled_funcs, key=key, p_shows=p_show, t_show=t_show)\n\n for p_show in p_show:\n self.child('episode').run(\n p_episodes=self.plex.episodes(p_show.rating_key, p_show),\n t_episodes=t_show.episodes if t_show else {},\n artifacts=artifacts\n )\n\n show = self.plex.to_trakt(key, p_show)\n\n self.store_episodes('collected', show)\n self.store_episodes('watched', show)\n\n self.finish()\n self.check_stopping()\n\n #\n # Push changes to trakt\n #\n for show in self.retrieve('collected'):\n self.send('show/episode/library', show)\n\n for show in self.retrieve('watched'):\n self.send('show/episode/seen', show)\n\n self.send_artifact('rate/shows', 'shows', 'ratings')\n self.send_artifact('rate/episodes', 'episodes', 'episode_ratings')\n\n for show in self.retrieve('missing.shows'):\n self.send('show/unlibrary', show)\n\n for show in self.retrieve('missing.episodes'):\n self.send('show/episode/unlibrary', show)\n\n Data.Save('last_artifacts.show.json', json_encode(self.artifacts))\n\n log.info('Finished pushing shows to trakt')\n return True\n\n def run_ratings(self, key, p_shows, t_show):\n return self.rate(key, p_shows, t_show)\n\n\nclass Movie(Base):\n key = 'movie'\n\n def run(self, section=None, artifacts=None):\n self.reset(artifacts)\n self.check_stopping()\n\n enabled_funcs = self.get_enabled_functions()\n if not enabled_funcs:\n log.info('There are no functions enabled, skipping push.movie')\n return True\n\n p_movies = self.plex.library('movie', section)\n if not p_movies:\n # No items found, no need to continue\n return True\n\n # Fetch library, and only get ratings and collection if enabled\n t_movies, t_movies_table = self.trakt.merged(\n 'movies',\n ratings='ratings' in enabled_funcs,\n collected='collected' in enabled_funcs\n )\n\n if t_movies_table is None:\n log.warn('Unable to construct merged library from trakt')\n return False\n\n self.start(len(p_movies))\n\n for x, (key, p_movie) in enumerate(p_movies.items()):\n self.check_stopping()\n self.progress(x + 1)\n\n t_movie = t_movies_table.get(key)\n\n log.debug('Processing \"%s\" [%s]', p_movie[0].title if p_movie else None, key)\n\n # TODO check result\n self.trigger(enabled_funcs, key=key, p_movies=p_movie, t_movie=t_movie)\n\n self.finish()\n self.check_stopping()\n\n #\n # Push changes to trakt\n #\n self.send_artifact('movie/seen', 'movies', 'watched')\n self.send_artifact('rate/movies', 'movies', 'ratings')\n self.send_artifact('movie/library', 'movies', 'collected')\n self.send_artifact('movie/unlibrary', 'movies', 'missing.movies')\n\n Data.Save('last_artifacts.movie.json', json_encode(self.artifacts))\n\n log.info('Finished pushing movies to trakt')\n return True\n\n def run_watched(self, key, p_movies, t_movie):\n return self.watch(key, p_movies, t_movie)\n\n def run_ratings(self, key, p_movies, t_movie):\n return self.rate(key, p_movies, t_movie)\n\n def run_collected(self, key, p_movies, t_movie):\n return self.collect(key, p_movies, t_movie)\n\n\nclass Push(Base):\n key = 'push'\n title = 'Push'\n children = [Show, Movie]\n threaded = True\n\n def run(self, *args, **kwargs):\n success = super(Push, self).run(*args, **kwargs)\n\n if kwargs.get('section') is None:\n # Update the status for each section\n for (_, k, _) in self.plex.sections():\n self.update_status(True, start_time=self.start_time, section=k)\n\n return success\n","sub_path":"Trakttv.bundle/Contents/Code/sync/push.py","file_name":"push.py","file_ext":"py","file_size_in_byte":9389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"313494849","text":"'''\r\nCreated on Aug 17, 2017\r\n\r\n@author: adave\r\n'''\r\n\r\nimport sys,os,json,subprocess\r\nfrom PySide import QtCore \r\nfrom PySide import QtGui\r\nimport shiboken\r\nimport maya._OpenMayaUI as oui\r\nimport maya.cmds as cmds\r\nimport Red9.startup.setup as sDir\r\n\r\n\r\ndef getMayaWindow():\r\n pointer = oui.MQtUtil_mainWindow()\r\n return shiboken.wrapInstance(long(pointer),QtGui.QWidget)\r\n\r\nmayaParent = getMayaWindow()\r\n\r\n\r\n\r\n\r\ndef ikGripUpdate():\r\n sel = cmds.ls(sl=1)\r\n ikGripUtil(sel).ikGripUpdateDoit()\r\n\r\nclass ikGripUtil:\r\n def __init__(self,ctrl):\r\n self.ctrl = ctrl \r\n \r\n def error(self):\r\n QtGui.QMessageBox.critical(mayaParent,\"Error\",\"Select IKGrip and Run this Script\")\r\n \r\n def ikGripUpdateDoit(self):\r\n if len(self.ctrl) != 1:\r\n self.error()\r\n else:\r\n ikGripCtrl = 'IkGripTarget_Ctr'\r\n rootCtrl = 'root_Ctr'\r\n name = self.ctrl[0].split(':')\r\n if name[1] != ikGripCtrl:\r\n self.error()\r\n else:\r\n rootCtrl = (name[0]+':'+rootCtrl)\r\n info = self.getInfo(rootCtrl) \r\n tempFile = (cmds.file(q=1,sn=1)).replace('.ma','.py')\r\n ikGripValue = self.getikGripValue(rootCtrl)\r\n \r\n tempSaFile = self.writeTempFile(tempFile,info,ikGripValue)\r\n \r\n standalone().subProcess(tempSaFile) \r\n os.remove(tempSaFile)\r\n\r\n text = \"IKgrip is updated \\n\"\r\n text += \"submit your checked out weapon files\\n\"\r\n text += \"after Testing in game\"\r\n msgBox = QtGui.QMessageBox.information(mayaParent,\"Information\",text)\r\n\r\n \r\n \r\n\r\n \r\n def getInfo(self,rootCtrl):\r\n info = []\r\n nodeType = 'network'\r\n mTag = cmds.listConnections(rootCtrl,d=False, s=True ,et=1, t = nodeType)[0]\r\n eTag = cmds.listConnections( mTag, d=True, s=False,et=1, t= nodeType)[0]\r\n data = json.loads(cmds.getAttr(eTag+'.assetData'))\r\n CHR = cmds.getAttr(eTag+'.skeletonAlias')\r\n \r\n info.append(data['file_path'])\r\n info.append(CHR)\r\n\r\n return info\r\n \r\n \r\n def getikGripValue(self,rootCtrl):\r\n cmds.select(cl=1)\r\n rootLoc = cmds.spaceLocator( p=(0, 0, 0),n=\"ikGripRoot_loc\")\r\n ikGripLoc = cmds.spaceLocator( p=(0, 0, 0),n=\"ikGrip_loc\")\r\n ikGripWorldloc = cmds.spaceLocator( p=(0, 0, 0),n=\"ikGripWorld_loc\")\r\n cmds.parent(ikGripLoc[0],rootLoc[0])\r\n rootCon = ApplyConstrain(rootCtrl,rootLoc[0]).pointOriCon(0)\r\n ikGripCon = ApplyConstrain(self.ctrl,ikGripLoc[0]).pointOriCon(0)\r\n cmds.delete(rootCon[0],rootCon[1],ikGripCon[0],ikGripCon[1])\r\n con = ApplyConstrain(ikGripWorldloc[0],rootLoc[0]).pointCon(0)\r\n cmds.delete(con[0])\r\n cmds.parent(ikGripLoc,w=1)\r\n tVal = cmds.getAttr(ikGripLoc[0]+'.translate')\r\n rVal = cmds.getAttr(ikGripLoc[0]+'.rotate')\r\n ikGripValue = [tVal[0][0],tVal[0][1],tVal[0][2],rVal[0][0],rVal[0][1],rVal[0][2]]\r\n cmds.delete(rootLoc,ikGripLoc,ikGripWorldloc)\r\n cmds.select(self.ctrl)\r\n return ikGripValue\r\n \r\n def writeTempFile(self,tempFile,info,ikGripValue):\r\n \r\n baseR9ScriptPath = sDir.red9ModulePath()\r\n ikGscript = os.path.abspath(os.path.join(baseR9ScriptPath,\"../cig/anim/ikGripStandalone.py\")) \r\n dumpFile = (open(ikGscript,'r'))\r\n text = dumpFile.readlines()\r\n dumpFile.close()\r\n text.insert(12,'scriptFile = \"%s\"\\n' % (tempFile))\r\n text.insert(13,'basePath = \"%s\"\\n' % info[0])\r\n text.insert(14,'ikGripCtrl = \"IkGripTarget_Ctr\"\\n')\r\n text.insert(15,'CHR = \"%s\"\\n' % info[1])\r\n text.insert(16,'ikGripCtrlValue = %s \\n' % ikGripValue)\r\n fileW = open(tempFile,'w') \r\n fileW.writelines(text) \r\n fileW.close()\r\n return tempFile\r\n\r\n \r\nclass standalone: \r\n def __init__(self):\r\n self.mayapy = (sys.executable).replace('maya','mayapy') \r\n \r\n def subProcess(self,tempScriptFile):\r\n subprocess.Popen([self.mayapy,tempScriptFile]).communicate()\r\n \r\n \r\n\r\n\r\n\r\nclass ApplyConstrain:\r\n \r\n def __init__(self,source,target=None):\r\n self.source = source\r\n self.target = target \r\n \r\n def pointCon(self,moV):\r\n self.con = cmds.pointConstraint((self.source),(self.target),mo = moV)\r\n return self.con\r\n \r\n def orientCon(self,moV):\r\n self.con = cmds.orientConstraint((self.source),(self.target),mo= moV)\r\n return self.con \r\n\r\n def pointOriCon(self,moV): \r\n self.con = [self.pointCon(moV),self.orientCon(moV)] \r\n return self.con \r\n\r\n\r\n \r\n\r\n","sub_path":"ikGripUpdate.py","file_name":"ikGripUpdate.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"358163760","text":"#from tensorflow.examples.tutorials.mnist import input_data\n#mnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)\n\nimport tensorflow as tf\nfrom sklearn import datasets\n\nimport numpy as np \nimport pandas as pd\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import preprocessing\n\n\ndef singleLayer_perceptron(x, h_1 , h_out, b_1 , b_out):\n # Hidden layer with RELU activation\n layer_1 = tf.add(tf.matmul(x, h_1), b_1 )\n layer_1 = tf.nn.relu(layer_1)\n # Hidden layer with RELU activation\n #layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])\n #layer_2 = tf.nn.relu(layer_2)\n\n #layer_3 = tf.add(tf.matmul(layer_2, weights['h3']), biases['b3'])\n #layer_3 = tf.nn.relu(layer_3)\n \n print(\"Output layer with linear activation\")\n out_layer = tf.matmul(layer_1, h_out) + b_out\n return out_layer\n\n\ndef prepData() :\n enc = OneHotEncoder()\n\n olivetti = datasets.fetch_olivetti_faces()\n X , y = olivetti.data, olivetti.target\n\n nb_classes = 40\n targets = np.array(y).reshape(-1)\n y_ = one_hot_targets = np.eye(nb_classes)[targets]\n\n X_train, X_test , Y_train, Y_test = train_test_split(X, y_, test_size=0.10, random_state=42)\n\n return X_train , Y_train , X_test, Y_test\n\n\n\nif __name__ == \"__main__\":\n\n\n x_train , y_train , x_test , y_test = prepData()\n\n x_train = pd.DataFrame(x_train)\n y_train = pd.DataFrame(y_train)\n x_test = pd.DataFrame(x_test)\n y_test = pd.DataFrame(y_test)\n\n x_ = x_train.values\n \n min_max_scaler = preprocessing.MinMaxScaler()\n \n x_scaled = min_max_scaler.fit_transform(x_)\n x_train = pd.DataFrame(x_scaled)\n \n \n x_ = x_test.values\n \n min_max_scaler = preprocessing.MinMaxScaler() \n x_scaled = min_max_scaler.fit_transform(x_)\n x_test = pd.DataFrame(x_scaled)\n \n \n \n\n learning_rate = 0.01\n training_epochs = 2000\n beta = 0.01\n #batch_size = 20\n #display_step = 1\n\n\n print(\"x train shape :\",x_train.shape, \" Y train shape :\",y_train.shape)\n print(\"x test shape :\",x_test.shape, \"\",\" Y test shape :\",y_test.shape)\n # Network Parameters\n n_hidden_1 = 256 # 1st layer number of features\n #n_hidden_2 = 256 # 2nd layer number of features\n #n_hidden_3 = 256\n n_input = x_train.shape[1] # MNIST data input (img shape: 28*28)\n n_classes = y_test.shape[1] # MNIST total classes (0-9 digits)\n\n\n print(\"n_inputs\",n_input)\n print(\"n_classes\",n_classes)\n\n # Parameters\n\n # tf Graph input\n \n #x_ = tf.placeholder(\"float\", [None, n_input])\n #y_ = tf.placeholder(\"float\", [None, n_classes])\n\n x_=tf.placeholder(tf.float32,shape=[None,n_input] , name='X')\n y_=tf.placeholder(tf.float32,shape=[None, n_classes] , name='Y')\n\n\n\n # Create model\n\n # Store layers weight & bias\n \"\"\"\n weights = {\n 'h1': tf.Variable(tf.random_uniform([n_input, n_hidden_1]), name=\"weight_h1\"),\n #'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),\n #'h3': tf.Variable(tf.random_normal([n_hidden_2, n_hidden_3])), \n 'out': tf.Variable(tf.random_uniform([n_hidden_1, n_classes]), name=\"weight_out\")\n }\n biases = {\n 'b1': tf.Variable(tf.random_uniform([n_hidden_1]) , name = \"biases_b1\"),\n #'b2': tf.Variable(tf.random_normal([n_hidden_2])),\n #'b3': tf.Variable(tf.random_normal([n_hidden_3])),\n 'out': tf.Variable(tf.random_uniform([n_classes]) , name = \"biases_out\")\n }\n \"\"\"\n weight_h1 = tf.Variable(tf.random_uniform([n_input, n_hidden_1]), name=\"weight_h1\")\n weight_out = tf.Variable(tf.random_uniform([n_hidden_1, n_classes]), name=\"weight_out\")\n\n biases_b1 = tf.Variable(tf.random_uniform([n_hidden_1]) , name = \"biases_b1\")\n biases_out = tf.Variable(tf.random_uniform([n_classes]) , name = \"biases_out\")\n\n # Construct model\n pred = singleLayer_perceptron(x_, weight_h1 , weight_out , biases_b1 , biases_out)\n print(\"single layer Model made \")\n\n # Define loss and optimizer\n cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=pred, labels=y_) + 0.01*tf.nn.l2_loss(weight_h1))\n\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n\n # Initializing the variables\n init = tf.global_variables_initializer()\n\n\n\n\n\n correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y_, 1))\n # Calculate accuracy\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n \n\n #X_ = pd.DataFrame(x_train)\n #Y_ = pd.DataFrame(x_test)\n #batch_counter = 0\n # Launch the graph\n\n tf.summary.scalar(\"Accuracy:\", accuracy)\n tf.summary.scalar(\"Entropy loss:\",cost)\n\n \n\n tf.summary.histogram(\"weights_1\", weight_h1)\n tf.summary.histogram(\"weights_out\",weight_out)\n\n tf.summary.histogram(\"biases_1\", biases_b1)\n tf.summary.histogram(\"biases_out\",biases_out)\n \n image_shaped_input = tf.reshape(x_, [-1, 64, 64, 1])\n tf.summary.image('input', image_shaped_input, 40)\n\n merged = tf.summary.merge_all()\n\n with tf.Session() as sess:\n sess.run(init)\n\n writer = tf.summary.FileWriter('./graphs', sess.graph)\n \n # Training cycle\n print(\"training epochs \",training_epochs)\n \n for epoch in range(training_epochs):\n #avg_cost = 0.\n #total_batch = int(x_train.shape[0]/batch_size)\n #print(\"total batches \",total_batch) \n # Loop over all batches\n #batch_counter = 0\n #for i in range(total_batch):\n \n #batch_x = x_train[batch_counter:batch_counter+batch_size,:]\n #batch_y = y_train[batch_counter:batch_counter+batch_size,:]\n #print(\"this is batch X \",batch_x)\n #print()\n #batch_x, batch_y = mnist.train.next_batch(batch_size)\n # Run optimization op (backprop) and cost op (to get loss value)\n #print(\"batch_x\",batch_x.shape)\n #print(\"batch_y\",batch_y.shape)\n _, c , sury= sess.run([optimizer, cost, merged], feed_dict={x_: x_train, y_:[t for t in y_train.as_matrix()] })\n\n writer.add_summary(sury,epoch)\n \n \n #batch_counter += batch_size\n # Compute average loss\n #avg_cost += c / total_batch\n # Display logs per epoch step\n #if epoch % display_step == 0:\n if epoch%100==0 :\n print(c , \" \", _)\n \n print(\"Test accuracy :\",sess.run(accuracy,feed_dict={x_: x_test, y_:[t for t in y_test.as_matrix()]}))\n \n #print(\"Epoch:\", '%04d' % (epoch+1), \"cost=\",\"{:.9f}\".format(c))\n print(\"Optimization Finished!\")\n\n # Test model\n \n\n","sub_path":"Week 10/Q_1_NeuralNetword.py","file_name":"Q_1_NeuralNetword.py","file_ext":"py","file_size_in_byte":6839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"571782897","text":"from collections import defaultdict\nimport json, math, ast\n\nclass Contexts ( object ):\n \"\"\"\n param text_tokenized: Text in list format.\n param vocabulary: Text's vocabulary.\n \"\"\"\n def __init__ ( self, text_tokenized, vocabulary ):\n self.text_tokenized = text_tokenized\n self.vocabulary = vocabulary\n\n def load_contexts ( self, doc_name = \"contexts_example\" ):\n \"\"\"\n Load a previously saved context dictionary created by the function 'save_all_contexts'.\n\n param doc_name: Dictionary of contexts name without extension '.dic'.\n \"\"\"\n try:\n with ( open ( \"./saved_contexts/\" + doc_name + \".dic\", \"r\" ) ) as f:\n contexts_dict = f.read ( )\n contexts_dict = ast.literal_eval ( contexts_dict )\n return contexts_dict\n except:\n print ( \"File doesn't exist.\" )\n return None\n\n def find_contexts ( self, target, left_margin = 4, right_margin = 4 ):\n \"\"\"\n Find the context of a target token in a window margin of 8 i.e 4 tokens to\n the left and 4 tokens to the right of the text (text_tokenized) where the target appears.\n\n param target: Token to find its contexts.\n param right_margin: Right tokens of the text that will be the target contexts.\n param left_margin: Left tokens of the text that will be the target contexts.\n \"\"\"\n left, right = [ ], [ ]\n print ( \"Displaying matches:\\n\" )\n for i in range ( ( len ( self.text_tokenized ) ) ):\n if ( self.text_tokenized [ i ] == target ):\n while ( i - left_margin < 0 ):\n left_margin += 1\n right = \" \".join ( self.text_tokenized [ i + 1 : right_margin + i + 1 ] )\n left = \" \".join ( self.text_tokenized [ i - left_margin : i ] )\n print ( \"{0:} {1:} {2:}\".format ( left, target, right ) )\n\n # Prototype only: This method will be slow to run.\n def save_all_contexts ( self, doc_name = \"contexts_example\", left_margin = 4, right_margin = 4 ):\n \"\"\"\n Find and save all the context of a vocabulary in a text tokenized.\n\n param doc_name: Name of the document which we are saving the contexts.\n param right_margin: Right tokens of the text that will be the target contexts.\n param left_margin: Left tokens of the text that will be the target contexts.\n \"\"\"\n left, right, contexts_dict = [ ], [ ], defaultdict ( list )\n for target in self.vocabulary:\n for i in range ( ( len ( self.text_tokenized ) ) ):\n if ( self.text_tokenized [ i ] == target ):\n #while ( i - left_margin < 0 ):\n # left_margin += 1\n right = self.text_tokenized [ i + 1 : right_margin + i + 1 ]\n left = self.text_tokenized [ i - left_margin : i ]\n contexts_dict [ target ].append ( left + right )\n # Stores the contexts dictionary in json format.\n try:\n with ( open ( \"./saved_contexts/\" + doc_name + \".dic\", \"w\" ) ) as f:\n json.dump ( contexts_dict, f )\n print ( \"\\nContexts succesfully saved.\" )\n except:\n print ( \"\\nContexts cannot be saved.\" )\n\n\nclass Similar ( object ):\n \"\"\"\n param contexts_dict: Dictionary of contexts which each key is a token of the vocabulary\n and each element is a list of lists that stores the contexts of that token.\n param vocabulary: Text's vocabulary.\n \"\"\"\n def __init__ ( self, contexts_dict, vocabulary ):\n self.contexts_dict = contexts_dict\n self.vocabulary = vocabulary\n\n def relative_frequency_vectors ( self ):\n \"\"\"\n Use the vector space model on bag-of-words context data to model of the context a word\n for paradigmatic relation discovery. The method represents a pseudo-document or context\n of each vocabulary token as one frequency vector from d1, d2, d3,..., dn (where n it's\n the vocabulary length) and then we can measure the similarity of these vektors. By\n viewing context in the vector space model, we convert the proble of paradigmatic relation\n discovery into the problem of computing the vectors and their similarity. Now, each element\n of the vector it's the counting of how many times the target token appears in all the\n contexts of every vocabulary element.\n \"\"\"\n counter, freq_vectors = 0, defaultdict ( list )\n for target in self.vocabulary:\n for key, contexts in self.contexts_dict.items ( ):\n for i in range ( len ( contexts ) ):\n if ( target in contexts [ i ] ):\n counter += contexts [ i ].count ( target )\n freq_vectors [ target ].append ( counter )\n counter = 0\n return freq_vectors\n\n # Prototype only: This method isn't very exact.\n def dot_product ( self, u, v ):\n \"\"\"\n Calculate the dot product of two vectors.\n\n param u: Vector 1.\n param v: Vector 2.\n \"\"\"\n # sum_u, sum_v = sum ( u ), sum ( v )\n dot_product = 0\n for i in range ( len ( u ) ):\n dot_product += ( u [ i ] ) * ( v [ i ] )\n return dot_product\n\n def vectors_angle ( self, u, v ):\n \"\"\"\n Calculate angle between two vectors: cos(Θ) = u·v / ||u||·||v||\n\n param u: Vector 1.\n param v: Vector 2.\n \"\"\"\n norm_u = math.sqrt ( sum ( list ( map ( lambda x : x**2, u ) ) ) )\n norm_v = math.sqrt ( sum ( list ( map ( lambda x : x**2, v ) ) ) )\n product_norms = norm_u * norm_v\n if ( product_norms != 0 ):\n return self.dot_product ( u, v ) / product_norms\n return 0\n\n\nclass InformationRetrieval ( object ):\n \"\"\"\n param documents: List of documents that will be analysed.\n param contexts_dict: Dictionary of contexts which each key is a token of the vocabulary\n and each element is a list of lists that stores the contexts of that token.\n param vocabulary: Text's vocabulary.\n \"\"\"\n def __init__ ( self, documents = [ [ ] ], contexts_dict = { }, vocabulary = [ ] ):\n self.documents = documents\n self.contexts_dict = contexts_dict\n self.vocabulary = vocabulary\n self.lenght_vocabulary = len ( self.vocabulary )\n\n def idf_weighting ( self ):\n \"\"\"\n For every token in the vocabulary, the method will 'penalize' popular terms and 'reward' the\n rare ones, the function that will allow this is defined by: IDF(W)=log((M+1)/k). Where 'M' it's\n the lenght of the vocabulary or corpus and 'k' the number of documents where the token 'W' appears.\n This measure it's called Inverse Document Frequency.\n \"\"\"\n idf = defaultdict ( float )\n print ( \"\\nCalculaing Inverse Document Frequency...\" )\n for target in self.vocabulary:\n idf_counter = 0\n for document in self.documents:\n if ( target in document ):\n idf_counter += 1\n idf [ target ] = math.log ( ( self.lenght_vocabulary + 1 ) / idf_counter, 2 )\n return idf\n\n def tf_idf ( self ):\n \"\"\"\n The Term Frequency it's defined by the followinf funcion: TF(w,d)=log(1 + x). Where 'w' it's\n a target word or token, 'd' references to a contexts of another token, and 'x' it's the number of\n counts where 'w' appears in 'd' (x=c(w,d)). The relation between IDF and TF is a numerical statistic\n that is intended to reflect how important a word is in a document or a corpus. This method calculate\n this 'numbers' by making the product between TF and IDF.\n \"\"\"\n idf, tf_idf = self.idf_weighting ( ), [ ]\n for target in self.vocabulary:\n tf_counter = 0\n for document in self.documents:\n if ( target in document ):\n tf_counter += document.count ( target )\n tf_idf.append ( ( target, math.log ( tf_counter + 1, 2 ) * idf [ target ] ) )\n tf_idf.sort ( key = lambda x : x [ 1 ] )\n return tf_idf\n\n def contexts_idf_weighting ( self ):\n \"\"\"\n Same as the method 'idf_weighting' only that this method it's focused only in contexts inside a\n document, not in a set of documents. For a greater analysis use 'idf_weighting' method.\n \"\"\"\n idf = defaultdict ( float )\n print ( \"\\nCalculaing Inverse Document Frequency...\" )\n for target in self.vocabulary:\n idf_counter = 0\n for key, contexts in self.contexts_dict.items ( ):\n for context in contexts:\n if ( target in context ):\n idf_counter += 1\n idf [ target ] = math.log ( ( self.lenght_vocabulary + 1 ) / idf_counter, 2 )\n return idf\n\n def context_tf_idf ( self ):\n \"\"\"\n Same as the method 'tf_idf' only that this method it's focused only in contexts inside a document,\n not in a set of documents. For a greater analysis use 'tf_idf' method.\n \"\"\"\n tf_idf, idf = defaultdict ( list ), self.contexts_idf_weighting ( )\n for target in self.vocabulary:\n for key, contexts in self.contexts_dict.items ( ):\n tf_counter = 0\n for i in range ( len ( contexts ) ):\n if ( target in contexts [ i ] ):\n tf_counter += contexts [ i ].count ( target )\n tf_idf [ target ].append ( math.log ( tf_counter + 1, 2 ) * idf [ key ] )\n return tf_idf\n\n\ndef demo ( ):\n from RawText import ProcessRawText\n import codecs\n\n # //////////////////////////////////////////////////////////////\n # Load a document from the local Excelsior Corpus.\n # //////////////////////////////////////////////////////////////\n corpus_root = \"./excelsior_corpus/e960401.htm\"\n f = codecs.open ( corpus_root, \"r\", \"latin-1\" )\n plane_text = f.read ( )\n f.close ( )\n\n # //////////////////////////////////////////////////////////////\n # The ProcessRawText class will receive a raw text to work with,\n # the process below will normalize it and create the vocabulary.\n # //////////////////////////////////////////////////////////////\n prt = ProcessRawText ( plane_text = plane_text )\n prt.load_lemmatization_file ( \"es\", encode = \"latin-1\" )\n prt.load_stopwords_file ( \"es\", encode = \"utf-8\" )\n prt.html_parser ( )\n prt.remove_special_characters ( )\n text_tokenized = prt.tokenize_text ( )\n text_tokenized = prt.word_lemmatize ( text_tokenized )\n text_tokenized = prt.remove_stopwords ( text_tokenized )\n vocabulary = prt.create_vocabulary ( text_tokenized )\n\n # /////////////////////////////////////////////////////////////////////////\n # The Contexts class will find all the context of a target word, or we can\n # can find all the words context with the method \"save_all_contexts\", this\n # method will save in a file all the contexts as a dictionary and we can\n # load them later with \"load_contexts\" to save having to find them again.\n # ////////////////////////////////////////////////////////////////////////\n print ( \"\\nClass Contexts:\\n\" )\n paradigmatic_context = Contexts ( text_tokenized, vocabulary )\n print ( \"\\t- Function find_contexts:\\n\" )\n paradigmatic_context.find_contexts ( \"computadora\" )\n print ( \"\\n\\t- Function save_all_contexts:\" )\n paradigmatic_context.save_all_contexts ( \"contexts_e960401\" )\n print ( \"\\n\\t- Function load_contexts:\\n\" )\n contexts_dict = paradigmatic_context.load_contexts ( \"contexts_e960401\" )\n for i in range ( len ( contexts_dict [ \"computadora\" ] ) ):\n print ( \"{}\".format ( contexts_dict [ \"computadora\" ] [ i ] ) )\n\n # ////////////////////////////////////////////////////////////////////////////\n # The Similar class will provide the option to find the similar words by using\n # a bag-of-words model implemented in the function \"relative_frequency_vectors\"\n # This class also provide two mathematical functions: the dot-product and the\n # cosine similarity of two non-zero vectors. This last method will help us to\n # find the similarity between two words.\n # ////////////////////////////////////////////////////////////////////////////\n print ( \"\\nClass Similar:\\n\" )\n sim = Similar ( contexts_dict, vocabulary )\n print ( \"\\t- Function relative_frequency_vectors:\\n\" )\n # relative_freq_vectors = sim.relative_frequency_vectors ( )\n\n # //////////////////////////////////////////////////////////////////////////////////////////////////\n # The InformationRetrieval class will find the Term Frequency - Inverse Document Frequency (tf-idf)\n # value with the tf_idf method, this will express how relevant it's a word in a document or corpus.\n # Once we have this value for all the vocabulary tokens we can find the similarity between two words\n # words using the mathematical methods in the Similar class.\n # //////////////////////////////////////////////////////////////////////////////////////////////////\n print ( \"Class InformationRetrieval:\\n\" )\n ir = InformationRetrieval ( documents = [ text_tokenized ], contexts_dict = contexts_dict, vocabulary = vocabulary )\n print ( \"\\t- Function context_tf_idf:\" )\n tf_idf = ir.context_tf_idf ( )\n\n # /////////////////////////////////////////////////////////////////////////////\n # Find the similar words of 'computadora' using the cosine between two vectors.\n # /////////////////////////////////////////////////////////////////////////////\n target, similar = tf_idf [ \"computadora\" ], [ ]\n for token in vocabulary:\n angle = sim.vectors_angle ( target, tf_idf [ token ] )\n similar.append ( ( token, angle ) )\n # Sort the elements in the list 'similar', the highest value it's the most similar word to the target.\n similar.sort ( key = lambda x : x [ 1 ] )\n print ( \"\\n\\nSimilar words of '{}':\\n\".format ( \"computadora\" ) )\n for i in range ( len ( similar ) - 1, len ( similar ) - 40, -1 ):\n print ( similar [ i ] )\n\nif ( __name__ == \"__main__\" ):\n demo ( )\n\n__all__ = [ \"Contexts\",\n \"Similar\",\n \"InformationRetrieval\" ]\n","sub_path":"ParadigmaticRelation.py","file_name":"ParadigmaticRelation.py","file_ext":"py","file_size_in_byte":14372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"396180615","text":"\r\nfrom amadeus import Client, ResponseError\r\nimport csv\r\nimport os\r\n\r\n\r\n# AEROPUERTOS\r\n# [nombre, nombre detallado, relevancia, [latitud, longitud], [ciudad, país], [distancia, unidad]]\r\n# Lista1 = ['name','detailedName','relevance']\r\n# Lista2 = ['geoCode','address','distance']\r\n\r\ndef aLista(dic,tomados):\r\n \r\n claves = dic.keys()\r\n lista = []\r\n \r\n for caso in tomados:\r\n if caso in claves:\r\n valor = dic[caso]\r\n lista.append(valor)\r\n \r\n else:\r\n lista.append(False)\r\n \r\n return lista\r\n \r\n\r\ndef aero1(dic):\r\n \r\n claves = dic.keys()\r\n tomados = ['name','detailedName','relevance']\r\n lista = []\r\n \r\n for caso in tomados:\r\n if caso in claves:\r\n valor = dic[caso]\r\n lista.append(valor)\r\n \r\n else:\r\n lista.append(False)\r\n \r\n return lista\r\n \r\n \r\ndef aero2(dic):\r\n \r\n claves = dic.keys()\r\n tomados = ['geoCode','address','distance']\r\n lista = []\r\n \r\n for caso in tomados:\r\n if (caso == 'geoCode') and (caso in claves):\r\n nuevo = dic[caso]\r\n lista.append(aLista(nuevo,['latitude','longitude']))\r\n \r\n elif (caso == 'address') and (caso in claves):\r\n nuevo = dic[caso]\r\n lista.append(aLista(nuevo,['cityName','countryName']))\r\n \r\n elif (caso == 'distance') and (caso in claves):\r\n nuevo = dic[caso]\r\n lista.append(aLista(nuevo,['value','unit']))\r\n \r\n else:\r\n lista.append(False)\r\n \r\n return lista\r\n \r\n# LISTA AERO \r\ndef aero(dic):\r\n \r\n lista = aero1(dic) + aero2(dic)\r\n return lista \r\n\r\n\r\n# respuesta.data (Api)\r\ndef listado(respuesta):\r\n \r\n lista = []\r\n for dato in respuesta:\r\n aeropuerto = aero(dato)\r\n lista.append(aeropuerto)\r\n \r\n return lista\r\n\r\n\r\ndef orden(lista):\r\n \r\n listaOrden = []\r\n while (lista != []):\r\n menor = min(lista)\r\n listaOrden.append(menor)\r\n lista.remove(menor)\r\n \r\n return listaOrden\r\n\r\n\r\ndef aFloat(lista):\r\n \r\n nros = []\r\n for nro in lista:\r\n nuevoNro = float(nro)\r\n nros.append(nuevoNro)\r\n \r\n return nros\r\n\r\n\r\ndef distancia(lista,medida):\r\n \r\n listaAero = []\r\n listaNum = []\r\n for aeropuerto in lista:\r\n num = aeropuerto[5][0]\r\n if (float(num) < medida):\r\n listaAero.append(aeropuerto)\r\n listaNum.append(num)\r\n \r\n \r\n nueva = [listaAero,listaNum]\r\n return nueva\r\n \r\n \r\n\r\n# LISTA AERO ORDEN \r\ndef ordenListaAero(lista,medida):\r\n \r\n parLista = distancia(lista,medida)\r\n listaNueva = aFloat(parLista[1])\r\n ordenada = orden(listaNueva)\r\n aeros = parLista[0]\r\n \r\n listaAerosOrden = []\r\n for nro in ordenada:\r\n longitud = len(aeros)\r\n contador = 0\r\n while (contador < longitud):\r\n aeropuerto = aeros[contador]\r\n if float(aeropuerto[5][0]) == nro:\r\n listaAerosOrden.append(aeropuerto)\r\n aeros.remove(aeropuerto)\r\n contador = contador + longitud\r\n \r\n else:\r\n contador = contador + 1\r\n \r\n return listaAerosOrden\r\n \r\n\r\n \r\n# Extrae (latitud,longitud) de CSV \r\ndef latLong(ciudad):\r\n \r\n archivo = open('worldcities.csv',encoding='utf8')\r\n lectura = csv.reader(archivo)\r\n listaCiudad = list(lectura)\r\n \r\n for fila in listaCiudad:\r\n if fila[0] == ciudad:\r\n latitud = fila[2]\r\n longitud = fila[3]\r\n return [latitud,longitud]\r\n \r\n return []\r\n \r\n \r\n \r\n# MOSTRAR AERO\r\n# AEROPUERTOS\r\n# Estructura: [ nombre,nombreDetallado,relevancia,[latitud,longitud],[ciudad,país],[distancia,unidad] ] \r\n \r\n\r\ndef mostrarAero(lista):\r\n \r\n print('Nombre: {}'.format(lista[0]))\r\n print('Nombre detallado: {}'.format(lista[1]))\r\n print('Relevancia: {}'.format(lista[2]))\r\n print('Latitud: {}'.format(lista[3][0]))\r\n print('Longitud: {}'.format(lista[3][1]))\r\n print('Ciudad: {}'.format(lista[4][0]))\r\n print('País: {}'.format(lista[4][1]))\r\n print('Distancia a la coordenada: {}'.format(lista[5][0]))\r\n print('Unidad de distancia: {}'.format(lista[5][1]))\r\n\r\n\r\n\r\n","sub_path":"Aero.py","file_name":"Aero.py","file_ext":"py","file_size_in_byte":4370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"636614094","text":"#!/usr/bin/python\nimport psycopg2\nimport pandas as pd\nimport math\nimport random\n\n\"\"\"\nDatabase Connection\n\n\"\"\"\n\nHOST_NAME = 'localhost'\nUSER_NAME = 'tienvb'\nPASSWORD = 'abc13579'\nDATABASE = 'testkvp'\nPORT = 5432\n\n\nclass DatabaseConnection(object):\n\n def __init__(self, hostname, username, password, database, port=5432):\n self.hostname = hostname\n self.username = username\n self.password = password\n self.database = database\n self.port = port\n self.connection = None\n\n def get_connection(self):\n if self.connection is None:\n self.connection = psycopg2.connect(host=self.hostname, user=self.username,\n password=self.password, dbname=self.database, port=self.port)\n return self.connection\n\n\nclass DimensionDataBase(object):\n\n def __init__(self, conn):\n self.conn = conn\n\n @property\n def table_name(self): raise NotImplementedError\n\n @property\n def fields_name(self): raise NotImplementedError\n\n @property\n def fields_format(self): raise NotImplementedError\n\n def build_data(self, **kwargs): raise NotImplementedError\n\n def do_insert(self, **kwargs):\n if self.conn is None:\n print(\"Connection does not exist!\")\n return\n # get cursor\n args = self.build_data(**kwargs)\n # print(args)\n cursor = self.conn.cursor()\n # build query\n args_str = ','.join(cursor.mogrify(\"(%s)\" % self.fields_format, x).decode(\"utf-8\") for x in args)\n sql = \"INSERT INTO %s (%s) VALUES %s\" % (self.table_name, self.fields_name, args_str)\n # execute the INSERT statement\n cursor.execute(sql)\n # commit the changes to the database\n self.conn.commit()\n count = cursor.rowcount\n print(count, \"Record inserted successfully into %s table\" % self.table_name)\n # close communication with the database\n cursor.close()\n\n\n\"\"\" Date Dimension Data \"\"\"\n\n\nclass DateDimensionData(DimensionDataBase):\n table_name = \"date\"\n fields_name = \"date_key, year, month, day, quarter, week, day_of_week\"\n fields_format = \"%s,%s,%s,%s,%s,%s,%s\"\n\n def build_data(self, **kwargs):\n from_date = kwargs.get(\"from_date\")\n to_date = kwargs.get(\"to_date\")\n # list date\n list_date = pd.date_range(start=from_date, end=to_date)\n data = []\n for d in list_date:\n date_key = int(d.strftime(\"%Y%m%d\"))\n date_month = d.month\n date_day = d.day\n date_quarter = math.ceil(date_month / 3)\n date_year, date_week, date_dow = d.isocalendar()\n data.append(\n (date_key, date_year, date_month, date_day, date_quarter, date_week, date_dow)\n )\n return data\n\n\n\"\"\" Branch Dimension Data \"\"\"\n\n\nclass BranchDimensionData(DimensionDataBase):\n table_name = \"branch\"\n fields_name = \"branch_key, real_key\"\n fields_format = \"%s,%s\"\n\n def build_data(self, **kwargs):\n num_row = kwargs.get(\"num_row\")\n # list branch\n data = []\n for i in range(1, num_row + 1):\n data.append(\n (i, i)\n )\n return data\n\n\n\"\"\" Product Dimension Data \"\"\"\n\n\nclass ProductDimensionData(BranchDimensionData):\n table_name = \"product\"\n fields_name = \"product_key, real_key\"\n\n\n\"\"\" Customer Dimension Data \"\"\"\n\n\nclass CustomerDimensionData(BranchDimensionData):\n table_name = \"customer\"\n fields_name = \"customer_key, real_key\"\n\n\n\"\"\" Invoice Dimension Data \"\"\"\n\n\nclass InvoiceDimensionData(BranchDimensionData):\n table_name = \"invoice\"\n fields_name = \"invoice_key, real_key\"\n\n\n\"\"\" Industry Dimension Data \"\"\"\n\n\nclass IndustryDimensionData(DimensionDataBase):\n table_name = \"industry\"\n fields_name = \"industry_key, name\"\n fields_format = \"%s,%s\"\n\n def build_data(self, **kwargs):\n num_row = kwargs.get(\"num_row\")\n # list branch\n data = []\n for i in range(1, num_row + 1):\n data.append(\n (i, \"Industry %s\" % i)\n )\n return data\n\n\n\"\"\" Retailer Dimension Data \"\"\"\n\n\nclass RetailerDimensionData(DimensionDataBase):\n table_name = \"retailer\"\n fields_name = \"retailer_key, real_key, contract_type, expiry_date_key\"\n fields_format = \"%s,%s,%s,%s\"\n\n def __init__(self, conn):\n super(RetailerDimensionData, self).__init__(conn=conn)\n self.date_keys = None\n\n def build_dates(self):\n list_date = pd.date_range(start=\"2018-06-01\", end=\"2022-12-31\")\n date_keys = []\n for d in list_date:\n date_key = int(d.strftime(\"%Y%m%d\"))\n date_keys.append(date_key)\n self.date_keys = date_keys\n\n def get_random_date(self):\n if self.date_keys is None:\n self.build_dates()\n return random.choice(self.date_keys)\n\n def build_data(self, **kwargs):\n num_row = kwargs.get(\"num_row\")\n \"\"\" Trial = 0, Basic = 1, Advance = 2 \"\"\"\n # list branch\n data = []\n\n # build list date\n\n for i in range(1, num_row + 1):\n if i <= 10:\n contract_type = 0\n elif i <= 400:\n contract_type = 1\n else:\n contract_type = 2\n expiry_date_key = self.get_random_date()\n data.append(\n (i, i, contract_type, expiry_date_key)\n )\n RETAILER_EXPIRY[i] = expiry_date_key\n return data\n\n\n\"\"\" Transactions Fact Data \"\"\"\n\n\nclass TransactionsFactData(DimensionDataBase):\n table_name = \"transactions_facts\"\n fields_name = \"invoice_key,product_key,customer_key,branch_key,retailer_key,industry_key,invoice_time_key,quantity,amount\"\n fields_format = \"%s,%s,%s,%s,%s,%s,%s,%s,%s\"\n\n def __init__(self, conn):\n super(TransactionsFactData, self).__init__(conn=conn)\n self.date_keys = None\n\n def build_dates(self):\n list_date = pd.date_range(start=\"2018-06-01\", end=\"2019-07-01\")\n date_keys = []\n for d in list_date:\n date_key = int(d.strftime(\"%Y%m%d\"))\n date_keys.append(date_key)\n self.date_keys = date_keys\n\n def get_random_date(self, retailer_key):\n if self.date_keys is None:\n self.build_dates()\n date_key = random.choice(self.date_keys)\n retailer_expiry = RETAILER_EXPIRY[retailer_key]\n if date_key < retailer_expiry:\n return date_key\n return retailer_expiry\n\n def get_retailer_data(self, retailer_key):\n invoice_time_key = self.get_random_date(retailer_key)\n industry_key = random.randint(1, 17)\n\n branch_mul = BRANCH // RETAILER\n retailer_branch = [(retailer_key - 1) * branch_mul + i for i in range(1, branch_mul + 1)]\n\n customer_mul = CUSTOMER // RETAILER\n retailer_customer = [(retailer_key - 1) * customer_mul + i for i in range(1, customer_mul + 1)]\n\n invoice_mul = INVOICE // RETAILER\n retailer_invoice = [(retailer_key - 1) * invoice_mul + i for i in range(1, invoice_mul + 1)]\n\n product_mul = PRODUCT // RETAILER\n retailer_product = [(retailer_key - 1) * product_mul + i for i in range(1, product_mul + 1)]\n\n return invoice_time_key, industry_key, retailer_branch, retailer_customer, retailer_invoice, retailer_product\n\n @staticmethod\n def get_random_price():\n price = random.randint(1, 1000)\n return price * 1000\n\n def build_data(self, **kwargs):\n # list branch\n data = []\n # build list date\n for retailer_key in range(1, RETAILER + 1):\n invoice_time_key, industry_key, retailer_branch, retailer_customer, retailer_invoice, retailer_product =\\\n self.get_retailer_data(retailer_key)\n # 2 branch\n product_price = {}\n for b_i, branch_key in enumerate(retailer_branch):\n # 40 invoice\n for in_i, invoice_key in enumerate(retailer_invoice[20*b_i:20*(b_i + 1)]):\n customer_key = retailer_customer[in_i // 2]\n # random product number in invoice\n num_product = random.randint(1, 10)\n # get random product in invoice\n invoice_product = random.sample(retailer_product, num_product)\n # invoice total values\n amount = 0\n list_row = []\n for product_key in invoice_product:\n # price of product\n if product_key not in product_price:\n price = self.get_random_price()\n product_price[product_key] = price\n else:\n price = product_price[product_key]\n # quantity of product\n quantity = random.randint(1, 100)\n # total price of product\n amount += price * quantity\n list_row.append(\n (\n invoice_key, product_key, customer_key, branch_key,\n retailer_key, industry_key, invoice_time_key, quantity\n )\n )\n for row in list_row:\n row_data = row + (amount, )\n data.append(row_data)\n return data\n\n\nif __name__ == \"__main__\":\n\n FROM_DATE = \"2015-01-01\"\n TO_DATE = \"2025-01-01\"\n INDUSTRY = 17\n RETAILER = 500\n BRANCH = 1000\n PRODUCT = 5000\n CUSTOMER = 5000\n INVOICE = 20000\n RETAILER_EXPIRY = {}\n\n db_connect = DatabaseConnection(hostname=HOST_NAME, username=USER_NAME, password=PASSWORD, database=DATABASE)\n connection = db_connect.get_connection()\n # Insert Date\n dim_date = DateDimensionData(conn=connection)\n dim_date.do_insert(from_date=FROM_DATE, to_date=TO_DATE)\n\n # Insert Industry\n dim_industry = IndustryDimensionData(conn=connection)\n dim_industry.do_insert(num_row=INDUSTRY)\n\n # Insert Retailer\n dim_retailer = RetailerDimensionData(conn=connection)\n dim_retailer.do_insert(num_row=RETAILER)\n\n # Insert Branch\n dim_branch = BranchDimensionData(conn=connection)\n dim_branch.do_insert(num_row=BRANCH)\n\n # Insert Product\n dim_product = ProductDimensionData(conn=connection)\n dim_product.do_insert(num_row=PRODUCT)\n\n # Insert Customer\n dim_customer = CustomerDimensionData(conn=connection)\n dim_customer.do_insert(num_row=CUSTOMER)\n\n # Insert Invoice\n dim_invoice = InvoiceDimensionData(conn=connection)\n dim_invoice.do_insert(num_row=INVOICE)\n\n # Insert Invoice\n fact_transaction = TransactionsFactData(conn=connection)\n fact_transaction.do_insert()\n\n connection.close()\n","sub_path":"sample_data/build_data.py","file_name":"build_data.py","file_ext":"py","file_size_in_byte":10890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"587013591","text":"import os\nimport time\nfrom pathlib import Path\nimport pymongo\nfrom dotenv import load_dotenv\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException, ElementClickInterceptedException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinary\n\n\nclass MvideoParser:\n def __init__(self, *args, **kwargs):\n self.gecko = os.path.normpath(os.path.join(os.path.dirname(__file__), 'geckodriver'))\n self.binary = FirefoxBinary(r'C:\\Program Files\\Mozilla Firefox\\firefox.exe')\n self.driver = webdriver.Firefox(firefox_binary=self.binary, executable_path=self.gecko + '.exe')\n self.driver.get('https://www.mvideo.ru/promo/bolshaya-shkolnaya-rasprodazha-skidki-bolee-40-mark168010620')\n self.mongo_uri = 'mongodb://localhost:27017'\n self.mongo_db = 'mvideo'\n self.mongo_collection = type(self).__name__\n self.client = pymongo.MongoClient(self.mongo_uri)\n self.db = self.client[self.mongo_db]\n\n __xpath = {\n 'pagination_next': '//div[@class=\"o-pagination-section\"]/div[contains(@class, \"c-pagination\")]'\n '/a[contains(@class, \"c-pagination__next\")]',\n 'items': '//div[@data-init=\"productTileList\"]//div[contains(@class, \"product-tiles-list-wrapper\")]/div',\n\n 'details_button': '//ul[@class=\"c-tabs__menu-list\"]/li',\n 'details_categories': '//div[@class=\"product-details-specification-content\"]/div[2]/div/h3',\n 'details': '//div[@class=\"product-details-specification-content\"]/div[2]/div'\n '//table[@class=\"table table-striped product-details-table\"]'\n '//span[@class=\"product-details-overview-specification\"]',\n 'title': '//div[@class=\"o-pdp-topic__title\"]/h1',\n 'price': '//div[@class=\"c-pdp-price__summary\"]/div[@class=\"c-pdp-price__offers\"]'\n '/div[contains(@class, \"c-pdp-price__current\")]'\n }\n\n def start(self):\n while True:\n items_len = len(self.wait_get_element(self.__xpath['items'], multiple=True))\n for index in range(0, items_len):\n items = self.wait_get_element(self.__xpath['items'], multiple=True)\n item = items[index]\n if index > 2:\n for _ in range(0, int(index // 3 * 10)):\n self.driver.find_element_by_xpath('//body').send_keys(Keys.ARROW_DOWN)\n item.click()\n try:\n self.wait_get_element(self.__xpath['details_button'], multiple=True)[1].click()\n except ElementClickInterceptedException as e:\n self.driver.find_element_by_xpath('//body').send_keys(Keys.PAGE_DOWN)\n self.wait_get_element(self.__xpath['details_button'], multiple=True)[1].click()\n\n result = {\n 'title': self.driver.find_element_by_xpath(self.__xpath['title']).text,\n 'price': self.driver.find_element_by_xpath(self.__xpath['price']).text,\n 'params': {},\n }\n\n details = self.wait_get_element(self.__xpath['details'], multiple=True)\n\n for i in range(0, len(details), 2):\n result['params'].update({details[i].text.replace('.', ''): details[i + 1].text})\n\n self.write_to_mongo(result)\n self.driver.execute_script('window.history.go(-2)')\n\n try:\n next_page = self.wait_get_element(self.__xpath['pagination_next'])\n next_page.click()\n time.sleep(2)\n except Exception as e:\n print('No more pages to parse')\n self.driver.quit()\n break\n\n def save_to_mongo(self, item):\n self.db[self.mongo_collection].insert_one(item)\n\n def wait_get_element(self, xpath, multiple=False, timeout=30):\n try:\n element_present = EC.presence_of_element_located((By.XPATH, xpath))\n WebDriverWait(self.driver, timeout).until(element_present)\n if multiple:\n return self.driver.find_elements_by_xpath(xpath)\n return self.driver.find_element_by_xpath(xpath)\n except TimeoutException:\n print(\"Timed out, shutting down\")\n self.driver.quit()\n\n\nif __name__ == '__main__':\n load_dotenv(dotenv_path=Path('.env').absolute())\n mvideo_parser = MvideoParser()\n mvideo_parser.start()","sub_path":"data_mining/hw7/mvideo_parse.py","file_name":"mvideo_parse.py","file_ext":"py","file_size_in_byte":4674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"39602254","text":"# ----------------------------------------------------------------------------\n# Copyright (c) 2013--, scikit-bio development team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n# ----------------------------------------------------------------------------\n\nfrom __future__ import absolute_import, division, print_function\n\nimport functools\n\nimport scipy.spatial.distance\nimport pandas as pd\n\nimport skbio\nfrom skbio.diversity.alpha._faith_pd import _faith_pd, _setup_faith_pd\nfrom skbio.diversity.beta._unifrac import (\n _setup_multiple_unweighted_unifrac, _setup_multiple_weighted_unifrac,\n _normalize_weighted_unifrac_by_default)\nfrom skbio.util._decorator import experimental\nfrom skbio.stats.distance import DistanceMatrix\nfrom skbio.diversity._util import (_validate_counts_matrix,\n _get_phylogenetic_kwargs)\n\n\ndef _get_alpha_diversity_metric_map():\n return {\n 'ace': skbio.diversity.alpha.ace,\n 'chao1': skbio.diversity.alpha.chao1,\n 'chao1_ci': skbio.diversity.alpha.chao1_ci,\n 'berger_parker_d': skbio.diversity.alpha.berger_parker_d,\n 'brillouin_d': skbio.diversity.alpha.brillouin_d,\n 'dominance': skbio.diversity.alpha.dominance,\n 'doubles': skbio.diversity.alpha.doubles,\n 'enspie': skbio.diversity.alpha.enspie,\n 'esty_ci': skbio.diversity.alpha.esty_ci,\n 'faith_pd': skbio.diversity.alpha.faith_pd,\n 'fisher_alpha': skbio.diversity.alpha.fisher_alpha,\n 'goods_coverage': skbio.diversity.alpha.goods_coverage,\n 'heip_e': skbio.diversity.alpha.heip_e,\n 'kempton_taylor_q': skbio.diversity.alpha.kempton_taylor_q,\n 'margalef': skbio.diversity.alpha.margalef,\n 'mcintosh_d': skbio.diversity.alpha.mcintosh_d,\n 'mcintosh_e': skbio.diversity.alpha.mcintosh_e,\n 'menhinick': skbio.diversity.alpha.menhinick,\n 'michaelis_menten_fit': skbio.diversity.alpha.michaelis_menten_fit,\n 'observed_otus': skbio.diversity.alpha.observed_otus,\n 'osd': skbio.diversity.alpha.osd,\n 'pielou_e': skbio.diversity.alpha.pielou_e,\n 'robbins': skbio.diversity.alpha.robbins,\n 'shannon': skbio.diversity.alpha.shannon,\n 'simpson': skbio.diversity.alpha.simpson,\n 'simpson_e': skbio.diversity.alpha.simpson_e,\n 'singles': skbio.diversity.alpha.singles,\n 'strong': skbio.diversity.alpha.strong,\n 'gini_index': skbio.diversity.alpha.gini_index,\n 'lladser_pe': skbio.diversity.alpha.lladser_pe,\n 'lladser_ci': skbio.diversity.alpha.lladser_ci}\n\n\n@experimental(as_of=\"0.4.1\")\ndef get_alpha_diversity_metrics():\n \"\"\" List scikit-bio's alpha diversity metrics\n\n The alpha diversity metrics listed here can be passed as metrics to\n ``skbio.diversity.alpha_diversity``.\n\n Returns\n -------\n list of str\n Alphabetically sorted list of alpha diversity metrics implemented in\n scikit-bio.\n\n See Also\n --------\n alpha_diversity\n get_beta_diversity_metrics\n\n \"\"\"\n metrics = _get_alpha_diversity_metric_map()\n return sorted(metrics.keys())\n\n\n@experimental(as_of=\"0.4.1\")\ndef get_beta_diversity_metrics():\n \"\"\" List scikit-bio's beta diversity metrics\n\n The beta diversity metrics listed here can be passed as metrics to\n ``skbio.diversity.beta_diversity``.\n\n Returns\n -------\n list of str\n Alphabetically sorted list of beta diversity metrics implemented in\n scikit-bio.\n\n See Also\n --------\n beta_diversity\n get_alpha_diversity_metrics\n scipy.spatial.distance.pdist\n\n Notes\n -----\n SciPy implements many additional beta diversity metrics that are not\n included in this list. See documentation for\n ``scipy.spatial.distance.pdist`` for more details.\n\n \"\"\"\n return sorted(['unweighted_unifrac', 'weighted_unifrac'])\n\n\n@experimental(as_of=\"0.4.1\")\ndef alpha_diversity(metric, counts, ids=None, validate=True, **kwargs):\n \"\"\" Compute alpha diversity for one or more samples\n\n Parameters\n ----------\n metric : str, callable\n The alpha diversity metric to apply to the sample(s). Passing metric as\n a string is preferable as this often results in an optimized version of\n the metric being used.\n counts : 1D or 2D array_like of ints or floats\n Vector or matrix containing count/abundance data. If a matrix, each row\n should contain counts of OTUs in a given sample.\n ids : iterable of strs, optional\n Identifiers for each sample in ``counts``. By default, samples will be\n assigned integer identifiers in the order that they were provided.\n validate: bool, optional\n If `False`, validation of the input won't be performed. This step can\n be slow, so if validation is run elsewhere it can be disabled here.\n However, invalid input data can lead to invalid results or error\n messages that are hard to interpret, so this step should not be\n bypassed if you're not certain that your input data are valid. See\n :mod:`skbio.diversity` for the description of what validation entails\n so you can determine if you can safely disable validation.\n kwargs : kwargs, optional\n Metric-specific parameters.\n\n Returns\n -------\n pd.Series\n Values of ``metric`` for all vectors provided in ``counts``. The index\n will be ``ids``, if provided.\n\n Raises\n ------\n ValueError, MissingNodeError, DuplicateNodeError\n If validation fails. Exact error will depend on what was invalid.\n TypeError\n If invalid method-specific parameters are provided.\n\n See Also\n --------\n skbio.diversity\n skbio.diversity.alpha\n skbio.diversity.get_alpha_diversity_metrics\n skbio.diversity.beta_diversity\n\n \"\"\"\n metric_map = _get_alpha_diversity_metric_map()\n\n if validate:\n counts = _validate_counts_matrix(counts, ids=ids)\n\n if metric == 'faith_pd':\n otu_ids, tree, kwargs = _get_phylogenetic_kwargs(counts, **kwargs)\n counts_by_node, branch_lengths = _setup_faith_pd(\n counts, otu_ids, tree, validate, single_sample=False)\n counts = counts_by_node\n metric = functools.partial(_faith_pd, branch_lengths=branch_lengths)\n elif callable(metric):\n metric = functools.partial(metric, **kwargs)\n elif metric in metric_map:\n metric = functools.partial(metric_map[metric], **kwargs)\n else:\n raise ValueError('Unknown metric provided: %r.' % metric)\n\n # kwargs is provided here so an error is raised on extra kwargs\n results = [metric(c, **kwargs) for c in counts]\n return pd.Series(results, index=ids)\n\n\n@experimental(as_of=\"0.4.0\")\ndef beta_diversity(metric, counts, ids=None, validate=True, pairwise_func=None,\n **kwargs):\n \"\"\"Compute distances between all pairs of samples\n\n Parameters\n ----------\n metric : str, callable\n The pairwise distance function to apply. See the scipy ``pdist`` docs\n and the scikit-bio functions linked under *See Also* for available\n metrics. Passing metrics as a strings is preferable as this often\n results in an optimized version of the metric being used.\n counts : 2D array_like of ints or floats\n Matrix containing count/abundance data where each row contains counts\n of OTUs in a given sample.\n ids : iterable of strs, optional\n Identifiers for each sample in ``counts``. By default, samples will be\n assigned integer identifiers in the order that they were provided\n (where the type of the identifiers will be ``str``).\n validate : bool, optional\n If `False`, validation of the input won't be performed. This step can\n be slow, so if validation is run elsewhere it can be disabled here.\n However, invalid input data can lead to invalid results or error\n messages that are hard to interpret, so this step should not be\n bypassed if you're not certain that your input data are valid. See\n :mod:`skbio.diversity` for the description of what validation entails\n so you can determine if you can safely disable validation.\n pairwise_func : callable, optional\n The function to use for computing pairwise distances. This function\n must take ``counts`` and ``metric`` and return a square, hollow, 2-D\n ``numpy.ndarray`` of dissimilarities (floats). Examples of functions\n that can be provided are ``scipy.spatial.distance.pdist`` and\n ``sklearn.metrics.pairwise_distances``. By default,\n ``scipy.spatial.distance.pdist`` will be used.\n kwargs : kwargs, optional\n Metric-specific parameters.\n\n Returns\n -------\n skbio.DistanceMatrix\n Distances between all pairs of samples (i.e., rows). The number of\n rows and columns will be equal to the number of rows in ``counts``.\n\n Raises\n ------\n ValueError, MissingNodeError, DuplicateNodeError\n If validation fails. Exact error will depend on what was invalid.\n TypeError\n If invalid method-specific parameters are provided.\n\n See Also\n --------\n skbio.diversity\n skbio.diversity.beta\n skbio.diversity.get_beta_diversity_metrics\n skbio.diversity.alpha_diversity\n scipy.spatial.distance.pdist\n sklearn.metrics.pairwise_distances\n\n \"\"\"\n if validate:\n counts = _validate_counts_matrix(counts, ids=ids)\n\n if pairwise_func is None:\n pairwise_func = scipy.spatial.distance.pdist\n\n if metric == 'unweighted_unifrac':\n otu_ids, tree, kwargs = _get_phylogenetic_kwargs(counts, **kwargs)\n metric, counts_by_node = _setup_multiple_unweighted_unifrac(\n counts, otu_ids=otu_ids, tree=tree, validate=validate)\n counts = counts_by_node\n elif metric == 'weighted_unifrac':\n # get the value for normalized. if it was not provided, it will fall\n # back to the default value inside of _weighted_unifrac_pdist_f\n normalized = kwargs.pop('normalized',\n _normalize_weighted_unifrac_by_default)\n otu_ids, tree, kwargs = _get_phylogenetic_kwargs(counts, **kwargs)\n metric, counts_by_node = _setup_multiple_weighted_unifrac(\n counts, otu_ids=otu_ids, tree=tree, normalized=normalized,\n validate=validate)\n counts = counts_by_node\n elif callable(metric):\n metric = functools.partial(metric, **kwargs)\n # remove all values from kwargs, since they have already been provided\n # through the partial\n kwargs = {}\n else:\n # metric is a string that scikit-bio doesn't know about, for\n # example one of the SciPy metrics\n pass\n\n distances = pairwise_func(counts, metric=metric, **kwargs)\n return DistanceMatrix(distances, ids)\n","sub_path":"toxic_docs_insight/flask/app/venv/lib/python2.7/site-packages/skbio/diversity/_driver.py","file_name":"_driver.py","file_ext":"py","file_size_in_byte":10959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"540908503","text":"# ニューラルネットワークのBP法による学習\n# 練習用のため拡張性ゼロのアホアホプログラミング\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# 乱数の種を設定\nnp.random.seed(3)\n\n# パラメータ\nEPSILON = 4.0 # シグモイド関数の傾き\nETA = 0.1 # 学習係数\nTIME = 1000 # 学習回数\nALPHA = 1.5\n\nsum_tha = 0.0\nsum_thb = 0.0\nsum_thc = 0.0\nsum_wab = 0.0\nsum_wac = 0.0\nsum_wbd = 0.0\nsum_wbe = 0.0\nsum_wcd = 0.0\nsum_wce = 0.0\n\nwabO = 0.0\nwacO = 0.0\nwbdO = 0.0\nwbeO = 0.0\nwcdO = 0.0\nwceO = 0.0\ntha0 = 0.0\nthbO = 0.0\nthcO = 0.0\n\n# シグモイド関数\ndef sigmoid(x):\n return 1 / (1 + np.exp(-1 * EPSILON * x))\n\n\n# 入力(XORの入力部分)\ndataX = np.array(\n [[0, 0],\n [0, 1],\n [1, 0],\n [1, 1]]\n)\n\n# 教師信号(XORの出力部分)\ndataY = np.array(\n [[0],\n [1],\n [1],\n [0]]\n)\n\n# 初期重みと初期閾値をランダムに与える\nwab = (np.random.rand() - 0.5) * 2 * 0.3 # -0.3から0.3の一様乱数\nwac = (np.random.rand() - 0.5) * 2 * 0.3\nwbd = (np.random.rand() - 0.5) * 2 * 0.3\nwbe = (np.random.rand() - 0.5) * 2 * 0.3\nwcd = (np.random.rand() - 0.5) * 2 * 0.3\nwce = (np.random.rand() - 0.5) * 2 * 0.3\ntha = (np.random.rand() - 0.5) * 2 * 0.3\nthb = (np.random.rand() - 0.5) * 2 * 0.3\nthc = (np.random.rand() - 0.5) * 2 * 0.3\n\n# 重みを表示\nprint(\"学習前の重み\")\nprint('wab=', wab)\nprint('wac=', wac)\nprint('wbd=', wbd)\nprint('wbe=', wbe)\nprint('wcd=', wcd)\nprint('wce=', wce)\nprint('tha=', tha)\nprint('thb=', thb)\nprint('thc=', thc)\nprint()\n\n# 誤差曲線のグラフ表示用\nx = []\ny = []\n\n# 学習\nfor t in range(TIME):\n\n outall = []\n errorAll = 0.0\n for p in range(len(dataX)):\n #############\n # 前向き計算\n #############\n\n # 入力層\n outd = dataX[p][0]\n oute = dataX[p][1]\n\n # 中間層\n xb = wbd * outd + wbe * oute + thb\n outb = sigmoid(xb)\n\n xc = wcd * outd + wce * oute + thc\n outc = sigmoid(xc)\n\n # 出力層\n xa = wab * outb + wac * outc + tha\n outa = sigmoid(xa)\n\n # 誤差計算\n outall.append(outa)\n error = (outa - dataY[p]) ** 2\n errorAll += error\n\n ##################\n # Back Propagation\n ##################\n\n # ここに更新式を書く\n\n # 中間層-出力層\n deltaa = (outa - tha) * EPSILON * (1 - outa) * outa\n deltab = deltaa * wab * EPSILON * (1 - outb) * outb\n deltac = deltaa * wac * EPSILON * (1 - outc) * outc\n\n sum_tha += - ETA * deltaa\n sum_thb += - ETA * deltab\n sum_thc += - ETA * deltac\n sum_wab += - ETA * deltaa * outb\n sum_wac += - ETA * deltaa * outc\n sum_wbd += - ETA * deltab * outd\n sum_wbe += - ETA * deltab * oute\n sum_wcd += - ETA * deltac * outd\n sum_wce += - ETA * deltac * oute\n # 誤差曲線のグラフ表示用の変数\n x.append(t)\n y.append(errorAll)\nwabO = sum_wab\nwacO = sum_wac\nwbdO = sum_wbd\nwbeO = sum_wbe\nwcdO = sum_wcd\nwceO = sum_wce\nthaO = sum_tha\nthbO = sum_thb\nthcO = sum_thc\n\nwab += sum_wab + ALPHA * wabO\nwac += sum_wac + ALPHA * wacO\nwbd += sum_wbd + ALPHA * wbdO\nwbe += sum_wbe + ALPHA * wbeO\nwcd += sum_wcd + ALPHA * wcdO\nwce += sum_wce + ALPHA * wceO\ntha += sum_tha + ALPHA * thaO\nthb += sum_thb + ALPHA * thbO\nthc += sum_thc + ALPHA * thcO\n\n# 学習後の出力\nprint(\"学習後の出力\")\nprint(errorAll)\nprint(outall[0])\nprint(outall[1])\nprint(outall[2])\nprint(outall[3])\nprint()\n\n# 重みを表示\nprint()\nprint(\"学習後の重み\")\nprint('wab=', wab)\nprint('wac=', wac)\nprint('wbd=', wbd)\nprint('wbe=', wbe)\nprint('wcd=', wcd)\nprint('wce=', wce)\nprint('tha=', tha)\nprint('thb=', thb)\nprint('thc=', thc)\nprint()\n\n","sub_path":"intelligent/firstSemester/9/bp-3.py","file_name":"bp-3.py","file_ext":"py","file_size_in_byte":3783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"504134980","text":"# Prime Number Generator\r\n\r\nnumArr = []\r\nprimes = []\r\n\r\nstress = (int(input(\"How many numbers would you like to check? \")))\r\n\r\ndef arrPopulation():\r\n\tfor i in range (stress):\r\n\t\tnumArr.append(i+1)\r\n\tprint (\"\\nArray Populated with \" + str(stress) + \" entries\")\r\n\r\ndef PrimeGenerator():\r\n\ttry:\r\n\t\ttimesDivided = 0\r\n\t\tprint (\"Checking For Prime Numbers... \\n\")\r\n\t\tfor i in range(stress):\r\n\t\t\ttimesDivided = 0\r\n\t\t\tfor f in range (stress):\r\n\t\t\t\tprint (str(numArr[i]) + \" / \" + str(numArr[f]), end='\\r')\r\n\t\t\t\tif ((numArr[i] / numArr[f]).is_integer()):\r\n\t\t\t\t\ttimesDivided = timesDivided + 1\r\n\t\t\tif (timesDivided == 2):\r\n\t\t\t\t# Number is prime\r\n\t\t\t\tprimes.append(numArr[i])\r\n\r\n\t\tprint (\"Found \" + str(len(primes)) + \" primes: \")\r\n\t\tfor g in range (len(primes)):\r\n\t\t\tprint (\"[ \" + str(g) + \" ] \" + str(primes[g]) + \", \", end='')\r\n\texcept (KeyboardInterrupt):\r\n\t\tprint (\"Found \" + str(len(primes)) + \" primes: \")\r\n\t\tfor g in range (len(primes)):\r\n\t\t\tprint (str(primes[g]) + \", \", end='')\r\n\r\narrPopulation()\r\nPrimeGenerator()\r\nprint (\"\\n\")\r\n","sub_path":"Python/primegenerator.py","file_name":"primegenerator.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"455746186","text":"from tweepy_auth import *\nimport tweepy as tpy\n\nimport csv\n\nauth = auth()\napi = api(auth)\n\ndef takeIntentTweets(file):\n tweets = []\n with open(file,'r') as f:\n reader = csv.reader(f)\n\n tweet_list = []\n for row in reader:\n if row[4] == str(1):\n if row[3] not in tweet_list: \n tweets.append({'screen_name':row[1],'tweet':row[3],'intent':row[4],'created_at':row[5],'status_url':row[6]})\n tweet_list.append(tweets[-1][\"tweet\"])\n print(tweet_list[-1])\n \n return tweets\n \ndef send(name,content):\n try:\n api.send_direct_message(screen_name = name, text = content)\n except:\n return \"Error\"\n \n return \"Tweeted\"\n\nif __name__ == \"__main__\":\n #takeIntentTweets(\"data/Wonder Woman/Wonder Woman.csv\")\n print(send('goviral_v2','this is awesome!'))\n","sub_path":"backend/ImproveContent/direct_message_api.py","file_name":"direct_message_api.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"195363993","text":"import re\nimport pyperclip\nimport sys\n\nSOURCE = \"client/GUI/common/fiches.go\"\n\nHEADER = \"\"\"\npackage common\n\nimport (\n\t\"github.com/benoitkugler/goACVE/client/GUI/fields\"\n\t\"github.com/benoitkugler/goACVE/core/datamodel\"\n\t\"github.com/benoitkugler/goACVE/core/rawdata\"\n\t\"github.com/therecipe/qt/widgets\"\n)\n\n// autogenerated from fiches.go\n\"\"\"\n\nTEMPLATE_NEW = \"\"\"\nfunc NewFiche{name}(base *datamodel.BaseLocale, editable bool) Fiche{name} {{\n\tf := Fiche{name}{{QFrame: basic.Frame()}}\n\t\n\t{fields}\n\t\n return f \n}}\t\n\"\"\"\n\nTEMPLATE_FUNCS= \"\"\"\nfunc (f *Fiche{name}) SetData(p rawdata.Raw{name}) {{\n\tf.initial{name} = p\n {fields_set}\t\n}}\n\nfunc (f *Fiche{name}) Reset() {{\n\tf.SetData(f.initial{name})\n}}\n\nfunc (f Fiche{name}) Valid() error {{\n\treturn nil\n}}\n\nfunc (f Fiche{name}) GetData() rawdata.Raw{name} {{\n p := f.initial{name}\n {fields_get}\n return p\n}}\n\nfunc (f Fiche{name}) SetLayout() {{\n\tlG := widgets.NewQFormLayout(nil)\n\tlG.SetVerticalSpacing(15)\n\n {fields_row}\n \n\tlay := widgets.NewQHBoxLayout2(f)\n\tlay.AddLayout(lG, 4)\n}}\n\n\"\"\"\n\nREG_NAME = re.compile(r\"type Fiche(\\w+) struct\")\nREG_FIELDS = re.compile(r\"(\\w+)\\s+\\*?fields.(\\w+)\")\n\ndef parse():\n with open(SOURCE) as f:\n lines = f.readlines()\n\n dic, current, name, in_fiche = {}, [], \"\", False\n for line in lines:\n match = REG_NAME.search(line)\n if match:\n in_fiche = True\n name = match.group(1)\n\n if in_fiche and \"}\" in line:\n dic[name] = current\n current = []\n in_fiche = False\n\n match_field = REG_FIELDS.search(line)\n if match_field:\n field, widget = match_field.group(1), match_field.group(2)\n current.append({\"field\" : field, \"widget\": widget})\n\n return dic\n\n\ndef render(dic):\n code = \"\"\n for name, fields_list in dic.items():\n fields_init, fields_get, fields_set, fields_row = \"\",\"\",\"\", \"\"\n for f_dic in fields_list:\n field_cap = f_dic['field']\n field_cap = field_cap[0].upper() + field_cap[1:]\n fields_init+=f\"f.{f_dic['field']} = fields.New{f_dic['widget']}(editable)\\n\"\n fields_get+=f\"p.{field_cap} = f.{f_dic['field']}.GetData()\\n\"\n fields_set+=f\"f.{f_dic['field']}.SetData(p.{field_cap})\\n\"\n fields_row += f\"\"\"lG.AddRow3(\"{field_cap}\", f.{f_dic['field']}) \\n\"\"\"\n\n code += TEMPLATE_NEW.format(name=name, fields=fields_init)\n code += TEMPLATE_FUNCS.format(name=name, fields_get=fields_get, fields_set=fields_set, fields_row=fields_row)\n return code\n\nif __name__ == '__main__':\n dic = parse()\n if len(sys.argv) >= 1:\n dic = { sys.argv[1] : dic[sys.argv[1]]}\n code = render(dic)\n else:\n code = HEADER + render(dic)\n pyperclip.copy(code)\n print(\"Code des fiches copié.\")","sub_path":"macros/fiches.py","file_name":"fiches.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"136155461","text":"import json\nimport os.path as osp\nimport uuid\nfrom threading import Lock\n\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nfrom .myzmq import Client\nfrom .remote_file_widget import Ui_Form as Ui_Dock\nfrom .remote_login_dialog import Ui_Form as Ui_Login\n\n\ndef synchronized(func):\n func.__lock__ = Lock()\n\n def lock_func(*args, **kwargs):\n with func.__lock__:\n return func(*args, **kwargs)\n\n return lock_func\n\n\nclass RemoteConfig:\n instance = None\n config = {}\n\n def __init__(self):\n self._read()\n\n @synchronized\n def __new__(cls, *args, **kwargs):\n if cls.instance is None:\n cls.instance = super().__new__(cls)\n return cls.instance\n\n @staticmethod\n def _write():\n setting = QSettings('remote_config.ini', QSettings.IniFormat)\n setting.setValue('zmq/ip', '127.0.0.1')\n setting.setValue('zmq/port', 7777)\n setting.setValue('user/id', str(uuid.uuid1()))\n setting.setValue('user/name', '未定义')\n setting.setValue('zmq/timeout', 3000)\n\n def _read(self):\n if not osp.exists('remote_config.ini'):\n self._write()\n setting = QSettings('remote_config.ini', QSettings.IniFormat)\n self.config['zmq/ip'] = setting.value('zmq/ip', '127.0.0.1')\n self.config['zmq/port'] = int(setting.value('zmq/port', 7777))\n self.config['user/id'] = setting.value('user/id', str(uuid.uuid1()))\n self.config['user/name'] = setting.value('user/name', '未定义')\n self.config['zmq/timeout'] = int(setting.value('zmq/timeout', 3000))\n\n def set(self, conf_dict):\n setting = QSettings('remote_config.ini', QSettings.IniFormat)\n for key, value in conf_dict.items():\n setting.setValue(key, value)\n self.config[key] = value\n setting.sync()\n\n def get(self, key):\n return self.config[key]\n\n\nclass MyZmqClient(Client):\n instance = None\n running = False\n\n def __init__(self): # noqa\n pass # 重载避免多次调用父类init\n\n def start(self, ip, port, timeout=3000):\n if self.running:\n self.stop()\n self.setTimeout(timeout)\n self.setAddress(ip, port)\n self.initMQ()\n self.running = True\n\n def stop(self):\n self.unInitMQ()\n self.running = False\n\n @synchronized\n def __new__(cls, *args, **kwargs):\n if cls.instance is None:\n cls.instance = super().__new__(cls)\n Client.__init__(cls.instance)\n return cls.instance\n\n\nclass RemoteListModel(QAbstractListModel):\n def __init__(self):\n super().__init__()\n self.lst_file = []\n self.lst_show = []\n\n def clearData(self):\n self.lst_file = []\n self.lst_show = []\n\n def rowCount(self, parent=None, *args, **kwargs):\n return len(self.lst_show)\n\n def data(self, index: QModelIndex, role=None):\n row = index.row()\n if role == Qt.DisplayRole:\n return self.lst_show[row]\n\n def flags(self, QModelIndex):\n return Qt.ItemIsEnabled | Qt.ItemIsSelectable\n\n\nclass RemoteQDockWidget(QDockWidget, Ui_Dock):\n def __init__(self, title, parent, plugin):\n super().__init__(title, parent)\n self.plugin = plugin\n self.initGui()\n self.msg_handle = MyZmqClient()\n self.remote_config = RemoteConfig()\n self.userID = self.remote_config.get('user/id')\n\n def showEvent(self, a0: QShowEvent) -> None:\n self.refreshRemoteFile()\n self.listCountChanged()\n\n def initGui(self):\n self.widget = QWidget(self)\n self.setupUi(self.widget)\n self.setWidget(self.widget)\n\n self.model = RemoteListModel()\n self.listView.setModel(self.model)\n self.btnRefresh.clicked.connect(self.btnRefreshClicked)\n self.txtFilter.textChanged.connect(self.txtFilterTextChanged)\n self.listView.activated.connect(self.listViewActivated)\n\n def listViewActivated(self, index: QModelIndex):\n row = index.row()\n filename = self.model.lst_show[row]\n self.plugin.loadRemoteFile(filename)\n\n def btnRefreshClicked(self):\n num = self.refreshRemoteFile()\n QMessageBox.information(self, '提示', '获取到{}个文件'.format(num))\n self.listCountChanged()\n\n def listCountChanged(self):\n count = len(self.model.lst_show)\n if count < 2:\n self.plugin.actions.openNextImg.setEnabled(False)\n self.plugin.actions.openPrevImg.setEnabled(False)\n return\n self.plugin.actions.openNextImg.setEnabled(True)\n self.plugin.actions.openPrevImg.setEnabled(True)\n\n def refreshRemoteFile(self):\n self.model.beginResetModel()\n self.model.clearData()\n lst = self.queryRemoteFile()\n self.model.lst_file = lst\n self.model.lst_show = lst.copy()\n self.model.endResetModel()\n return len(lst)\n\n def txtFilterTextChanged(self, a0: str):\n if not a0:\n self.model.beginResetModel()\n self.model.lst_show = self.model.lst_file.copy()\n self.model.endResetModel()\n return\n self.model.beginResetModel()\n self.model.lst_show = []\n for file in self.model.lst_file:\n if a0 not in file:\n continue\n self.model.lst_show.append(file)\n self.model.endResetModel()\n\n def queryRemoteFile(self):\n ret, smsg = self.msg_handle.request(self.userID + ':GetList')\n if not ret:\n return []\n dct = json.loads(smsg)\n lst = dct['file']\n return lst\n\n\nclass MyLoginDialog(QDialog, Ui_Login):\n def __init__(self, parent, plugin):\n super().__init__(parent=parent)\n self.setupUi(self)\n self.plugin = plugin\n self.msg_handle = MyZmqClient()\n self.remote_config = RemoteConfig()\n\n # 信号槽\n self.btnLogin.clicked.connect(self.btnLoginClicked)\n self.btnLogout.clicked.connect(self.btnLogoutClicked)\n\n self.txtID.setReadOnly(True)\n self.isLogin = False\n\n @property\n def timeout(self):\n return self.remote_config.get('zmq/timeout')\n\n @property\n def ip(self):\n return self.remote_config.get('zmq/ip')\n\n @property\n def port(self):\n return self.remote_config.get('zmq/port')\n\n @property\n def userID(self):\n return self.remote_config.get('user/id')\n\n @property\n def userName(self):\n return self.remote_config.get('user/name')\n\n def showEvent(self, QShowEvent):\n self.txtID.setText(self.userID)\n self.txtIP.setText(self.ip)\n self.numPort.setValue(self.port)\n self.txtName.setText(self.userName)\n\n def saveConfig(self):\n conf = {'zmq/ip': self.txtIP.text(),\n 'zmq/port': self.numPort.value(),\n 'user/id': self.txtID.text(),\n 'user/name': self.txtName.text()}\n self.remote_config.set(conf)\n\n def btnLoginClicked(self):\n self.saveConfig()\n self.msg_handle.start(self.ip, self.port, self.timeout)\n ret, msg = self.msg_handle.request(self.userID + ':Login:' + self.userName)\n if ret and msg == '200':\n QMessageBox.information(self, '提示', '登录成功', QMessageBox.Ok)\n self.isLogin = True\n self.plugin.remote_dock.show()\n self.close()\n return\n elif not ret:\n QMessageBox.information(self, '提示', '连接失败', QMessageBox.Ok)\n return\n QMessageBox.information(self, '提示', '登录失败', QMessageBox.Ok)\n\n def btnLogoutClicked(self):\n self.saveConfig()\n if not self.isLogin:\n QMessageBox.information(self, '提示', '还未登录', QMessageBox.Ok)\n return\n ret, msg = self.msg_handle.request(self.userID + ':Logout')\n if ret and msg == '200':\n QMessageBox.information(self, '提示', '登出成功', QMessageBox.Ok)\n self.isLogin = False\n self.plugin.remote_dock.hide()\n self.close()\n return\n elif not ret:\n QMessageBox.information(self, '提示', '连接失败', QMessageBox.Ok)\n return\n QMessageBox.information(self, '提示', '登出失败', QMessageBox.Ok)\n","sub_path":"labelme/remote_file.py","file_name":"remote_file.py","file_ext":"py","file_size_in_byte":8373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"633503622","text":"import os\n\nclass SettingsObject(object):\n def __init__(self, installPath = \"\", virtualEnvPath = \"\", localPath=\"\"):\n self.executingPath = os.getcwd()\n if installPath:\n self.installPath = installPath \n else:\n self.installPath = os.path.join(self.executingPath, 'czinstall', 'bin')\n if virtualEnvPath:\n self.virtualEnvPath = virtualEnvPath\n else:\n self.virtualEnvPath = os.path.join(self.executingPath, 'czinstall', 'virtualenv')\n if localPath:\n self.configureLocal(localPath)\n else:\n self.configureLocal(os.path.join(os.getcwd(), 'local'))\n \n def reconfigure(self, *args, **kw):\n for key, value in kw.items():\n setattr(self, key, value)\n \n def configureLocal(self, path):\n self.reconfigure(localPath = path, downloadCache = os.path.join(path, 'cache'), buildDirectory = os.path.join(path, 'build'))\n\n def getInstallPath(self):\n return self.installPath\n \n def getVirtualEnvPath(self):\n return self.virtualEnvPath\n","sub_path":"CannedZen/setting.py","file_name":"setting.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"269231558","text":"import numpy as np\n\nclass knn_classifier():\n '''\n A classifier using k-nearest-neighbor.\n '''\n def __init__(self):\n pass\n \n def train(self, X_train, y_train):\n '''\n Train the classifier\n '''\n self.X = X_train.reshape((X_train.shape[0], -1))\n self.y = y_train\n \n def distance(self, X):\n '''\n Compute the distance between each image in X and each point in self.X\n \n Arguments:\n - X: A numpy array of N * D containing N images, each with D pixels\n \n Return:\n - dists: A numpy array of N * num_train. The dists[i, j] = the L2 distance\n between X[i] and self.X[j]\n '''\n\n X = X.reshape((X.shape[0], -1))\n return -2 * X.dot(self.X.T) + np.sum(X ** 2, axis=1, keepdims=True) + np.sum(self.X.T ** 2, axis=0, keepdims=True)\n \n \n def predict(self, X, k):\n '''\n Predict the label of images in X\n \n Arguments:\n - X: A numpy array of N * D containing N images, each with D pixels\n - k: An odd number of nearest neighbors\n \n Return:\n - labels: A numpy array of N * 1 containing the labels of N images\n '''\n X = X.reshape((X.shape[0], -1))\n dists = self.distance(X)\n k_closest_y = self.y[dists.argsort()[:, :k]]\n \n labels = []\n for k_votes in k_closest_y:\n appear_time = []\n for i in range(k):\n appear_time.append(np.count_nonzero(k_votes == i))\n labels.append(k_votes[np.argmax(appear_time)])\n return labels","sub_path":"classifier/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"418170126","text":"#!/usr/bin/env python\n# _*_ coding:utf-8 _*_\n# create time: 4/23/2017\nimport asyncio\nimport json\nimport threading\nimport time\n\n__author__ = 'Devin -- http://zhangchuzhao.site'\n\n\nclass MyDict(dict):\n num = 110\n name = 'devin'\n\n def __getattr__(self, item):\n try:\n return self[item]\n except KeyError:\n raise AttributeError('no attribute: %s' % item)\n\n def __setattr__(self, key, value):\n self[key] = value\n\nmydict = MyDict(name='devinzhang', num=120)\nprint(mydict['name'])\nprint(mydict.name)\nmydict.num = 100\nprint(mydict['num'])\nprint(mydict.num) # 如果没有找到对应的属性,再重__getattr__方法中获取\nprint(dir(mydict))\n\n\n\n\n","sub_path":"AwesomeBlog/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"234182761","text":"# -*- coding: utf-8 -*-\n'''\n@Author: zhou\n@Date : 19-7-3 上午10:13\n@Desc :\n'''\nimport time\nimport names\nimport pika\n\nconnection = pika.BlockingConnection(\n pika.ConnectionParameters(host='localhost'))\nchannel = connection.channel()\n\nchannel.queue_declare(queue='hello')\n\ni = 0\nwhile True:\n time.sleep(3)\n name = names.get_full_name()\n channel.basic_publish(exchange='', routing_key='hello', body=name)\n i = i + 1\n print(\" {} Sent {}\".format(i, name))\n # connection.close()\n","sub_path":"mq/rabbitmq/send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"283441028","text":"import pandas as pd\r\nimport numpy as np\r\nfrom sklearn import preprocessing\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.model_selection import cross_val_score,train_test_split\r\nfrom keras.models import Sequential,load_model\r\nfrom keras.layers import Activation\r\nfrom keras.optimizers import SGD\r\nfrom keras.layers import Dense\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom sklearn.cluster import KMeans\r\n\r\ndf = pd.read_csv(\"finalmodel.csv\")\r\ndf = df.dropna()\r\nle = preprocessing.LabelEncoder()\r\ncolumns = [\"District_Name\",\"Season\",\"Area\",\"Production\"]\r\ncolumn2 = [\"Crop\"]\r\n# print(df[[\"District_Name\",\"Season\",\"Crop\"]])\r\n\r\n\r\ndictionary={0: \"Tur\",1:\"Bajra\",2:\"Coconut\",3:\"Cotton\",4:\"Groundnut\",5:\"Jowar\",6:\"Maize\",7:\"Paddy\",8:\"Moong\",9:\"Niger Seed\",10:\"Ragi\",11:\"Rice\",12:\"Sesamun\",13:\"Soyabean\",14:\"Sugarcane\",15:\"Sunflower\",16:\"Urad\",17:\"Wheat\"}\r\n\r\nseries = pd.Series(dictionary)\r\nvar = le.fit_transform(df.District_Name)\r\ndf.District_Name =var\r\n#print(df.District_Name.unique)\r\n\r\nvar = le.fit_transform(df.Season)\r\ndf.Season =var\r\n#print(df.Season.unique)\r\n\r\nvar = le.fit_transform(df.Crop)\r\ndf.Crop =var\r\n#print(df.Crop.unique)\r\n\r\nvar1 = MinMaxScaler()\r\na0 = np.array(df.Area)\r\na1 = np.array(df.Production)\r\na0 = a0.reshape(a0.shape[0],1)\r\na1 = a1.reshape(a1.shape[0],1)\r\n\r\na11 = var1.fit_transform(a0)\r\na21 = var1.fit_transform(a1)\r\n\r\n# print(a11.max())\r\n# print(a21.min())\r\n\r\nX = df[columns].values\r\n#print(X)\r\ny = list(df.Crop)\r\n#print(y)\r\n# print(df.isna().sum())\r\n\r\n(X_train, X_test, ytrain, ytest) = train_test_split(X,y, test_size=0.25, random_state=42,shuffle = True)\r\n\r\nkmeans = KMeans(n_clusters=18,init='k-means++')\r\ny_kmeans = kmeans.fit(X_train)\r\nprint(list(ytest))\r\nprint(\"------------------------------------------------------------------------------------------------------------------------\")\r\ny_test = list(kmeans.predict(X_test))\r\nprint(\"We predict \",y_test)\r\n\r\n'''\r\nprint(Xtrain.shape,ytrain.shape)\r\n\r\nmodel = Sequential()\r\nmodel.add(Dense(1000, activation='', input_shape=[Xtrain.shape[1]]))\r\nmodel.add(Dense(200, activation='relu'))\r\nmodel.add(Dense(30, activation='relu'))\r\nmodel.add(Dense(1))\r\n\r\nmodel.compile(loss='mse', optimizer='rmsprop', metrics=['mean_squared_error'])\r\nmodel.fit(Xtrain, ytrain, epochs=10, batch_size=10, verbose=1,validation_split = 0.2)\r\n\r\nxnew = np.array([[51,2,30,6040]])\r\nynew=model.predict_classes(xnew)\r\nprint(ynew)\r\n'''# model.save('re.h5')\r\n# model = load_model('re.h5')\r\n# model.evaluate(Xtest,ytest)\r\n#pred = model.predict(Xtest)\r\n#print(int(pred))\r\n# lol=int(np.argmax(pred))\r\n# print(lol)\r\n# print(ytest[lol][0])\r\n# print(dictionary[ytest[lol][0]])","sub_path":"final/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"176727873","text":"# car detection helper functions\nimport os\nimport glob\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport time\nimport pickle\nfrom collections import deque\nfrom scipy.ndimage.measurements import label\nimport io\nimport base64\nfrom skimage.feature import hog\nfrom sklearn.svm import LinearSVC\nfrom sklearn.preprocessing import StandardScaler\n# NOTE: the next import is only valid for scikit-learn version <= 0.17\n# for scikit-learn >= 0.18 use:\n# from sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import train_test_split\nimport subprocess\nimport random\nimport sys\nfrom tqdm import tqdm\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML\n\n\n# load all images\ndef load_images(basedir):\n \"\"\"\n Images are divided up into vehicles and non-vehicles folders, \n each of which contains subfolders. Different folders represent \n different sources for images (eg. GTI, kitti, generated by me,...).\n \"\"\"\n image_types = os.listdir(basedir)\n res = []\n for imtype in image_types:\n res.extend(glob.glob(basedir + imtype + '/*'))\n return res\n \ndef visualize(fig, rows, cols, imgs, titles):\n \"\"\"\n Function for plotting multiple images.\n \"\"\"\n for i, img in enumerate(imgs):\n plt.subplot(rows, cols, i + 1)\n plt.title(i + 1)\n img_dims = len(img.shape)\n if img_dims < 3:\n plt.imshow(img, cmap='hot')\n else:\n plt.imshow(img)\n plt.title(titles[i])\n #plt.show()\n\ndef convert_color(img, conv='RGB2YCrCb'):\n \"\"\"\n Function to convert an image from a \n space color to another one.\n \"\"\"\n if conv == 'RGB2YCrCb':\n return cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)\n elif conv == 'BGR2YCrCb':\n return cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)\n elif conv == 'RGB2LUV':\n return cv2.cvtColor(img, cv2.COLOR_RGB2LUV)\n elif conv == 'HSV':\n return cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n elif conv == 'LUV':\n return cv2.cvtColor(img, cv2.COLOR_RGB2LUV)\n elif conv == 'HLS':\n return cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n elif conv == 'YUV':\n return cv2.cvtColor(img, cv2.COLOR_RGB2YUV)\n elif conv == 'YCrCb':\n return cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)\n\ndef draw_boxes(img, bboxes, color=(0, 255, 0), thick=6):\n \"\"\"\n Function to draw bounding boxes\n 1. Make a copy of the image.\n 2. Iterate through the bounding boxes and draw a \n rectangle given bbox coordinates.\n 3. Return the image copy with boxes drawn.\n \"\"\"\n imcopy = np.copy(img)\n for bbox in bboxes:\n cv2.rectangle(imcopy, bbox[0], bbox[1], color, thick)\n return imcopy\n\n\ndef get_hog_features(img, orient, pix_per_cell, cell_per_block, \n vis=False, feature_vec=True):\n \"\"\"\n Function to return HOG features and visualization.\n \n Call with two outputs if vis==True, otherwise call with one output\n \n The histogram of oriented gradients (HOG) is a feature \n descriptor used in computer vision and image processing \n for the purpose of object detection. The technique counts \n occurrences of gradient orientation in localized portions \n of an image. This method is similar to that of edge \n orientation histograms, scale-invariant feature transform \n descriptors, and shape contexts, but differs in that it is \n computed on a dense grid of uniformly spaced cells and uses \n overlapping local contrast normalization for improved accuracy.\n \n Source: https://en.wikipedia.org/wiki/Histogram_of_oriented_gradients\n \"\"\"\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,\n cell_per_block),\n block_norm='L1', # added due to Python warning\n transform_sqrt=True, \n visualize=vis, feature_vector=feature_vec)\n return features, hog_image\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 block_norm='L1', # added due to Python warning\n transform_sqrt=True, \n visualize=vis, feature_vector=feature_vec)\n return features\n\n\ndef bin_spatial(img, size=(32, 32)):\n \"\"\"\n Function to compute binned color features.\n It takes an image, a color space, and a new image size\n and returns a feature vector\n \"\"\"\n color1 = cv2.resize(img[:,:,0], size).ravel()\n color2 = cv2.resize(img[:,:,1], size).ravel()\n color3 = cv2.resize(img[:,:,2], size).ravel()\n return np.hstack((color1, color2, color3))\n\n\ndef color_hist(img, nbins=32):\n \"\"\"\n Function to compute the color histogram features: \n 1. Compute the histogram of the RGB channels separately.\n 2. Concatenate the histograms into a single feature vector.\n 3. Return the individual histograms, bin_centers and feature vector.\n \"\"\"\n channel1_hist = np.histogram(img[:,:,0], bins=nbins)\n channel2_hist = np.histogram(img[:,:,1], bins=nbins)\n channel3_hist = np.histogram(img[:,:,2], bins=nbins)\n hist_features = np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0]))\n return hist_features\n\n\ndef single_img_features(img, 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 vis=False): \n \"\"\"\n Function to extract features from a single image window:\n 1. Define an empty list to receive features\n 2. Apply color conversion if other than 'RGB'\n 3. Compute spatial features if flag is set\n 4. Compute histogram features if flag is set \n 5. Compute HOG features if flag is set\n 6. Return concatenated array of features \n \"\"\"\n img_features = []\n \n if color_space != 'RGB':\n feature_image = convert_color(img, color_space)\n else: \n feature_image = np.copy(img) \n\n if spatial_feat == True:\n spatial_features = bin_spatial(feature_image, size=spatial_size)\n img_features.append(spatial_features)\n\n if hist_feat == True:\n hist_features = color_hist(feature_image, nbins=hist_bins)\n img_features.append(hist_features)\n\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 if vis == True:\n hog_features, hog_image = get_hog_features(feature_image[:,:,hog_channel], orient, \n pix_per_cell, cell_per_block, vis=True, 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 img_features.append(hog_features)\n\n if vis == True:\n return np.concatenate(img_features), hog_image\n else:\n return np.concatenate(img_features)\n \ndef test_single_img_features():\n \"\"\"\n Test feature extraction from a single image:\n 1. Choose random car & not-car indices.\n 2. Read in car & notcar images.\n 3. Define feature parameters.\n 4. Extract the features for car & not-car.\n 5. Visualize them.\n \"\"\"\n #%matplotlib inline\n\n car_ind = np.random.randint(0, len(cars))\n notcar_ind = np.random.randint(0, len(notcars))\n\n car_image = mpimg.imread(cars[car_ind])\n notcar_image = mpimg.imread(notcars[notcar_ind])\n\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 = 0 # Can be 0,1,2, or \"ALL\"\n spatial_size = (32, 32) # spatial binning dimensions\n hist_bins = 16 # 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\n car_features, car_hog_image = single_img_features(car_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, vis=True)\n notcar_features, notcar_hog_image = single_img_features(notcar_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, vis=True)\n\n images = [car_image, car_hog_image, notcar_image, notcar_hog_image]\n titles = ['car image', 'car HOG image', 'notcar image', 'notcar HOG image']\n fig = plt.figure(figsize=(12, 3)) \n visualize(fig, 1, 4, images, titles)\n\n\ndef show_features(image):\n \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 = 0 # Can be 0,1,2, or \"ALL\"\n spatial_size = (32, 32) # spatial binning dimensions\n hist_bins = 16 # 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\n features, hog_image = 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, vis=True)\n return hog_image\n\ndef extract_features(imgs, color_space='RGB', spatial_size=(32, 32), hist_bins=32, \n orient=9, pix_per_cell=8, cell_per_block=2, hog_channel=0,\n spatial_feat=True, hist_feat=True, hog_feat=True):\n \"\"\"\n Extract the features of a list of images.\n \"\"\"\n features = []\n with tqdm(total=len(imgs), file=sys.stdout) as pbar:\n count=0\n for file in imgs:\n image = mpimg.imread(file)\n img_features = single_img_features(image, color_space, spatial_size,\n hist_bins, orient, \n pix_per_cell, cell_per_block, hog_channel,\n spatial_feat, hist_feat, hog_feat, vis=False)\n \n features.append(img_features)\n\n count += 1\n pbar.set_description('processed: %d' % (count))\n pbar.update(1)\n return features\n\ndef train_model(cars, notcars,\n color_space='YCrCb', spatial_size=(32, 32), hist_bins=32,\n orient=9, pix_per_cell=8, cell_per_block=2, hog_channel=0,\n spatial_feat=True, hist_feat=True, hog_feat=True,\n n_samples=0):\n \"\"\"\n Function to train a SVC classifier from extracted features of images.\n \n 1. Collects training data and extracts features using `extract_features`.\n 2. Normalizes data using `sklearn.preprocessing.StandardScaler`.\n 3. Splits data into train/test set using sklearn.model_selection.train_test_split, and\n 4. Creates a LinearSVC model.\n 5. train and computes accuracy on test set.\n 6. Returns the model and the scaler.\n \"\"\"\n t = time.time()\n if n_samples > 0:\n test_cars = np.array(cars)[np.random.randint(0, len(cars), n_samples)]\n test_notcars = np.array(notcars)[np.random.randint(0, len(notcars), n_samples)]\n else:\n test_cars = cars\n test_notcars = notcars\n print(\"Extracting car photo features...\")\n car_features = extract_features(test_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 print(\"Done\")\n print(\"Extracting non-car photo features...\")\n notcar_features = extract_features(test_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 print(\"Done\")\n t_features = time.time() - t\n \n print(\"Normalizing the features ... \", end='')\n # Normalize features\n X = np.vstack((car_features, notcar_features)).astype(np.float64)\n \n X_scaler = StandardScaler().fit(X)\n scaled_X = X_scaler.transform(X)\n print(\"Done\")\n\n print(\"Training the model ...\", end='')\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 X_train, X_test, y_train, y_test = train_test_split(scaled_X, y, test_size=0.2)\n\n # Use a linear SVC and train\n svc = LinearSVC()\n t = time.time()\n svc.fit(X_train, y_train)\n t_training = round(time.time() - t, 2)\n print(\"Done\")\n \n # computes the accuracy\n accuracy = round(svc.score(X_test, y_test), 4)\n \n print('color:{}'.format(color_space), 'spatial_size:', spatial_size, \n 'orient:{}, hog:{}, hist:{}, feat:{}, time: {}s, acc: {}'.format(\n orient, hog_channel, hist_bins, \n len(X_train[0]), \n t_training, accuracy))\n\n return svc, X_scaler\n\ndef run_train_model(cars, notcars):\n print(\"Test training model...\")\n for color_space in ['RGB', 'YCrCb']:\n for spatial_size in [(16, 16), (32, 32)]:\n for hist_bins in [16, 32]:\n for orient in [9, 12]:\n for hog_channel in [0,'ALL']:\n train_model(cars, notcars, color_space=color_space,\n spatial_size=spatial_size, \n hist_bins=hist_bins, orient=orient, \n pix_per_cell=8, cell_per_block=2,\n hog_channel=hog_channel,\n spatial_feat=True, hist_feat=True,\n hog_feat=True, n_samples=1000)\n\ndef save_model(model, scaler):\n \"\"\"\n Pickles the model and save it to file system.\n \"\"\"\n with open('./classifier.pkl', 'wb') as fp:\n data = {\n 'model': model,\n 'scaler': scaler\n }\n pickle.dump(data, fp)\n\ndef load_model():\n \"\"\"\n Loads an existing trained model.\n \"\"\"\n with open('./classifier.pkl', 'rb') as fp:\n data = pickle.load(fp)\n return data['model'], data['scaler']\n\ndef slide_window(img, x_start_stop=[None, None], y_start_stop=[400, 656], \n xy_window=(64, 64), xy_overlap=(0.5, 0.5)):\n \"\"\"\n This function takes an image, start and stop positions in both x and y, \n window size (x and y dimensions), and overlap fraction (for both x and y)\n \"\"\"\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 \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\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 \n # Compute the number of windows in x/y\n nx_windows = np.int(xspan/nx_pix_per_step) - 1\n ny_windows = np.int(yspan/ny_pix_per_step) - 1\n \n # Initialize a list to append window positions to\n window_list = []\n \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 \n # Append window position to list\n window_list.append(((startx, starty), (endx, endy)))\n\n return window_list\n\ndef search_windows(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 Given an image and the list of windows to be \n searched (output of slide_windows()),\n returns windows for positive detections:\n \n Foreach window in list:\n 1. Extract the test window from original image\n 2. Extract features for that window using single_img_features()\n 3. Scale extracted features to be fed to classifier.\n 4. Predict using your classifier.\n 5. If positive (prediction == 1) then save the window.\n \"\"\"\n on_windows = []\n off_windows = []\n for window in windows: \n test_img = cv2.resize(img[window[0][1]:window[1][1], window[0][0]:window[1][0]], (64, 64)) \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 test_features = scaler.transform(np.array(features).reshape(1, -1))\n prediction = clf.predict(test_features)\n if prediction == 1:\n on_windows.append(window)\n else:\n off_windows.append(window)\n \n return on_windows, off_windows\n\n\ndef test_slide_window(example_images, model, scaler, xy_window=(128, 128), xy_overlap=(0.5, 0.5),\n color_space='YCrCb', spatial_size=(16, 16), hist_bins=32, \n orient=12, pix_per_cell=8, cell_per_block=2, hog_channel='ALL', \n spatial_feat=True, hist_feat=True, hog_feat=True):\n\n print(\"Testing with window size:\", xy_window)\n images = []\n titles = []\n\n for img_src in example_images:\n t1 = time.time()\n img = mpimg.imread(img_src)\n draw_img = np.copy(img)\n\n img = img.astype(np.float32) / 255\n\n windows = slide_window(img, xy_window=xy_window, xy_overlap=xy_overlap)\n\n hot_windows, cold_windows = search_windows(img, windows, model, scaler,\n color_space=color_space, \n spatial_size=spatial_size,\n hist_bins=hist_bins, \n orient=orient,\n pix_per_cell=pix_per_cell, \n cell_per_block=cell_per_block, \n hog_channel=hog_channel,\n spatial_feat=spatial_feat, \n hist_feat=hist_feat,\n hog_feat=hog_feat) \n\n\n window_img = draw_boxes(draw_img, cold_windows, color=(255,0, 0),\n thick=6)\n window_img = draw_boxes(window_img, hot_windows, color=(0, 255, 0),\n thick=6)\n #plt.imshow(window_img)\n #plt.show()\n images.append(window_img)\n titles.append('')\n # print(time.time() - t1, 'seconds to process one image searching', len(windows), 'windows')\n\n fig = plt.figure(figsize=(18, 18), dpi=300)\n visualize(fig, 5, 2, images, titles);\n \n# test model on one image\ndef test_model(image, model, scaler):\n features = single_img_features(image, color_space='YCrCb',\n spatial_size=(16,16),\n hist_bins=32, orient=12, pix_per_cell=8,\n cell_per_block=2, hog_channel='ALL',\n spatial_feat=True, hist_feat=True,\n hog_feat=True, )\n\n test_features = scaler.transform(np.array(features).reshape(1, -1))\n\n prediction = model.predict(test_features)\n\n return prediction\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\ndef draw_labeled_bboxes(image, labels):\n \"\"\"\n Given an image and a list of detected cars, the\n function iterates through all detected cars:\n 1. Find pixels with each car_number label value.\n 2. Identify x and y values of those pixels.\n 3. Define a bounding box based on min/max x and y.\n 4. Draw the box on the image.\n Returns a copy of the image with bounding boxes.\n \"\"\"\n img = np.copy(image)\n for car_number in range(1, labels[1]+1):\n nonzero = (labels[0] == car_number).nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n bbox = ((np.min(nonzerox), np.min(nonzeroy)), (np.max(nonzerox), np.max(nonzeroy)))\n cv2.rectangle(img, bbox[0], bbox[1], (0,255,0), 6)\n return img\n\ndef find_cars(img, model, scaler, ystart, ystop, scale, spatial_size=(16, 16),\n hist_bins=32, orient=12, pix_per_cell=8, cell_per_block=2):\n \"\"\"\n Function to detect cars in images. It uses approaches from \n the previous functions and methodologies, and some improvements\n are introduced:\n 1. Instead of using different window sizes we're resizing the whole image.\n 2. Compute individual channel HOG features for the entire image, \n once rather than computing for small portions of the image.\n 3. It creates a heatmap image based on the prediction boxes.\n \"\"\"\n draw_img = np.copy(img)\n heatmap = np.zeros_like(img[:,:,0])\n img = img.astype(np.float32) / 255\n img_boxes = []\n \n img_tosearch = img[ystart:ystop,:,:]\n ctrans_tosearch = convert_color(img_tosearch, conv='RGB2YCrCb')\n \n if scale != 1:\n imshape = ctrans_tosearch.shape\n ctrans_tosearch = cv2.resize(ctrans_tosearch, (np.int(imshape[1]/scale), np.int(imshape[0]/scale)))\n \n ch1 = ctrans_tosearch[:,:,0]\n ch2 = ctrans_tosearch[:,:,1]\n ch3 = ctrans_tosearch[:,:,2]\n \n nxblocks = (ch1.shape[1] // pix_per_cell) - 1\n nyblocks = (ch1.shape[0] // pix_per_cell) - 1\n nfeat_per_block = orient * cell_per_block ** 2\n window = 64\n nblocks_per_window = (window // pix_per_cell) - 1\n cells_per_step = 2 # instead of overlap, define how many cells to step\n nxsteps = (nxblocks - nblocks_per_window) // cells_per_step\n nysteps = (nyblocks - nblocks_per_window) // cells_per_step\n \n hog1 = get_hog_features(ch1, orient, pix_per_cell, cell_per_block, feature_vec=False)\n hog2 = get_hog_features(ch2, orient, pix_per_cell, cell_per_block, feature_vec=False)\n hog3 = get_hog_features(ch3, orient, pix_per_cell, cell_per_block, feature_vec=False)\n \n # Sliding window implementation\n for xb in range(nxsteps):\n for yb in range(nysteps):\n ypos = yb * cells_per_step\n xpos = xb * cells_per_step\n\n # extract HOG for this patch\n hog_feat1 = hog1[ypos:ypos + nblocks_per_window, xpos:xpos+nblocks_per_window].ravel()\n hog_feat2 = hog2[ypos:ypos + nblocks_per_window, xpos:xpos+nblocks_per_window].ravel()\n hog_feat3 = hog3[ypos:ypos + nblocks_per_window, xpos:xpos+nblocks_per_window].ravel()\n hog_features = np.hstack((hog_feat1, hog_feat2, hog_feat3))\n \n xleft = xpos * pix_per_cell\n ytop = ypos * pix_per_cell\n \n #extract the image patch\n subimg = cv2.resize(\n ctrans_tosearch[ytop:ytop+window, xleft:xleft+window], \n (64, 64)\n )\n \n # get color features\n spatial_features = bin_spatial(subimg, size=spatial_size)\n hist_features = color_hist(subimg, nbins=hist_bins)\n \n # scale features and make a prediction\n test_features = scaler.transform(np.hstack((spatial_features, hist_features, hog_features)).reshape(1,-1))\n test_prediction = model.predict(test_features)\n \n if test_prediction == 1:\n xbox_left = np.int(xleft * scale)\n ytop_draw = np.int(ytop * scale)\n win_draw = np.int(window * scale)\n cv2.rectangle(draw_img, \n (xbox_left, ytop_draw + ystart), \n (xbox_left + win_draw, ytop_draw + ystart + win_draw),\n (0,255,0), 6)\n img_boxes.append((\n (xbox_left, ytop_draw + ystart),\n (xbox_left + win_draw, ytop_draw + ystart + win_draw)))\n heatmap[ytop_draw+ystart:ytop_draw+win_draw+ystart,\n xbox_left:xbox_left+win_draw] += 1\n\n return draw_img, heatmap, img_boxes\n\nclass VideoProcessor():\n \"\"\"\n Quick and dirty class toprocess each video frame.\n It uses other functions from the previous blocks of code\n in this notebook.\n \"\"\"\n def __init__(self, model, scaler):\n self.frame_number = 0\n self._heatmaps = deque(maxlen=5)\n self.model = model\n self.scaler = scaler\n \n def process_image(self, img):\n \"\"\"\n Find vehicles into it, given an undistorted image.\n \"\"\"\n out_img, heatmap, _ = find_cars(img, self.model, self.scaler, 400,\n 656, 1.5)\n self._heatmaps.append(heatmap)\n \n if len(self._heatmaps) < 5:\n return img\n\n # Calculate the average of the last heatmaps\n heatmaps = np.sum(np.array(self._heatmaps), axis=0).astype(np.float32)\n heatmaps = apply_threshold(heatmaps, 4)\n labels = label(heatmaps)\n draw_img = draw_labeled_bboxes(img, labels)\n \n return draw_img\n\ndef process_image(img, video_processor):\n \"\"\"\n Function to process a frame of the video.\n It returns the image with overlayed boxes on detected cars.\n \"\"\"\n draw_img = video_processor.process_image(img)\n return draw_img\n\ndef playvideo(filename):\n video = io.open(filename, 'r+b').read()\n encoded = base64.b64encode(video)\n return HTML(data=''''''.format(encoded.decode('ascii')))\n\ndef download_data():\n # download vehicle photos\n dw_cmd1 = [\"wget\", \"https://tinyurl.com/y39psq9c\", \n \"-O\", \"vehicles.zip\"]\n output = subprocess.Popen(dw_cmd1, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n stdout,stderr=output.communicate()\n #print(stdout.decode())\n if not (stderr is None):\n print(stderr.decode())\n\n # unzip vehicle photos\n unzip_cmd1=[\"unzip\", \"vehicles.zip\"]\n output = subprocess.Popen(unzip_cmd1, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n stdout,stderr=output.communicate()\n print(\"Vehicle files downloaded and unzipped\")\n if not (stderr is None):\n print(stderr.decode())\n\n # download non-vehicle photos\n dw_cmd1 = [\"wget\", \"https://tinyurl.com/y2ary7q7\", \n \"-O\", \"non-vehicles.zip\"]\n output = subprocess.Popen(dw_cmd1, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n stdout,stderr=output.communicate()\n #print(stdout.decode())\n if not (stderr is None):\n print(stderr.decode())\n\n # unzip non-vehicle photos\n unzip_cmd1=[\"unzip\", \"non-vehicles.zip\"]\n output = subprocess.Popen(unzip_cmd1, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n stdout,stderr=output.communicate()\n print(\"Non-vehicle file downloaded and unzipped\")\n if not (stderr is None):\n print(stderr.decode())\n\ndef load_training_images():\n # load vehicle images\n cars = load_images('./vehicles/')\n print('Number of vehicle images found: {}'.format(len(cars)))\n\n # load non vehicle images\n notcars = load_images('./non-vehicles/')\n print('Number of non-vehicle images found: {}'.format(len(notcars)))\n\n # load images for testing\n searchpath = 'ML_CV_Teaching/vehicle_detection/test_images/*'\n example_images = glob.glob(searchpath)\n print('Number of example images: {}'.format(len(example_images)))\n\n return cars, notcars, example_images\n\ndef show_random_car_image(cars):\n car_idx = random.randint(0,len(cars))\n car_img = mpimg.imread(cars[car_idx])\n car_feature_img = show_features(car_img)\n print(\"Showing one random car image:\")\n plt.imshow(car_img)\n plt.show()\n plt.imshow(car_feature_img)\n\ndef show_random_notcar_image(notcars):\n # show the features of the above non-vehicle picture\n not_car_idx = random.randint(0,len(notcars))\n not_car_img = mpimg.imread(notcars[not_car_idx])\n not_car_feature_img = show_features(not_car_img)\n print(\"Showing one random not car image:\")\n plt.imshow(not_car_img)\n plt.show()\n plt.imshow(not_car_feature_img)\n\ndef train_car_model(cars, notcars):\n model, scaler = train_model(cars, notcars,\n color_space='YCrCb',\n spatial_size=(16, 16), hist_bins=32,\n orient=12, \n pix_per_cell=8, cell_per_block=2,\n hog_channel='ALL', spatial_feat=True, \n hist_feat=True, \n hog_feat=True, \n n_samples=0)\n return model, scaler\n\ndef test_model_on_random_iage(cars, notcars, model, scaler):\n if random.choice([True, False]):\n imgs = cars\n else:\n imgs = notcars\n \n car_idx = random.randint(0,len(imgs))\n car_img = mpimg.imread(imgs[car_idx])\n plt.imshow(car_img)\n is_car = test_model(car_img, model, scaler)\n if is_car:\n print(\"AI says this is a vehicle\")\n else:\n print(\"AI says this is not a vehicle.\")\n\n\ndef test_on_static_frames(model, scaler, example_images, xy_window=(128,128)):\n # with 128x128 sliding windows\n for i in range(len(example_images)):\n test_slide_window(example_images[i:i+1], model, scaler,\n xy_window, xy_overlap=(0.5, 0.5))\n\ndef load_video_clip1():\n # short video\n clip1_path = \"ML_CV_Teaching/vehicle_detection/test_video.mp4\"\n clip = VideoFileClip(clip1_path)\n #playvideo(\"ML_CV_Teaching/vehicle_detection/test_video.mp4\")\n\n return clip, clip1_path\n\ndef process_video_clip1(clip, model, scaler):\n video_processor = VideoProcessor(model, scaler)\n output_video = \"./test_video_out.mp4\"\n output_clip = clip.fl_image(lambda image: process_image(image,video_processor))\n output_clip.write_videofile(output_video, audio=False)\n\n #playvideo(output_video)\n\n return output_video\n\ndef load_video_clip2():\n # long video\n clip2_path = \"./ML_CV_Teaching/vehicle_detection/project_video.mp4\"\n clip = VideoFileClip(\"./ML_CV_Teaching/vehicle_detection/project_video.mp4\")\n #playvideo(\"./ML_CV_Teaching/vehicle_detection/project_video.mp4\")\n\n return clip, clip2_path\n \ndef process_video_clip2(clip, model, scaler):\n video_processor = VideoProcessor(model, scaler)\n output_video = \"./project_video_out.mp4\"\n output_clip = clip.fl_image(lambda image: process_image(image,video_processor))\n output_clip.write_videofile(output_video, audio=False)\n\n #playvideo(output_video)\n\n return (output_video)\n\n\ndef load_video_clip3():\n # long video\n clip2_path = \"./ML_CV_Teaching/vehicle_detection/Shorter Video.mp4\"\n clip = VideoFileClip(clip2_path)\n #playvideo(\"./ML_CV_Teaching/vehicle_detection/project_video.mp4\")\n\n return clip, clip2_path\n \ndef process_video_clip3(clip, model, scaler):\n video_processor = VideoProcessor(model, scaler)\n output_video = \"./shorter_video_out.mp4\"\n output_clip = clip.fl_image(lambda image: process_image(image,video_processor))\n output_clip.write_videofile(output_video, audio=False)\n\n #playvideo(output_video)\n\n return (output_video)\n \n","sub_path":"vehicle_detection/car_detect_pkg.py","file_name":"car_detect_pkg.py","file_ext":"py","file_size_in_byte":34418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"395138401","text":"#!/usr/bin/python3\n\nimport re\nimport sys\nfrom select import select\n\n\n# Checks each word for validity and then adds up their dominant letter totals.\ndef get_dominant_letter_count(word_list, valid_word):\n \"\"\"\n :param word_list: a list of words composing a sentence.\n :param valid_word: a regex string defining the acceptance criteria being matched.\n :return: returns the total of dominant characters across all words in the sentence.\n \"\"\"\n total = 0\n for word in word_list:\n if valid_word.match(word):\n # Find max count for each word.\n max_count = max([word.count(x) for x in word])\n # Add the dominant counts up.\n total += max_count\n return total\n\n\ndef main():\n sentences = ''\n\n # Check the number of arguments to see if a filename was provided as input.\n if len(sys.argv) > 1:\n # Enforces the input file extensions.\n if sys.argv[1].lower().endswith('.txt'):\n try:\n fin = open(sys.argv[1], 'r')\n sentences = fin.read().lower()\n # Catches file IO errors where the file does not exist.\n except IOError:\n print('ERROR: Invalid filename. File could not be found.')\n return\n # Catches all invalid filename extension types.\n else:\n print('ERROR: Invalid input file extension. Only accepts \\'.txt\\' files.')\n return\n\n # Checks to see if stdin has been assigned to a device, i.e. input was provided.\n elif select([sys.stdin,], [], [], 0.0)[0]:\n sentences = sys.stdin.read().lower()\n\n # Creates a list of words by splitting the input using whitespace as a delimiter.\n word_list = sentences.split()\n # Regex expression that accepts only alphabetic strings possibly sandwiched by whitespace\n valid_word = re.compile('^\\s?[a-zA-Z]+\\s?$',)\n\n # Total number of dominant letters from all words across all sentences.\n count = get_dominant_letter_count(word_list, valid_word)\n print(count)\n return count\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"domletters.py","file_name":"domletters.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"179305009","text":"# Copyright 2019 Huawei Technologies Co., Ltd\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ============================================================================\r\n\r\nimport numpy as np\r\nimport pytest\r\n\r\nimport mindspore.context as context\r\nimport mindspore.nn as nn\r\nfrom mindspore import Tensor\r\nfrom mindspore.common import dtype as mstype\r\nfrom mindspore.common.initializer import initializer\r\nfrom mindspore.common.parameter import Parameter\r\nfrom mindspore.ops import operations as P\r\n\r\ncontext.set_context(mode=context.GRAPH_MODE, device_target=\"CPU\")\r\n\r\n\r\nclass NetArgmax(nn.Cell):\r\n def __init__(self):\r\n super(NetArgmax, self).__init__()\r\n self.argmax = P.Argmax(output_type=mstype.int32)\r\n x = Tensor(np.array([[1., 20., 5.],\r\n [67., 8., 9.],\r\n [130., 24., 15.]]).astype(np.float32))\r\n self.x = Parameter(initializer(x, x.shape()), name='x')\r\n\r\n def construct(self):\r\n return self.argmax(self.x)\r\n\r\n\r\n@pytest.mark.level0\r\n@pytest.mark.platform_x86_cpu\r\n@pytest.mark.env_onecard\r\ndef test_argmax():\r\n Argmax = NetArgmax()\r\n output = Argmax()\r\n print(\"================================\")\r\n expect = np.array([1, 0, 0]).astype(np.float32)\r\n print(output)\r\n assert (output.asnumpy() == expect).all()\r\n","sub_path":"tests/st/ops/cpu/test_argmax_op.py","file_name":"test_argmax_op.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"146714391","text":"from pygame import *\nfrom pygame.locals import *\nimport sys\nfrom time import sleep\nimport numpy as np\nimport random\nimport tensorflow as tf\nfrom pylab import savefig\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\n\"\"\"\n\n******Refined Game Program. Now finally working properly!******\n\n------Agent------\n\nConvolutional Neural Nets: No\nLayers: 1\nExperience Replay: Yes\nPlayers: Square\nParameters: 9\nBullet: Beam\nActivation Function: Linear\nTarget Network: Yes\n\"\"\"\n\narena_size = 500\n\n#Screen Setup\ndisp_x, disp_y = 1000, 800\narena_x = arena_y = arena_size\nborder = 4; border_2 = 1\n\n#Color Setup\nwhite = (255, 255, 255); aqua= (0, 200, 200)\nred = (255, 0, 0); green = (0, 255, 0)\nblue = (0, 0, 255); black = (0, 0, 0)\ngreen_yellow = (173, 255, 47); energy_blue = (125, 249, 255)\n\n#Initialize character positions\ninit_character_a_state = [disp_x/2 - arena_x/2 + 50, disp_y/2 - arena_y/2 + 50]\ninit_character_b_state = [disp_x/2 + arena_x/2 - 50, disp_y/2 + arena_y/2 - 50]\n\n#Setup character dimentions\ncharacter_size = 50\ncharacter_move_speed = 50\n\n#Initialize character stats\ncharacter_init_health = 100\n\n#initialize bullet stats\nbeam_damage = 20\nbeam_width = 20\nbeam_ob = -100\nbeam_cooldown_time = 5\n\n\nclass Agent_Init:\n #The Neural Network\n def __init__(self):\n self.input_layer = tf.placeholder(shape=[1,10],dtype=tf.float32)\n self.weight_1 = tf.Variable(tf.random_uniform([10,9],0,0.01))\n self.Q = tf.matmul(self.input_layer, self.weight_1)\n self.predict = tf.argmax(self.Q, 1)\n self.next_Q = tf.placeholder(shape=[1,9],dtype=tf.float32)\n self.loss = tf.reduce_sum(tf.square(self.next_Q - self.Q))\n self.trainer = tf.train.GradientDescentOptimizer(learning_rate=0.001)\n self.updateModel = self.trainer.minimize(self.loss)\n self.target_input_layer = tf.placeholder(shape=[1,10],dtype=tf.float32)\n self.target_weight_1 = tf.Variable(tf.random_uniform([10,9],0,0.01))\n self.target_Q = tf.matmul(self.target_input_layer, self.target_weight_1)\n self.target_next_Q = tf.placeholder(shape=[1,9],dtype=tf.float32)\n self.sess = tf.Session()\n self.saver = tf.train.Saver()\n\nagent_1 = Agent_Init()\ninitialize = tf.global_variables_initializer()\n\njList = []\nrList = []\n\ninit()\nfont.init()\nmyfont = font.SysFont('Comic Sans MS', 15)\nmyfont2 = font.SysFont('Comic Sans MS', 150)\nmyfont3 = font.SysFont('Gothic', 30)\ndisp = display.set_mode((disp_x, disp_y), 0, 32)\n\n#CHARACTER/BULLET PARAMETERS\nagent_x = agent_y = int()\nbot_x = bot_y = int()\nagent_hp = bot_hp = int()\nbot_beam_dir = int()\nagent_beam_fire = bot_beam_fire = bool()\nagent_beam_x = bot_beam_x = agent_beam_y = bot_beam_y = int()\nagent_beam_size_x = agent_beam_size_y = bot_beam_size_x = bot_beam_size_y = int()\nagent_beam_cooldown = bot_beam_cooldown = int()\nagent_beam_cooldown_active = bot_beam_cooldown_active = bool()\nbot_current_action = agent_current_action = int()\n\n\ndef param_init():\n \"\"\"Initializes parameters\"\"\"\n global agent_x, agent_y, bot_x, bot_y, agent_hp, bot_hp, agent_beam_fire, bot_beam_fire, agent_beam_x, bot_beam_x, agent_beam_y, bot_beam_y\n\n agent_x = list(init_character_a_state)[0]; agent_y = list(init_character_a_state)[1]\n bot_x = list(init_character_b_state)[0]; bot_y = list(init_character_b_state)[1]\n agent_hp = bot_hp = character_init_health\n agent_beam_fire = bot_beam_fire = False\n agent_beam_x = bot_beam_x = agent_beam_y = bot_beam_y = beam_ob\n agent_beam_size_x = agent_beam_size_y = bot_beam_size_x = bot_beam_size_y = 0\n agent_beam_cooldown = bot_beam_cooldown = 0\n agent_beam_cooldown_active = bot_beam_cooldown_active = False\n\n\n\ndef screen_blit():\n global disp, disp_x, disp_y, arena_x, arena_y, border, border_2, character_size, agent_x, \\\n agent_y, bot_x, bot_y, character_init_health, agent_hp, bot_hp, red, blue, aqua, green, black, green_yellow, energy_blue, \\\n agent_beam_fire, bot_beam_fire, agent_beam_x, agent_beam_y, bot_beam_x, bot_beam_y, agent_beam_size_x, agent_beam_size_y, \\\n bot_beam_size_x, bot_beam_size_y, beam_width, agent_beam_cooldown, bot_beam_cooldown\n\n agent_beam_cooldown_disp = myfont.render(('Cooldown: %d' % agent_beam_cooldown), 1, white)\n bot_beam_cooldown_disp = myfont.render(('Cooldown: %d' % bot_beam_cooldown), 1, white)\n disp.fill(black)\n draw.rect(disp, white, (disp_x / 2 - arena_x / 2 - border, disp_y /\n 2 - arena_y / 2 - border, arena_x + border * 2, arena_y + border * 2))\n draw.rect(disp, black, (disp_x / 2 - arena_x / 2,\n disp_y / 2 - arena_y / 2, arena_x, arena_y))\n if bot_beam_fire == True:\n draw.rect(disp, energy_blue, (bot_beam_x, bot_beam_y, bot_beam_size_x, bot_beam_size_y))\n bot_beam_size_x = bot_beam_size_y = 0\n bot_beam_x = bot_beam_y = beam_ob\n bot_beam_fire = False\n if agent_beam_fire == True:\n draw.rect(disp, green_yellow, (agent_beam_x, agent_beam_y, agent_beam_size_x, agent_beam_size_y))\n agent_beam_size_x = agent_beam_size_y = 0\n agent_beam_x = agent_beam_y = beam_ob\n agent_beam_fire = False\n\n draw.rect(disp, red, (agent_x, agent_y, character_size, character_size))\n draw.rect(disp, blue, (bot_x, bot_y, character_size, character_size))\n\n draw.rect(disp, red, (disp_x / 2 - arena_x / 2 - border, disp_y / 2 + arena_y / 2 +\n border + border_2, float(agent_hp) / float(character_init_health) * 100, 10))\n draw.rect(disp, blue, (disp_x / 2 + arena_x / 2 + border - 100, disp_y / 2 + arena_y / 2 +\n border + border_2, float(bot_hp) / float(character_init_health) * 100, 10))\n disp.blit(agent_beam_cooldown_disp, (disp_x / 2 - arena_x / 2 - border, disp_y / 2 + arena_y / 2 +\n border * 2 + 10 + border_2))\n disp.blit(bot_beam_cooldown_disp, (disp_x / 2 + arena_x / 2 + border - 100, disp_y / 2 + arena_y / 2 +\n border * 2 + 10 + border_2))\n\n\ndef beam_hit_detector(player):\n global agent_x, agent_y, bot_x, bot_y, agent_beam_fire, bot_beam_fire, agent_beam_x, \\\n bot_beam_x, agent_beam_y, bot_beam_y, agent_beam_size_x, agent_beam_size_y, \\\n bot_beam_size_x, bot_beam_size_y, bot_current_action, agent_current_action, beam_width, character_size\n\n if player == \"bot\":\n if bot_current_action == 1:\n return disp_y/2 - arena_y/2 <= agent_y <= bot_y and (agent_x < bot_beam_x + beam_width < agent_x + character_size or agent_x < bot_beam_x < agent_x + character_size)\n elif bot_current_action == 2:\n return bot_x <= agent_x <= disp_x/2 + arena_x/2 and (agent_y < bot_beam_y + beam_width < agent_y + character_size or agent_y < bot_beam_y < agent_y + character_size)\n elif bot_current_action == 3:\n return bot_y <= agent_y <= disp_y/2 + arena_y/2 and (agent_x < bot_beam_x + beam_width < agent_x + character_size or agent_x < bot_beam_x < agent_x + character_size)\n elif bot_current_action == 4:\n return disp_x/2 - arena_x/2 <= agent_x <= bot_x and (agent_y < bot_beam_y + beam_width < agent_y + character_size or agent_y < bot_beam_y < agent_y + character_size)\n else:\n if agent_current_action == 1:\n return disp_y/2 - arena_y/2 <= bot_y <= agent_y and (bot_x < agent_beam_x + beam_width < bot_x + character_size or bot_x < agent_beam_x < bot_x + character_size)\n elif agent_current_action == 2:\n return agent_x <= bot_x <= disp_x/2 + arena_x/2 and (bot_y < agent_beam_y + beam_width < bot_y + character_size or bot_y < agent_beam_y < bot_y + character_size)\n elif agent_current_action == 3:\n return agent_y <= bot_y <= disp_y/2 + arena_y/2 and (bot_x < agent_beam_x + beam_width < bot_x + character_size or bot_x < agent_beam_x < bot_x + character_size) \n elif agent_current_action == 4:\n return disp_x/2 - arena_x/2 <= bot_x <= agent_x and (bot_y < agent_beam_y + beam_width < bot_y + character_size or bot_y < agent_beam_y < bot_y + character_size)\n\n\n\"\"\"\ndef mapping(maximum, number):\n return int(number * maximum)\n\"\"\"\ndef action(agent_action, bot_action):\n global agent_x, agent_y, bot_x, bot_y, agent_hp, bot_hp, agent_beam_fire, \\\n bot_beam_fire, agent_beam_x, bot_beam_x, agent_beam_y, bot_beam_y, agent_beam_size_x, \\\n agent_beam_size_y, bot_beam_size_x, bot_beam_size_y, beam_width, agent_current_action, \\\n bot_current_action, character_size, agent_beam_cooldown, agent_beam_cooldown_active, \\\n bot_beam_cooldown, bot_beam_cooldown_active, beam_cooldown_time\n\n agent_current_action = agent_action; bot_current_action = bot_action\n reward = reward2 = 0\n cont = True; \n successful_agent_1 = successful_agent_2 = False\n winner = \"\"\n if 1 <= bot_action <= 4:\n if bot_beam_cooldown_active == False:\n bot_beam_fire = True\n bot_beam_cooldown_active = True\n bot_beam_cooldown = beam_cooldown_time\n if bot_action == 1:\n if bot_y > disp_y/2 - arena_y/2:\n bot_beam_x = bot_x + character_size/2 - beam_width/2; bot_beam_y = disp_y/2 - arena_y/2\n bot_beam_size_x = beam_width; bot_beam_size_y = bot_y - disp_y/2 + arena_y/2\n else:\n reward2 += -5\n elif bot_action == 2:\n if bot_x + character_size < disp_x/2 + arena_x/2:\n bot_beam_x = bot_x + character_size; bot_beam_y = bot_y + character_size/2 - beam_width/2\n bot_beam_size_x = disp_x/2 + arena_x/2 - bot_x - character_size; bot_beam_size_y = beam_width\n else:\n reward2 += -5\n elif bot_action == 3:\n if bot_y + character_size < disp_y/2 + arena_y/2:\n bot_beam_x = bot_x + character_size/2 - beam_width/2; bot_beam_y = bot_y + character_size\n bot_beam_size_x = beam_width; bot_beam_size_y = disp_y/2 + arena_y/2 - bot_y - character_size\n else:\n reward2 += -5\n elif bot_action == 4:\n if bot_x > disp_x/2 - arena_x/2:\n bot_beam_x = disp_x/2 - arena_x/2; bot_beam_y = bot_y + character_size/2 - beam_width/2\n bot_beam_size_x = bot_x - disp_x/2 + arena_x/2; bot_beam_size_y = beam_width\n else:\n reward2 += -5\n else:\n reward2 -= 5\n if 1 <= agent_action <= 4:\n if agent_beam_cooldown_active == False:\n agent_beam_fire = True\n agent_beam_cooldown_active = True\n agent_beam_cooldown = beam_cooldown_time\n if agent_action == 1:\n if agent_y > disp_y/2 - arena_y/2:\n agent_beam_x = agent_x + character_size/2 - beam_width/2; agent_beam_y = disp_y/2 - arena_y/2\n agent_beam_size_x = beam_width; agent_beam_size_y = agent_y - disp_y/2 + arena_y/2\n else:\n reward += -5\n elif agent_action == 2:\n if agent_x + character_size < disp_x/2 + arena_x/2:\n agent_beam_x = agent_x + character_size; agent_beam_y = agent_y + character_size/2 - beam_width/2\n agent_beam_size_x = disp_x/2 + arena_x/2 - agent_x - character_size; agent_beam_size_y = beam_width\n else:\n reward += -5\n elif agent_action == 3:\n if agent_y + character_size < disp_y/2 + arena_y/2:\n agent_beam_x = agent_x + character_size/2 - beam_width/2; agent_beam_y = agent_y + character_size\n agent_beam_size_x = beam_width; agent_beam_size_y = disp_y/2 + arena_y/2 - agent_y - character_size\n else:\n reward += -5\n elif agent_action == 4:\n if agent_x > disp_x/2 - arena_x/2:\n agent_beam_x = disp_x/2 - arena_x/2; agent_beam_y = agent_y + character_size/2 - beam_width/2\n agent_beam_size_x = agent_x - disp_x/2 + arena_x/2; agent_beam_size_y = beam_width\n else:\n reward += -5\n else:\n reward -= 5\n if bot_beam_fire == True:\n if beam_hit_detector(\"bot\"):\n #print(\"Agent Got Hit!\")\n agent_hp -= beam_damage\n reward += -20\n reward2 += 40\n if agent_hp <= 0:\n cont = False\n successful_agent_2 = True\n winner = \"Bot\"\n if bot_beam_cooldown_active == True:\n bot_beam_cooldown -= 1\n if bot_beam_cooldown == 0:\n bot_beam_cooldown_active = False\n\n if agent_beam_fire == True:\n if beam_hit_detector(\"agent\"):\n #print(\"Bot Got Hit!\")\n bot_hp -= beam_damage\n reward += 40\n reward2 -= 20\n if bot_hp <= 0:\n successful_agent_1 = True\n cont = False\n winner = \"Agent\"\n if agent_beam_cooldown_active == True:\n agent_beam_cooldown -= 1\n if agent_beam_cooldown == 0:\n agent_beam_cooldown_active = False\n\n if 5 <= bot_action <= 8:\n if bot_action == 5:\n bot_y -= character_move_speed\n if bot_y <= disp_y/2 - arena_y/2:\n bot_y = disp_y/2 - arena_y/2\n reward2 += -5\n elif agent_y <= bot_y <= agent_y + character_size and (agent_x <= bot_x < agent_x + character_size or bot_x <= agent_x < bot_x + character_size):\n bot_y = agent_y + character_size\n reward2 += -1\n elif bot_action == 6:\n bot_x += character_move_speed\n if bot_x >= disp_x/2 + arena_x/2 - character_size:\n bot_x = disp_x/2 + arena_x/2 - character_size\n reward2 += -5\n elif agent_x <= bot_x + character_size <= agent_x + character_size and (agent_y <= bot_y < agent_y + character_size or bot_y <= agent_y < bot_y + character_size):\n bot_x = agent_x - character_size\n reward2 += -1\n elif bot_action == 7:\n bot_y += character_move_speed\n if bot_y + character_size >= disp_y/2 + arena_y/2:\n bot_y = disp_y/2 + arena_y/2 - character_size\n reward2 += -5\n elif agent_y <= bot_y <= agent_y + character_size and (agent_x <= bot_x < agent_x + character_size or bot_x <= agent_x < bot_x + character_size):\n bot_y = agent_y - character_size\n reward2 += -1\n elif bot_action == 8:\n bot_x -= character_move_speed\n if bot_x <= disp_x/2 - arena_x/2:\n bot_x = disp_x/2 - arena_x/2\n reward2 += -5\n elif agent_x <= bot_x <= agent_x + character_size and (agent_y <= bot_y < agent_y + character_size or bot_y <= agent_y < bot_y + character_size):\n bot_x = agent_x + character_size\n reward2 += -1\n\n if 5 <= agent_action <= 8:\n if agent_action == 5:\n agent_y -= character_move_speed\n if agent_y <= disp_y/2 - arena_y/2:\n agent_y = disp_y/2 - arena_y/2\n reward += -5\n elif bot_y <= agent_y <= bot_y + character_size and (bot_x <= agent_x < bot_x + character_size or agent_x <= bot_x < agent_x + character_size):\n agent_y = bot_y + character_size\n reward += -1\n elif agent_action == 6:\n agent_x += character_move_speed\n if agent_x + character_size >= disp_x/2 + arena_x/2:\n agent_x = disp_x/2 + arena_x/2 - character_size\n reward += -5\n elif bot_x <= agent_x + character_size <= bot_x + character_size and (bot_y <= agent_y <= bot_y + character_size or agent_y <= bot_y < agent_y + character_size):\n agent_x = bot_x - character_size\n reward += -1\n elif agent_action == 7:\n agent_y += character_move_speed\n if agent_y + character_size >= disp_y/2 + arena_y/2:\n agent_y = disp_y/2 + arena_y/2 - character_size\n reward += -5\n elif bot_y <= agent_y + character_size <= bot_y + character_size and (bot_x <= agent_x < bot_x + character_size or agent_x <= bot_x < agent_x + character_size):\n agent_y = bot_y - character_size\n reward += -1\n elif agent_action == 8:\n agent_x -= character_move_speed\n if agent_x <= disp_x/2 - arena_x/2:\n agent_x = disp_x/2 - arena_x/2\n reward += -5\n elif bot_x <= agent_x <= bot_x + character_size and (bot_y <= agent_y <= bot_y + character_size or agent_y <= bot_y < agent_y + character_size):\n agent_x = bot_x + character_size\n reward += -1\n\n return reward, reward2, cont, successful_agent_1, successful_agent_2, winner\n\n\n#Parameters\ny = 0.75\ne1 = e2 = 0.3\nnum_episodes = 10000\nbatch_size = 25\n\nagent_1.sess.run(initialize)\nturn_count = 0\nfor i in tqdm(range(1, num_episodes)):\n rAll = 0; d = False; c = True; j = 0\n param_init()\n samples_agent_1 = []\n while c == True:\n j += 1\n turn_count += 1 \n current_state_agent_1 = np.array([[float(agent_x - disp_x/2 + arena_x/2) / float(arena_x),\n float(agent_y - disp_y/2 + arena_y/2) / float(arena_y),\n float(bot_x - disp_x/2 + arena_x/2) / float(arena_x),\n float(bot_y - disp_y/2 + arena_y/2) / float(arena_y),\n float(bot_x - agent_x) / float(arena_x),\n float(bot_y - agent_y) / float(arena_y),\n float(agent_beam_cooldown) / float(beam_cooldown_time),\n agent_beam_cooldown_active,\n float(bot_beam_cooldown) / float(beam_cooldown_time),\n bot_beam_cooldown_active\n ]])\n\n if np.random.rand(1) < e1:\n a = np.array([random.randint(0, 8)])\n else:\n a, _ = agent_1.sess.run([agent_1.predict, agent_1.Q],feed_dict={agent_1.input_layer : current_state_agent_1})\n\n b = np.array([random.randint(0, 8)])\n r, r2, c, d, d2, winner = action(a + 1, b + 1)\n next_state_agent_1 = np.array([[float(agent_x - disp_x / 2 + arena_x / 2) / float(arena_x),\n float(agent_y - disp_y / 2 +arena_y / 2) / float(arena_y),\n float(bot_x - disp_x / 2 + arena_x / 2) / float(arena_x),\n float(bot_y - disp_y / 2 + arena_y / 2) / float(arena_y),\n float(bot_x - agent_x) / float(arena_x),\n float(bot_y - agent_y) / float(arena_y),\n float(agent_beam_cooldown) / float(beam_cooldown_time),\n agent_beam_cooldown_active,\n float(bot_beam_cooldown) / float(beam_cooldown_time),\n bot_beam_cooldown_active\n ]])\n\n samples_agent_1.append([current_state_agent_1, a, r, next_state_agent_1, d])\n\n if len(samples_agent_1) > batch_size:\n for count in range(batch_size):\n [batch_current_state, action_taken, reward, batch_next_state, terminal] = samples_agent_1[random.randint(0, len(samples_agent_1) - 1)]\n if turn_count % 50 == 0:\n agent_1.target_weight_1 = agent_1.weight_1\n batch_allQ = agent_1.sess.run(agent_1.target_Q, feed_dict={agent_1.target_input_layer : batch_current_state})\n batch_Q1 = agent_1.sess.run(agent_1.target_Q, feed_dict = {agent_1.target_input_layer : batch_next_state})\n batch_maxQ1 = np.max(batch_Q1)\n batch_targetQ = batch_allQ\n if np.isnan(batch_targetQ).any():\n print(\"NaN Detected. Episode :%d Terminating...\" % i)\n sys.exit()\n if terminal:\n batch_targetQ[0][action_taken] = reward\n else:\n batch_targetQ[0][action_taken] = reward + y * batch_maxQ1\n agent_1.sess.run(agent_1.updateModel, feed_dict={agent_1.input_layer : batch_current_state, agent_1.next_Q : batch_targetQ})\n #print \"Loss: \", sess.run(agent_1.loss, feed_dict={agent_1.input_layer : batch_current_state, agent_1.next_Q : batch_targetQ})\n \n for eve in event.get():\n if eve.type==QUIT:\n quit()\n sys.exit()\n keys = key.get_pressed()\n if keys[K_s]:\n screen_blit()\n display.update()\n else:\n disp.fill(black)\n display.update()\n\n jList.append(j)\n if d == True:\n e1 *= 0.9\n\n print(\"Winner: \", winner)\n if i%1000 == 0:\n agent_1.saver.save(agent_1.sess, 'agent_1')\n","sub_path":"Agent vs. Random action bot.py","file_name":"Agent vs. Random action bot.py","file_ext":"py","file_size_in_byte":21398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"561347152","text":"'''\r\nCreated on Oct 22, 2018\r\n\r\n@author: QDoan\r\n'''\r\nimport logging, time, os\r\nfrom selenium import webdriver\r\nfrom mtmf.pages.instructor_home_page import InstructorHomePage\r\nfrom mtmf.pages import login_page\r\nfrom myutils import utils_files_io, utils_directory\r\n\r\ndef prepare_courses_for_checking():\r\n driver = webdriver.Chrome('C:/Workspace/Tools/drivers/chromedriver.exe')\r\n driver.set_window_size(1650, 1000)\r\n \r\n ''' Login into Mindtap Math Foundation '''\r\n msg = 'Logging into MTMF...'\r\n print(msg)\r\n logging.info(' ' + msg)\r\n login_page.login_mindtap_prod(driver)\r\n \r\n home_page = InstructorHomePage(driver)\r\n courses_list = utils_files_io.read_list_from_file('data/courses_list.txt')\r\n for course_key in courses_list:\r\n \r\n ''' Register if course does not exist '''\r\n if home_page.course_found(course_key):\r\n course_name = home_page.retrieve_course_name_with_course_key(course_key)\r\n msg = 'Course {} ({}) found. Skip registering.'.format(course_key, course_name)\r\n logging.info(' ' + msg); print(msg)\r\n else:\r\n msg = 'Registering with course key {}...'.format(course_key)\r\n logging.info(' ' + msg); print(msg)\r\n home_page.register_with_course_key(course_key); time.sleep(1)\r\n \r\n ''' Extract course name '''\r\n course_name = home_page.retrieve_course_name_with_course_key(course_key)\r\n \r\n ''' Check to see if course name can be used for filename '''\r\n try:\r\n filename = 'C:/Workspace/Sandbox/{} ({}).json'.format(course_name, course_key)\r\n utils_files_io.write_list_to_file(['test'], filename)\r\n os.remove(filename)\r\n except:\r\n print('Course name \"{}\" cannot be used for filename'.format(course_name))\r\n\r\ndef get_courses_list_to_be_checked():\r\n\r\n # Get list of courses that finished running\r\n items_list = utils_files_io.read_list_from_file('C:/Workspace/Sandbox/DSM-6513 Gradebook/courses_list_finished.txt')\r\n courses_list_done = []\r\n for item in items_list:\r\n course_key = item.split(', ')[0]\r\n if course_key not in courses_list_done:\r\n courses_list_done.append(course_key)\r\n else:\r\n print('Course {} appears previously.'.format(course_key))\r\n \r\n courses_list_full = utils_files_io.read_list_from_file('data/courses_list_full.txt')\r\n for course in courses_list_full:\r\n if course not in courses_list_done: \r\n print(course)\r\n \r\ndef pretty_printed_impacted_students():\r\n infile = 'C:/Workspace/Sandbox/DSM-6513 Gradebook/GWDM-V3XQ-MMMM-MUEB.json'\r\n jo = utils_files_io.read_json_from_file(infile)\r\n for assignment in jo.keys():\r\n print(assignment)\r\n [print(student) for student in jo[assignment]]\r\n print()\r\n \r\nif __name__ == '__main__':\r\n logfile = 'C:/Workspace/Sandbox/log.txt'\r\n if os.path.isfile(logfile): os.remove(logfile)\r\n logging.basicConfig(filename=logfile, level=logging.INFO)\r\n\r\n# prepare_courses_for_checking()\r\n \r\n# print('starting...')\r\n# get_courses_list_to_be_checked()\r\n\r\n pretty_printed_impacted_students()\r\n\r\n# items_list = utils_directory.get_subdir_name_from_directory('C:/Workspace/Sandbox/DSM-6513 Gradebook')\r\n# for item in items_list:\r\n# print(item)\r\n\r\n ","sub_path":"DevMathPython/mtmf/gradebook/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"597758891","text":"dataset = {\n \"698612\":{\n \"cen_year\":\"2005\",\n \"tree_loc\":\"Assigned\",\n \"spc_latin\":\"PLATANUS ACERIFOLIA\",\n \"horz_other\":\"No\"\n },\n \"860288\":{\n \"cen_year\":\"2006\",\n \"tree_loc\":\"Side\",\n \"spc_latin\":\"ULMUS SPECIES\",\n \"horz_other\":\"No\"\n },\n \"641807\":{\n \"cen_year\":\"2006\",\n \"tree_loc\":\"Median\",\n \"spc_latin\":\"GLEDITSIA TRIACANTHOS\",\n \"horz_other\":\"No\"\n }\n}\n","sub_path":"PotapenkoIV/dataset_structure.py","file_name":"dataset_structure.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"644380148","text":"from flask import render_template\nfrom flask import Flask,request\nimport os\nfrom app import app\nimport sqlite3\n\n@app.route('/', methods = ['GET', 'POST'])\n@app.route('/index.html')\n@app.route('/index', methods = ['GET', 'POST'])\ndef index():\n return render_template(\"index.html\")\n\n@app.route(\"/people.html\")\n@app.route(\"/people\")\ndef people():\n conn=sqlite3.connect('people.db')\n cursor = conn.cursor()\n cursor.execute('select * from people where category == \\'PhD\\'')\n values= cursor.fetchall()\n \n PhDs=[]\n for stu in values:\n path=\"./app/static/save_file/\"+stu[0]+\".jpg\"\n if os.path.isfile(path):\n img=\"../static/people_png/\"+stu[0]+\".png\"\n else:\n img=\"../static/res/img/people/unknown.jpg\"\n homepage=\"../single_people/\"+stu[0]\n PhDs.append([stu[0],homepage,img])\n\n cursor.execute('select * from people where category == \\'graduate\\'')\n values= cursor.fetchall()\n \n masters=[]\n for stu in values:\n path=\"./app/static/save_file/\"+stu[0]+\".jpg\"\n if os.path.isfile(path):\n img=\"../static/people_png/\"+stu[0]+\".png\"\n else:\n img=\"../static/res/img/people/unknown.jpg\"\n homepage=\"../single_people/\"+stu[0]\n masters.append([stu[0],homepage,img])\n\n cursor.execute('select * from people where category == \\'undergraduate\\'')\n values= cursor.fetchall()\n \n undergraduates=[]\n for stu in values:\n path=\"./app/static/save_file/\"+stu[0]+\".jpg\"\n if os.path.isfile(path):\n img=\"../static/people_png/\"+stu[0]+\".png\"\n else:\n img=\"../static/res/img/people/unknown.jpg\"\n homepage=\"../single_people/\"+stu[0]\n undergraduates.append([stu[0],homepage,img])\n\n\n phdnumber = len(PhDs)\n phdrows = list(range(phdnumber//5+1))\n \n masternumber = len(masters)\n masterrows = list(range(masternumber//5+1))\n \n undergraduatenumber = len(undergraduates)\n undergraduaterows = list(range(undergraduatenumber//5+1))\n \n\n cursor.close()\n conn.close()\n\n return render_template(\"people1.html\", PhDs=PhDs,phdnumber=phdnumber,phdrows=phdrows,\n masters=masters,masternumber=masternumber,masterrows=masterrows, \n undergraduates=undergraduates,undergraduatenumber=undergraduatenumber,undergraduaterows=undergraduaterows,)\n \n@app.route(\"/research.html\")\n@app.route(\"/research\")\ndef research():\n return render_template(\"research.html\")\n\n@app.route(\"/projects.html\")\n@app.route(\"/projects\")\ndef projects():\n return render_template(\"projects.html\")\n\n@app.route(\"/news.html\")\n@app.route(\"/news\")\ndef news():\n return render_template(\"news.html\")\n\n@app.route(\"/publications.html\")\n@app.route(\"/publications\")\ndef publications():\n conn=sqlite3.connect('LIKE1.db')\n cursor = conn.cursor()\n\n cursor.execute('select * from PUBLICATION where year == \\'2017\\'')\n values= cursor.fetchall()\n pubs2017 = values\n\n cursor.execute('select * from PUBLICATION where year == \\'2016\\'')\n values= cursor.fetchall()\n pubs2016 = values\n\n cursor.execute('select * from PUBLICATION where year == \\'2015\\'')\n values= cursor.fetchall()\n pubs2015 = values\n\n cursor.execute('select * from PUBLICATION where year == \\'2014\\'')\n values= cursor.fetchall()\n pubs2014 = values\n\n cursor.close()\n conn.close()\n return render_template(\"publications.html\",pubs2017=pubs2017,pubs2016=pubs2016,pubs2015=pubs2015,pubs2014=pubs2014) \n\n@app.route(\"/information.html\")\n@app.route(\"/information\")\ndef information():\n return render_template(\"information.html\", job=1)\n\n@app.route(\"/information/job1.html\")\ndef job1():\n return render_template(\"information.html\", job=1)\n@app.route(\"/information/job2.html\")\ndef job2():\n return render_template(\"information.html\", job=2)\n@app.route(\"/information/job3.html\")\ndef job3():\n return render_template(\"information.html\", job=3)\n\n@app.route('/hello')\ndef hello():\n return 'Hello World'\n\n\n\n@app.route('/single_people/',methods = ['GET', 'POST'])\ndef single_people(name):\n conn=sqlite3.connect('people.db')\n cur=conn.cursor()\n cur.execute('select * from people where name=\\''+name+'\\'')\n values=cur.fetchall()[0]\n print(values)\n category=values[1]\n homepage=values[2]\n email=values[3]\n office=values[4]\n title1=values[5]\n title2=values[6]\n title3=values[7]\n title4=values[8]\n title5=values[9]\n content1=values[10]\n content2=values[11]\n content3=values[12]\n content4=values[13]\n content5=values[14]\n title_content=[]\n if(content1!=None):\n title_content.append([title1,content1])\n if(content2!=None):\n title_content.append([title2,content2])\n if(content3!=None):\n title_content.append([title3,content3])\n if(content4!=None):\n title_content.append([title4,content4])\n if(content5!=None):\n title_content.append([title5,content5])\n name1=name\n print(type(name1))\n name2=name1.split('_',1)[0]+\" \"+name1.split('_',1)[1]\n name1.replace('_',' ')\n print(name1)\n\n path=\"./app/static/save_file/\"+name+\".jpg\"\n if os.path.isfile(path):\n img=\"../static/save_file/\"+name+\".jpg\"\n else:\n img=\"../static/res/img/people/unknown.jpg\"\n\n #return name\n return render_template(\"single_people.html\",\n name=name2,\n category=category,\n homepage=homepage,\n email=email,\n office=office,\n title_content=title_content,\n img=img)","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"120651708","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/11/5 13:55\n# @Software: PyCharm Community Edition\n# @Author : Ada\n# @File : http_request.py\nimport requests\nfrom API.API_7.common.config import config\n\nclass HTTPRequest:\n \"\"\"\n 公共使用一个session,cookies自动传递\n 使用这类的request方法去完成不同的http请求,并且返回响应结果\n \"\"\"\n def request(self,method,url,data=None,json=None,cookies=None):\n method=method.upper()#将method强制转成大写\n\n if type(data)==str:\n data=eval(data) #str转成字典\n\n if method =='GET':\n resp=requests.get(url,params=data,cookies=cookies)# resp是response对象\n elif method == 'POST':\n if json is not None:\n resp=requests.post(url, json=json,cookies=cookies)\n else:\n resp=requests.post(url, data=data,cookies=cookies)\n else:\n resp=None\n print('UN-support-method')\n return resp\n\nclass HTTPRequest2:\n \"\"\"\n 使用这类的request方法去完成不同的http请求,并且返回响应结果\n \"\"\"\n def __init__(self):\n #打开一个session\n self.session =requests.sessions.session()\n\n def request(self,method,url,data=None,json=None):\n method=method.upper()#将method强制转换成全大写\n\n if type(data)==str:\n data=eval(data) #str转成字典\n #拼接url\n url = config.get('api','pre_url') + url\n print('请求url:',url)\n print('请求data:',data)\n\n\n if method==\"GET\":\n resp=self.session.request(method=method,url=url,params=data)\n elif method=='POST':\n if json is not None:\n resp = self.session.request(method=method,url=url, json=json)\n else:\n resp = self.session.request(method=method,url=url,data=data)\n else:\n resp= None\n print('UN-support-method')\n print('请求response:', resp.text)\n return resp\n def close(self):\n self.session.close()#用完记得关闭\n\n\n\nif __name__==\"__main__\":\n params={\"mobilephone\":\"15810447878\",\"pwd\":\"123456\"}\n http_request=HTTPRequest()\n #调用注册\n resp1 = http_request.request('POST','http://test.lemonban.com/futureloan/mvc/api/member/register', data=params)\n print(resp1.status_code)\n print(resp1.text)\n print(resp1.cookies)\n # 调用登录\n resp2 = http_request.request('POST','http://test.lemonban.com/futureloan/mvc/api/member/login',\n data=params)\n print(resp2.status_code)\n print(resp2.text)\n print(resp2.cookies)\n #调用充值\n params = {\"mobilephone\": \"15810447878\", \"amount\": \"1000\"}\n resp3 = http_request.request('POST','http://test.lemonban.com/futureloan/mvc/api/member/recharge',\n data=params, cookies=resp2.cookies)\n print(resp3.status_code)\n print(resp3.text)\n print(resp3.cookies)\n\n http_request2 = HTTPRequest2()\n #登录\n params = {\"mobilephone\": \"15810447878\", \"pwd\": \"123456\"}\n resp4=http_request2.request('POST','http://test.lemonban.com/futureloan/mvc/api/member/login',\n data=params)\n # 充值\n params = {\"mobilephone\": \"15810447878\", \"amount\": \"1000\"}\n resp5 =http_request2.request('POST', 'http://test.lemonban.com/futureloan/mvc/api/member/recharge',\n data=params)\n print(resp4.status_code)\n print(resp4.text)\n print(resp4.cookies)\n print(resp5.status_code)\n print(resp5.text)\n print(resp5.cookies)","sub_path":"common/http_request.py","file_name":"http_request.py","file_ext":"py","file_size_in_byte":3599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"282745667","text":"# coding: utf-8\nimport datetime\nfrom secrets import token_hex\nfrom redis_tool.redis_server import redis_client\nfrom ticket.sql import ticket_sql\nimport logging\n\nlogger = logging.getLogger('django')\n\n\nclass TicketAuthorize:\n @staticmethod\n def validate_ticket(ticket):\n cached_user_id = redis_client.get_instance(ticket)\n if cached_user_id:\n valid_ticket = True\n user_id = cached_user_id\n err_msg = None\n else:\n res_ticket = ticket_sql.get_ticket(ticket)\n if not res_ticket:\n valid_ticket = False\n user_id = None\n err_msg = 'ticket不存在'\n else:\n ticket = res_ticket\n expire_time = ticket['expired_time'][: ticket['expired_time'].find('.')]\n expire_time = expire_time.replace('T', ' ')\n if datetime.datetime.strptime(expire_time, '%Y-%m-%d %H:%M:%S') > datetime.datetime.now():\n valid_ticket = True\n user_id = ticket['user']['id']\n err_msg = None\n redis_client.set_instance(key=ticket['ticket'], value=user_id)\n else:\n valid_ticket = False\n user_id = None\n err_msg = 'ticket已过期'\n return {'valid_ticket': valid_ticket, 'user_id': user_id, 'err_msg': err_msg}\n\n @staticmethod\n def create_ticket(user_id):\n now = datetime.datetime.now()\n expired_time = datetime.datetime.now() + datetime.timedelta(days=1)\n ticket = token_hex(32)\n ticket_sql.create_ticket(user_id=user_id, ticket=ticket, create_time=str(now), expired_time=str(expired_time))\n redis_client.set_instance(ticket, user_id)\n return ticket\n\n @staticmethod\n def delete_ticket(ticket):\n redis_client.delete(ticket)\n ticket_sql.delete_ticket(ticket)\n return\n","sub_path":"ticket/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"59262009","text":"\"\"\"This adapter aggregates all inputs and writes the aggregate\nvalues to each output\n\"\"\"\nimport numpy as np\nfrom smif.model import SectorModel\n\n\ndef _aggregate_inputs_to_output(data_handle, input_names, inputs, output_name, outputs):\n # check output exists\n assert output_name in outputs, \\\n \"Expected to find output '{}' when aggregating\".format(output_name)\n\n # set up zero output\n output_spec = outputs[output_name]\n output_data = np.zeros(output_spec.shape)\n\n for input_name in input_names:\n # check input exists\n assert input_name in inputs, \\\n \"Expected to find input '{}' when aggregating to output '{}'\".format(\n input_name, output_name)\n # check specs match\n input_spec = inputs[input_name]\n assert input_spec.shape == output_spec.shape, \\\n \"Expected input {} and output {} spec shapes to match\".format(\n input_spec, output_spec)\n # add input to output data in-place\n input_data = data_handle.get_data(input_name).as_ndarray()\n output_data += input_data\n\n # write output\n data_handle.set_results(output_name, output_data)\n\n\nclass AggregateEnergyConstrained(SectorModel):\n \"\"\"Aggregate inputs to outputs for energy models in constrained heat mode\n \"\"\"\n def simulate(self, data_handle):\n to_output_from_inputs = self._get_aggregate_map()\n for output_name, input_names in to_output_from_inputs.items():\n _aggregate_inputs_to_output(\n data_handle, input_names, self.inputs, output_name, self.outputs)\n\n def _get_aggregate_map(self):\n return {\n 'building_biomass_boiler': [\n 'residential_biomass_boiler_biomass',\n 'service_biomass_boiler_biomass',\n 'industry_biomass_boiler_biomass',\n ],\n 'building_elec_boiler': [\n 'residential_electricity_boiler_electricity',\n 'service_electricity_boiler_electricity',\n ],\n 'building_heatpump': [\n 'residential_electricity_heat_pumps_electricity',\n 'service_electricity_heat_pumps_electricity',\n ],\n 'building_gas_boiler': [\n 'residential_gas_boiler_gas',\n 'service_gas_boiler_gas',\n ],\n 'building_hydrogen_boiler': [\n 'residential_hydrogen_boiler_hydrogen',\n 'service_hydrogen_boiler_hydrogen',\n ],\n 'building_hydrogen_heatpump': [\n 'residential_hydrogen_heat_pumps_hydrogen',\n 'service_hydrogen_heat_pumps_hydrogen',\n ],\n 'building_oil_boiler': [\n 'residential_oil_boiler_oil',\n 'service_oil_boiler_oil',\n 'industry_oil_boiler_oil',\n ],\n 'dh_biomass_boiler': [\n 'residential_biomass_district_heating_biomass',\n 'service_biomass_district_heating_biomass',\n 'industry_biomass_district_heating_biomass',\n ],\n 'dh_elec_boiler': [\n 'residential_electricity_district_heating_electricity',\n 'service_electricity_district_heating_electricity',\n 'industry_electricity_district_heating_electricity',\n ],\n 'dh_gas_CHP': [\n 'residential_gas_district_heating_CHP_gas',\n 'service_gas_district_heating_CHP_gas',\n 'industry_gas_district_heating_CHP_gas',\n ],\n 'dh_hydrogen_fuelcell': [\n 'residential_hydrogen_district_heating_fuel_cell',\n 'service_hydrogen_district_heating_fuel_cell',\n 'residential_hydrogen_fuel_cell_hydrogen',\n 'service_hydrogen_fuel_cell_hydrogen',\n 'industry_hydrogen_district_heating_fuel_cell',\n 'industry_hydrogen_fuel_cell_hydrogen',\n ],\n 'elecload': [\n 'industry_electricity_boiler_electricity',\n 'industry_electricity_heat_pumps_electricity',\n 'industry_electricity_non_heating',\n ],\n 'gasload': [\n 'industry_gas_non_heating',\n 'industry_gas_boiler_gas',\n ],\n 'hydrogen_non_heat_eh': [\n 'residential_hydrogen_non_heating',\n 'service_hydrogen_non_heating',\n 'industry_hydrogen_boiler_hydrogen',\n 'industry_hydrogen_heat_pumps_hydrogen',\n 'industry_hydrogen_non_heating',\n ],\n 'oil_non_heat_eh': [\n 'residential_oil_non_heating',\n 'service_oil_non_heating',\n 'industry_oil_non_heating',\n ],\n 'building_solidfuel_boiler': [\n 'residential_solid_fuel_boiler_solid_fuel',\n 'service_solid_fuel_boiler_solid_fuel',\n 'industry_solid_fuel_boiler_solid_fuel',\n ],\n 'solid_fuel_non_heat_eh': [\n 'residential_solid_fuel_non_heating',\n 'service_solid_fuel_non_heating',\n 'industry_solid_fuel_non_heating',\n ]\n }\n\n\nclass AggregateEnergyOptimised(SectorModel):\n \"\"\"Aggregate inputs to outputs for energy models in unconstrained/optimised heat mode\n \"\"\"\n def simulate(self, data_handle):\n to_output_from_inputs = self._get_aggregate_map()\n for output_name, input_names in to_output_from_inputs.items():\n _aggregate_inputs_to_output(\n data_handle, input_names, self.inputs, output_name, self.outputs)\n\n def _get_aggregate_map(self):\n return {\n 'hydrogen_non_heat_eh': [\n 'residential_hydrogen',\n 'service_hydrogen',\n 'industry_hydrogen'\n ],\n 'oil_non_heat_eh': [\n 'residential_oil',\n 'service_oil',\n 'industry_oil'\n ],\n 'solid_fuel_non_heat_eh': [\n 'residential_solid_fuel',\n 'service_solid_fuel',\n 'industry_solid_fuel'\n ],\n 'heatload_com': [\n 'service_heat',\n 'industry_heat'\n ]\n }\n","sub_path":"models/aggregate.py","file_name":"aggregate.py","file_ext":"py","file_size_in_byte":6368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"126714841","text":"import os\nfrom .mrover_arm import MRoverArm\nfrom .configuration_space_test import ConfigurationSpaceTest\n# from .kinematics_tester import KinematicsTester\nfrom rover_common.aiohelper import run_coroutines\nfrom rover_common import aiolcm\n\n\ndef main():\n config_path = os.environ['MROVER_CONFIG']\n geom_file = config_path + '/config_kinematics/mrover_arm_geom.json'\n args = {\n 'geom_file': geom_file,\n }\n lcm_ = aiolcm.AsyncLCM()\n\n arm = MRoverArm(args, lcm_)\n\n config = ConfigurationSpaceTest(arm)\n config.straight_up_torque_test()\n\n # config.write_file()\n # config.read_file()\n # tester = KinematicsTester(arm)\n # tester.kinematics_test()\n\n lcm_.subscribe(\"/arm_position\", arm.arm_position_callback)\n lcm_.subscribe(\"/target_orientation\", arm.target_orientation_callback)\n lcm_.subscribe(\"/target_angles\", arm.target_angles_callback)\n lcm_.subscribe(\"/confirmation\", arm.arm_position_callback)\n lcm_.subscribe(\"/motion_execute\", arm.motion_execute_callback)\n lcm_.subscribe(\"/simulation_mode\", arm.simulation_mode_callback)\n lcm_.subscribe(\"/ik_arm_control\", arm.cartesian_control_callback)\n lcm_.subscribe(\"/lock_joint_e\", arm.lock_e_callback)\n lcm_.subscribe(\"/ik_enabled\", arm.ik_enabled_callback)\n\n run_coroutines(lcm_.loop(), arm.execute_spline())\n","sub_path":"onboard/kinematics/src/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"304077422","text":"#!/usr/bin/env python\ndocstring='''\nreindex_complex.py mutList.txt complex.pdb reindex.txt reindex.pdb\n Reindex residue number in BindProf format mutation file \"mutList.txt\"\n and dimer PDB file \"complex.pdb\" so that the first residue start from \n one. if the structure contains any missing residue, residue number gaps\n will be removed\n'''\nimport Bio.PDB\nimport sys,os\nimport re\n\nclass NonHetSelect(Bio.PDB.Select): # class to select ATOM entries\n def accept_residue(self,residue): # remove heteroatoms\n return 1 if residue.id[0]==' ' else 0\n def accept_atom(self, atom): # remove alternative location\n return not atom.is_disordered() or atom.get_altloc() == 'A'\n\ndef reindex_complex(mutList_in,pdb_in,mutList_out,pdb_out):\n '''\n Read PDB file \"pdb_in\", reindex residue number of both chains so that\n residue number starts from 1. Make corresponding change to BindProf format\n mutation file \"mutList_in\" and make corresponding change.\n\n Output reindex mutation file and PDB file to \"mutList_out\" and \"pdb_out\"\n\n return two dict, first has old residue index as key & new residue index as\n value. second has new residue index as key & old residue index as value\n '''\n #### reindex complex pdb ####\n resi_dict=dict()\n inv_resi_dict=dict()\n struct = Bio.PDB.PDBParser(PERMISSIVE=1).get_structure(\"complex\",pdb_in)\n model=struct[0]\n for chain in model:\n resi_dict[chain.id]=dict()\n inv_resi_dict[chain.id]=dict()\n index=1\n for residue in chain:\n if residue.id[0]==' ':\n resi_dict[chain.id][str(residue.id[1])]=str(index)\n inv_resi_dict[chain.id][str(index)]=str(residue.id[1])\n residue.id=(residue.id[0],index,residue.id[-1])\n index+=1\n\n io=Bio.PDB.PDBIO()\n io.set_structure(model)\n io.save(pdb_out,NonHetSelect())\n\n #### reindex mutation file ####\n fp=open(mutList_in,'rU')\n mutation_list=[l.strip() for l in \\\n fp.read().replace(';','').splitlines() if l.strip()]\n fp.close()\n\n mutation_pattern=re.compile(\"^(\\w)(\\w)(\\d+)(\\w)\")\n mutation_txt=''\n for mutation_set in mutation_list:\n for mutation in mutation_set.split(','):\n wt_res,chain,resi,mut_res=mutation_pattern.findall(mutation)[0]\n mutation_txt+=wt_res+chain+resi_dict[chain][resi]+mut_res+','\n mutation_txt=mutation_txt[:-1]+';\\n' # remove trailing comma\n fp=open(mutList_out,'w')\n fp.write(mutation_txt)\n fp.close()\n return resi_dict,inv_resi_dict\n \nif __name__==\"__main__\":\n if len(sys.argv)<5:\n print >>sys.stderr,docstring\n exit()\n\n reindex_complex(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])\n","sub_path":"bin/module/reindex_complex_biopython.py","file_name":"reindex_complex_biopython.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"111543821","text":"# coding: utf-8\n\nfrom state.player_state.base import PlayerStateBase\nfrom state.player_state.wait import WaitState\n\n\n\nclass DealerChooseState(PlayerStateBase):\n def __init__(self):\n super(DealerChooseState, self).__init__()\n\n def next_state(self, owner):\n # owner.machine.trigger(ShowCardState())\n # owner.table.machine.cur_state.execute(owner.table, \"skip_show_card\")\n # 2018.5.9改明牌之后出牌\n owner.machine.trigger(WaitState())\n owner.table.machine.cur_state.execute(owner.table, \"skip_step\")\n\n def execute(self, owner, event, proto=None):\n super(DealerChooseState, self).execute(owner, event, proto)\n from logic.player_action import dealer_choose\n if event == \"dealer_choose\":\n dealer_choose(owner, proto)\n else:\n owner.table.logger.warn(\"player {0} event {1} not register\".format(owner.seat, event))\n","sub_path":"state/player_state/dealer_choose.py","file_name":"dealer_choose.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"361097995","text":"\"\"\"\n\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom fwmi import H1\n\n\nswitch_lam = 2\nlam = 532e-9 * switch_lam\ntheta_t = 1.5 * np.pi / 180\ngamma_m = 1.40e9 / switch_lam # molecular signal spectral width\ngamma_a = 50e6 / switch_lam # aerosol signal spectral width\nfopd = 0.15 * switch_lam\nt_ref = 20\nt = 20\np = 1\nf = 0.1\n\nh1 = H1(fopd, theta_t, gamma_m, gamma_a, lam, t, t_ref, p, lam / 10)\n\nn_T = 1000\ntheta_d = 0.12 * np.pi / 180\nd_T = np.linspace(-1, 1, n_T)\nprint(h1.d1, h1.d2, h1.d3)\n\nt_m = np.zeros(n_T)\nt_a = np.zeros(n_T)\nsdr = np.zeros(n_T)\nfsrs = np.zeros(n_T)\nopds = np.zeros(n_T)\ntheta_t_0 = theta_t\nfor i in range(n_T):\n n1 = h1.generate_n1(h1.t + d_T[i])\n d1 = h1.d1_thermal_expansion(h1.t + d_T[i])\n n2 = h1.generate_n2(h1.t + d_T[i])\n d2 = h1.d2_thermal_expansion(h1.t + d_T[i])\n n3 = h1.generate_n3(h1.t + d_T[i])\n opd = h1.opd_exact(theta_t, n1, d1, n2, d2, n3, h1.d3)\n opds[i] = opd\n fsrs[i] = h1.fsr(opd)\n t_m[i] = h1.overall_transmittance(theta_d, f, h1.gamma_m, h1.fsr(opd))\n t_a[i] = h1.overall_transmittance(theta_d, f, h1.gamma_a, h1.fsr(opd))\n sdr[i] = t_m[i] / t_a[i]\n\n\nfig, ax = plt.subplots()\n# ax.plot(d_T, t_a, color='black')\nax.plot(d_T, sdr, color='black')\n# ax.plot(d_T, (opds - fopd) / lam, color='black')\n# ax.plot(d_d1 * 1000, fsrs, color='black')\n# ax.set_ylim([0, 400])\nax.grid(True)\nax.set_xlabel(r\"Temperature Variation ($^\\circ$C)\")\nax.set_ylabel(r\"SDR\")\nax.set_title(\"SDR v. Temperature Variation\")\nax.text(2.1, 110, r\"$\\theta_t$($\\Delta\\theta_t$=0) = {0}$^\\circ$\".format(round(theta_t_0 * 180 / np.pi, 1)))\nplt.show()\n","sub_path":"sdr_v_temp.py","file_name":"sdr_v_temp.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"298462536","text":"import tensorflow as tf\n\n\nclass ResBlock(tf.keras.layers):\n def __init__(self, output_filter):\n super(ResBlock, self).__init__()\n self.conv1 = tf.keras.layers.Conv2D(filters=output_filter,\n kernel_size=(3, 3),\n padding=\"same\")\n self.bn1 = tf.keras.layers.BatchNormalization()\n self.conv2 = tf.keras.layers.Conv2D(filters=output_filter,\n kernel_size=(3, 3),\n strides=1,\n padding=\"same\")\n self.bn2 = tf.keras.layers.BatchNormalization()\n\n def call(self, x, input_filter, output_filter):\n res = self.conv1(x)\n res = self.bn1(res)\n res = tf.nn.relu(res)\n res = self.conv12(res)\n res = self.bn2(res)\n\n if input_filter == output_filter:\n identity = x\n else:\n identity = tf.keras.layers.Conv2D(filters=output_filter, kernel_size=(1, 1),\n padding=\"same\")\n output = tf.keras.layers.add([res, identity])\n output = tf.nn.relu(output)\n return output\n\n\nclass DenseLayer(tf.keras.layers):\n def __init__(self, growth_rate, drop_rate):\n super().__init__()\n self.bn1 = tf.keras.layers.BatchNormalization()\n self.conv1 = tf.keras.layers.Conv2D(filters=4 * growth_rate,\n kernel_size=(1, 1),\n strides=1,\n padding='same')\n self.bn2 = tf.keras.layers.BatchNormalization()\n self.conv2 = tf.keras.layers.Conv2D(filters=growth_rate,\n kernel_size=(3, 3),\n strides=1,\n padding='same')\n self.dropout = tf.keras.layers.Dropout(rate=drop_rate)\n self.listLayers = [self.bn1,\n tf.keras.layers.Activation(\"relu\"),\n self.conv1,\n self.bn2,\n tf.keras.layers.Activation(\"relu\"),\n self.conv2,\n self.dropout]\n\n def call(self, x):\n y = x\n for layer in self.listLayers:\n y = layer(y)\n y = tf.keras.layers.concatenate([x, y], axis=-1)\n return y\n\n\nclass DenseBlock(tf.keras.layers):\n def __init__(self, num_layers, growth_rate, drop_rate=0.5):\n super().__init__()\n self.num_layers = num_layers\n self.growth_rate = growth_rate\n self.drop_rate = drop_rate\n self.listLayers = []\n for _ in range(self.num_layers):\n self.listLayers.append(DenseLayer(growth_rate=self.growth_rate, drop_rate=self.drop_rate))\n\n def call(self, x):\n for layer in self.listLayers:\n x = layer(x)\n return x\n","sub_path":"Block/MyBlocks.py","file_name":"MyBlocks.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"234746785","text":"#!/usr/bin/env python\n\n# Redactor. Written by Daniel Levin\n# Uses id3reader, written by Ned Batchelder (http://nedbatchelder.com)\n\nimport sys\nimport id3reader\nfrom types import *\nimport os\n\ndef print_usage():\n print(\"Usage: redactor [format] [files]\\nRenames according to the format specified. Use the letters p, a, t, T, g. They denote performer (artist), album, title, track and genre respectively.\\n\\nExample:\\nredactor pta *.mp3\\nredactor aTg *.mp3\")\n exit()\n\ndef translate_command(cmd):\n if (cmd == 'p'):\n return 'performer'\n if (cmd == 'a'):\n return 'album'\n if (cmd == 't'):\n return 'title'\n if (cmd == 'T'):\n return 'track'\n if (cmd == 'g'):\n return 'genre'\n if (cmd == 'y'):\n return 'year'\n\ndef main():\n argc = len(sys.argv)\n if (argc < 3):\n print_usage()\n if (sys.argv[1] == \"-h\" or sys.argv[1] == \"--help\"):\n print_usage()\n else:\n output_format = sys.argv[1]\n for i in range(2, argc):\n id3r = id3reader.Reader(sys.argv[i])\n final_value = \"\"\n first_loop_complete = False\n for att in output_format:\n tag_elem = id3r.getValue(translate_command(att))\n if (isinstance(tag_elem, NoneType)):\n print(\"Error on \" + sys.argv[i])\n break\n else:\n if (not first_loop_complete):\n final_value += tag_elem\n first_loop_complete = True\n else:\n final_value += \" - \" + tag_elem\n print(final_value)\n os.rename(sys.argv[i], final_value + \".mp3\")\n\n\nif (__name__== \"__main__\"):\n main()\n","sub_path":"redactor.py","file_name":"redactor.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"11168425","text":"from random import uniform\nfrom random import sample\n\nSCL = 1000\n\ndef clampSCL(x): return max(0, min(SCL, x))\n\ncenters = [(uniform(0,SCL), uniform(0,SCL)) for i in range(100)]\n\npoints = []\nfor c in centers:\n points.extend([(uniform(clampSCL(c[0]-SCL/50), clampSCL(c[0]+SCL/50)), uniform(clampSCL(c[1]-SCL/50), clampSCL(c[1]+SCL/50))) for i in range(100)])\n\npoints.extend([(uniform(0,SCL), uniform(0,SCL)) for i in range(SCL)])\n\ndef eudist(x,y):\n return sum(map(lambda a,b: float(a-b)**2, x,y))**0.5\n\nedges = []\nfor p in xrange(len(points)):\n x = sample(xrange(len(points)), 1000)\n x = map(lambda x: (eudist(points[p],points[x]), x), x)\n x.sort()\n for (d,q) in x[:3]:\n if q != p: edges.append((p,q))\n for (d,q) in x[3:50]:\n if (uniform(d/SCL/2,1) - d/SCL/2) > 0.9:\n if q != p: edges.append((p,q))\n\nopen('temp','w').write(compress(dumps((points, edges))))\n\nfrom zlib import compress,decompress\nfrom pickle import dumps,loads\n\n(points,edges) = loads(decompress(open('temp','r').read()))\n\nimport Tkinter\nmaster = Tkinter.Tk()\nw = Tkinter.Canvas(master, width=SCL, height=SCL)\nw.pack()\nfor e in edges:\n w.create_line(points[e[0]][0], points[e[0]][1], points[e[1]][0], points[e[1]][1])\n\n\nem = {}\nfor e in edges:\n em.setdefault(e[0], set()).add(e[1])\n\ndef reaches(l):\n s = set()\n f = set(l)\n while True:\n s.update(f)\n nf = set()\n for i in f:\n nf.update(em[i])\n f = nf\n f.difference_update(s)\n if(len(f) == 0):\n break\n\nimport heapq\ndef mindist(i,js):\n return min((eudist(points[i], points[j]) for j in js))\n\ndef dijkstra(sources,targets, heur = lambda x,y: 0):\n vm = dict(((i,None) for i in sources))\n vd = dict(((i,0) for i in sources))\n pq = []\n for i in sources:\n for j in em[i]:\n heapq.heappush(pq, (eudist(points[i], points[j])+heur(j,targets), i, j))\n while True:\n if len(pq) == 0: return []\n (d, i, j) = heapq.heappop(pq)\n if j in vm: continue\n if j in targets:\n l = [j,i]\n while l[-1] != None:\n l.append(vm[l[-1]])\n l.pop()\n l.reverse()\n return l, len(vm)\n vm[j] = i\n vd[j] = vd[i] + eudist(points[i],points[j])\n for k in em[j]:\n heapq.heappush(pq, (vd[j]+eudist(points[j], points[k])+heur(k,targets), j, k)) \n","sub_path":"s13/last_semester/mkgraph.py","file_name":"mkgraph.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"117175963","text":"def display():\n\n sfile= open(\"story.txt\",'r')\n\n a = sfile.readlines()\n print(a)\n print('no of lines is',len(a))\n length=0\n for i in range(len(a)):\n a[i]=a[i][::-1]\n print(a[i])\n '''\n for i in range(len(a)):\n b=(a[i]).split(' ')\n for j in range(len(b)):\n length=length+len(b[j])\n print('no of characters in file is ',length-len(a))\n '''\n sfile.close()\ndisplay()\n","sub_path":"datafilehandling/txt file/#9.py","file_name":"#9.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"36957418","text":"from Config import *\n\nclass DataParser(object):\n\n\tdef transformTimeEvent(self, time_event):\n\t\tminutes = time_event / 60\n\t\tresult_minutes = int(minutes) % 60\n\t\thours = int(minutes) / 60\n\t\tresult_hours = int(hours) % 24\n\t\tresult_days = int(hours) / 24\n\t\tresult = \"days=\"+str(result_days)+\", hours=\"+str(result_hours)+\", minutes=\"+str(result_minutes)\n\t\treturn result\n\n\tdef calculatePriority(self, priority):\n\t\tresult = priority\n\t\tif(result < 0):\n\t\t\tresult = 0\n\t\treturn int(result)\n\n\tdef parseField(self, field):\n\t\ttry:\n\t\t\tif(field < 1 or field == None ):\n\t\t\t\tresult = None\n\t\t\telif(isinstance(field, int) or isinstance(field, float)):\n\t\t\t\tresult = field\n\t\t\telse:\n\t\t\t\tresultStr = field.replace(\" \",\"\")\n\t\t\t\tif(resultStr == \"\"):\n\t\t\t\t\treturn None\n\t\t\t\tresult = int(resultStr)\n\t\t\treturn result\n\t\texcept ValueError:\n\t\t\treturn None\n","sub_path":"translator/DataParser.py","file_name":"DataParser.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"382845789","text":"from pygame import *\nimport random, time as pytime\n\nboard = [\n\t\t[1,1,1,1,1,1,1,1],\n\t\t[0,0,0,0,0,0,0,0],\n\t\t[0,0,0,0,0,0,0,0],\n\t\t[0,0,0,0,0,0,0,0],\n\t\t[0,0,0,0,0,0,0,0],\n\t\t[0,0,0,0,0,0,0,0],\n\t\t[0,0,0,0,0,0,0,0],\n\t\t[2,2,2,2,2,2,2,2]\n\t\t]\n\nPLAYERTURN,CPUTURN=1,0\nSIGN,PIECE,valid_move,numpiece=[-1,1],[[1,3],[2,4]],[],[8,8]\nnormalmove =[(-1,-1),(1,-1)]\nrunning,over,picking,turn,skip = True,False,False,PLAYERTURN,False\nc1,c2,c3=(153,255,102),(0,102,0),(102,204,51)\n\ninit()\ndisplay.init()\ndisplay.set_caption(\"PyCheckers\")\ndisplay.set_icon(image.load(\"logo.png\"))\nscreen = display.set_mode((288,256), HWSURFACE|DOUBLEBUF)\nclock=time.Clock()\nboardimg=surface.Surface((256,256))\n\n#create board surface\nboardimg.fill(c1)\nfor y in range(0,8):\n\tfor x in range(0,4):\n\t\tif y % 2 == 0:\n\t\t\tdraw.rect(boardimg, c2, Rect(32*(x*2+1), 32*y, 32, 32))\n\t\telse:\n\t\t\tdraw.rect(boardimg, c2, Rect(32*(x*2), 32*y, 32, 32))\n\n#create pieces\npieces = [surface.Surface((32,32)),surface.Surface((32,32)),surface.Surface((32,32)),surface.Surface((32,32))]\nfor p in pieces:\n\tp.fill((255,0,255))\n\tp.set_colorkey((255,0,255))\ndraw.circle(pieces[0], (255,255,255), (16,16), 15)\ndraw.circle(pieces[1], (255,121,75), (16,16), 15)\ndraw.circle(pieces[2], (255,255,255), (16,16), 15)\ndraw.circle(pieces[3], (255,121,75), (16,16), 15)\ndraw.circle(pieces[2], (255,204,0), (16,16), 10)\ndraw.circle(pieces[3], (255,255,121), (16,16), 10)\n\n#INFO\nfnt=font.Font(None, 48)\nwinner=[fnt.render(\"CPU Win\", 1, (255,0,0)),fnt.render(\"Player Win\", 1, (0,0,255))]\n\ndef get_opposite(turn):\n\tif turn==PLAYERTURN:\n\t\treturn CPUTURN\n\telse:\n\t\treturn PLAYERTURN\n\t\t\ndef get_valid_move(x,y,turn):\n\tresult = []\n\topposite=get_opposite(turn)\n\tmoverule=normalmove\n\n\tfor n in moverule:\n\t\tdx,dy=n[0]+x,n[1]*SIGN[turn]+y\n\t\tif (dx>=0) and (dx<=7) and (dy>=0) and (dy<=7):\n\t\t\tif board[dy][dx]==0:\n\t\t\t\tresult += [(dx,dy)]\n\t\t\telif board[dy][dx] in PIECE[opposite]:#jump\n\t\t\t\tex,ey=n[0]+dx,n[1]*SIGN[turn]+dy\n\t\t\t\tif (ex>=0) and (ex<=7) and (ey>=0) and (ey<=7) and board[ey][ex]==0:\n\t\t\t\t\tresult += [(ex,ey)]\n\treturn result\n\t\ndef no_more_move(turn):\n\tfor y in range(0,8):\n\t\tfor x in range(0,8):\n\t\t\tif board[y][x] in PIECE[turn]:\n\t\t\t\tif len(get_valid_move(x,y,turn)):\n\t\t\t\t\treturn False\n\treturn True\n\t\ndef switch_turn():\n\tglobal turn\n\tif turn==PLAYERTURN:\n\t\tturn=CPUTURN\n\telse:\n\t\tturn=PLAYERTURN\n\t\t\ndef pick(px,py,cx,cy,turn):\n\tresult = []\n\tboard[cy][cx] = board[py][px]\n\tboard[py][px] = 0\n\tif abs(cx-px)>1:#jump\n\t\tboard[(py+cy)/2][(px+cx)/2] = 0\n\t\tnumpiece[get_opposite(turn)]-=1\n\t\tif numpiece[get_opposite(turn)]==0:\n\t\t\tover=True\n\t\t\treturn []\n\t\ttmp = get_valid_move(cx,cy, turn)\n\t\tfor j in tmp:\n\t\t\tif abs(j[0]-cx)>1:\n\t\t\t\tpx,py=cx,cy\n\t\t\t\tresult = tmp\n\t\t\t\tbreak\n\tif cy in [0,7] and (board[cy][cx]<3):\n\t\tboard[cy][cx]+=2\n\treturn result\n\t\ndef get_moveable(turn):\n\tresult = []\n\tfor y in range(0,8):\n\t\tfor x in range(0,8):\n\t\t\tif board[y][x] in PIECE[turn]:\n\t\t\t\ttmp = get_valid_move(x,y,turn)\n\t\t\t\tif len(tmp)>0:\n\t\t\t\t\tresult += [(x,y)]\n\treturn result\n\nwhile running:\n\tclock.tick(20)\n\tscreen.fill((102,102,102))\n\tscreen.blit(boardimg, (0, 0))\n\tscreen.blit(pieces[turn], (256, 0))\n\tif picking:\n\t\tfor v in valid_move:\n\t\t\tdraw.rect(screen, c3, Rect(32*v[0], 32*v[1], 32, 32))\n\tfor y in range(0,8):\n\t\tfor x in range(0,8):\n\t\t\tif board[y][x]>0:\n\t\t\t\tscreen.blit(pieces[(board[y][x])-1], (32*x, 32*y))\n\tfor e in event.get():\n\t\tif e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):\n\t\t\trunning = False\n\t\t\tbreak\n\t\tif not over and turn == PLAYERTURN and e.type == MOUSEBUTTONDOWN:\n\t\t\tcx,cy=e.pos[0]/32,e.pos[1]/32\n\t\t\tif cx in range(0,8) and cy in range(0,8):\n\t\t\t\tif board[cy][cx]>0 and board[cy][cx] in PIECE[turn]:\n\t\t\t\t\tif not picking:\n\t\t\t\t\t\tpicking = True\n\t\t\t\t\tpx,py=cx,cy\n\t\t\t\t\tvalid_move = get_valid_move(px,py,turn)\n\t\t\t\t\tif no_more_move(turn):\n\t\t\t\t\t\tover = True\n\t\t\t\t\t\tswitch_turn()\n\t\t\t\telif picking and board[cy][cx]==0 and (cx,cy) in valid_move:\n\t\t\t\t\tpicking = False\n\t\t\t\t\tboard[cy][cx] = board[py][px]\n\t\t\t\t\tboard[py][px] = 0\n\t\t\t\t\t\n\t\t\t\t\tif abs(cx-px)>1:#jump\n\t\t\t\t\t\tboard[(py+cy)/2][(px+cx)/2] = 0\n\t\t\t\t\t\tnumpiece[get_opposite(turn)]-=1\n\t\t\t\t\t\tif numpiece[get_opposite(turn)]==0:\n\t\t\t\t\t\t\tover=True\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\ttmp = get_valid_move(cx,cy, turn)\n\t\t\t\t\t\tfor j in tmp:\n\t\t\t\t\t\t\tif abs(j[0]-cx)>1:\n\t\t\t\t\t\t\t\tpx,py=cx,cy\n\t\t\t\t\t\t\t\tvalid_move = tmp\n\t\t\t\t\t\t\t\tpicking=True\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\tif cy in [0,7] and (board[cy][cx]<3):\n\t\t\t\t\t\tboard[cy][cx]+=2\n\t\t\t\t\tif not picking:\n\t\t\t\t\t\tswitch_turn()\n\tif turn==CPUTURN and not over:\n\t\tif not skip:\n\t\t\tskip = True\n\t\telse:\n\t\t\tif not picking:\n\t\t\t\tvalid_move = []\n\t\t\t\tmoveable_pieces=get_moveable(turn)\n\t\t\t\tif len(moveable_pieces)==0:\n\t\t\t\t\tswitch_turn()\n\t\t\t\t\tover=True\n\t\t\t\telse:\n\t\t\t\t\tl,i=0,0\n\t\t\t\t\tfor m in moveable_pieces:#find max move\n\t\t\t\t\t\tvv = get_valid_move(m[0],m[1],turn)\n\t\t\t\t\t\tfor v in vv:\n\t\t\t\t\t\t\ttmpl=abs(v[0]-m[0])\n\t\t\t\t\t\t\tif tmpl>=l:\n\t\t\t\t\t\t\t\tl=tmpl\n\t\t\t\t\tif l>1:\n\t\t\t\t\t\ttmp = []\n\t\t\t\t\t\tfor m in moveable_pieces:#max move is priority\n\t\t\t\t\t\t\tvv = get_valid_move(m[0],m[1],turn)\n\t\t\t\t\t\t\tfor v in vv:\n\t\t\t\t\t\t\t\ttmpl=abs(v[0]-m[0])\n\t\t\t\t\t\t\t\tif tmpl==l:\n\t\t\t\t\t\t\t\t\ttmp += [m]\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tmoveable_pieces = tmp\n\t\t\t\t\tm = moveable_pieces[random.randint(0,len(moveable_pieces)-1)]\n\t\t\t\t\tpx,py=m[0],m[1]\n\t\t\t\t\tvalid_move = get_valid_move(px,py,turn)\n\t\t\t\t\tpicking = True\n\t\t\t\tskip = False\n\t\t\telse:\n\t\t\t\tpytime.sleep(0.2)\n\t\t\t\tl,li,i=0,0,0\n\t\t\t\tfor v in valid_move:\n\t\t\t\t\ttmpl=abs(v[0]-px)\n\t\t\t\t\tif tmpl>=l:\n\t\t\t\t\t\tl=tmpl\n\t\t\t\t\t\tli=i\n\t\t\t\t\ti+=1\n\t\t\t\tfor v in valid_move:\n\t\t\t\t\tif abs(v[0]-px)